fix: preserve task intent across diagnostics and review continuation
This commit is contained in:
@@ -7,6 +7,7 @@ import { assertChangeSetsResolved, assertProposalUnsealed } from '../shared/cont
|
||||
import { assertWorkspacePath, assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { assertMcpResolved } from '../core/tools/mcp-contract.mjs';
|
||||
import { assertWorkersResolved, assertWorkerWriteScope } from '../shared/contracts/workers.mjs';
|
||||
import { settleAppliedTask } from '../shared/contracts/task-control.mjs';
|
||||
|
||||
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const ignored = new Set(['node_modules', '.git', '.next', '.data', 'bin', 'obj', 'dist', 'dist-client', 'dist-server', '__pycache__', '.venv', 'venv', '.tox', '.pytest_cache', '.mypy_cache', '.ruff_cache', 'htmlcov']);
|
||||
@@ -223,7 +224,7 @@ export function applyChange(store, session, id) {
|
||||
} finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
|
||||
change.status = 'applied'; change.appliedAt = now();
|
||||
store.invalidateChecks(project.id);
|
||||
if (session.status === 'needs_review' && !session.changes.some(item => ['pending', 'conflict'].includes(item.status))) session.status = 'completed';
|
||||
if (session.status === 'needs_review') settleAppliedTask(store, session);
|
||||
store.event(session, { kind: 'change', label: '已应用 ' + change.path, phase: 'completed', output: exists ? '写入前基线检查通过,原文已备份。' : '写入前基线检查通过,已创建新文件。' });
|
||||
return change;
|
||||
}
|
||||
|
||||
+21
-7
@@ -8,6 +8,7 @@ import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDef
|
||||
import { now, repairToolPairs } from './store.mjs';
|
||||
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
|
||||
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
|
||||
import { taskToolAllowed, taskContract } from '../shared/contracts/task-control.mjs';
|
||||
import { CheckRunner } from '../core/check-runner.mjs';
|
||||
import { inspectProject } from '../core/project-inspector.mjs';
|
||||
import { projectEnvironment } from '../core/process-environment.mjs';
|
||||
@@ -208,7 +209,9 @@ export class Runtime {
|
||||
const deadline = record.budget.maxDurationMs > 0 ? setTimeout(() => controller.abort(new BudgetExceeded('time_limit', '已到达本次运行的时间预算,执行记录已保存。')), record.budget.maxDurationMs) : null;
|
||||
run.promise = this.run(session, config, run).finally(() => {
|
||||
clearTimeout(deadline); this.active.delete(id);
|
||||
this.store.finishRun(session, record, run.stopReason ?? null);
|
||||
const status = session.status;
|
||||
if (record.purpose === 'diagnostic') session.status = record.taskStatusBefore;
|
||||
this.store.finishRun(session, record, run.stopReason ?? null, { status });
|
||||
});
|
||||
run.promise.catch(() => {});
|
||||
return session;
|
||||
@@ -228,8 +231,10 @@ export class Runtime {
|
||||
if (!task || run?.taskId !== task.id || !stoppedForReview || pendingDeliveryReview(this.store, session) || session.changes.some(change => ['pending', 'conflict'].includes(change.status))
|
||||
|| [...this.store.core.tool.values()].some(tool => tool.taskId === task.id && tool.requiresVerification)
|
||||
|| !session.changes.some(change => change.status === 'applied' && (!change.taskId || change.taskId === task.id))) throw Object.assign(new Error('当前没有已审查并应用、需要继续交付的任务改动。'), { status: 409 });
|
||||
const content = '本任务的改动已经审查并应用。请继续原始目标,识别并实际执行工程检查,依据失败日志修复,完成审查和交付说明。';
|
||||
return this.start(id, content, true, { instructionSource: 'review-action' });
|
||||
if (taskContract(task).checks === 'skip' && task.delivery?.status === 'files_applied') throw Object.assign(new Error('文件已按原要求应用完成,无需自动检查;如需追加工作,请明确发送新的要求。'), { status: 409 });
|
||||
const result = this.start(id, '', true, { instructionSource: 'review-action' });
|
||||
this.store.message(session, 'system', '审查操作:改动已应用,继续核对原目标。原有范围与限制保留,此操作没有追加测试要求。');
|
||||
return result;
|
||||
}
|
||||
async run(session, config, run) {
|
||||
const signal = run.controller.signal;
|
||||
@@ -257,8 +262,9 @@ export class Runtime {
|
||||
}) : '') + '\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: task.goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [],
|
||||
}) + '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
goal: taskContract(task).goal, instructions: task.instructions, constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], contract: taskContract(task),
|
||||
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question : '')
|
||||
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
|
||||
+ '\n' + sessionContext(session, run.project, config, value => this.provider.redact(value))
|
||||
+ (task.readProgress?.warning ? '\n当前读取进展:' + task.readProgress.warning : '')
|
||||
+ (taskPlan ? '\n当前Task依赖计划与尚未核验的原步骤(任务数据,不授权额外操作):\n' + JSON.stringify({
|
||||
@@ -273,7 +279,7 @@ export class Runtime {
|
||||
...([...this.store.core.research_target.values()].some(target => target.sessionId === session.id && target.taskId === run.taskId) ? researchToolDefinitions : []),
|
||||
...([...this.store.core.engine_job.values()].some(job => job.sessionId === session.id && job.taskId === run.taskId) ? engineToolDefinitions : []),
|
||||
...(this.browserManager().builds(run.project).length || [...this.store.core.browser_plan.values()].some(plan => plan.sessionId === session.id && plan.taskId === run.taskId) ? browserToolDefinitions : [])];
|
||||
const tools = run.worker ? availableTools.filter(tool => WORKER_TOOLS.has(tool.function.name)) : availableTools;
|
||||
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 });
|
||||
@@ -354,6 +360,12 @@ export class Runtime {
|
||||
if (!calls.length) {
|
||||
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 (session.status === 'completed' && taskContract(task).checks !== 'skip' && (['failed', 'stale', 'unknown', 'unverified', 'running'].includes(task.verification?.status)
|
||||
|| taskContract(task).checks === 'required' && task.verification?.status !== 'passed')) {
|
||||
session.status = 'paused'; run.stopReason = 'verification_incomplete';
|
||||
this.store.message(session, 'system', '答复已收到,但当前任务的工程检查尚未通过,不能视为交付完成。原目标与检查结果已保留。');
|
||||
}
|
||||
if (externalEngine) await this.engineRunner().finish(session, run);
|
||||
if (session.status === 'completed' && run.worker) {
|
||||
try { await this.workerManager().output(session, run.worker); signal.throwIfAborted(); }
|
||||
@@ -363,7 +375,7 @@ export class Runtime {
|
||||
this.store.message(session, 'system', '子任务还不能交付:' + this.provider.redact(error.message ?? String(error)) + '。原目标和结果已保存。');
|
||||
}
|
||||
}
|
||||
if (session.status === 'completed' && task.currentTaskPlanId) {
|
||||
if (session.status === 'completed' && task.currentTaskPlanId && run.record.purpose !== 'diagnostic') {
|
||||
const finalPlan = await this.taskPlanner().inspect(session, { candidates: false });
|
||||
if (!finalPlan.all_verified) {
|
||||
session.status = 'paused'; run.stopReason = 'task_plan_incomplete';
|
||||
@@ -456,6 +468,8 @@ export class Runtime {
|
||||
try {
|
||||
const args = JSON.parse(call.function.arguments);
|
||||
validateToolArgs(tool, args);
|
||||
if (!taskToolAllowed(this.store.core.task.get(run.taskId), run.record, tool, args)) throw new Error(run.record.purpose === 'diagnostic'
|
||||
? '本次是只读运行诊断,不执行文件修改、命令或其他副作用操作。原任务目标保持。' : '原任务明确无需测试;这项自动检查没有执行。请直接完成原目标,追加测试需要用户明确要求。');
|
||||
assertWorkerTool(this.store, session, tool, args);
|
||||
if (run.worker?.engine) this.engineRunner().assertCurrent(session, run);
|
||||
event.input = JSON.parse(this.provider.redact(JSON.stringify(args)));
|
||||
|
||||
+18
-6
@@ -7,6 +7,7 @@ import { StateDatabase, runtimeOwnerAlive } from '../core/storage/state-database
|
||||
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
|
||||
import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs';
|
||||
import { ACTIVE_STATES, CORE_KINDS, createTask, createRun, ownedRecord, emptyUsage, accumulateUsage, accountedTokens, isId } from '../shared/contracts/execution.mjs';
|
||||
import { isContinuation, isDiagnosticQuestion, taskContract, updateTaskContract } from '../shared/contracts/task-control.mjs';
|
||||
import { WORKSPACE_ACTIVE, projectWorkspaceIdentity, assertWorkspacePath } from '../shared/contracts/workspaces.mjs';
|
||||
import { RESEARCH_ACTIVE } from '../shared/contracts/research.mjs';
|
||||
import { ENGINE_ACTIVE, publicEngineJob } from '../shared/contracts/engines.mjs';
|
||||
@@ -362,7 +363,7 @@ export class Store extends EventEmitter {
|
||||
session.revision = (session.revision ?? 0) + 1;
|
||||
session.updatedAt = now();
|
||||
const task = this.core.task.get(session.taskId), run = this.core.run.get(session.runId);
|
||||
if (task) { task.status = session.status; task.updatedAt = session.updatedAt; }
|
||||
if (task) { if (run?.purpose !== 'diagnostic') task.status = session.status; task.updatedAt = session.updatedAt; }
|
||||
if (run && !run.finishedAt) run.status = session.status;
|
||||
let committed;
|
||||
try { committed = this.storage.save(session, this.recordsFor(session), type, { status: session.status, ...detail }); }
|
||||
@@ -465,11 +466,18 @@ export class Store extends EventEmitter {
|
||||
});
|
||||
if (inputs.length>1 || inputs.length && !forceNewTask && task?.attachmentIds?.length && (resume || !['completed','idle'].includes(task.status))) throw new Error('当前任务已有截图,请新建任务再添加。');
|
||||
const previousRunId = session.runId ?? null;
|
||||
if (forceNewTask || !task || !resume && ['completed', 'idle'].includes(task.status)) {
|
||||
if (task) task.contract ??= taskContract(task, id => this.core.task.get(id));
|
||||
const purpose = !forceNewTask && task && !resume && isDiagnosticQuestion(content) ? 'diagnostic' : 'execution';
|
||||
const continuing = task && isContinuation(content);
|
||||
if (forceNewTask || !task || !resume && !continuing && purpose !== 'diagnostic' && ['completed', 'idle'].includes(task.status)) {
|
||||
const previous = task?.id ?? null;
|
||||
const goal = content || session.messages.find(message => message.role === 'user')?.content || session.title;
|
||||
task = createTask(session, goal, config, previous); this.core.task.set(task.id, task);
|
||||
} else if (content && (!resume || instructionSource)) task.instructions.push({ id: randomUUID(), content, createdAt: now(), ...(instructionSource ? { source: instructionSource } : {}) });
|
||||
} else if (content && purpose !== 'diagnostic' && (!resume || instructionSource)) {
|
||||
task.instructions.push({ id: randomUUID(), content, createdAt: now(), source: instructionSource ?? 'user' });
|
||||
updateTaskContract(task, content);
|
||||
}
|
||||
task.contract ??= taskContract(task, id => this.core.task.get(id));
|
||||
if (task.readProgress) {
|
||||
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
|
||||
task.readProgress.sessionInspection = null;
|
||||
@@ -477,7 +485,10 @@ export class Store extends EventEmitter {
|
||||
const workspaceIdentity = projectWorkspaceIdentity(this.project(session.projectId));
|
||||
task.workspaceIdentity ??= structuredClone(workspaceIdentity);
|
||||
if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 });
|
||||
const run = createRun(session, task, config, resume ? previousRunId : null);
|
||||
const run = createRun(session, task, config, resume || continuing ? previousRunId : null);
|
||||
run.purpose = purpose;
|
||||
if (purpose === 'diagnostic') { run.question = String(content); run.taskStatusBefore = task.status; }
|
||||
if (instructionSource) run.source = instructionSource;
|
||||
if(resumePlan){task.budget.maxTokens=config.maxTaskTokens;run.resumePlanId=resumePlan.id;resumePlan.status='consumed';resumePlan.newRunId=run.id;}
|
||||
run.workspaceIdentity = structuredClone(workspaceIdentity);
|
||||
this.core.run.set(run.id, run); task.activeRunId = run.id;
|
||||
@@ -515,8 +526,8 @@ export class Store extends EventEmitter {
|
||||
session.usage = usage;
|
||||
}
|
||||
|
||||
finishRun(session, run, stopReason = null) {
|
||||
run.status = session.status; run.finishedAt = now(); run.stopReason = stopReason;
|
||||
finishRun(session, run, stopReason = null, { status = session.status } = {}) {
|
||||
run.status = status; run.finishedAt = now(); run.stopReason = stopReason;
|
||||
const step = this.core.step.get(run.checkpoint.stepId);
|
||||
if (step && ['running', 'waiting'].includes(step.status)) { step.status = session.status === 'completed' || session.status === 'needs_review' ? 'completed' : 'interrupted'; step.finishedAt = now(); }
|
||||
this.save(session, { type: 'run.finished', detail: { stopReason } });
|
||||
@@ -630,6 +641,7 @@ export class Store extends EventEmitter {
|
||||
runs: [...this.core.run.values()].filter(value => value.sessionId === session.id).slice(-20).map(value => ({ id: value.id, taskId: value.taskId,
|
||||
status: value.status, startedAt: value.startedAt, finishedAt: value.finishedAt, steps: value.steps, toolCalls: value.toolCalls,
|
||||
usage: value.usage, stopReason: value.stopReason, model: value.model, budget: value.budget, resumeOf: value.resumeOf,
|
||||
...(value.purpose ? { purpose: value.purpose, source: value.source, taskStatusBefore: value.taskStatusBefore } : {}),
|
||||
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}), ...(value.review ? { review: value.review } : {}) })),
|
||||
progress: { totalTools: tools.length, completedTools: tools.filter(value => value.state === 'completed').length,
|
||||
requiresVerification: tools.filter(value => value.requiresVerification).map(value => ({ id: value.id, tool: value.tool, callId: value.callId, state: value.state })) },
|
||||
|
||||
Reference in New Issue
Block a user