diff --git a/apps/web/client/draft.ts b/apps/web/client/draft.ts index 61cccbf9..60f48ae6 100644 --- a/apps/web/client/draft.ts +++ b/apps/web/client/draft.ts @@ -52,7 +52,7 @@ export function editableTaskDraft(draft: TaskDraft, unresolved = false, fixedEnv ? draft : { ...draft, environment }; } -const archiveSchemas = ['theorem-os.web-export.v1', 'theorem-os.web-archive.v1']; +const archiveSchemas = ['theorem-os.web-export.v1', 'theorem-os.web-archive.v1', 'theorem-os.web-archive.v2']; const maximumFileBytes = 16 * 1024 * 1024; const encoder = new TextEncoder(); const editableNumber = /^[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d*)?|\.)?$/; diff --git a/apps/web/client/trajectory.ts b/apps/web/client/trajectory.ts index 8181e2b6..7d73354b 100644 --- a/apps/web/client/trajectory.ts +++ b/apps/web/client/trajectory.ts @@ -126,15 +126,25 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] { if (found) found.used = true; return found; }; - /** An assembled check covers every target; the copies stored under each goal task are one check. */ + /** Match the batch outcome and prefer a receipt that explains why it passed or failed. */ const claimAssembly = (at: number, passed: boolean) => { - const found = claim(at, slot => slot.check.passed === passed && (!targets.length || targets.every(name => slot.check.theorems.includes(name)))); - if (found) for (let position = firstAt(found.check.at); position < slots.length && slots[position]!.check.at === found.check.at; position++) - if (slots[position]!.version.commit === found.version.commit) slots[position]!.used = true; + const found = claim(at, slot => slot.check.originalProblemPassed === passed && slot.check.passed === passed) ?? + claim(at, slot => slot.check.originalProblemPassed === passed) ?? + claim(at, slot => slot.check.originalProblemPassed === undefined && slot.check.passed === passed && + (!targets.length || targets.every(name => slot.check.theorems.includes(name)))); + // Older pages may still have a complete copy of the same batch under each goal. + if (found && found.check.originalProblemPassed === undefined) { + for (let position = firstAt(found.check.at); position < slots.length && slots[position]!.check.at === found.check.at; position++) { + const slot = slots[position]!; + if (slot.version.commit === found.version.commit && slot.check.originalProblemPassed === undefined) slot.used = true; + } + } return found; }; + const forTask = (slot: Slot, taskId: string, passed?: boolean) => slot.version.taskId === taskId && + slot.check.originalProblemPassed === undefined && (passed === undefined || slot.check.passed === passed); const latestCheck = (taskId: string, at: number) => { - for (let position = firstAt(at + 1) - 1; position >= 0; position--) if (slots[position]!.version.taskId === taskId) return slots[position]; + for (let position = firstAt(at + 1) - 1; position >= 0; position--) if (forTask(slots[position]!, taskId)) return slots[position]; }; const refOf = (slot: Slot | undefined): TrajectoryRef | undefined => slot && { version: slot.version, check: slot.check }; const deliveryFor = proofDeliveryLookup(data.deliveries.values()); @@ -160,7 +170,7 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] { // A reused check is the latest recorded one of the task; it is not claimed again. slot = latestCheck(taskId, at); passed ??= event.type === 'task_failure_check_reused' ? false : slot?.check.passed; - } else slot = claim(at, item => item.version.taskId === taskId && (passed === undefined || item.check.passed === passed)); + } else slot = claim(at, item => forTask(item, taskId, passed)); if (passed === undefined) return; const ref = refOf(slot), outcome: TrajectoryOutcome = passed ? details.conditional ? 'conditional' : 'passed' : 'failed'; const previous = lastAttempt.get(taskId); @@ -172,14 +182,14 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] { const taskId = event.details?.taskId; if (!taskId) return; // Integrating checks the task on the main line; that check belongs to this step, not to a new attempt. - claim(at, item => item.version.taskId === taskId && item.check.passed); + claim(at, item => forTask(item, taskId, true)); const step = lastAttempt.get(taskId); if (step) step.integrated = true; }; const recheck = (event: WebEvent, at: number) => { const taskId = event.details?.taskId, passed = event.details?.passed; if (!taskId) return; - const slot = claim(at, item => item.version.taskId === taskId && (passed === undefined || item.check.passed === passed)); + const slot = claim(at, item => forTask(item, taskId, passed)); const result: RecheckResult = { taskId, passed: passed ?? slot?.check.passed ?? false, ref: refOf(slot), ...(event.type === 'task_conditional_recheck_finished' ? { conditional: true } : {}) }; const last = steps.at(-1); @@ -253,10 +263,10 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] { inputs.sort((a, b) => a.at - b.at || a.order - b.order || a.sequence - b.sequence); for (const item of inputs) item.run(); - // Every unconsumed check is an attempt of its own, even when the same commit was checked more than once. + // Every unconsumed task check is an attempt of its own, even when the same commit was checked more than once. // Assembly, integration and rechecks already consumed their slots; reusing a receipt does not consume a new check. for (const { version, check, used } of slots) { - if (used) continue; + if (used || check.originalProblemPassed !== undefined) continue; steps.push({ kind: 'attempt', at: check.at, taskId: version.taskId, workerId: owners.get(version.taskId), number: 0, outcome: check.passed ? 'passed' : 'failed', ref: { version, check }, reused: false, integrated: false, note: noteOf(version.taskId, { version, check }) }); } diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index 619012d2..5284f1cd 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -15,6 +15,7 @@ import { WebKnowledgeService } from './knowledgeService'; import { freezeModuleConfiguration } from './moduleRegistry'; import { WebStorageError } from './storage'; import { isAcceptedRun, isStatementReviewed } from './presentation'; +import { projectStoredObservationChecks } from './observationChecks'; type Job = { owner: string; run: WebRun; input: WebRunInput; provider: WebWorkerProvider; controller: AbortController; formalization?: WorkerInput['formalization']; @@ -327,7 +328,7 @@ export class WebJobs { } if (actualHarness) job.run.agentHarness = { ...actualHarness }; job.run.solverAttempt = { solverRunId: observation.solverRunId, round: current?.round ?? 0, sequence: observation.sequence }; - job.run.observation = observation; + job.run.observation = projectStoredObservationChecks(observation); job.run.updatedAt = observation.observedAt; this.persist(job.run); } diff --git a/apps/web/observationChecks.ts b/apps/web/observationChecks.ts new file mode 100644 index 00000000..eda15e94 --- /dev/null +++ b/apps/web/observationChecks.ts @@ -0,0 +1,38 @@ +import type { WebCheckReceipt, WebObservation } from './collaboration'; + +/** Earlier frames copied each original-goal receipt onto every goal in its batch. */ +export function projectStoredObservationChecks(observation: WebObservation): WebObservation { + const targets = observation.inspection.problem?.targets ?? []; + if (targets.length < 2 || observation.checks.length < 2) return observation; + + const targetByName = new Map(targets.map(target => [target.theoremName, target])); + const taskKey = (id: string, version: string) => `${id}\0${version}`; + const goalTargets = new Map(observation.inspection.tasks.filter(task => task.kind === 'goal' && task.theorem) + .map(task => [taskKey(task.id, task.version), targetByName.get(task.theorem!)])); + const assignedTarget = (check: WebCheckReceipt) => goalTargets.get(taskKey(check.taskId, check.taskVersion)); + const receiptKey = (check: WebCheckReceipt) => + `${check.id}\0${check.commit}\0${check.sourceDigest}\0${check.environmentDigest}`; + + const copied = new Set(); + for (const check of observation.checks) { + const assigned = assignedTarget(check), { theoremName, proofPath } = check.record; + if (!assigned || typeof theoremName !== 'string' || theoremName === assigned.theoremName) continue; + const checked = targetByName.get(theoremName); + if (checked && checked.proofPath === proofPath) copied.add(receiptKey(check)); + } + if (!copied.size) return observation; + + const checks = observation.checks.flatMap(check => { + const target = assignedTarget(check); + if (!target || !copied.has(receiptKey(check))) return [check]; + const { record } = check; + if (record.theoremName !== target.theoremName || record.proofPath !== target.proofPath) return []; + // The per-target verdict must bind to this frozen declaration and this exact commit. + const passed = record.status === 'kernel_verified' && record.claim === 'statement' && + record.targetCommit === check.commit && Boolean(target.declarationHash) && + record.sourceDeclarationHash === target.declarationHash; + if (typeof record.passed !== 'boolean') return [check]; + return [{ ...check, record: { ...record, originalProblemPassed: record.passed, passed: passed || record.passed } }]; + }); + return { ...observation, checks }; +} diff --git a/apps/web/observationSources.ts b/apps/web/observationSources.ts index 07f5ba3c..752fece0 100644 --- a/apps/web/observationSources.ts +++ b/apps/web/observationSources.ts @@ -2,12 +2,12 @@ import { mathDigest } from '../../src/math/mathRuntimeIo'; import type { WebObservation, WebTaskSource } from './collaboration'; type SourceReference = { sha256: string }; -type ObservationWithSource = Omit & { - sources: (Omit & { - source: Text; dependencySources?: { file: string; source: Text }[]; - })[]; +type TaskSourceWithText = Omit & { + source: Text; dependencySources?: { file: string; source: Text }[]; }; +type ObservationWithSource = Omit & { sources: TaskSourceWithText[] }; +export type CompactWebTaskSource = TaskSourceWithText; export type CompactWebObservation = ObservationWithSource; export type WorkerObservationFrame = { type: 'observation'; @@ -27,9 +27,10 @@ function mapSources(observation: ObservationWithSource, map: (so }; } -export function compactObservation(observation: WebObservation, save: (digest: string, text: string) => void): CompactWebObservation { +/** Share text hashes across a batch of observations without reading or hashing unchanged text again. */ +export function observationCompactor(save: (digest: string, text: string) => void): (observation: WebObservation) => CompactWebObservation { const digests = new Map(); - return mapSources(observation, (source: string) => { + return observation => mapSources(observation, (source: string) => { let sha256 = digests.get(source); if (!sha256) { sha256 = mathDigest(source); @@ -40,6 +41,10 @@ export function compactObservation(observation: WebObservation, save: (digest: s }); } +export function compactObservation(observation: WebObservation, save: (digest: string, text: string) => void): CompactWebObservation { + return observationCompactor(save)(observation); +} + /** Legacy records inline their sources. References must all resolve before handing the observation to a consumer. */ export function hydrateObservation(observation: WebObservation | CompactWebObservation, read: (digest: string) => string | undefined): WebObservation { diff --git a/apps/web/sample.ts b/apps/web/sample.ts index d6b0cb09..a1938014 100644 --- a/apps/web/sample.ts +++ b/apps/web/sample.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; import type { WebObservation } from './collaboration'; +import { projectStoredObservationChecks } from './observationChecks'; import { webArchive } from './storage'; import { webAgentActionLimits, webSampleRunId, type WebAgentAction, type WebEvent, type WebRun } from './shared'; import { recordedTrajectory, trajectoryPage, trajectoryQuery, trajectoryVersion, trajectoryVersionDetail, trajectoryVersionQuery, type TrajectoryIndex } from './trajectory'; @@ -25,7 +26,10 @@ const readOnly: WebSampleResponse = { status: 403, body: { error: '示例运行 export function loadWebSample(file = new URL('./sample/run.json', import.meta.url)): WebSampleFile | undefined { try { const sample = JSON.parse(fs.readFileSync(file, 'utf8')) as WebSampleFile; - return sample.schema === webSampleSchema && sample.run?.id === webSampleRunId ? sample : undefined; + if (sample.schema !== webSampleSchema || sample.run?.id !== webSampleRunId) return undefined; + sample.observations = sample.observations.map(projectStoredObservationChecks); + if (sample.run.observation) sample.run.observation = projectStoredObservationChecks(sample.run.observation); + return sample; } catch { return undefined; } } diff --git a/apps/web/storage.ts b/apps/web/storage.ts index b39c47fe..f12365f6 100644 --- a/apps/web/storage.ts +++ b/apps/web/storage.ts @@ -5,7 +5,9 @@ import { canonicalMathJson, mathDigest, syncMathDirectory, writeMathFrozen } fro import type { WebArchive, WebCheckReceipt, WebCommandResult, WebObservation, WebTaskSource } from './collaboration'; import type { WebAccountIdentity, WebAgentAction, WebEvent, WebExplanation, WebRun, WorkerExplanationCheckpoint } from './shared'; import type { WebShareSnapshot } from './share'; -import { compactObservation, hydrateObservation, type CompactWebObservation } from './observationSources'; +import { compactObservation, hydrateObservation, observationCompactor, + type CompactWebObservation, type CompactWebTaskSource } from './observationSources'; +import { projectStoredObservationChecks } from './observationChecks'; export type WebCreation = { schema: 'theorem-os.web-creation.v1'; requestId: string; digest: string }; type StoredRun = { owner: string; run: WebRun; creation?: WebCreation }; @@ -14,18 +16,28 @@ type ObservationRecord = WebObservation | CompactWebObservation; type StoredExplanationCheckpoint = { binding: string; checkpoint: WorkerExplanationCheckpoint }; export type StoredWebSession = { id: string; csrf: string; touchedAt: number; account?: WebAccountIdentity & { id: string }; passwordResetUntil?: number }; -export type StoredWebArchive = { - schema: 'theorem-os.web-archive.v1'; - summary: WebArchive; +type ArchiveEvidence = { run: WebRun; observations: WebObservation[]; sources: WebTaskSource[]; +}; +type ArchiveRecords = { + summary: WebArchive; checks: WebCheckReceipt[]; events: WebEvent[]; /** Older saved archives did not contain the separately stored Agent actions. */ actions?: WebAgentAction[]; - commands: WebCommandResult[]; }; +type StoredWebArchiveV1 = ArchiveRecords & ArchiveEvidence & { schema: 'theorem-os.web-archive.v1'; commands: WebCommandResult[] }; +export type StoredWebArchiveV2 = ArchiveRecords & { + schema: 'theorem-os.web-archive.v2'; + run: Omit & { observation?: CompactWebObservation }; + observations: CompactWebObservation[]; + sources: CompactWebTaskSource[]; + sourceBlobs: Record; + commands: (Omit & { observation?: CompactWebObservation })[]; +}; +export type StoredWebArchive = StoredWebArchiveV1 | StoredWebArchiveV2; export type StoredWebShare = { token: string; createdAt: string; snapshot: WebShareSnapshot }; type ShareIndex = { ownerDigest: string; runId: string }; @@ -48,8 +60,16 @@ const publicRecord = (value: T): T => JSON.parse(JSON.stringify(value, /** All retained process evidence, with coverage of the recording rather than a claim of fresh proof acceptance. */ export function webArchive(run: WebRun, records: { observations: WebObservation[]; events: WebEvent[]; - actions: WebAgentAction[]; commands: WebCommandResult[] }, catalogDigest?: string): StoredWebArchive { - const { observations, events, actions, commands } = records; + actions: WebAgentAction[]; commands: WebCommandResult[] }, catalogDigest?: string): StoredWebArchiveV2 { + const { events, actions, commands } = records; + const sourceBlobs: Record = {}; + const referenceSources = observationCompactor((digest, source) => { sourceBlobs[digest] = source; }); + const compact = (frame: WebObservation) => referenceSources(projectStoredObservationChecks(frame)); + const observations = records.observations.map(compact); + const { observation, ...runFields } = run; + const archivedRun = { ...runFields, ...(observation ? { observation: compact(observation) } : {}) }; + const archivedCommands = commands.map(({ observation: recorded, ...command }) => + ({ ...command, ...(recorded ? { observation: compact(recorded) } : {}) })); const unique = (items: T[]) => [...new Map(items.map(item => [mathDigest(encoded(item)), item])).values()]; const sources = unique(observations.flatMap(item => item.sources)), checks = unique(observations.flatMap(item => item.checks)); const complete = (items: { sequence: number }[], expected: number) => items.length === expected @@ -67,10 +87,22 @@ export function webArchive(run: WebRun, records: { observations: WebObservation[ events: events.length, observations: observations.length, actions: actions.length, commands: commands.length, droppedActions: run.actions?.dropped ?? 0, sources: sources.length, checks: checks.length, coverage, ...(catalogDigest ? { catalogDigest } : {}) }; - const payload = publicRecord({ schema: 'theorem-os.web-archive.v1' as const, run, observations, sources, checks, events, actions, commands }); + const payload = publicRecord({ + schema: 'theorem-os.web-archive.v2' as const, run: archivedRun, observations, sources, sourceBlobs, checks, events, actions, + commands: archivedCommands, + }); return { ...payload, summary: { ...identity, digest: mathDigest(encoded({ ...payload, identity })) } }; } +/** Consumers that need inline observations can read either archive format. */ +export function readWebArchiveObservations(archive: StoredWebArchive): Pick { + if (archive.schema === 'theorem-os.web-archive.v1') return { run: archive.run, observations: archive.observations }; + const { observation, ...run } = archive.run; + const hydrate = (frame: CompactWebObservation) => hydrateObservation(frame, digest => archive.sourceBlobs[digest]); + return { run: { ...run, ...(observation ? { observation: hydrate(observation) } : {}) }, + observations: archive.observations.map(hydrate) }; +} + /** Optional web-only persistence. An omitted root keeps the same API in memory for disposable fixtures. */ export class WebStorage { readonly root?: string; @@ -246,13 +278,13 @@ export class WebStorage { } private hydrateObservations(directory: string[], records: ObservationRecord[]): WebObservation[] { const sources = new Map(); - return records.map(record => hydrateObservation(record, digest => { + return records.map(record => projectStoredObservationChecks(hydrateObservation(record, digest => { const cached = sources.get(digest); if (cached !== undefined) return cached; const text = this.getRecord([...directory, 'source-blobs', `${digest}.json`]); if (text !== undefined) sources.set(digest, text); return text; - })); + }))); } private readObservation(directory: string[], sequence: number): WebObservation | undefined { const observation = this.getRecord([...directory, 'observations', `${sequence}.json`]); @@ -370,7 +402,7 @@ export class WebStorage { return records; } - exportRun(owner: string, run: WebRun, catalogDigest?: string): StoredWebArchive { + exportRun(owner: string, run: WebRun, catalogDigest?: string): StoredWebArchiveV2 { if (!this.getRun(owner, run.id)) throw new WebStorageError(404, '运行不存在或不属于当前会话。'); return webArchive(run, { observations: this.listObservations(owner, run.id), events: this.listEvents(owner, run.id), actions: this.listActionsAfter(owner, run.id, 0, Number.MAX_SAFE_INTEGER), commands: this.listCommands(owner, run.id) }, catalogDigest); diff --git a/apps/web/trajectory.ts b/apps/web/trajectory.ts index 1c1b6dbf..7f35bc91 100644 --- a/apps/web/trajectory.ts +++ b/apps/web/trajectory.ts @@ -30,8 +30,9 @@ export const trajectoryLimits = { const textLimits = { guidance: 2_000, headline: 160 } as const; const readLimits = { events: 5_000, observations: 40 } as const; -/** One Lean check of a version; receipts recorded at the same verification time (one per target theorem) form one check. */ -export type TrajectoryCheck = { at: number; passed: boolean; status: string; receiptIds: string[]; theorems: string[]; headline?: string; observation: number }; +/** One Lean check of a task version. An original-problem check separately records the outcome of the whole batch. */ +export type TrajectoryCheck = { at: number; passed: boolean; status: string; receiptIds: string[]; theorems: string[]; headline?: string; observation: number; + originalProblemPassed?: boolean }; /** A task's code at one commit, with every recorded check of it. */ export type TrajectoryVersion = { key: string; taskId: string; commit: string; file?: string; source?: number; firstAt: number; checks: TrajectoryCheck[]; revision: number; @@ -136,11 +137,13 @@ function foldCheck(index: TrajectoryIndex, receipt: WebCheckReceipt, observation trim(index, 'versions', index.versions, trajectoryLimits.versions); if (!index.versions.has(key)) return; } - let check = version.checks.find(item => item.at === at); + const originalProblemPassed = typeof record.originalProblemPassed === 'boolean' ? record.originalProblemPassed : undefined; + let check = version.checks.find(item => item.at === at && item.originalProblemPassed === originalProblemPassed); if (check?.receiptIds.includes(receipt.id)) return; if (!check) { if (version.checks.length >= trajectoryLimits.checks) version.checks.splice(1, 1); // The first check stays: it is the attempt itself. - check = { at, passed: true, status: 'kernel_verified', receiptIds: [], theorems: [], observation }; + check = { at, passed: true, status: 'kernel_verified', receiptIds: [], theorems: [], observation, + ...(originalProblemPassed === undefined ? {} : { originalProblemPassed }) }; version.checks.push(check); version.checks.sort((a, b) => a.at - b.at); version.firstAt = Math.min(version.firstAt, at); diff --git a/apps/web/workerBridge.ts b/apps/web/workerBridge.ts index 03f1daa1..0b039988 100644 --- a/apps/web/workerBridge.ts +++ b/apps/web/workerBridge.ts @@ -13,7 +13,7 @@ import { humanGuidanceInputSchema, queueHumanGuidance, readHumanGuidance, withdr import { parseCooperationPlan, taskGroup, taskVersion, type TaskRecord } from '../../src/solver/tasks'; import { allowedKnowledgeFile, buildTheoremKnowledge, validateTheoremKnowledge, type TheoremKnowledgeBase } from '../../src/solver/theoremKnowledge'; import { importKnowledgeRuns } from '../../src/solver/theoremKnowledgeRuns'; -import type { ProofCheck } from '../../src/solver/modules/evidence'; +import { proofReceiptsMatch, type ProofCheck } from '../../src/solver/modules/evidence'; import type { WebCheckReceipt, WebCommand, WebCommandResult, WebObservation, WebTaskSource } from './collaboration'; import type { WorkerMessage } from './shared'; import { projectWebDeclarationArtifacts } from './declarationArtifacts'; @@ -131,15 +131,22 @@ function sourceProjection(state: SolverRunState, directory: string) { sourceBytes += bytes; sourceIds.add(key); } catch { sourcePartial = true; } }; - const addProof = (node: Pick, proof: ProofCheck) => { + const addProof = (node: Pick, proof: ProofCheck, original?: SolverRunState['problem']['targets'][number]) => { const version = taskVersion(node.task); if ('taskDigest' in proof && proof.taskDigest !== version) { sourcePartial = true; checkPartial = true; return; } addSource(node, proof.commit, proof.sourceDigest); for (const receipt of proof.verification.results) { + if (receipt.proofPath !== node.task.proofPath || receipt.theoremName !== node.task.theoremName) continue; const id = receipt.receiptId || `observation-${mathDigest(canonicalMathJson(receipt))}`; const key = canonicalMathJson([node.task.id, version, proof.commit, id]); if (checkIds.has(key)) continue; - const record = { ...receipt, passed: proof.passed, + // The original-problem check can pass one target while failing the batch. + const passed = original ? proofReceiptsMatch({ ...proof.verification, status: receipt.status, results: [receipt] }, proof.commit, [{ + proofPath: original.proofPath, theoremName: original.theoremName, expectedSourceDeclarationHash: original.declarationHash, + statementHash: state.problem.contract.statementHash, leanStatementHash: state.problem.contract.leanStatementHash, claim: 'statement', + }]) : proof.passed; + const record = { ...receipt, passed, + ...(original ? { originalProblemPassed: proof.passed } : {}), ...('conditions' in proof ? { conditions: proof.conditions ?? [] } : {}), ...('references' in proof ? { references: proof.references } : {}), verification: { schema: proof.verification.schema, status: proof.verification.status, @@ -169,9 +176,11 @@ function sourceProjection(state: SolverRunState, directory: string) { } if (commit) addSource(node, commit); else sourcePartial = true; } - if (state.check) for (const node of state.cooperation?.tasks ?? []) if (node.task.kind === 'goal' && - state.check.verification.results.some(receipt => receipt.proofPath === node.task.proofPath && receipt.theoremName === node.task.theoremName)) - addProof(node, state.check); + if (state.check) for (const node of state.cooperation?.tasks ?? []) if (node.task.kind === 'goal') { + const target = state.problem.targets.find(item => item.proofPath === node.task.proofPath && item.theoremName === node.task.theoremName); + if (target && state.check.verification.results.some(receipt => + receipt.proofPath === target.proofPath && receipt.theoremName === target.theoremName)) addProof(node, state.check, target); + } if (!state.cooperation?.tasks.length && state.problem.targets.length) sourcePartial = true; return { sources, checks, coverage: { sources: sourcePartial ? 'partial' as const : 'recorded' as const, checks: checkPartial ? 'partial' as const : 'recorded' as const } }; diff --git a/docs/web-workbench.md b/docs/web-workbench.md index 2677c90b..eecaaa07 100644 --- a/docs/web-workbench.md +++ b/docs/web-workbench.md @@ -223,6 +223,7 @@ SMTP 密码只放在环境变量或 `.env` 中,不要写进仓库。服务在 | `POST /api/runs/:id/edits/preview`、`POST /api/runs/:id/edits` | 预览或提交完整版本化计划 | | `GET /api/runs/:id/commands/:commandId` | 查询原命令回执、应用或投递状态 | | `POST /api/runs/:id/archive`、`GET /api/runs/:id/archives/:archiveId` | 保存与下载可复核归档 | +| `GET /api/runs/:id/download`、`GET /api/runs/:id/snapshot` | 下载完整研究归档或运行快照 | | `GET /api/knowledge/catalogs`、`GET /api/knowledge/search` | 不可变目录版本和检索 | | `GET /api/knowledge/:entryId` | metadata/source/dependencies/consumers/finding 视图,保留分页范围 | | `GET /api/modules` | 实际可用模块注册表 | @@ -231,6 +232,8 @@ SMTP 密码只放在环境变量或 `.env` 中,不要写进仓库。服务在 | `GET /api/runs/:id/verification-kit` | 本地复核压缩包(ZIP):固定版本的 `lean-toolchain` / `lakefile.toml` / `lake-manifest.json`、`Submission.lean`、`Original.lean`、逐目标 `#print axioms` 的 `Check.lean`、中英文 README 与 `report.json`;找不到原题目标时 409 | | `GET/POST /api/module-plans`、`DELETE /api/module-plans/:id` | 持久方案库与版本冲突检查 | +直接下载和新保存的完整归档使用 `theorem-os.web-archive.v2`。任务和依赖的 `source` 字段使用 `{"sha256":"…"}` 引用,按摘要在同一文件的 `sourceBlobs` 对象中查找原文。历史观测、最近观测、命令回执附带的观测和顶层源码索引共用这份原文表。摘要继续记录覆盖范围和证据数量,`summary.digest` 绑定实际导出的内容。旧 v1 归档按保存时的格式和摘要下载。工作台可以从两版归档和 `theorem-os.web-export.v1` 运行快照导入任务草稿。 + ### 配置研究模块 打开「研究配置 → 模块方案」,或点击草稿模块图中的配置图标,可选择 M3 搜索策略与 M4 上下文范围,并新增自定义策略。每项策略包含名称、所属模块、规则、启用开关及「补充默认建议 / 替换默认建议」。支持 M1 证明构造、M3 搜索决策、M4 上下文选择和 M5 协作与复用;M2 检查及 S3 最终验收保持固定。 diff --git a/scripts/build-web-sample.ts b/scripts/build-web-sample.ts index fc319c8a..434545d7 100644 --- a/scripts/build-web-sample.ts +++ b/scripts/build-web-sample.ts @@ -5,12 +5,12 @@ import fs from 'node:fs'; import path from 'node:path'; import { webSampleRunId, webSampleSchema, type WebSampleFile } from '../apps/web/sample'; import { sampleActions } from './web-sample-actions'; -import type { StoredWebArchive } from '../apps/web/storage'; +import { readWebArchiveObservations, type StoredWebArchive } from '../apps/web/storage'; const input = path.resolve(process.argv[2] ?? 'out/web-cooperative-smoke/archive.json'); const output = path.resolve('apps/web/sample/run.json'); const archive = JSON.parse(fs.readFileSync(input, 'utf8')) as StoredWebArchive; -if (archive.schema !== 'theorem-os.web-archive.v1' || archive.run.result?.status !== 'evaluated_passed') +if (!['theorem-os.web-archive.v1', 'theorem-os.web-archive.v2'].includes(archive.schema) || archive.run.result?.status !== 'evaluated_passed') throw new Error(`${input} is not an accepted web archive`); const from = archive.run.id; @@ -29,12 +29,13 @@ const readable: [recorded: string, shown: string][] = [ ['Prove Tutorial.zero_add using Nat.zero_add.', '证明 Tutorial.zero_add:可以直接用 Nat.zero_add。'], ]; // Ids, the smoke marker and the container work directory are replaced everywhere, including nested records. -let text = JSON.stringify({ run: archive.run, observations: archive.observations, events: archive.events }); +const recorded = readWebArchiveObservations(archive); +let text = JSON.stringify({ ...recorded, events: archive.events }); text = text.replaceAll(from, webSampleRunId) .replaceAll('WEB_COOPERATIVE_SMOKE\\n', '').replaceAll('WEB_COOPERATIVE_SMOKE', title) .replace(/\/work\/run-[A-Za-z0-9]+\//gu, '/workspace/'); for (const [recorded, shown] of readable) text = text.replaceAll(JSON.stringify(recorded).slice(1, -1), JSON.stringify(shown).slice(1, -1)); -const data = JSON.parse(text) as Pick; +const data = JSON.parse(text) as typeof recorded & Pick; const sample: WebSampleFile = { schema: webSampleSchema, recordedAt: archive.summary.createdAt, diff --git a/scripts/test-web-collaboration.ts b/scripts/test-web-collaboration.ts index 04e08fce..0c063d1a 100644 --- a/scripts/test-web-collaboration.ts +++ b/scripts/test-web-collaboration.ts @@ -105,7 +105,7 @@ try{ await page.locator('[data-collab-archive]').click();await page.locator('[data-collab-archives] [data-collab-archive-download]').waitFor(); const archiveId = await page.locator('[data-collab-archive-id]').getAttribute('data-collab-archive-id');control.emit();await poll(page);assert.equal(await page.locator('[data-collab-archive-id]').getAttribute('data-collab-archive-id'),archiveId,'archive summary survives polling'); await page.reload();await ready(page);await selectHistoryRun(page,run.id, 'collaboration');await page.locator('[data-collab-archive-download]').waitFor();assert.equal(await page.locator('[data-collab-archive-id]').getAttribute('data-collab-archive-id'),archiveId,'archive summary reloads from the server run'); - const downloadReady = page.waitForEvent('download');await page.locator('[data-collab-archive-download]').click();const download=await downloadReady;const archiveFile=path.join(output,'downloaded-archive.json');await download.saveAs(archiveFile);const archiveText=await fs.readFile(archiveFile,'utf8');const archived=JSON.parse(archiveText) as {schema:string;summary:{id:string;runId:string;evidence:string};sources:Array<{taskVersion:string}>;checks:Array<{id:string}>};assert.equal(archived.schema,'theorem-os.web-archive.v1');assert.equal(archived.summary.runId,run.id);assert.equal(archived.summary.id,archiveId);assert.equal(archived.summary.evidence,'recorded-not-replayed');assert.ok(archived.sources.some(source=>source.taskVersion==='base-v1'));assert.ok(archived.checks.some(check=>check.id==='base-check'));assert.equal(archiveText.includes(input.apiKey),false);await page.locator('.collab-archives').screenshot({path:path.join(output,'archive-summary.png')}); + const downloadReady = page.waitForEvent('download');await page.locator('[data-collab-archive-download]').click();const download=await downloadReady;const archiveFile=path.join(output,'downloaded-archive.json');await download.saveAs(archiveFile);const archiveText=await fs.readFile(archiveFile,'utf8');const archived=JSON.parse(archiveText) as {schema:string;summary:{id:string;runId:string;evidence:string};sources:Array<{taskVersion:string}>;checks:Array<{id:string}>};assert.equal(archived.schema,'theorem-os.web-archive.v2');assert.equal(archived.summary.runId,run.id);assert.equal(archived.summary.id,archiveId);assert.equal(archived.summary.evidence,'recorded-not-replayed');assert.ok(archived.sources.some(source=>source.taskVersion==='base-v1'));assert.ok(archived.checks.some(check=>check.id==='base-check'));assert.equal(archiveText.includes(input.apiKey),false);await page.locator('.collab-archives').screenshot({path:path.join(output,'archive-summary.png')}); await openSettings(page);await page.locator('[data-server-module-library] > summary').click();await page.locator('[data-server-plan-name]').fill('Saved on server');await page.locator('#module-plan-scheduler').selectOption('critical-path');await page.locator('#module-plan-context').selectOption('essential');await page.locator('[data-server-plan-save]').click();await page.locator('[data-server-plan-notice]').getByText(/已保存/).waitFor(); await page.locator('#module-plan-scheduler').selectOption('plan');await page.locator('[data-server-plan-load]').click();assert.equal(await page.locator('#module-plan-scheduler').inputValue(),'critical-path'); const catalogs=await page.evaluate(async()=>await(await fetch('/api/knowledge/catalogs')).json());await page.locator('#knowledge-catalog').selectOption(catalogs.catalogs[0].digest);await closeSettings(page); diff --git a/scripts/test-web-continuation-archive.ts b/scripts/test-web-continuation-archive.ts index ec0e8617..48112d9d 100644 --- a/scripts/test-web-continuation-archive.ts +++ b/scripts/test-web-continuation-archive.ts @@ -107,10 +107,12 @@ try { await page.goto(`${origin}/?run=${run.id}`); await ready(page); await page.locator('[data-chat-recovery="continue-checked"]').waitFor(); - const downloaded = await download(page, `.chat-task-actions a[href="/api/runs/${run.id}/download"]`); + const chatDetails = page.locator('[data-chat-result-more]'); + if (await chatDetails.getAttribute('open') === null) await chatDetails.locator('summary').click(); + const downloaded = await download(page, `.chat-result-more-actions a[href="/api/runs/${run.id}/download"]`); const archive = downloaded.body as StoredWebArchive; assert.equal(downloaded.filename, `theoremos-${run.id}.json`); - assert.equal(archive.schema, 'theorem-os.web-archive.v1'); + assert.equal(archive.schema, 'theorem-os.web-archive.v2'); assert.ok(archive.events.length > 200); assert.equal(archive.events[0]!.sequence, 1); assert.equal(archive.observations.length, 4); assert.equal(archive.actions!.length, 1); assert.ok(archive.sources.length > 0); assert.ok(archive.checks.length > 0); diff --git a/scripts/test-web-results.ts b/scripts/test-web-results.ts index c32f3f9e..fcf09770 100644 --- a/scripts/test-web-results.ts +++ b/scripts/test-web-results.ts @@ -140,7 +140,7 @@ async function assertNoResultArchive(h: Harness, run: WebRun, status: 'cancelled assert.equal(downloaded.suggestedFilename(), `theoremos-${run.id}.json`); const raw = await fs.readFile((await downloaded.path())!, 'utf8'); const archive = JSON.parse(raw) as { schema: string; run: WebRun }; - assert.equal(archive.schema, 'theorem-os.web-archive.v1'); + assert.equal(archive.schema, 'theorem-os.web-archive.v2'); assert.equal(archive.run.id, run.id); assert.equal(archive.run.status, status); assert.equal(archive.run.result, undefined); diff --git a/scripts/test-web-round8-budget.ts b/scripts/test-web-round8-budget.ts index 9f032ba1..bad1442d 100644 --- a/scripts/test-web-round8-budget.ts +++ b/scripts/test-web-round8-budget.ts @@ -74,7 +74,7 @@ try { const archive = await response.json(); // The server persists omitted budgets as zero, the explicit unlimited value. assert.equal(archive.run.maxTotalTokens, cap ?? 0); - assert.equal(archive.schema, operation === 'download' ? 'theorem-os.web-archive.v1' : 'theorem-os.web-export.v1'); + assert.equal(archive.schema, operation === 'download' ? 'theorem-os.web-archive.v2' : 'theorem-os.web-export.v1'); await fs.writeFile(path.join(output, `${locale}-source-${cap ?? 'unlimited'}.json`), JSON.stringify(archive, null, 2) + '\n'); await importJson(page, archive, `${locale}-real-${operation}-${cap ?? 'unlimited'}.json`); diff --git a/scripts/test-web-trajectory.ts b/scripts/test-web-trajectory.ts index 357ab0de..c084c9c6 100644 --- a/scripts/test-web-trajectory.ts +++ b/scripts/test-web-trajectory.ts @@ -441,6 +441,9 @@ try { await showArtifacts(page); const note = page.locator('[data-run-continuation]'); await note.waitFor(); + const continuedId = (await page.locator('.detail-heading').getAttribute('data-run'))!; + await waitForRun({ page }, continuedId, run => run.status === 'completed'); + await page.locator(`.detail-heading[data-run="${continuedId}"]`).getByText('运行结束', { exact: true }).waitFor(); assert.match(await note.innerText(), /从「zero_add · 第 2 次」继续/u); assert.equal(continued.length, 1); assert.equal(continued[0]!.continuation?.runId, run.id); @@ -448,7 +451,6 @@ try { assert.equal(await page.locator('#draft-continuation').isHidden(), true, 'one submission uses the continuation'); assert.deepEqual(await audit(page, { scope: '#run-detail' }), [], 'Continued run accessibility'); await shot(page, 'trajectory-continued-1440.png'); - const continuedId = (await page.locator('.detail-heading').getAttribute('data-run'))!; await note.getByRole('button', { name: '看原运行' }).click(); await page.locator(`.detail-heading[data-run="${run.id}"]`).waitFor({ state: 'attached' }); await showArtifacts(page); // The original lists what came of it: the later run, the version it started from, and its own status. diff --git a/src/solver/cooperationShared.ts b/src/solver/cooperationShared.ts index 2980f4a8..1c4f45cb 100644 --- a/src/solver/cooperationShared.ts +++ b/src/solver/cooperationShared.ts @@ -74,6 +74,7 @@ export type PlanPublication = { nonce: string; file: string; offset: number; eve export type InitialPlanPublication = PlanPublication; export type PlanPublicationRejection = { nonce: string; file: string; offset: number; baseVersion: string; reason: string }; export type FailedTaskInput = { id: string; taskId: string; taskDigest: string; inputDigest: string; basis: BlockerBasis; + declarationDigest?: string; attemptFingerprint?: string; relatedFailureIds?: string[]; sourceDigest: string; targetDigest: string; seedSourceDigest: string; seedTargetDigest: string; canonicalSourceDigest: string; canonicalTargetDigest: string; feedback: string; diff --git a/src/solver/cooperationTaskProofs.ts b/src/solver/cooperationTaskProofs.ts index fae223a2..6c962507 100644 --- a/src/solver/cooperationTaskProofs.ts +++ b/src/solver/cooperationTaskProofs.ts @@ -143,7 +143,9 @@ export abstract class CooperationTaskProofs extends CooperationStatements { return mathDigest(canonicalMathJson({ ...(local ? {} : { file: task.proofPath, offset: targets[0].startOffset }), source: target })); } private failedTaskBasis(task: CooperativeTask, conditions?: readonly CooperativeTask[], - assignment = this.node(task.id)?.assignment): { basis: BlockerBasis; inputDigest: string } { + assignment = this.node(task.id)?.assignment) { + const taskDigest = digest(task); + const declarationDigest = mathDigest(canonicalMathJson([task.proofPath, task.theoremName])); const normalized = task.kind === 'lemma' ? { ...task, theoremName: undefined, proofPath: undefined } : task; conditions ??= this.assignmentConditions(task, assignment); const node = this.node(task.id), routeId = node && selectedTaskRoute(node, this.archive.tasks)?.id; @@ -157,8 +159,9 @@ export abstract class CooperationTaskProofs extends CooperationStatements { buildDigest: this.input.state.buildDigest, evaluatorDigest: this.input.state.evaluatorDigest, environment: projectMathematicsRuntimeEnvironment(this.input.access.get(this.lead.id)?.environment ?? {}) })); const previous = this.archive.failedTaskInputs?.findLast(record => record.basis.contractDigest === contractDigest && - record.basis.environmentDigest === environmentDigest) ?? - this.archive.failedTaskInputs?.findLast(record => record.basis.contractDigest === contractDigest && this.missingTaskDeclaration(record)); + record.basis.environmentDigest === environmentDigest && this.sameFailedDeclaration(record, { taskDigest, declarationDigest })) ?? + this.archive.failedTaskInputs?.findLast(record => record.basis.contractDigest === contractDigest && + this.reusableMissingDeclaration(record, task.id)); const basis: BlockerBasis = { contractDigest, environmentDigest, dependencies: Object.fromEntries(Object.entries(raw.dependencies).map(([id, entry]) => { const dependency = this.node(id), proof = dependency?.integratedCheck; @@ -172,17 +175,29 @@ export abstract class CooperationTaskProofs extends CooperationStatements { // Dependency task IDs, revision counters and replayed receipts do not change the mathematics. const inputDigest = mathDigest(canonicalMathJson({ contractDigest, environmentDigest, dependencies: Object.values(basis.dependencies).map(entry => canonicalMathJson(entry)).sort() })); - return { basis, inputDigest }; + return { basis, inputDigest, taskId: task.id, taskDigest, declarationDigest }; } private missingTaskDeclaration(record: FailedTaskInput) { return record.targetDigest === 'declaration-count:0' && record.feedback.startsWith('math_task_missing_declaration\n'); } - private sameFailedTaskBasis(record: FailedTaskInput, candidate: Pick) { + private sameFailedDeclaration(record: FailedTaskInput, candidate: Pick) { + return record.declarationDigest === undefined ? record.taskDigest === candidate.taskDigest : + record.declarationDigest === candidate.declarationDigest; + } + private reusableMissingDeclaration(record: FailedTaskInput, taskId: string) { + // Preserve deduplication when a plan replaces a missing helper with a renamed version of the same contract. + return this.missingTaskDeclaration(record) && (record.taskId === taskId || !this.node(record.taskId)); + } + private sameFailedTaskBasis(record: FailedTaskInput, + candidate: Pick) { + const sameDeclaration = this.sameFailedDeclaration(record, candidate); + const sameMissing = candidate.targetDigest === record.targetDigest && + (sameDeclaration ? this.missingTaskDeclaration(record) : this.reusableMissingDeclaration(record, candidate.taskId)); + if (!sameMissing && !sameDeclaration) return false; if (record.inputDigest === candidate.inputDigest) return true; // A different checker cannot materialize a declaration absent from these same sources. // Still reopen for changed contracts, assumptions, checked dependencies or selected route inputs. - if (!this.missingTaskDeclaration(record) || candidate.targetDigest !== 'declaration-count:0' || - record.basis.contractDigest !== candidate.basis.contractDigest) return false; + if (!sameMissing || record.basis.contractDigest !== candidate.basis.contractDigest) return false; const dependencies = (basis: BlockerBasis) => Object.values(basis.dependencies).map(entry => canonicalMathJson(entry)).sort(); return canonicalMathJson(dependencies(record.basis)) === canonicalMathJson(dependencies(candidate.basis)); } @@ -191,14 +206,15 @@ export abstract class CooperationTaskProofs extends CooperationStatements { record.targetDigest === candidate.targetDigest && this.sameFailedTaskBasis(record, candidate)); } protected failedTaskInput(task: CooperativeTask, assignment: TaskAssignment, worktree: string, commit: string, conditions?: readonly CooperativeTask[]) { - const { basis, inputDigest } = this.failedTaskBasis(task, conditions, assignment), sourceDigest = this.leanSourceDigest(worktree, commit); + const input = this.failedTaskBasis(task, conditions, assignment), sourceDigest = this.leanSourceDigest(worktree, commit); const targetDigest = this.taskSourceDigest(task, worktree, commit); const localTargetDigest = this.taskSourceDigest(task, worktree, commit, true); - return { id: mathDigest(canonicalMathJson({ inputDigest, sourceDigest, targetDigest })), taskId: task.id, taskDigest: digest(task), + return { id: mathDigest(canonicalMathJson({ inputDigest: input.inputDigest, declarationDigest: input.declarationDigest, sourceDigest, targetDigest })), + ...input, ...(!localTargetDigest.startsWith('declaration-count:') ? { - attemptFingerprint: mathDigest(canonicalMathJson({ inputDigest, target: localTargetDigest })), + attemptFingerprint: mathDigest(canonicalMathJson({ inputDigest: input.inputDigest, target: localTargetDigest })), } : {}), - inputDigest, basis, sourceDigest, targetDigest, seedSourceDigest: this.leanSourceDigest(worktree, assignment.seedCommit), + sourceDigest, targetDigest, seedSourceDigest: this.leanSourceDigest(worktree, assignment.seedCommit), seedTargetDigest: this.taskSourceDigest(task, worktree, assignment.seedCommit), canonicalSourceDigest: this.leanSourceDigest(this.lead.worktree, this.archive.canonicalCommit!), canonicalTargetDigest: this.taskSourceDigest(task, this.lead.worktree, this.archive.canonicalCommit!) }; @@ -271,30 +287,33 @@ export abstract class CooperationTaskProofs extends CooperationStatements { for (const node of this.archive.tasks) { if (advisory(node.task) || !['pending', 'blocked'].includes(node.status) || [node.proof, node.integratedCheck].some(proof => proof?.passed && proof.taskDigest === digest(node.task))) continue; - const { basis, inputDigest } = this.failedTaskBasis(node.task); + const candidate = this.failedTaskBasis(node.task); const worker = this.input.workers.find(worker => worker.id === node.assignment?.workerId); const session = worker && this.input.state.workers?.find(record => record.id === worker.id); const active = worker && this.active.get(worker.id)?.action; - const ownsOutput = worker && node.assignment?.taskDigest === digest(node.task) && - (!session || session.sessionTaskId === node.task.id && (!session.sessionTaskVersion || session.sessionTaskVersion === digest(node.task))) && + const ownsOutput = worker && node.assignment?.taskDigest === candidate.taskDigest && + (!session || session.sessionTaskId === node.task.id && (!session.sessionTaskVersion || session.sessionTaskVersion === candidate.taskDigest)) && (!active || active.kind === 'task' && active.task.id === node.task.id && active.assignment === node.assignment) && + ![...this.preparingTaskTypes].some(([other, prep]) => other !== node && prep.workerId === worker.id) && !this.archive.tasks.some(other => other !== node && other.status === 'running' && other.assignment?.workerId === worker.id); - const sourceDigest = ownsOutput ? this.leanSourceDigest(worker.worktree, git(worker.worktree, ['rev-parse', 'HEAD'])) : canonicalSourceDigest; - const targetDigest = ownsOutput ? this.taskSourceDigest(node.task, worker.worktree, git(worker.worktree, ['rev-parse', 'HEAD'])) : - this.taskSourceDigest(node.task, this.lead.worktree, this.archive.canonicalCommit!); - const record = this.archive.failedTaskInputs.findLast(record => this.sameFailedTaskBasis(record, { basis, inputDigest, targetDigest }) && - (record.sourceDigest === sourceDigest && record.targetDigest === targetDigest || !ownsOutput && + const worktree = ownsOutput ? worker.worktree : this.lead.worktree; + const commit = ownsOutput ? git(worktree, ['rev-parse', 'HEAD']) : this.archive.canonicalCommit!; + const sourceDigest = this.leanSourceDigest(worktree, commit); + const targetDigest = this.taskSourceDigest(node.task, worktree, commit); + // A host reseed can replace the failed candidate with its unchanged canonical inputs before a new session starts. + const record = this.archive.failedTaskInputs.findLast(record => this.sameFailedTaskBasis(record, { ...candidate, targetDigest }) && + (record.sourceDigest === sourceDigest && record.targetDigest === targetDigest || sourceDigest === canonicalSourceDigest && (record.seedSourceDigest === sourceDigest && record.seedTargetDigest === targetDigest || record.canonicalSourceDigest === sourceDigest && record.canonicalTargetDigest === targetDigest))); if (record && !this.pendingTaskRepair(node, record)) { const feedback = this.repeatedTaskFeedback(record); if (node.status === 'blocked' && node.feedback === feedback) continue; this.moveTask(node, 'blocked', 'input-blocked'); node.feedback = feedback; this.wakeLead('task-repeated-input-blocked'); changed = true; - this.input.emit('task_repeated_input_blocked', { taskId: node.task.id, taskDigest: digest(node.task), - failureId: record.id, inputDigest, sourceDigest }); + this.input.emit('task_repeated_input_blocked', { taskId: node.task.id, taskDigest: candidate.taskDigest, + failureId: record.id, inputDigest: candidate.inputDigest, sourceDigest }); } else if (!record && node.status === 'blocked' && node.feedback?.startsWith('math_task_repeated_failed_input\n')) { this.moveTask(node, 'pending', 'reopened'); node.feedback = undefined; changed = true; - this.input.emit('task_failed_input_reopened', { taskId: node.task.id, inputDigest, sourceDigest }); + this.input.emit('task_failed_input_reopened', { taskId: node.task.id, inputDigest: candidate.inputDigest, sourceDigest }); } } return changed; diff --git a/src/solver/research.ts b/src/solver/research.ts index 13fea360..7aac41ae 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -30,7 +30,7 @@ import { aggregateUsage, buildTokenBudget, initializeUsageAccounting, modelDispa import { ResearchUsage } from './researchUsage'; import { inspectKnowledgeUses } from './knowledgeUsage'; import { checkKnowledgeApplications } from './knowledgeApplications'; -import { parseMathResponse } from './deliveries'; +import { parseMathResponse, readMathResponse } from './deliveries'; import { readCheckpointNotesDigest, savedContextCheckpoint } from './contextCheckpoint'; import { committedSource } from './problem'; import type { ContinuationSnapshot } from './continuationInput'; @@ -982,9 +982,9 @@ export async function runResearchWorkers(input: { // would cancel the response on direct-provider sessions with no host request relay. void activeSession.notify!( 'A typed proof task is now ready. Finish the current model response and tool work, then save ' + - 'this investigation in worktree-root RESEARCH.md. Keep the exact inputs, current argument, ' + - 'reproduction commands, results and next unresolved step. After saving, return so the host can ' + - 'recheck the proposed switch. Leave an unfinished investigation as a draft.', + 'worktree-root RESEARCH.md. If the investigation is complete, write the normal JSON math-result. ' + + 'If unfinished, save a Markdown draft with the exact inputs, current argument, reproduction commands, ' + + 'results and next unresolved step. After saving, return so the host can recheck the proposed switch.', { mode: 'advisory' }).then(() => { if (current()) { proofNoticeDelivered = true; @@ -1009,9 +1009,17 @@ export async function runResearchWorkers(input: { planningCheckpoint = usage.stopReason === 'math_initial_planning_limit'; const resultStatus = typeof result === 'string' ? result : result && typeof result === 'object' && 'status' in result ? result.status : undefined; if (milestone?.requested && resultStatus === 'completed') softSliceCheckpoint = true; - // A natural return after the save request preserves an unfinished draft. A relay - // checkpoint confirms the same successor and a current draft at the unpaid boundary. - proofHandoffCheckpoint = handoffAtBoundary || Boolean(proofNoticeDelivered && resultStatus === 'completed'); + const completedAfterNotice = proofNoticeDelivered && resultStatus === 'completed'; + let submittedResult = false; + if (completedAfterNotice && !handoffAtBoundary && researchHandoffNotes()) { + // Only an explicit result distinguishes a normal return from saving prose for the handoff. + // The regular delivery path still validates the result and its frozen assignment. + try { + const finding = readMathResponse(worker.worktree, 'math-result'); + submittedResult = typeof finding.summary === 'string' && Boolean(finding.summary.trim()); + } catch { /* Missing or unfinished control responses remain handoff drafts. */ } + } + proofHandoffCheckpoint = handoffAtBoundary || (completedAfterNotice && !submittedResult); cooperativeCheckpoint = proofHandoffCheckpoint || checkpointRequested && (resultStatus === 'interrupted' || resultStatus === 'checkpoint' || checkpointClosing && resultStatus === 'failed' && researchFailureReason(detail) === 'math_codex_transport_closed'); completed = resultStatus === 'completed'; diff --git a/tests/repeatedDelivery.test.ts b/tests/repeatedDelivery.test.ts index 8e60dcf1..f5730dfa 100644 --- a/tests/repeatedDelivery.test.ts +++ b/tests/repeatedDelivery.test.ts @@ -470,6 +470,17 @@ describe('persistent typed delivery failure guards', () => { expect(checker).toHaveBeenCalledTimes(1); }); + it('dispatches an independent declaration of the same type while an absent helper stays blocked', async () => { + reseed('theorem goal : True := by sorry\n'); + checker.mockRejectedValue(new Error(missing)); await exhaustRepair(); + const independent: TaskRecord = { task: task('independent'), status: 'pending', attempts: 0 }; + state.cooperation!.tasks.push(independent); + (cooperative as any).refreshFailedTaskInputs(); + expect(candidate.status).toBe('blocked'); expect(independent.status).toBe('pending'); + expect(await cooperative.next(researcher, budget)).toMatchObject({ kind: 'task', task: { id: independent.task.id } }); + expect(checker).toHaveBeenCalledOnce(); + }); + it('preserves failure and unused repair records across serialization and restore', async () => { await cooperative.deliver(researcher, action, seed); const restored = JSON.parse(JSON.stringify(state)) as SolverRunState, resumed = create(restored); diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts index ce09c632..49e862ba 100644 --- a/tests/solverCooperativeCheckpoints.test.ts +++ b/tests/solverCooperativeCheckpoints.test.ts @@ -460,8 +460,9 @@ describe('cooperative advisory scheduling checkpoints', () => { expect(vi.getTimerCount()).toBe(0); }); - it.each(['ready', 'compacting', 'claimed-elsewhere', 'target-lost-at-boundary', 'dispatch-mismatch'] as const)( - 'only checkpoints at the request boundary with a saved draft and the same proof (%s)', async outcome => { + it.each(['ready', 'ready-with-structured-draft', 'compacting', 'claimed-elsewhere', 'target-lost-at-boundary', + 'dispatch-mismatch', 'completed-with-ready-proof', 'completed-with-reassigned-proof'] as const)( + 'preserves drafts and completed findings during a typed proof handoff (%s)', async outcome => { const { state, workers, check, events, controller, run, wake } = fixture(false, undefined, undefined, true); const held = heldAdvisoryTurns(2, ['investigate', 'goal_1']); const open = async (options: MathAgentOptions): Promise => ({ @@ -477,6 +478,9 @@ describe('cooperative advisory scheduling checkpoints', () => { // A peer becomes responsible for the goal after the final handoff check and before dispatch. reassignGoal(); } + // Once the finding is published, this fixture with no available proof owner would wake the Lead. + if (outcome === 'completed-with-reassigned-proof' && event === 'research_delivered') + controller.abort(new Error('fixture_complete')); }); void completion.catch(() => {}); await held.wait(0, completion); @@ -498,14 +502,33 @@ describe('cooperative advisory scheduling checkpoints', () => { await vi.advanceTimersByTimeAsync(5_000); expect(held.notify).toHaveBeenCalledWith(expect.stringContaining('A typed proof task is now ready'), { mode: 'advisory' }); expect(boundary()).toBe(false); - const notes = 'Inspected the exact pinned input. The independent review is unfinished.\n'; + const completedReview = outcome === 'completed-with-ready-proof' || outcome === 'completed-with-reassigned-proof'; + const notes = completedReview || outcome === 'ready-with-structured-draft' + ? JSON.stringify({ summary: 'The interface is feasible by the displayed construction.', conclusion: 'supporting', + evidenceRefs: ['construction:fixture'] }) + : 'Inspected the exact pinned input. The independent review is unfinished.\n'; activity({ event: 'item_started', itemType: 'commandExecution' }); fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); expect(boundary()).toBe(false); activity({ event: 'item_completed', itemType: 'commandExecution' }); expect(held.interrupt).not.toHaveBeenCalled(); - if (outcome === 'claimed-elsewhere') { + if (completedReview) { + if (outcome === 'completed-with-reassigned-proof') { reassignGoal(); expect(boundary()).toBe(false); } + held.done[0].resolve('completed'); + await vi.waitFor(() => expect(events.some(({ event }) => + event === 'research_delivered' || event === 'feasibility_review_checkpoint_saved')).toBe(true)); + const audit = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; + expect(audit).toMatchObject({ status: 'completed', finding: expect.stringContaining('displayed construction') }); + expect(audit.researchCompletion).toBeDefined(); + expect(events).toContainEqual({ event: 'research_delivered', + details: expect.objectContaining({ taskId: 'investigate', complete: true }) }); + expect(events.some(({ event }) => event === 'turn_checkpoint')).toBe(false); + if (outcome === 'completed-with-ready-proof') { + await held.wait(1, completion); + expect(held.actions[1].task.id).toBe('goal_1'); + } + } else if (outcome === 'claimed-elsewhere') { // The existing handoff is stale by the time the model asks for another request. reassignGoal(); expect(boundary()).toBe(false); @@ -533,11 +556,13 @@ describe('cooperative advisory scheduling checkpoints', () => { cooldownUntil: Date.now() + 10 * 60_000 }) }); } else expect(events.some(item => item.event === 'cooperative_preemption_mismatch')).toBe(false); } - const audit = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - const draft = state.cooperation!.researchDrafts!.investigate; - expect(audit.researchCompletion).toBeUndefined(); - expect(draft.feasibilityInputDigest).toBe(held.actions[0].assignment.feasibilityInputDigest); - expect(committedSource(workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(notes); + if (!completedReview) { + const audit = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; + const draft = state.cooperation!.researchDrafts!.investigate; + expect(audit.researchCompletion).toBeUndefined(); + expect(draft.feasibilityInputDigest).toBe(held.actions[0].assignment.feasibilityInputDigest); + expect(committedSource(workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(notes); + } expect(held.interrupt).not.toHaveBeenCalled(); expect(check).not.toHaveBeenCalled(); controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); expect(vi.getTimerCount()).toBe(0); diff --git a/tests/solverIntegrationRecovery.test.ts b/tests/solverIntegrationRecovery.test.ts index 623b4456..ef80db1c 100644 --- a/tests/solverIntegrationRecovery.test.ts +++ b/tests/solverIntegrationRecovery.test.ts @@ -6,6 +6,7 @@ import type { SolverRunState } from '../src/solver/archive'; import type { CooperativeResearch } from '../src/solver/cooperation'; import type { ResearchWorker } from '../src/solver/modules/organization'; import { committedSource, commitSolverSources, type SolverProblem } from '../src/solver/problem'; +import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; @@ -199,6 +200,47 @@ describe('checked task integration recovery', () => { expect(host.verify).toHaveBeenCalledTimes(2); }); + it.each([false, true])('dispatches a different same-type declaration after an exhausted proof failure (legacy=%s)', async legacy => { + state.workers = workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })); + Object.assign(state.workers[1], { sessionTaskId: action.task.id, sessionTaskVersion: taskVersion(action.task) }); + const failedCommit = writeLemma(workers[1], 'lemma recovery_lemma : True := by exact missing_recovery_proof'); + host.verify.mockImplementation(async request => failedBatch(verified(request), { + stdoutPreview: () => 'Submission.lean:3:1: error: unknown identifier missing_recovery_proof', + })); + await cooperative.deliver(workers[1], action, failedCommit); + expect(node().status).toBe('pending'); + node().status = 'running'; + expect(cooperative.started(workers[1], action)).toBe(true); + await cooperative.deliver(workers[1], action, failedCommit); + expect(node().status).toBe('blocked'); + const [failure] = state.cooperation!.failedTaskInputs!; + if (legacy) delete failure.declarationDigest; + + const nextTask: CooperativeTask = { ...action.task, id: 'independent_fact', objective: 'Prove a different fact.', + theoremName: 'Tutorial.independent_fact', ownerId: workers[1].id }; + state.cooperation!.tasks.push({ task: nextTask, status: 'pending', attempts: 0 }); + const goal = node('goal_0'); + goal.task = { ...goal.task, status: 'active', dependsOn: [nextTask.id], conditional: false }; + const refresh = () => (cooperative as any).refreshFailedTaskInputs(); + refresh(); + expect(node(nextTask.id)).toMatchObject({ status: 'pending', attempts: 0 }); + + // Another waiting worker may refresh dispatch while the host has reseeded this worktree for its next declaration. + const observationStart = events.length; + const preflight = vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => { + refresh(); + return { current: () => true, result: { status: 'deferred', inputDigest: 'offline-fixture', taskDigest: taskVersion(input.task), + reason: 'fixture-deferred', evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } }; + }); + const next = await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity }); + expect(next).toMatchObject({ kind: 'task', task: { id: nextTask.id } }); + expect(preflight).toHaveBeenCalledOnce(); + expect(node().status).toBe('blocked'); + expect(events.slice(observationStart)).not.toContainEqual(expect.objectContaining({ + event: 'task_failed_input_reopened', details: expect.objectContaining({ taskId: action.task.id }), + })); + }); + it.each(['conditional', 'verified'] as const)('publishes a %s proof without using inherited failed feedback as its summary', async status => { if (status === 'conditional') await conditionalParent(false); else { diff --git a/tests/webCollaboration.test.ts b/tests/webCollaboration.test.ts index 1e8daf51..6b17e44b 100644 --- a/tests/webCollaboration.test.ts +++ b/tests/webCollaboration.test.ts @@ -8,7 +8,7 @@ import { createWebService } from '../apps/web/server'; import { readWebConfig } from '../apps/web/config'; import { isAcceptedRun } from '../apps/web/presentation'; import { WebJobs } from '../apps/web/jobs'; -import { WebStorage } from '../apps/web/storage'; +import { readWebArchiveObservations, WebStorage } from '../apps/web/storage'; import type { WebCommand, WebCommandResult, WebObservation } from '../apps/web/collaboration'; import type { WebRunner } from '../apps/web/runner'; import { parseWorkerMessage } from '../apps/web/runner'; @@ -223,7 +223,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => response.resolve({ id: 'capture', status: 'captured', observation: captured }); const archive = await pending; const saved = jobs.storage.getArchive('alice', run.id, archive.id)!; - expect(saved.sources[0].source).toBe('-- Provider echoed [REDACTED]'); + expect(readWebArchiveObservations(saved).observations[0].sources[0].source).toBe('-- Provider echoed [REDACTED]'); expect(JSON.stringify(saved)).not.toContain(key); expect(JSON.stringify(jobs.storage.getRun('alice', run.id))).not.toContain(key); expect(run.status).toBe('completed'); diff --git a/tests/webDraft.test.ts b/tests/webDraft.test.ts index adbf9a97..e20d01fa 100644 --- a/tests/webDraft.test.ts +++ b/tests/webDraft.test.ts @@ -106,7 +106,7 @@ describe('task draft codecs without credentials or run-result state', () => { expect(decodeTaskDraft(archive())).not.toHaveProperty('result'); }); - describe.each(['theorem-os.web-export.v1', 'theorem-os.web-archive.v1'])('%s token budgets', schema => { + describe.each(['theorem-os.web-export.v1', 'theorem-os.web-archive.v1', 'theorem-os.web-archive.v2'])('%s token budgets', schema => { it.each([ [10_000, '1'], [20_000, '2'], [15_000, '1.5'], [10_003, '1.0003'], [12_345_678, '1234.5678'], [100_000_000, '10000'], diff --git a/tests/webPersistence.test.ts b/tests/webPersistence.test.ts index 36ddf336..00a1c383 100644 --- a/tests/webPersistence.test.ts +++ b/tests/webPersistence.test.ts @@ -6,7 +6,7 @@ import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { buildTheoremKnowledge, type KnowledgeCandidate, type KnowledgeRouteFindingCandidate } from '../src/solver/theoremKnowledge'; import type { WebObservation, WebTaskSource } from '../apps/web/collaboration'; import type { WebRun } from '../apps/web/shared'; -import { WebStorage } from '../apps/web/storage'; +import { readWebArchiveObservations, WebStorage, type StoredWebArchive } from '../apps/web/storage'; import { WebKnowledgeService } from '../apps/web/knowledgeService'; import { WebModuleRegistry, freezeModuleConfiguration } from '../apps/web/moduleRegistry'; @@ -97,7 +97,8 @@ describe('durable web evidence and registered research configuration without mod coverage: { events: 'complete', observations: 'complete', actions: 'complete', commands: 'recorded', sources: 'partial', checks: 'partial' } }); expect(bundle.run.status).toBe('cancelled'); expect(bundle.run.result).toBeUndefined(); expect(bundle.events).toHaveLength(205); expect(restarted.getEvents('alice', saved.id)).toHaveLength(205); - expect(bundle.observations).toHaveLength(2); expect(bundle.sources[0]?.source).toBe(sourceText); + expect(bundle.observations).toHaveLength(2); + expect(readWebArchiveObservations(bundle).observations[0].sources[0].source).toBe(sourceText); expect(bundle.checks[0]?.record).toMatchObject({ passed: true, conditional: true, conditions: ['unproved-precondition'] }); expect(bundle.actions).toHaveLength(1); expect(bundle.actions?.[0]?.command).toBe('cat Submission.lean'); expect(bundle.commands).toEqual([{ id: 'guidance-1', status: 'delivered' }]); @@ -129,11 +130,56 @@ describe('durable web evidence and registered research configuration without mod store.saveRun('alice', saved); expect(store.loadRuns()).toEqual([{ owner: 'alice', run: saved }]); const archive = store.archiveRun('alice', saved); - expect(store.getArchive('alice', saved.id, archive.id)?.sources[0]?.source).toBe(sourceText); + expect(readWebArchiveObservations(store.getArchive('alice', saved.id, archive.id)!).observations[0].sources[0].source).toBe(sourceText); store.deleteRun('bob', saved.id); expect(store.getRun('alice', saved.id)).toBeDefined(); store.deleteRun('alice', saved.id); expect(store.loadRuns()).toEqual([]); }); + it('keeps repeated task and dependency source text once across historical frames and saved archives', () => { + const store = new WebStorage(root), saved = run(); + const largeSource = 'theorem fixture : True := by trivial\n/- ' + 'z'.repeat(850_000) + '-/\n'; + const dependency = '-- frozen dependency\n'; + const largeTask = { ...taskSource, sourceDigest: mathDigest(largeSource), source: largeSource, + dependencySources: [{ file: 'Dependency.lean', source: dependency }] }; + const frames = Array.from({ length: 66 }, (_, index) => ({ ...observation(index + 1), sources: [largeTask] })); + const directory = ['owners', mathDigest('alice'), 'runs', saved.id]; + // A run can retain both older inline frames and newer frames with source references. + store.saveRecord([...directory, 'observations', '1.json'], frames[0], true); + for (const frame of frames.slice(1)) store.saveObservation('alice', frame); + saved.observation = frames.at(-1); + store.saveRun('alice', saved); + store.saveCommand('alice', saved.id, 'capture', { id: 'capture', status: 'captured', observation: frames[0] }); + + const exported = store.exportRun('alice', saved); + expect(exported.summary).toMatchObject({ sources: 1, observations: 66, coverage: { observations: 'complete' } }); + expect(exported.sourceBlobs).toEqual({ [mathDigest(largeSource)]: largeSource, [mathDigest(dependency)]: dependency }); + expect(exported.sources[0]).toMatchObject({ taskId: largeTask.taskId, source: { sha256: mathDigest(largeSource) }, + dependencySources: [{ file: 'Dependency.lean', source: { sha256: mathDigest(dependency) } }] }); + expect(exported.commands).toEqual([{ id: 'capture', status: 'captured', observation: exported.observations[0] }]); + expect(Buffer.byteLength(JSON.stringify(exported))).toBeLessThan(1_000_000); + expect(readWebArchiveObservations(exported)).toEqual({ run: saved, observations: frames }); + + const summary = store.archiveRun('alice', saved), restarted = new WebStorage(root); + const savedArchive = restarted.getArchive('alice', saved.id, summary.id)!; + expect(savedArchive).toMatchObject({ schema: 'theorem-os.web-archive.v2', summary }); + expect(readWebArchiveObservations(savedArchive)).toEqual({ run: saved, observations: frames }); + expect(fs.statSync(path.join(root, ...directory, 'archives', `${summary.id}.json`)).size).toBeLessThan(1_000_000); + }); + + it('reads saved v1 archives with their original digest and inline evidence', () => { + const store = new WebStorage(root), saved = run(), frame = saved.observation!; + store.saveRun('alice', saved); + const { digest: _digest, ...identity } = store.exportRun('alice', saved).summary; + const payload = { schema: 'theorem-os.web-archive.v1' as const, run: saved, observations: [frame], + sources: frame.sources, checks: frame.checks, events: [], commands: [] }; + const legacy: StoredWebArchive = { ...payload, summary: { ...identity, digest: mathDigest(canonicalMathJson({ ...payload, identity }) + '\n') } }; + const record = ['owners', mathDigest('alice'), 'runs', saved.id, 'archives', `${identity.id}.json`]; + store.saveRecord(record, legacy, true); + const loaded = new WebStorage(root).getArchive('alice', saved.id, identity.id)!; + expect(loaded).toEqual(legacy); + expect(readWebArchiveObservations(loaded)).toEqual({ run: saved, observations: [frame] }); + }); + it('merges checked declarations and advisory findings into immutable owner-bound catalogs with reproducible worker pins', () => { const service = new WebKnowledgeService(new WebStorage(root)); const first = service.importCatalog('alice', buildTheoremKnowledge([candidate()])); diff --git a/tests/webSample.test.ts b/tests/webSample.test.ts index 2b1ec86d..2c64efc4 100644 --- a/tests/webSample.test.ts +++ b/tests/webSample.test.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import { describe, expect, it } from 'vitest'; import { loadWebSample, webSampleResponse, webSampleRunId } from '../apps/web/sample'; -import type { StoredWebArchive } from '../apps/web/storage'; +import { readWebArchiveObservations, type StoredWebArchiveV2 } from '../apps/web/storage'; const file = new URL('../apps/web/sample/run.json', import.meta.url); @@ -42,9 +42,10 @@ describe('web sample run', () => { it('downloads the full read-only recording and names its smaller run snapshot separately', () => { const sample = loadWebSample(file)!, query = new URLSearchParams(); - const full = webSampleResponse(sample, 'download', 'GET', query), bundle = full.body as StoredWebArchive; - expect(bundle.schema).toBe('theorem-os.web-archive.v1'); - expect(bundle.events).toEqual(sample.events); expect(bundle.observations).toEqual(sample.observations); + const full = webSampleResponse(sample, 'download', 'GET', query), bundle = full.body as StoredWebArchiveV2; + expect(bundle.schema).toBe('theorem-os.web-archive.v2'); + expect(bundle.events).toEqual(sample.events); + expect(readWebArchiveObservations(bundle)).toEqual({ run: sample.run, observations: sample.observations }); expect(bundle.actions).toEqual(sample.actions); expect(bundle.commands).toEqual([]); expect(bundle.sources.length).toBeGreaterThan(0); expect(bundle.checks.length).toBeGreaterThan(0); const snapshot = webSampleResponse(sample, 'snapshot', 'GET', query); diff --git a/tests/webServer.test.ts b/tests/webServer.test.ts index e74f0975..0ab46502 100644 --- a/tests/webServer.test.ts +++ b/tests/webServer.test.ts @@ -10,6 +10,7 @@ import { readWebConfig, type WebConfig } from '../apps/web/config'; import { getLeanTaskEnvironment } from '../src/math/leanTaskEnvironment'; import { loadWebSample } from '../apps/web/sample'; import { decodeTaskDraft } from '../apps/web/client/draft'; +import { readWebArchiveObservations, type StoredWebArchiveV2 } from '../apps/web/storage'; import type { WebRunner } from '../apps/web/runner'; import { webLimits, webSampleRunId, type WebResult, type WebRun, type WebRunInput, type WebSession, type WorkerInput, type WorkerMessage } from '../apps/web/shared'; import type { WebObservation } from '../apps/web/collaboration'; @@ -590,7 +591,7 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( expect(visible.status).toBe('completed'); if (route.endsWith('/download')) { expect(response.headers.get('content-disposition')).toContain(`theoremos-${run.id}.json`); - expect(data.schema).toBe('theorem-os.web-archive.v1'); + expect(data.schema).toBe('theorem-os.web-archive.v2'); } } expect((await request(`/api/runs/${run.id}/download`, bob)).status).toBe(404); @@ -632,7 +633,7 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( expect(sample.actions.map((action: { workerId: string; kind: string }) => `${action.workerId}:${action.kind}`)).toEqual( ['solver:edit', 'engineer:edit', 'solver:edit', 'engineer:edit', 'researcher-1:edit']); const bundleResponse = await request(`${route}/download`, alice), bundle = await bundleResponse.json(); - expect(bundle.schema).toBe('theorem-os.web-archive.v1'); + expect(bundle.schema).toBe('theorem-os.web-archive.v2'); expect(bundle.events.length).toBeGreaterThan(250); expect(bundle.events[0].sequence).toBe(1); expect(bundle.actions).toHaveLength(3); @@ -656,10 +657,13 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( const owner = alice.cookie.slice('theoremos_session='.length); service.storage.saveCommand(owner, run.id, 'saved-guidance', { id: 'saved-guidance', status: 'delivered' }); runner.calls[0].finish(); await tick(); - const archive = await (await request(`/api/runs/${run.id}/download`, alice)).json(); + const archive = await (await request(`/api/runs/${run.id}/download`, alice)).json() as StoredWebArchiveV2; expect(archive.observations).toHaveLength(4); expect(archive.sources.length).toBeGreaterThan(0); expect(archive.checks.length).toBeGreaterThan(0); - expect(archive.sources).toContainEqual(recording.observations[0].sources[0]); + const recordedSource = recording.observations[0].sources[0]; + const source = archive.sources.find(item => item.taskVersion === recordedSource.taskVersion && item.commit === recordedSource.commit); + expect(source && archive.sourceBlobs[source.source.sha256]).toBe(recordedSource.source); + expect(readWebArchiveObservations(archive).observations[0].sources[0]).toEqual(recordedSource); expect(archive.commands).toEqual([{ id: 'saved-guidance', status: 'delivered' }]); expect(archive.summary).toMatchObject({ observations: 4, commands: 1, requiresFreshCheck: true, coverage: { observations: 'complete', actions: 'complete', commands: 'recorded' } }); @@ -688,7 +692,7 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( expect(data.run.error).toContain('[REDACTED]'); const download = await request(`/api/runs/${run.id}/download`, alice); expect(download.status).toBe(200); - expect(await download.json()).toMatchObject({ schema: 'theorem-os.web-archive.v1', run: data.run, + expect(await download.json()).toMatchObject({ schema: 'theorem-os.web-archive.v2', run: data.run, events: data.run.events, observations: [], actions: [], sources: [], checks: [], commands: [] }); expect(data.run).not.toHaveProperty('result'); expect(await (await request('/api/runs', alice)).text()).not.toContain(key); @@ -715,7 +719,7 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( const text = await response.text(); expect(text).not.toContain(key); const archive = JSON.parse(text); - expect(archive.schema).toBe('theorem-os.web-archive.v1'); + expect(archive.schema).toBe('theorem-os.web-archive.v2'); expect(archive.run).toEqual((await (await request(`/api/runs/${run.id}`, alice)).json()).run); expect(archive.run.status).toBe(status); expect(archive.run.source).toBe(submitted.source.replaceAll(key, '[REDACTED]')); @@ -744,7 +748,7 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( const received = await request(`/api/runs/${first.id}/download`, alice); expect(received.status).toBe(200); const archive = await received.json(); - expect(archive.schema).toBe('theorem-os.web-archive.v1'); + expect(archive.schema).toBe('theorem-os.web-archive.v2'); expect(archive.run.status).toBe('running'); expect(archive.run.result).toEqual(result); expect(runner.calls[0].signal.aborted).toBe(false); diff --git a/tests/webTrajectory.test.ts b/tests/webTrajectory.test.ts index 1a708fd4..8c47ac88 100644 --- a/tests/webTrajectory.test.ts +++ b/tests/webTrajectory.test.ts @@ -105,13 +105,33 @@ describe('web trajectory steps', () => { expect(trajectoryTaskNames(mergeTrajectory(emptyTrajectory(), first()))).toEqual(new Map([['goal_1', 'add_zero'], ['goal_2', 'zero_add']])); // The host's fixed proof note repeats the Lean outcome, so no attempt quotes it. expect(of(list, 'attempt').map(step => step.note)).toEqual([undefined, undefined]); - // Without a plan the names come from each task's own single-theorem checks; the assembled two-theorem check names nothing. + // Without a plan, each task's own receipts still identify its theorem. const unplanned = structuredClone(sample); for (const observation of unplanned.observations) observation.plan = null; expect(trajectoryTaskNames(mergeTrajectory(emptyTrajectory(), first(recordedTrajectory(unplanned.events, unplanned.observations))))) .toEqual(new Map([['goal_1', 'add_zero'], ['goal_2', 'zero_add']])); }); + it('uses the failed target to explain a mixed original-problem check without adding task attempts', () => { + const file = structuredClone(sample); + for (const observation of file.observations) { + for (const { taskId, record } of observation.checks) if (record.originalProblemPassed !== undefined) { + record.originalProblemPassed = false; + if (taskId === 'goal_2') { + record.passed = false; + record.status = 'failed'; + record.error = 'Failure in the second target'; + } + } + } + for (const event of file.events) if (event.type === 'proof_checked') event.details = { ...event.details, passed: false }; + const list = steps(file); + expect(of(list, 'attempt').map(step => step.taskId)).toEqual(['goal_1', 'goal_2']); + expect(of(list, 'proof')).toMatchObject([{ assembled: true, outcome: 'failed', + ref: { version: { taskId: 'goal_2' }, check: { passed: false, originalProblemPassed: false, + headline: 'Failure in the second target', theorems: ['Tutorial.zero_add'] } } }]); + }); + it('shows a failed attempt with its Lean reason, and the next attempt compared with it', () => { const [add, failed, passed] = of(steps(withFailedAttempt(sample)), 'attempt'); expect(add!.taskId).toBe('goal_1'); diff --git a/tests/webWorkerBridge.test.ts b/tests/webWorkerBridge.test.ts index 74edeb99..b4e611aa 100644 --- a/tests/webWorkerBridge.test.ts +++ b/tests/webWorkerBridge.test.ts @@ -14,7 +14,6 @@ import { webWorkerFixture } from './helpers/webWorkerBridge'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { webGuidanceSchema } from '../apps/web/collaborationValidation'; import { parseWorkerMessage } from '../apps/web/runner'; -import { WebStorage } from '../apps/web/storage'; import type { WebObservation } from '../apps/web/collaboration'; import { webProofMessageSink } from '../apps/web/proofJournal'; @@ -112,6 +111,54 @@ describe('isolated Web worker bridge', () => { expect(messages.filter(message => message.type === 'catalog')).toHaveLength(1); }); + it('reports each original target verdict when a shared Lean check only partially passes, including in retained observations', async () => { + const f = fixture(), firstTarget = f.state.problem.targets[0]!; + const secondTarget = { ...firstTarget, theoremName: 'Original.second', declarationHash: mathDigest('second declaration') }; + const second = { ...f.goal, id: 'second', theoremName: secondTarget.theoremName, dependsOn: [f.goal.id] }; + const { statementHash, leanStatementHash } = f.state.problem.contract; + const { commit, sourceDigest, verification } = f.proof; + const firstReceipt = { ...verification.results[0]!, theoremName: firstTarget.theoremName, receiptId: 'goal-passed', + statementHash, leanStatementHash, sourceDeclarationHash: firstTarget.declarationHash }; + const secondReceipt = { ...firstReceipt, theoremName: secondTarget.theoremName, receiptId: 'second-failed', + sourceDeclarationHash: secondTarget.declarationHash, status: 'failed' as const, error: 'Failure in second target' }; + f.state.problem.targets = [firstTarget, secondTarget]; + f.state.cooperation!.tasks = [ + { task: f.goal, status: 'pending', attempts: 0 }, { task: second, status: 'pending', attempts: 0 }, + ]; + f.state.cooperation!.history = []; + f.state.check = { commit, sourceDigest, passed: false, verification: { + ...verification, status: 'failed', results: [secondReceipt, firstReceipt], + } }; + f.save(); + + const { observation } = await createWebWorkerBridge({ + webRunId: 'web-fixture', directory: f.directory, output: f.output, + }).capture(); + expect(observation.acceptance).toBe('not-assessed'); + expect(observation.checks).toMatchObject([ + { taskId: f.goal.id, taskVersion: taskVersion(f.goal), id: firstReceipt.receiptId, commit, sourceDigest, + record: { theoremName: firstTarget.theoremName, status: 'kernel_verified', passed: true, + verification: { status: 'failed' }, acceptance: 'not-assessed' } }, + { taskId: second.id, taskVersion: taskVersion(second), id: secondReceipt.receiptId, commit, sourceDigest, + record: { theoremName: secondTarget.theoremName, status: 'failed', passed: false, error: secondReceipt.error } }, + ]); + + const legacy = { ...observation, checks: observation.checks.flatMap(({ record: { originalProblemPassed: _batch, ...record }, ...check }) => + [f.goal, second].map(task => ({ ...check, taskId: task.id, taskVersion: taskVersion(task), record: { ...record, passed: false } }))) }; + const owner = 'offline-owner', storage = new WebStorage(path.join(f.directory, 'stored-receipts')); + storage.saveObservation(owner, legacy); + expect(storage.listObservations(owner, observation.webRunId)[0]!.checks).toEqual(observation.checks); + expect(storage.getCheckReceipt(owner, observation.webRunId, secondReceipt.receiptId)).toEqual(observation.checks[1]); + expect(storage.getCheckReceipt(owner, observation.webRunId, firstReceipt.receiptId)).toEqual(observation.checks[0]); + + // A retained kernel success for another declaration hash cannot prove this frozen declaration. + const mismatched = { ...legacy, sequence: 2, checks: legacy.checks.map(check => check.id !== firstReceipt.receiptId + ? check : { ...check, record: { ...check.record, sourceDeclarationHash: 'other-declaration' } }) }; + storage.saveObservation(owner, mismatched); + expect(storage.getCheckReceipt(owner, observation.webRunId, firstReceipt.receiptId)) + .toMatchObject({ taskId: f.goal.id, record: { status: 'kernel_verified', passed: false } }); + }); + it('continues observation sequences across a host-authorized library round and retires old guidance references', async () => { const f = fixture(), messages: WorkerMessage[] = []; const options = { webRunId: 'web-fixture', directory: f.directory, onMessage: (message: WorkerMessage) => messages.push(message) };