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;
}
+97
View File
@@ -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;
}
+11
View File
@@ -10,6 +10,7 @@ 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';
@@ -141,6 +142,8 @@ export class DeliveryReporter {
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',
@@ -212,6 +215,14 @@ export function renderDeliveryMarkdown(report) {
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('', '## 单轮观察(仅记录)', '', '外显事实分类不改变停止、权限或预算;不是自主交付收益证明。');
for (const run of report.turnObservations) if (run.error) lines.push('', escapeCell(run.runId + ':' + (typeof run.error === 'string' ? run.error : '观察未能记录,原执行结果保留。')), '');
lines.push('', '| Run / 轮次 | 观察 | 新读取字符 | 重复读取 | 新失败 / 重复失败 | 原收据核对 |', '| --- | --- | --- | --- | --- | --- |');
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), '',