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
+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 }; }
}