From 0c74e7ecee985940d80d66ebf4cb6d57883dbe5f Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Wed, 25 Nov 2026 20:33:02 +0800 Subject: [PATCH] Fix workbench evidence and solver recovery --- apps/web/client/app.ts | 2 +- apps/web/client/draftRecovery.ts | 2 + apps/web/client/problemDrafts.tsx | 5 +- apps/web/client/solutionRoute.ts | 4 +- apps/web/client/trajectory.ts | 51 ++++++------ apps/web/client/trajectoryView.tsx | 75 ++++++++++-------- apps/web/client/ui/ChatWorkspace.tsx | 2 +- apps/web/jobs.ts | 10 +-- apps/web/moduleTelemetry.ts | 4 + apps/web/observationSources.ts | 78 ++++++++++++++++--- apps/web/progress.ts | 11 +-- apps/web/proofJournal.ts | 12 ++- apps/web/runner.ts | 74 ++++++++++-------- apps/web/sample.ts | 8 +- apps/web/server.ts | 20 +++-- apps/web/shared.ts | 5 +- apps/web/storage.ts | 14 ++-- apps/web/trajectory.ts | 59 ++++++++++---- apps/web/worker-command.ts | 11 ++- apps/web/workerBridge.ts | 61 ++++++++------- docs/web-workbench.md | 2 +- scripts/test-web-continuation-archive.ts | 7 +- scripts/test-web-draft-recovery.ts | 18 +++-- scripts/test-web-editor-post-state.ts | 25 ++---- .../test-web-onboarding-post-continuity.ts | 11 ++- scripts/test-web-problem-drafts.ts | 68 +++------------- scripts/test-web-problem-lifecycle.ts | 32 +------- scripts/test-web-simple-workbench.ts | 2 +- src/math/leanProofSearch.ts | 15 +++- src/solver/cooperationIntegration.ts | 22 ++++-- src/solver/cooperationTaskProofs.ts | 3 +- src/solver/modules/search.ts | 11 ++- src/solver/proofSearchTool.ts | 4 +- tests/proofSearchRuntime.test.ts | 49 ++++++++++++ tests/repeatedDelivery.test.ts | 7 +- tests/webContinuationIdentity.test.ts | 47 +++++++---- tests/webDraftRecovery.test.ts | 2 +- tests/webJobs.test.ts | 23 ++++++ tests/webKnowledgeApi.test.ts | 2 +- tests/webModuleTelemetry.test.ts | 4 + tests/webPersistence.test.ts | 31 +++++++- tests/webRunner.test.ts | 25 +++++- tests/webTrajectory.test.ts | 20 ++++- tests/webWorkerBridge.test.ts | 48 +++++++++++- 44 files changed, 645 insertions(+), 341 deletions(-) diff --git a/apps/web/client/app.ts b/apps/web/client/app.ts index 1508d3da..383e4283 100644 --- a/apps/web/client/app.ts +++ b/apps/web/client/app.ts @@ -1311,7 +1311,7 @@ function selectedProblemLibraries() { } function renderAccountProblemDraft() { const session = state.session; - const show = Boolean(session && draftReady && researchEntry === 'lean' && state.composing && !currentRun() && problemDraftTarget); + const show = Boolean(session && (session.account || problemDraftTarget) && draftReady && researchEntry === 'lean' && state.composing && !currentRun()); problemDraftHost.hidden = !show; renderProblemDraftPanel(problemDraftHost, show && session ? { owner: ownerOfSession(session), account: Boolean(session.account), value: leanProblemDraft(captureDraft(), selectedProblemLibraries()), diff --git a/apps/web/client/draftRecovery.ts b/apps/web/client/draftRecovery.ts index 7dbe6ec2..30136bcd 100644 --- a/apps/web/client/draftRecovery.ts +++ b/apps/web/client/draftRecovery.ts @@ -13,6 +13,8 @@ function copyDraft(draft: TaskDraft): TaskDraft { maxTurns: draft.maxTurns, maxRunSeconds: draft.maxRunSeconds, workers: draft.workers, ...(draft.maxTotalTokens !== undefined ? { maxTotalTokens: draft.maxTotalTokens } : {}), effort: draft.effort, environment: draft.environment, coordination: draft.coordination, templateId: draft.templateId, + ...(draft.autoExplain !== undefined ? { autoExplain: draft.autoExplain } : {}), + ...(draft.explanationLanguage !== undefined ? { explanationLanguage: draft.explanationLanguage } : {}), ...(draft.researchMode ? { researchMode: draft.researchMode } : {}), ...(draft.skillLoading ? { skillLoading: draft.skillLoading } : {}), ...(draft.nativeTeamCapacity ? { nativeTeamCapacity: draft.nativeTeamCapacity } : {}), diff --git a/apps/web/client/problemDrafts.tsx b/apps/web/client/problemDrafts.tsx index 54c55c0d..584d3b27 100644 --- a/apps/web/client/problemDrafts.tsx +++ b/apps/web/client/problemDrafts.tsx @@ -128,12 +128,15 @@ export function ProblemDraftPanel(props: ProblemDraftPanelProps) { rememberBinding(props.owner, item.version.value.mode, next, true); }); if (mounted.current && item.version.value.mode === props.value.mode) { + setOpen(false); setShowArchived(false); setNotice(submitted ? tx('已复制为新题,原提交记录和归档版本会保留。请先保存这份新草稿。', 'Copied into a new problem. The original submission and archived version remain. Save this new draft first.') : tx('已恢复到编辑器,核对后即可提交。', 'Restored in the editor. Review it before submitting.')); void load(); } } catch (cause) { if (mounted.current) notify(cause); } finally { lock.current = false; if (mounted.current) setBusy(false); } }; const visible = items.map(item => ({ ...item, versions: item.versions.filter(version => showArchived || (version.status ?? 'open') === 'open') })).filter(item => item.versions.length); - return
setOpen(event.currentTarget.open)}> + const original = props.value.mode === 'natural' ? props.value.text : props.value.draft.source; + return } } - {props.problemDrafts?.target &&
+ {props.problemDrafts && (props.problemDrafts.account || props.problemDrafts.target) &&
}
; diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index 5284f1cd..92913d93 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -143,20 +143,20 @@ export class WebJobs { if (this.list(owner).length >= webLimits.maxRuns) throw new Error(`已达到 ${webLimits.maxRuns} 条运行记录的上限。请先下载需要的档案,删除已结束的记录后重试。`); const now = new Date().toISOString(); - const pinnedDigest = input.knowledgeDigest === undefined + const knowledgeDigest = input.knowledgeDigest === undefined ? continuation ? this.get(owner, continuation.runId)?.knowledgeDigest : this.knowledge.latestReusableCatalog(owner)?.digest - : input.knowledgeDigest ?? undefined; - if (pinnedDigest && !this.knowledge.getCatalog(owner, pinnedDigest)) + : input.knowledgeDigest; + if (knowledgeDigest && !this.knowledge.getCatalog(owner, knowledgeDigest)) throw new WebStorageError(404, '所选知识目录不存在或不属于当前会话。'); const pinnedInput: WebRunInput = { ...input, environment: input.environment ?? 'standard', autoExplain: input.autoExplain ?? true, explanationLanguage: input.explanationLanguage ?? 'zh' }; if (researchConfiguration && !input.nativeTeamCapacity) pinnedInput.modulePlan = structuredClone(researchConfiguration.modulePlan); if (input.researchMode === 'skill') pinnedInput.skillLoading ??= webDefaultSkillLoading(provider); - if (pinnedDigest) pinnedInput.knowledgeDigest = pinnedDigest; + if (knowledgeDigest) pinnedInput.knowledgeDigest = knowledgeDigest; else delete pinnedInput.knowledgeDigest; const { apiKey, knowledgeDigest: _selectedKnowledgeDigest, ...visible } = pinnedInput; const environment = input.environment ?? 'standard'; - const run: WebRun = { ...clean(visible, apiKey), ...(pinnedDigest ? { knowledgeDigest: pinnedDigest } : {}), + const run: WebRun = { ...clean(visible, apiKey), ...(knowledgeDigest !== undefined ? { knowledgeDigest } : {}), environment, id: crypto.randomUUID(), title: '', status: 'queued', phase: 'queued', createdAt: now, updatedAt: now, timings: {}, events: [], modules: {} }; diff --git a/apps/web/moduleTelemetry.ts b/apps/web/moduleTelemetry.ts index 201996c7..caabb841 100644 --- a/apps/web/moduleTelemetry.ts +++ b/apps/web/moduleTelemetry.ts @@ -15,6 +15,10 @@ export function sanitizeWebEventDetails(value: unknown): WebEventDetails | undef const details: WebEventDetails = {}; for (const key of ['workerId', 'taskId', 'moduleId'] as const) if (Object.hasOwn(value, key) && typeof value[key] === 'string' && ids.test(value[key])) details[key] = value[key]; + if (Object.hasOwn(value, 'commit') && typeof value.commit === 'string' && + /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(value.commit)) details.commit = value.commit; + if (Object.hasOwn(value, 'taskDigest') && typeof value.taskDigest === 'string' && + /^[a-f0-9]{64}$/u.test(value.taskDigest)) details.taskDigest = value.taskDigest; if (details.moduleId && ['__proto__', 'prototype', 'constructor'].includes(details.moduleId)) delete details.moduleId; for (const key of ['turn', 'usedBytes', 'maxBytes'] as const) if (Object.hasOwn(value, key) && count(value[key])) details[key] = value[key]; diff --git a/apps/web/observationSources.ts b/apps/web/observationSources.ts index 752fece0..e4758aec 100644 --- a/apps/web/observationSources.ts +++ b/apps/web/observationSources.ts @@ -1,5 +1,5 @@ import { mathDigest } from '../../src/math/mathRuntimeIo'; -import type { WebObservation, WebTaskSource } from './collaboration'; +import type { WebNativeTeam, WebObservation, WebTaskSource, WebTeamProof } from './collaboration'; type SourceReference = { sha256: string }; type TaskSourceWithText = Omit & { @@ -9,12 +9,34 @@ type ObservationWithSource = Omit & { sources: export type CompactWebTaskSource = TaskSourceWithText; export type CompactWebObservation = ObservationWithSource; +type TeamProofWithSource = Omit & { + sources: { file: string; source: Text }[]; + declarations: (Omit & { checkedSource?: Text })[]; +}; +type NativeTeamWithSource = Omit & { + tasks: (Omit & { rejection?: TeamProofWithSource })[]; + deliveries: (Omit & { proof?: TeamProofWithSource })[]; + adoptions: (Omit & { proof?: TeamProofWithSource })[]; +}; +/** Older v2 archives kept native team source inline. */ +export type ArchivedWebObservation = Omit & { + inspection: Omit & { nativeTeam?: NativeTeamWithSource }; +}; export type WorkerObservationFrame = { type: 'observation'; observation: CompactWebObservation; sourceBlobs: Record; }; +export const maxWorkerObservationBytes = 15 * 1024 * 1024; + +/** A standalone frame includes every referenced blob, unlike a frame on an open stream. */ +export function standaloneObservationFrame(observation: WebObservation): WorkerObservationFrame { + const sourceBlobs: Record = {}; + const compact = compactObservation(observation, (digest, source) => { sourceBlobs[digest] = source; }); + return { type: 'observation', observation: compact, sourceBlobs }; +} + function mapSources(observation: ObservationWithSource, map: (source: From) => To): ObservationWithSource { return { ...observation, @@ -27,10 +49,9 @@ function mapSources(observation: ObservationWithSource, map: (so }; } -/** 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 { +function sourceCompactor(save: (digest: string, text: string) => void) { const digests = new Map(); - return observation => mapSources(observation, (source: string) => { + return (source: string): SourceReference => { let sha256 = digests.get(source); if (!sha256) { sha256 = mathDigest(source); @@ -38,22 +59,59 @@ export function observationCompactor(save: (digest: string, text: string) => voi save(sha256, source); } return { sha256 }; - }); + }; } export function compactObservation(observation: WebObservation, save: (digest: string, text: string) => void): CompactWebObservation { - return observationCompactor(save)(observation); + return mapSources(observation, sourceCompactor(save)); } -/** 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 { - return mapSources(observation, (source: string | SourceReference) => { +function sourceHydrator(read: (digest: string) => string | undefined) { + return (source: string | SourceReference): string => { if (typeof source === 'string') return source; if (typeof source?.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(source.sha256)) throw new Error('web_observation_source_reference_invalid'); const text = read(source.sha256); if (text === undefined) throw new Error('web_observation_source_blob_missing'); return text; + }; +} + +/** 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 { + return mapSources(observation, sourceHydrator(read)); +} + +function mapTeamSources(team: NativeTeamWithSource, map: (source: From) => To): NativeTeamWithSource { + const mapProof = ({ sources, declarations, ...proof }: TeamProofWithSource): TeamProofWithSource => ({ + ...proof, + sources: sources.map(({ source, ...file }) => ({ ...file, source: map(source) })), + declarations: declarations.map(({ checkedSource, ...declaration }) => ({ + ...declaration, ...(checkedSource === undefined ? {} : { checkedSource: map(checkedSource) }), + })), }); + return { + ...team, + tasks: team.tasks.map(({ rejection, ...task }) => ({ ...task, ...(rejection ? { rejection: mapProof(rejection) } : {}) })), + deliveries: team.deliveries.map(({ proof, ...delivery }) => ({ ...delivery, ...(proof ? { proof: mapProof(proof) } : {}) })), + adoptions: team.adoptions.map(({ proof, ...adoption }) => ({ ...adoption, ...(proof ? { proof: mapProof(proof) } : {}) })), + }; +} + +/** Share source references across archive frames, including native team proof evidence. */ +export function archiveObservationCompactor(save: (digest: string, text: string) => void) { + const reference = sourceCompactor(save); + return (observation: WebObservation): ArchivedWebObservation => { + const { nativeTeam, ...inspection } = observation.inspection; + return { ...mapSources(observation, reference), + inspection: { ...inspection, ...(nativeTeam ? { nativeTeam: mapTeamSources(nativeTeam, reference) } : {}) } }; + }; +} + +export function hydrateArchiveObservation(observation: ArchivedWebObservation, read: (digest: string) => string | undefined): WebObservation { + const resolve = sourceHydrator(read); + const { nativeTeam, ...inspection } = observation.inspection; + return { ...mapSources({ ...observation, inspection }, resolve), + inspection: { ...inspection, ...(nativeTeam ? { nativeTeam: mapTeamSources(nativeTeam, resolve) } : {}) } }; } diff --git a/apps/web/progress.ts b/apps/web/progress.ts index 1667ee89..4bff59e0 100644 --- a/apps/web/progress.ts +++ b/apps/web/progress.ts @@ -106,12 +106,13 @@ const failureDescriptions: Record = { const recoveries = new Set(['worker_recovered', 'team_transport_fallback']); const fields: Record = { turn_started: ['turn'], turn_checkpoint: ['turn', 'reason'], proof_check_started: ['turn'], - proof_checked: ['passed', 'reused'], research_action: ['operation'], + proof_checked: ['passed', 'reused', 'commit'], research_action: ['operation'], context_compiled: ['usedBytes', 'maxBytes'], evaluation_finished: ['status'], library_request_rejected: ['reason'], task_library_application: ['taskId', 'passed'], - task_assigned: ['taskId'], task_checked: ['taskId', 'passed', 'conditional'], - task_check_reused: ['taskId'], task_failure_check_reused: ['taskId'], - task_recheck_started: ['taskId'], task_recheck_finished: ['taskId', 'passed'], task_integrated: ['taskId'], + task_assigned: ['taskId'], task_checked: ['taskId', 'passed', 'conditional', 'commit', 'taskDigest'], + task_check_reused: ['taskId', 'passed', 'commit', 'taskDigest'], task_failure_check_reused: ['taskId', 'commit', 'taskDigest'], + task_recheck_started: ['taskId'], task_recheck_finished: ['taskId', 'passed', 'commit', 'taskDigest'], + task_integrated: ['taskId', 'commit', 'taskDigest'], review_assigned: ['role'], statement_review_requested: ['taskId'], statement_review_assigned: ['taskId', 'role'], statement_review_completed: ['taskId', 'status'], delivery_published: ['taskId', 'status'], research_delivered: ['taskId'], @@ -130,7 +131,7 @@ const fields: Record = { task_failed_input_recorded: ['taskId'], task_failed_input_reopened: ['taskId'], task_attempt_repeated_advisory: ['taskId'], task_repair_requested: ['taskId', 'reason'], task_repair_interrupted: ['taskId', 'reason'], task_checkpoint_continuation_requested: ['taskId'], - task_conditional_recheck_started: ['taskId'], task_conditional_recheck_finished: ['taskId', 'passed'], + task_conditional_recheck_started: ['taskId'], task_conditional_recheck_finished: ['taskId', 'passed', 'commit', 'taskDigest'], task_recheck_dependency_invalidated: ['taskId'], task_integration_superseded: ['taskId', 'reason'], statement_review_reused: ['taskId'], feasibility_review_reassigned: ['taskId', 'reason'], research_checkpoint_recorded: ['taskId'], research_checkpoint_reopened: ['taskId', 'reason'], diff --git a/apps/web/proofJournal.ts b/apps/web/proofJournal.ts index 7caeac33..ba48f691 100644 --- a/apps/web/proofJournal.ts +++ b/apps/web/proofJournal.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import { writeMathTextDurable } from '../../src/math/mathRuntimeIo'; import type { WorkerMessage } from './shared'; -import type { WorkerObservationFrame } from './observationSources'; +import { standaloneObservationFrame, type WorkerObservationFrame } from './observationSources'; export const webProofJournalDirectory = '/var/theoremos-proof'; export const webProofJournalFiles = ['transitions.json', 'observation.json', 'artifact.json', 'terminal.json'] as const; @@ -31,9 +31,17 @@ export function webProofMessageSink(output: NodeJS.WritableStream, apiKey: strin } if (file) { try { + let stored: WorkerMessage | WorkerObservationFrame = message; + if (message.type === 'observation') { + stored = standaloneObservationFrame(message.observation); + if (secret && JSON.stringify(stored).includes(secret)) { + const redacted: typeof message = JSON.parse(redact(message)); + stored = standaloneObservationFrame(redacted.observation); + } + } writeMathTextDurable(path.join(journal.directory, file), redact({ webRunId: journal.webRunId, - messages: message.type === 'library_restart' ? transitions : [message], + messages: message.type === 'library_restart' ? transitions : [stored], }) + '\n'); } catch { /* A failed backup write must not suppress the live result. */ } } diff --git a/apps/web/runner.ts b/apps/web/runner.ts index 9a70f87f..6928d4ea 100644 --- a/apps/web/runner.ts +++ b/apps/web/runner.ts @@ -29,7 +29,7 @@ import { webFormalizationPhases, webFormalizationReason, type WorkerFormalizatio import { mathDigest, readMathText } from '../../src/math/mathRuntimeIo'; import { webProofJournalDirectory, webProofJournalFiles } from './proofJournal'; import { webWorkerDisconnectGraceMs, webWorkerHeartbeatMs, webWorkerShutdownMs } from './workerDisconnect'; -import { hydrateObservation, type CompactWebObservation } from './observationSources'; +import { hydrateObservation, maxWorkerObservationBytes, type CompactWebObservation } from './observationSources'; export type WebRunner = { readiness(): Promise<{ ready: boolean; message: string; nativeTeam?: boolean; nativeTeamPreferences?: boolean; nativeTeamExpertCards?: boolean }>; @@ -99,34 +99,43 @@ const workerMessageSchema = z.discriminatedUnion('type', [ proof: z.string().max(128 * 1024), report: z.record(z.unknown()) }).strict() }).strict(), ]); -export function parseWorkerMessage(line: string, stream?: { runId: string; sources: Map }): WorkerMessage | undefined { +type ObservationStream = { runId: string; sources: Map }; + +function readWorkerObservation(observation: unknown, supplied: unknown, stream?: ObservationStream): WebObservation | undefined { + if (!object(observation) || stream && observation.webRunId !== stream.runId) return; + if (supplied === undefined) return isWebObservation(observation) ? observation : undefined; + if (!object(supplied)) return; + const current = new Map(); + let bytes = 0; + const hydrated = hydrateObservation(observation as CompactWebObservation, digest => { + const cached = current.get(digest); + if (cached !== undefined) return cached; + let source: string | undefined; + if (Object.hasOwn(supplied, digest)) { + const text = supplied[digest]; + if (typeof text !== 'string' || mathDigest(text) !== digest) throw new Error('web_observation_invalid_source_blob'); + source = text; + } else source = stream?.sources.get(digest); + if (source !== undefined) { + bytes += Buffer.byteLength(source); + if (bytes > maxWorkerObservationBytes) throw new Error('web_observation_too_large'); + current.set(digest, source); + } + return source; + }); + if (!isWebObservation(hydrated)) return; + if (stream) stream.sources = current; + return hydrated; +} + +export function parseWorkerMessage(line: string, stream?: ObservationStream): WorkerMessage | undefined { try { const value: unknown = JSON.parse(line); if (object(value) && value.type === 'observation') { - if (Object.keys(value).length === 2 && isWebObservation(value.observation)) - return { type: 'observation', observation: value.observation }; - if (Object.keys(value).length !== 3 || !object(value.observation) || !object(value.sourceBlobs) || - stream && value.observation.webRunId !== stream.runId) return; - const current = new Map(); - let bytes = 0; - const observation = hydrateObservation(value.observation as CompactWebObservation, digest => { - let source = current.get(digest); - if (source === undefined) { - const supplied = value.sourceBlobs as Record; - if (Object.hasOwn(supplied, digest)) { - const text = supplied[digest]; - if (typeof text !== 'string' || mathDigest(text) !== digest) throw new Error('web_observation_invalid_source_blob'); - source = text; - } else source = stream?.sources.get(digest); - if (source !== undefined) current.set(digest, source); - } - if (source !== undefined) bytes += Buffer.byteLength(source); - if (bytes > 15 * 1024 * 1024) throw new Error('web_observation_too_large'); - return source; - }); - if (!isWebObservation(observation)) return; - if (stream) stream.sources = current; - return { type: 'observation', observation }; + if (Object.keys(value).length !== (Object.hasOwn(value, 'sourceBlobs') ? 3 : 2)) return; + const observation = readWorkerObservation(value.observation, value.sourceBlobs, stream); + if (observation) return { type: 'observation', observation }; + return; } if (object(value) && value.type === 'catalog' && Object.keys(value).length === 2) return { type: 'catalog', catalog: validateTheoremKnowledge(value.catalog) }; @@ -150,7 +159,7 @@ async function readProofJournal(container: string, webRunId: string, signal: Abo const packet: unknown = JSON.parse(readMathText(path.join(journal, file), 16 * 1024 * 1024 + 4096)); if (!object(packet) || packet.webRunId !== webRunId || !Array.isArray(packet.messages)) continue; for (const raw of packet.messages) { - const message = parseWorkerMessage(JSON.stringify(raw)); + const message = parseWorkerMessage(JSON.stringify(raw), { runId: webRunId, sources: new Map() }); if (message) events.push(message); } } catch { /* Missing or interrupted checkpoint writes do not invalidate an available terminal receipt. */ } @@ -204,7 +213,7 @@ export class DockerWebRunner implements WebRunner { if (!this.active.has(id)) throw new Error('运行环境尚未就绪或已结束。'); return new Promise((resolve, reject) => { const child = spawn('docker', ['exec', '--interactive', `theoremos-web-${id}`, - 'bun', 'apps/web/worker-command.ts'], { stdio: ['pipe', 'pipe', 'ignore'] }); + 'bun', 'apps/web/worker-command.ts', '--observation-source-refs'], { stdio: ['pipe', 'pipe', 'ignore'] }); let output = '', settled = false; const finish = (error?: Error) => { if (settled) return; @@ -213,9 +222,12 @@ export class DockerWebRunner implements WebRunner { try { const value: unknown = JSON.parse(output); if (!object(value) || typeof value.id !== 'string' || typeof value.status !== 'string') throw new Error(); - if (value.observation && !isWebObservation(value.observation)) throw new Error(); - if (value.catalog) validateTheoremKnowledge(value.catalog); - resolve(value as WebCommandResult); + const { observation, sourceBlobs, ...receipt } = value; + const observed = observation === undefined ? undefined + : readWorkerObservation(observation, sourceBlobs, { runId: id, sources: new Map() }); + if (observation !== undefined && !observed) throw new Error(); + if (receipt.catalog) validateTheoremKnowledge(receipt.catalog); + resolve({ ...receipt, ...(observed ? { observation: observed } : {}) } as WebCommandResult); } catch { reject(new Error('运行环境未返回有效命令回执。')); } }; const timer = setTimeout(() => finish(new Error('命令回执超时,请先查询当前回执再重试。')), 15_000); diff --git a/apps/web/sample.ts b/apps/web/sample.ts index a1938014..644561db 100644 --- a/apps/web/sample.ts +++ b/apps/web/sample.ts @@ -60,9 +60,11 @@ export function webSampleResponse(sample: WebSampleFile, operation: string | und return trajectory ? { status: 200, body: { trajectory: trajectoryPage(sampleTrajectory(sample), trajectory) } } : { status: 400, body: { error: '轨迹游标无效。' } }; } if (operation === 'trajectory/version') { - const wanted = trajectoryVersionQuery(query), version = wanted && trajectoryVersion(sampleTrajectory(sample), wanted.taskId, wanted.commit); - if (!version) return { status: wanted ? 404 : 400, body: { error: wanted ? '这个版本没有记录或已超出保留范围。' : '版本参数无效。' } }; - return { status: 200, body: { version: trajectoryVersionDetail(version, sequence => sample.observations.find(item => item.sequence === sequence)) } }; + const index = sampleTrajectory(sample); + const wanted = trajectoryVersionQuery(query), version = wanted && trajectoryVersion(index, wanted.taskId, wanted.commit); + if (!version || (wanted.taskVersion !== undefined && !version.checks.some(check => check.taskVersion === wanted.taskVersion))) + return { status: wanted ? 404 : 400, body: { error: wanted ? '这个版本没有记录或已超出保留范围。' : '版本参数无效。' } }; + return { status: 200, body: { version: trajectoryVersionDetail(index, version, sequence => sample.observations.find(item => item.sequence === sequence), wanted.taskVersion) } }; } const newestFirst = [...sample.observations].reverse(); const source = /^tasks\/([^/]+)\/source$/u.exec(operation); diff --git a/apps/web/server.ts b/apps/web/server.ts index 48267244..b4c544c6 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -91,6 +91,7 @@ const inputSchema = z.object({ // A question about one recorded version; its code and Lean's output are read here, never taken from the request. const explainSchema = z.object({ taskId: z.string().min(1).max(200), commit: z.string().regex(/^[A-Za-z0-9]{1,128}$/u), + taskVersion: z.string().min(1).max(200).optional(), question: z.string().trim().min(1).max(webExplainLimits.question), turns: z.array(z.object({ question: z.string().min(1).max(webExplainLimits.question), answer: z.string().min(1).max(webExplainLimits.answer) }).strict()).max(webExplainLimits.turns).default([]), @@ -1044,14 +1045,21 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock throw new HttpError(503, '当前运行镜像不支持个人专家资料。请移除专家资产或更新运行镜像。'); if (input.nativeTeamPreferredProfiles?.length && !readiness.nativeTeamPreferences) throw new HttpError(503, '当前运行镜像不支持角色偏好。清空偏好后仍可使用原生团队。'); const from = input.continueFrom as WebContinuation | undefined; - const saved = from && jobs.get(owner, from.runId) ? trajectories.version(owner, from.runId, from.taskId, from.commit)?.source : undefined; - if (from && !saved) throw new HttpError(404, '这个版本的代码没有记录或已超出保留范围。'); - if (from && saved && (['taskVersion', 'sourceDigest', 'environmentDigest', 'file'] as const).some(field => from[field] !== undefined && from[field] !== saved[field])) + const previousRun = from ? jobs.get(owner, from.runId) : undefined; + const saved = from && previousRun ? from.taskVersion + ? storage.getTaskSource(owner, from.runId, from.taskId, from.taskVersion, from.commit) + : trajectories.version(owner, from.runId, from.taskId, from.commit)?.source : undefined; + if (from && !saved) { + if (previousRun && from.taskVersion && trajectories.version(owner, from.runId, from.taskId, from.commit)?.source) + throw new HttpError(409, '续跑来源的固定版本与保存记录不一致,请重新选择。'); + throw new HttpError(404, '这个版本的代码没有记录或已超出保留范围。'); + } + if (from && saved && (['sourceDigest', 'environmentDigest', 'file'] as const).some(field => from[field] !== undefined && from[field] !== saved[field])) throw new HttpError(409, '续跑来源的固定版本与保存记录不一致,请重新选择。'); const approved = input.formalizationId ? formalizations.confirmed(owner, input.formalizationId) : undefined; if (approved && (input.source !== approved.evidence.candidate.source || input.environment !== approved.evidence.request.environment)) throw new HttpError(409, 'Lean 原题或环境已改变,请重新形式化确认,或作为普通 Lean 题目创建。'); - if (from && jobs.get(owner, from.runId)?.formalizationId !== input.formalizationId) + if (from && previousRun?.formalizationId !== input.formalizationId) throw new HttpError(409, '继续研究必须保留原运行的形式化来源。'); // Only a new run costs allowance; a replayed request above already returned the run it created. admitWork(); @@ -1210,7 +1218,7 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (operation === 'trajectory/version' && request.method === 'GET') { const query = trajectoryVersionQuery(url.searchParams); if (!query) throw new HttpError(400, '版本参数无效。'); - const version = trajectories.version(owner, run.id, query.taskId, query.commit); + const version = trajectories.version(owner, run.id, query.taskId, query.commit, query.taskVersion); if (!version) throw new HttpError(404, '这个版本没有记录或已超出保留范围。'); json(response, 200, { version }); return; } @@ -1221,7 +1229,7 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (!provider) throw new HttpError(409, '这次运行的模型服务已不在配置中。'); const apiKey = parsed.data.apiKey || heldKey(session, provider); if (!apiKey) throw new HttpError(400, '请填写 API Key。'); - const version = trajectories.version(owner, run.id, parsed.data.taskId, parsed.data.commit); + const version = trajectories.version(owner, run.id, parsed.data.taskId, parsed.data.commit, parsed.data.taskVersion); if (!version) throw new HttpError(404, '这个版本没有记录或已超出保留范围。'); const feedback = failedFeedback(version.checks); if (!feedback) throw new HttpError(409, '这个版本没有未通过的 Lean 检查可以解释。'); diff --git a/apps/web/shared.ts b/apps/web/shared.ts index fb185472..d1afa29f 100644 --- a/apps/web/shared.ts +++ b/apps/web/shared.ts @@ -119,6 +119,8 @@ export type WebEventDetails = { maxBytes?: number; status?: string; taskId?: string; + taskDigest?: string; + commit?: string; role?: 'lead' | 'researcher' | 'prover' | 'engineer' | 'reviewer'; moduleId?: string; slot?: ResearchModuleSlot; @@ -178,7 +180,8 @@ export type WebRun = { agentHarness?: NonNullable; planApproval?: boolean; modulePlan?: ResearchModulePlan; - knowledgeDigest?: string; + /** Frozen catalog digest, or null when the researcher explicitly chose no history. */ + knowledgeDigest?: string | null; continueFrom?: WebContinuation; formalizationId?: string; formalization?: { id: string; evidenceSha256?: string; original: string; confirmedAt?: string; candidateDigest?: string; diff --git a/apps/web/storage.ts b/apps/web/storage.ts index f12365f6..3f8cfc23 100644 --- a/apps/web/storage.ts +++ b/apps/web/storage.ts @@ -5,8 +5,8 @@ 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, observationCompactor, - type CompactWebObservation, type CompactWebTaskSource } from './observationSources'; +import { archiveObservationCompactor, compactObservation, hydrateArchiveObservation, hydrateObservation, + type ArchivedWebObservation, type CompactWebObservation, type CompactWebTaskSource } from './observationSources'; import { projectStoredObservationChecks } from './observationChecks'; export type WebCreation = { schema: 'theorem-os.web-creation.v1'; requestId: string; digest: string }; @@ -31,11 +31,11 @@ type ArchiveRecords = { 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[]; + run: Omit & { observation?: ArchivedWebObservation }; + observations: ArchivedWebObservation[]; sources: CompactWebTaskSource[]; sourceBlobs: Record; - commands: (Omit & { observation?: CompactWebObservation })[]; + commands: (Omit & { observation?: ArchivedWebObservation })[]; }; export type StoredWebArchive = StoredWebArchiveV1 | StoredWebArchiveV2; @@ -63,7 +63,7 @@ export function webArchive(run: WebRun, records: { observations: WebObservation[ actions: WebAgentAction[]; commands: WebCommandResult[] }, catalogDigest?: string): StoredWebArchiveV2 { const { events, actions, commands } = records; const sourceBlobs: Record = {}; - const referenceSources = observationCompactor((digest, source) => { sourceBlobs[digest] = source; }); + const referenceSources = archiveObservationCompactor((digest, source) => { sourceBlobs[digest] = source; }); const compact = (frame: WebObservation) => referenceSources(projectStoredObservationChecks(frame)); const observations = records.observations.map(compact); const { observation, ...runFields } = run; @@ -98,7 +98,7 @@ export function webArchive(run: WebRun, records: { observations: WebObservation[ 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]); + const hydrate = (frame: ArchivedWebObservation) => hydrateArchiveObservation(frame, digest => archive.sourceBlobs[digest]); return { run: { ...run, ...(observation ? { observation: hydrate(observation) } : {}) }, observations: archive.observations.map(hydrate) }; } diff --git a/apps/web/trajectory.ts b/apps/web/trajectory.ts index 7f35bc91..6e4ccf56 100644 --- a/apps/web/trajectory.ts +++ b/apps/web/trajectory.ts @@ -32,7 +32,7 @@ const readLimits = { events: 5_000, observations: 40 } as const; /** 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 }; + originalProblemPassed?: boolean; taskVersion?: string; file?: string }; /** 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; @@ -57,6 +57,7 @@ export type TrajectoryContext = { workers: { id: string; role: string }[]; targe export type TrajectoryIndex = { instance: string; revision: number; eventCursor: number; observationCursor: number; lastObservedAt?: number; events: WebEvent[]; versions: Map; sources: Map; + sourceRevisions: Map; plans: TrajectoryPlan[]; plan?: Map; planVersion?: string; deliveries: Map; guidance: Map; edits: Map; workers: Map; targets: string[]; contextRevision: number; @@ -68,7 +69,7 @@ export type TrajectoryIndex = { let instances = 0; const started = Date.now().toString(36); export function createTrajectoryIndex(): TrajectoryIndex { - return { instance: `${started}-${++instances}`, revision: 0, eventCursor: 0, observationCursor: 0, events: [], versions: new Map(), sources: new Map(), + return { instance: `${started}-${++instances}`, revision: 0, eventCursor: 0, observationCursor: 0, events: [], versions: new Map(), sources: new Map(), sourceRevisions: new Map(), plans: [], deliveries: new Map(), guidance: new Map(), edits: new Map(), workers: new Map(), targets: [], contextRevision: 0, retired: new Set(), dropped: { events: 0, versions: 0, plans: 0, deliveries: 0, guidance: 0, edits: 0 } }; } @@ -76,6 +77,7 @@ export function createTrajectoryIndex(): TrajectoryIndex { const clip = (value: string | undefined, limit: number) => value === undefined ? undefined : value.length > limit ? `${value.slice(0, limit - 1)}…` : value; const millis = (value: string | number | undefined) => typeof value === 'number' ? value : value === undefined ? NaN : Date.parse(value); const versionKey = (taskId: string, commit: string) => `${taskId}\u0000${commit}`; +const sourceRevisionKey = (key: string, taskVersion: string) => `${key}\u0000${taskVersion}`; /** Drops the oldest entries over the limit, remembering them so a repeated record is not added again. */ function trim(index: TrajectoryIndex, section: keyof TrajectoryIndex['dropped'], items: Map, limit: number) { for (const key of items.keys()) { @@ -110,12 +112,22 @@ function foldEvents(index: TrajectoryIndex, events: readonly WebEvent[]) { function foldSource(index: TrajectoryIndex, source: WebTaskSource, observation: number) { const key = versionKey(source.taskId, source.commit); + if (retired(index, 'versions', key)) return; const version = index.versions.get(key); + const revision = sourceRevisionKey(key, source.taskVersion); + if (!index.sourceRevisions.has(revision)) { + index.sourceRevisions.set(revision, observation); + for (const old of index.sourceRevisions.keys()) { + if (index.sourceRevisions.size <= trajectoryLimits.versions) break; + index.sourceRevisions.delete(old); + } + if (version) version.revision = index.revision; + } if (version) { if (version.source === undefined) { version.source = observation; version.file = source.file; version.revision = index.revision; } return; } - if (index.sources.has(key) || retired(index, 'versions', key)) return; + if (index.sources.has(key)) return; index.sources.set(key, { file: source.file, observation }); // Sources wait here until a check names them; the map is bounded like the versions it feeds. for (const old of index.sources.keys()) { if (index.sources.size <= trajectoryLimits.versions) break; index.sources.delete(old); } @@ -138,11 +150,12 @@ function foldCheck(index: TrajectoryIndex, receipt: WebCheckReceipt, observation if (!index.versions.has(key)) return; } const originalProblemPassed = typeof record.originalProblemPassed === 'boolean' ? record.originalProblemPassed : undefined; - let check = version.checks.find(item => item.at === at && item.originalProblemPassed === originalProblemPassed); + let check = version.checks.find(item => item.at === at && item.originalProblemPassed === originalProblemPassed && item.taskVersion === receipt.taskVersion); 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, taskVersion: receipt.taskVersion, + ...(typeof record.proofPath === 'string' ? { file: record.proofPath } : {}), ...(originalProblemPassed === undefined ? {} : { originalProblemPassed }) }; version.checks.push(check); version.checks.sort((a, b) => a.at - b.at); @@ -292,16 +305,22 @@ export function trajectoryPage(index: TrajectoryIndex, query: TrajectoryQuery, b /** One version's saved file and receipts, read only from the observations the index recorded for it. */ export type TrajectoryVersionDetail = { taskId: string; commit: string; source?: WebTaskSource; checks: WebCheckReceipt[] }; -export function trajectoryVersionDetail(version: TrajectoryVersion, observation: (sequence: number) => WebObservation | undefined): TrajectoryVersionDetail { - const sequences = [...new Set([...(version.source !== undefined ? [version.source] : []), ...version.checks.map(check => check.observation)])]; - const receipts = new Set(version.checks.flatMap(check => check.receiptIds)); +export function trajectoryVersionDetail(index: TrajectoryIndex, version: TrajectoryVersion, + observation: (sequence: number) => WebObservation | undefined, taskVersion?: string): TrajectoryVersionDetail { + const selected = taskVersion === undefined ? version.checks : version.checks.filter(check => check.taskVersion === taskVersion); + const sourceFrame = taskVersion === undefined ? version.source + : index.sourceRevisions.get(sourceRevisionKey(version.key, taskVersion)); + const sequences = [...new Set([...(sourceFrame !== undefined ? [sourceFrame] : []), ...selected.map(check => check.observation)])]; + const receipts = new Set(selected.flatMap(check => check.receiptIds)); + const matches = (item: WebTaskSource | WebCheckReceipt) => item.taskId === version.taskId && item.commit === version.commit && + (taskVersion === undefined || item.taskVersion === taskVersion); let source: WebTaskSource | undefined; const checks = new Map(); for (const sequence of sequences) { const item = observation(sequence); if (!item) continue; - source ??= item.sources.find(entry => entry.taskId === version.taskId && entry.commit === version.commit); - for (const check of item.checks) if (check.taskId === version.taskId && check.commit === version.commit && receipts.has(check.id) && !checks.has(check.id)) checks.set(check.id, check); + source ??= item.sources.find(matches); + for (const check of item.checks) if (matches(check) && receipts.has(check.id) && !checks.has(check.id)) checks.set(check.id, check); } return { taskId: version.taskId, commit: version.commit, ...(source ? { source } : {}), checks: [...checks.values()].slice(-64) }; } @@ -313,9 +332,11 @@ export function trajectoryQuery(params: URLSearchParams): TrajectoryQuery | unde if (instance !== undefined && !/^[a-z0-9-]{1,64}$/u.test(instance)) return; return { after, since, ...(instance ? { instance } : {}) }; } -export function trajectoryVersionQuery(params: URLSearchParams): { taskId: string; commit: string } | undefined { - const taskId = params.get('task') ?? '', commit = params.get('commit') ?? ''; - return taskId && taskId.length <= 200 && /^[A-Za-z0-9]{1,128}$/u.test(commit) ? { taskId, commit } : undefined; +export function trajectoryVersionQuery(params: URLSearchParams): { taskId: string; commit: string; taskVersion?: string } | undefined { + const taskId = params.get('task') ?? '', commit = params.get('commit') ?? '', taskVersion = params.get('taskVersion'); + if (!taskId || taskId.length > 200 || !/^[A-Za-z0-9]{1,128}$/u.test(commit) || + (taskVersion !== null && (!taskVersion || taskVersion.length > 200))) return; + return { taskId, commit, ...(taskVersion !== null ? { taskVersion } : {}) }; } export const trajectoryVersion = (index: TrajectoryIndex, taskId: string, commit: string) => index.versions.get(versionKey(taskId, commit)); @@ -344,12 +365,16 @@ export class WebTrajectories { const { index, behind } = this.read(owner, runId); return trajectoryPage(index, query, behind); } - version(owner: string, runId: string, taskId: string, commit: string): TrajectoryVersionDetail | undefined { + version(owner: string, runId: string, taskId: string, commit: string, taskVersion?: string): TrajectoryVersionDetail | undefined { + const find = (index: TrajectoryIndex) => { + const version = trajectoryVersion(index, taskId, commit); + if (taskVersion === undefined || version?.checks.some(check => check.taskVersion === taskVersion)) return version; + }; let read = this.read(owner, runId); // A rebuilt index catches up before answering, a bounded number of chunks at a time. - for (let chunk = 0; read.behind && !trajectoryVersion(read.index, taskId, commit) && chunk < 50; chunk++) read = this.read(owner, runId); - const version = trajectoryVersion(read.index, taskId, commit); - return version && trajectoryVersionDetail(version, sequence => this.reader.getObservation(owner, runId, sequence)); + for (let chunk = 0; read.behind && !find(read.index) && chunk < 50; chunk++) read = this.read(owner, runId); + const version = find(read.index); + return version && trajectoryVersionDetail(read.index, version, sequence => this.reader.getObservation(owner, runId, sequence), taskVersion); } forget(owner: string, runId: string) { this.indexes.delete(`${owner}\u0000${runId}`); } forgetOwner(owner: string) { for (const key of [...this.indexes.keys()]) if (key.startsWith(`${owner}\u0000`)) this.indexes.delete(key); } diff --git a/apps/web/worker-command.ts b/apps/web/worker-command.ts index f22d4c2f..8570b532 100644 --- a/apps/web/worker-command.ts +++ b/apps/web/worker-command.ts @@ -1,9 +1,10 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { handleWebWorkerCommand } from './workerBridge'; +import { standaloneObservationFrame } from './observationSources'; /** Private docker-exec input; command payloads never become arguments or container metadata. */ -export async function runWebWorkerCommand(input: NodeJS.ReadableStream = process.stdin): Promise { +export async function runWebWorkerCommand(input: NodeJS.ReadableStream = process.stdin, sourceRefs = false): Promise { let bytes = 0; const chunks: Buffer[] = []; try { @@ -15,11 +16,15 @@ export async function runWebWorkerCommand(input: NodeJS.ReadableStream = process } const command = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); const result = await handleWebWorkerCommand(command); - process.stdout.write(JSON.stringify(result) + '\n'); + if (sourceRefs && result.observation) { + const { observation, sourceBlobs } = standaloneObservationFrame(result.observation); + process.stdout.write(JSON.stringify({ ...result, observation, sourceBlobs }) + '\n'); + } else process.stdout.write(JSON.stringify(result) + '\n'); } catch (error) { process.stdout.write(JSON.stringify({ id: 'command', status: 'rejected', reason: error instanceof Error ? error.message : 'web_command_failed' }) + '\n'); } } -if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) void runWebWorkerCommand(); +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) + void runWebWorkerCommand(process.stdin, process.argv.includes('--observation-source-refs')); diff --git a/apps/web/workerBridge.ts b/apps/web/workerBridge.ts index 0b039988..93eb1ab6 100644 --- a/apps/web/workerBridge.ts +++ b/apps/web/workerBridge.ts @@ -18,7 +18,7 @@ import type { WebCheckReceipt, WebCommand, WebCommandResult, WebObservation, Web import type { WorkerMessage } from './shared'; import { projectWebDeclarationArtifacts } from './declarationArtifacts'; import { projectWebNativeTeam } from './nativeTeamObservation'; -import { compactObservation, type WorkerObservationFrame } from './observationSources'; +import { maxWorkerObservationBytes, standaloneObservationFrame, type WorkerObservationFrame } from './observationSources'; export const webActiveRunFile = '/work/active-run.json'; const activeRunSchema = z.object({ schema: z.literal('theorem-os.web-active-run.v1'), @@ -32,7 +32,6 @@ const metaSchema = z.object({ schema: z.literal('theorem-os.web-bridge.v1'), web }).strict(); type BridgeMeta = z.infer; const maxSourceBytes = 4 * 1024 * 1024, maxSourcesBytes = 6 * 1024 * 1024, maxChecksBytes = 2 * 1024 * 1024; -const maxMessageBytes = 15 * 1024 * 1024; const oid = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u; const childOf = (directory: string, file: string) => path.isAbsolute(file) && file.startsWith(directory + path.sep); const relativePath = (file: string) => file && !path.isAbsolute(file) && !file.includes('\\') && @@ -107,6 +106,7 @@ function sourceProjection(state: SolverRunState, directory: string) { const sources: WebTaskSource[] = [], checks: WebCheckReceipt[] = []; let sourceBytes = 0, checkBytes = 0, sourcePartial = false, checkPartial = false; const sourceIds = new Set(), checkIds = new Set(); + const sourceTexts = new Set(); const roots = runRoots(state, directory), snapshots = new Map>(); const snapshot = (commit: string) => { let value = snapshots.get(commit); @@ -123,11 +123,14 @@ function sourceProjection(state: SolverRunState, directory: string) { const source = selected.files[file], dependencySources = Object.entries(selected.files) .filter(([dependency]) => dependency !== file && dependency.endsWith('.lean')) .map(([file, source]) => ({ file, source })); - const bytes = Buffer.byteLength(source) + dependencySources.reduce((sum, dependency) => sum + Buffer.byteLength(dependency.source), 0); + const newTexts = [...new Set([source, ...dependencySources.map(dependency => dependency.source)])] + .filter(text => !sourceTexts.has(text)); + const bytes = newTexts.reduce((sum, text) => sum + Buffer.byteLength(text), 0); if (sourceBytes + bytes > maxSourcesBytes) { sourcePartial = true; return; } sources.push({ taskId: node.task.id, taskVersion: version, commit, sourceDigest: selected.digest, environmentDigest: state.environmentDigest, file, source, scope: 'owned-file', ...(dependencySources.length ? { dependencySources } : {}) }); + for (const text of newTexts) sourceTexts.add(text); sourceBytes += bytes; sourceIds.add(key); } catch { sourcePartial = true; } }; @@ -176,10 +179,13 @@ 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') { + const wholeChecks = [state.check, ...(state.workers ?? []).map(worker => worker.check)] + .filter((proof): proof is ProofCheck => proof !== undefined); + 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 (!target) continue; + for (const proof of wholeChecks) if (proof.verification.results.some(receipt => + receipt.proofPath === target.proofPath && receipt.theoremName === target.theoremName)) addProof(node, proof, target); } if (!state.cooperation?.tasks.length && state.problem.targets.length) sourcePartial = true; return { sources, checks, coverage: { sources: sourcePartial ? 'partial' as const : 'recorded' as const, @@ -232,19 +238,26 @@ export function createWebWorkerBridge(options: { if (state.cooperation?.planVersion && state.cooperation.tasks.length) plan = exportRunPlan(state); const payload = { inspection, snapshot: inspection.snapshot, plan, ...projection, declarations, guidance: readHumanGuidance(stateFile, state.runId), deliveries: state.cooperation?.deliveries ?? [], history }; - const contentDigest = mathDigest(canonicalMathJson(payload)); + let observation: WebObservation = { schema: 'theorem-os.web-observation.v1', webRunId: options.webRunId, + solverRunId: state.runId, sequence: 0, observedAt: new Date().toISOString(), evidence: 'recorded-not-replayed', + acceptance: 'not-assessed', ...payload }; + let frame = standaloneObservationFrame(observation); + const contentDigest = mathDigest(canonicalMathJson({ ...frame.observation, observedAt: '' })); const changed = restarted || previous?.contentDigest !== contentDigest; const sequence = (previous?.sequence ?? 0) + Number(changed); if (restarted) messages.push({ type: 'library_restart', previousSolverRunId: previous!.solverRunId, solverRunId: state.runId, round: options.libraryRestart!.round }); - let observation: WebObservation = { schema: 'theorem-os.web-observation.v1', webRunId: options.webRunId, - solverRunId: state.runId, sequence, observedAt: new Date().toISOString(), evidence: 'recorded-not-replayed', - acceptance: 'not-assessed', ...payload }; - if (options.apiKey && canonicalMathJson(observation).includes(options.apiKey)) { - observation = JSON.parse(JSON.stringify(observation).replaceAll(JSON.stringify(options.apiKey).slice(1, -1), '[REDACTED]')); + observation.sequence = sequence; + frame.observation.sequence = sequence; + let frameJson = JSON.stringify(frame); + const secret = options.apiKey && JSON.stringify(options.apiKey).slice(1, -1); + if (secret && frameJson.includes(secret)) { + observation = JSON.parse(JSON.stringify(observation).replaceAll(secret, '[REDACTED]')); observation.coverage.sources = 'partial'; observation.coverage.checks = 'partial'; + frame = standaloneObservationFrame(observation); + frameJson = JSON.stringify(frame); } - if (Buffer.byteLength(canonicalMathJson(observation)) > maxMessageBytes) throw new Error('web_observation_too_large'); + if (Buffer.byteLength(frameJson) > maxWorkerObservationBytes) throw new Error('web_observation_too_large'); const meta: BridgeMeta = { schema: 'theorem-os.web-bridge.v1', webRunId: options.webRunId, solverRunId: state.runId, libraryRound: options.libraryRestart?.round ?? previous?.libraryRound ?? 0, sequence, contentDigest, observations: [...(restarted ? [] : previous?.observations ?? []), @@ -258,11 +271,11 @@ export function createWebWorkerBridge(options: { const imported = importKnowledgeRuns([stateFile], { includeFindings: true }); if (buildRunInspection(readRunInspection(options.output).state).snapshot.stateDigest !== inspection.snapshot.stateDigest) throw new Error('web_catalog_state_changed'); - const base = fs.existsSync(catalogFile) ? validateTheoremKnowledge(JSON.parse(readMathText(catalogFile, maxMessageBytes))) : undefined; + const base = fs.existsSync(catalogFile) ? validateTheoremKnowledge(JSON.parse(readMathText(catalogFile, maxWorkerObservationBytes))) : undefined; const candidate = buildTheoremKnowledge(imported.candidates, base, imported.findings); const text = canonicalMathJson(candidate); if (options.apiKey && text.includes(options.apiKey)) throw new Error('web_catalog_secret_redacted'); - if (Buffer.byteLength(text) > maxMessageBytes) throw new Error('web_catalog_too_large'); + if (Buffer.byteLength(text) > maxWorkerObservationBytes) throw new Error('web_catalog_too_large'); const digest = mathDigest(text); if (digest !== previous?.catalogDigest) { writeMathJsonDurable(catalogFile, candidate); catalog = candidate; } meta.catalogKey = key; meta.catalogDigest = digest; @@ -274,27 +287,23 @@ export function createWebWorkerBridge(options: { } } if (input.includeCatalog && !catalog && fs.existsSync(catalogFile)) { - catalog = validateTheoremKnowledge(JSON.parse(readMathText(catalogFile, maxMessageBytes))); + catalog = validateTheoremKnowledge(JSON.parse(readMathText(catalogFile, maxWorkerObservationBytes))); } lease.assertHeld(); if (!previous || canonicalMathJson(previous) !== canonicalMathJson(meta)) writeMathJsonDurable(metaFile, meta); if (changed || input.force) messages.push({ type: 'observation', observation }); if (catalog) messages.push({ type: 'catalog', catalog }); - return { observation, ...(catalog ? { catalog } : {}) }; + return { frame, result: { observation, ...(catalog ? { catalog } : {}) } }; }); for (const message of messages) { if (!options.onMessage) break; if (message.type !== 'observation') { options.onMessage(message); continue; } - const current = new Set(); - const sourceBlobs: Record = {}; - const observation = compactObservation(message.observation, (digest, source) => { - current.add(digest); - if (!emittedSources.has(digest)) sourceBlobs[digest] = source; - }); - options.onMessage(message, { type: 'observation', observation, sourceBlobs }); - emittedSources = current; + const blobs = Object.entries(result.frame.sourceBlobs); + const sourceBlobs = Object.fromEntries(blobs.filter(([digest]) => !emittedSources.has(digest))); + options.onMessage(message, { ...result.frame, sourceBlobs }); + emittedSources = new Set(blobs.map(([digest]) => digest)); } - return result; + return result.result; } return { capture }; } diff --git a/docs/web-workbench.md b/docs/web-workbench.md index eecaaa07..8fdb4c2f 100644 --- a/docs/web-workbench.md +++ b/docs/web-workbench.md @@ -232,7 +232,7 @@ 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` 运行快照导入任务草稿。 +直接下载和新保存的完整归档使用 `theorem-os.web-archive.v2`。任务、依赖和原生团队证明的源码使用 `{"sha256":"…"}` 引用,按摘要在同一文件的 `sourceBlobs` 对象中查找原文。历史观测、最近观测、命令回执附带的观测和顶层源码索引共用这份原文表。早期 v2 归档的原生团队源码为内联文本。摘要继续记录覆盖范围和证据数量,`summary.digest` 绑定实际导出的内容。旧 v1 归档按保存时的格式和摘要下载。工作台可以从两版归档和 `theorem-os.web-export.v1` 运行快照导入任务草稿,并保留明确选择的「不使用历史知识」。 ### 配置研究模块 diff --git a/scripts/test-web-continuation-archive.ts b/scripts/test-web-continuation-archive.ts index 48112d9d..71e5f7ab 100644 --- a/scripts/test-web-continuation-archive.ts +++ b/scripts/test-web-continuation-archive.ts @@ -100,7 +100,8 @@ try { assert.equal(goals.goals[0]!.subgoals[0]!.state, 'proved'); assert.ok(nextSteps(run, goals).some(step => step.id === 'continue-checked' && step.tasks.includes('goal_1'))); const helper = run.observation!.inspection.tasks.find(task => task.id === 'goal_1')!; - const checkedSource = run.observation!.sources.find(item => item.taskId === helper.id && item.commit === helper.proof.commit)!; + const checkedSource = run.observation!.sources.find(item => + item.taskId === helper.id && item.commit === helper.proof.commit && item.taskVersion === helper.version)!; assert.equal(helper.proof.status, 'checked'); assert.ok(checkedSource); const owner = (await context.cookies(origin)).find(cookie => cookie.name === 'theoremos_session')!.value; service.storage.saveCommand(owner, run.id, 'fixture-guidance', { id: 'fixture-guidance', status: 'delivered' }); @@ -116,6 +117,8 @@ try { 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); + assert.ok(archive.sources.some(item => item.taskId === helper.id && item.commit === helper.proof.commit && item.taskVersion !== helper.version), + 'the same commit also has a source saved under an earlier task version'); assert.deepEqual(archive.commands, [{ id: 'fixture-guidance', status: 'delivered' }]); assert.deepEqual(archive.summary.coverage, { events: 'complete', observations: 'complete', actions: 'complete', commands: 'recorded', sources: 'partial', checks: 'partial' }); @@ -155,7 +158,7 @@ try { assert.equal(starts.length, 2); assert.equal(starts[1]!.input.source, source); assert.deepEqual(starts[1]!.continuation, { runId: run.id, taskId: helper.id, commit: helper.proof.commit, - label: starts[1]!.continuation!.label, taskVersion: archive.sources.find(item => item.taskId === helper.id && item.commit === helper.proof.commit)!.taskVersion, sourceDigest: checkedSource.sourceDigest, + label: starts[1]!.continuation!.label, taskVersion: helper.version, sourceDigest: checkedSource.sourceDigest, environmentDigest: checkedSource.environmentDigest, file: checkedSource.file, source: checkedSource.source }); assert.match(starts[1]!.continuation!.label, /add_zero/u); const continued = await waitForRun(h, starts[1]!.id, item => item.status === 'completed'); diff --git a/scripts/test-web-draft-recovery.ts b/scripts/test-web-draft-recovery.ts index ab41d1cf..82e8c310 100644 --- a/scripts/test-web-draft-recovery.ts +++ b/scripts/test-web-draft-recovery.ts @@ -94,9 +94,10 @@ async function assertDraft(page: Page, expected: TaskDraft) { assert.deepEqual(a async function recovery(page: Page): Promise { return page.evaluate(key => { const raw = sessionStorage.getItem(key); return raw ? JSON.parse(raw) : null; }, recoveryKey); } +const withExplanationDefaults = (draft: TaskDraft): TaskDraft => ({ autoExplain: true, explanationLanguage: 'zh', ...draft }); async function assertBackup(page: Page, expected: TaskDraft, reason: string) { await page.locator('#draft-recovery').waitFor({ state: 'visible' }); - assert.deepEqual(await recovery(page), { schema: recoveryKey, reason, task: { schema: draftKey, draft: expected }, libraries: [] }); + assert.deepEqual(await recovery(page), { schema: recoveryKey, reason, task: { schema: draftKey, draft: withExplanationDefaults(expected) }, libraries: [] }); assert.equal(await page.locator('#draft-recovery-local').isVisible(), false); } async function privateStorage(page: Page) { @@ -106,9 +107,10 @@ async function privateStorage(page: Page) { return { session, local: JSON.stringify(localStorage) }; }); assert.equal(stored.session?.includes(credential) ?? false, false, 'neither saved draft may retain the entered API Key'); - // Only the open run ID and the notification preference persist; neither holds draft text. + // The open run and interface preferences persist independently of drafts. const local = JSON.parse(stored.local) as Record; delete local['theorem-os.web-resume.v1']; delete local['theorem-os.web-notify.v1']; + delete local['theoremos-history-collapsed-v1']; assert.deepEqual(local, {}, 'draft recovery must not write to localStorage'); assert.equal(stored.local.includes(credential), false); if (stored.session) { @@ -279,7 +281,7 @@ try { await page.locator('#run-settings[open]').waitFor(); await assertDraft(page, fixture.draft); assert.equal(await page.locator('#api-key').evaluate(field => field === document.activeElement), true); - assert.deepEqual((await recovery(page))?.task.draft, original); + assert.deepEqual((await recovery(page))?.task.draft, withExplanationDefaults(original)); assert.equal((await recovery(page))?.reason, 'reuse'); await restore(page, original, true); await closeSettings(page); assert.equal(await page.locator('#run-count').textContent(), '1', 'restoring must not add or delete history'); @@ -303,7 +305,7 @@ try { await importJson(page, incoming); await page.locator('#import-task-dialog[open]').waitFor(); await closeDialog(page, '#import-task-dialog', () => page.locator('#confirm-import').click()); await page.locator('#run-settings[open]').waitFor(); await assertDraft(page, incoming); - assert.equal((await recovery(page))?.reason, 'import'); assert.deepEqual((await recovery(page))?.task.draft, current); + assert.equal((await recovery(page))?.reason, 'import'); assert.deepEqual((await recovery(page))?.task.draft, withExplanationDefaults(current)); assert.equal(await page.locator('#api-key').evaluate(field => field === document.activeElement), true); await restore(page, current, true); await closeSettings(page); }); @@ -322,7 +324,7 @@ try { await fileStarted(page); await releaseFile(page); await assertBackup(page, initial, 'source'); await page.locator('#source-file').setInputFiles({ name: 'wrong.txt', mimeType: 'text/plain', buffer: Buffer.from('wrong') }); await page.locator('#source-error').waitFor({ state: 'visible' }); - assert.deepEqual((await recovery(page))?.task.draft, initial); + assert.deepEqual((await recovery(page))?.task.draft, withExplanationDefaults(initial)); await closeSettings(page); await restore(page, initial); await page.locator('#source-file').setInputFiles({ name: 'again.lean', mimeType: 'text/plain', buffer: Buffer.from(source) }); await page.waitForFunction(source => (document.querySelector('#source') as HTMLTextAreaElement).value === source, source); @@ -337,12 +339,12 @@ try { if (action === 'unchanged') await closeDialog(page, '#source-editor', () => page.locator('#apply-editor').click()); else await discardSourceEditor(page, () => action === 'escape' ? page.keyboard.press('Escape') : page.locator('#cancel-editor').click()); - await assertDraft(page, imported); assert.deepEqual((await recovery(page))?.task.draft, initial); + await assertDraft(page, imported); assert.deepEqual((await recovery(page))?.task.draft, withExplanationDefaults(initial)); assert.equal(await page.locator('#expand-source').evaluate(button => button === document.activeElement), true); } await page.locator('#expand-source').click(); await page.locator('#expanded-source').fill(`${source}\n-- applied recovery edit`); await closeDialog(page, '#source-editor', () => page.locator('#apply-editor').click()); - assert.equal((await recovery(page))?.reason, 'edit'); assert.deepEqual((await recovery(page))?.task.draft, imported); + assert.equal((await recovery(page))?.reason, 'edit'); assert.deepEqual((await recovery(page))?.task.draft, withExplanationDefaults(imported)); await openSettings(page); await restore(page, imported, true); await closeSettings(page); }); @@ -464,7 +466,7 @@ try { await page.locator('#source').fill('theorem submitted_after_reset : True := by trivial\n'); await page.locator('#submit-run').click(); await page.locator('#run-settings[open]').waitFor(); await page.locator('#api-key-validation').waitFor({ state: 'visible' }); - assert.deepEqual((await recovery(page))?.task.draft, original); + assert.deepEqual((await recovery(page))?.task.draft, withExplanationDefaults(original)); assert.equal(h.requests.filter(runtimeWrite).length, 0); await page.locator('#api-key').fill(credential); let release!: () => void, sawRequest!: () => void; diff --git a/scripts/test-web-editor-post-state.ts b/scripts/test-web-editor-post-state.ts index f866252d..0e2958e0 100644 --- a/scripts/test-web-editor-post-state.ts +++ b/scripts/test-web-editor-post-state.ts @@ -75,27 +75,18 @@ try { checks.push({ id: 'E1-lean-draft-resumes-on-refresh', language, width, after, editorVisibleWithoutSwitching: true }); phase = `account-lean-refresh-${language}`; - assert.equal(await page.locator('[data-problem-account-drafts]:visible').count(), 0); - const draft = await page.evaluate(async ({ source, task, title }) => { - const session = await (await fetch('/api/session')).json(); - const response = await fetch('/api/research/personal/drafts', { - method: 'POST', - headers: { 'content-type': 'application/json', 'x-csrf-token': session.csrfToken }, - body: JSON.stringify({ - requestId: crypto.randomUUID(), expectedRevision: 0, - scope: { kind: 'problem', draftKey: crypto.randomUUID() }, - value: { mode: 'lean', draft: { providerId: '', model: '', source, task, maxTurns: '20', maxRunSeconds: '0', workers: '1', effort: 'high', environment: 'mathlib', coordination: 'cooperative', templateId: '' } }, - summary: title, deviceId: 'test-device', deviceName: 'Desktop browser', clientUpdatedAt: new Date().toISOString(), - }), - }); - if (!response.ok) throw new Error(await response.text()); - return (await response.json()).item; - }, { source: lean, task: 'Keep this exact Lean draft and continue here.', title: `Lean continuation ${language}` }); + const savePanel = page.locator('[data-problem-account-drafts]:visible'); + await savePanel.locator(':scope > summary').click(); + await savePanel.locator('[data-problem-draft-title]').fill(`Lean continuation ${language}`); + const saved = page.waitForResponse(reply => new URL(reply.url()).pathname === '/api/research/personal/drafts' && reply.request().method() === 'POST'); + await savePanel.locator('[data-save-problem-draft]').click(); + const saveResponse = await saved; assert.equal(saveResponse.status(), 201, await saveResponse.text()); + const { item: draft } = await saveResponse.json(); const other = await actor(language, width); await other.page.goto(`${origin}/?accountDraft=${draft.draft.id}&draftVersion=${draft.version.id}`); await other.page.locator(`[data-problem-draft-version="${draft.version.id}"] [data-restore-problem-draft]`).click(); await other.page.locator('#source').waitFor({ state: 'visible' }); assert.equal(await other.page.locator('#source').inputValue(), lean); - assert.equal(await other.page.locator('[data-problem-account-drafts]:visible').count(), 0); + assert.equal(await other.page.locator('[data-problem-account-drafts]:visible').getAttribute('open'), null); await other.page.reload(); await other.page.locator('#source').waitFor({ state: 'visible' }); assert.equal(await other.page.locator('#source').isVisible(), true); assert.equal(await other.page.locator('#source').inputValue(), lean); await other.page.screenshot({ path: path.join(output, `account-lean-refresh-visible-${language}.png`), fullPage: true }); diff --git a/scripts/test-web-onboarding-post-continuity.ts b/scripts/test-web-onboarding-post-continuity.ts index 130e3711..6867eba4 100644 --- a/scripts/test-web-onboarding-post-continuity.ts +++ b/scripts/test-web-onboarding-post-continuity.ts @@ -81,10 +81,13 @@ try{ const references=new WebSharedProofs(service.storage),reading=references.register(`account:${account.id}`,{token,requestId:crypto.randomUUID()}),prepared=references.prepare(`account:${account.id}`,reading.id,{requestId:crypto.randomUUID(),expectedDigest:reading.digest,confirmed:true}); await a.page.goto(`${origin}/?sharedDraft=${prepared.id}`);await a.page.locator('[data-shared-proof-origin][data-shared-proof-status=available]').waitFor();await a.page.locator('#source').waitFor({state:'visible'}); const source=await a.page.locator('#source').inputValue(),beforeOrigin=await a.page.locator('[data-shared-proof-origin]').innerText(); - assert.equal(await a.page.locator('[data-problem-account-drafts]:visible').count(),0); - const item=await a.page.evaluate(async({source,title,sharedProofOrigin})=>{const session=await(await fetch('/api/session')).json(); - const reply=await fetch('/api/research/personal/drafts',{method:'POST',headers:{'content-type':'application/json','x-csrf-token':session.csrfToken},body:JSON.stringify({requestId:crypto.randomUUID(),expectedRevision:0,scope:{kind:'problem',draftKey:crypto.randomUUID()},value:{mode:'lean',draft:{providerId:'',model:'',source,task:'',maxTurns:'20',maxRunSeconds:'0',workers:'1',effort:'high',environment:'mathlib',coordination:'cooperative',templateId:'',sharedProofOrigin}},summary:title,deviceId:'test-device',deviceName:'Desktop browser',clientUpdatedAt:new Date().toISOString()})}); - if(!reply.ok)throw new Error(await reply.text());return(await reply.json()).item;},{source,title:`Shared proof ${language}`,sharedProofOrigin:{readingId:reading.id,title:reading.share.title,digest:reading.digest}}); + const savePanel=a.page.locator('[data-problem-account-drafts]:visible'); + await savePanel.locator(':scope > summary').click(); + await savePanel.locator('[data-problem-draft-title]').fill(`Shared proof ${language}`); + const saved=a.page.waitForResponse(reply=>new URL(reply.url()).pathname==='/api/research/personal/drafts'&&reply.request().method()==='POST'); + await savePanel.locator('[data-save-problem-draft]').click(); + const saveResponse=await saved;assert.equal(saveResponse.status(),201,await saveResponse.text()); + const {item}=await saveResponse.json(); assert.equal(item.version.value.mode,'lean');assert.deepEqual(item.version.value.draft.sharedProofOrigin,{readingId:reading.id,title:reading.share.title,digest:reading.digest}); await a.page.screenshot({path:path.join(output,`shared-account-before-${language}.png`),fullPage:true}); const b=await actor(language,width);await b.page.goto(`${origin}/?accountDraft=${item.draft.id}&draftVersion=${item.version.id}`);const restorePanel=b.page.locator('[data-problem-account-drafts]:visible');const row=restorePanel.locator(`[data-problem-draft-version="${item.version.id}"]`);await row.locator('[data-restore-problem-draft]').click();await b.page.locator('#source').waitFor({state:'visible'}); diff --git a/scripts/test-web-problem-drafts.ts b/scripts/test-web-problem-drafts.ts index c7322c37..916c34dc 100644 --- a/scripts/test-web-problem-drafts.ts +++ b/scripts/test-web-problem-drafts.ts @@ -64,62 +64,12 @@ async function openPanel(page: Page) { await panel(page).locator('[data-problem-draft-title]').waitFor(); } async function save(page: Page, title: string): Promise> { - if (await panel(page).count()) { - await openPanel(page); await panel(page).locator('[data-problem-draft-title]').fill(title); - const response = page.waitForResponse(response => response.url() === `${origin}/api/research/personal/drafts` && response.request().method() === 'POST'); - await panel(page).locator('[data-save-problem-draft]').click(); - const result = await response; assert.equal(result.status(), 201, await result.text()); - await panel(page).locator('[data-save-problem-draft]:enabled').waitFor(); - return (await result.json()).item; - } - assert.equal(await panel(page).count(), 0); - if (await page.locator('body[data-entry=lean]').count()) { - const task = await page.locator('#task').inputValue(); - await page.waitForFunction(expected => { - try { return JSON.parse(sessionStorage.getItem('theorem-os.web-draft.v1') || '{}')?.draft?.task === expected; } catch { return false; } - }, task); - } else { - const text = await page.locator('#formalize-original').inputValue(); - await page.waitForFunction(expected => Object.entries(sessionStorage).some(([k, v]) => { - if (!k.startsWith('theorem-os.chat-draft.') || k.endsWith('.quotes') || k.endsWith('.position')) return false; - try { return JSON.parse(v).text === expected; } catch { return false; } - }), text); - } - return await page.evaluate(async savedTitle => { - const session = await (await fetch('/api/session')).json(); - const owner = session.draftOwner; - const mode = document.body.dataset.entry === 'lean' ? 'lean' : 'natural'; - let value: ProblemDraftValue; - if (mode === 'lean') { - const stored = JSON.parse(sessionStorage.getItem('theorem-os.web-draft.v1') || '{}').draft || {}; - const { autoExplain: _ae, explanationLanguage: _el, continueFrom: _cf, formalization: _fm, problemBudget: _pb, ...leanDraft } = stored; - value = { mode: 'lean', draft: leanDraft }; - } else { - const chatKey = Object.keys(sessionStorage).find(key => key.startsWith('theorem-os.chat-draft.') && !key.endsWith('.quotes') && !key.endsWith('.position')); - const stored = chatKey ? JSON.parse(sessionStorage.getItem(chatKey) || '{}') : {}; - value = { mode: 'natural', text: stored.text ?? '', settings: stored.settings }; - } - const bindingKey = `theorem-os.problem-draft.${owner}.${mode}`; - const binding = JSON.parse(sessionStorage.getItem(bindingKey) || 'null') || { draftKey: crypto.randomUUID(), revision: 0, title: '' }; - const sig = (v: unknown, t: string) => JSON.stringify([t, v], (_k, x) => x && typeof x === 'object' && !Array.isArray(x) - ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x); - const response = await fetch('/api/research/personal/drafts', { - method: 'POST', - headers: { 'content-type': 'application/json', 'x-csrf-token': session.csrfToken }, - body: JSON.stringify({ - requestId: crypto.randomUUID(), expectedRevision: binding.revision, - scope: { kind: 'problem', draftKey: binding.draftKey }, value, summary: savedTitle, - deviceId: 'test-device', deviceName: 'Desktop browser', clientUpdatedAt: new Date().toISOString(), - }), - }); - if (!response.ok) throw new Error(await response.text()); - const item = (await response.json()).item; - sessionStorage.setItem(bindingKey, JSON.stringify({ - draftKey: binding.draftKey, revision: item.version.revision, title: savedTitle, - draftId: item.draft.id, versionId: item.version.id, savedSignature: sig(value, savedTitle), - })); - return item; - }, title); + await openPanel(page); await panel(page).locator('[data-problem-draft-title]').fill(title); + const response = page.waitForResponse(response => response.url() === `${origin}/api/research/personal/drafts` && response.request().method() === 'POST'); + await panel(page).locator('[data-save-problem-draft]').click(); + const result = await response; assert.equal(result.status(), 201, await result.text()); + await panel(page).locator('[data-save-problem-draft]:enabled').waitFor(); + return (await result.json()).item; } async function chooseVersion(page: Page, item: ResearchAccountDraftResult, click = true) { const current = new URL(page.url()); @@ -163,7 +113,7 @@ try { checks.push('Original text and settings survive multiple example replacements and refresh.'); phase = 'natural-account-save'; - assert.equal(await panel(page).count(), 0, 'Authenticated home hides idle cloud-draft panel'); + assert.equal(await panel(page).getAttribute('open'), null, 'A typed problem offers a collapsed save control'); await page.locator('#formalize-key').fill('sk-disposable-key'); const natural = await save(page, '待完成的归纳证明'); assert.equal(natural.version.value.mode, 'natural'); await page.goto(`${origin}/?accountDraft=${natural.draft.id}&draftVersion=${natural.version.id}`); @@ -176,7 +126,7 @@ try { assert.equal(await panel(other).count(), 0); await chooseVersion(other, natural); await waitOriginal(other, original); assert.equal(new URL(other.url()).searchParams.has('accountDraft'), false); - assert.equal(await panel(other).count(), 0, 'Restoring hides the explicit recovery drawer'); + assert.equal(await panel(other).getAttribute('open'), null, 'Restoring closes the preview and keeps the save control'); await settings(other); assert.equal(await other.locator('#formalize-model').inputValue(), 'original-model'); assert.equal(await other.locator('#formalize-environment').inputValue(), 'mathlib'); assert.equal(await other.locator('#formalize-key').inputValue(), ''); @@ -253,7 +203,7 @@ try { await linked.screenshot({ path: path.join(output, 'desktop-zh-original-recovery.png'), fullPage: true }); await chooseVersion(linked, natural); await waitOriginal(linked, original); assert.equal(new URL(linked.url()).searchParams.has('accountDraft'), false); - assert.equal(await panel(linked).count(), 0); + assert.equal(await panel(linked).getAttribute('open'), null); checks.push('A draft link survives login and refresh, opens a preview, and restores only after an explicit click.'); await noOverflow(linked); diff --git a/scripts/test-web-problem-lifecycle.ts b/scripts/test-web-problem-lifecycle.ts index ffc89b7f..72a180dd 100644 --- a/scripts/test-web-problem-lifecycle.ts +++ b/scripts/test-web-problem-lifecycle.ts @@ -26,33 +26,9 @@ const browser=await startBrowser(service.server,port); const panel=(page:Page)=>page.locator('[data-problem-account-drafts]:visible'); async function openPanel(page:Page){if(await page.locator('#formalize-settings[open]:visible').count())await page.locator('#formalize-settings > summary').click();if(await panel(page).getAttribute('open')!=='')await panel(page).locator(':scope > summary').click();await panel(page).locator('[data-problem-draft-title]').waitFor();} async function save(page:Page,title:string):Promise>{ - if(await panel(page).count()){ - await openPanel(page);await panel(page).locator('[data-problem-draft-title]').fill(title); - const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/api/research/personal/drafts'&&r.request().method()==='POST'); - await panel(page).locator('[data-save-problem-draft]').click();const r=await response;assert.equal(r.status(),201,await r.text());await panel(page).locator('[data-save-problem-draft]:enabled').waitFor();return (await r.json()).item; - } - assert.equal(await panel(page).count(),0); - if(await page.locator('body[data-entry=lean]').count()){ - const task=await page.locator('#task').inputValue(); - await page.waitForFunction(expected=>{try{return JSON.parse(sessionStorage.getItem('theorem-os.web-draft.v1')||'{}')?.draft?.task===expected;}catch{return false;}},task); - }else{ - const text=await page.locator('#formalize-original').inputValue(); - await page.waitForFunction(expected=>Object.entries(sessionStorage).some(([k,v])=>{if(!k.startsWith('theorem-os.chat-draft.')||k.endsWith('.quotes')||k.endsWith('.position'))return false;try{return JSON.parse(v).text===expected;}catch{return false;}}),text); - } - return await page.evaluate(async savedTitle=>{ - const session=await(await fetch('/api/session')).json(),owner=session.draftOwner,mode=document.body.dataset.entry==='lean'?'lean':'natural'; - let value:ProblemDraftValue; - if(mode==='lean'){const stored=JSON.parse(sessionStorage.getItem('theorem-os.web-draft.v1')||'{}').draft||{};const{autoExplain:_ae,explanationLanguage:_el,continueFrom:_cf,formalization:_fm,problemBudget:_pb,...leanDraft}=stored;value={mode:'lean',draft:leanDraft};} - else{const k=Object.keys(sessionStorage).find(x=>x.startsWith('theorem-os.chat-draft.')&&!x.endsWith('.quotes')&&!x.endsWith('.position'));const stored=k?JSON.parse(sessionStorage.getItem(k)||'{}'):{};value={mode:'natural',text:stored.text??'',settings:stored.settings};} - const bindingKey=`theorem-os.problem-draft.${owner}.${mode}`; - const binding=JSON.parse(sessionStorage.getItem(bindingKey)||'null')||{draftKey:crypto.randomUUID(),revision:0,title:''}; - const sig=(v:unknown,t:string)=>JSON.stringify([t,v],(_k,x)=>x&&typeof x==='object'&&!Array.isArray(x)?Object.fromEntries(Object.entries(x).sort(([a],[b])=>a.localeCompare(b))):x); - const reply=await fetch('/api/research/personal/drafts',{method:'POST',headers:{'content-type':'application/json','x-csrf-token':session.csrfToken},body:JSON.stringify({requestId:crypto.randomUUID(),expectedRevision:binding.revision,scope:{kind:'problem',draftKey:binding.draftKey},value,summary:savedTitle,deviceId:'test-device',deviceName:'Desktop browser',clientUpdatedAt:new Date().toISOString()})}); - if(!reply.ok)throw new Error(await reply.text()); - const item=(await reply.json()).item; - sessionStorage.setItem(bindingKey,JSON.stringify({draftKey:binding.draftKey,revision:item.version.revision,title:savedTitle,draftId:item.draft.id,versionId:item.version.id,savedSignature:sig(value,savedTitle)})); - return item; - },title); + await openPanel(page);await panel(page).locator('[data-problem-draft-title]').fill(title); + const response=page.waitForResponse(r=>new URL(r.url()).pathname==='/api/research/personal/drafts'&&r.request().method()==='POST'); + await panel(page).locator('[data-save-problem-draft]').click();const r=await response;assert.equal(r.status(),201,await r.text());await panel(page).locator('[data-save-problem-draft]:enabled').waitFor();return (await r.json()).item; } async function list(page:Page):Promise{return page.evaluate(async()=> (await (await fetch('/api/research/personal/drafts?kind=problem&status=all')).json()).items);} async function waitSubmitted(page:Page,draftId:string,submissionId?:string,versionId?:string){ @@ -74,7 +50,7 @@ try{ const current=await context(language,width),page=await current.newPage();active=page; await page.goto(origin);await page.locator('#send-code:enabled').waitFor();await page.locator('#login-email').fill(email);await page.locator('#login-captcha').fill('24680');if(await page.locator('#terms-option').isVisible())await page.locator('#accept-terms').check();await page.locator('#send-code').click();await page.locator('#code-step:visible').waitFor();await page.locator('#login-code').fill(mail.at(-1)!.text.match(/\b\d{6}\b/u)![0]);await page.locator('#verify-code').click();await page.locator('#formalize-original').waitFor(); await page.locator('#formalize-original').fill(webFormalizationStatement);await openChatModelSettings(page);await page.locator('#formalize-model').fill('fixture-model');await openAdvancedChatSettings(page);await page.locator('#formalize-environment').selectOption('standard');await page.locator('#formalize-settings > summary').click(); - phase=`refresh-status-${language}`;assert.equal(await panel(page).count(),0);const first=await save(page,'Problem A');await page.goto(`${origin}/?accountDraft=${first.draft.id}&draftVersion=${first.version.id}`);await page.locator('#formalize-original').waitFor();await openPanel(page); + phase=`refresh-status-${language}`;const first=await save(page,'Problem A');await page.goto(`${origin}/?accountDraft=${first.draft.id}&draftVersion=${first.version.id}`);await page.locator('#formalize-original').waitFor();await openPanel(page); await panel(page).locator('[data-problem-draft-notice]').waitFor(); await page.locator('#formalize-original').fill(webFormalizationStatement+'\nUse induction.');await panel(page).getByText(/新修改尚未保存到账号|Your new edits are not yet saved to your account/).waitFor(); await page.screenshot({path:path.join(output,`${language}-${width}-dirty-after-reload.png`),fullPage:true}); diff --git a/scripts/test-web-simple-workbench.ts b/scripts/test-web-simple-workbench.ts index e3179701..3b3ff391 100644 --- a/scripts/test-web-simple-workbench.ts +++ b/scripts/test-web-simple-workbench.ts @@ -231,7 +231,7 @@ try { } const lean = 'theorem simple_fixture : True := by\n sorry\n'; await actor.locator('#source').fill(lean); assert.equal(await actor.locator('[data-problem-account-drafts]:visible').count(), 0, - 'Lean draft mode keeps cloud-draft panels hidden unless restoring a link'); + 'An anonymous Lean draft has no account save control'); await actor.reload(); await actor.locator('#source:visible').waitFor(); assert.equal(await actor.locator('#source').inputValue(), lean); await actor.locator('#open-natural-language').click(); await actor.locator('#formalize-original').waitFor(); diff --git a/src/math/leanProofSearch.ts b/src/math/leanProofSearch.ts index 37ed6291..ef19d7ef 100644 --- a/src/math/leanProofSearch.ts +++ b/src/math/leanProofSearch.ts @@ -185,6 +185,8 @@ export type LeanProofSearchStatus = 'candidate' | 'exhausted' | 'budget-exhauste export async function searchLeanBranches(input: { projectRoot: string; file: string; theoremName: string; type: string; scope: LeanProofSearchScope; request: unknown; env?: NodeJS.ProcessEnv; signal?: AbortSignal; + /** An ordinary worker search may start at the current root if its implicit resume has a different basis. */ + restartStaleImplicitResume?: boolean; /** Only a host-scoped independent nextCheck may replay the explicitly retained source instead of live owned files. */ retainedInput?: { basisDigest: string; checkpointDigest: string }; onCheckpoint?: (reference: SearchCheckpointReference) => void; @@ -236,10 +238,15 @@ export async function searchLeanBranches(input: { }; if (request.resume) { checkpoint = readCheckpoint(project, request.resume); - validateCheckpoint(checkpoint, basis); - if (checkpoint.generation < latest) requireLatestResume(); - } else if (latest >= 0) requireLatestResume(); - else { + if (input.restartStaleImplicitResume && !input.retainedInput && !request.branches.some(branch => branch.from) && + canonicalMathJson(checkpoint.basis) !== canonicalMathJson(basis)) checkpoint = undefined; + else { + validateCheckpoint(checkpoint, basis); + if (checkpoint.generation < latest) requireLatestResume(); + } + } + if (!checkpoint) { + if (latest >= 0) requireLatestResume(); checkpoint = emptyProofSearchCheckpoint(basis); const replaySources = projection!.replaySources; if (replaySources.reduce((size, item) => size + Buffer.byteLength(item.file) + Buffer.byteLength(item.source), 0) > 2_000_000) diff --git a/src/solver/cooperationIntegration.ts b/src/solver/cooperationIntegration.ts index 35eac393..ce8dbd6f 100644 --- a/src/solver/cooperationIntegration.ts +++ b/src/solver/cooperationIntegration.ts @@ -323,13 +323,14 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { else await publish(); }; await persistProgress(); - const finish = async (node: TaskRecord) => { + const finish = async (node: TaskRecord, receipt?: TaskProof) => { if (!checked.has(node.task.id)) { checked.add(node.task.id); progress.completed++; } progress.taskId = undefined; if (node.status === 'integrated' && node.task.kind === 'goal' && node.integratedCheck?.passed && !node.integratedCheck.conditions?.length && this.checkedDeliveries.has(node.integratedCheck) && hasTaskAcceptance(node.integratedCheck)) freshGoals.set(node.task.id, digest(node.task)); - this.input.emit('task_recheck_finished', { ...progress, taskId: node.task.id, passed: node.status === 'integrated', ...(snapshot ? { staged: true } : {}) }); + this.input.emit('task_recheck_finished', { ...progress, taskId: node.task.id, passed: node.status === 'integrated', + commit: receipt?.commit, taskDigest: receipt?.taskDigest, ...(snapshot ? { staged: true } : {}) }); await persistProgress(); }; while (pending.length || retryable.size) { @@ -353,11 +354,14 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { this.input.signal.throwIfAborted(); if (snapshot && !snapshot.current()) return false; const assignment = this.canonicalCheckAssignment(node.task, canonical, tasks); + let savedReceipt: TaskProof | undefined; try { if (reusable(node)) { node.feedback = undefined; - this.input.emit('task_check_reused', { taskId: node.task.id, commit: node.integratedCheck!.commit, canonicalCommit: canonical }); - await finish(node); continue; + const receipt = node.integratedCheck!; + this.input.emit('task_check_reused', { taskId: node.task.id, passed: receipt.passed, + commit: receipt.commit, taskDigest: receipt.taskDigest, canonicalCommit: canonical }); + await finish(node, receipt); continue; } if (!batchAttempted.has(node) && (this.input.modules.M2.checkTask ?? checkTaskProof) === checkTaskProof) { const source = projection(node); @@ -404,7 +408,7 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { this.input.signal.throwIfAborted(); if (['unavailable', 'blocked'].includes(receipt.verification.status)) throw verifierFailure('integrated-task-recheck', receipt, node.task); if (snapshot && !snapshot.current()) return false; - node.integratedCheck = receipt; + savedReceipt = node.integratedCheck = receipt; if (!receipt.passed && !retried.has(node) && !receipt.conditions?.length && hasDeterministicLeanFailure(receipt.verification)) retryable.set(node, beforeGoals); if (!receipt.passed) { this.moveTask(node, 'blocked', 'invalidated'); node.feedback = solverProofFeedback(receipt); if (!snapshot) this.wakeLead('integration-blocked'); } @@ -418,7 +422,7 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { if (snapshot && !snapshot.current()) return false; this.moveTask(node, 'blocked', 'invalidated'); node.feedback = rejected.message; if (!snapshot) this.wakeLead('integration-blocked'); } - await finish(node); + await finish(node, savedReceipt); } this.input.signal.throwIfAborted(); if (snapshot && !snapshot.current()) return false; @@ -437,6 +441,7 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { const group = this.archive.groups?.find(record => record.group.id === taskGroup(node.task)); if ((node.task.status ?? 'active') !== 'active' || group && group.group.status !== 'active') continue; const saved = node.proof; + let savedReceipt: TaskProof | undefined; this.input.emit('task_conditional_recheck_started', { taskId: node.task.id }); try { if (!(node.task.conditional || node.assignment && hasTaskConnectionCheck(node.task, node.assignment)) || @@ -461,7 +466,7 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { return proof; }); if (['unavailable', 'blocked'].includes(proof.verification.status)) throw verifierFailure('conditional-task-recheck', proof, node.task); - node.proof = proof; + savedReceipt = node.proof = proof; if (proof.passed) node.feedback = undefined; else { this.moveTask(node, 'blocked', 'invalidated'); node.feedback = solverProofFeedback(proof); this.wakeLead('conditional-recheck-failed'); @@ -470,7 +475,8 @@ export abstract class CooperationIntegration extends CooperationTaskProofs { this.input.signal.throwIfAborted(); node.feedback = expectedRejection(error, integrationRejections).message; this.moveTask(node, 'blocked', 'invalidated'); this.wakeLead('conditional-recheck-failed'); } - this.input.emit('task_conditional_recheck_finished', { taskId: node.task.id, passed: node.status === 'conditional' }); + this.input.emit('task_conditional_recheck_finished', { taskId: node.task.id, passed: node.status === 'conditional', + commit: savedReceipt?.commit, taskDigest: savedReceipt?.taskDigest }); this.changed(); } } diff --git a/src/solver/cooperationTaskProofs.ts b/src/solver/cooperationTaskProofs.ts index 6c962507..8695204f 100644 --- a/src/solver/cooperationTaskProofs.ts +++ b/src/solver/cooperationTaskProofs.ts @@ -1119,7 +1119,8 @@ export abstract class CooperationTaskProofs extends CooperationStatements { result.status === 'failed' && ((result.sorryCount ?? 0) > 0 || result.error === 'Lean exited with status 1.')); if (!repairable || !this.retryTaskLocally(node, proof.commit)) this.wakeLead('task-check-failed'); } - this.input.emit('task_checked', { taskId: node.task.id, passed: proof.passed, conditional: Boolean(proof.conditions?.length), commit: proof.commit }); + this.input.emit('task_checked', { taskId: node.task.id, passed: proof.passed, conditional: Boolean(proof.conditions?.length), + commit: proof.commit, taskDigest: proof.taskDigest }); this.changed(); } /** Keep canonical failures authoritative, while draining all checks before a caller releases its workspace. */ diff --git a/src/solver/modules/search.ts b/src/solver/modules/search.ts index 2d630ccc..164deae7 100644 --- a/src/solver/modules/search.ts +++ b/src/solver/modules/search.ts @@ -51,14 +51,17 @@ export function selectedTaskRoute(node: TaskRecord, tasks: readonly TaskRecord[] priority?: ReturnType): ProofRoute | undefined { if (!node.alternativeRoutes?.length) return; const assigned = node.alternativeRoutes?.find(route => route.id === node.assignment?.routeId); - // An active proof or delivery keeps its mathematical inputs. A pending draft - // may resume on another freshly checked branch when its old inputs fail. - if (assigned && node.status !== 'pending') return assigned; + const recoveringFailure = node.status === 'blocked' && node.feedback?.startsWith('math_task_repeated_failed_input\n'); + // Keep the route fixed during proof and delivery. A blocked failure can + // reconsider its inputs when a freshly checked route is available. + if (assigned && node.status !== 'pending' && !recoveringFailure) return assigned; const routes = openRoutes(node), ready = routes.filter(route => dispatchRouteReady(route, tasks)); + const readyRoute = ready.find(route => route.id === assigned?.id) ?? ready[0]; + if (readyRoute || recoveringFailure && assigned) return readyRoute ?? assigned; const compare = (priority ?? createProofRoutePriority(tasks)).compareRoutes; const ranked = routes.toSorted((a, b) => compare(a, b) || Number(b.id === node.assignment?.routeId) - Number(a.id === node.assignment?.routeId)); - return ready.find(route => route.id === node.assignment?.routeId) ?? ready[0] ?? ranked[0]; + return ranked[0]; } export function plannedTaskDependencyIds(node: TaskRecord, tasks: readonly TaskRecord[]): readonly string[] { const route = selectedTaskRoute(node, tasks); diff --git a/src/solver/proofSearchTool.ts b/src/solver/proofSearchTool.ts index 832802ef..6fcdffa8 100644 --- a/src/solver/proofSearchTool.ts +++ b/src/solver/proofSearchTool.ts @@ -51,7 +51,8 @@ export async function runProofSearchTool(input: { projectRoot: string; request: const constraints = path.join(context.project, '.lake/source-constraints.json'); if (fs.existsSync(constraints)) assertSolverProjectSources(JSON.parse(readMathText(constraints)) as SolverSourceConstraints, context.project); const request = proofSearchRequestSchema.parse(input.request); - if (!request.resume && context.record) request.resume = context.record.checkpoint; + const implicitResume = !request.resume && context.record; + if (implicitResume) request.resume = implicitResume.checkpoint; const queueCheckpoint = (reference: SearchCheckpointReference) => { const event = { kind: 'progress', id: reference.digest, summary: 'Saved advisory proof-search state; candidate proofs require independent verification.', @@ -64,6 +65,7 @@ export async function runProofSearchTool(input: { projectRoot: string; request: }; const result = await searchLeanBranches({ projectRoot: context.project, file: context.task.proofPath!, theoremName: context.task.theoremName!, type: context.task.type!, scope: context.scope, request, + restartStaleImplicitResume: Boolean(implicitResume && context.scope.taskId === context.assignment.taskId), ...(context.independentSearch && context.record ? { retainedInput: { basisDigest: context.record.basisDigest, checkpointDigest: context.record.checkpoint.digest } } : {}), signal: input.signal, env: input.env, onCheckpoint: queueCheckpoint }); diff --git a/tests/proofSearchRuntime.test.ts b/tests/proofSearchRuntime.test.ts index fcece481..ba7b0e21 100644 --- a/tests/proofSearchRuntime.test.ts +++ b/tests/proofSearchRuntime.test.ts @@ -7,6 +7,8 @@ import { proofSearchCheckpointSchema, searchLeanBranches, type ProofSearchCheckp type SearchCheckpointReference } from '../src/math/leanProofSearch'; import type { ProofSearchSession } from '../src/math/pantographSession'; import { projectProofSearchRecord, retainProofSearchCheckpoint } from '../src/solver/proofSearchRecords'; +import { runProofSearchTool } from '../src/solver/proofSearchTool'; +import { assignmentDeliveryFile, taskVersion } from '../src/solver/tasks'; const boundary = vi.hoisted(() => ({ projection: vi.fn(), retainedProjection: vi.fn(), backend: vi.fn(), open: vi.fn() })); vi.mock('../src/math/leanSearchProjection', () => ({ @@ -192,6 +194,53 @@ describe('proof-search runtime persistence with fake Lean boundaries', () => { expect(readCheckpoint(project, first.reference)).toEqual(first.checkpoint); }); + it('starts a fresh worker search on changed source only if no resume or old node was requested', async () => { + const helper = { id: scope.taskId, kind: 'lemma' as const, objective: 'Prove helper', revision: 0, proofPath: target.file, + theoremName: target.theoremName, type: target.type, dependsOn: [] }; + const identity = { ...scope, taskDigest: taskVersion(helper) }; + boundary.projection.mockReturnValue(projection(project)); + boundary.open.mockResolvedValue(session()); + const first = await search({ scope: identity }); + const assignment = { taskId: identity.taskId, taskDigest: identity.taskDigest, workerId: 'owner', seedCommit: 'seed' }; + const firstCheckpoint = readCheckpoint(project, first.checkpoint!); + const record = retainProofSearchCheckpoint({ projectRoot: project, runDirectory: directory, reference: first.checkpoint!, + scope: identity, workerId: assignment.workerId, assignmentKey: assignmentDeliveryFile(assignment) }); + const projected = projectProofSearchRecord({ record, scope: identity, projectRoot: project, runDirectory: directory })!; + fs.writeFileSync(path.join(project, 'COOPERATION.json'), JSON.stringify({ + researchDelivery: { assignment, projectRelative: '.', ownedFiles: [target.file], ...identity }, tasks: [{ task: helper }], + proofSearchRecords: { [helper.id]: projected }, + })); + const changedSource = sources[0]!.source + '-- edited helper inputs\n'; + fs.writeFileSync(path.join(project, target.file), changedSource); + const changedFiles = [{ file: target.file, digest: mathDigest(changedSource) }, sourceFiles[1]!]; + const changedProjection = projection(project, { sourceFiles: changedFiles, + sourceDigest: mathDigest(canonicalMathJson(changedFiles)), projectionDigest: mathDigest('changed projection'), + replaySources: [{ file: target.file, source: changedSource }, sources[1]!] }); + clearBoundaryCalls(); + boundary.projection.mockReturnValue(changedProjection); + const fake = session(); + boundary.open.mockResolvedValue(fake); + const run = (request: unknown) => runProofSearchTool({ projectRoot: project, env, request }); + const request = { branches: [{ tactics: ['intro n', 'rfl'] }] }; + await expect(run({ ...request, resume: projected.checkpoint })).resolves.toMatchObject({ + status: 'stale', reason: 'proof_search_stale_basis', + }); + await expect(run({ branches: [{ from: firstCheckpoint.nodes[1]!.id, tactics: ['rfl'] }] })).resolves.toMatchObject({ + status: 'stale', reason: 'proof_search_stale_basis', + }); + expect(boundary.open).not.toHaveBeenCalled(); + clearBoundaryCalls(); + const next = await run(request); + expect(next).toMatchObject({ status: 'candidate', proofAcceptance: 'not-accepted', sourceBinding: 'current-worker-source', + counters: { issued: 2, completed: 2, replay: 0 } }); + expect(next.basis).not.toBe(first.basis); + expect(boundary.projection).toHaveBeenCalledTimes(1); + expect(boundary.retainedProjection).not.toHaveBeenCalled(); + expect(boundary.open).toHaveBeenCalledTimes(1); + expect(readCheckpoint(project, first.checkpoint!)).toEqual(firstCheckpoint); + expect(readCheckpoint(project, next.checkpoint!).replaySources?.[0]?.source).toBe(changedSource); + }); + it.each([ ['basisDigest', 'proof_search_stale_retained_basis'], ['checkpointDigest', 'proof_search_stale_retained_checkpoint'], diff --git a/tests/repeatedDelivery.test.ts b/tests/repeatedDelivery.test.ts index f5730dfa..7a6c1404 100644 --- a/tests/repeatedDelivery.test.ts +++ b/tests/repeatedDelivery.test.ts @@ -644,7 +644,7 @@ describe('persistent typed delivery failure guards', () => { expect(checker).toHaveBeenCalledTimes(1); }); - it('keeps a failed OR branch blocked after assignment reset and permits a different checked branch', async () => { + it.each(['retained', 'reset'] as const)('switches to a different checked OR branch after failure with a %s assignment', async assignment => { candidate.task = task('candidate', 'goal'); candidate.assignment!.taskDigest = taskVersion(candidate.task); action = { kind: 'task', task: candidate.task, assignment: candidate.assignment! }; const branches = ['left', 'right'].map(id => @@ -654,12 +654,15 @@ describe('persistent typed delivery failure guards', () => { prerequisiteTaskIds: [], closingTaskId: record.task.id })); (cooperative as any).syncProofRoutes(); candidate.assignment!.routeId = 'via_left'; await exhaustRepair(); - candidate.assignment = undefined; candidate.proof = undefined; candidate.status = 'pending'; + if (assignment === 'reset') { + candidate.assignment = undefined; candidate.proof = undefined; candidate.status = 'pending'; + } const research: TaskRecord = { task: task('investigate', 'research'), status: 'pending', attempts: 0 }; state.cooperation!.tasks.push(research); const independent = await cooperative.next(researcher, budget); expect(independent).toMatchObject({ kind: 'task', task: { id: 'investigate' } }); expect(candidate.status).toBe('blocked'); expect(checker).toHaveBeenCalledTimes(1); + if (assignment === 'retained') expect(candidate.assignment?.routeId).toBe('via_left'); research.status = 'completed'; branches[0].status = 'blocked'; const alternate = await cooperative.next(researcher, budget); expect(alternate).toMatchObject({ kind: 'task', task: { id: 'candidate' }, assignment: { routeId: 'via_right' } }); diff --git a/tests/webContinuationIdentity.test.ts b/tests/webContinuationIdentity.test.ts index 93262412..8a1ee2dd 100644 --- a/tests/webContinuationIdentity.test.ts +++ b/tests/webContinuationIdentity.test.ts @@ -27,16 +27,36 @@ describe('web continuation frozen source identity', () => { const parent = service.jobs.create(owner, input, provider); await new Promise(resolve => setImmediate(resolve)); const observation = structuredClone(sample.observations.at(-1)!); - observation.webRunId = parent.id; observation.sequence = 1; parent.observation = observation; - const target = observation.sources.find(source => observation.checks.some(check => check.taskId === source.taskId && check.commit === source.commit))!; - observation.sources.push({ ...target, taskVersion: 'another-task-version-at-the-same-commit' }); - service.storage.saveObservation(owner, observation); service.storage.saveRun(owner, parent); - const from: WebContinuation = { runId: parent.id, taskId: target.taskId, commit: target.commit, label: 'Saved version' }; - const query = await fetch(`${origin}/api/runs/${parent.id}/trajectory/version?${new URLSearchParams({ task: from.taskId, commit: from.commit })}`, - { headers: { Cookie: cookie } }); + observation.webRunId = parent.id; + const target = observation.sources.find(source => observation.checks.some(check => check.taskId === source.taskId && + check.taskVersion === source.taskVersion && check.commit === source.commit && check.record.passed === true))!; + const receipt = observation.checks.find(check => check.taskId === target.taskId && check.taskVersion === target.taskVersion && + check.commit === target.commit && check.record.passed === true)!; + const earlierRevision = 'earlier-task-version-at-the-same-commit'; + service.storage.saveObservation(owner, { ...observation, sequence: 1, + sources: [{ ...target, taskVersion: earlierRevision, file: 'Earlier.lean', source: '-- earlier revision\n' }], + checks: [{ ...receipt, id: 'earlier-failed-check', taskVersion: earlierRevision, + record: { ...receipt.record, proofPath: 'Earlier.lean', passed: false, status: 'failed' } }] }); + service.storage.saveObservation(owner, { ...observation, sequence: 2, sources: [], checks: [receipt] }); + parent.observation = { ...observation, sequence: 3, sources: [target], checks: [] }; + service.storage.saveRun(owner, parent); + const query = await fetch(`${origin}/api/runs/${parent.id}/trajectory`, { headers: { Cookie: cookie } }); expect(query.status).toBe(200); - const recorded = (await query.json()).version.source, expected = { ...from, taskVersion: recorded.taskVersion, sourceDigest: recorded.sourceDigest, - environmentDigest: recorded.environmentDigest, file: recorded.file }; + const { trajectory } = await query.json(); + const matching = trajectory.versions.find((item: { taskId: string; commit: string }) => item.taskId === target.taskId && item.commit === target.commit); + expect(matching.checks).toMatchObject([{ taskVersion: earlierRevision, passed: false }, { taskVersion: target.taskVersion, passed: true }]); + const detail = async (taskVersion?: string) => { + const params = new URLSearchParams({ task: target.taskId, commit: target.commit, ...(taskVersion ? { taskVersion } : {}) }); + const response = await fetch(`${origin}/api/runs/${parent.id}/trajectory/version?${params}`, { headers: { Cookie: cookie } }); + expect(response.status).toBe(200); + return (await response.json()).version; + }; + expect(await detail()).toMatchObject({ source: { taskVersion: earlierRevision }, checks: [{ id: 'earlier-failed-check' }, { id: receipt.id }] }); + expect(await detail(target.taskVersion)).toMatchObject({ source: target, checks: [{ id: receipt.id }] }); + expect(await detail(earlierRevision)).toMatchObject({ source: { file: 'Earlier.lean' }, checks: [{ id: 'earlier-failed-check' }] }); + const from: WebContinuation = { runId: parent.id, taskId: target.taskId, commit: target.commit, label: 'Saved version', + taskVersion: matching.checks.find((check: { passed: boolean }) => check.passed).taskVersion }; + const expected = { ...from, sourceDigest: target.sourceDigest, environmentDigest: target.environmentDigest, file: target.file }; const body = { ...input, task: 'Continued offline', continueFrom: from, requestId: 'freeze-source-once' }; const response = await post(body); expect(response.status).toBe(201); const continued = (await response.json()).run as WebRun; @@ -46,15 +66,16 @@ describe('web continuation frozen source identity', () => { await new Promise(resolve => setImmediate(resolve)); const worker = calls.find(call => call.id === continued.id)!; expect(worker.input.continueFrom).toEqual(from); - expect(worker.continuation).toEqual({ ...expected, source: recorded.source }); - const legacy = service.jobs.create(owner, { ...input, task: 'Legacy continuation', continueFrom: from }, provider); + expect(worker.continuation).toEqual({ ...expected, source: target.source }); + const { taskVersion: _taskVersion, ...legacyFrom } = from; + const legacy = service.jobs.create(owner, { ...input, task: 'Legacy continuation', continueFrom: legacyFrom }, provider); await new Promise(resolve => setImmediate(resolve)); const journeyResponse = await fetch(`${origin}/api/research/workspace/problem/${continued.id}/journey`, { headers: { Cookie: cookie } }); expect(journeyResponse.status).toBe(200); const journey = (await journeyResponse.json()).item; expect(journey.lineage.find((edge: { toRunId: string }) => edge.toRunId === continued.id)).toMatchObject({ status: 'recorded', - source: { runId: from.runId, taskId: from.taskId, commit: from.commit, taskVersion: recorded.taskVersion, - sourceDigest: recorded.sourceDigest, environmentDigest: recorded.environmentDigest, file: recorded.file } }); + source: { runId: from.runId, taskId: from.taskId, commit: from.commit, taskVersion: target.taskVersion, + sourceDigest: target.sourceDigest, environmentDigest: target.environmentDigest, file: target.file } }); expect(journey.lineage.find((edge: { toRunId: string }) => edge.toRunId === legacy.id)).toMatchObject({ status: 'ambiguous' }); const replay = await post(body); expect(replay.status).toBe(200); expect((await replay.json()).run.id).toBe(continued.id); expect(calls.filter(call => call.id === continued.id)).toHaveLength(1); diff --git a/tests/webDraftRecovery.test.ts b/tests/webDraftRecovery.test.ts index b217be07..9d52d1a6 100644 --- a/tests/webDraftRecovery.test.ts +++ b/tests/webDraftRecovery.test.ts @@ -71,7 +71,7 @@ describe('one recoverable draft replacement', () => { expect(reloaded.current?.draft).toEqual(original); }); it('stores the full editable draft independently of autosave and restores it in a fresh controller', () => { - const saved = storage(), before = draft(), recovery = new DraftRecovery(() => saved); + const saved = storage(), before = draft({ autoExplain: false, explanationLanguage: 'en' }), recovery = new DraftRecovery(() => saved); saved.values.set(taskDraftStorageKey, 'unrelated autosave'); recovery.remember(before, draft({ task: 'Replacement task' }), 'template'); expect(recovery.current).toEqual({ draft: before, reason: 'template', persisted: true }); diff --git a/tests/webJobs.test.ts b/tests/webJobs.test.ts index 6aac306e..bc99e3a3 100644 --- a/tests/webJobs.test.ts +++ b/tests/webJobs.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { WebJobs } from '../apps/web/jobs'; +import { decodeTaskDraft } from '../apps/web/client/draft'; import type { WebRunner } from '../apps/web/runner'; import type { WebObservation } from '../apps/web/collaboration'; import { webLimits, type WebProvider, type WebResult, type WebRunInput, type WorkerInput, type WorkerMessage } from '../apps/web/shared'; @@ -218,6 +219,28 @@ describe('web job ownership, scheduling and secret lifetime without provider cal expect(continued.knowledgeDigest).toBeUndefined(); }); + it('keeps an explicit no-history choice when recreating an archived run', async () => { + const { jobs, runner } = setup(); + const catalog = jobs.knowledge.importCatalog('owner', buildTheoremKnowledge([known('existing')])); + const original = jobs.create('owner', { ...input(), knowledgeDigest: null }, provider); + await tick(); + runner.calls[0]!.finish(); + await tick(); + const archive = jobs.storage.exportRun('owner', original); + const draft = decodeTaskDraft(JSON.parse(JSON.stringify(archive))); + expect(draft.knowledgeDigest).toBeNull(); + const recreated = jobs.create('owner', { ...input(), knowledgeDigest: draft.knowledgeDigest }, provider); + const automatic = jobs.create('owner', input(), provider); + expect(recreated.knowledgeDigest).toBeNull(); + expect(automatic.knowledgeDigest).toBe(catalog.digest); + await tick(); + expect(runner.calls[1]!.input.knowledgeCatalog).toBeUndefined(); + runner.calls[1]!.finish(); + await tick(); + expect(runner.calls[2]!.input.knowledgeCatalog?.entries).toHaveLength(1); + runner.calls[2]!.finish(); + }); + it('prevents another owner from reading or cancelling a job', async () => { const { jobs, runner } = setup(); const run = jobs.create('alice', input(), provider); diff --git a/tests/webKnowledgeApi.test.ts b/tests/webKnowledgeApi.test.ts index 6e23cde3..1d2c2947 100644 --- a/tests/webKnowledgeApi.test.ts +++ b/tests/webKnowledgeApi.test.ts @@ -114,7 +114,7 @@ describe('knowledge and module configuration through the real HTTP service witho const optedOut = await request(alice, '/api/runs', { ...input(), knowledgeDigest: null }); expect(optedOut.status).toBe(201); const noHistoryRun = (await optedOut.json()).run; - expect(noHistoryRun.knowledgeDigest).toBeUndefined(); + expect(noHistoryRun.knowledgeDigest).toBeNull(); const isolated = await request(bob, '/api/runs', input()); expect(isolated.status).toBe(201); const bobRun = (await isolated.json()).run; diff --git a/tests/webModuleTelemetry.test.ts b/tests/webModuleTelemetry.test.ts index 821e0728..3a35f087 100644 --- a/tests/webModuleTelemetry.test.ts +++ b/tests/webModuleTelemetry.test.ts @@ -186,6 +186,10 @@ describe('allowlisted web progress translation', () => { const task = translateWebProgress({ event: 'task_checked', taskId: 'goal-1', passed: true, conditional: true, commit: 'private-commit', verification: { status: 'kernel_verified' } }); expect(task?.details).toEqual({ taskId: 'goal-1', passed: true, conditional: true }); + const commit = 'a'.repeat(40), taskDigest = 'b'.repeat(64); + const exact = translateWebProgress({ event: 'task_checked', taskId: 'goal-1', passed: false, commit, taskDigest }); + expect(exact?.details).toEqual({ taskId: 'goal-1', passed: false, commit, taskDigest }); + expect(parseWorkerMessage(JSON.stringify(exact))).toEqual(exact); const lemma = translateWebProgress({ event: 'lemma_checked', workerId: 'solver', bridge: true, lemma: false, passed: true, status: 'evaluated_passed', error: 'private-lean-error' }); expect(lemma?.details).toEqual({ workerId: 'solver' }); diff --git a/tests/webPersistence.test.ts b/tests/webPersistence.test.ts index 00a1c383..acd1dce8 100644 --- a/tests/webPersistence.test.ts +++ b/tests/webPersistence.test.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; 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 { WebNativeTeam, WebObservation, WebTaskSource, WebTeamProof } from '../apps/web/collaboration'; import type { WebRun } from '../apps/web/shared'; import { readWebArchiveObservations, WebStorage, type StoredWebArchive } from '../apps/web/storage'; import { WebKnowledgeService } from '../apps/web/knowledgeService'; @@ -180,6 +180,35 @@ describe('durable web evidence and registered research configuration without mod expect(readWebArchiveObservations(loaded)).toEqual({ run: saved, observations: [frame] }); }); + it('deduplicates native delivery and adoption source in v2, and reads older v2 files with inline team proof material', () => { + const store = new WebStorage(), saved = run(); + const source = 'theorem native_result : True := by trivial\n/-' + 'z'.repeat(110_000) + '-/\n'; + const checkedSource = '-- Exact checked projection\n' + source; + const proof: WebTeamProof = { commit: taskSource.commit, sourceDigest: mathDigest(source), + environmentDigest: taskSource.environmentDigest, sources: [{ file: taskSource.file, source }], + declarations: [{ file: taskSource.file, name: 'native_result', checkedSource, receipts: [] }] }; + const nativeTeam: WebNativeTeam = { schema: 'theorem-os.web-native-team.v1', runId: 'solver-old', maxAgents: 3, + memberCount: 1, taskCount: 3, taskOmissions: 0, tasks: [], findings: [], + deliveries: Array.from({ length: 2 }, (_, index) => + ({ id: `delivery-${index}`, taskId: `task-${index}`, memberId: 'engineer', references: [], proof })), + adoptions: [{ id: 'adoption', deliveryId: 'delivery-0', targetId: 'lead', status: 'completed', proof }] }; + const frames = Array.from({ length: 66 }, (_, index) => { + const frame = observation(index + 1); + return { ...frame, sources: [], inspection: { ...frame.inspection, nativeTeam } }; + }); + for (const frame of frames) store.saveObservation('alice', frame); + saved.observation = frames.at(-1); + store.saveRun('alice', saved); + const archive = store.exportRun('alice', saved); + expect(archive.sourceBlobs).toEqual({ [mathDigest(source)]: source, [mathDigest(checkedSource)]: checkedSource }); + expect(Buffer.byteLength(JSON.stringify(archive))).toBeLessThan(1_000_000); + expect(readWebArchiveObservations(archive)).toEqual({ run: saved, observations: frames }); + + const olderFrame = { ...archive.observations[0], inspection: frames[0].inspection }; + const olderArchive = { ...archive, run: { ...archive.run, observation: olderFrame }, observations: [olderFrame], sourceBlobs: {} }; + expect(readWebArchiveObservations(olderArchive)).toEqual({ run: { ...saved, observation: frames[0] }, observations: [frames[0]] }); + }); + 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/webRunner.test.ts b/tests/webRunner.test.ts index 96743de7..976fe53b 100644 --- a/tests/webRunner.test.ts +++ b/tests/webRunner.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it, vi } from 'vitest'; import { readWebConfig, webDefaults } from '../apps/web/config'; import { DockerWebRunner, parseWorkerMessage, webPrivateImagePaths } from '../apps/web/runner'; import { webProofMessageSink } from '../apps/web/proofJournal'; +import { standaloneObservationFrame } from '../apps/web/observationSources'; +import { loadWebSample } from '../apps/web/sample'; import { createWebHostDisconnectWatchdog, webWorkerHeartbeatMs } from '../apps/web/workerDisconnect'; import { writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import type { WorkerExplanationInput, WorkerExplanationMessage, WorkerInput, WorkerMessage } from '../apps/web/shared'; @@ -63,6 +65,10 @@ async function main() { } else if (args[0] === 'wait') { while (!fs.existsSync(path.join(root, 'journal', 'terminal.json'))) await new Promise(resolve => setTimeout(resolve, 10)); process.stdout.write('0\\n'); + } else if (args[0] === 'exec') { + let input = ''; for await (const chunk of process.stdin) input += chunk; + if (JSON.parse(input).type !== 'capture' || !args.includes('--observation-source-refs')) process.exit(1); + process.stdout.write(fs.readFileSync(path.join(root, 'capture.json'))); } else if (args[0] === 'cp') fs.cpSync(path.join(root, 'journal'), args[2], { recursive: true }); else if (args[0] !== 'create' && args[0] !== 'rm') process.exitCode = 1; } @@ -81,17 +87,30 @@ main().catch(() => process.exit(1)); status: 'candidate', workerId: 'solver', capturedAt: '2026-11-24T03:00:00.000Z' } } as const; const terminal = { type: 'result', result: { status: 'evaluated_passed', proof: artifact.artifact.source, report: { evaluator: { status: 'passed' } } } } as const; + const observation = { ...loadWebSample()!.observations.find(item => item.sources.length)!, webRunId: request.id }; + const receipt = { id: 'capture', status: 'captured', observation }; + const frame = standaloneObservationFrame(observation); + fs.writeFileSync(path.join(root, 'capture.json'), JSON.stringify({ ...receipt, observation: frame.observation, sourceBlobs: frame.sourceBlobs })); vi.stubEnv('PATH', root); - const run = new DockerWebRunner(config).run(request, message => messages.push(message), controller.signal); + const runner = new DockerWebRunner(config); + const run = runner.run(request, message => messages.push(message), controller.signal); try { sink(artifact); await vi.waitFor(() => expect(fs.readFileSync(callsPath, 'utf8')).toContain('["wait",')); expect(fs.readFileSync(callsPath, 'utf8')).not.toContain('["rm",'); + expect(await runner.command(request.id, { type: 'capture' })).toEqual(receipt); + fs.writeFileSync(path.join(root, 'capture.json'), JSON.stringify(receipt)); + expect(await runner.command(request.id, { type: 'capture' })).toEqual(receipt); + const privateSource = `\n-- ${request.input.apiKey}`; + sink({ type: 'observation', observation: { ...observation, + sources: observation.sources.map(source => ({ ...source, source: source.source + privateSource })) } }); + expect(fs.readFileSync(path.join(journal, 'observation.json'), 'utf8')).not.toContain(request.input.apiKey); sink(terminal); await run; - expect(messages).toEqual([artifact, terminal]); + expect(messages).toEqual([{ type: 'observation', observation: { ...observation, + sources: observation.sources.map(source => ({ ...source, source: source.source + '\n-- [REDACTED]' })) } }, artifact, terminal]); const calls = fs.readFileSync(callsPath, 'utf8').trim().split('\n').map(line => JSON.parse(line) as string[]); - expect(calls.map(args => args[0])).toEqual(['create', 'start', 'wait', 'cp', 'rm']); + expect(calls.map(args => args[0])).toEqual(['create', 'start', 'wait', 'exec', 'exec', 'cp', 'rm']); expect(calls[0]).toContain('type=volume,destination=/var/theoremos-proof'); expect(calls[0]).toContain('THEOREMOS_WORKER_JOURNAL=/var/theoremos-proof'); } finally { diff --git a/tests/webTrajectory.test.ts b/tests/webTrajectory.test.ts index 8c47ac88..788a9399 100644 --- a/tests/webTrajectory.test.ts +++ b/tests/webTrajectory.test.ts @@ -5,6 +5,7 @@ import type { WebEvent, WebRun } from '../apps/web/shared'; import { checkHeadline, recordedTrajectory, trajectoryPage, trajectoryQuery, trajectoryVersionQuery, WebTrajectories, type TrajectoryPage } from '../apps/web/trajectory'; import { buildTrajectory, emptyTrajectory, mergeTrajectory, retryRuns, sameWords, stepTasks, trajectoryTally, trajectoryTaskNames, type TrajectoryStep } from '../apps/web/client/trajectory'; import { withFailedAttempt } from '../scripts/web-trajectory-fixture'; +import { translateWebProgress } from '../apps/web/progress'; const sample = loadWebSample()!; const first = (index = recordedTrajectory(sample.events, sample.observations)) => trajectoryPage(index, { after: 0, since: 0 }); @@ -138,7 +139,24 @@ describe('web trajectory steps', () => { expect(failed).toMatchObject({ taskId: 'goal_2', number: 1, outcome: 'failed', integrated: false }); expect(failed!.ref!.check).toMatchObject({ passed: false, headline: 'The rfl tactic failed.', receiptIds: ['lean-failed-attempt'] }); expect(passed).toMatchObject({ taskId: 'goal_2', number: 2, outcome: 'passed', integrated: true }); - expect(passed!.previous?.commit).toBe(failed!.ref!.version.commit); + expect(passed!.previous?.version.commit).toBe(failed!.ref!.version.commit); + }); + + it.each(['commit', 'task revision'] as const)('matches overlapping failed attempts by their recorded %s', identity => { + const data = emptyTrajectory(), at = Date.UTC(2026, 9, 22); + const firstCommit = 'a'.repeat(40), keptCommit = identity === 'commit' ? 'b'.repeat(40) : firstCommit; + const keptVersion = 'c'.repeat(64), firstVersion = identity === 'task revision' ? 'd'.repeat(64) : keptVersion; + data.events = [[firstCommit, firstVersion], [keptCommit, keptVersion]].map(([commit, taskDigest], index) => { + const event = translateWebProgress({ event: 'task_checked', taskId: 'goal', passed: false, commit, taskDigest })!; + return { type: event.event, message: event.message, details: event.details, at: new Date(at + 700 * index).toISOString(), sequence: index + 1 }; + }); + data.versions.set(keptCommit, { key: keptCommit, taskId: 'goal', commit: keptCommit, firstAt: at + 650, revision: 1, + checks: [{ at: at + 650, passed: false, status: 'failed', receiptIds: ['kept-receipt'], theorems: ['Goal'], + observation: 1, taskVersion: keptVersion, headline: 'type mismatch' }] }); + const [firstAttempt, lastAttempt] = of(buildTrajectory({ data, status: 'running', createdAt: new Date(at).toISOString() }), 'attempt'); + expect(firstAttempt).toMatchObject({ number: 1, outcome: 'failed', ref: undefined }); + expect(lastAttempt).toMatchObject({ number: 2, outcome: 'failed', + ref: { version: { commit: keptCommit }, check: { taskVersion: keptVersion, receiptIds: ['kept-receipt'] } } }); }); it('takes a task\'s consecutive attempts as one entry, where the last of them stands', () => { diff --git a/tests/webWorkerBridge.test.ts b/tests/webWorkerBridge.test.ts index b4e611aa..0a30918d 100644 --- a/tests/webWorkerBridge.test.ts +++ b/tests/webWorkerBridge.test.ts @@ -12,6 +12,7 @@ import { WebStorage } from '../apps/web/storage'; import type { WorkerInput, WorkerMessage } from '../apps/web/shared'; import { webWorkerFixture } from './helpers/webWorkerBridge'; import { mathDigest } from '../src/math/mathRuntimeIo'; +import { hashMathFormalSourceDeclaration } from '../src/math/leanSource'; import { webGuidanceSchema } from '../apps/web/collaborationValidation'; import { parseWorkerMessage } from '../apps/web/runner'; import type { WebObservation } from '../apps/web/collaboration'; @@ -111,6 +112,44 @@ describe('isolated Web worker bridge', () => { expect(messages.filter(message => message.type === 'catalog')).toHaveLength(1); }); + it('keeps every target source when its shared file would exceed the expanded frame budget', async () => { + const f = fixture(), webRunId = 'web-fixture'; + const tasks = Array.from({ length: 20 }, (_, index) => ({ ...f.goal, id: `goal-${index}`, + theoremName: `Original.target${index}`, dependsOn: [] })); + const source = 'namespace Original\n' + tasks.map((_, index) => `theorem target${index} : True := by sorry\n`).join('') + + 'end Original\n/- ' + 'a'.repeat(850_000) + ' -/\n'; + fs.writeFileSync(path.join(f.project, 'Submission.lean'), source); + const commit = f.commit(); + f.state.problem.targets = tasks.map(task => ({ proofPath: task.proofPath!, theoremName: task.theoremName, + declarationHash: hashMathFormalSourceDeclaration(source, task.theoremName)! })); + f.state.cooperation!.canonicalCommit = commit; + f.state.cooperation!.tasks = tasks.map(task => ({ task, status: 'pending', attempts: 0 })); + f.state.cooperation!.history = []; + f.save(); + + const journal = path.join(f.directory, 'journal'); + fs.mkdirSync(journal); + let wire = ''; + const sink = webProofMessageSink(new Writable({ + write(chunk: Buffer, _encoding, done) { wire = chunk.toString('utf8'); done(); }, + }), '', { directory: journal, webRunId }); + const bridge = createWebWorkerBridge({ webRunId, directory: f.directory, output: f.output, onMessage(message, frame) { + if (message.type === 'observation') sink(message, frame); + } }); + const { observation } = await bridge.capture(); + expect(observation.coverage.sources).toBe('recorded'); + expect(observation.sources.map(item => item.taskId)).toEqual(tasks.map(task => task.id)); + expect(Object.values(JSON.parse(wire).sourceBlobs)).toEqual([source]); + const stream = { runId: webRunId, sources: new Map() }; + expect(parseWorkerMessage(wire, stream)).toEqual({ type: 'observation', observation }); + f.state.turns++; f.save(); + const next = await bridge.capture(); + expect(JSON.parse(wire).sourceBlobs).toEqual({}); + expect(parseWorkerMessage(wire, stream)).toEqual({ type: 'observation', observation: next.observation }); + const backup = JSON.parse(fs.readFileSync(path.join(journal, 'observation.json'), 'utf8')).messages[0]; + expect(parseWorkerMessage(JSON.stringify(backup))).toEqual({ type: 'observation', observation: next.observation }); + }); + 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') }; @@ -126,14 +165,15 @@ describe('isolated Web worker bridge', () => { { 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: { + const check = f.state.workers![0]!.check = { commit, sourceDigest, passed: false, verification: { ...verification, status: 'failed', results: [secondReceipt, firstReceipt], } }; f.save(); - const { observation } = await createWebWorkerBridge({ + const bridge = createWebWorkerBridge({ webRunId: 'web-fixture', directory: f.directory, output: f.output, - }).capture(); + }); + const { observation } = await bridge.capture(); expect(observation.acceptance).toBe('not-assessed'); expect(observation.checks).toMatchObject([ { taskId: f.goal.id, taskVersion: taskVersion(f.goal), id: firstReceipt.receiptId, commit, sourceDigest, @@ -142,6 +182,8 @@ describe('isolated Web worker bridge', () => { { taskId: second.id, taskVersion: taskVersion(second), id: secondReceipt.receiptId, commit, sourceDigest, record: { theoremName: secondTarget.theoremName, status: 'failed', passed: false, error: secondReceipt.error } }, ]); + f.state.check = check; f.save(); + expect((await bridge.capture()).observation.checks).toEqual(observation.checks); 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 } }))) };