fix(runtime): preserve model capacity history and cache evidence with resumable file proposals
This commit is contained in:
+22
-5
@@ -9,9 +9,11 @@ import { spawn, execFile } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { sanitizeModelText } from '../core/models/upstream-error.mjs';
|
||||
import { OUTPUT_TRUNCATED_HINT } from '../core/models/protocols.mjs';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { setImmediate as yieldExecution } from 'node:timers/promises';
|
||||
import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch } from './files.mjs';
|
||||
import { proposeFileChunk, discardFileDraft, pendingFileDrafts } from '../core/workspaces/file-proposal-drafts.mjs';
|
||||
import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions, browserToolDefinitions } from './provider.mjs';
|
||||
import { now, repairToolPairs } from './store.mjs';
|
||||
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
|
||||
@@ -82,6 +84,8 @@ labels.plan_task = '保存任务依赖计划';
|
||||
labels.verify_task_step = '核验任务步骤原证据';
|
||||
labels.inspect_task_plan = '核对任务计划与未完成项';
|
||||
labels.verify_existing_files = '核对当前已有成果';
|
||||
labels.propose_file_chunk = '组装长文件提案';
|
||||
labels.discard_file_draft = '放弃未完成文件草稿';
|
||||
labels.read_registered_skill = '读取已登记技能修订';
|
||||
labels.call_registered_mcp = '请求调用已登记MCP工具';
|
||||
|
||||
@@ -122,6 +126,7 @@ export function validateToolArgs(tool, args) {
|
||||
|| new Set(args.change_ids).size !== args.change_ids.length) throw new Error('变更集需要1到32个不同的提案ID。');
|
||||
return;
|
||||
}
|
||||
if (['propose_file_chunk', 'discard_file_draft'].includes(tool)) return; // The draft contract validates its full input before changing state.
|
||||
const required = ['diagnose_environment','plan_environment','inspect_session', 'inspect_project', 'index_project', 'plan_checks', 'plan_delivery', 'delivery_report'].includes(tool) ? [] : tool === 'read_artifact' ? ['artifact_id'] : tool === 'prepare_environment' ? ['plan_id','fingerprint'] : tool === 'run_checks' ? ['plan_id'] : tool === 'list_files' || tool === 'read_file' ? ['path'] : ['search_files', 'query_code'].includes(tool) ? ['query']
|
||||
: tool === 'propose_patch' ? ['path', 'base_sha256', 'reason'] : tool === 'propose_file' ? ['path', 'content', 'reason'] : ['command', 'reason'];
|
||||
for (const field of required) if (typeof args[field] !== 'string') throw new Error('工具参数 ' + field + ' 必须是文本。');
|
||||
@@ -148,6 +153,7 @@ export class Runtime {
|
||||
projectIndexer() { return this.codeIndex ??= new ProjectIndex({ cacheDirectory: path.join(this.store.directory, 'cache', 'project-index') }); }
|
||||
fileResults() { return this.results ??= new FileResults(this.store); }
|
||||
async fileDelivery(session) {
|
||||
if (pendingFileDrafts(session).length) return { satisfied: false, stopReason: 'file_draft_incomplete', message: '仍有未完成的分段文件草稿;请继续组装完整提案或显式放弃,片段不能视为交付。' };
|
||||
const task = this.store.owned('task', session.taskId, session.id), delivery = this.fileResults().completion(session);
|
||||
if (!delivery.satisfied) return { ...delivery, stopReason: 'delivery_incomplete', message: delivery.requiresChange
|
||||
? '当前要求包含修改,尚无对应追加要求之后的实际文件改动。已有成果核对不能代替修改。'
|
||||
@@ -354,16 +360,21 @@ export class Runtime {
|
||||
// Keep the complete goal once in this request view. The stored contract
|
||||
// still contains its original goal for intent and evidence verification.
|
||||
const { goal, ...contract } = taskContract(task);
|
||||
const context = this.provider.redact(projectContext(run.project) + (run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({
|
||||
const stablePrefix = config.historyPolicy === 'preserve';
|
||||
const fixedRules = projectContext(run.project, { inventory: false });
|
||||
const workerContract = run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({
|
||||
parent_task_id: run.worker.parentTaskId, worker_id: run.worker.id, write_paths: run.worker.paths, budget: run.worker.budget,
|
||||
rule: '只有范围内提案、审查应用和当前工程检查构成完成;不得请求任意终端、独立Git提交、外部工具或嵌套协作。',
|
||||
}) : '') + '\n当前项目/会话/任务身份:' + JSON.stringify({
|
||||
}) : '';
|
||||
const fixedContext = fixedRules + workerContract;
|
||||
const context = this.provider.redact((stablePrefix ? projectContext(run.project).slice(fixedRules.length) : projectContext(run.project) + workerContract) + '\n当前项目/会话/任务身份:' + JSON.stringify({
|
||||
project_id: run.project.id, session_id: session.id, task_id: task.id, workspace: projectWorkspaceIdentity(run.project) }) + '\n当前Task文件提案状态:' + JSON.stringify(state)
|
||||
+ '\n当前任务目标与全部追加要求(用户任务数据,完整保留):\n' + JSON.stringify({
|
||||
goal, instructions: task.instructions.filter(instruction => instruction.source !== 'review-action'), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract,
|
||||
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question
|
||||
+ '\n所属原执行与失败(核对失败时保持未知,不根据其它项目补造原因):' + JSON.stringify(inspectDiagnosticContext(this.store, session, run.record)) : '')
|
||||
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
+ (pendingFileDrafts(session).length ? '\n当前未完成分段草稿(未创建可应用提案):' + JSON.stringify(pendingFileDrafts(session).map(row => ({ draft_id: row.id, path: row.path, next_offset: row.characters, draft_sha256: row.sha256 }))) : '')
|
||||
+ (deliveryProgress ? '\n当前工程执行依据(每次请求重新核对,非操作授权):\n' + JSON.stringify(deliveryProgress) : '')
|
||||
+ (requirementReview ? '\n用户逐项要求复核(任务数据,不授权额外操作;证据和用户确认分别记录):\n' + JSON.stringify({
|
||||
revision: requirementReview.revision, status: requirementReview.status, unreviewed_sources: requirementReview.unreviewed_sources,
|
||||
@@ -392,7 +403,7 @@ export class Runtime {
|
||||
const tools = availableTools.filter(tool => (!run.worker || WORKER_TOOLS.has(tool.function.name)) && taskToolAllowed(task, run.record, tool.function.name));
|
||||
const projectMemory = await this.memoryManager().context(session, { redact: value => this.provider.redact(value) });
|
||||
signal.throwIfAborted();
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: context, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
const planned = this.requestPlanner().prepare(session, run.record, config, { system: stablePrefix ? this.provider.redact(fixedContext) : context, contextTail: stablePrefix ? context : null, tools, stepId: stepRecord.id, projectMemory, skillCatalog, mcpCatalog,
|
||||
transportReservationTokens:run.worker?.engine?ENGINE_SEED_RESERVATION:0,engineStepOnly:!!run.worker?.engine });
|
||||
if (planned.record.archivedGroups && !projectionLogged) {
|
||||
projectionLogged = true; session.compactions++;
|
||||
@@ -486,7 +497,7 @@ export class Runtime {
|
||||
run.record.outputTruncationRecoveries = (run.record.outputTruncationRecoveries ?? 0) + 1;
|
||||
if (run.record.outputTruncationRecoveries <= OUTPUT_TRUNCATION_RECOVERY_LIMIT) {
|
||||
this.store.finishStep(session, stepRecord);
|
||||
const note = '上一次响应在达到单次输出上限前被截断(finish_reason=length),其中的工具调用整体未执行(即使某个工具参数已完整也未应用,避免落地被截断的半成品)。请把这次改动拆小:每次响应只提交一个文件的 propose_file/propose_patch,或分多轮 prepare_change_set,不要在一个响应里堆叠多个大参数工具。原目标和已读依据都保留。';
|
||||
const note = OUTPUT_TRUNCATED_HINT;
|
||||
// The truncated assistant turn was never appended, so the conversation
|
||||
// stays valid. Feed the instruction to the model as a standalone turn
|
||||
// in the provider history, and mirror it to the visible chat log.
|
||||
@@ -533,6 +544,10 @@ export class Runtime {
|
||||
this.store.finishStep(session, stepRecord);
|
||||
session.status = session.changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review' : 'completed';
|
||||
if (run.record.purpose === 'diagnostic') { session.status = 'completed'; run.stopReason = 'diagnostic_answered'; }
|
||||
else if (pendingFileDrafts(session).length) {
|
||||
session.status = 'paused'; run.stopReason = 'file_draft_incomplete';
|
||||
this.store.message(session, 'system', '仍有未完成的分段文件草稿,片段不能作为完整交付;原片段和续接位置已保存。');
|
||||
}
|
||||
else if (session.status === 'completed' && taskContract(task).kind === 'file') {
|
||||
const delivery = await this.fileDelivery(session);
|
||||
if (!delivery.satisfied) {
|
||||
@@ -851,13 +866,15 @@ export class Runtime {
|
||||
}
|
||||
else if (tool === 'search_files') result = searchFiles(run.project, args);
|
||||
else if (tool === 'propose_file') result = proposeFile(this.store, session, args);
|
||||
else if (tool === 'propose_file_chunk') result = proposeFileChunk(this.store, session, args);
|
||||
else if (tool === 'discard_file_draft') result = discardFileDraft(this.store, session, args);
|
||||
else if (tool === 'propose_patch') result = proposePatch(this.store, session, args);
|
||||
else if (tool === 'run_command') result = await this.requestCommand(session, event, args, run);
|
||||
else throw new Error('当前能力表没有工具:' + tool);
|
||||
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)) {
|
||||
else if (['propose_file', 'propose_patch', 'propose_file_chunk', 'discard_file_draft', '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);
|
||||
|
||||
Reference in New Issue
Block a user