fix: hand off complete changes and retain verified source context

This commit is contained in:
Agent Workbench Dev
2026-11-03 07:58:13 +08:00
parent 876df5f421
commit c1521e6cd2
35 changed files with 669 additions and 79 deletions
+20 -14
View File
@@ -181,6 +181,7 @@ export class RequestPlanner {
let omitted = [], reference = null, workingReference = null, latestReference = null;
const latestDocument = latestToolDocument(this.store, session, run, groups);
const entries = [];
let retainedSources = [];
const metricsFor = (indices, includeNotice = true, currentEntries = entries, includeLatest = true) => {
const missing = groups.filter(group => !indices.has(group.index));
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, evidence)] : []),
@@ -194,22 +195,25 @@ export class RequestPlanner {
const mandatory = metricsFor(selected);
if (mandatory.estimatedInputTokens > budget.inputBudget) throw pause(budget, mandatory, breakdown);
const observed = workingCandidates(this.store, session, run, groups);
// Reserve other small source files before admitting a new result group.
// Historical locator pages are optional; they cannot evict actual code.
// Admit complete small source observations before optional raw history.
// A reservation alone does not keep code in the actual sent request.
const newest = groups.at(-1);
const newestFiles = new Set((newest?.messages[0].tool_calls ?? []).filter(call => call.function.name === 'read_file').map(call => {
try { return JSON.parse(call.function.arguments).path; } catch { return null; }
}));
const pinned = observed.filter(candidate => candidate.observation.kind === 'file' && candidate.observation.content.length <= 2000
&& !newestFiles.has(candidate.observation.path)).slice(0, 12).map(candidate => workingEntry(candidate, candidate.observation.content.length));
const retention = Math.min(2048, Math.max(0, metricsFor(selected, true, pinned).estimatedInputTokens - mandatory.estimatedInputTokens));
const retentionTarget = budget.inputBudget;
for (const candidate of observed.filter(candidate => candidate.observation.kind === 'file' && candidate.observation.content.length <= 2000)) {
if (entries.length >= 12) break;
const entry = workingEntry(candidate, candidate.observation.content.length);
if (metricsFor(selected, true, [...entries, entry]).estimatedInputTokens <= retentionTarget) entries.push(entry);
}
retainedSources = [...entries];
const newestUseful = newest?.messages.every(message => {
if (message.role !== 'tool') return true;
try { const result = JSON.parse(message.content); return !result.kind?.startsWith('context-') && result.kind !== 'tool-result'; } catch { return true; }
});
if (newestUseful && !selected.has(newest.index) && newest.contributionTokens <= budget.inputBudget) {
selected.add(newest.index);
if (metricsFor(selected).estimatedInputTokens + retention > budget.inputBudget) selected.delete(newest.index);
const remaining = entries.filter(entry => entry.source.group_index !== newest.index);
if (metricsFor(selected, true, remaining).estimatedInputTokens > budget.inputBudget) selected.delete(newest.index);
else entries.splice(0, entries.length, ...remaining);
}
const target = Math.max(budget.targetInputTokens, metricsFor(selected).estimatedInputTokens);
const priority = [...new Set(evidence.map(value => value.group_index))].map(index => groups[index]);
@@ -220,7 +224,8 @@ export class RequestPlanner {
};
// A small result in a mixed large group must remain usable. It is a
// separate, provenance-checked observation, never a broken tool pair.
const candidates = observed.filter(candidate => !selected.has(candidate.source.group_index));
const candidates = observed.filter(candidate => !selected.has(candidate.source.group_index)
&& !entries.some(entry => entry.source.call_id === candidate.source.call_id));
for (const [index, candidate] of candidates.entries()) {
if (entries.length >= 12) break;
const remaining = target - metricsFor(selected).estimatedInputTokens;
@@ -325,9 +330,9 @@ export class RequestPlanner {
// The next result replaces the current latest-result feedback. Do not
// reserve both views when sizing that result's actual protocol page.
nextReadFixedInputTokens: metricsFor(new Set(lastUser ? [lastUser.index] : []), true, [], false).estimatedInputTokens,
workingRetentionTokens: Math.min(2048, Math.max(0, metricsFor(new Set(lastUser ? [lastUser.index] : []), true,
entries.filter(entry => entry.observation.kind === 'file' && !entry.truncated && entry.total_content_characters <= 2000)).estimatedInputTokens
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens)),
workingRetentionTokens: Math.max(0, metricsFor(new Set(lastUser ? [lastUser.index] : []), true, retainedSources).estimatedInputTokens
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens),
workingRetentionPolicyVersion: 1,
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0) - (memoryReference ? 1 : 0) - (skillReference ? 1 : 0) - (mcpReference ? 1 : 0),
archivedGroups: omitted.length, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => group.index),
historyIndexArtifactId: reference?.id ?? null, historyIndexSha256: reference?.sha256 ?? null, actualUsage: null,
@@ -400,7 +405,8 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|| (frozen.workingSetSha256 ?? null) !== (plan.workingSetSha256 ?? null)
|| (frozen.workingSetEntries ?? 0) !== (plan.workingSetEntries ?? 0)) throw new Error('工作依据与发送前的封存记录不匹配。');
if ((frozen.workingSetViewVersion ?? 1) !== (plan.workingSetViewVersion ?? 1)
|| (frozen.workingRetentionTokens ?? 0) !== (plan.workingRetentionTokens ?? 0)) throw new Error('工作依据视图或保留预算与封存记录不匹配。');
|| (frozen.workingRetentionTokens ?? 0) !== (plan.workingRetentionTokens ?? 0)
|| (frozen.workingRetentionPolicyVersion ?? 0) !== (plan.workingRetentionPolicyVersion ?? 0)) throw new Error('工作依据视图或保留预算与封存记录不匹配。');
if ((frozen.nextReadFixedInputTokens ?? null) !== (plan.nextReadFixedInputTokens ?? null)) throw new Error('下一工具页的固定预算与封存记录不匹配。');
if ((frozen.latestToolsArtifactId ?? null) !== (plan.latestToolsArtifactId ?? null)
|| (frozen.latestToolsSha256 ?? null) !== (plan.latestToolsSha256 ?? null)
+2 -1
View File
@@ -81,7 +81,8 @@ export function workingCandidates(store, session, run, groups) {
}
// Keep complete small modules/requirements before larger evidence excerpts.
// Every selected page still identifies the exact invocation that read it.
primary.sort((a, b) => Number(a.observation.content.length > 2000) - Number(b.observation.content.length > 2000));
primary.sort((a, b) => Number(a.observation.content.length > 2000) - Number(b.observation.content.length > 2000)
|| a.observation.content.length - b.observation.content.length || a.observation.path.localeCompare(b.observation.path));
const checks = candidates.filter(candidate => ['check-results', 'command-result'].includes(candidate.observation.kind));
const artifacts = candidates.filter(candidate => candidate.observation.kind === 'artifact-page');
return [...primary, ...checks, ...artifacts, ...secondary].slice(0, 24);
+3 -1
View File
@@ -226,7 +226,9 @@ class EngineRunDriver {
const rejected=this.store.artifactStore.write(this.session,this.run.record,
JSON.parse(this.provider.redact(JSON.stringify({schemaVersion:1,owner,view,body,budget:contextBudget,dispatched:false}))),{kind:'engine-model-rejection'});
this.store.core.artifact.set(rejected.id,rejected);(this.job.inputRejections??=[]).push({artifactId:rejected.id,sha256:rejected.sha256,...contextBudget});this.save('input_rejected');
const error=new BudgetExceeded('engine_input_budget','原引擎必需目标、最新结果或剩余尝试超出封存预算,未发送模型请求。原输入和容量分项已保存;请核对上下文/预算后显式继续。');
const error=new BudgetExceeded('engine_input_budget',contextBudget.limitingReason==='context_limit'
?'原引擎必需输入超过上下文窗口可用容量,未发送模型请求。原输入和容量分项已保存;请核对模型容量后显式继续。'
:'原引擎输入可容纳于上下文窗口,但下一次请求的用量预留超过剩余预算,未发送模型请求。原输入和容量分项已保存;请核对运行和任务预算后显式继续。');
error.contextBudget={...contextBudget,rejectionArtifactId:rejected.id,rejectionSha256:rejected.sha256};throw error;
}
const selected = config.modelRouting ? { ...config, modelRouting: { ...config.modelRouting, maxAttempts: attempts } } : config;
+17
View File
@@ -130,6 +130,23 @@ export class ChangeSetManager {
for (let index = 0; index < set.files.length; index++) set.files[index].state = observations[index].state;
return observations;
}
async reviewReady(session, id, run) {
const set = this.own(session, id, null, { current: true });
if (session.runId !== run.id || session.taskId !== run.taskId || set.status !== 'prepared' || set.attemptedAt) return false;
const pending = session.changes.filter(change => change.taskId === run.taskId && ['pending', 'conflict'].includes(change.status));
if (pending.length !== set.files.length || pending.some(change => change.status !== 'pending'
|| !set.files.some(file => file.changeId === change.id))) return false;
if ([...this.store.core.tool.values()].some(tool => tool.sessionId === session.id && tool.taskId === run.taskId && tool.requiresVerification)) return false;
assertMcpResolved(this.store, session.projectId);
assertWorkersResolved(this.store, session.projectId);
this.snapshots(session, set, { pending: true });
const project = this.store.project(session.projectId);
await verifyWorkspaceProject(this.store, project);
const inspection = await inspectProject(project);
return session.runId === run.id && session.taskId === run.taskId && set.status === 'prepared'
&& JSON.stringify(gitBaseline(inspection)) === JSON.stringify(set.baseline)
&& this.inspect(session, set).every(value => value.state === 'before');
}
async prepare(session, changeIds, { source = 'user', collaborationBinding = null } = {}) {
if (!Array.isArray(changeIds) || !changeIds.length || changeIds.length > 32 || new Set(changeIds).size !== changeIds.length) throw conflict('变更集需要1到32个不同的提案ID。');
this.requireIdle(session, { source });