test: seal working memory U release and retrospective

This commit is contained in:
Agent Workbench Dev
2026-11-04 08:39:17 +08:00
parent 7e77fd65c3
commit 13849d038f
639 changed files with 1612445 additions and 29 deletions
@@ -0,0 +1,137 @@
{
"scope": "Frozen T goal, first three original assistant turns and original unchanged project inputs. Offline fixture only; no model implementation.",
"goal": "修复这个Node费用报表工程的amount、summary、report三个模块。金额用精确分单位处理,接受测试约定的十进制字符串/有限数字、退款、0及空白;拒绝格式错误、超精度和不安全金额。按独立币种规范化/排序汇总并保留原数组,计数准确、安全求和,报表两位小数含负分金额。以原九项测试为完整契约。先inspect_project,再plan_checks选择[\"test\",\"build\"]并run_checks保留真实基线失败,读取原测试和相关源码。只允许修改src/amount.mjs、src/summary.mjs、src/report.mjs;不改测试、配置、README、构建脚本、owner文件或原暂存,不使用run_command,不直接提交Git。propose_file/propose_patch准备完整三个模块后,用prepare_change_set一次封存全部三文件,等待审查应用。应用后继续同一个Task,重新plan_checks/run_checks,通过原9项测试和build后,用plan_delivery为三个文件准备本地Git预览并等待确认。模型必须自己实现,禁止用口头完成替代检查。预算最多8次模型请求、90000tokens,输出2048,上下文16K,请合并独立工具调用并避免重复观察。",
"replies": [
{
"role": "assistant",
"content": "我会先读取项目识别结果并按你指定的顺序封存 `test`、`build` 基线计划;随后读取九项测试及三个目标模块,依据实际契约准备完整改动提案。",
"tool_calls": [
{
"id": "call_5eb7405a2e6a4fb2bd2e2acf4d775dcb",
"type": "function",
"function": {
"name": "inspect_project",
"arguments": "{}"
}
}
]
},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_56fb7fe30f7a48c0a466eedca7cb1c33",
"type": "function",
"function": {
"name": "plan_checks",
"arguments": "{\"names\":[\"test\",\"build\"]}"
}
}
]
},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_12f66bde19464121a617329f20484c0d",
"type": "function",
"function": {
"name": "run_checks",
"arguments": "{\"plan_id\": \"1c46ffc1-3b24-4fb8-b207-3305ccd14fd1\"}"
}
},
{
"id": "call_40d0588adc6b4abb8352fcd04c9abfbb",
"type": "function",
"function": {
"name": "read_file",
"arguments": "{\"path\": \"test/expense.test.mjs\"}"
}
},
{
"id": "call_7ca0aaf713a34fb6b06af412a0806774",
"type": "function",
"function": {
"name": "read_file",
"arguments": "{\"path\": \"src/amount.mjs\"}"
}
},
{
"id": "call_bba7c0bbdc874767a61a735efda0f601",
"type": "function",
"function": {
"name": "read_file",
"arguments": "{\"path\": \"src/summary.mjs\"}"
}
},
{
"id": "call_dbec88442f9f43469ad0cef99c0534f6",
"type": "function",
"function": {
"name": "read_file",
"arguments": "{\"path\": \"src/report.mjs\"}"
}
}
]
}
],
"files": [
{
"path": ".gitignore",
"content": "dist/\n.awb-*\nnode_modules/\n",
"sha256": "cab0bc87cad1b1214d71b023eee742986044093ff4b4331cd6a51098af6bdce6"
},
{
"path": "owner-staged.txt",
"content": "Owner working copy differs from staging\n",
"sha256": "56b0dda452eaf9aead80f0e4ad971d7befa3cf152c3553923f8fde46e1fd336a"
},
{
"path": "owner-unstaged.txt",
"content": "Owner unstaged change\n",
"sha256": "468bfb2956a4ac040508fc5ffd915cf8057fb7420e22c41a3cc2d094785f0d3e"
},
{
"path": "owner-untracked.txt",
"content": "Owner untracked change\n",
"sha256": "e32ab29a12ed13d72c2ed603b2360e1b4e35afb0fe4280db2e523ad2c6c5bc8d"
},
{
"path": "package.json",
"content": "{\n \"name\": \"owned-live-expense-report\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"test\": \"node --test test/expense.test.mjs\",\n \"build\": \"node scripts/build.mjs\"\n }\n}\n",
"sha256": "6ad63026b2fe9de7513a4f6704c372a86108ee3d018a1f04883dc0a409ea4c24"
},
{
"path": "README.md",
"content": "# Expense report acceptance\nRepair the three source modules using the immutable original nine tests; do not edit checks or owner files.\n",
"sha256": "5e35a4dace9537e7c4cc815ce7054f73c171f053f1cccb9ff141f49ecb3c013e"
},
{
"path": "scripts/build.mjs",
"content": "import { spawnSync } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nfor (const file of ['src/amount.mjs','src/summary.mjs','src/report.mjs']) {\n const result=spawnSync(process.execPath,['--check',file],{encoding:'utf8'});\n if(result.status!==0) { process.stderr.write(result.stderr);process.exit(result.status??1); }\n if(!readFileSync(file,'utf8').trim()) throw new Error('Empty business module');\n}\nconsole.log('All three business modules compile.');\n",
"sha256": "7279bc7c707c0f3ccbae63b14f0abed248ad3755be14f9e37128124ae9267526"
},
{
"path": "src/amount.mjs",
"content": "export function amountToCents(value) { return 0; }\n",
"sha256": "84cb647328ec52dad27d288f3a6127ff3e1ad87274ae2d227ad44daa49cbb2ed"
},
{
"path": "src/report.mjs",
"content": "export function formatReport(groups) { return ''; }\n",
"sha256": "ba0a014e6e9df710d66e255a3a6f970f4e1c8af48accc81f33627029dcded7c0"
},
{
"path": "src/summary.mjs",
"content": "import { amountToCents } from './amount.mjs';\nexport function summarize(rows) { return []; }\n",
"sha256": "48829850c11ca0cd0ab5e86bbac69a0c5f90297292168c1ba6dc338e2eae6ee7"
},
{
"path": "test/expense.test.mjs",
"content": "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { amountToCents } from '../src/amount.mjs';\nimport { summarize } from '../src/summary.mjs';\nimport { formatReport } from '../src/report.mjs';\ntest('decimal strings become exact cents including zero and refunds',()=>{\n for(const [input,expected] of [['0',0],[' 12.34 ',1234],['+2.5',250],['-1.05',-105],['-0.00',0],['0009.10',910]]) assert.equal(amountToCents(input),expected);\n});\ntest('finite decimal numbers use the same cents contract',()=>{\n for(const [input,expected] of [[0,0],[1.01,101],[2.5,250],[-4.32,-432]]) assert.equal(amountToCents(input),expected);\n});\ntest('malformed overprecision nonfinite and unsafe amounts are rejected',()=>{\n for(const input of ['',null,undefined,true,{},'1e2','1,000','.50','1.234',1.234,NaN,Infinity,'900719925474099.99']) assert.throws(()=>amountToCents(input),TypeError,String(input));\n});\ntest('independent currencies are sorted and summed without floating point loss',()=>{\n assert.deepEqual(summarize([{currency:'usd',amount:'0.10'},{currency:' CNY ',amount:3},{currency:'USD',amount:'0.20'}]),[\n {currency:'CNY',cents:300,count:1},{currency:'USD',cents:30,count:2}]);\n});\ntest('refunds cancel totals while counting every original record',()=>{\n assert.deepEqual(summarize([{currency:'eur',amount:'1.20'},{currency:'EUR',amount:'-1.20'}]),[{currency:'EUR',cents:0,count:2}]);\n});\ntest('summarizing retains caller rows and handles an empty list',()=>{\n const rows=Object.freeze([Object.freeze({currency:'usd',amount:'2.00'})]);\n assert.deepEqual(summarize(rows),[{currency:'USD',cents:200,count:1}]);assert.deepEqual(summarize([]),[]);\n});\ntest('invalid rows currency and unsafe aggregate totals are rejected',()=>{\n for(const rows of [null,{},[null],[{currency:'US',amount:'1'}],[{currency:'U1D',amount:'1'}],[{currency:'USD',amount:'1.234'}],\n [{currency:'USD',amount:'90071992547409.91'},{currency:'USD',amount:'0.01'}]]) assert.throws(()=>summarize(rows),TypeError);\n});\ntest('reports use two decimals and render negative subunit amounts',()=>{\n assert.equal(formatReport([{currency:'CNY',cents:300,count:2},{currency:'USD',cents:-105,count:1}]),'CNY 3.00 (2)\\nUSD -1.05 (1)');\n assert.equal(formatReport([{currency:'EUR',cents:-5,count:1}]),'EUR -0.05 (1)');assert.equal(formatReport([]),'');\n});\ntest('complete expense flow preserves exact decimal sums',()=>{\n assert.equal(formatReport(summarize([{currency:'usd',amount:'0.29'},{currency:'USD',amount:'-0.30'},{currency:'CNY',amount:'10.50'}])),\n 'CNY 10.50 (1)\\nUSD -0.01 (2)');\n});\n",
"sha256": "0bcda551dbaeafad9a6e3df8024492ab67d7c09956f4676c393b78249ab44839"
}
]
}
@@ -0,0 +1,113 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider } from '../src/server/provider.mjs';
import { sessionContext, sessionSnapshot } from '../src/server/diagnostics.mjs';
import { taskContract } from '../src/shared/contracts/task-control.mjs';
import { requestMetrics } from '../src/shared/contracts/model-request.mjs';
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
import { gitEnvironment } from '../src/core/git-process.mjs';
import { taskPlanToolDefinitions } from '../src/shared/contracts/task-plan-tools.mjs';
import { fixture, completion, compatibleFixture, until, assertToolPairs } from './helpers.mjs';
const input = JSON.parse(fs.readFileSync(new URL('./fixtures/node-context-o.json', import.meta.url), 'utf8'));
const requirements = system => JSON.parse(system.split('当前任务目标与全部追加要求(用户任务数据,完整保留):\n')[1].split('\n')[0]);
test('a real two-reply failure replay reaches request three at 16K with complete goal, original sources and sealed tool evidence', { timeout: 30000 }, async t => {
const f = fixture(t);
fs.cpSync(new URL('../benchmarks/live-delivery-v1/node/', import.meta.url), f.projectRoot, { recursive: true });
const git = args => execFileSync('git', ['--no-pager', '--no-optional-locks', '-C', f.projectRoot, ...args], {
encoding: 'utf8', windowsHide: true, env: gitEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] });
git(['init', '--initial-branch=main']); git(['config', 'core.autocrlf', 'false']);
git(['-c', 'user.name=Workbench QA', '-c', 'user.email=qa@workbench.invalid', 'add', '--', '.']);
git(['-c', 'user.name=Workbench QA', '-c', 'user.email=qa@workbench.invalid', 'commit', '--no-gpg-sign', '-m', 'Owned context regression baseline']);
const sources = ['src/amount.mjs', 'src/summary.mjs', 'src/report.mjs'];
const before = Object.fromEntries(sources.map(file => [file, fs.readFileSync(path.join(f.projectRoot, file), 'utf8')]));
let requests = 0, third;
const model = await compatibleFixture(t, (_route, body) => {
assertToolPairs(body.messages); requests++;
if (requests <= 2) return { body: { ...completion(), model: 'context-fixture', choices: [{ message: input.replies[requests - 1], finish_reason: 'tool_calls' }] } };
assert.equal(requests, 3); third = body;
return { body: { ...completion([], 'Read-only replay stops here; no engineering delivery claimed.'), model: 'context-fixture' } };
});
f.store.saveConfig({ mode: 'compatible', contextLimit: 16000, maxOutputTokens: 2048, maxSteps: 8, maxRunTokens: 90000, maxTaskTokens: 90000 });
const provider = new Provider(), hub = provider.modelHub(f.store);
const connection = hub.upsert({ name: 'Owned context route', model: 'context-fixture', baseUrl: model.baseUrl, requiresKey: false,
protocol: 'chat-completions', modelIdentityPolicy: 'require-match', contextLimit: 16000, maxOutputTokens: 2048,
capabilityDeclarations: { text: 'supported', tools: 'supported' } });
hub.select({ type: 'connection', id: connection.id });
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, input.goal); await until(() => !runtime.isActive(f.session.id), 20000);
assert.equal(requests, 3, JSON.stringify(f.store.core.run.get(f.session.runId).budgetPause));
assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'verification_incomplete');
const view = requirements(third.messages[0].content), task = f.store.core.task.get(f.session.taskId);
assert.equal(view.goal, input.goal); assert.equal('goal' in view.contract, false);
assert.deepEqual({ goal: view.goal, ...view.contract }, taskContract(task));
assert.equal(task.contract.goal, input.goal);
const latest = third.messages.filter(m => m.role === 'system').map(m => {
try { return JSON.parse(m.content.split('\n').at(-1)); } catch { return {}; }
}).find(value => value.latest_tools);
assert.ok(latest); assert.equal(latest.data.entries.length, 6);
const working=third.messages.filter(m=>m.role==='system').map(m=>{try{return JSON.parse(m.content.split('\n').at(-1));}catch{return{};}}).find(value=>value.working_set);
for (const file of sources) {
const direct=third.messages.filter(m=>m.role==='tool').map(m=>JSON.parse(m.content)).find(result=>result.path===file&&typeof result.content==='string');
const sent=working?.data.entries.find(entry=>entry.observation.path===file)?.content
??direct?.content??latest.data.entries.find(entry => entry.result.path === file)?.result.content_excerpt;
assert.equal(sent,before[file],'The actual bounded request must retain every original source byte, regardless of versioned view.');
assert.equal(fs.readFileSync(path.join(f.projectRoot, file), 'utf8'), before[file]);
}
for (const step of JSON.parse(input.replies[1].tool_calls.at(-1).function.arguments).steps) {
assert.ok(third.messages[0].content.includes(step.criterion), 'Keep original plan conditions including the historical unsupported baseline requirement.');
}
const plans = [...f.store.core.context_plan.values()];
for (const plan of plans) verifyPlanEvidence(f.store, f.session, plan);
assert.ok(requestMetrics(third).estimatedInputTokens <= plans.at(-1).budget.inputBudget);
assert.equal(plans.at(-1).budget.contextLimit, 16000); assert.equal(plans.at(-1).budget.outputReservation, 2048);
assert.equal(plans.at(-1).budget.safetyTokens, 1600);
assert.equal(f.session.changes.length, 0); assert.equal(f.session.approvals.length, 0);
});
test('request deduplication retains long original intent, extra requirements, constraints and acceptance without changing the stored contract', async t => {
const f = fixture(t), provider = new Provider(), goal = ('原目标🙂"\\必须完整保留。').repeat(60) + 'Read README.md; preserve all files.';
let original;
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
const planner = runtime.requestPlanner(), prepare = planner.prepare.bind(planner);
const instruction = { source: 'user', content: '追加要求🙂"\\:保留空白与中文。' }, review = { source: 'review-action', content: '系统审查动作,不是业务需求' };
planner.prepare = (session, run, config, options) => {
const task = f.store.core.task.get(run.taskId);
if (!original) {
task.instructions.push(instruction, review); task.constraints.push('仅可读取,不可写入。'); task.acceptance.push('逐字保留中文与emoji🙂。');
original = structuredClone(task.contract);
// The first context was already assembled. Assert on the next turn.
} else {
const view = requirements(options.system);
assert.equal(view.goal, goal); assert.deepEqual(view.instructions, [instruction]);
assert.deepEqual(view.constraints, task.constraints); assert.deepEqual(view.acceptance, task.acceptance);
assert.deepEqual({ goal: view.goal, ...view.contract }, original); assert.deepEqual(task.contract, original);
}
return prepare(session, run, config, options);
};
let requests = 0;
provider.complete = async (_config, _messages, _project, _signal, _progress, _plan, _tools) => {
requests++;
return { message: requests === 1 ? input.replies[0] : { role: 'assistant', content: 'Read-only fixture.' }, usage: { prompt_tokens: 10, completion_tokens: 2 } };
};
runtime.start(f.session.id, goal); await runtime.active.get(f.session.id).promise;
assert.equal(requests, 2); assert.deepEqual(f.store.core.task.get(f.session.taskId).contract, original);
});
test('only the routine context avoids plan echoes; diagnostic API and requests without an included plan keep original observations', t => {
const f = fixture(t), output = JSON.stringify({ plan_id: 'owned-plan', criterion: '完整原条件🙂', steps: Array(10).fill('Long original plan step') });
f.session.events.push({ kind: 'tool', tool: 'plan_task', phase: 'completed', input: { expected_revision: 0 }, output });
const snapshot = sessionSnapshot(f.session, f.project, f.store.config), original = structuredClone(f.session);
assert.equal(snapshot.recentTools[0].outputExcerpt, output);
assert.ok(sessionContext(f.session, f.project, f.store.config).includes('owned-plan'));
const projected = sessionContext(f.session, f.project, f.store.config, String, { taskPlanIncluded: true });
assert.ok(!projected.includes('owned-plan')); assert.match(projected, /原工具结果仍保存在所属历史/);
assert.deepEqual(f.session, original);
const checks = taskPlanToolDefinitions[0].function.parameters.properties.steps.items.properties.checks.description;
assert.match(checks, /当前源码的最新通过结果/); assert.match(checks, /基线失败/);
});
@@ -0,0 +1,109 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash, randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { RequestPlanner, verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
import { Provider, toolDefinitions } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { fixture, call, completion, compatibleFixture, until, assertToolPairs } from './helpers.mjs';
const sha = text => createHash('sha256').update(text).digest('hex');
const feedbackFrom = messages => messages.filter(message => message.role === 'system').map(message => {
try { return JSON.parse(message.content.split('\n').at(-1)); } catch { return {}; }
}).find(value => value.latest_tools)?.data;
const workingFrom = messages => messages.filter(message => message.role === 'system').map(message => {
try { return JSON.parse(message.content.split('\n').at(-1)); } catch { return {}; }
}).find(value => value.working_set)?.data;
function setup(t) {
const f = fixture(t), config = { ...f.store.config, contextLimit: 16000, maxOutputTokens: 2048 };
const run = f.store.beginRun(f.session, 'Repair four source modules; preserve tests and report actual verification.', false, config);
f.session.providerMessages.push({ role: 'user', content: f.store.core.task.get(run.taskId).goal });
const planner = new RequestPlanner(f.store);
const add = items => {
const calls = items.map(item => call(randomUUID(), item.tool, item.args ?? {})), results = [];
for (const [index, invocation] of calls.entries()) {
const event = f.store.event(f.session, { kind: 'tool', tool: invocation.function.name, toolCallId: invocation.id,
runId: run.id, phase: 'queued', label: 'Actual recorded tool result' });
f.store.registerInvocation(f.session, invocation, run, event); f.store.beginInvocation(f.session, invocation, run, event);
f.store.finishInvocation(f.session, event, items[index].result);
results.push({ role: 'tool', tool_call_id: invocation.id, content: JSON.stringify(items[index].result) });
}
f.session.providerMessages.push({ role: 'assistant', content: '', tool_calls: calls }, ...results);
f.store.save(f.session); return calls;
};
const prepare = () => planner.prepare(f.session, run, config, { system: 'Current project and sealed Task requirements.', tools: toolDefinitions });
return { ...f, run, add, prepare };
}
test('the latest oversized session result reaches the next request together with already read source modules', t => {
const f = setup(t);
const files = ['normalize', 'summary', 'render', 'cli'].map(name => ({ path: 'src/' + name + '.mjs', content: 'export const ' + name + ' = value => value;\n' }));
for (const file of files) f.add([{ tool: 'read_file', args: { path: file.path }, result: { ...file, sha256: sha(file.content), start_line: 1, end_line: 1 } }]);
const calls = f.add([{ tool: 'inspect_session', result: { source: 'agent_workbench_runtime',
session: { id: f.session.id, status: 'running' }, changes: [], lastFailure: null,
execution: { task: { id: f.run.taskId, status: 'running', verification: { status: 'failed', checkJobId: 'actual-failed-check' } },
progress: { totalTools: 5, completedTools: 4, requiresVerification: [] },
checks: [{ id: 'actual-failed-check', status: 'failed', results: [{ name: 'test', status: 'failed', exitCode: 1,
tests: { total: 14, passed: 1, failed: 13, skipped: 0, cancelled: 0 }, logArtifactId: 'actual-failure-log' }] }],
contextPlans: [{ request: 'Historical request metadata '.repeat(16000) }] } } }]);
const original = structuredClone(f.session.providerMessages), plan = f.prepare();
const feedback = feedbackFrom(plan.messages);
assert.ok(feedback, 'An oversized completed tool group must have mandatory actual-result feedback');
assert.equal(feedback.entries[0].tool, 'inspect_session');
assert.equal(feedback.entries[0].result.session.status, 'running');
assert.equal(feedback.entries[0].result.execution.task.verification.status, 'failed');
assert.equal(feedback.entries[0].result.execution.checks[0].results[0].tests.failed, 13);
const document = JSON.parse(f.store.artifactStore.read(f.store.owned('artifact', plan.record.latestToolsArtifactId, f.session.id)));
assert.equal(document.entries[0].source.call_id, calls[0].id);
const working = workingFrom(plan.messages);
for (const file of files) assert.equal(working.entries.find(entry => entry.observation.path === file.path)?.content, file.content);
assert.deepEqual(f.session.providerMessages, original); assertToolPairs(plan.messages);
assert.ok(plan.record.estimatedInputTokens <= plan.record.budget.inputBudget);
verifyPlanEvidence(f.store, f.session, plan.record);
});
test('every call in a large latest group keeps its actual outcome, including denied and unknown results', t => {
const f = setup(t);
f.add([{ tool: 'query_code', args: { query: 'module' }, result: { totalMatches: 1, results: [{ path: 'src/main.mjs', line: 4, name: 'actual' }],
index: { metadata: 'Oversized index '.repeat(24000) } } },
{ tool: 'run_command', args: { command: 'node actual.mjs', reason: 'Saved fixture result' }, result: { status: 'denied', message: 'Command was not executed.' } },
{ tool: 'propose_file', args: { path: 'src/main.mjs', content: 'Saved proposal', reason: 'Fixture proposal' },
result: { status: 'unknown', requires_verification: true, change_id: 'unconfirmed-change', message: 'Original result requires verification.' } }]);
const plan = f.prepare(), entries = feedbackFrom(plan.messages).entries;
assert.deepEqual(entries.map(entry => entry.tool), ['query_code', 'run_command', 'propose_file']);
assert.equal(entries[0].result.results[0].path, 'src/main.mjs');
assert.equal(entries[1].result.status, 'denied'); assert.equal(entries[2].result.requires_verification, true);
verifyPlanEvidence(f.store, f.session, plan.record);
const document = f.store.owned('artifact', plan.record.latestToolsArtifactId, f.session.id);
const saved = JSON.parse(f.store.artifactStore.read(document));
const original = f.store.owned('artifact', saved.entries[0].source.result_artifact_id, f.session.id);
fs.writeFileSync(path.join(f.data, 'artifacts', original.relative), 'changed original bytes');
assert.throws(() => verifyPlanEvidence(f.store, f.session, plan.record), /执行工件校验失败/);
});
test('a small complete latest tool group is sent once and needs no duplicate feedback view', t => {
const f = setup(t), calls = f.add([{ tool: 'inspect_session', result: { session: { id: f.session.id, status: 'running' } } }]);
const plan = f.prepare();
assert.equal(plan.record.latestToolsArtifactId, null); assert.equal(feedbackFrom(plan.messages), undefined);
assert.equal(plan.messages.filter(message => message.tool_call_id === calls[0].id).length, 1);
verifyPlanEvidence(f.store, f.session, plan.record);
f.add([{ tool: 'inspect_session', result: { session: { id: f.session.id, status: 'completed' } } }]);
verifyPlanEvidence(f.store, f.session, plan.record);
});
test('real HTTP repeated state inspection pauses after three identical engineering outcomes and preserves tool pairing', { timeout: 30000 }, async t => {
const f = fixture(t); let requests = 0;
const model = await compatibleFixture(t, (_route, body) => {
requests++; assertToolPairs(body.messages);
return { body: completion([call('state-query-' + requests, 'inspect_session', {})]) };
});
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'state-query-fixture', maxSteps: 12 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Inspect the state, then finish without changing files.');
await until(() => !runtime.isActive(f.session.id), 20000);
assert.equal(f.session.status, 'paused'); assert.equal(f.store.core.run.get(f.session.runId).stopReason, 'no_progress');
assert.equal(requests, 3); assert.equal(f.session.events.filter(event => event.tool === 'inspect_session' && event.phase === 'completed').length, 3);
assertToolPairs(f.session.providerMessages);
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'README.md'), 'utf8'), '# Fixture project\n\nA local test project with TODO work.\n');
});
@@ -0,0 +1,394 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { RequestPlanner, historyGroups, verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
import { workingCandidates, workingMessage, workingDocument, workingEntry, verifyWorkingDocument } from '../src/core/context/working-set.mjs';
import { filePage } from '../src/core/context/read-budget.mjs';
import { requestMetrics } from '../src/shared/contracts/model-request.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Provider, toolDefinitions } from '../src/server/provider.mjs';
import { Store } from '../src/server/store.mjs';
import { CheckRunner } from '../src/core/check-runner.mjs';
import { createDeliveryProject } from './fixtures/delivery-project.mjs';
import { fixture, call, completion, compatibleFixture, until, assertToolPairs } from './helpers.mjs';
const sha = text => createHash('sha256').update(text, 'utf8').digest('hex');
const setFrom = messages => messages.filter(message => message.role === 'system').map(message => {
try { return JSON.parse(message.content.split('\n').at(-1)); } catch { return {}; }
}).find(value => value.working_set)?.data;
function setup(t, config = {}) {
const f = fixture(t);
f.config = { ...f.store.config, contextLimit: 10000, maxOutputTokens: 1024, ...config };
f.run = f.store.beginRun(f.session, 'Fix this project, preserve the public API and report actual checks.', false, f.config);
f.session.providerMessages.push({ role: 'user', content: f.store.core.task.get(f.run.taskId).goal });
f.planner = new RequestPlanner(f.store);
f.prepare = () => f.planner.prepare(f.session, f.run, f.config, { system: 'Current project and complete Task requirements.', tools: toolDefinitions });
return f;
}
function group(f, items) {
const calls = items.map(item => call(randomUUID(), item.tool, item.args));
const results = [];
for (const [index, invocation] of calls.entries()) {
const event = f.store.event(f.session, { kind: 'tool', tool: invocation.function.name, toolCallId: invocation.id,
runId: f.run.id, phase: 'queued', startedAt: new Date().toISOString(), label: 'Recorded fixture observation' });
f.store.registerInvocation(f.session, invocation, f.run, event);
f.store.beginInvocation(f.session, invocation, f.run, event);
f.store.finishInvocation(f.session, event, items[index].result);
results.push({ role: 'tool', tool_call_id: invocation.id, content: JSON.stringify(items[index].result) });
}
f.session.providerMessages.push({ role: 'assistant', content: '', tool_calls: calls }, ...results);
f.store.save(f.session);
return calls;
}
const read = (file, content) => ({ tool: 'read_file', args: { path: file },
result: { path: file, content, sha256: sha(content), start_line: 1, end_line: 2, total_lines: 2, truncated: false } });
const huge = () => ({ tool: 'query_code', args: { query: 'source' }, result: { results: 'Large mixed metadata '.repeat(16000) } });
const fragment = (text, offset, end, extra = {}) => ({ tool: 'read_file', args: { path: 'test/requirements.mjs', offset },
result: { path: 'test/requirements.mjs', sha256: sha(text), content: text.slice(offset, end), start_line: 1, end_line: 1,
range_start_line: 1, range_end_line: 1, offset, next_offset: end, total_characters: text.length, ...extra } });
test('all actually returned same-version fragments reach the bounded request, including overlap and Unicode, with independent original provenance', t => {
const f = setup(t, { contextLimit: 16000, maxOutputTokens: 2048 }), text = '头🙂"\\' + 'requirement;'.repeat(240) + '尾';
for (const [a, b] of [[0, 473], [473, 2089], [0, 472], [2089, 2557], [2557, text.length]]) group(f, [fragment(text, a, b), huge()]);
const original = structuredClone(f.session.providerMessages), sent = f.prepare(), set = setFrom(sent.messages);
const entry = set.entries.find(entry => entry.observation.path === 'test/requirements.mjs');
assert.equal(entry.content, text); assert.equal(entry.truncated, false); assert.equal(entry.fragments.count, 5);
assert.deepEqual(entry.sent_range, [0, text.length]); assertToolPairs(sent.messages);
assert.deepEqual(f.session.providerMessages, original); verifyPlanEvidence(f.store, f.session, sent.record);
const doc = JSON.parse(f.store.artifactStore.read(f.store.owned('artifact', sent.record.workingSetArtifactId, f.session.id)));
const altered = structuredClone(doc); altered.entries.find(e => e.fragments).fragments.pop();
assert.throws(() => verifyWorkingDocument(f.store, f.session, sent.record, altered, historyGroups(f.session.providerMessages)), /工作依据|片段/);
f.session.changes.push({ path: 'test/requirements.mjs', status: 'applied', appliedAt: '2099-01-01', sha256: sha('replacement') });
assert.equal(workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages), 3).filter(e => e.observation.kind === 'file').length, 0);
verifyPlanEvidence(f.store, f.session, sent.record); // Current changes cannot rewrite a historical wire request.
});
test('unread gaps and different range origins remain separate; partial sending names the precise missing already-observed range', t => {
const f = setup(t), text = '0123456789🙂';
group(f, [fragment(text, 0, 4), fragment(text, 6, 10), fragment(text, 0, 4, { range_start_line: 2, range_end_line: 2, start_line: 2, end_line: 2 })]);
const candidates = workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages), 3);
assert.equal(candidates.length, 3); assert.ok(candidates.every(c => !c.observation.content.includes('45')));
const entry = workingEntry(candidates.find(c => c.observation.offset === 6), 2);
const message = workingMessage({ id: 'original', sha256: sha('original') }, workingDocument(f.session, f.run, [entry], 3), 4);
const view = JSON.parse(message.content.split('\n').at(-1)).data.entries[0];
assert.deepEqual(view.sent_range, [6, 8]); assert.deepEqual(view.unsent_observed_range, [8, 10]);
assert.ok(view.source.result_artifact_id);
});
test('same-SHA conflicting overlaps and invalid coordinates fail closed, while a new SHA never inherits old fragments', t => {
const f = setup(t), text = '0123456789';
group(f, [fragment(text, 0, 6), fragment(text, 4, 10, { content: 'XX6789' })]);
assert.throws(() => workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages), 3), /重叠内容冲突/);
group(f, [fragment('abcdefghij', 0, 4)]);
const fresh = workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages), 3);
assert.equal(fresh.length, 1); assert.equal(fresh[0].observation.content, 'abcd');
group(f, [fragment('abcdefghij', 4, 10, { next_offset: 11 })]);
assert.throws(() => workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages), 3), /坐标/);
});
test('versioned old views keep the original single-page semantics and verification', t => {
const f = setup(t), text = '0123456789'; group(f, [fragment(text, 0, 4), fragment(text, 4, 10)]);
const groups = historyGroups(f.session.providerMessages);
for (const version of [1, 2]) {
const old = workingCandidates(f.store, f.session, f.run, groups, version);
assert.equal(old.length, 1); assert.equal(old[0].observation.content, '456789');
const document = workingDocument(f.session, f.run, old.map(c => workingEntry(c, c.observation.content.length)), version);
verifyWorkingDocument(f.store, f.session, { taskId: f.run.taskId, workingSetEntries: 1 }, document, groups);
assert.doesNotThrow(() => workingMessage({ id: 'old', sha256: sha('old') }, document, version));
}
});
test('small code and actual failed command stay visible when their original multi-tool group cannot fit', t => {
const f = setup(t), code = 'export const add = (a, b) => a + b;\n';
const calls = group(f, [read('src/add.mjs', code), huge(), { tool: 'run_command', args: { command: 'node check.mjs', reason: 'Fixture evidence.' },
result: { status: 'completed', exit_code: 1, stdout: '1 test failed', stderr: 'Expected add(2, 3) to equal 5' } }]);
const original = structuredClone(f.session.providerMessages), plan = f.prepare(), set = setFrom(plan.messages);
assert.ok(set); assert.equal(set.taskId, f.run.taskId); assert.equal(set.entries.find(entry => entry.observation.path === 'src/add.mjs').content, code);
assert.ok(set.entries.some(entry => entry.observation.exit_code === 1 && entry.content.includes('Expected add')));
assert.ok(!plan.messages.some(message => message.tool_calls?.some(call => call.id === calls[0].id)));
assert.deepEqual(f.session.providerMessages, original); assertToolPairs(plan.messages);
assert.ok(requestMetrics(plan.body).estimatedInputTokens <= plan.record.budget.inputBudget);
verifyPlanEvidence(f.store, f.session, plan.record);
const sent = f.store.artifactStore.read(f.store.owned('artifact', plan.record.requestArtifactId, f.session.id));
assert.equal(sha(sent), plan.record.requestSha256); assert.ok(plan.record.workingSetEntries >= 2);
});
test('mixed group retains six distinct small file observations with exact multilingual text and bounded request bytes', t => {
const f = setup(t, { contextLimit: 14000 }), files = Array.from({ length: 6 }, (_, index) => read('src/模块-' + index + '.mjs',
'export const value = "第' + index + '个🙂\\雪";\r\n'));
group(f, [...files, huge()]);
const plan = f.prepare(), set = setFrom(plan.messages);
for (const file of files) {
const entry = set.entries.find(entry => entry.observation.path === file.args.path);
assert.ok(entry); assert.equal(entry.content, file.result.content); assert.equal(entry.content_sha256, sha(file.result.content));
assert.ok(entry.content.isWellFormed()); assert.equal(entry.truncated, false);
}
assert.ok(requestMetrics(plan.body).estimatedInputTokens <= plan.record.budget.inputBudget);
assertToolPairs(plan.messages); verifyPlanEvidence(f.store, f.session, plan.record);
});
test('working observations are bound to the current Task and stop treating a pre-application file revision as current evidence', t => {
const f = setup(t); group(f, [read('src/old.mjs', 'Previous task bytes\n'), huge()]);
f.session.status = 'completed'; f.store.finishRun(f.session, f.run);
f.run = f.store.beginRun(f.session, 'A different Task must use its own observations.', false, f.config);
f.session.providerMessages.push({ role: 'user', content: 'A different Task must use its own observations.' });
group(f, [read('src/current.mjs', 'Current task bytes\n'), huge()]);
const plan = f.prepare(), set = setFrom(plan.messages);
assert.ok(set.entries.some(entry => entry.observation.path === 'src/current.mjs'));
assert.ok(!set.entries.some(entry => entry.observation.path === 'src/old.mjs'));
f.session.changes.push({ id: randomUUID(), taskId: f.run.taskId, path: 'src/current.mjs', status: 'applied',
sha256: sha('Newly applied revision'), appliedAt: new Date(Date.now() + 1000).toISOString() });
assert.ok(!workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages)).some(entry => entry.observation.path === 'src/current.mjs'));
// A historical sent observation remains valid evidence of what was sent.
verifyPlanEvidence(f.store, f.session, plan.record);
});
test('a sealed observation rejects changed or missing original result artifacts instead of recreating evidence', t => {
const f = setup(t); group(f, [read('src/evidence.mjs', 'Exact recorded source\n'), huge()]);
const plan = f.prepare(), set = setFrom(plan.messages), entry = set.entries[0];
const artifact = f.store.owned('artifact', entry.source.result_artifact_id, f.session.id), target = path.join(f.data, 'artifacts', artifact.relative);
fs.writeFileSync(target, 'External corrupted observation');
assert.throws(() => verifyPlanEvidence(f.store, f.session, plan.record), /工件校验失败/);
assert.throws(() => f.prepare(), /工件校验失败/); assert.equal(fs.readFileSync(target, 'utf8'), 'External corrupted observation');
fs.unlinkSync(target); assert.throws(() => f.prepare(), /ENOENT/); assert.equal(fs.existsSync(target), false);
});
test('a real passed-check observation is excluded after a source edit invalidates the check, while its historical sent evidence remains valid', async t => {
const f = setup(t); createDeliveryProject(f);
fs.writeFileSync(path.join(f.projectRoot, 'src/add.mjs'), 'export const add = (a, b) => a + b;\n');
const runner = new CheckRunner(f.store), plan = await runner.plan(f.session), { promise } = await runner.start(f.session, plan.id);
const job = await promise; assert.equal(job.status, 'passed');
group(f, [{ tool: 'run_checks', args: { plan_id: plan.id }, result: { status: 'completed', check_status: job.status,
job_id: job.id, plan_id: plan.id, results: job.results, summary: job.summary, fingerprint: job.fingerprint } }, huge()]);
const sent = f.prepare(); assert.ok(setFrom(sent.messages).entries.some(entry => entry.observation.job_id === job.id));
fs.appendFileSync(path.join(f.projectRoot, 'src/add.mjs'), '// Later real source edit.\n');
await runner.plan(f.session); assert.equal(job.stale, true);
assert.ok(!workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages)).some(entry => entry.observation.job_id === job.id));
verifyPlanEvidence(f.store, f.session, sent.record);
});
test('budgeted file pages reconstruct UTF-8 text including long single lines and surrogate boundaries', () => {
const text = '首行🙂"\\\r\n' + '超长单行🙂\\"'.repeat(2000) + '\n最后一行🙂';
const file = { path: '长文件.mjs', content: text, sha256: sha(text), start_line: 21, end_line: 23, total_lines: 23, bom: true, truncated: true };
let offset = 0, joined = '', count = 0;
while (offset < text.length) {
const page = filePage(file, { offset }, { maximumMessageBytes: 2800, callId: 'file-page' });
assert.ok(Buffer.byteLength(JSON.stringify({ role: 'tool', tool_call_id: 'file-page', content: JSON.stringify(page) })) <= 2800);
assert.ok(page.next_offset > offset); assert.equal(page.offset, offset); assert.equal(page.content, text.slice(offset, page.next_offset));
assert.ok(page.content.isWellFormed()); assert.equal(page.sha256, file.sha256); assert.equal(page.range_start_line, 21); assert.equal(page.range_end_line, 23);
joined += page.content; offset = page.next_offset; count++;
}
assert.equal(joined, text); assert.ok(count > 10);
const unicode = filePage({ ...file, content: '🙂雪' }, { offset: 1, limit: 1 }, { maximumMessageBytes: 1500 });
assert.equal(unicode.offset, 0); assert.equal(unicode.content, '🙂'); assert.equal(unicode.next_offset, 2);
});
test('actual HTTP multi-tool reads survive an oversized runtime snapshot and the sealed evidence survives reopening', { timeout: 30000 }, async t => {
const f = fixture(t); fs.mkdirSync(path.join(f.projectRoot, 'src'));
const code = 'export const actual = "真实模块🙂";\n'; fs.writeFileSync(path.join(f.projectRoot, 'src/actual.mjs'), code);
let requests = 0;
const model = await compatibleFixture(t, (_route, body) => {
requests++; assertToolPairs(body.messages);
if (requests === 1) {
const run = f.store.core.run.get(f.session.runId);
for (let index = 0; index < 160; index++) {
const artifact = f.store.artifactStore.write(f.session, run, 'Runtime snapshot fixture ' + index, { kind: 'fixture-evidence' });
f.store.core.artifact.set(artifact.id, artifact);
}
f.store.save(f.session);
return { body: completion([call('mixed-read', 'read_file', { path: 'src/actual.mjs' }), call('mixed-snapshot', 'inspect_session', {})]) };
}
const set = setFrom(body.messages);
assert.ok(set, 'A small result in a large mixed group must be visible in a sealed observation');
assert.equal(set.entries.find(entry => entry.observation.path === 'src/actual.mjs').content, code);
return { body: completion([], 'Used the actual source observation to complete this read-only task.') };
});
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'working-set-fixture', maxSteps: 6 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Read src/actual.mjs and the runtime state. Preserve all files.');
await until(() => !runtime.isActive(f.session.id), 20000);
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.failure)); assert.equal(requests, 2);
assert.equal([...f.store.core.tool.values()].length, 2); assert.equal(fs.readFileSync(path.join(f.projectRoot, 'src/actual.mjs'), 'utf8'), code);
const plan = [...f.store.core.context_plan.values()].at(-1); assert.ok(plan.workingSetEntries);
verifyPlanEvidence(f.store, f.session, plan); f.store.close();
const reopened = new Store(f.data); f.onCleanup(() => reopened.close());
verifyPlanEvidence(reopened, reopened.session(f.session.id), reopened.core.context_plan.get(plan.id));
assert.equal(requests, 2); assertToolPairs(reopened.session(f.session.id).providerMessages);
});
test('actual HTTP file pagination advances over a long file with each returned page visible in the next request', { timeout: 30000 }, async t => {
const f = fixture(t), text = ('真实长行🙂"\\' + 'content'.repeat(25) + '\n').repeat(150);
fs.writeFileSync(path.join(f.projectRoot, 'README.md'), text);
let joined = '', requests = 0, priorOffset = 0;
const model = await compatibleFixture(t, (_route, body) => {
requests++; assertToolPairs(body.messages);
if (requests === 1) return { body: completion([call('file-first', 'read_file', { path: 'README.md', start_line: 1, end_line: 200 })]) };
const result = body.messages.filter(message => message.role === 'tool').map(message => JSON.parse(message.content)).findLast(result => result.path === 'README.md');
assert.ok(result, 'The newest actual budgeted page must be sent'); assert.equal(result.offset, priorOffset);
assert.equal(result.content, text.slice(result.offset, result.next_offset)); joined += result.content; priorOffset = result.next_offset;
if (result.next_offset === result.total_characters) return { body: completion([], 'Completed the actual paginated read.') };
return { body: completion([call('file-next-' + requests, 'read_file', { path: 'README.md', start_line: result.range_start_line,
end_line: result.range_end_line, offset: result.next_offset })]) };
});
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'file-page-fixture', maxSteps: 12 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Read this long file using actual pages. Preserve its bytes.');
await until(() => !runtime.isActive(f.session.id), 20000);
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.failure)); assert.ok(requests > 2); assert.equal(joined, text);
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'README.md'), 'utf8'), text);
});
test('later mixed history pages cannot displace the actual module sources and complete requirements', t => {
const f = setup(t, { contextLimit: 16000, maxOutputTokens: 2048 });
const files = [read('src/normalize.mjs', 'export const normalizeTasks = input => input;\n'),
read('src/summary.mjs', 'export const summarizeTasks = tasks => ({ total: tasks.length });\n'),
read('src/render.mjs', 'export const renderSummary = summary => JSON.stringify(summary);\n'),
read('src/cli.mjs', 'export const run = args => args;\n'),
read('README.md', 'The complete seven engineering requirements.\n'.repeat(18)),
read('test/delivery.test.mjs', 'A sealed actual test assertion with Unicode 雪🙂.\n'.repeat(65))];
group(f, [...files, huge()]);
for (let index = 0; index < 12; index++) {
const text = 'Historical locator metadata '.repeat(400), artifact = f.store.artifactStore.write(f.session, f.run, text, { kind: 'context-history-index' });
f.store.core.artifact.set(artifact.id, artifact);
group(f, [{ tool: 'read_artifact', args: { artifact_id: artifact.id, offset: 0 }, result: {
artifact_id: artifact.id, kind: artifact.kind, sha256: artifact.sha256, content: text,
offset: 0, next_offset: text.length, total_characters: text.length, truncated: false,
} }]);
}
const plan = f.planner.prepare(f.session, f.run, f.config, { system: 'Complete mandatory project and Task state. '.repeat(160), tools: toolDefinitions });
const set = setFrom(plan.messages); assert.ok(set);
for (const file of files) {
const entry = set.entries.find(entry => entry.observation.path === file.args.path);
assert.ok(entry, 'Missing actual observed file: ' + file.args.path);
assert.equal(entry.content, file.result.content); assert.equal(entry.truncated, false);
}
assertToolPairs(plan.messages); verifyPlanEvidence(f.store, f.session, plan.record);
assert.ok(plan.record.estimatedInputTokens <= plan.record.budget.inputBudget);
});
test('a later narrow page of the same file revision cannot evict the wider actual observation', t => {
const f = setup(t), text = 'An actual previously read complete source line.\n'.repeat(42);
group(f, [read('src/complete.mjs', text), huge()]);
for (const offset of [400, 800, 1200]) group(f, [{ tool: 'read_file', args: { path: 'src/complete.mjs', offset }, result: {
path: 'src/complete.mjs', sha256: sha(text), content: text.slice(offset, offset + 180), start_line: 1, end_line: 2,
range_start_line: 1, range_end_line: 2, offset, next_offset: offset + 180, total_characters: text.length,
} }, huge()]);
const plan = f.prepare(), set = setFrom(plan.messages);
const candidates = workingCandidates(f.store, f.session, f.run, historyGroups(f.session.providerMessages));
assert.equal(candidates.find(candidate => candidate.observation.path === 'src/complete.mjs').observation.content, text);
assert.equal(set.entries.find(entry => entry.observation.path === 'src/complete.mjs').content, text);
verifyPlanEvidence(f.store, f.session, plan.record);
});
test('six small source files stay complete across metadata turns even when mandatory evidence exceeds the soft target', t => {
const f = setup(t, { contextLimit: 32000, maxOutputTokens: 2048 });
const files = [['src/App.tsx', 1991], ['test/domain.test.mjs', 1715], ['src/transition.ts', 167],
['src/query.ts', 142], ['src/types.ts', 82], ['src/summary.ts', 155]].map(([name, size]) => read(name,
('// ' + name + '\n').padEnd(size, 'x')));
group(f, [...files, huge()]);
const system = 'Complete original Task constraints and required permission boundaries. '.repeat(620);
const original = structuredClone(f.session.providerMessages);
let exceededSoftTarget = false;
for (let index = 0; index < 4; index++) {
group(f, [{ tool: 'inspect_session', args: {}, result: { session: { status: 'running' },
execution: { progress: { completedTools: index + 7 } }, metadata: 'Historical metadata '.repeat(1800) } }]);
const prepared = f.planner.prepare(f.session, f.run, f.config, { system, tools: toolDefinitions });
const set = setFrom(prepared.messages);
for (const file of files) {
const entry = set.entries.find(entry => entry.observation.path === file.args.path);
assert.equal(entry?.content, file.result.content); assert.equal(entry.truncated, false);
}
assert.equal(prepared.record.budget.targetInputTokens, 16000);
assert.ok(prepared.record.estimatedInputTokens <= prepared.record.budget.inputBudget);
assert.ok(prepared.record.workingRetentionTokens > 2048);
exceededSoftTarget ||= prepared.record.estimatedInputTokens > 16000;
assertToolPairs(prepared.messages); verifyPlanEvidence(f.store, f.session, prepared.record);
}
assert.ok(exceededSoftTarget, 'The regression must exercise the soft-target boundary.');
assert.deepEqual(f.session.providerMessages.slice(0, original.length), original);
});
test('historical read-artifact navigation points to the original artifact and next page, never its result wrapper', t => {
const f = setup(t), text = 'An actual saved failure log.\n';
const artifact = f.store.artifactStore.write(f.session, f.run, text, { kind: 'check-log' }); f.store.core.artifact.set(artifact.id, artifact);
const calls = group(f, [{ tool: 'read_artifact', args: { artifact_id: artifact.id, offset: 0 }, result: {
artifact_id: artifact.id, kind: artifact.kind, sha256: artifact.sha256, content: text,
offset: 0, next_offset: text.length, total_characters: text.length, truncated: false,
} }, huge()]);
const wrapper = [...f.store.core.tool.values()].find(tool => tool.callId === calls[0].id).resultArtifactId;
const plan = f.prepare(), navigation = plan.messages.filter(message => message.role === 'system').map(message => {
try { return JSON.parse(message.content.split('\n').at(-1)).working_evidence; } catch { return null; }
}).find(Boolean);
const link = navigation.find(item => item.name === 'read_artifact'); assert.ok(link);
assert.equal(link.artifact_id, artifact.id); assert.equal(link.next_offset, text.length);
assert.notEqual(link.result_artifact_id, wrapper); verifyPlanEvidence(f.store, f.session, plan.record);
});
test('a 1.6.1 full-provenance sent view remains verifiable after introducing the compact view', t => {
const f = setup(t); group(f, [read('src/legacy.mjs', 'export const legacy = true;\n'), huge()]);
const prepared = f.prepare(), record = structuredClone(prepared.record);
const workingArtifact = f.store.owned('artifact', record.workingSetArtifactId, f.session.id);
const document = JSON.parse(f.store.artifactStore.read(workingArtifact));
const oldMessage = workingMessage(workingArtifact, document, 1), body = structuredClone(prepared.body);
const currentMessage = workingMessage(workingArtifact, document, prepared.record.workingSetViewVersion);
body.messages = body.messages.map(message => message.content === currentMessage.content ? oldMessage : message);
const metrics = requestMetrics(body), request = f.planner.artifact(f.session, f.run, body, 'model-request');
Object.assign(record, { requestSha256: metrics.sha256, requestBytes: metrics.bytes, estimatedInputTokens: metrics.estimatedInputTokens, requestArtifactId: request.id });
// A modern reservation is bound to the actual request body. Rewriting only
// the sent view must fail; genuine 1.6.1 records predate these fields.
assert.throws(() => verifyPlanEvidence(f.store, f.session, record), /模型预算预留与原估算\/用量\/实际线路不一致/);
delete record.tokenReservation; delete record.maxBudgetAttempts;
delete record.workingSetViewVersion; delete record.workingRetentionTokens;
const frozen = f.planner.artifact(f.session, f.run, record, 'context-plan'); record.artifactId = frozen.id;
assert.notEqual(oldMessage.content, currentMessage.content); assert.ok(oldMessage.content.includes('invocation_id'));
assert.ok(!currentMessage.content.includes('invocation_id'));
verifyPlanEvidence(f.store, f.session, record);
record.workingSetViewVersion = 2;
assert.throws(() => verifyPlanEvidence(f.store, f.session, record), /工作依据视图或保留预算/);
});
test('actual HTTP requests keep four observed modules after a later large history read and preserve all source bytes', { timeout: 30000 }, async t => {
const f = fixture(t), files = ['normalize', 'summary', 'render', 'cli'].map(name => ({
path: 'src/' + name + '.mjs', content: 'export const ' + name + ' = value => value; // observed 雪🙂\n',
}));
fs.mkdirSync(path.join(f.projectRoot, 'src'), { recursive: true });
for (const file of files) fs.writeFileSync(path.join(f.projectRoot, file.path), file.content);
let requests = 0;
const model = await compatibleFixture(t, (_route, body) => {
requests++; assertToolPairs(body.messages);
if (requests === 1) {
const run = f.store.core.run.get(f.session.runId);
for (let index = 0; index < 160; index++) {
const artifact = f.store.artifactStore.write(f.session, run, 'Recorded fixture snapshot ' + index, { kind: 'fixture-evidence' });
f.store.core.artifact.set(artifact.id, artifact);
}
f.store.save(f.session);
return { body: completion([...files.map((file, index) => call('four-file-' + index, 'read_file', { path: file.path })), call('four-snapshot', 'inspect_session', {})]) };
}
const set = setFrom(body.messages);
for (const file of files) {
const raw = body.messages.filter(message => message.role === 'tool').map(message => JSON.parse(message.content)).find(result => result.path === file.path);
const view = set?.entries.find(entry => entry.observation.path === file.path);
assert.equal(raw?.content ?? view?.content, file.content, 'Lost actual module after historical read: ' + file.path);
}
if (requests === 2) {
const index = body.messages.filter(message => message.role === 'system').map(message => {
try { return JSON.parse(message.content.split('\n').at(-1)).history_index; } catch { return null; }
}).find(Boolean);
assert.ok(index);
return { body: completion([call('later-metadata-page', 'read_artifact', { artifact_id: index.artifact_id, limit: 16000 })]) };
}
return { body: completion([], 'Used the previously observed modules after the large metadata result.') };
});
f.store.saveConfig({ mode: 'compatible', baseUrl: model.baseUrl, model: 'working-retention-http-fixture', contextLimit: 16000, maxOutputTokens: 2048, maxSteps: 6 });
const runtime = new Runtime(f.store, new Provider()); f.onCleanup(() => runtime.stopAll());
runtime.start(f.session.id, 'Read the four modules and preserve their bytes while inspecting historical metadata.');
await until(() => !runtime.isActive(f.session.id), 25000);
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.failure)); assert.equal(requests, 3);
for (const file of files) assert.equal(fs.readFileSync(path.join(f.projectRoot, file.path), 'utf8'), file.content);
const plans = [...f.store.core.context_plan.values()]; assert.equal(plans.length, 3);
for (const plan of plans) verifyPlanEvidence(f.store, f.session, plan);
});