fix(context): preserve progress counters and reserve fresh read evidence

This commit is contained in:
Agent Workbench Dev
2026-11-03 12:03:42 +08:00
parent 10dbd8f500
commit ecdc939c29
9 changed files with 174 additions and 8 deletions
+4
View File
@@ -2,6 +2,10 @@
## I 修复启动
I-C修复后10/10、构建通过。编译宿主Chat完整交付3组/7次自有请求通过:原3失败→两文件提案/批次审查→显式同Task续接→直接采用当前SHA/失效检查快照重新计划/审批→原3通过与构建→Git预览及显式确认,仅两文件提交、原用户暂存/工作区保持,报告逐尝试身份matched。首验证器误把plan_checks的id读成plan_id,在第二请求失败,原日志/样本保存;修正验证器后新隔离例通过,产品没有以该失败修改检查契约。真正模型与Purge收益尚未新测。
I-C首轮10项9通过/1失败保持:新增状态摘要占用下一请求空间,最新大日志页被归档,实际原文仍保留。已压缩常驻身份到最近两项、已读摘要限定2000字节,分页前预留下一状态开销(不扩大请求预算),重验原失败及相关分页/无进展。三项新空转专项均通过:相同提案不能清读取/查询计数、复用证明不新建进展、同SHA区间并集/新SHA及跨Run分离。
I-B首2项真实文件/检查专项通过,证明旧检查失效、应用SHA、当前计划/检查到Git预览建议和用户再次修改阻断,快照本身没有执行检查或提交。构建与编译宿主10组原交接UI通过(整批应用、显式续接、真实Node检查及两视口预算诊断)。下一补最终编译API完整检查/Git及实际Harness,尚不把建议快照当真实模型交付。
I-A小步提交3659f5e8。更广模型/引擎/交付开发轮90/90通过,保持其开发轮含义;I-B开始新增当前应用SHA/检查计划/下一可验证动作快照,宿主原权限不改变。两次猜测共享checks模块不存在、补丁最后锚点不匹配均在生效前纠正;后续按现有CheckRunner.planFor复用封存校验,不重复造检查契约。
+70
View File
@@ -0,0 +1,70 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {createHash,randomUUID} from 'node:crypto';
import {fixture,compatibleFixture,launchWorkbench,until,call,completion} from '../tests/helpers.mjs';
import {createDeliveryProject,deliveryGit} from '../tests/fixtures/delivery-project.mjs';
if(process.argv.includes('--help')){console.log('node scripts/verify-delivery-progress.mjs [--responses] [--app-root ABSOLUTE_ROOT] — compiled host, owned HTTP fixture, real tests/review/continuation/Git; no configured-model requests.');process.exit(0);}
const args=process.argv.slice(2),responses=args.includes('--responses'),rootIndex=args.indexOf('--app-root'),appRoot=rootIndex<0?process.cwd():path.resolve(args[rootIndex+1]);
const directory=path.resolve('.qa','delivery-progress-'+randomUUID());fs.mkdirSync(directory,{recursive:true});
const cleanups=[],t={after:fn=>cleanups.push(fn)},f=fixture(t),snapshots=[],checks=[];
createDeliveryProject(f);const parent=deliveryGit(f,['rev-parse','HEAD']).trim(),protectedIndex=deliveryGit(f,['show',':owner-staged.txt']);
const protectedFiles=['owner-staged.txt','owner-unstaged.txt','owner-untracked.txt'].map(file=>[file,fs.readFileSync(path.join(f.projectRoot,file))]);
f.store.close();let requests=0,firstPhase=0,host,result;
const marker='已应用修改后的当前交付依据(每次请求重新核对,非操作授权):\n';
try{
const upstream=await compatibleFixture(t,(route,body)=>{
const messages=body.messages??body.input,allText=messages.map(value=>typeof value.content==='string'?value.content:JSON.stringify(value.content??'')).join('\n');
const position=allText.indexOf(marker),progress=position<0?null:JSON.parse(allText.slice(position+marker.length).split('\n')[0]);requests++;
let calls;
if(progress){snapshots.push(progress);assert.ok(progress.files.every(file=>file.current));assert.ok(progress.next_action,'known facts must permit the next fixture action');
calls=[call('next-'+requests,progress.next_action.tool,progress.next_action.arguments)];
}else{
firstPhase++;
if(firstPhase===1)calls=[call('old-plan','plan_checks',{names:['test','build']})];
else if(firstPhase===2){
const original=messages.filter(value=>value.role==='tool'||value.type==='function_call_output').map(value=>{try{return JSON.parse(value.content??value.output);}catch{return null;}}).findLast(value=>value?.id&&Array.isArray(value.checks));
assert.ok(original);calls=[call('old-check','run_checks',{plan_id:original.id})];
}else if(firstPhase===3)calls=[call('fix-add','propose_file',{path:'src/add.mjs',content:"import {sum} from './math.mjs';\nexport const add=sum;\n",reason:'Owned repair after original failing tests'}),
call('fix-math','propose_file',{path:'src/math.mjs',content:'export const sum=(a,b)=>a+b;\n',reason:'Owned repair'})];
else if(firstPhase===4){
const ids=messages.filter(value=>value.role==='tool'||value.type==='function_call_output').map(value=>{try{return JSON.parse(value.content??value.output)?.change_id;}catch{return null;}}).filter(Boolean);
assert.equal(ids.length,2);calls=[call('seal','prepare_change_set',{change_ids:ids})];
}else throw new Error('Fixture must not poll for state after the recorded application.');
}
const response=completion(calls);response.model='owned-delivery-progress';
if(!responses)return {body:response};
return {body:{id:'owned-response-'+requests,model:response.model,status:'completed',output:calls.map(tool=>({type:'function_call',id:'item-'+tool.id,call_id:tool.id,name:tool.function.name,arguments:tool.function.arguments})),
usage:{input_tokens:13,output_tokens:7,total_tokens:20}}};
});
host=await launchWorkbench(t,f.data,{}, {appRoot});assert.notEqual(new URL(host.url).port,'4318');
const connection=await host.api('/model-center/connections',{name:'Owned progress fixture',model:'owned-delivery-progress',baseUrl:upstream.baseUrl,requiresKey:false,
protocol:responses?'responses':'chat-completions',contextLimit:32000,maxOutputTokens:512,modelIdentityPolicy:'require-match'});
await host.api('/model-center/select',{type:'connection',id:connection.id});const route='/sessions/'+f.session.id;
const settle=async()=>{let state;await until(async()=>{state=await host.api(route);for(const approval of state.approvals.filter(value=>value.status==='pending'))await host.api(route+'/approvals/'+approval.id,{allow:true});
return !['running','awaiting_approval','stopping'].includes(state.status);},60000);return state;};
await host.api(route+'/messages',{content:'修复加法模块,通过原测试与构建,并准备审查后的本地Git交付。'});
let state=await settle();assert.equal(state.status,'needs_review',JSON.stringify(state.failure));assert.equal(requests,4);
assert.equal(state.execution.checks[0].status,'failed');assert.equal(state.execution.checks[0].results[0].tests.failed,3);
const taskId=state.taskId,batch=state.execution.changeSets.at(-1);assert.equal(batch.status,'prepared');
await host.api(route+'/change-sets/'+batch.id+'/apply',{fingerprint:batch.fingerprint});
await until(async()=>(await host.api(route)).execution.changeSets.at(-1).status==='completed',20000);assert.equal(requests,4);
checks.push('original three failed tests, complete batch review and application with no automatic model continuation');
await host.api(route+'/continue-reviewed',{});state=await settle();assert.equal(state.status,'needs_review',JSON.stringify(state.failure));
assert.equal(state.taskId,taskId);assert.equal(state.execution.run.stopReason,'git_review');assert.equal(requests,7);
assert.deepEqual(snapshots.map(value=>value.stage),['needs_current_check_plan','ready_for_checks','ready_for_git_preview']);
const passed=state.execution.checks.at(-1);assert.equal(passed.status,'passed');assert.equal(passed.results[0].tests.passed,3);
assert.equal(deliveryGit(f,['rev-parse','HEAD']).trim(),parent);checks.push('current applied SHA and stale checks drive new plan, approval, original tests/build and Git preview without state polling');
await host.api(route+'/delivery-jobs',{planId:state.execution.deliveryPlans.at(-1).id});
await until(async()=>{state=await host.api(route);return !!state.execution.deliveries.at(-1)?.reportArtifactId;},30000);
const job=state.execution.deliveries.at(-1);assert.equal(job.status,'completed');assert.deepEqual(job.paths.slice().sort(),['src/add.mjs','src/math.mjs']);
assert.equal(deliveryGit(f,['show',':owner-staged.txt']),protectedIndex);for(const [file,bytes]of protectedFiles)assert.deepEqual(fs.readFileSync(path.join(f.projectRoot,file)),bytes);
const report=await host.api('/artifacts/'+job.reportArtifactId+'?session='+state.id+'&limit=64000');assert.equal(report.truncated,false);
const raw=JSON.parse(report.content);assert.equal(raw.status,'verified_committed');assert.equal(raw.task.id,taskId);
assert.ok(raw.runs.flatMap(run=>run.consumption).every(receipt=>receipt.modelIdentity.status==='matched'));
checks.push('explicit Git confirmation publishes only reviewed files and preserves owner index/worktree with identity-bearing report');
result={success:true,version:host.bootstrap.version,protocol:responses?'responses':'chat-completions',requests,checks,snapshots,commit:job.commit,
reportSha256:createHash('sha256').update(report.content).digest('hex'),realModelRequests:0};
}catch(error){result={success:false,error:error.stack,requests,checks,snapshots,realModelRequests:0};throw error;}
finally{fs.writeFileSync(path.join(directory,'result.json'),JSON.stringify(result,null,2));console.log(JSON.stringify({success:result.success,directory,checks:checks.length,requests}));for(const action of cleanups.reverse())await action();}
+30 -3
View File
@@ -33,7 +33,10 @@ export function readMessageBudget(plan, message) {
const calls = message.tool_calls?.length ?? 1;
const assistantTokens = Math.ceil(Buffer.byteLength(JSON.stringify(message), 'utf8') / 3) + 8;
// Reserve space for the current call's framing and the next state/notice.
const tokens = plan.budget.inputBudget - (plan.nextReadFixedInputTokens ?? plan.mandatoryInputTokens) - (plan.workingRetentionTokens ?? 0) - assistantTokens - calls * 8 - 512;
// The next request also gains bounded read coverage and route observations.
// Reserve their growth before returning a page, rather than dropping that
// new page or enlarging the request budget afterwards.
const tokens = plan.budget.inputBudget - (plan.nextReadFixedInputTokens ?? plan.mandatoryInputTokens) - (plan.workingRetentionTokens ?? 0) - assistantTokens - calls * 8 - 512 - 2048;
return Math.max(1024, Math.floor(tokens * 3 / calls));
}
@@ -89,7 +92,7 @@ export function recordArtifactRead(task, artifact, result, invocationId, runId =
} else progress.changingIndexes = [];
progress.warning = progress.repeated >= 1 ? '本次运行已经返回该工件区间,请使用已返回内容,或按next_offset读取新的区间。'
: progress.changingIndexes.length >= 3 ? '连续读取更新的历史索引没有推进工程;请直接读取实际结果或项目文件,依据已有信息继续任务。' : null;
progress.pause = progress.checkPause === true || progress.repeated >= 3 || progress.changingIndexes.length >= 6;
progress.pause = progress.checkPause === true || progress.noopPause === true || progress.repeated >= 3 || progress.changingIndexes.length >= 6;
progress.last = { artifactId: artifact.id, sha256: artifact.sha256, offset: start, nextOffset: end, invocationId,
contentSha256: createHash('sha256').update(result.content, 'utf8').digest('hex') };
return progress;
@@ -101,6 +104,7 @@ export function clearReadStreak(task) {
task.readProgress.sessionInspection = null;
task.readProgress.observations = [];
task.readProgress.checkPause = false;
task.readProgress.noopPause = false;
task.readProgress.resultRepeats = 0;
}
@@ -150,6 +154,29 @@ export function recordSessionInspection(task, result) {
const consecutive = previous?.signature === signature ? previous.consecutive + 1 : 1;
progress.sessionInspection = { signature, consecutive };
progress.warning = consecutive >= 2 ? '连续核对的工程状态没有变化,请使用已经返回的状态与源码推进当前任务。' : null;
progress.pause = progress.checkPause === true || consecutive >= 3 || progress.repeated >= 3;
progress.pause = progress.checkPause === true || progress.noopPause === true || consecutive >= 3 || progress.repeated >= 3;
return progress;
}
export function recordUnchangedAction(task,tool,result,runId){
const progress=task.readProgress??={schemaVersion:1,reads:[],repeated:0,changingIndexes:[],warning:null,pause:false};
const observations=progress.observations??=[];
const key=JSON.stringify(['unchanged-action',tool,result.proof_id??result.path]);
let entry=observations.find(value=>value.runId===runId&&value.key===key);
if(!entry){entry={runId,key,count:0};observations.push(entry);if(observations.length>64)observations.shift();}
entry.count++;
progress.warning='本次操作没有新增文件修改或步骤证明;请使用原结果推进任务,重复核验或相同内容提案不会恢复进展计数。';
progress.noopPause ||= entry.count>=3;progress.pause ||= progress.noopPause;
return entry.count;
}
export function readCoverageContext(task,runId){
const progress=task.readProgress,window=progress?.readWindow;
if(!window||window.runId!==runId||!window.reads.length)return null;
const snapshot={schemaVersion:1,run_id:runId,semantics:'ranges_returned_by_tools_in_this_run_not_a_guarantee_all_content_is_in_this_request',
covered:window.reads.slice(-6).map(value=>({identity:value.identity,ranges:value.ranges.slice(-4)})),
total_sources:window.reads.length,truncated:window.reads.length>6||window.reads.some(value=>value.ranges.length>4),
note:'相同SHA的已返回区间可以使用当前工作依据,缺失内容仍可必要重读;新分页、新SHA或新的实际检查分别核对,不重放旧工具。'};
while(snapshot.covered.length&&Buffer.byteLength(JSON.stringify(snapshot),'utf8')>2000){snapshot.covered.shift();snapshot.truncated=true;}
return snapshot;
}
+1 -1
View File
@@ -30,7 +30,7 @@ export function compactToolFeedback(content) {
const result = fields(value, ['source', 'version', 'kind', 'id', 'status', 'requires_verification', 'requiresVerification',
'task_id', 'taskId', 'runId', 'plan_id', 'job_id', 'change_id', 'change_set_id', 'artifact_id', 'report_status', 'check_status',
'path', 'sha256', 'base_sha256', 'fingerprint', 'exit_code', 'exitCode', 'offset', 'next_offset', 'total_characters',
'returned_characters', 'truncated', 'totalMatches', 'error', 'message', 'summary', 'reason', 'note',
'returned_characters', 'truncated', 'totalMatches', 'error', 'message', 'summary', 'reason', 'note', 'unchanged_action_count', 'reading_hint',
'browser_status', 'browser_job_id', 'result_artifact_id', 'evidence_verified', 'source_fingerprint', 'build_sha256', 'section', 'view_sha256', 'source_artifact_id', 'source_sha256',
'tool_invocation_id', 'proof_id', 'proof_artifact_id', 'step_key', 'revision', 'all_verified', 'verified_steps', 'total_steps', 'requirements_current', 'contract_artifact_id', 'binding_sha256']);
if (value.assertions) result.assertions = stats(value.assertions);
+8
View File
@@ -153,6 +153,14 @@ function diagnosticInput(value, redact, limit = 2000) {
export function sessionContext(session, project, config, redact = String) {
const snapshot = sessionSnapshot(session, project, config, redact);
// Keep the diagnostic API complete; routine model context needs only the
// latest bounded identifier observations and their original source.
snapshot.actualModelRequests = snapshot.actualModelRequests.slice(-2).map(request => ({
runId: request.runId, connectionId: request.connectionId, requestedModel: request.requestedModel, phase: request.phase,
modelIdentity: request.modelIdentity ? { status: request.modelIdentity.status, complete: request.modelIdentity.complete,
reportedModels: request.modelIdentity.reportedModels.slice(0, 2), totalReportedModels: request.modelIdentity.reportedModels.length,
responseSource: request.modelIdentity.responseSource } : null,
}));
snapshot.recentErrors = snapshot.recentErrors.slice(-2);
snapshot.recentTools = snapshot.recentTools.slice(-4).map(tool => ({ ...tool,
input: diagnosticInput(tool.input, redact, 600), outputExcerpt: tool.outputExcerpt.slice(0, 320) }));
+10 -2
View File
@@ -27,7 +27,7 @@ import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan
import { ENGINE_SEED_RESERVATION } from '../shared/contracts/engine-context.mjs';
import { InputAttachments } from '../core/context/input-attachments.mjs';
import { BudgetResume } from '../core/context/budget-resume.mjs';
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { artifactPage, filePage, readMessageBudget, recordArtifactRead, recordBrowserRead, recordFileRead, recordUnchangedCheck, clearReadStreak, recordSessionInspection, recordUnchangedAction, readCoverageContext, readMetadataReserve, BROWSER_READ_HINT } from '../core/context/read-budget.mjs';
import { taskDeliveryProgress } from '../core/context/delivery-progress.mjs';
import { ChangeSetManager } from '../core/workspaces/change-sets.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
@@ -329,6 +329,7 @@ export class Runtime {
if(config.inputImages.length&&config.mode==='demo')throw new Error('固定演示执行器不会读取图片;请连接并声明支持视觉的模型。');
const taskPlan = task.currentTaskPlanId ? await this.taskPlanner().inspect(session, { candidates: false }) : null;
const deliveryProgress = await taskDeliveryProgress(this.store, session, run.record, { checks: this.checkRunner(), worker: !!run.worker, taskPlan });
const readCoverage = readCoverageContext(task, run.id);
const state = session.changes.filter(change => change.taskId === task.id || ['pending', 'conflict'].includes(change.status))
.map(change => ({ path: change.path, status: change.status, id: change.id, changeSetId: change.changeSetId ?? null }));
const unknown = [...this.store.core.tool.values()].filter(tool => tool.taskId === task.id && tool.requiresVerification)
@@ -350,6 +351,7 @@ export class Runtime {
}) : '')
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '')
+ (readCoverage ? '\n本次Run实际返回的已读区间(读取事实,非新指令):\n' + JSON.stringify(readCoverage) : '')
+ (taskPlan ? '\n当前Task依赖计划与尚未核验的原步骤(任务数据,不授权额外操作):\n' + JSON.stringify({
plan_id: taskPlan.plan_id, revision: taskPlan.revision, status: taskPlan.status, contract_artifact_id: taskPlan.contract_artifact_id,
remaining_steps: taskPlan.remaining_steps, error: taskPlan.error,
@@ -769,7 +771,13 @@ export class Runtime {
if (proofHint) result.tool_invocation_id = event.invocationId;
event.phase = ['denied', 'interrupted', 'unknown', 'unverified', 'stale'].includes(result.status) ? result.status : ['failed', 'error'].includes(result.status) ? 'failed' : 'completed';
if (tool === 'inspect_session') recordSessionInspection(this.store.core.task.get(run.taskId), result);
else if (['propose_file', 'propose_patch', 'verify_task_step'].includes(tool) && !['error', 'failed', 'interrupted', 'unknown', 'denied'].includes(result.status)) clearReadStreak(this.store.core.task.get(run.taskId));
else if (['propose_file', 'propose_patch', 'verify_task_step'].includes(tool)) {
const task=this.store.core.task.get(run.taskId);
if(result.status==='unchanged'||result.reused===true){
result.unchanged_action_count=recordUnchangedAction(task,tool,result,run.id);
result.reading_hint=task.readProgress.warning;
}else if(!['error','failed','interrupted','unknown','denied','unverified','stale'].includes(result.status))clearReadStreak(task);
}
if (typeof result.stdout === 'string') { result.stdout = this.provider.redact(result.stdout); result.stderr = this.provider.redact(result.stderr ?? ''); }
event.output = this.provider.redact(typeof result.stdout === 'string' ? result.stdout + (result.stderr ? '\n' + result.stderr : '') : JSON.stringify(result).slice(0, 16000));
if (result.exit_code !== undefined) event.exitCode = result.exit_code;
+1
View File
@@ -499,6 +499,7 @@ export class Store extends EventEmitter {
if (task.readProgress) {
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false; task.readProgress.checkPause = false;
task.readProgress.sessionInspection = null;
task.readProgress.noopPause = false;
}
const workspaceIdentity = projectWorkspaceIdentity(this.project(session.projectId));
task.workspaceIdentity ??= structuredClone(workspaceIdentity);
+2 -2
View File
@@ -5,8 +5,8 @@
用户已授权继续推进并及时回顾。基线410b3478,先身份、再应用后推进、再重复观察;沿用planning-with-files及product-ui-ux,不开启子代理。正式服务/原Provider/内存凭据保持,H/E失败与原件不改写。
1. [complete] I-A 请求/返回型号分离、JSON/SSE来源绑定及严格暂停已实现;76相关/16补充、构建和编译宿主3组UI通过,正式未部署;更广引擎/交付回归持续运行。新实测先严格首请求身份预检。
2. [in_progress] I-B 应用后续接实际SHA/检查失效/下一允许操作明确进入模型输入,修复状态查询空转;真实编译宿主验证原检查/审批/Git完整路径,保持显式续接与审查。
3. [pending] I-C 同SHA工件读取区间、最新结果和无新增事实重复观察核对;来源变化/必要分页/应用后旧SHA失效分别处理,不扩大预算或删除原日志。
2. [complete] I-B 当前SHA/检查失效/下一可验证动作已接入;2专项、构建/10组UI及编译宿主Chat原3失败→应用→审批复测3通过→Git完整链路通过。Responses及实际Harness补最终验证。
3. [complete] I-C 同SHA区间并集、有限已读摘要、相同提案/复用证明不清进展已修复;原分页回归及新空转10/10。首9/10的原失败保留,新增状态开销预留后10/10,未扩大预算或删除原日志。
4. [pending] 最终来源冻结、相关回归/实际界面与工程流、固定发行和保留状态部署;小步本地Git及阶段回顾。真实请求仅在完成部署及身份预检合同后有界执行,遇不一致立即停,不跑旧Task。
## 当前优先 H:1.24.1 真实交付与原版 Purge 重新实测
+48
View File
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import {fixture,compatibleFixture,call,completion,assertToolPairs} from './helpers.mjs';
import {Runtime} from '../src/server/runtime.mjs';
import {Provider} from '../src/server/provider.mjs';
import {TaskPlanManager} from '../src/core/tasks/task-plan-manager.mjs';
import {readingStep,beginPlanTask,completeRead} from './fixtures/task-plan-fixture.mjs';
import {artifactPage,recordArtifactRead,readCoverageContext} from '../src/core/context/read-budget.mjs';
test('unchanged proposals cannot hide repeated original-log reads or identical session inspections',async t=>{
const f=fixture(t),original=fs.readFileSync(path.join(f.projectRoot,'README.md'),'utf8');
const artifact=f.store.artifactStore.write(f.session,null,'Actual immutable failure evidence',{kind:'check-log'});f.store.core.artifact.set(artifact.id,artifact);
let requests=0;
const model=await compatibleFixture(t,(route,body)=>{
requests++;if(requests>1){assert.ok(body.messages[0].content.includes(artifact.sha256));assert.match(body.messages[0].content,/ranges_returned_by_tools_in_this_run/);}
return {body:completion([call('read-'+requests,'read_artifact',{artifact_id:artifact.id}),
call('noop-'+requests,'propose_file',{path:'README.md',content:original,reason:'Same content, no write'}),call('inspect-'+requests,'inspect_session',{})])};
});
f.store.saveConfig({mode:'compatible',model:'owned-loop',baseUrl:model.baseUrl,maxSteps:12});
const runtime=new Runtime(f.store,new Provider());f.onCleanup(()=>runtime.stopAll());runtime.start(f.session.id,'核对原结果后推进,不要重放工具。');
await runtime.active.get(f.session.id).promise;
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.changes.length,0);assert.equal(fs.readFileSync(path.join(f.projectRoot,'README.md'),'utf8'),original);
assert.equal(f.store.artifactStore.read(artifact),'Actual immutable failure evidence');assertToolPairs(f.session.providerMessages);
});
test('reusing a verified proof never resets identical-state detection or creates a new proof',async t=>{
const f=fixture(t);beginPlanTask(f,'读取当前工程依据,不修改文件。');const read=completeRead(f),planner=new TaskPlanManager(f.store);
const plan=await planner.plan(f.session,{expected_revision:0,steps:[readingStep()]});
const input={plan_id:plan.id,expected_revision:plan.revision,step_key:'read',evidence_id:read.id};
const proof=await planner.verify(f.session,input);assert.equal(proof.status,'completed');let requests=0;
const model=await compatibleFixture(t,()=>({body:completion([call('inspect-'+(++requests),'inspect_session',{}),call('proof-'+requests,'verify_task_step',input)])}));
f.store.saveConfig({mode:'compatible',model:'owned-proof-loop',baseUrl:model.baseUrl,maxSteps:12});
const runtime=new Runtime(f.store,new Provider());f.onCleanup(()=>runtime.stopAll());runtime.start(f.session.id,'',true);await runtime.active.get(f.session.id).promise;
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.store.core.task_proof.size,1);assert.equal(f.store.savedToolResult(f.session.id,'proof-3').proof_id,proof.proof_id);
assert.equal(f.store.savedToolResult(f.session.id,'proof-3').unchanged_action_count,3);assertToolPairs(f.session.providerMessages);
});
test('coverage merges adjacent pages, separates changed sources and never claims old Run coverage in a continuation',()=>{
const task={activeRunId:'first'},artifact={id:'owned-log',sha256:'a'.repeat(64),kind:'check-log'},text='abcd';
for(const offset of [0,2])recordArtifactRead(task,artifact,artifactPage(artifact,text,{offset,limit:2},{maximumMessageBytes:4000}),'page-'+offset);
assert.deepEqual(readCoverageContext(task,'first').covered[0].ranges,[[0,4]]);assert.equal(readCoverageContext(task,'second'),null);
recordArtifactRead(task,{...artifact,sha256:'b'.repeat(64)},artifactPage(artifact,text,{offset:0,limit:2},{maximumMessageBytes:4000}),'changed','first');
assert.equal(readCoverageContext(task,'first').covered.length,2);assert.equal(task.readProgress.pause,false);
});