100 lines
8.2 KiB
JavaScript
100 lines
8.2 KiB
JavaScript
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 verifyTurnProgressReceipt(store, session, run, artifactId) {
|
|
const owned = row => row.sessionId === session.id && row.projectId === session.projectId && row.taskId === run.taskId && row.runId === run.id;
|
|
if (run.sessionId !== session.id || run.projectId !== session.projectId) throw new Error('单轮观察运行归属不一致。');
|
|
const artifact = store.owned('artifact', artifactId, session.id);
|
|
if (!owned(artifact) || artifact.kind !== 'turn-progress-shadow') throw new Error('单轮观察原收据归属不一致。');
|
|
const original = JSON.parse(store.artifactStore.read(artifact)), tools = [];
|
|
if (original.taskId !== run.taskId || original.runId !== run.id) 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('单轮观察的工具或原结果来源变化。');
|
|
const value = JSON.parse(store.artifactStore.read(result));
|
|
tools.push({ ...toolProgressFacts(record, value, result, record.progressFailureCategory),
|
|
success: record.state === 'completed' && !record.requiresVerification && !['failed', 'error', 'denied', 'unknown', 'interrupted', 'unverified'].includes(value.status) });
|
|
}
|
|
return { observation: original, tools, artifact };
|
|
}
|
|
|
|
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 {
|
|
if (view.turns.length !== view.artifact_ids.length) throw new Error('单轮观察与原收据数量不一致。');
|
|
for (let i = 0; i < view.turns.length; i++) {
|
|
const { observation: original } = verifyTurnProgressReceipt(store, session, run, view.artifact_ids[i]);
|
|
if (planHash(original) !== planHash(view.turns[i])) throw new Error('单轮观察与原收据不一致。');
|
|
}
|
|
} catch { view.evidence_verified = false; view.error = '单轮观察的原收据或工具结果待核对;不用于交付通过判定。'; }
|
|
return view;
|
|
}
|