feat(tasks): bind diagnostics to original failures and explain delivery gaps

This commit is contained in:
Agent Workbench Dev
2026-11-04 13:53:54 +08:00
parent d389b23c99
commit 929d12ba66
19 changed files with 441 additions and 21 deletions
+1 -3
View File
@@ -5,10 +5,8 @@ import { Modal } from './components';
import type { RequirementDraft, RequirementItem, RequirementView, Session, TaskPlanStep } from './types';
import { RequirementDraftEditor, RequirementScopeFields, requirementInput as clean, requirementRoles } from './RequirementDraftEditor';
import './RequirementPanel.css';
import { requirementStates as states } from '../shared/contracts/task-follow-up.mjs';
const states: Record<string, string> = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对',
evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行',
scope_unknown: '范围待澄清', reference_recorded: '参考已记录', boundary_recorded: '边界已记录' };
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
const scope = (kind: TaskPlanStep['kind']) => kind === 'analysis' ? { tools: ['read_file'] } : ['changes', 'results'].includes(kind)
? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] };
+42
View File
@@ -0,0 +1,42 @@
import { useEffect, useState } from 'react';
import { api } from './api';
import type { DeliveryStatus, Session } from './types';
export function TaskFollowUp({ session, openArtifact }: { session: Session; openArtifact: (id: string) => void }) {
const task = session.execution?.task, run = session.execution?.run;
const [value, setValue] = useState<DeliveryStatus | null>(null), [error, setError] = useState(''), [refresh, setRefresh] = useState(0), [loading, setLoading] = useState(false);
const identity = session.id + '/' + task?.id + '/' + run?.id;
const [loadedIdentity, setLoadedIdentity] = useState('');
const active = ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => {
let alive = true;
setError('');
if (!task || !run || active) { setLoading(false); return; }
const timer = setTimeout(() => {
setLoading(true); setError('');
api<DeliveryStatus>(`/sessions/${session.id}/delivery-status?taskId=${task.id}&runId=${run.id}`)
.then(result => { if (alive) { setValue(result); setLoadedIdentity(identity); } })
.catch(reason => { if (alive) { setError(reason instanceof Error ? reason.message : String(reason)); setValue(null); } })
.finally(() => { if (alive) setLoading(false); });
}, 160);
return () => { alive = false; clearTimeout(timer); };
}, [identity, session.revision, session.status, refresh]);
const current = loadedIdentity === identity ? value : null, diagnostic = current?.diagnostics.at(-1), context = diagnostic?.context;
return <section className="task-record-section task-follow-up" aria-label="当前缺口与下一步">
<div className="record-heading"><h3>当前缺口与下一步</h3><button className="text-button" disabled={active || loading} onClick={() => setRefresh(n => n + 1)}>{loading ? '正在核对' : '刷新当前结果'}</button></div>
{active ? <p className="record-footnote">等待所属运行、检查或审批结束,再核对当前结果。</p> : error ? <p role="alert" className="plan-problem">{error} 请刷新当前结果;原记录保留。</p> : current ? <>
<p><strong>{current.followUp.statusLabel}</strong></p>
<p className="follow-up-next">下一步:{current.followUp.nextStep}</p>
{!!current.followUp.gaps.length && <details><summary>待处理事项 · {current.followUp.gaps.length}</summary><ul>{current.followUp.gaps.map((gap, i) => <li key={gap.kind + gap.id + i}><strong>{gap.label}</strong><p>{gap.nextStep}</p></li>)}</ul></details>}
{diagnostic && context && <div className="diagnostic-origin" aria-label="诊断原执行">
<strong>最近只读诊断 · {diagnostic.status === 'completed' ? '答复已完成' : diagnostic.status === 'failed' ? '诊断失败' : '尚未完成'}</strong>
<p>{diagnostic.question}</p>
{diagnostic.failure && <p>本次诊断错误:{diagnostic.failure.message}</p>}
{context.evidenceVerified ? <><p>原执行:{context.originalRunId?.slice(0, 8) ?? '未记录'}</p><p>原错误:{context.failure?.value.message ?? '未记录具体错误;原因保持未知。'}</p>
{context.check && <p>原检查:{context.check.id.slice(0, 8)} · {context.check.status}</p>}</> : <p>{context.error ?? context.note}</p>}
{context.artifactId && <button className="text-button" onClick={() => openArtifact(context.artifactId!)}>查看诊断原绑定</button>}
</div>}
<p className="record-footnote">{current.followUp.note}</p>
</> : <p className="record-footnote">正在核对当前目标、要求和原结果。</p>}
</section>;
}
+9
View File
@@ -5,6 +5,15 @@
.record-heading > span:not(.status) { margin-left: auto; font-size: 11px; color: var(--muted); }
.record-heading > code { margin-left: auto; font-size: 11px; color: var(--muted); }
.task-goal { line-height: 1.85; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
.task-follow-up { font-size: 12px; line-height: 1.8; overflow-wrap: anywhere; }
.follow-up-next { margin: 10px 0; }
.task-follow-up summary { cursor: pointer; color: var(--teal); }
.task-follow-up ul { padding-left: 18px; }
.task-follow-up li { margin-top: 12px; }
.task-follow-up li p { margin-top: 3px; }
.diagnostic-origin { margin-top: 14px; padding-left: 10px; border-left: 2px solid #bd9654; }
.diagnostic-origin p { margin: 6px 0; white-space: pre-wrap; }
@media (max-width: 600px) { .task-follow-up .text-button { min-height: 44px; } }
.record-id { display: inline-block; font-size: 10px; color: var(--muted); margin-top: 9px; }
.task-instructions { margin-top: 14px; font-size: 11px; }
.task-instructions summary { cursor: pointer; color: var(--teal); }
+3
View File
@@ -17,6 +17,7 @@ import './TaskPanel.css';
import { EnvironmentPanel } from './EnvironmentPanel';
import { PreviewPanel } from './PreviewPanel';
import { FileResultsPanel } from './FileResultsPanel';
import { TaskFollowUp } from './TaskFollowUp';
const stopReasons: Record<string, string> = { model_identity: '模型返回型号需要核对', no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
@@ -100,6 +101,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
{!!task.instructions.length && <details className="task-instructions"><summary>追加要求 · {task.instructions.length}</summary>{task.instructions.map(instruction => <p key={instruction.id}><small>{instruction.source && instruction.source !== 'user' ? '系统操作 · ' + instruction.source : '用户要求'}</small><br />{instruction.content}</p>)}</details>}
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
</section>
{task && <TaskFollowUp session={session} openArtifact={openArtifact} />}
{task && <FileResultsPanel session={session} busy={busy} onSession={onSession} openArtifact={openArtifact} />}
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <RequirementPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
@@ -112,6 +114,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
{run ? <><div className="run-status"><Status value={run.status} /><code title={run.id}>{run.id.slice(0, 8)}</code></div>
{run.status === 'needs_review' && task.delivery?.status === 'files_applied' && <p className="record-footnote">这次运行在文件审查前结束;文件此后已应用,当前交付状态见上方任务目标。</p>}
{run.purpose === 'diagnostic' && <p className="record-footnote">本次为只读诊断,运行结束仅表示答复完成;原任务状态另行保留。</p>}
{run.purpose === 'diagnostic' && run.diagnosticContext && <p className="record-footnote">原执行 {run.diagnosticContext.originalRunId?.slice(0, 8) ?? '未记录'}<button className="text-button" onClick={() => openArtifact(run.diagnosticContext!.artifactId)}>查看原绑定</button></p>}
<dl className="record-fields"><ActualModelFields run={run} session={session} />{run.workspaceIdentity && <><dt>执行目录</dt><dd className="record-endpoint">{run.workspaceIdentity.root}</dd>{run.workspaceIdentity.branch && <><dt>独立分支</dt><dd className="record-endpoint">{run.workspaceIdentity.branch}</dd></>}</>}<dt>开始 / 结束</dt><dd>{time(run.startedAt)}<br />{time(run.finishedAt)}</dd><dt>模型轮次 / 工具</dt><dd>{run.steps} / {run.toolCalls}</dd><dt>已报告用量</dt><dd>{number(run.usage?.totalTokens)} tokens<br /><small>输入 {number(run.usage?.inputTokens)} · 输出 {number(run.usage?.outputTokens)}</small></dd>
{!!run.usage?.unknownRequests && <><dt>未报告用量</dt><dd>{run.usage.unknownRequests} 次请求 · 估算 {number(run.usage.estimatedUnknownTokens)} tokens</dd></>}
<dt>本次预算</dt><dd>{number(run.budget?.maxTokens)} tokens · {Math.round((run.budget?.maxDurationMs ?? 0) / 60000)} 分钟 · {run.budget?.maxSteps} 轮</dd><dt>任务累计</dt><dd>{number(execution?.accountedTaskTokens)} / {number(task.budget.maxTokens)} tokens</dd>
+12
View File
@@ -149,6 +149,18 @@ export interface TurnObservation {
}
export interface Run { progressShadow?: { mode: 'shadow'; observations: number; truncated: boolean; turns: TurnObservation[] }; progressShadowArtifactIds?: string[]; progressShadowError?: { kind: string; phase: string } }
export interface RunBrief { purpose?: 'execution' | 'diagnostic'; source?: string; taskStatusBefore?: string; consumption?: ModelConsumption[] }
export interface Run { question?: string; diagnosticContext?: { artifactId: string; sha256: string; originalRunId: string | null } }
export interface DiagnosticContext {
artifactId?: string; originalRunId?: string | null; evidenceVerified: boolean; historical?: boolean; note?: string; error?: string;
failure?: { id: string; eventId: string; runId: string; sha256: string; value: RuntimeFailure } | null;
check?: { id: string; runId: string; status: string } | null;
}
export interface DeliveryStatus {
requirementsRevision: number;
followUp: { taskId: string; runId: string; goal: string; taskStatus: string; status: string; statusLabel: string; nextStep: string; note: string;
gaps: { kind: string; id: string; label: string; nextStep: string }[] };
diagnostics: { runId: string; status: string; stopReason: string | null; question: string; failure?: RuntimeFailure | null; context: DiagnosticContext }[];
}
export interface TaskCheckpoint {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; createdAt: string;
status: string; artifactId: string; sha256: string; sourceFingerprint: string; requirementsSha256: string;
+47 -11
View File
@@ -14,9 +14,12 @@ import { inspectTurnProgress } from './context/turn-progress-recorder.mjs';
import { FileResults } from './tasks/file-results.mjs';
import { taskContract } from '../shared/contracts/task-control.mjs';
import { modelIdentityLabel } from '../shared/contracts/model-identity.mjs';
import { inspectDiagnosticContext } from './tasks/diagnostic-context.mjs';
import { deliveryFollowUp, requirementNextStep, requirementStates } from '../shared/contracts/task-follow-up.mjs';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
existing_verified: '当前成果已核对,无新增修改', needs_requirements: '用户要求仍有待复核事项', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
research_verified: '约定研究范围已核对,无新增修改', scope_verified: '约定范围已核对,按约定未测试',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
@@ -44,7 +47,7 @@ export function verifiedCheck(store, session, inspection) {
export class DeliveryReporter {
constructor(store, { redact = String } = {}) { this.store = store; this.redact = redact; }
async create(session, { job = null, inspection = null } = {}) {
async inspect(session, { job = null, inspection = null } = {}) {
const taskId = session.taskId, runId = session.runId;
const task = this.store.owned('task', taskId, session.id);
const run = this.store.owned('run', runId, session.id);
@@ -125,15 +128,22 @@ export class DeliveryReporter {
requiresVerification: !!value.requiresVerification, evidenceVerified, evidenceError, acknowledgedAt: value.acknowledgedAt ?? null };
});
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('核对页面结果期间任务已切换,请重新生成报告。'), { status: 409 });
const researchScope = !hasFileScope && !changes.some(change => change.status === 'applied') && requirements.configured && requirements.all_resolved
&& requirements.items.some(item => (item.role ?? 'requirement') === 'requirement' && ['evidence', 'user'].includes(item.method))
&& requirements.items.every(item => item.method === 'scope' || item.method === 'not_requested' || item.method === 'user' || item.kind === 'analysis')
&& (contract.checks === 'skip' || !['failed', 'stale', 'unknown', 'unverified'].includes(task.verification.status));
const needsChecks = !check && !(contract.checks !== 'required' && (researchScope || hasFileScope && fileDelivery.satisfied
&& (contract.checks === 'skip' || contract.checks === 'unspecified' && task.verification.status === 'not_configured')));
const status = requiresVerification.length || unresolved.length ? 'needs_verification'
: ['running', 'awaiting_approval', 'stopping'].includes(session.status) ? 'in_progress'
: deliveryReview || changes.some(change => ['pending', 'conflict'].includes(change.status)) ? 'needs_review'
: requirements.configured && !requirements.all_resolved ? 'needs_requirements'
: taskPlan.configured && !taskPlan.all_verified ? 'needs_plan_verification'
: hasFileScope && !fileDelivery.satisfied ? 'needs_results'
: !check && !(hasFileScope && fileDelivery.satisfied && (contract.checks === 'skip' || contract.checks === 'unspecified' && task.verification.status === 'not_configured')) ? 'needs_checks'
: needsChecks ? 'needs_checks'
: browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: hasFileScope && !fileDelivery.newChanges ? 'existing_verified' : hasFileScope && contract.checks === 'skip' ? 'files_delivered'
: researchScope && !check ? contract.checks === 'skip' ? 'scope_verified' : 'research_verified'
: hasFileScope && !fileDelivery.newChanges ? 'existing_verified' : hasFileScope && contract.checks === 'skip' ? 'files_delivered'
: commits.length ? 'verified_committed' : 'verified_uncommitted';
const report = {
schemaVersion: 1, kind: 'engineering-delivery', generatedAt: new Date().toISOString(), status, statusLabel: labels[status],
@@ -141,7 +151,11 @@ export class DeliveryReporter {
task: { id: task.id, goal: task.goal, status: task.status, instructions: task.instructions, acceptance: task.acceptance ?? [],
contract, delivery: task.delivery ?? null,
workspaceIdentity: task.workspaceIdentity ?? null, requirementsAcceptance: requirements.status, note: '源码和检查证据不代替业务需求验收。' },
requirements,
requirements, runId,
diagnostics: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId && value.purpose === 'diagnostic')
.map(value => ({ runId: value.id, status: value.status, stopReason: value.stopReason, question: value.question,
failure: session.events.findLast(event => event.runId === value.id && event.kind === 'error')?.diagnostic ?? null,
context: inspectDiagnosticContext(this.store, session, value) })),
turnObservations: [...this.store.core.run.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ runId: value.id, ...inspectTurnProgress(this.store, session, value) })),
fileResults, fileDelivery,
@@ -150,7 +164,7 @@ export class DeliveryReporter {
note: !fileDelivery.newChanges && hasFileScope ? '本任务无新增修改;未创建提交,已有用户修改保持原归属。' : '仅本任务实际应用的文件可进入Git交付预览。' },
source: { fingerprint: inspection.sourceFingerprint, scope: inspection.scope, gitHead: inspection.git.head, branch: inspection.git.branch },
runs: [...this.store.core.run.values()].filter(value => value.taskId === taskId).map(value => ({ id: value.id, resumeOf: value.resumeOf,
engine: value.engine, status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason,
engine: value.engine, purpose: value.purpose ?? 'execution', status: value.status, model: value.model, startedAt: value.startedAt, finishedAt: value.finishedAt, usage: value.usage, stopReason: value.stopReason,
consumption: structuredClone(value.consumption ?? []),
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })),
usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null },
@@ -176,14 +190,22 @@ export class DeliveryReporter {
requiresVerification,
limitations: ['本切片验证已选工程检查和提交范围;业务需求验收另行记录。', '提交为本地普通提交,不执行仓库hooks和GPG签名。', '请求输入为本地UTF-8估算;服务实际分词和用量另行记录。', '未配置模型单价,费用未知。'],
};
const safe = JSON.parse(this.redact(JSON.stringify(report)));
const markdown = renderDeliveryMarkdown(safe);
const jsonArtifact = this.store.artifactStore.write(session, run, safe, { kind: 'delivery-report' });
report.followUp = deliveryFollowUp(report);
return JSON.parse(this.redact(JSON.stringify(report)));
}
async create(session, options = {}) {
const taskId = session.taskId, runId = session.runId;
const report = await this.inspect(session, options);
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('生成报告期间任务已切换,请重新生成。'), { status: 409 });
const run = this.store.owned('run', runId, session.id), job = options.job;
const markdown = renderDeliveryMarkdown(report);
const jsonArtifact = this.store.artifactStore.write(session, run, report, { kind: 'delivery-report' });
const markdownArtifact = this.store.artifactStore.write(session, run, markdown, { kind: 'delivery-report-markdown', mediaType: 'text/markdown' });
this.store.core.artifact.set(jsonArtifact.id, jsonArtifact); this.store.core.artifact.set(markdownArtifact.id, markdownArtifact);
if (job) { job.reportArtifactId = jsonArtifact.id; job.reportMarkdownArtifactId = markdownArtifact.id; }
this.store.save(session, { type: 'delivery.report', detail: { status, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id } });
return { report: safe, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id };
this.store.save(session, { type: 'delivery.report', detail: { status: report.status, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id } });
return { report, artifactId: jsonArtifact.id, markdownArtifactId: markdownArtifact.id };
}
}
@@ -211,10 +233,24 @@ export function renderDeliveryMarkdown(report) {
'', '| 要求 / 条件 | 用户原文来源 | 修订 | 复核状态 | 原证据 / 下一步 |', '| --- | --- | --- | --- | --- |');
for (const item of report.requirements.items) lines.push('| ' + [item.title + ' / ' + item.criterion,
item.source.kind + ':' + item.source.id + ' [' + item.source.start + ',' + item.source.end + ') ' + item.source.quote,
item.revision, item.status, item.error ?? item.user_note ?? item.proof_artifact_id ?? (item.status === 'not_requested' ? '按约定未执行,非测试通过' : '选择实际证据或完成用户验收')].map(escapeCell).join(' | ') + ' |');
item.revision, requirementStates[item.status] ?? item.status, [item.error, item.user_note, item.proof_artifact_id, requirementNextStep(item)].filter(Boolean).join(' · ')].map(escapeCell).join(' | ') + ' |');
if (report.requirements.unreviewed_sources?.length) lines.push('', '尚未审阅的用户来源:' + report.requirements.unreviewed_sources.join('、'));
if (report.requirements.error) lines.push('', report.requirements.error);
}
if (report.followUp) {
lines.push('', '## 当前缺口与下一步', '', report.followUp.note, '', '原目标:' + report.followUp.goal, '', '下一步:' + report.followUp.nextStep);
for (const gap of report.followUp.gaps) lines.push('', '- ' + gap.label + ':' + gap.nextStep);
}
if (report.diagnostics?.length) {
lines.push('', '## 只读诊断与原执行', '', '诊断答复不核销原目标、原失败或未知操作。');
for (const diagnostic of report.diagnostics) {
const context = diagnostic.context;
lines.push('', '诊断Run:' + diagnostic.runId + ' · ' + diagnostic.status, '问题:' + diagnostic.question,
...(diagnostic.failure ? ['本次诊断错误:' + diagnostic.failure.message] : []),
context.evidenceVerified ? '原执行:' + (context.originalRunId ?? '未记录') + ' · 原失败:' + (context.failure?.value.message ?? '未记录具体错误;原因保持未知。')
: '原失败绑定未核对:' + (context.error ?? context.note), '原工件:' + (context.artifactId ?? '旧记录未封存'));
}
}
if (report.turnObservations?.some(row => row.recorded || row.error)) {
lines.push('', '## 单轮观察(仅记录)', '', '外显事实分类不改变停止、权限或预算;不是自主交付收益证明。');
for (const run of report.turnObservations) if (run.error) lines.push('', escapeCell(run.runId + ':' + (typeof run.error === 'string' ? run.error : '观察未能记录,原执行结果保留。')), '');
+45
View File
@@ -0,0 +1,45 @@
import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const owned = (value, session, taskId) => value?.sessionId === session.id && value.projectId === session.projectId && value.taskId === taskId;
// Preserve the execution being explained even if the diagnostic itself fails.
// These are original observations, not permission to repeat an operation.
export function bindDiagnosticContext(store, session, task, run) {
const runs = [...store.core.run.values()].filter(value => owned(value, session, task.id) && value.purpose !== 'diagnostic');
const error = session.events.findLast(event => event.taskId === task.id
&& runs.some(value => value.id === event.runId) && (event.kind === 'error' || event.kind === 'tool' && event.phase === 'failed'));
const value = error ? structuredClone(error.diagnostic ?? { source: error.kind, title: error.label, message: error.output ?? '', occurredAt: error.createdAt }) : null;
const check = [...store.core.check_job.values()].findLast(value => owned(value, session, task.id));
const snapshot = { schemaVersion: 1, projectId: session.projectId, sessionId: session.id, taskId: task.id, runId: run.id,
goal: task.contract?.goal ?? task.goal, taskStatusBefore: task.status, originalRunId: error?.runId ?? check?.runId ?? runs.at(-1)?.id ?? null,
failure: error ? { id: value.id ?? error.id, eventId: error.id, runId: error.runId, sha256: hash(value), value } : null,
verification: structuredClone(task.verification ?? null),
check: check ? { id: check.id, runId: check.runId, status: check.status, sourceFingerprint: check.sourceFingerprint ?? null,
logs: check.results.map(result => ({ id: result.logArtifactId ?? null, sha256: store.core.artifact.get(result.logArtifactId)?.sha256 ?? null })) } : null,
note: '绑定原执行及原失败;只读诊断答复不构成原目标交付,不重放工具或检查。' };
const artifact = store.artifactStore.write(session, run, snapshot, { kind: 'diagnostic-context' });
store.core.artifact.set(artifact.id, artifact);
return { artifactId: artifact.id, sha256: artifact.sha256, originalRunId: snapshot.originalRunId };
}
export function inspectDiagnosticContext(store, session, run) {
if (!run.diagnosticContext) return { evidenceVerified: false, historical: true, note: '旧诊断未封存原失败绑定,不能补造所属错误。' };
try {
if (!owned(run, session, session.taskId)) throw new Error('诊断不属于当前Task。');
const reference = run.diagnosticContext, artifact = store.owned('artifact', reference.artifactId, session.id);
if (artifact.taskId !== run.taskId || artifact.runId !== run.id || artifact.kind !== 'diagnostic-context' || artifact.sha256 !== reference.sha256)
throw new Error('诊断原工件身份或SHA无法核对。');
const value = JSON.parse(store.artifactStore.read(artifact));
if (!owned(value, session, run.taskId) || value.runId !== run.id || value.originalRunId !== reference.originalRunId)
throw new Error('诊断原项目/Task/Run绑定不一致。');
if (value.originalRunId && !owned(store.core.run.get(value.originalRunId), session, run.taskId)) throw new Error('原执行不属于此Task。');
if (value.failure) {
const event = session.events.find(row => row.id === value.failure.eventId);
const original = event?.diagnostic ?? (event ? { source: event.kind, title: event.label, message: event.output ?? '', occurredAt: event.createdAt } : null);
if (!event || event.taskId !== run.taskId || event.runId !== value.failure.runId || hash(original) !== value.failure.sha256 || hash(value.failure.value) !== value.failure.sha256)
throw new Error('原失败记录已变化或无法核对。');
}
return { ...value, ...reference, evidenceVerified: true };
} catch (error) { return { ...run.diagnosticContext, evidenceVerified: false, error: error.message }; }
}
+6
View File
@@ -701,6 +701,12 @@ return async (request, response) => {
else await runtime.gitDelivery().reconcile(session, deliveryJob[1]);
return json(response, store.publicSession(session));
}
if (method === 'GET' && action === 'delivery-status') {
if (url.searchParams.get('taskId') !== session.taskId || url.searchParams.get('runId') !== session.runId)
throw Object.assign(new Error('所选原任务或运行已变化,请刷新后核对。'), { status: 409 });
const report = await runtime.gitDelivery().reporter.inspect(session);
return json(response, { followUp: report.followUp, diagnostics: report.diagnostics, requirementsRevision: report.requirements.revision });
}
if (method === 'POST' && action === 'delivery-reports') {
await body(request); await runtime.gitDelivery().report(session);
return json(response, store.publicSession(session), 201);
+7 -4
View File
@@ -15,6 +15,7 @@ import { safePath, listFiles, readLines, searchFiles, proposeFile, proposePatch
import { projectContext, toolDefinitions, researchToolDefinitions, engineToolDefinitions, browserToolDefinitions } from './provider.mjs';
import { now, repairToolPairs } from './store.mjs';
import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnostics.mjs';
import { inspectDiagnosticContext } from '../core/tasks/diagnostic-context.mjs';
import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs';
import { tokenBudgetState,checkModelDispatchBudget } from '../shared/contracts/model-reservation.mjs';
import { taskToolAllowed, taskContract } from '../shared/contracts/task-control.mjs';
@@ -355,13 +356,14 @@ export class Runtime {
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 : '')
}) + (run.record.purpose === 'diagnostic' ? '\n本次仅回答运行诊断问题,允许读取所属结果;不得修改文件、执行命令或将解释视为原任务交付。诊断问题:' + run.record.question
+ '\n所属原执行与失败(核对失败时保持未知,不根据其它项目补造原因):' + JSON.stringify(inspectDiagnosticContext(this.store, session, run.record)) : '')
+ '\n结果未知的调用,不得假定成功或重放:' + JSON.stringify(unknown)
+ (deliveryProgress ? '\n当前工程执行依据(每次请求重新核对,非操作授权):\n' + JSON.stringify(deliveryProgress) : '')
+ (requirementReview ? '\n用户逐项要求复核(任务数据,不授权额外操作;证据和用户确认分别记录):\n' + JSON.stringify({
revision: requirementReview.revision, status: requirementReview.status, unreviewed_sources: requirementReview.unreviewed_sources,
error: requirementReview.error, items: requirementReview.items.map(item => ({ key: item.key, revision: item.revision, title: item.title,
criterion: item.criterion, method: item.method, kind: item.kind, paths: item.paths, tools: item.tools, checks: item.checks,
criterion: item.criterion, role: item.role ?? 'requirement', source: item.source, method: item.method, kind: item.kind, paths: item.paths, tools: item.tools, checks: item.checks,
status: item.status, error: item.error, proof_id: item.proof_id })) }) : '')
+ (fileResults.results.length || fileResults.sources.length ? '\n当前成果与可显式采用的旧来源(任务数据,原文件不等于新写入):' + JSON.stringify({
current: fileResults.results.slice(0, 8).map(row => ({ id: row.id, taskId: row.taskId, runId: row.runId, verification: row.verification, error: row.error, reason: row.reason, files: row.files.map(({ path, sha256, origin }) => ({ path, sha256, origin })) })),
@@ -626,7 +628,7 @@ export class Runtime {
if (error.diagnostic?.kind === 'model_identity') run.stopReason = 'model_identity';
const diagnostic = error.diagnostic ?? { source: 'workbench', origin: 'local', stage: 'agent_loop', kind: 'runtime',
title: '工作台任务需要处理', message: this.provider.redact(error.message ?? String(error)), occurredAt: now() };
session.lastFailure = { ...diagnostic, runId: run.id };
session.lastFailure = { ...diagnostic, projectId: session.projectId, sessionId: session.id, taskId: run.taskId, runId: run.id };
const message = this.store.message(session, 'system', diagnostic.message);
session.failure = { ...session.lastFailure, messageId: message.id };
this.store.event(session, { kind: 'error', source: diagnostic.source, label: diagnostic.title, phase: 'failed',
@@ -666,7 +668,8 @@ export class Runtime {
const maximumMessageBytes = Math.max(1, pageBytes - readMetadataReserve(readMetadata));
if (!['act_browser_tab','prepare_environment','run_command', 'run_checks', 'run_browser'].includes(tool)) this.store.invocationState(session, event, 'running');
else this.store.save(session);
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session) };
if (tool === 'inspect_session') result = { ...sessionSnapshot(session, run.project, run.config, value => this.provider.redact(value)), execution: this.store.executionSnapshot(session),
...(run.record.purpose === 'diagnostic' ? { diagnosticContext: inspectDiagnosticContext(this.store, session, run.record) } : {}) };
else if (tool === 'read_registered_skill') {
verifyPlanEvidence(this.store, session, this.store.owned('context_plan', run.record.currentContextPlanId, session.id));
result = this.skillRegistry().read(session, run.record, args, { maximumMessageBytes, callId: call.id });
+5 -1
View File
@@ -4,6 +4,7 @@ import path from 'node:path';
import { EventEmitter } from 'node:events';
import { randomUUID, createHash } from 'node:crypto';
import { lastSessionFailure } from './diagnostics.mjs';
import { bindDiagnosticContext } from '../core/tasks/diagnostic-context.mjs';
import { StateDatabase, runtimeOwnerAlive } from '../core/storage/state-database.mjs';
import { ArtifactStore } from '../core/storage/artifact-store.mjs';
import { collectLegacy, cleanConfig } from '../core/storage/legacy-import.mjs';
@@ -506,7 +507,10 @@ export class Store extends EventEmitter {
if (JSON.stringify(task.workspaceIdentity) !== JSON.stringify(workspaceIdentity)) throw Object.assign(new Error('任务的工作区身份已变化,不能将原任务移动到另一个工作区。'), { status: 409 });
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 (purpose === 'diagnostic') {
run.question = String(content); run.taskStatusBefore = task.status;
run.diagnosticContext = bindDiagnosticContext(this, session, task, run);
}
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);
@@ -0,0 +1,4 @@
import type { RequirementItem } from '../../client/types';
export const requirementStates: Record<string, string>;
export function resolvedRequirement(item: RequirementItem): boolean;
export function requirementNextStep(item: RequirementItem): string;
+36
View File
@@ -0,0 +1,36 @@
export const requirementStates = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对',
evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行',
scope_unknown: '范围待澄清', reference_recorded: '参考已记录', boundary_recorded: '边界已记录' };
export const resolvedRequirement = item => ['evidence_verified', 'user_confirmed', 'not_requested', 'reference_recorded', 'boundary_recorded'].includes(item.status);
export function requirementNextStep(item) {
if (item.status === 'scope_unknown') return '澄清原文用途、业务范围及验收方式后修订此项。';
if (item.status === 'reference_recorded') return '已记录参考用途;不自动要求修改或交付该文件。';
if (item.status === 'boundary_recorded') return '已记录禁止事项;是否遵守仍需实际证据,不计为验收通过。';
if (item.status === 'not_requested') return '按约定未执行检查;不计为测试通过,原失败保留。';
if (item.status === 'evidence_verified') return '所选范围的原证据已核对;其它要求分别复核。';
if (item.status === 'user_confirmed') return '用户体验结论已记录;不代替工程检查。';
if (item.error) return item.error + ' 核对当前输入和原记录后重新选择证据。';
return item.method === 'user' ? '实际体验此项后记录用户结论。' : '选择属于当前Task、要求修订及当前输入的实际证据进行复核。';
}
// Both the task page and saved report use this same read-only assessment.
export function deliveryFollowUp(report) {
const gaps = [];
const add = (kind, id, label, nextStep) => gaps.push({ kind, id, label, nextStep });
for (const item of report.requiresVerification) add('unknown', item.id, item.tool + '结果需要核对', '核对原输入、原工件和实际副作用;不要重放已进入执行的操作。');
for (const item of report.changes.filter(row => ['pending', 'conflict'].includes(row.status))) add('review', item.id, item.path + '等待审查', '在改动面板核对差异与冲突后决定是否应用。');
if (report.deliveryReview) add('review', report.deliveryReview.planId, 'Git交付等待审查', '核对当前交付预览后确认或撤回。');
if (report.requirements.error) add('requirements', report.task.id, '要求原记录无法核对', report.requirements.error);
for (const id of report.requirements.unreviewed_sources ?? []) add('source', id, '用户原文尚未审阅', '从原文整理草案或手动记录要求,确认用途和验收范围。');
for (const item of report.requirements.items.filter(row => !resolvedRequirement(row))) add('requirement', item.key, item.title + ' · ' + (requirementStates[item.status] ?? item.status), requirementNextStep(item));
for (const item of report.taskPlan.steps.filter(row => row.status !== 'verified')) add('plan', item.key, item.title + '尚未核验', '核对当前计划步骤、依赖和原实际证据。');
if (report.status === 'needs_results') add('files', report.task.id, '当前文件成果仍需核对', '回到原目标,在文件成果中核对当前字节与要求的修改范围。');
if (report.status === 'needs_checks') add('checks', report.task.id, '工程检查尚未通过当前输入核验', '查看原检查与失败日志;需要修复时继续原目标,检查仍须审批。');
if (report.status === 'needs_browser_checks') add('browser', report.task.id, '页面验收仍待完成', '核对当前构建、所属页面计划和原验收结果。');
const latestDiagnostic = report.diagnostics?.at(-1);
if (latestDiagnostic && !latestDiagnostic.context.evidenceVerified) add('diagnostic', latestDiagnostic.runId, '诊断的原失败绑定未核对', latestDiagnostic.context.error ?? latestDiagnostic.context.note);
return { taskId: report.task.id, runId: report.runId, goal: report.task.goal, taskStatus: report.task.status, status: report.status,
statusLabel: report.statusLabel, gaps, nextStep: gaps[0]?.nextStep ?? (report.status === 'in_progress' ? '等待所属运行、检查或审批结束,按原目标核对结果。'
: report.status === 'verified_uncommitted' ? '核对要求与当前结果;需要Git交付时先准备预览并审查。' : '查看已核对的范围与原证据;需要新增工作时明确追加要求。'),
note: '诊断答复完成仅表示解释结束;原目标、原失败和未知结果继续保留。' };
}