feat(tasks): review sourced requirements against current original evidence

This commit is contained in:
Agent Workbench Dev
2026-11-04 10:36:50 +08:00
parent ce3afb2f0d
commit 785dd0c54d
70 changed files with 6103 additions and 7 deletions
+190
View File
@@ -0,0 +1,190 @@
import { randomUUID } from 'node:crypto';
import { TaskPlanManager } from './task-plan-manager.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { taskContract } from '../../shared/contracts/task-control.mjs';
import { taskPlanInput, planHash, planError } from '../../shared/contracts/task-plans.mjs';
import { readText } from '../../server/files.mjs';
import { FileResults } from './file-results.mjs';
const same = (a, b) => planHash(a) === planHash(b);
const now = () => new Date().toISOString();
const checkKeys = (value, keys) => {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !keys.includes(key)))
throw planError('要求复核包含未声明字段。', 'input', 400);
};
const requiredText = (value, max) => {
if (typeof value !== 'string' || !value.trim() || value.length > max || value.includes('\0')) throw planError('请填写有效的要求或复核说明。', 'input', 400);
return value.trim();
};
export function requirementSources(task) {
return [{ kind: 'goal', id: task.id, text: task.goal, at: task.createdAt ?? null },
...(task.instructions ?? []).filter(row => row.source !== 'review-action').map(row => ({ kind: 'instruction', id: row.id, text: row.content, at: row.createdAt ?? row.at ?? null }))]
.map(row => ({ ...row, sha256: planHash({ kind: row.kind, id: row.id, text: row.text }) }));
}
function itemInput(value, sources) {
checkKeys(value, ['key', 'title', 'criterion', 'source', 'kind', 'tools', 'paths', 'checks', 'viewport_width', 'actions', 'method']);
checkKeys(value.source, ['kind', 'id', 'start', 'end']);
const original = sources.find(row => row.kind === value.source.kind && row.id === value.source.id);
const { start, end } = value.source;
if (!original || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end <= start || end > original.text.length)
throw planError('要求来源必须是当前Task用户原文的有效范围。', 'input', 400);
const method = value.method ?? 'evidence';
if (!['evidence', 'user', 'not_requested'].includes(method)) throw planError('复核方式无效。', 'input', 400);
const { source, method: ignored, ...fields } = value;
// Reuse the existing bounded evidence scopes; a statement alone never passes.
const step = taskPlanInput({ expected_revision: 0, steps: [{ ...fields, depends_on: [] }] }).steps[0];
if (method === 'not_requested' && step.kind !== 'checks') throw planError('仅检查约定可记录为未执行。', 'input', 400);
return { ...step, method, source: { ...source, quote: original.text.slice(start, end), sourceSha256: original.sha256, at: original.at } };
}
const ledgerContract = row => ({ schemaVersion: 1, kind: 'task-requirements', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
taskId: row.taskId, runId: row.runId, revision: row.revision, parentId: row.parentId, items: row.items, sources: row.sources, createdAt: row.createdAt });
const proofContract = row => ({ schemaVersion: 1, kind: 'requirement-proof', id: row.id, sessionId: row.sessionId, projectId: row.projectId,
taskId: row.taskId, runId: row.runId, key: row.key, requirementSha256: row.requirementSha256, requirementRevision: row.requirementRevision,
evidenceId: row.evidenceId, outcome: row.outcome, sourceFingerprint: row.sourceFingerprint, status: row.status, error: row.error,
note: row.note, createdAt: row.createdAt });
// This ledger lives on the existing Task. It delegates all engineering proof
// checks to TaskPlanManager and grants no tool, command or file permissions.
export class RequirementReview {
constructor(store, { planner = new TaskPlanManager(store), redact = String } = {}) { this.store = store; this.planner = planner; this.redact = redact; }
current(session) { return this.store.owned('task', session.taskId, session.id).requirementRevisions?.at(-1) ?? null; }
verifyRecord(session, row, kind, contract) {
if (row.sessionId !== session.id || row.projectId !== session.projectId || row.taskId !== session.taskId) throw planError('要求记录不属于当前项目和Task。');
const original = this.planner.artifact(session, row.contractArtifactId, kind, row.taskId, row.runId);
if (original.artifact.sha256 !== row.contractSha256 || original.text !== JSON.stringify(contract(row))) throw planError('要求或复核记录与原工件不一致。');
}
write(session, run, row, kind, contract) {
const artifact = this.store.artifactStore.write(session, run, contract(row), { kind });
this.store.core.artifact.set(artifact.id, artifact);
return { ...row, contractArtifactId: artifact.id, contractSha256: artifact.sha256 };
}
async evidence(session, item, id, inspection) {
if (item.kind === 'results') {
const result = new FileResults(this.store).verify(session, id, { current: false });
if (result.taskId !== session.taskId || !item.paths.every(file => result.files.some(row => row.path === file)))
throw planError('成果凭据不属于当前Task或未覆盖要求文件。');
const files = result.files.filter(file => item.paths.includes(file.path));
for (const file of files) if (readText(this.store.project(session.projectId), file.path).sha256 !== file.sha256)
throw planError('当前要求的成果文件SHA已变化。', 'stale');
const artifact = this.store.owned('artifact', result.contractArtifactId, session.id);
return { kind: 'file_result', id: result.id, runId: result.runId, scope: 'current_requirement_files',
files: files.map(({ path, sha256, origin }) => ({ path, sha256, origin })),
artifacts: [{ id: artifact.id, kind: artifact.kind, runId: artifact.runId, sha256: artifact.sha256, bytes: artifact.bytes }] };
}
const outcome = await this.planner.evidence(session, item, id, { inspection });
if (item.kind === 'analysis') {
const record = this.store.owned('tool', id, session.id);
const result = JSON.parse(this.planner.artifact(session, record.resultArtifactId, 'tool-result', record.taskId, record.runId).text);
if (record.tool === 'read_file' && (!result.sha256 || readText(this.store.project(session.projectId), result.path).sha256 !== result.sha256))
throw planError('原读取对应旧文件SHA,请使用当前文件的实际读取。', 'stale');
if (record.tool === 'inspect_project' && result.sourceFingerprint !== inspection.sourceFingerprint)
throw planError('原工程观察对应旧源码输入。', 'stale');
}
return outcome;
}
save(session, input) { return this.planner.mutate(session, 'user', async () => {
checkKeys(input, ['expected_revision', 'requirements']);
const { task, run } = this.planner.task(session), previous = this.current(session), revision = previous?.revision ?? 0;
if (previous) this.verifyRecord(session, previous, 'task-requirements', ledgerContract);
if (input.expected_revision !== revision) throw planError('要求修订已变化,请刷新后保存。', 'stale');
if (revision >= 24 || !Array.isArray(input.requirements) || !input.requirements.length || input.requirements.length > 24)
throw planError('每个Task最多24项要求与24次修订。', 'input', 400);
const sources = requirementSources(task), items = input.requirements.map(value => itemInput(value, sources));
if (new Set(items.map(row => row.key)).size !== items.length || previous?.items.some(row => !items.some(item => item.key === row.key)))
throw planError('要求ID需唯一;原要求不能删除,可修订并保留原记录。', 'input', 400);
if (JSON.stringify(items).length > 24000) throw planError('要求范围过大,请缩小Task。', 'input', 400);
for (const item of items) {
if (item.method === 'not_requested' && taskContract(task).checks !== 'skip') throw planError('当前用户约定没有跳过检查,不能标为按约定未执行。');
const old = previous?.items.find(row => row.key === item.key);
const { revision: oldRevision, ...oldContent } = old ?? {};
item.revision = old && same(oldContent, item) ? oldRevision : (oldRevision ?? 0) + 1;
}
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
if (session.taskId !== task.id || session.runId !== run.id || this.current(session)?.id !== previous?.id || !same(sources, requirementSources(task)))
throw planError('保存期间原任务、来源或要求已变化。', 'stale');
const row = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
revision: revision + 1, parentId: previous?.id ?? null, items, sources, createdAt: now() }, 'task-requirements', ledgerContract);
(task.requirementRevisions ??= []).push(row);
this.store.save(session, { type: 'task.requirements_saved', detail: { id: row.id, revision: row.revision } });
return row;
}); }
async inspect(session, { candidates = false, inspection = null } = {}) {
const { task, run } = this.planner.task(session), ledger = this.current(session), sources = requirementSources(task);
const base = { configured: !!ledger, task_id: task.id, revision: ledger?.revision ?? 0, sources, items: [], all_resolved: false, binding_sha256: null,
note: '证据核对只证明所选范围;模型完成答复不等于业务验收。' };
if (!ledger) return { ...base, status: 'not_recorded', unreviewed_sources: sources.map(row => row.id) };
try { this.verifyRecord(session, ledger, 'task-requirements', ledgerContract); }
catch (error) { return { ...base, status: 'unverified', error: this.redact(error.message) }; }
const unreviewed = sources.filter(row => !ledger.sources.some(old => old.id === row.id && old.sha256 === row.sha256)).map(row => row.id);
const items = [], proofs = task.requirementProofs ?? [];
for (const item of ledger.items) {
const source = sources.find(row => row.id === item.source.id && row.kind === item.source.kind);
const proof = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item) && row.status === 'verified');
const attempt = proofs.findLast(row => row.key === item.key && row.requirementSha256 === planHash(item));
let status = 'pending', error = null, outcome = null;
try {
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('原用户来源已变化。', 'stale');
if (item.method === 'not_requested') {
if (taskContract(task).checks !== 'skip') throw planError('当前检查约定已变化。', 'stale');
status = 'not_requested';
} else if (proof) {
this.verifyRecord(session, proof, 'requirement-proof', proofContract);
const sourceRead = item.kind === 'analysis' && this.store.core.tool.get(proof.evidenceId)?.tool === 'read_file';
if (item.kind === 'analysis' || item.method === 'user') {
inspection ??= await inspectProject(this.store.project(session.projectId));
if (!inspection.scope.complete || !sourceRead && proof.sourceFingerprint !== inspection.sourceFingerprint) throw planError('复核后源码输入已变化。', 'stale');
}
if (item.method !== 'user') {
outcome = await this.evidence(session, item, proof.evidenceId, inspection);
if (!same(outcome, proof.outcome)) throw planError('实际记录与原复核结果不一致。', 'stale');
}
status = item.method === 'user' ? 'user_confirmed' : 'evidence_verified';
} else if (attempt?.status === 'rejected') status = 'failed';
} catch (cause) { status = cause.code === 'stale' ? 'stale' : 'unverified'; error = this.redact(cause.message); }
items.push({ ...item, status, error, evidence: outcome, proof_id: proof?.id ?? null, proof_artifact_id: proof?.contractArtifactId ?? null,
user_note: status === 'user_confirmed' ? proof.note : null,
last_rejection: attempt?.status === 'rejected' ? { id: attempt.id, message: attempt.error, at: attempt.createdAt } : null,
...(candidates && item.method === 'evidence' ? { candidates: this.planner.candidates(session, item) } : {}) });
}
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('核对期间Task/Run或要求已变化。', 'stale');
const resolved = !unreviewed.length && items.every(row => ['evidence_verified', 'user_confirmed', 'not_requested'].includes(row.status));
return { ...base, items, unreviewed_sources: unreviewed, status: resolved ? 'resolved' : 'incomplete', all_resolved: resolved,
history: proofs.map(row => ({ id: row.id, key: row.key, revision: row.requirementRevision, status: row.status, error: row.error, at: row.createdAt, artifact_id: row.contractArtifactId })),
contract_artifact_id: ledger.contractArtifactId, contract_sha256: ledger.contractSha256,
binding_sha256: resolved ? planHash({ ledger: ledger.contractSha256, proofs: items.map(row => [row.key, row.proof_id, row.status, row.evidence]) }) : null };
}
verify(session, input) { return this.planner.mutate(session, 'user', async () => {
checkKeys(input, ['expected_revision', 'key', 'evidence_id', 'note']);
const { task, run } = this.planner.task(session), ledger = this.current(session);
if (!ledger || ledger.revision !== input.expected_revision) throw planError('要求修订已变化,请刷新后复核。', 'stale');
this.verifyRecord(session, ledger, 'task-requirements', ledgerContract);
const item = ledger.items.find(row => row.key === input.key);
if (!item || item.method === 'not_requested') throw planError('请选择需要复核的当前要求。');
if ((task.requirementProofs?.length ?? 0) >= 128) throw planError('复核记录已到上限,请缩小任务。');
if (item.method === 'user' ? input.evidence_id !== undefined : input.note !== undefined) throw planError('用户确认和原证据核对不能混用。', 'input', 400);
const note = item.method === 'user' ? requiredText(input.note, 1000) : null;
let outcome = null, inspection = null, error = null;
try {
const source = requirementSources(task).find(row => row.kind === item.source.kind && row.id === item.source.id);
if (!source || source.sha256 !== item.source.sourceSha256) throw planError('用户要求来源已变化。', 'stale');
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
inspection = await inspectProject(this.store.project(session.projectId));
if (!inspection.scope.complete) throw planError('源码范围不完整,不能复核。');
if (item.method !== 'user') outcome = await this.evidence(session, item, input.evidence_id, inspection);
} catch (cause) { error = this.redact(cause.message); }
if (task.id !== session.taskId || run.id !== session.runId || ledger.id !== this.current(session)?.id) throw planError('复核期间任务或要求已变化。', 'stale');
const proof = this.write(session, run, { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: task.id, runId: run.id,
key: item.key, requirementSha256: planHash(item), requirementRevision: item.revision, evidenceId: input.evidence_id ?? null,
sourceFingerprint: inspection?.sourceFingerprint ?? null, outcome, status: error ? 'rejected' : 'verified', error, note, createdAt: now() }, 'requirement-proof', proofContract);
(task.requirementProofs ??= []).push(proof);
this.store.save(session, { type: error ? 'task.requirement_rejected' : 'task.requirement_verified', detail: { id: proof.id, key: item.key } });
return { status: error ? 'error' : 'completed', proof_id: proof.id, ...(error ? { message: error } : {}) };
}); }
async assertReady(session, { inspection = null, expectedBinding = undefined } = {}) {
const view = await this.inspect(session, { inspection });
if (view.configured && !view.all_resolved) throw planError('用户要求仍有待复核、失效或未审阅来源,请先核对要求与证据。', 'stale');
if (expectedBinding !== undefined && expectedBinding !== view.binding_sha256) throw planError('Git预览后的要求或证据已变化,请重新预览。', 'stale');
return view;
}
}