feat(runtime): observe turn evidence without changing execution controls

This commit is contained in:
Agent Workbench Dev
2026-11-04 11:26:47 +08:00
parent 785dd0c54d
commit 6fe04042c5
291 changed files with 66740 additions and 3 deletions
@@ -0,0 +1,90 @@
import { observeTurn, toolProgressFacts } from './turn-progress.mjs';
import { planHash } from '../../shared/contracts/task-plans.mjs';
// Local, bounded observation. Original tools/jobs remain the evidence of record.
// Observer failure is recorded on the Run and cannot interrupt execution.
export function recordTurnProgress(store, session, run, step, phase = 'settled', failure = null) {
try {
if (run.taskId !== session.taskId || run.sessionId !== session.id || run.projectId !== session.projectId) throw new Error('Observer Task/Run ownership mismatch.');
if (step && (step.runId !== run.id || step.taskId !== run.taskId || step.sessionId !== session.id || step.projectId !== session.projectId))
throw new Error('Observer step ownership mismatch.');
const task = store.owned('task', run.taskId, session.id);
const owned = row => row.taskId === run.taskId && row.sessionId === session.id && row.projectId === session.projectId;
const tools = [];
// Waiting is an intermediate snapshot, not a second consumption of tools
// already completed earlier in this same turn. Settle them exactly once.
for (const id of phase === 'waiting' ? [] : step?.progressToolIds ?? []) {
const record = store.owned('tool', id, session.id);
if (!owned(record) || record.runId !== run.id || record.stepId !== step.id) throw new Error('Observer tool ownership mismatch.');
const artifact = store.owned('artifact', record.resultArtifactId, session.id);
if (!owned(artifact) || artifact.runId !== run.id || artifact.kind !== 'tool-result') throw new Error('Observer result ownership mismatch.');
tools.push(toolProgressFacts(record, JSON.parse(store.artifactStore.read(artifact)), artifact, record.progressFailureCategory));
}
if (failure) {
const event = session.events.findLast(row => row.runId === run.id && row.diagnostic?.id === failure.id);
tools.push({ id: failure.id ?? null, name: 'model_request',
sourceEventId: event?.id, diagnosticSha256: event ? planHash(event.diagnostic) : null,
artifactId: failure.upstream?.artifactId, resultSha256: failure.upstream?.artifactSha256,
failure: { category: failure.kind ?? 'unknown', signature: planHash({ kind: failure.kind, code: failure.code,
httpStatus: failure.httpStatus, stage: failure.stage, outcome: failure.outcome, message: failure.message }) } });
}
const waiting = session.approvals.filter(row => row.taskId === run.taskId && row.projectId === session.projectId && row.runId === run.id && row.status === 'pending').map(row => ({ kind: 'approval', id: row.id }));
for (const row of store.core.check_job.values()) if (owned(row) && ['queued', 'running'].includes(row.status)) waiting.push({ kind: 'check_job', id: row.id });
if (session.status === 'needs_review') waiting.push({ kind: 'review', id: run.id });
const facts = { projectId: session.projectId, sessionId: session.id, taskId: run.taskId, runId: run.id,
stepId: step?.id, stepIndex: step?.index, phase, tools, waiting,
changes: session.changes.filter(row => row.taskId === run.taskId && row.status === 'applied').map(row => [row.path, row.sha256]),
checks: [...store.core.check_job.values()].filter(row => owned(row) && !row.requiresVerification && !row.stale && ['passed', 'failed'].includes(row.status))
.map(row => [row.sourceFingerprint, row.status, row.results.map(result => [result.name, result.status, store.core.artifact.get(result.logArtifactId)?.sha256])]),
requirements: (task.requirementProofs ?? []).filter(row => row.status === 'verified' && task.requirementRevisions?.at(-1)?.items.some(item => item.key === row.key && planHash(item) === row.requirementSha256))
.map(row => [row.key, row.requirementSha256, row.sourceFingerprint, row.outcome ? planHash(row.outcome) : planHash(row.note)]),
userBoundaries: (task.instructions ?? []).filter(row => row.source !== 'review-action').map(row => [row.id, planHash(row.content)]) };
const result = observeTurn(run.progressShadow, facts);
// Persist only the individual public-fact observation as an immutable receipt.
const artifact = store.artifactStore.write(session, run, result.observation, { kind: 'turn-progress-shadow' });
store.core.artifact.set(artifact.id, artifact);
run.progressShadow = result.state;
run.progressShadowArtifactIds = [...(run.progressShadowArtifactIds ?? []), artifact.id].slice(-40);
store.save(session, { type: 'run.progress_shadow', detail: { runId: run.id, stepId: step?.id ?? null, classification: result.observation.classification, artifactId: artifact.id } });
return result.observation;
} catch {
run.progressShadowError = { kind: 'observation_unavailable', phase };
return null;
}
}
export function inspectTurnProgress(store, session, run) {
if (!run.progressShadow) return { mode: 'shadow', recorded: false, turns: [], evidence_verified: false, error: run.progressShadowError ?? null };
const view = { mode: 'shadow', recorded: true, observations: run.progressShadow.observations, truncated: run.progressShadow.truncated,
turns: structuredClone(run.progressShadow.turns), artifact_ids: run.progressShadowArtifactIds ?? [], evidence_verified: true,
error: run.progressShadowError ? '部分观察未能记录,保留的原收据单独核对;原执行结果保持。' : null };
try {
const owned = row => row.sessionId === session.id && row.projectId === session.projectId && row.taskId === run.taskId && row.runId === run.id;
if (view.turns.length !== view.artifact_ids.length) throw new Error('单轮观察与原收据数量不一致。');
for (let i = 0; i < view.turns.length; i++) {
const artifact = store.owned('artifact', view.artifact_ids[i], session.id);
if (!owned(artifact) || artifact.kind !== 'turn-progress-shadow') throw new Error('单轮观察原收据归属不一致。');
const original = JSON.parse(store.artifactStore.read(artifact));
if (planHash(original) !== planHash(view.turns[i])) throw new Error('单轮观察与原收据不一致。');
for (const ref of original.tools) {
if (ref.tool === 'model_request') {
const event = session.events.find(row => row.id === ref.source_event_id && row.runId === run.id);
if (!event?.diagnostic || event.diagnostic.id !== ref.id || planHash(event.diagnostic) !== ref.diagnostic_sha256)
throw new Error('单轮观察的原模型失败记录待核对。');
if (ref.result_artifact_id) {
const result = store.owned('artifact', ref.result_artifact_id, session.id);
if (!owned(result) || result.sha256 !== ref.result_sha256 || !['model-http-response', 'model-stream-response'].includes(result.kind))
throw new Error('单轮观察的原模型失败响应来源变化。');
store.artifactStore.read(result);
}
continue;
}
const record = store.owned('tool', ref.id, session.id), result = store.owned('artifact', ref.result_artifact_id, session.id);
if (!owned(record) || !owned(result) || record.tool !== ref.tool || record.argsSha256 !== ref.args_sha256 || result.kind !== 'tool-result'
|| record.resultArtifactId !== result.id || result.sha256 !== ref.result_sha256) throw new Error('单轮观察的工具或原结果来源变化。');
store.artifactStore.read(result);
}
}
} catch { view.evidence_verified = false; view.error = '单轮观察的原收据或工具结果待核对;不用于交付通过判定。'; }
return view;
}
@@ -0,0 +1,97 @@
import { createHash } from 'node:crypto';
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const validRange = read => read && typeof read.key === 'string' && /^[a-f0-9]{64}$/.test(read.sha256)
&& Number.isSafeInteger(read.start) && Number.isSafeInteger(read.end) && read.start >= 0 && read.end > read.start;
const merge = ranges => ranges.sort((a, b) => a[0] - b[0]).reduce((result, range) => {
const last = result.at(-1); if (last && range[0] <= last[1]) last[1] = Math.max(last[1], range[1]); else result.push([...range]); return result;
}, []);
const size = ranges => ranges.reduce((sum, [start, end]) => sum + end - start, 0);
export const TURN_PROGRESS_LIMITS = Object.freeze({ sources: 32, ranges: 24, facts: 96, failures: 48, turns: 40, tools: 64 });
// External facts only. Neither message wording nor model reasoning is an input.
// Every result is shadow data, never a stop/permission/budget decision.
export function observeTurn(previous, facts) {
const scope = { projectId: facts.projectId, sessionId: facts.sessionId, taskId: facts.taskId, runId: facts.runId };
if (previous && hash(previous.scope) !== hash(scope)) throw new Error('Turn observation belongs to another Task/Run.');
const state = previous ? structuredClone(previous) : { schemaVersion: 1, mode: 'shadow', scope, reads: [], facts: [], failures: [], turns: [], observations: 0, truncated: false };
let uncertain = false;
const remember = (collection, signature, limit) => {
if (collection.includes(signature)) return false;
if (collection.length >= limit) { state.truncated = true; uncertain = true; return false; }
collection.push(signature); return true;
};
const delta = { read_characters: 0, new_sources: 0, repeated_reads: 0, changed_files: 0, check_results: 0, requirement_evidence: 0,
user_boundaries: 0, new_failures: 0, repeated_failures: 0, other_observations: 0 };
const reasons = [], refs = [];
const tools = facts.tools ?? [];
if (tools.length > TURN_PROGRESS_LIMITS.tools) { state.truncated = true; uncertain = true; }
for (const tool of tools.slice(0, TURN_PROGRESS_LIMITS.tools)) {
refs.push({ id: tool.id, tool: tool.name, args_sha256: tool.argsSha256 ?? null, result_artifact_id: tool.artifactId ?? null, result_sha256: tool.resultSha256 ?? null,
...(tool.sourceEventId ? { source_event_id: tool.sourceEventId, diagnostic_sha256: tool.diagnosticSha256 } : {}) });
if (tool.failure) {
const signature = hash([tool.name, tool.argsSha256, tool.failure.category, tool.failure.signature]);
if (remember(state.failures, signature, TURN_PROGRESS_LIMITS.failures)) { delta.new_failures++; reasons.push('new_failure:' + tool.failure.category); }
else if (!uncertain) { delta.repeated_failures++; reasons.push('repeated_failure:' + tool.failure.category); }
continue;
}
if (validRange(tool.read)) {
const read = tool.read, key = hash([read.key, read.sha256, read.unit]);
let entry = state.reads.find(value => value.key === key);
if (!entry) {
if (state.reads.length >= TURN_PROGRESS_LIMITS.sources) { state.truncated = true; uncertain = true; continue; }
entry = { key, sha256: read.sha256, unit: read.unit, ranges: [] }; state.reads.push(entry); delta.new_sources++;
}
const ranges = merge([...entry.ranges, [read.start, read.end]]), growth = size(ranges) - size(entry.ranges);
if (ranges.length > TURN_PROGRESS_LIMITS.ranges) { state.truncated = true; uncertain = true; continue; }
entry.ranges = ranges; delta.read_characters += growth;
if (!growth) delta.repeated_reads++;
} else if (tool.observationSignature && remember(state.facts, hash(['observation', tool.name, tool.observationSignature]), TURN_PROGRESS_LIMITS.facts)) delta.other_observations++;
}
const count = (rows, kind, field) => {
if ((rows?.length ?? 0) > TURN_PROGRESS_LIMITS.facts) { state.truncated = true; uncertain = true; }
for (const row of (rows ?? []).slice(0, TURN_PROGRESS_LIMITS.facts))
if (remember(state.facts, hash([kind, row]), TURN_PROGRESS_LIMITS.facts)) delta[field]++;
};
count(facts.changes, 'changes', 'changed_files'); count(facts.checks, 'checks', 'check_results');
count(facts.requirements, 'requirements', 'requirement_evidence'); count(facts.userBoundaries, 'user', 'user_boundaries');
if (delta.read_characters) reasons.push('new_returned_file_or_artifact_range');
if (delta.repeated_reads) reasons.push('same_sha_range_already_returned');
for (const field of ['changed_files', 'check_results', 'requirement_evidence', 'user_boundaries', 'other_observations']) if (delta[field]) reasons.push(field);
const waiting = (facts.waiting ?? []).slice(0, 16).map(row => ({ kind: row.kind, id: row.id }));
const growth = delta.read_characters + delta.changed_files + delta.check_results + delta.requirement_evidence + delta.other_observations;
const classification = facts.phase === 'baseline' ? 'baseline' : waiting.length ? 'waiting' : growth ? 'evidence_growth' : delta.new_failures ? 'new_failure_evidence'
: delta.user_boundaries ? 'user_boundary' : uncertain ? 'unknown_bounded' : delta.repeated_failures ? 'repeated_failure_candidate'
: delta.repeated_reads ? 'repeated_read_candidate' : 'no_observed_change';
if (facts.phase === 'baseline') { for (const key of Object.keys(delta)) delta[key] = 0; reasons.length = 0; reasons.push('existing_facts_not_run_progress'); }
const observation = { schemaVersion: 1, mode: 'shadow', taskId: scope.taskId, runId: scope.runId,
stepId: facts.stepId ?? null, stepIndex: facts.stepIndex ?? null, phase: facts.phase ?? 'settled', classification,
delta, reasons: [...new Set(reasons)].slice(0, 16), tools: refs, waiting, truncated: state.truncated,
note: '外显事实观察;不等于业务交付,不改变停止、权限或预算。' };
state.observations++; state.turns.push(observation);
if (state.turns.length > TURN_PROGRESS_LIMITS.turns) { state.turns.shift(); state.truncated = true; }
return { state, observation };
}
export function toolProgressFacts(record, result, artifact, failureCategory = null) {
const value = { id: record.id, name: record.tool, argsSha256: record.argsSha256, artifactId: artifact?.id, resultSha256: artifact?.sha256 };
const status = result.status;
if (record.requiresVerification || ['unknown', 'interrupted', 'unverified'].includes(status)) {
value.failure = { category: 'requires_verification', signature: hash([status, result.code, result.message]) };
} else if (['failed', 'error', 'denied'].includes(status)) {
value.failure = { category: status === 'denied' ? 'permission' : failureCategory ?? 'tool_or_environment', signature: hash([status, result.code, result.message, result.exit_code]) };
} else if (['read_file', 'read_artifact', 'read_browser_result', 'read_research_evidence'].includes(record.tool) && typeof result.content === 'string') {
const start = result.offset ?? 0, end = result.next_offset ?? start + result.content.length;
// Offsets refer to UTF-16 characters within the original tool range. They
// are deliberately not labeled file bytes or cumulative token savings.
if (end - start === result.content.length) value.read = { key: hash([result.path ?? result.artifact_id ?? result.job_id,
result.range_start_line ?? result.start_line ?? null, result.range_end_line ?? result.end_line ?? null, result.section ?? null]),
sha256: result.sha256, start, end, unit: 'utf16_in_original_range' };
} else if (['inspect_project', 'list_files', 'search_files', 'index_project', 'query_code'].includes(record.tool)) {
const { tool_invocation_id, repeated_read_count, reading_hint, ...actual } = result;
// Random invocation IDs and changing timestamps are not observation growth.
delete actual.inspectedAt; delete actual.createdAt; delete actual.durationMs;
value.observationSignature = hash(actual);
}
return value;
}
@@ -0,0 +1,299 @@
import { verifyNodeBinding } from './environment/environment-inspector.mjs';
import { verifyEnvironmentPreparation } from './environment/environment-evidence.mjs';
import { inspectProject } from './project-inspector.mjs';
import { ChangeSetManager } from './workspaces/change-sets.mjs';
import { verifyPlanEvidence } from './context/request-plan.mjs';
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
import { projectWorkspaceIdentity, unresolvedWorkspaces } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { verifyPythonCheckEvidence } from './python-runtime.mjs';
import { currentBrowserVerification, verifyBrowserJob } from './browser/browser-manager.mjs';
import { TaskPlanManager } from './tasks/task-plan-manager.mjs';
import { RequirementReview } from './tasks/requirement-review.mjs';
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';
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
existing_verified: '当前成果已核对,无新增修改', needs_requirements: '用户要求仍有待复核事项', files_delivered: '当前文件已交付,按约定未测试', needs_results: '当前文件成果仍需核对',
needs_checks: '需要实际工程检查', needs_browser_checks: '需要实际页面验收', needs_plan_verification: '任务计划仍有未完成项', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
const escapeCell = value => String(value ?? '').replaceAll('|', '\\|').replaceAll('\n', ' ');
export function verifiedCheck(store, session, inspection) {
const task = store.core.task.get(session.taskId);
const job = store.core.check_job.get(task?.verification.checkJobId);
if (!job || job.sessionId !== session.id || job.taskId !== task.id || job.projectId !== session.projectId
|| job.status !== 'passed' || job.stale || !inspection.scope.complete) return null;
const same = job.sourceFingerprint ? job.sourceFingerprint === inspection.sourceFingerprint : job.fingerprint === inspection.fingerprint;
if (!same || !job.results.length || job.results.some(result => result.status !== 'passed' || result.exitCode !== 0)
|| !job.results.some(result => result.kind === 'test' && result.tests?.passed > 0 && result.tests.passed === result.tests.total && !result.tests.failed && !result.tests.skipped && !result.tests.cancelled)) return null;
try { verifyNodeBinding(store.project(session.projectId),job.environment); verifyEnvironmentPreparation(store,session.projectId,job.environment); } catch { return null; }
for (const result of job.results) {
if (!result.logArtifactId) return null;
try {
const artifact = store.owned('artifact', result.logArtifactId, session.id);
if (artifact.taskId !== task.id || artifact.kind !== 'check-log') return null;
store.artifactStore.read(artifact);
verifyPythonCheckEvidence(store, session, job, result);
} catch { return null; }
}
return job;
}
export class DeliveryReporter {
constructor(store, { redact = String } = {}) { this.store = store; this.redact = redact; }
async create(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);
const project = this.store.project(session.projectId);
await verifyWorkspaceProject(this.store, project);
inspection ??= await inspectProject(project);
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('生成报告期间任务已切换,请重新生成。'), { status: 409 });
if (job && (job.sessionId !== session.id || job.taskId !== taskId)) throw new Error('提交记录不属于当前任务。');
const changes = session.changes.filter(change => change.taskId === taskId);
const resultManager = new FileResults(this.store), fileResults = resultManager.inspect(session).results, fileDelivery = resultManager.completion(session), contract = taskContract(task);
const hasFileScope = contract.kind === 'file' || fileResults.length > 0;
const jobs = [...this.store.core.delivery_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
const check = verifiedCheck(this.store, session, inspection);
const requiresVerification = [...this.store.core.tool.values()].filter(value => value.taskId === taskId && value.requiresVerification)
.map(value => ({ id: value.id, tool: value.tool, status: value.state }));
requiresVerification.push(...unresolvedWorkspaces(this.store, project.id).map(value => ({ id: value.id, tool: 'workspace', status: value.status })));
const unresolved = jobs.filter(value => value.requiresVerification || value.status === 'unknown');
const checkJobs = [...this.store.core.check_job.values()].filter(value => value.taskId === taskId);
const pythonEvidence = new Map();
for (const checkJob of checkJobs) if (!checkJob.stale && checkJob.sourceFingerprint === inspection.sourceFingerprint) {
for (const result of checkJob.results.filter(value => value.engine === 'python' && value.status === 'passed')) {
try { verifyPythonCheckEvidence(this.store, session, checkJob, result); pythonEvidence.set(result.id, { verified: true }); }
catch (error) {
pythonEvidence.set(result.id, { verified: false, error: error.message });
requiresVerification.push({ id: result.id, tool: 'python_check', status: 'evidence_unverified' });
}
}
}
const sets = [...this.store.core.change_set.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
const changeSets = sets.map(set => {
let snapshotVerified = true, snapshotError = null;
try { new ChangeSetManager(this.store).snapshots(session, set); } catch (error) { snapshotVerified = false; snapshotError = error.message; }
return { id: set.id, taskId: set.taskId, runId: set.runId, status: set.status, fingerprint: set.fingerprint,
paths: set.files.map(file => file.path), snapshotVerified, snapshotError, requiresVerification: !!set.requiresVerification,
summary: set.summary, verifiedAt: set.verifiedAt ?? null, finishedAt: set.finishedAt ?? null };
});
requiresVerification.push(...changeSets.filter(set => set.requiresVerification || !set.snapshotVerified)
.map(set => ({ id: set.id, tool: 'change_set', status: set.status })));
const commits = jobs.filter(value => value.status === 'completed' && value.commit && value.sourceFingerprint === inspection.sourceFingerprint);
const contextCache = new Map();
const contextPlans = [...this.store.core.context_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === taskId).map(plan => {
let evidenceVerified = true, evidenceError = null;
try {
verifyPlanEvidence(this.store, session, plan, contextCache);
} catch (error) { evidenceVerified = false; evidenceError = error.message; }
return { id: plan.id, runId: plan.runId, stepId: plan.stepId, status: plan.status, requestSha256: plan.requestSha256, requestBytes: plan.requestBytes,
requestArtifactId: plan.requestArtifactId, planArtifactId: plan.artifactId, estimatedInputTokens: plan.estimatedInputTokens,
beforeInputTokens: plan.beforeInputTokens, beforeBytes: plan.beforeBytes, estimateMethod: plan.estimateMethod, budget: plan.budget,
archivedGroups: plan.archivedGroups, retainedMessages: plan.retainedMessages, actualUsage: plan.actualUsage, requestAttempts: plan.requestAttempts,
historyIndexArtifactId: plan.historyIndexArtifactId, historyIndexSha256: plan.historyIndexSha256,
workingSetArtifactId: plan.workingSetArtifactId ?? null, workingSetSha256: plan.workingSetSha256 ?? null,
workingSetEntries: plan.workingSetEntries ?? 0, workingSetViewVersion: plan.workingSetViewVersion ?? 1,
workingRetentionTokens: plan.workingRetentionTokens ?? 0,
latestToolsArtifactId: plan.latestToolsArtifactId ?? null, latestToolsSha256: plan.latestToolsSha256 ?? null,
latestToolsEntries: plan.latestToolsEntries ?? 0, evidenceVerified, evidenceError };
});
requiresVerification.push(...contextPlans.filter(plan => !plan.evidenceVerified).map(plan => ({ id: plan.id, tool: 'model_context', status: 'evidence_unverified' })));
const deliveryReview = pendingDeliveryReview(this.store, session);
const browserVerification = await currentBrowserVerification(this.store, session, inspection);
const planner = new TaskPlanManager(this.store), taskPlan = await planner.inspect(session, { inspection, candidates: false });
const requirements = await new RequirementReview(this.store, { planner }).inspect(session, { inspection });
const taskPlanHistory = [...this.store.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
try { planner.planFor(session, value.id); evidenceVerified = true; } catch (error) { evidenceError = error.message; }
return { id: value.id, runId: value.runId, revision: value.revision, parentPlanId: value.parentPlanId, steps: value.steps,
requirementsSha256: value.requirementsSha256, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256, evidenceVerified, evidenceError };
});
const taskProofs = [...this.store.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === taskId)
.map(value => ({ id: value.id, runId: value.runId, planId: value.planId, stepKey: value.stepKey, status: value.status, evidenceId: value.evidenceId,
outcome: value.outcome, error: value.error, createdAt: value.createdAt, contractArtifactId: value.contractArtifactId, contractSha256: value.contractSha256 }));
const browserChecks = [...this.store.core.browser_job.values()].filter(value => value.sessionId === session.id && value.taskId === taskId).map(value => {
let evidenceVerified = false, evidenceError = null;
if (value.resultArtifactId) { try { verifyBrowserJob(this.store, session, value); evidenceVerified = true; } catch (error) { evidenceError = error.message; } }
if (value.requiresVerification || value.resultArtifactId && !evidenceVerified) requiresVerification.push({ id: value.id, tool: 'browser_check', status: 'evidence_unverified' });
return { id: value.id, taskId: value.taskId, runId: value.runId, planId: value.planId, status: value.status, summary: value.summary,
sourceFingerprint: value.sourceFingerprint, buildSha256: value.buildSha256, assertions: value.assertions, screenshots: value.screenshots,
resultArtifactId: value.resultArtifactId ?? null, resultSha256: value.resultSha256 ?? null, cleanup: value.cleanup ?? null,
requiresVerification: !!value.requiresVerification, evidenceVerified, evidenceError, acknowledgedAt: value.acknowledgedAt ?? null };
});
if (taskId !== session.taskId || runId !== session.runId) throw Object.assign(new Error('核对页面结果期间任务已切换,请重新生成报告。'), { status: 409 });
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'
: browserVerification.required && browserVerification.status !== 'passed' ? 'needs_browser_checks'
: 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],
project: { id: project.id, name: project.name, root: project.root }, workspace: projectWorkspaceIdentity(project),
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,
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,
checkPolicy: contract.checks === 'skip' ? 'not_requested' : contract.checks,
gitOutcome: { status: !fileDelivery.newChanges && hasFileScope ? 'no_new_changes' : commits.length ? 'committed' : 'uncommitted',
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,
consumption: structuredClone(value.consumption ?? []),
...(value.workspaceIdentity ? { workspaceIdentity: value.workspaceIdentity } : {}) })),
usage: { ...task.usage, priceStatus: 'not_configured', amount: null, currency: null },
changes: changes.map(value => ({ id: value.id, path: value.path, status: value.status, reason: value.reason, baseSha256: value.baseSha256,
sha256: value.sha256, changeSetId: value.changeSetId ?? null, appliedAt: value.appliedAt ?? null, additions: value.additions, deletions: value.deletions })),
changeSets,
...(deliveryReview ? { deliveryReview: { planId: deliveryReview.id, status: 'pending', paths: deliveryReview.paths } } : {}),
contextPlans,
browserVerification, browserChecks,
taskPlan, taskPlanHistory, taskProofs,
checks: checkJobs.map(value => ({ id: value.id, status: value.status, planId: value.planId,
...(value.environment ? { environment:value.environment } : {}),
contractArtifactId: this.store.core.check_plan.get(value.planId)?.contractArtifactId ?? null,
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
sourceFingerprint: value.sourceFingerprint ?? null, startedAt: value.startedAt, finishedAt: value.finishedAt,
results: value.results.map(result => ({ ...result, logExcerpt: undefined,
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null,
...(result.engine === 'python' ? { pythonEvidence: pythonEvidence.get(result.id) ?? { verified: false, state: 'historical_or_not_passed' } } : {}) })) })),
verifiedCheckJobId: check?.id ?? null,
deliveries: jobs.map(value => ({ id: value.id, status: value.status, commit: value.commit ?? null, expectedCommit: value.expectedCommit ?? null,
parent: value.parent, sourceFingerprint: value.sourceFingerprint, paths: value.paths, summary: value.summary, requiresVerification: !!value.requiresVerification,
workspacePreserved: value.workspacePreserved ?? null, indexPreserved: value.indexPreserved ?? null, finishedAt: value.finishedAt })),
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' });
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 };
}
}
export function renderDeliveryMarkdown(report) {
const lines = ['# 项目交付报告', '', '**' + report.statusLabel + '**', '', '生成时间:' + report.generatedAt, '',
'项目:' + report.project.name, '项目目录:' + report.project.root, 'Task:' + report.task.id, '',
'## 任务与范围', '', report.task.goal, '',
'源码指纹:' + report.source.fingerprint, '当前Git HEAD:' + (report.source.gitHead ?? '未启用'),
'分支:' + (report.source.branch ?? '未记录'), '', report.task.note, '', '## 改动', '',
'| 文件 | 状态 | SHA256 |', '| --- | --- | --- |'];
for (const change of report.changes) lines.push('| ' + [change.path, change.status, change.sha256].map(escapeCell).join(' | ') + ' |');
if (report.fileResults?.length) {
lines.push('', '## 当前已有成果', '', '成果核对保存当前文件与采用原因;不代表本任务新写入、测试通过或业务验收通过。', '',
'| 文件 | 当前核对 | 原文件 SHA256 | 来源 Task / Run | 凭据 |', '| --- | --- | --- | --- | --- |');
for (const result of report.fileResults) {
for (const file of result.files) lines.push('| ' + [file.path, result.verification, file.sha256,
file.origin ? file.origin.taskId + ' / ' + file.origin.runId + ' · 原SHA ' + file.origin.sha256 : '本次读取已有文件', result.contractArtifactId].map(escapeCell).join(' | ') + ' |');
lines.push('', '采用原因:' + result.reason, ...(result.error ? ['', result.error] : []));
}
}
if (report.gitOutcome) lines.push('', report.gitOutcome.note);
if (report.checkPolicy === 'not_requested') lines.push('', '测试约定:按用户要求未自动测试;不记作测试通过。');
if (report.requirements) {
lines.push('', '## 用户要求与证据', '', report.requirements.note, '', '复核状态:' + report.requirements.status,
'', '| 要求 / 条件 | 用户原文来源 | 修订 | 复核状态 | 原证据 / 下一步 |', '| --- | --- | --- | --- | --- |');
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(' | ') + ' |');
if (report.requirements.unreviewed_sources?.length) lines.push('', '尚未审阅的用户来源:' + report.requirements.unreviewed_sources.join('、'));
if (report.requirements.error) lines.push('', report.requirements.error);
}
if (report.turnObservations?.some(row => row.recorded || row.error)) {
lines.push('', '## 单轮观察(仅记录)', '', '外显事实分类不改变停止、权限或预算;不是自主交付收益证明。', '',
'| Run / 轮次 | 观察 | 新读取字符 | 重复读取 | 新失败 / 重复失败 | 原收据核对 |', '| --- | --- | --- | --- | --- | --- |');
for (const run of report.turnObservations) if (run.error) lines.push('', escapeCell(run.runId + ':' + (typeof run.error === 'string' ? run.error : '观察未能记录,原执行结果保留。')), '');
for (const run of report.turnObservations) for (const turn of run.turns) lines.push('| ' + [run.runId + ' / ' + (turn.stepIndex ?? turn.phase),
turn.classification, turn.delta.read_characters, turn.delta.repeated_reads, turn.delta.new_failures + ' / ' + turn.delta.repeated_failures,
run.evidence_verified ? '原字节已核对' : run.error].map(escapeCell).join(' | ') + ' |');
}
if (report.taskPlan?.configured) {
lines.push('', '## 执行计划与实际核验', '', '计划:' + (report.taskPlan.plan_id ?? '无法核对'),
'核验:' + (report.taskPlan.verified_steps ?? 0) + '/' + (report.taskPlan.total_steps ?? 0), '',
'| 步骤 / 通过条件 | 状态 | 前置依赖 | 原证据 |', '| --- | --- | --- | --- |');
for (const step of report.taskPlan.steps) lines.push('| ' + [step.title + ' / ' + step.criterion, step.status,
step.depends_on.join(', ') || '无', step.evidence?.id ?? '尚未核验'].map(escapeCell).join(' | ') + ' |', ...(step.error ? ['', step.error, ''] : []));
if (report.taskPlan.error) lines.push('', report.taskPlan.error);
lines.push('', '任务计划固定实际操作范围;业务语义验收另行记录。', '', '### 原计划与核验工件', '');
for (const plan of report.taskPlanHistory ?? []) lines.push('计划 ' + plan.revision + ':' + plan.contractArtifactId + ' · SHA256 ' + plan.contractSha256);
for (const proof of report.taskProofs ?? []) lines.push('步骤 ' + proof.stepKey + ' · ' + proof.status + ':' + proof.contractArtifactId + ' · SHA256 ' + proof.contractSha256);
}
if (report.workspace?.kind === 'managed-worktree') lines.push('', '## 独立开发工作区', '', '工作区:' + report.workspace.workspaceId,
'来源项目:' + report.workspace.sourceProjectId, '来源目录:' + report.workspace.sourceRoot,
'起始提交:' + report.workspace.baseCommit, '独立分支:' + report.workspace.branch,
'交付保存在此分支;合并回来源项目需要另行审查。');
if (report.changeSets?.length) {
lines.push('', '## 多文件变更集', '', '| 批次 | 实际状态 | 快照 | 审查指纹 |', '| --- | --- | --- | --- |');
for (const set of report.changeSets) lines.push('| ' + [set.id, set.status, set.snapshotVerified ? 'SHA256校验通过' : '需要核对', set.fingerprint].map(escapeCell).join(' | ') + ' |',
'', set.summary ?? '', '');
}
lines.push('', '## 实际检查', '', '| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |', '| --- | --- | --- | --- | --- |');
for (const job of report.checks) for (const result of job.results) lines.push('| ' + [job.id.slice(0, 8) + ' / ' + result.command,
job.stale ? '源码已变化 / ' + result.status : result.status, result.exitCode ?? '未知', result.tests ? result.tests.passed + '/' + result.tests.total : '不适用或未知', result.logSha256 ?? '未知'].map(escapeCell).join(' | ') + ' |');
const environments=report.checks.filter(job=>job.environment);
if(environments.length){
lines.push('','### 实际依赖环境','','| 检查记录 | Node / npm | 声明与运行时输入 | 实际依赖字节 | 准备记录 |','| --- | --- | --- | --- | --- |');
for(const job of environments)lines.push('| '+[job.id,job.environment.runtime.node.version+' / '+(job.environment.runtime.npm?.version??'未知'),job.environment.dependencyInputs,job.environment.installed.sha256??'没有依赖目录',job.environment.preparation?.jobId??'已有环境,无所属准备凭据'].map(escapeCell).join(' | ')+' |');
lines.push('','环境准备只记录安装;以上工程检查结果另行判定。');
}
const pythonResults = report.checks.flatMap(job => job.results.filter(result => result.python));
if (pythonResults.length) {
lines.push('', '### Python实际执行', '', '| 检查 | 解释器 | 版本 | 结构化结果SHA256 |', '| --- | --- | --- | --- |');
for (const result of pythonResults) lines.push('| ' + [result.command, result.python.runtime.executable, result.python.runtime.version, result.metricsSha256 ?? '未返回'].map(escapeCell).join(' | ') + ' |',
'', '运行器SHA256:' + result.python.runner.sha256, '封存输入SHA256:' + result.python.inputSha256,
...(result.compilation ? ['语法编译:' + result.compilation.compiled + '/' + result.compilation.total + ' 个源码文件。'] : []));
}
if (report.browserChecks?.length || report.browserVerification?.required) {
lines.push('', '## 实际页面验收', '', '当前页面验收:' + report.browserVerification.status, '', '| 浏览器Job | 状态 | 实际断言 | 原结果SHA256 |', '| --- | --- | --- | --- |');
for (const check of report.browserChecks ?? []) {
lines.push('| ' + [check.id, check.status, check.assertions.passed + '/' + check.assertions.total, check.evidenceVerified ? check.resultSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
for (const image of check.screenshots) lines.push('', '截图 ' + image.label + ' · ' + image.width + '×' + image.height + ' · SHA256 ' + image.sha256);
}
lines.push('', '浏览器页面属于工程输入;观察或截图不代替断言,源码或构建变化后需要重新检查。', '');
}
lines.push('', '## Git交付', '');
if (report.deliveryReview) lines.push('Git提交预览已保存,等待确认。计划:' + report.deliveryReview.planId, '');
if (!report.deliveries.length) lines.push('尚无内置Git提交记录。');
for (const delivery of report.deliveries) lines.push('- ' + delivery.status + ' · ' + (delivery.commit ?? '实际结果未确认') + ' · ' + delivery.paths.join(', '),
' ' + (delivery.summary ?? ''));
lines.push('', '## 模型与用量', '', 'Run型号为启动配置;每次实际发送与返回型号见下表。型号标识或登记映射不认证底层模型权重。', '', '| Run | 启动型号 | 状态 | 已报告tokens |', '| --- | --- | --- | --- |');
for (const run of report.runs) lines.push('| ' + [run.id, run.model?.mode === 'demo' ? '离线固定演示' : run.model?.model ?? '未记录',
run.status, run.usage?.totalTokens ?? 0].map(escapeCell).join(' | ') + ' |');
lines.push('', '| 尝试 | 请求型号 | 上游报告型号 | 核对结果 | 原响应 SHA256 |', '| --- | --- | --- | --- | --- |');
for (const run of report.runs) {
for (const receipt of run.consumption ?? []) {
const identity = receipt.modelIdentity;
lines.push('| ' + [receipt.attemptId, identity?.requestedModel ?? receipt.model ?? '未记录', identity?.reportedModels?.join(', ') || '未记录',
modelIdentityLabel(identity), identity?.responseSource?.sha256 ?? '未记录'].map(escapeCell).join(' | ') + ' |');
if (identity?.mapping) lines.push('', '用户登记的映射依据:' + escapeCell(identity.mapping.source));
}
if (!run.consumption?.length && run.usage?.requests) lines.push('', 'Run ' + run.id + ' 的历史记录未保存返回型号核对,不能从启动配置补推。');
}
lines.push('', '累计已报告:' + (report.usage.totalTokens ?? 0) + ' tokens;未报告请求:' + (report.usage.unknownRequests ?? 0) + '。费用:未知。', '', '## 尚待确认', '');
if (report.contextPlans?.length) {
const at = lines.length - 2;
const contextLines = ['', '## 请求上下文', '', '| 请求 | 状态 | 输入估算 | 已报告输入 | 省略组 | 正文SHA256校验 |', '| --- | --- | --- | --- | --- | --- |'];
for (const plan of report.contextPlans) contextLines.push('| ' + [plan.id, plan.status, plan.estimatedInputTokens,
plan.actualUsage?.prompt_tokens ?? '未返回', plan.archivedGroups, plan.evidenceVerified ? plan.requestSha256 : '需要核对'].map(escapeCell).join(' | ') + ' |');
lines.splice(at, 0, ...contextLines, '');
}
for (const value of report.requiresVerification) lines.push('- ' + value.tool + ' · ' + value.id + ' · ' + value.status);
for (const note of report.limitations) lines.push('- ' + note);
return lines.join('\n') + '\n';
}