diff --git a/apps/web/client/researchLibraryProposal.tsx b/apps/web/client/researchLibraryProposal.tsx index 02be7509..0f2660a0 100644 --- a/apps/web/client/researchLibraryProposal.tsx +++ b/apps/web/client/researchLibraryProposal.tsx @@ -1,15 +1,17 @@ import { useEffect, useRef, useState } from 'preact/hooks'; +import { localizeMessage } from '../i18n'; import type { ResearchLibraryTrial, ResearchLibraryProposalTarget, ResearchLibraryTrialHistory } from '../researchLibraryTrialTypes'; import type { ResearchFeedback } from '../researchProjectTypes'; import { base, enc, ErrorBox, Field, MutationState, theoremHref, tx, useMutation, useResource, type Item, type Items } from './researchShared'; import { readLibraryProposalDraft, writeLibraryProposalDraft, type LibraryProposalDraft } from './researchLibraryProposalDraft'; -export function PersonalTrialAttempt({ trial, eligible }: { trial: ResearchLibraryTrial; eligible?: boolean }) { - const data = useResource>(eligible === undefined && trial.status === 'passed' ? `${base}/library-trials/${enc(trial.id)}/history` : undefined); - const allowed = eligible ?? data.data?.item.personalAttempt; +export function PersonalTrialAttempt({ trial, history }: { trial: ResearchLibraryTrial; history?: ResearchLibraryTrialHistory }) { + const data = useResource>(!history && trial.status === 'passed' ? `${base}/library-trials/${enc(trial.id)}/history` : undefined); + const eligibility = history ?? data.data?.item; return
{data.error && } - {allowed && <>

{tx('把这份候选和固定库带入你的新研究草稿,核对配置后再开始。', 'Bring this candidate and fixed library into your new research draft. Review the configuration before starting.')}

+ {eligibility?.personalAttemptReason &&

{localizeMessage(eligibility.personalAttemptReason)}

} + {eligibility?.personalAttempt && <>

{tx('把这份候选和固定库带入你的新研究草稿,核对配置后再开始。', 'Bring this candidate and fixed library into your new research draft. Review the configuration before starting.')}

{tx('准备个人新尝试', 'Prepare a personal attempt')}}
; } diff --git a/apps/web/client/researchLibraryTrialHistory.tsx b/apps/web/client/researchLibraryTrialHistory.tsx index 7ac5cf01..0c6de6cc 100644 --- a/apps/web/client/researchLibraryTrialHistory.tsx +++ b/apps/web/client/researchLibraryTrialHistory.tsx @@ -53,7 +53,7 @@ export function LibraryTrialHistoryReader({ id }: { id: string }) { - + } ; } diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index 2b185b64..912f99bf 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -60,6 +60,9 @@ export class WebJobs { for (const { owner, run, creation } of this.storage.loadRuns()) { if (creation) this.creations.set(JSON.stringify([owner, creation.requestId]), { ...creation, runId: run.id }); const provider: WebWorkerProvider = { id: run.providerId, name: run.providerId, baseUrl: '' }; + const tail = this.storage.recoverRunTail(owner, run); + const recoveredObservation = tail.observation && this.applyObservation(run, tail.observation); + if (tail.actionCount !== undefined) run.actions = { ...run.actions, count: tail.actionCount }; this.jobs.set(run.id, { owner, run, provider, input: { ...run, apiKey: '' }, controller: new AbortController() }); if (run.result && (!terminal(run) || run.phase === 'interrupted' && run.result.status === 'evaluated_passed')) { if (run.phase === 'interrupted') { @@ -75,7 +78,10 @@ export class WebJobs { run.failure = { kind: 'interrupted' }; delete run.queue; this.event(run, 'interrupted', run.error); - } else if (run.phase === 'interrupted' && !run.failure) run.failure = { kind: 'interrupted' }; + } else { + if (run.phase === 'interrupted' && !run.failure) run.failure = { kind: 'interrupted' }; + if (recoveredObservation || tail.actionCount !== undefined) this.persist(run); + } } } @@ -314,31 +320,34 @@ export class WebJobs { this.persist(job.run); } private observe(job: Job, observation: WebObservation) { - const current = job.run.solverAttempt ?? (job.run.observation && { - solverRunId: job.run.observation.solverRunId, round: 0, sequence: job.run.observation.sequence }); - if (observation.webRunId !== job.run.id || observation.snapshot.runId !== observation.solverRunId || + if (this.applyObservation(job.run, observation)) this.persist(job.run); + } + private applyObservation(run: WebRun, observation: WebObservation) { + const current = run.solverAttempt ?? (run.observation && { + solverRunId: run.observation.solverRunId, round: 0, sequence: run.observation.sequence }); + if (observation.webRunId !== run.id || observation.snapshot.runId !== observation.solverRunId || current && (current.solverRunId !== observation.solverRunId || current.sequence >= observation.sequence)) return; const configuration = observation.inspection.configuration; - const actualHarness = configuration?.agentHarness, expectedHarness = job.run.harness ?? 'codex'; + const actualHarness = configuration?.agentHarness, expectedHarness = run.harness ?? 'codex'; if (actualHarness && actualHarness.id !== expectedHarness || expectedHarness !== 'codex' && !actualHarness || - job.run.agentHarness && canonicalMathJson(job.run.agentHarness) !== canonicalMathJson(actualHarness)) return; - if ((configuration?.researchMode ?? 'legacy') !== (job.run.researchMode ?? 'legacy')) return; + run.agentHarness && canonicalMathJson(run.agentHarness) !== canonicalMathJson(actualHarness)) return; + if ((configuration?.researchMode ?? 'legacy') !== (run.researchMode ?? 'legacy')) return; if ((configuration?.researchDelegation?.mode === 'team' ? configuration.researchDelegation.maxAgents : undefined) - !== job.run.nativeTeamCapacity) return; - if (canonicalMathJson(configuration?.researchDelegation?.preferredProfiles ?? []) !== canonicalMathJson(job.run.nativeTeamPreferredProfiles ?? [])) return; - const cards = job.researchConfiguration?.personalExperts; + !== run.nativeTeamCapacity) return; + if (canonicalMathJson(configuration?.researchDelegation?.preferredProfiles ?? []) !== canonicalMathJson(run.nativeTeamPreferredProfiles ?? [])) return; + const cards = run.researchConfiguration?.personalExperts; if (configuration?.researchDelegation?.personalExperts?.digest !== (cards?.length ? personalExpertCardsDigest(cards) : undefined)) return; - if (job.run.researchMode === 'skill') { - const skill = configuration?.researchSkill, frozen = job.run.researchSkill; - if (!skill || skill.loading !== (job.run.skillLoading ?? 'native') || + if (run.researchMode === 'skill') { + const skill = configuration?.researchSkill, frozen = run.researchSkill; + if (!skill || skill.loading !== (run.skillLoading ?? 'native') || frozen && (skill.name !== frozen.name || skill.digest !== frozen.digest || skill.loading !== frozen.loading)) return; - job.run.researchSkill = { ...skill }; + run.researchSkill = { ...skill }; } - if (actualHarness) job.run.agentHarness = { ...actualHarness }; - job.run.solverAttempt = { solverRunId: observation.solverRunId, round: current?.round ?? 0, sequence: observation.sequence }; - job.run.observation = projectStoredObservationChecks(observation); - job.run.updatedAt = observation.observedAt; - this.persist(job.run); + if (actualHarness) run.agentHarness = { ...actualHarness }; + run.solverAttempt = { solverRunId: observation.solverRunId, round: current?.round ?? 0, sequence: observation.sequence }; + run.observation = projectStoredObservationChecks(observation); + run.updatedAt = observation.observedAt; + return true; } guidance(owner: string, runId: string, id: string) { const run = this.get(owner, runId); @@ -509,8 +518,9 @@ export class WebJobs { const tally = job.run.actions ??= { count: 0 }; if (tally.count >= webAgentActionLimits.perRun) tally.dropped = (tally.dropped ?? 0) + 1; else { - tally.count++; - this.storage.saveAction(job.owner, job.run.id, { ...message.action, sequence: tally.count, at: new Date().toISOString() }); + const sequence = tally.count + 1; + this.storage.saveAction(job.owner, job.run.id, { ...message.action, sequence, at: new Date().toISOString() }); + tally.count = sequence; } this.actionsChanged(job.run); } else if (message.type === 'artifact') { diff --git a/apps/web/observationChecks.ts b/apps/web/observationChecks.ts index eda15e94..54ae133f 100644 --- a/apps/web/observationChecks.ts +++ b/apps/web/observationChecks.ts @@ -1,7 +1,30 @@ +import { canonicalMathJson } from '../../src/math/mathRuntimeIo'; import type { WebCheckReceipt, WebObservation } from './collaboration'; -/** Earlier frames copied each original-goal receipt onto every goal in its batch. */ export function projectStoredObservationChecks(observation: WebObservation): WebObservation { + const projected = projectOriginalProblemChecks(observation); + // Task checks bind both statement hashes to the task revision. Older workers could also + // publish them as whole-problem checks, storing the actual task verdict in the batch field. + const isTaskCheck = ({ taskVersion, record }: WebCheckReceipt) => + record.statementHash === taskVersion && record.leanStatementHash === taskVersion; + if (!projected.checks.some(check => isTaskCheck(check) && typeof check.record.originalProblemPassed === 'boolean')) return projected; + + const taskChecks = new Set(); + const checks = projected.checks.flatMap(check => { + if (!isTaskCheck(check)) return [check]; + const { originalProblemPassed, ...record } = check.record; + const normalized = typeof originalProblemPassed === 'boolean' ? + { ...check, record: { ...record, passed: originalProblemPassed } } : check; + const key = canonicalMathJson(normalized); + if (taskChecks.has(key)) return []; + taskChecks.add(key); + return [normalized]; + }); + return { ...projected, checks }; +} + +/** Earlier frames copied each original-goal receipt onto every goal in its batch. */ +function projectOriginalProblemChecks(observation: WebObservation): WebObservation { const targets = observation.inspection.problem?.targets ?? []; if (targets.length < 2 || observation.checks.length < 2) return observation; diff --git a/apps/web/researchApi.ts b/apps/web/researchApi.ts index 77660d3d..86b4318d 100644 --- a/apps/web/researchApi.ts +++ b/apps/web/researchApi.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo'; import { inspectScopedLeanDeclarations } from '../../src/math/leanSource'; -import { researchCandidateScopeReason } from './researchCandidateScope'; +import { researchCandidateScopeReason, withResearchLibraryImports } from './researchCandidateScope'; import { WebResearchProjects } from './researchProjects'; import { WebResearchAssets } from './researchAssets'; import { researchOverview } from './researchOverview'; @@ -192,7 +192,7 @@ export class WebResearchApi { ? { expectedType: task.type ?? planned?.type } : {}) } : undefined; const attachment = submission.libraryTrial; const candidateTarget = attachment?.candidateTarget ?? inferredTarget; - const prefix = attachment?.imports.map(name => `import ${name}\n`).join('') ?? ''; + const imports = attachment?.imports ?? []; const dependencySources = attachment?.dependencySources ?? baseline.dependencySources; const expectedKind = task?.kind === 'lemma' ? planned?.declaration === 'definition' ? 'definition' : 'theorem' : inspectScopedLeanDeclarations(run.source).find(item => item.qualifiedName === candidateTarget?.name)?.kind ?? 'theorem'; @@ -202,7 +202,7 @@ export class WebResearchApi { : declaration?.kind !== expectedKind ? expectedKind === 'definition' ? '此任务要求定义,请保留计划指定的声明种类。' : '此任务要求定理或引理,请勿用定义替代证明。' : task.kind === 'lemma' && !candidateTarget.expectedType ? '候选辅助声明的计划类型不可用,请刷新后重新选择。' - : researchCandidateScopeReason({ originalSource: prefix + run.source, baselineSource: prefix + baseline.source, + : researchCandidateScopeReason({ originalSource: withResearchLibraryImports(run.source, imports), baselineSource: withResearchLibraryImports(baseline.source, imports), candidateSource: submission.source, targetName: candidateTarget.name }); const result = reason ? undefined : await this.runner.check!({ environment: run.environment, source: submission.source, sourceFile: base.file, dependencySources, diff --git a/apps/web/researchCandidateScope.ts b/apps/web/researchCandidateScope.ts index 93914bfc..b0b8f2fe 100644 --- a/apps/web/researchCandidateScope.ts +++ b/apps/web/researchCandidateScope.ts @@ -1,6 +1,6 @@ import { inspectLeanDeclarationRegions, inspectScopedLeanDeclarations, repeatedLeanLocalNames } from '../../src/math/leanSource'; import { maskLeanComments, maskLeanCommentsAndStrings } from '../../src/math/leanSyntax'; -import { mathConstructionImports } from '../../src/math/mathConstructionSources'; +import { mathConstructionHeader, mathConstructionImports } from '../../src/math/mathConstructionSources'; import { libraryForbiddenToken } from '../../src/math/libraryPacks'; import { solverMathlibImports, solverSourceContext } from '../../src/solver/sourceContext'; @@ -8,6 +8,17 @@ export type ResearchCandidateScopeInput = Readonly<{ originalSource: string; baselineSource: string; candidateSource: string; targetName: string; }>; +/** Add the trial's imports after any Lean module/prelude directives. */ +export function withResearchLibraryImports(source: string, imports: readonly string[]): string { + if (!imports.length) return source; + const added = imports.map(name => `import ${name}\n`).join(''); + const { directivesEnd } = mathConstructionHeader(source); + if (!directivesEnd) return added + source; + const lineBreak = /^\r?\n/u.exec(source.slice(directivesEnd))?.[0]; + const offset = directivesEnd + (lineBreak?.length ?? 0); + return source.slice(0, offset) + (lineBreak ? '' : '\n') + added + source.slice(offset); +} + const declarations = (source: string) => { const regions = new Map(inspectLeanDeclarationRegions(source).map(item => [item.startOffset, item])); return inspectScopedLeanDeclarations(source).map(item => ({ ...item, ...regions.get(item.startOffset)! })); diff --git a/apps/web/researchLibraryTrialTypes.ts b/apps/web/researchLibraryTrialTypes.ts index 48958b2c..a90bd171 100644 --- a/apps/web/researchLibraryTrialTypes.ts +++ b/apps/web/researchLibraryTrialTypes.ts @@ -55,6 +55,6 @@ export type ResearchLibraryTrialHistoryItem = Pick item.file.slice(0, -5).replaceAll('/', '.')))] .filter(name => !mathConstructionImports(baseline).includes(name)); - const prefix = imports.map(name => `import ${name}\n`).join(''); const proof = input.proof.trim(), indent = baseline.slice(baseline.lastIndexOf('\n', start - 1) + 1, start).match(/^\s*/u)?.[0] ?? ''; - const source = prefix + baseline.slice(0, region.bodyOffset) + ' ' + proof.split('\n').map((line, index) => index ? indent + line : line).join('\n') + '\n' + baseline.slice(region.endOffset); - const beforeDeclarations = inspectScopedLeanDeclarations(prefix + baseline), afterDeclarations = inspectScopedLeanDeclarations(source); + const candidate = baseline.slice(0, region.bodyOffset) + ' ' + proof.split('\n').map((line, index) => index ? indent + line : line).join('\n') + '\n' + baseline.slice(region.endOffset); + const source = withResearchLibraryImports(candidate, imports), importedBaseline = withResearchLibraryImports(baseline, imports); + const beforeDeclarations = inspectScopedLeanDeclarations(importedBaseline), afterDeclarations = inspectScopedLeanDeclarations(source); if (beforeDeclarations.length !== afterDeclarations.length || beforeDeclarations.some((before, index) => { const after = afterDeclarations[index]; return !after || before.kind !== after.kind || before.qualifiedName !== after.qualifiedName || before.declarationType !== after.declarationType; })) fail(400, '请只填写目标的证明体,不要添加、删除或重写其他声明。'); - const reason = researchCandidateScopeReason({ originalSource: prefix + resolved.run.source, baselineSource: prefix + baseline, + const reason = researchCandidateScopeReason({ originalSource: withResearchLibraryImports(resolved.run.source, imports), baselineSource: importedBaseline, candidateSource: source, targetName: resolved.target.declaration }); if (reason) fail(400, reason); const planned = resolved.run.observation?.plan?.tasks.find(item => item.id === resolved.task.id); @@ -191,6 +191,9 @@ export class WebResearchLibraryTrials { return { ...copy(stored.draft), ...(this.pending.has(`${viewer}:${id}`) ? { status: 'checking' as const } : {}) }; } history(viewer: string, id: string): ResearchLibraryTrialHistory { + return this.readHistory(viewer, id, true); + } + private readHistory(viewer: string, id: string, includeAttempt: boolean): ResearchLibraryTrialHistory { const stored = this.deps.storage.getRecord(this.path(viewer, id)) ?? fail(404, '试用候选不存在或不属于当前账号。'); const trial = copy(stored.draft), ref = trial.target.ref; // History retains its frozen source. Current run/release permission is still required on every read. @@ -208,7 +211,18 @@ export class WebResearchLibraryTrials { let current = true, reason: string | undefined; try { this.get(viewer, id); } catch (error) { if (!(error instanceof WebStorageError && error.status === 409)) throw error; current = false; reason = error.message; } if (this.pending.has(`${viewer}:${id}`)) trial.status = 'checking'; - return { trial, current, ...(reason ? { reason } : {}), personalAttempt: current && trial.status === 'passed' && Boolean(this.deps.jobs.get(viewer, ref.runId)), + let personalAttempt = false, personalAttemptReason: string | undefined; + if (includeAttempt && current && trial.status === 'passed') { + const ownRun = this.deps.jobs.get(viewer, ref.runId); + if (ownRun) { + try { this.checkedPersonalAttempt(viewer, trial, ownRun, stored, trial.digest); personalAttempt = true; } + catch (error) { + if (!(error instanceof WebStorageError && [400, 403, 404, 409].includes(error.status))) throw error; + personalAttemptReason = error.message; + } + } + } + return { trial, current, ...(reason ? { reason } : {}), personalAttempt, ...(personalAttemptReason ? { personalAttemptReason } : {}), libraryPack: copy(stored.libraryPack) as ResearchLibraryPack, dependencySources: copy(stored.dependencySources) }; } historyList(viewer: string, raw: unknown = {}): { items: ResearchLibraryTrialHistoryItem[]; total: number; nextOffset?: number } { @@ -220,7 +234,7 @@ export class WebResearchLibraryTrials { if (!/^trial_[a-f0-9]{32}\.json$/u.test(file)) return []; const stored = this.deps.storage.getRecord([...root, file]); if (!stored || filters.runId && stored.draft.target.ref.runId !== filters.runId || filters.assetId && stored.draft.release.assetId !== filters.assetId) return []; try { - const { trial, current, reason } = this.history(viewer, stored.draft.id); + const { trial, current, reason } = this.readHistory(viewer, stored.draft.id, false); if (filters.status && trial.status !== filters.status) return []; return [{ id: trial.id, digest: trial.digest, release: trial.release, target: trial.target.ref, runTitle: trial.target.runTitle, taskTitle: trial.target.taskTitle, declaration: trial.declaration.name, createdAt: trial.createdAt, status: trial.status, current, @@ -297,11 +311,14 @@ export class WebResearchLibraryTrials { parse(hash, digest); const trial = this.get(viewer, id), run = this.deps.jobs.get(viewer, trial.target.ref.runId) ?? fail(403, '只有原研究的所有者可以准备个人新尝试。'); const stored = this.deps.storage.getRecord(this.path(viewer, id))!; + return this.checkedPersonalAttempt(viewer, trial, run, stored, digest); + } + private checkedPersonalAttempt(viewer: string, trial: ResearchLibraryTrial, run: WebRun, stored: Stored, digest: string): ResearchLibraryPersonalAttemptPreparation { if (trial.digest !== digest || trial.status !== 'passed' || !trial.check?.receipt.passed || identity(trial.check.receipt) !== trial.check.receiptId || trial.check.receipt.draftDigest !== trial.digest || trial.check.receipt.sourceDigest !== mathDigest(trial.source) || trial.check.receipt.libraryPackDigest !== libraryPackDigest(stored.libraryPack) || mathDigest(trial.source) !== trial.sourceDigest) fail(409, '只有这份已通过独立检查的固定候选可以准备个人新尝试。'); - return { trialId: id, originRunId: run.id, ...this.attemptConfiguration(viewer, run, trial, trial.source, stored.libraryPack as ResearchLibraryPack, stored.dependencySources) }; + return { trialId: trial.id, originRunId: run.id, ...this.attemptConfiguration(viewer, run, trial, trial.source, stored.libraryPack as ResearchLibraryPack, stored.dependencySources) }; } validateProposalOrigin(viewer: string, raw: ResearchLibraryProposalOrigin): ResearchLibraryProposalOrigin { const origin = parse(researchLibraryProposalOriginSchema, raw); @@ -317,7 +334,7 @@ export class WebResearchLibraryTrials { const origin = run.libraryProposalOrigin; if (!origin || origin.projectId !== projectId || origin.feedbackId !== feedbackId || origin.trialDigest !== input.trialDigest) fail(409, '这次运行未记录此提案的固定来源。'); - let project = this.deps.projects.detail(viewer, projectId); + const project = this.deps.projects.detail(viewer, projectId); const feedback = project.feedback.find(item => item.id === feedbackId), attachment = feedback?.payload && 'libraryTrial' in feedback.payload ? feedback.payload.libraryTrial : undefined; if (!attachment || attachment.trial.digest !== input.trialDigest || !feedback?.target) fail(404, '原提案或其固定来源当前不可访问。'); const attached = project.runs.find(item => item.runId === run.id); @@ -325,20 +342,15 @@ export class WebResearchLibraryTrials { if (!project.permissions.edit) fail(403, '只有协作者可绑定研究运行。'); const sourceTarget = feedback?.target ?? fail(404, '来源陈述版本不存在。'); const sourceVersion = project.versions.find(item => item.id === sourceTarget.statementVersionId) ?? fail(404, '来源陈述版本不存在。'); - let version = project.versions.find(item => item.source === run.source && item.environment === run.environment + const version = project.versions.find(item => item.source === run.source && item.environment === run.environment && (!item.environmentDigest || item.environmentDigest === run.observation?.inspection.configuration.environmentDigest)); - if (!version) { - if (!input.createStatementVersion) fail(409, '本次源码与现有陈述不同,请确认创建新的陈述版本后再关联。'); - const requestId = `library-source-${mathDigest(input.requestId).slice(0, 48)}`; - project = this.deps.projects.addVersion(viewer, projectId, { requestId, expectedRevision: input.expectedRevision, - statement: sourceVersion.statement, source: run.source, environment: run.environment, - ...(sourceVersion.assumptions ? { assumptions: sourceVersion.assumptions } : {}), - ...(run.observation?.inspection.configuration.environmentDigest ? { environmentDigest: run.observation.inspection.configuration.environmentDigest } : {}) }); - version = project.versions.find(item => item.source === run.source && item.environment === run.environment)!; - } else if (project.revision !== input.expectedRevision) fail(409, '研究项目已经更新,请刷新后重新核对。'); + if (!version && !input.createStatementVersion) fail(409, '本次源码与现有陈述不同,请确认创建新的陈述版本后再关联。'); + if (project.revision !== input.expectedRevision) fail(409, '研究项目已经更新,请刷新后重新核对。'); + const statementRef = version ? { statementVersionId: version.id } : {}; + const newStatement = version ? undefined : { statement: sourceVersion.statement, assumptions: sourceVersion.assumptions }; return this.deps.projects.bindRun(viewer, projectId, { requestId: `library-attach-${mathDigest(input.requestId).slice(0, 48)}`, - expectedRevision: project.revision, runId: run.id, statementVersionId: version.id, exposure: 'members', - grants: { guidance: false, edit: false, approve: false, proof: false } }); + expectedRevision: input.expectedRevision, runId: run.id, ...statementRef, exposure: 'members', + grants: { guidance: false, edit: false, approve: false, proof: false } }, newStatement); } private attemptConfiguration(viewer: string, run: WebRun, trial: ResearchLibraryTrial, source: string, libraryPack: ResearchLibraryPack, dependencySources: { file: string; source: string }[]): Omit { diff --git a/apps/web/researchProjects.ts b/apps/web/researchProjects.ts index d68a9ca7..ed779b96 100644 --- a/apps/web/researchProjects.ts +++ b/apps/web/researchProjects.ts @@ -43,6 +43,7 @@ const grantsSchema = z.object({ guidance: z.boolean().optional(), edit: z.boolea approve: z.boolean().optional(), proof: z.boolean().optional() }).strict(); const bindingSchema = z.object({ ...mutation, runId: id, statementVersionId: id, exposure: z.enum(['members', 'public']).optional(), grants: grantsSchema.optional() }).strict(); +const bindingWithStatementSchema = bindingSchema.omit({ statementVersionId: true }); const taskRefSchema = z.object({ id, version: nonempty(128) }).strict(); const observationRefSchema = z.object({ sequence: z.number().int().positive(), stateDigest: hash }).strict(); const targetSchema = z.object({ runId: id, statementVersionId: id, observationRef: observationRefSchema, @@ -370,38 +371,55 @@ export class WebResearchProjects { const stored = this.writable(viewer, projectId), input = parse(versionSchema, value) as ResearchStatementInput; if (this.request(stored, viewer, 'version', input)) return this.detail(viewer, projectId); this.compare(stored.project.revision, input.expectedRevision); + const version = this.appendVersion(stored, viewer, input, options?.preserveSource); + this.remember(stored, viewer, 'version', input, version.id); this.save(stored); return this.detail(viewer, projectId); + } + private statementVersionId(viewer: string, requestId: string) { + return `version-${mathDigest(`${this.identity(viewer)}:${requestId}`).slice(0, 32)}`; + } + private appendVersion(stored: StoredProject, viewer: string, input: ResearchStatementInput, preserveSource?: boolean) { const { requestId, expectedRevision: _expected, ...statement } = input; - const source = input.formalizationId || options?.preserveSource ? input.source : input.source.trim(); + const source = input.formalizationId || preserveSource ? input.source : input.source.trim(); const version: ResearchStatementVersion = { ...statement, source, - id: `version-${mathDigest(`${this.identity(viewer)}:${requestId}`).slice(0, 32)}`, + id: this.statementVersionId(viewer, requestId), sourceDigest: mathDigest(source), author: this.author(viewer), createdAt: now() }; stored.versions.push(version); stored.project.currentStatementVersionId = version.id; this.event(stored, viewer, 'statement-created', '建立新的形式化陈述版本', { statementVersionId: version.id }); this.contribute(stored, viewer, 'formalization', '建立形式化陈述版本', { statementVersionId: version.id }); - this.remember(stored, viewer, 'version', input, version.id); this.save(stored); return this.detail(viewer, projectId); + return version; } - bindRun(viewer: string, projectId: string, value: unknown): ResearchProjectDetail { + bindRun(viewer: string, projectId: string, value: unknown, newStatement?: Pick): ResearchProjectDetail { this.authenticated(viewer); - const stored = this.readable(viewer, projectId), input = parse(bindingSchema, value) as ResearchRunBindingInput; + const stored = this.readable(viewer, projectId); + const input = (newStatement + ? parse(bindingWithStatementSchema.transform(binding => ({ ...binding, statementVersionId: this.statementVersionId(viewer, binding.requestId) })), value) + : parse(bindingSchema, value)) as ResearchRunBindingInput; + const requestInput = newStatement ? { ...input, newStatement } : input; if (!this.access(viewer, stored).edit) throw new WebStorageError(403, '只有协作者可绑定研究运行。'); - if (this.request(stored, viewer, 'binding', input)) return this.detail(viewer, projectId); + if (this.request(stored, viewer, 'binding', requestInput)) return this.detail(viewer, projectId); this.compare(stored.project.revision, input.expectedRevision); - const version = stored.versions.find(item => item.id === input.statementVersionId); const run = this.storage.getRun(viewer, input.runId); - if (!version) throw new WebStorageError(404, '陈述版本不存在。'); + const version = stored.versions.find(item => item.id === input.statementVersionId); + if (!version && !newStatement) throw new WebStorageError(404, '陈述版本不存在。'); if (!run) throw new WebStorageError(404, '运行不存在或不属于本人。'); - if (run.source !== version.source || run.environment !== version.environment || - version.environmentDigest && run.observation?.inspection.configuration.environmentDigest !== version.environmentDigest) + const environmentDigest = run.observation?.inspection.configuration.environmentDigest; + if (version && (run.source !== version.source || run.environment !== version.environment || + version.environmentDigest && environmentDigest !== version.environmentDigest)) throw new WebStorageError(409, '运行的原题或环境与陈述版本不一致。'); const previous = stored.bindings.find(binding => binding.runId === run.id); - if (previous && (previous.runOwner !== viewer || previous.statementVersionId !== version.id)) + if (previous && (previous.runOwner !== viewer || previous.statementVersionId !== input.statementVersionId)) throw new WebStorageError(409, '运行已经绑定其他陈述。'); - const binding: StoredBinding = { runId: run.id, statementVersionId: version.id, owner: this.author(viewer), runOwner: viewer, + if (newStatement) { + const statement = parse(versionSchema, { ...newStatement, requestId: input.requestId, source: run.source, + environment: run.environment, ...(environmentDigest ? { environmentDigest } : {}) }) as ResearchStatementInput; + this.appendVersion(stored, viewer, statement, true); + } + const binding: StoredBinding = { runId: run.id, statementVersionId: input.statementVersionId, owner: this.author(viewer), runOwner: viewer, exposure: input.exposure ?? 'members', grants: { ...noGrants, ...input.grants }, createdAt: previous?.createdAt ?? now() }; if (previous) stored.bindings[stored.bindings.indexOf(previous)] = binding; else stored.bindings.push(binding); this.event(stored, viewer, 'run-bound', previous ? '更新运行共享与操作授权' : '关联研究运行', - { runId: run.id, statementVersionId: version.id }); - this.remember(stored, viewer, 'binding', input, run.id); this.save(stored); return this.detail(viewer, projectId); + { runId: run.id, statementVersionId: binding.statementVersionId }); + this.remember(stored, viewer, 'binding', requestInput, run.id); this.save(stored); return this.detail(viewer, projectId); } /** Internal authorization result. Only the caller's explicit projection may cross an HTTP response. */ resolveBinding(viewer: string, projectId: string, runId: string, permission: ResearchRunPermission = 'read') { diff --git a/apps/web/sample.ts b/apps/web/sample.ts index 81429141..280c2907 100644 --- a/apps/web/sample.ts +++ b/apps/web/sample.ts @@ -71,8 +71,9 @@ export function webSampleResponse(sample: WebSampleFile, operation: string | und const newestFirst = [...sample.observations].reverse(); const source = /^tasks\/([^/]+)\/source$/u.exec(operation); if (source) { - const taskId = decodeURIComponent(source[1]), version = query.get('version') ?? undefined; - const found = newestFirst.flatMap(item => item.sources).find(item => item.taskId === taskId && (version === undefined || item.taskVersion === version)); + const taskId = decodeURIComponent(source[1]), version = query.get('version'), commit = query.get('commit'); + const found = newestFirst.flatMap(item => item.sources).find(item => item.taskId === taskId && + (version === null || item.taskVersion === version) && (commit === null || item.commit === commit)); return found ? { status: 200, body: { source: found } } : { status: 404, body: { error: '该任务版本没有已保存的源码。' } }; } const check = /^checks\/([^/]+)$/u.exec(operation); diff --git a/apps/web/storage.ts b/apps/web/storage.ts index 3b05faa6..24901638 100644 --- a/apps/web/storage.ts +++ b/apps/web/storage.ts @@ -54,6 +54,7 @@ const safeRunId = (id: string) => { return id; }; const bySequence = (items: T[]) => items.sort((a, b) => a.sequence - b.sequence); +const immutableRecordChanged = 'web_storage_immutable_record_changed'; const credentialFields = new Set(['apiKey', 'api_key', 'access_token', 'refresh_token', 'authorization']); /** Records accept visible run data only. Credential objects never become restart state. */ const publicRecord = (value: T): T => JSON.parse(JSON.stringify(value, @@ -154,14 +155,14 @@ export class WebStorage { const key = this.key(segments), text = encoded(publicRecord(value)); if (!this.root) { const previous = this.memory.get(key); - if (immutable && previous !== undefined && previous !== text) throw new Error('web_storage_immutable_record_changed'); + if (immutable && previous !== undefined && previous !== text) throw new Error(immutableRecordChanged); this.memory.set(key, text); return; } const file = path.join(this.root, key); fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); if (immutable) { if (fs.existsSync(file)) { - if (fs.readFileSync(file, 'utf8') !== text) throw new Error('web_storage_immutable_record_changed'); + if (fs.readFileSync(file, 'utf8') !== text) throw new Error(immutableRecordChanged); return; } else writeMathFrozen(file, text); } else { @@ -192,7 +193,8 @@ export class WebStorage { } getSession(id: string): StoredWebSession | undefined { return this.getRecord(['sessions', `${digestKey(id)}.json`]); } listSessions(): StoredWebSession[] { - return this.listRecords(['sessions']).map(file => this.getRecord(['sessions', file])!); + return this.listRecords(['sessions']).filter(file => /^[a-f0-9]{64}\.json$/u.test(file)) + .map(file => this.getRecord(['sessions', file])!); } deleteSession(id: string): void { this.deleteRecord(['sessions', `${digestKey(id)}.json`]); } @@ -238,6 +240,15 @@ export class WebStorage { .filter((item): item is StoredRun => Boolean(item))) .sort((a, b) => a.run.createdAt.localeCompare(b.run.createdAt)); } + /** Evidence files can reach disk before their counters and pointers in run.json. */ + recoverRunTail(owner: string, run: WebRun): { observation?: WebObservation; actionCount?: number } { + const directory = this.runPath(owner, run.id); + const frame = this.latestWrittenRecord([...directory, 'observations'], + run.solverAttempt?.sequence ?? run.observation?.sequence ?? 0); + const action = this.latestWrittenRecord([...directory, 'actions'], run.actions?.count ?? 0); + return { ...(frame ? { observation: this.hydrateObservations(directory, [frame])[0] } : {}), + ...(action ? { actionCount: action.sequence } : {}) }; + } deletedCreation(owner: string, requestId: string): WebCreation | undefined { return this.getRecord([...this.ownerPath(owner), 'deleted-requests', `${digestKey(requestId)}.json`]); } @@ -279,16 +290,17 @@ export class WebStorage { const directory = this.runPath(owner, observation.webRunId); const recordPath = [...directory, 'observations', `${observation.sequence}.json`]; const existing = this.getRecord(recordPath); - if (existing?.sources.some(source => typeof source.source === 'string')) { - // A run restored from an older server can still save its last inline observation. - this.saveRecord(recordPath, observation, true); - return; - } - const record = compactObservation(observation, (digest, source) => { + const inline = existing?.sources.some(source => typeof source.source === 'string'); + const record = inline ? observation : compactObservation(observation, (digest, source) => { const segments = [...directory, 'source-blobs', `${digest}.json`], key = this.key(segments); if (!(this.root ? fs.existsSync(path.join(this.root, key)) : this.memory.has(key))) this.saveRecord(segments, source, true); }); - this.saveRecord(recordPath, record, true); + try { this.saveRecord(recordPath, record, true); } + catch (error) { + // The read projection can normalize legacy receipts without changing the frozen observation. + if (!existing || !(error instanceof Error) || error.message !== immutableRecordChanged || + encoded(this.hydrateObservations(directory, [existing])[0]) !== encoded(publicRecord(observation))) throw error; + } } private hydrateObservations(directory: string[], records: ObservationRecord[]): WebObservation[] { const sources = new Map(); @@ -305,15 +317,13 @@ export class WebStorage { return observation && this.hydrateObservations(directory, [observation])[0]; } listObservations(owner: string, runId: string): WebObservation[] { - const directory = this.runPath(owner, runId), observations = [...directory, 'observations']; - return this.hydrateObservations(directory, bySequence(this.listRecords(observations) - .map(file => this.getRecord([...observations, file])!))); + return this.listObservationsAfter(owner, runId, 0, Number.MAX_SAFE_INTEGER); } getObservation(owner: string, runId: string, sequence?: number): WebObservation | undefined { const directory = this.runPath(owner, runId); - if (sequence === undefined) sequence = this.listRecords([...directory, 'observations']) - .reduce((latest, file) => /^\d+\.json$/u.test(file) ? Math.max(latest, Number.parseInt(file, 10)) : latest, 0); - return sequence ? this.readObservation(directory, sequence) : undefined; + if (sequence !== undefined) return sequence ? this.readObservation(directory, sequence) : undefined; + const latest = this.latestWrittenRecord([...directory, 'observations'], 0); + return latest && this.hydrateObservations(directory, [latest])[0]; } getTaskSource(owner: string, runId: string, taskId: string, version?: string, commit?: string): WebTaskSource | undefined { return this.listObservations(owner, runId).reverse().flatMap(item => item.sources) @@ -403,9 +413,23 @@ export class WebStorage { } /** Numbered records after `after` in sequence order; reading stops at a record that cannot be parsed, to be read again later. */ listRecordsAfter(directory: string[], after: number, limit: number): T[] { return this.recordsAfter(directory, after, limit); } + private numberedSequences(directory: string[], after: number): number[] { + return this.listRecords(directory).flatMap(file => /^\d+\.json$/u.test(file) ? [Number.parseInt(file, 10)] : []) + .filter(sequence => sequence > after); + } + private latestWrittenRecord(directory: string[], after: number): T | undefined { + for (const sequence of this.numberedSequences(directory, after).sort((a, b) => b - a)) { + try { + const record = this.getRecord([...directory, `${sequence}.json`]); + if (record?.sequence === sequence) return record; + } catch (error) { + if (!(error instanceof SyntaxError)) throw error; + // A crash during exclusive file creation can leave a truncated final record. + } + } + } private recordsAfter(directory: string[], after: number, limit: number): T[] { - const sequences = this.listRecords(directory).flatMap(file => /^\d+\.json$/u.test(file) ? [Number.parseInt(file, 10)] : []) - .filter(sequence => sequence > after).sort((a, b) => a - b).slice(0, limit); + const sequences = this.numberedSequences(directory, after).sort((a, b) => a - b).slice(0, limit); const records: T[] = []; for (const sequence of sequences) { let record: T | undefined; diff --git a/apps/web/workerBridge.ts b/apps/web/workerBridge.ts index 94454e2a..4daaa79e 100644 --- a/apps/web/workerBridge.ts +++ b/apps/web/workerBridge.ts @@ -184,7 +184,8 @@ function sourceProjection(state: SolverRunState, directory: string) { if (commit) addSource(node, commit); else sourcePartial = true; } const wholeChecks = [state.check, ...(state.workers ?? []).map(worker => worker.check)] - .filter((proof): proof is ProofCheck => proof !== undefined); + // Cooperative workers also retain their most recent task-scoped proof in check. + .filter((proof): proof is ProofCheck => proof !== undefined && !('taskDigest' in proof)); for (const [index, target] of state.problem.targets.entries()) { const node = state.cooperation?.tasks.find(item => item.task.kind === 'goal' && item.task.proofPath === target.proofPath && item.task.theoremName === target.theoremName); diff --git a/src/math/leanProofSearch.ts b/src/math/leanProofSearch.ts index 21102a81..512cfbcb 100644 --- a/src/math/leanProofSearch.ts +++ b/src/math/leanProofSearch.ts @@ -42,6 +42,7 @@ const nodeSchema = z.object({ id: digest, tactics: z.array(tactic).max(128), status: z.enum(['pending', 'open', 'candidate', 'rejected']), view: viewSchema.optional(), error: z.string().max(4000).optional() }).strict(); export const proofSearchCheckpointSchema = z.object({ schema: z.literal('theorem-os.proof-search-checkpoint.v1'), generation: natural, basis: basisSchema, + assignmentKey: z.string().min(1).max(4096).optional(), nodes: z.array(nodeSchema).min(1).max(4096), actions: z.array(z.object({ sequence: natural, from: digest, to: digest, replay: z.boolean(), requestDigest: digest.optional(), branchIndex: natural.optional(), proposal: proposalSchema.optional(), @@ -192,7 +193,7 @@ export async function searchLeanBranches(input: { /** 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 }; + retainedInput?: { basisDigest: string; checkpoint: SearchCheckpointReference; assignmentKey?: string }; onCheckpoint?: (reference: SearchCheckpointReference) => void; }) { const request = proofSearchRequestSchema.parse(input.request), scope = proofSearchScopeSchema.parse(input.scope); @@ -206,6 +207,7 @@ export async function searchLeanBranches(input: { const cancelTimer = scheduleMathTimeout(() => controller.abort(), request.limits.timeoutMs); let projection: ReturnType | undefined, session: ProofSearchSession | undefined; let reference: SearchCheckpointReference | undefined, checkpoint: ProofSearchCheckpoint | undefined; + let retainedCheckpoint: ProofSearchCheckpoint | undefined; let status: LeanProofSearchStatus = 'unavailable', reason: string | undefined; let candidates: { node: string; proofSource: string }[] = []; try { @@ -215,14 +217,16 @@ export async function searchLeanBranches(input: { if (readMathFile(path.join(project, 'lean-toolchain'), 1000).bytes.toString('utf8').trim() !== backend.toolchain) throw new Error('proof_search_backend_toolchain_mismatch'); if (input.retainedInput) { - if (!request.resume || request.resume.digest !== input.retainedInput.checkpointDigest) + const retained = input.retainedInput.checkpoint; + if (!input.retainedInput.assignmentKey && request.resume && request.resume.digest !== retained.digest) throw new Error('proof_search_stale_retained_checkpoint'); - const saved = readCheckpoint(project, request.resume, history); + const saved = readCheckpoint(project, retained, history); if (mathDigest(canonicalMathJson(saved.basis)) !== input.retainedInput.basisDigest || canonicalMathJson(saved.basis.scope) !== canonicalMathJson(scope) || canonicalMathJson(saved.basis.target) !== canonicalMathJson({ file: input.file, theoremName: input.theoremName, type: input.type })) throw new Error('proof_search_stale_retained_basis'); if (!saved.replaySources?.length) throw new Error('proof_search_unsupported_missing_replay_sources'); + retainedCheckpoint = saved; projection = prepareRetainedLeanSearchProjection({ ...input, env, sources: saved.replaySources.map(item => ({ file: item.file!, source: item.source! })) }); } else projection = prepareLeanSearchProjection({ ...input, env }); @@ -240,20 +244,33 @@ export async function searchLeanBranches(input: { const match = /^retained-(0|[1-9][0-9]*)-([a-f0-9]{64})\.json$/u.exec(name); return match ? [{ name, generation: Number(match[1]), digest: match[2]! }] : []; }).sort((a, b) => b.generation - a.generation)[0]; - const latest = Math.max(latestLocal, projected?.generation ?? -1); + const localReference = () => { + const file = localProofSearchPath(project, basisDigest, latestLocal, history); assertMathCanonicalPath(file); + return { path: path.relative(project, file), digest: mathDigest(readMathFile(file, checkpointLimit).bytes) }; + }; + const retained = input.retainedInput; + // An independent history can outlive an assignment. Unpublished local files + // from a prior dispatch reserve generations but cannot resume the current one. + const local = retainedCheckpoint && retained?.assignmentKey && latestLocal > retainedCheckpoint.generation + ? localReference() : undefined; + const ownedLocal = local && readCheckpoint(project, local, history).assignmentKey === retained?.assignmentKey ? local : undefined; + const resumableLocal = retained?.assignmentKey && !ownedLocal ? -1 : latestLocal; + const latest = Math.max(resumableLocal, retainedCheckpoint?.generation ?? projected?.generation ?? -1); const requireLatestResume = () => { - if (latestLocal === latest) { - const file = localProofSearchPath(project, basisDigest, latest, history); assertMathCanonicalPath(file); - reference = { path: path.relative(project, file), digest: mathDigest(readMathFile(file, checkpointLimit).bytes) }; - } else { - reference = { path: path.relative(project, path.join(directory, projected!.name)), digest: projected!.digest }; - } + reference = resumableLocal === latest ? ownedLocal ?? localReference() : retained?.checkpoint ?? + { path: path.relative(project, path.join(directory, projected!.name)), digest: projected!.digest }; checkpoint = readCheckpoint(project, reference, history); validateCheckpoint(checkpoint, basis); throw new Error('proof_search_stale_resume_required: use the returned latest checkpoint'); }; - if (request.resume) { - checkpoint = readCheckpoint(project, request.resume, history); + const resume = request.resume ?? (ownedLocal && resumableLocal === latest ? ownedLocal : retained?.checkpoint); + if (resume) { + const saved = readCheckpoint(project, resume, history); + if (retainedCheckpoint && retained && resume.digest !== retained.checkpoint.digest && + (!retained.assignmentKey || saved.assignmentKey !== retained.assignmentKey || saved.generation <= retainedCheckpoint.generation || + path.resolve(project, resume.path) !== localProofSearchPath(project, basisDigest, saved.generation, history))) + throw new Error('proof_search_stale_retained_checkpoint'); + checkpoint = saved; if (input.restartStaleImplicitResume && !input.retainedInput && !request.branches.some(branch => branch.from) && canonicalMathJson(checkpoint.basis) !== canonicalMathJson(basis)) checkpoint = undefined; else { @@ -269,7 +286,8 @@ export async function searchLeanBranches(input: { throw new Error('proof_search_unsupported_replay_source_size'); checkpoint.replaySources = replaySources; } - let generation = Math.max(latest, checkpoint.generation); + if (retained?.assignmentKey) checkpoint.assignmentKey = retained.assignmentKey; + let generation = Math.max(latestLocal, projected?.generation ?? -1, checkpoint.generation); const save = (value: ProofSearchCheckpoint) => { value.generation = ++generation; proofSearchCheckpointSchema.parse(value); diff --git a/src/math/mathConstructionSources.ts b/src/math/mathConstructionSources.ts index 006988dc..33a99c29 100644 --- a/src/math/mathConstructionSources.ts +++ b/src/math/mathConstructionSources.ts @@ -15,10 +15,16 @@ export function mathConstructionImports(source: string): string[] { /** Header import module names with their source offsets, for exact rewrites. */ export function mathConstructionImportSpans(source: string): { name: string; start: number; end: number }[] { + return mathConstructionHeader(source).imports; +} + +/** Read the optional module/prelude directives and imports at the beginning of a file. */ +export function mathConstructionHeader(source: string): { directivesEnd: number; imports: { name: string; start: number; end: number }[] } { let offset = 0, tokenStart = 0; - const next = (): string | undefined => { + const next = (sameLine = false): string | undefined => { for (;;) { - while (/\s/u.test(source[offset] ?? '') && offset < source.length) offset++; + while (offset < source.length && (sameLine ? /[^\S\r\n]/u : /\s/u).test(source[offset]!)) offset++; + if (sameLine && (source[offset] === '\r' || source[offset] === '\n')) break; if (source.startsWith('--', offset)) { const end = source.indexOf('\n', offset); offset = end < 0 ? source.length : end; @@ -85,8 +91,13 @@ export function mathConstructionImportSpans(source: string): { name: string; sta 'initialize', 'builtin_initialize', ]); - let token = next(); - while (token === 'prelude' || token === 'module') token = next(); + let token = next(), directivesEnd = 0; + while (token === 'prelude' || token === 'module') { + const nextToken = next(true); + // Retain inline comments, stopping before later comments such as declaration documentation. + directivesEnd = tokenStart; + token = nextToken ?? next(); + } while (token === 'import' || token === 'public' || token === 'private' || token === 'meta') { while (token === 'public' || token === 'private' || token === 'meta') token = next(); if (token !== 'import') break; @@ -97,7 +108,7 @@ export function mathConstructionImportSpans(source: string): { name: string; sta token = next(); } } - return imports; + return { directivesEnd, imports }; } const assertRegularSource = (root: string, relative: string): string => { diff --git a/src/solver/continuationSeed.ts b/src/solver/continuationSeed.ts index 949e91f7..67e7829b 100644 --- a/src/solver/continuationSeed.ts +++ b/src/solver/continuationSeed.ts @@ -19,9 +19,12 @@ import type { DeliveryRecord } from './deliveries'; import { researchRecordSchema, researchSourceDigest, restoreResearch } from './researchRecords'; import { researchSourceTasks, scopedResearchSources, type ResearchSourceTask } from './researchSources'; import { researchSourceKinds, researchSourceUseSchema } from './researchReferences'; -import { proofSearchCheckpointReferenceSchema } from './proofSearchRecords'; +import { installRetainedProofSearchText, MAX_PROOF_SEARCH_CHECKPOINT_BYTES, proofSearchCheckpointReferenceSchema, + proofSearchRecordForAssignment, proofSearchRecordSchema, readRetainedProofSearchText, relocateRetainedProofSearchRecord, + type ProofSearchRecord } from './proofSearchRecords'; import { mathematicalGapSchema } from './mathematicalGaps'; import { checkOutcomeSchema, nextCheckRecordSchema, nextCheckScopeSchema } from './nextCheckContract'; +import { currentNextCheck } from './nextChecks'; import { goalProgressStateSchema, resetGoalProgressClock } from './goalProgress'; import { assessTaskResponsibility, researchWorkerCanNode, researchWorkerCanTask } from './modules/organization'; import { CAPACITY_EXPLORATION_FOCUSES, currentCapacityExploration, plannedTaskRecords, type CapacityExploration } from './capacityExploration'; @@ -108,7 +111,7 @@ const frozenCandidate = z.object({ taskId: id, taskDigest: hash, workerId: id, dependencies: z.array(handoffReference), sources: z.record(z.string()), seedSources: z.record(z.string()), }).strict(); const researchDelivery = z.object({ id: z.string().min(1), producer: id, taskId: id, taskDigest: hash, - groupId: id.optional(), kind: z.literal('research'), status: z.enum(['advisory', 'superseded']), + groupId: id.optional(), kind: z.enum(['research', 'progress']), status: z.enum(['advisory', 'conditional', 'superseded']), statement: z.string(), premises: z.array(z.string()), dependencies: z.array(handoffReference), remainingObligations: z.array(z.string()), summary: z.string(), evidenceRefs: z.array(z.string()), createdAt: z.number().int().nonnegative(), commit: oid.optional(), sourceDigest: z.string().optional(), @@ -186,6 +189,10 @@ const sourceSchema = z.object({ history: z.unknown(), capacityExplorations: capacitySource.optional(), nextChecks: nextCheckSource.optional(), + proofSearch: z.object({ + records: z.record(proofSearchRecordSchema), + checkpoints: z.record(hash, z.string().max(MAX_PROOF_SEARCH_CHECKPOINT_BYTES)), + }).strict().optional(), goalProgress: goalProgressStateSchema.optional(), completedResearch: z.array(completedResearchRecord).optional(), researchContext: researchContext.optional(), @@ -278,7 +285,7 @@ const emptyInitialPlan = z.object({ tasks: z.array(z.never()).length(0), groups: function validateSeedPlan(state: SolverRunState, source: SeedSource): ReturnType { if (!source.initialPlanning) return validatePlan(state, source.plan); if (source.candidateIds.length || source.conditionalCandidates?.length || source.frozenCandidates?.length || source.capacityExplorations || - source.completedResearch || source.researchContext || source.nextChecks || source.taskDrafts?.length) + source.completedResearch || source.researchContext || source.nextChecks || source.proofSearch || source.taskDrafts?.length) throw new Error('math_continuation_seed_initial_plan_invalid'); return emptyInitialPlan.parse(source.plan); } @@ -415,8 +422,9 @@ function advisoryResearchDelivery(delivery: DeliveryRecord): DeliveryRecord { // Publication provenance is useful; old proof evidence, references, artifacts, // assignment keys and acceptance statuses are never replayed into the new host. return researchDelivery.parse({ id: delivery.id, producer: delivery.producer, taskId: delivery.taskId, - taskDigest: delivery.taskDigest, groupId: delivery.groupId, kind: 'research', - status: delivery.status === 'superseded' ? 'superseded' : 'advisory', statement: delivery.statement, + taskDigest: delivery.taskDigest, groupId: delivery.groupId, kind: delivery.kind, + status: delivery.status === 'superseded' ? 'superseded' : + delivery.kind === 'progress' && delivery.status === 'conditional' ? 'conditional' : 'advisory', statement: delivery.statement, premises: delivery.premises, dependencies: delivery.dependencies, remainingObligations: delivery.remainingObligations, summary: delivery.summary, evidenceRefs: delivery.evidenceRefs, createdAt: delivery.createdAt, commit: delivery.commit, sourceDigest: delivery.sourceDigest, finding: delivery.finding, @@ -432,7 +440,8 @@ function capturedResearchContext(state: SolverRunState): z.infer ({ ...node, proof: node.proof?.taskDigest ? node.proof : undefined, integratedCheck: node.integratedCheck?.taskDigest ? node.integratedCheck : undefined })), - deliveries: (state.cooperation!.deliveries ?? []).filter(delivery => delivery.kind === 'research' && + deliveries: (state.cooperation!.deliveries ?? []).filter(delivery => + (delivery.kind === 'research' || delivery.kind === 'progress' && delivery.mathematicalGap) && delivery.taskId && delivery.taskDigest).map(advisoryResearchDelivery) }); } @@ -449,6 +458,66 @@ function restoredResearchDeliveries(source: SeedSource, state: SolverRunState): return [...deliveries.values()]; } +function captureProofSearch(archived: SolverRunState, runDirectory: string): SeedSource['proofSearch'] { + const cooperation = archived.cooperation!, identity = { problemReceiptDigest: archived.problem.receiptDigest, + environmentDigest: archived.environmentDigest }; + const records: [string, ProofSearchRecord][] = [], checkpoints: Record = {}; + const capture = (record: ProofSearchRecord) => { + const digest = record.checkpoint.digest; + if (Object.hasOwn(checkpoints, digest)) return true; + try { + checkpoints[digest] = readRetainedProofSearchText(runDirectory, record); + return true; + } catch { return false; } + }; + for (const check of cooperation.nextChecks ?? []) { + if (check.status !== 'pending' || check.check.execution?.kind !== 'proof-search' || + !currentNextCheck(check, cooperation, identity)) continue; + if (check.proofSearchSeed) capture(check.proofSearchSeed); + const scope = { ...identity, ...check.scope.target }; + const selected = proofSearchRecordForAssignment(cooperation.proofSearchRecords, scope, check); + if (selected?.history === check.id && capture(selected)) records.push([check.taskId, selected]); + if (!check.proofSearchSeed && check.scope.executionBasisDigest) { + const owner = proofSearchRecordForAssignment(cooperation.proofSearchRecords, scope); + if (owner?.basisDigest === check.scope.executionBasisDigest && capture(owner)) records.push([scope.taskId, owner]); + } + } + if (Object.keys(checkpoints).length) return { records: Object.fromEntries(records), checkpoints }; +} + +function restoreProofSearch(source: SeedSource, state: SolverRunState, runDirectory: string) { + const artifacts = new Map(); + const identity = { problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest }; + const restore = (record: ProofSearchRecord) => { + if (record.problemReceiptDigest !== identity.problemReceiptDigest || record.environmentDigest !== identity.environmentDigest) return; + let text = source.proofSearch?.checkpoints[record.checkpoint.digest]; + // Older frozen continuations contain the pinned record but predate embedded checkpoint bytes. + if (text === undefined && !source.proofSearch) { + try { text = readRetainedProofSearchText(path.dirname(source.source.stateFile), record); } + catch { return; } + } + if (text === undefined) return; + const relocated = relocateRetainedProofSearchRecord(runDirectory, record); + artifacts.set(record.checkpoint.digest, { record: relocated, text }); + return relocated; + }; + const records = Object.fromEntries(Object.entries(source.proofSearch?.records ?? {}).flatMap(([taskId, record]) => { + const restored = restore(record); + return restored ? [[taskId, restored] as const] : []; + })); + const checks = source.nextChecks?.records.map(check => { + if (check.status !== 'pending' || !check.scope.executionBasisDigest) return check; + const seed = check.proofSearchSeed && restore(check.proofSearchSeed); + if (seed) return { ...check, proofSearchSeed: seed }; + if (records[check.taskId] || !check.proofSearchSeed && + records[check.scope.target.taskId]?.basisDigest === check.scope.executionBasisDigest) return check; + if (check.scope.problemReceiptDigest === identity.problemReceiptDigest && check.scope.environmentDigest === identity.environmentDigest) + return { ...check, status: 'stale' as const }; + return check; + }); + return { records, checks, artifacts }; +} + const draftOutputDigest = researchCheckpointOutputDigest; const ordinaryCheckpointTask = (node: TaskRecord) => continuableResearch(node.task) && !node.capacityExploration && !node.nextCheckId; const pausedResearchCheckpoint = (node: TaskRecord, checkpoint?: ResearchCheckpoint) => ordinaryCheckpointTask(node) && @@ -752,6 +821,8 @@ function captureSource(sourceStateFile: string, stateFile: string, state: Solver } const completedResearch = capturedCompletedResearch(archived, previousResearch); const context = capturedResearchContext(archived); + const proofSearch = sameProblem && archived.environmentDigest === state.environmentDigest + ? captureProofSearch(archived, sourceDirectory) : undefined; const conditionalCandidates = planned.filter(node => !isAdvisoryTask(node.task) && !(node.proof?.passed && !node.proof.conditions?.length) && !(node.integratedCheck?.passed && !node.integratedCheck.conditions?.length) && @@ -793,6 +864,7 @@ function captureSource(sourceStateFile: string, stateFile: string, state: Solver ...(archived.cooperation.nextChecks?.length ? { nextChecks: { records: archived.cooperation.nextChecks, tasks: archived.cooperation.tasks.filter(node => node.nextCheckId).map(node => ({ task: node.task, nextCheckId: node.nextCheckId!, status: node.status, ...(node.finding ? { finding: node.finding } : {}) })) } } : {}), + ...(proofSearch ? { proofSearch } : {}), ...(!added && archived.cooperation.goalProgress ? { goalProgress: archived.cooperation.goalProgress } : {}), ...(completedResearch.length ? { completedResearch } : {}), ...(completedResearch.length || context.deliveries.length ? { researchContext: context } : {}), @@ -952,13 +1024,17 @@ export async function seedSolverContinuation(options: { canonicalMathJson(node.researchCompletion ?? null) === canonicalMathJson(record?.record ?? null); }; const priorCooperation = state.cooperation; + lease.assertHeld(); + const proofSearch = restoreProofSearch(source, state, directory); if (seeded && priorCooperation && (priorCooperation.planVersion !== planVersion || canonicalMathJson(plannedTaskRecords(priorCooperation.tasks).map(node => node.task)) !== canonicalMathJson(plan.tasks) || canonicalMathJson(capacityOrigin(capturedCapacityRecords(state))) !== canonicalMathJson(capacityOrigin(source.capacityExplorations?.records ?? [])) || canonicalMathJson(priorCooperation.capacityExplorationInputs ?? []) !== canonicalMathJson(source.capacityExplorations?.inputs ?? []) || - canonicalMathJson(priorCooperation.nextChecks ?? []) !== canonicalMathJson(source.nextChecks?.records ?? []) || + canonicalMathJson(priorCooperation.nextChecks ?? []) !== canonicalMathJson(proofSearch.checks ?? []) && + canonicalMathJson(priorCooperation.nextChecks ?? []) !== canonicalMathJson(source.nextChecks?.records ?? []) || + canonicalMathJson(priorCooperation.proofSearchRecords ?? {}) !== canonicalMathJson(proofSearch.records) || source.researchContext && canonicalMathJson(priorCooperation.deliveries ?? []) !== canonicalMathJson(restoredResearchDeliveries(source, state)) || (source.completedResearch || source.researchCheckpoints) && ![pendingResearch, restoredResearch].some(records => @@ -1018,6 +1094,8 @@ export async function seedSolverContinuation(options: { throw new Error('math_continuation_seed_destination_changed'); readContinuationSnapshot(snapshot.file, snapshot.digest, { taskDigest: state.taskDigest, problemReceiptDigest: state.problem.receiptDigest }); saveReport(); + for (const { record, text } of proofSearch.artifacts.values()) + installRetainedProofSearchText(directory, record, text); const canonical = await withSolverWorktree(state.worktree, state.problem.baseCommit, async checkout => { for (const [file, text] of Object.entries(source.canonicalSources)) { const target = path.join(checkout, state.problem.projectRelative, file); assertMathCanonicalPath(target); @@ -1038,9 +1116,12 @@ export async function seedSolverContinuation(options: { capacityExploration: record.capacityExploration, attempts: 0, status: record.status === 'completed' ? 'completed' : 'pending', ...(record.finding === undefined ? {} : { finding: record.finding }) }); - for (const node of source.nextChecks?.tasks ?? []) tasks.push({ task: node.task, nextCheckId: node.nextCheckId, - attempts: 0, status: node.status === 'completed' ? 'completed' : node.status === 'blocked' ? 'blocked' : 'pending', - ...(node.finding ? { finding: node.finding } : {}) }); + for (const node of source.nextChecks?.tasks ?? []) { + const stale = proofSearch.checks?.some(check => check.id === node.nextCheckId && check.status === 'stale'); + tasks.push({ task: stale ? { ...node.task, status: 'stopped' } : node.task, nextCheckId: node.nextCheckId, + attempts: 0, status: node.status === 'completed' ? 'completed' : node.status === 'blocked' || stale ? 'blocked' : 'pending', + ...(node.finding ? { finding: node.finding } : {}) }); + } // A timeout only grants more time to the identical tree/items/environment key; // it never restores proof acceptance. Retries retain this run's later timeout progress. if (!state.continuationDigest && source.verificationCheckpoints) state.verificationCheckpoints = source.verificationCheckpoints.map(record => ({ @@ -1052,7 +1133,8 @@ export async function seedSolverContinuation(options: { canonicalCommit: canonical, leadSeedCommit: canonical, planVersion, planEdited: !source.initialPlanning, ...(source.capacityExplorations?.inputs === undefined ? {} : { capacityExplorationInputs: source.capacityExplorations.inputs.map(entry => ({ ...entry })) }), - ...(source.nextChecks ? { nextChecks: structuredClone(source.nextChecks.records) } : {}), + ...(proofSearch.checks ? { nextChecks: proofSearch.checks } : {}), + ...(Object.keys(proofSearch.records).length ? { proofSearchRecords: proofSearch.records } : {}), ...(source.goalProgress ? { goalProgress: structuredClone(source.goalProgress) } : {}), deliveries: [], history: [...capacities.filter(record => record.archived).map(archivedCapacity), ...completedResearchHistory(source)], edits: [], cursors: {} }; diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts index abcf5561..85534f0a 100644 --- a/src/solver/cooperationCore.ts +++ b/src/solver/cooperationCore.ts @@ -402,7 +402,7 @@ export abstract class CooperationCore { protected refreshNextChecks() { const identity = { problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest }; const now = Date.now(); - for (const proposed of [...proposedNextChecks(this.archive, identity, now), + for (const proposed of [...proposedNextChecks(this.archive, identity, now, path.dirname(this.lead.worktree)), ...proposedDefinitionContractChecks(this.archive, identity, now)]) { const previous = this.archive.nextChecks?.find(record => record.id === proposed.record.id); if (previous) { diff --git a/src/solver/nextChecks.ts b/src/solver/nextChecks.ts index ac1c8474..02b86fbf 100644 --- a/src/solver/nextChecks.ts +++ b/src/solver/nextChecks.ts @@ -7,7 +7,7 @@ import { isAdvisoryTask, isFeasibilityReview, taskGroup, taskVersion, type Coope import { independentFeasibilityWorker } from './modules/organization'; import { currentDefinitionContractCheck } from './definitionContractChecks'; import type { ProofRoute } from './proofRoutes'; -import { proofSearchRecordMatches, type ProofSearchRecord } from './proofSearchRecords'; +import { historicalProofSearchRecord, proofSearchRecordMatches, type ProofSearchRecord } from './proofSearchRecords'; type Identity = { problemReceiptDigest: string; environmentDigest: string }; type State = { tasks: readonly TaskRecord[]; deliveries?: readonly DeliveryRecord[]; nextChecks?: readonly NextCheckRecord[]; @@ -30,7 +30,7 @@ export function nextCheckTarget(gap: Gap, state: State): CooperativeTask | undef /** Check host-adopted identity, not a worker-supplied basis or a host/worker path spelling. */ function executionSearchSeed(check: NextCheck, target: CooperativeTask, state: State, identity: Identity, - requireCheckpointMatch: boolean): ProofSearchRecord | undefined | null { + requireCheckpointMatch: boolean, runDirectory?: string): ProofSearchRecord | undefined | null { const execution = check.execution; if (execution?.kind !== 'proof-search' || !execution.checkpoint && !execution.basis && !execution.node) return; const scope = { ...identity, ...reference(target) }; @@ -38,8 +38,13 @@ function executionSearchSeed(check: NextCheck, target: CooperativeTask, state: S proofSearchRecordMatches(record, scope) && (!execution.basis || execution.basis === record.basisDigest); // A reported digest can identify a retained independent history. Without one, use the owner's history. const checkpoint = requireCheckpointMatch ? execution.checkpoint : undefined; - if (checkpoint) return Object.values(state.proofSearchRecords ?? {}).find(record => - record.checkpoint.digest === checkpoint.digest && matches(record)) ?? null; + if (checkpoint) { + const latest = Object.values(state.proofSearchRecords ?? {}).find(record => + record.checkpoint.digest === checkpoint.digest && matches(record)); + if (latest || !runDirectory) return latest ?? null; + return historicalProofSearchRecord({ digest: checkpoint.digest, runDirectory, scope, basisDigest: execution.basis, + deliveries: state.deliveries ?? [], nextChecks: state.nextChecks }) ?? null; + } const owner = state.proofSearchRecords?.[target.id]; return matches(owner) ? owner : null; } @@ -80,12 +85,12 @@ function checkTask(record: Pick { if (gap.scopeStatus !== 'current-contracts' || !gap.nextCheck) return []; const target = nextCheckTarget(gap, state); if (!target) return []; - const proofSearchSeed = executionSearchSeed(gap.nextCheck, target, state, identity, true); + const proofSearchSeed = executionSearchSeed(gap.nextCheck, target, state, identity, true, runDirectory); if (proofSearchSeed === null) return []; const delivery = state.deliveries?.find(item => item.id === gap.deliveryId); const scope = { ...identity, parent: reference(gap.scope.source), target: reference(target), diff --git a/src/solver/proofSearchRecords.ts b/src/solver/proofSearchRecords.ts index b4baa67d..72e04632 100644 --- a/src/solver/proofSearchRecords.ts +++ b/src/solver/proofSearchRecords.ts @@ -5,6 +5,7 @@ import type { NextCheckRecord } from './nextCheckContract'; import { assertMathCanonicalPath } from '../math/paths'; import { canonicalMathJson, mathDigest, parseMathJson, readMathFile, writeMathTextDurable } from '../math/mathRuntimeIo'; import { localProofSearchPath, projectedProofSearchPath } from '../math/proofSearchCheckpointPath'; +import type { DeliveryRecord } from './deliveries'; export function proofSearchCheckForAssignment(assignment: { taskId: string; taskDigest: string }, currentChecks: readonly NextCheckRecord[], identity: { problemReceiptDigest: string; environmentDigest: string }) { @@ -42,6 +43,7 @@ export type ProofSearchScope = z.infer; export const proofSearchCheckpointEnvelopeSchema = z.object({ schema: z.literal('theorem-os.proof-search-checkpoint.v1'), generation: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), + assignmentKey: z.string().min(1).max(4096).optional(), basis: z.object({ scope: proofSearchScopeSchema, sourceDigest: digest, projectionDigest: digest, backendDigest: digest, @@ -64,16 +66,59 @@ export const proofSearchRecordSchema = z.object({ export type ProofSearchRecord = z.infer; const invalid = () => new Error('math_proof_search_checkpoint_invalid'); -function parsedCheckpoint(reference: ProofSearchCheckpointReference, file: string) { - assertMathCanonicalPath(file); - const bytes = readMathFile(file, MAX_PROOF_SEARCH_CHECKPOINT_BYTES).bytes; - if (mathDigest(bytes) !== reference.digest) throw invalid(); +function parseCheckpoint(bytes: Buffer, checkpointDigest: string) { + if (bytes.length > MAX_PROOF_SEARCH_CHECKPOINT_BYTES || mathDigest(bytes) !== checkpointDigest) throw invalid(); const parsed = proofSearchCheckpointEnvelopeSchema.safeParse(parseMathJson(bytes, 'math_proof_search_checkpoint_invalid')); if (!parsed.success) throw invalid(); const checkpoint = parsed.data, basisDigest = mathDigest(canonicalMathJson(checkpoint.basis)); return { checkpoint, basisDigest, bytes }; } +function parsedCheckpoint(reference: ProofSearchCheckpointReference, file: string) { + assertMathCanonicalPath(file); + return parseCheckpoint(readMathFile(file, MAX_PROOF_SEARCH_CHECKPOINT_BYTES).bytes, reference.digest); +} + +function retainedCheckpointPath(runDirectory: string, checkpointDigest: string) { + return path.join(path.resolve(runDirectory), 'proof-search-artifacts', digest.parse(checkpointDigest) + '.json'); +} + +function readRetainedCheckpoint(runDirectory: string, reference: ProofSearchCheckpointReference) { + const file = retainedCheckpointPath(runDirectory, reference.digest); + if (reference.path !== file) throw invalid(); + return parsedCheckpoint(reference, file); +} + +function assertRetainedCheckpoint(record: ProofSearchRecord, saved: ReturnType) { + const { checkpoint, basisDigest, bytes } = saved; + if (basisDigest !== record.basisDigest || checkpoint.generation !== record.generation || + !proofSearchRecordMatches(checkpoint.basis.scope, record) || + checkpoint.assignmentKey && checkpoint.assignmentKey !== record.assignmentKey || + checkpoint.basis.sourceDigest !== record.sourceDigest || checkpoint.basis.projectionDigest !== record.projectionDigest || + checkpoint.basis.backendDigest !== record.backendDigest) throw invalid(); + if (mathDigest(bytes.toString('utf8')) !== record.checkpoint.digest) throw invalid(); +} + +function writeCheckpoint(file: string, text: string) { + assertMathCanonicalPath(file); + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + assertMathCanonicalPath(file); + writeMathTextDurable(file, text, 0o400); +} + +function checkpointRecord(saved: ReturnType, reference: ProofSearchCheckpointReference, + origin: Pick): ProofSearchRecord { + const { checkpoint, basisDigest } = saved; + const usage = toolUsageSchema.safeParse(checkpoint.counters); + return proofSearchRecordSchema.parse({ + schema: 'theorem-os.proof-search-record.v1', ...checkpoint.basis.scope, + sourceDigest: checkpoint.basis.sourceDigest, projectionDigest: checkpoint.basis.projectionDigest, + backendDigest: checkpoint.basis.backendDigest, basisDigest, generation: checkpoint.generation, + ...origin, checkpoint: reference, ...(usage.success ? { toolUsage: usage.data } : {}), + evidence: 'advisory-proof-search', proofAcceptance: 'not-accepted', + }); +} + /** Read only an exact, regular project scratch checkpoint; an arbitrary artifact path is not an input. */ export function readProofSearchCheckpoint(projectRoot: string, value: ProofSearchCheckpointReference, history?: string) { try { @@ -94,7 +139,7 @@ export function readProofSearchCheckpoint(projectRoot: string, value: ProofSearc } catch { throw invalid(); } } -export function proofSearchRecordMatches(record: ProofSearchRecord | undefined, scope: ProofSearchScope): record is ProofSearchRecord { +export function proofSearchRecordMatches(record: T | undefined, scope: ProofSearchScope): record is T { return Boolean(record && record.taskId === scope.taskId && record.taskDigest === scope.taskDigest && record.problemReceiptDigest === scope.problemReceiptDigest && record.environmentDigest === scope.environmentDigest); } @@ -116,31 +161,48 @@ export function retainProofSearchCheckpoint(input: { projectRoot: string; runDirectory: string; reference: ProofSearchCheckpointReference; scope: ProofSearchScope; workerId: string; assignmentKey: string; now?: number; history?: string; requiredBasisDigest?: string; }): ProofSearchRecord { - const { checkpoint, basisDigest, bytes } = readProofSearchCheckpoint(input.projectRoot, input.reference, input.history); - if (canonicalMathJson(checkpoint.basis.scope) !== canonicalMathJson(input.scope) || - input.requiredBasisDigest && basisDigest !== input.requiredBasisDigest) + const saved = readProofSearchCheckpoint(input.projectRoot, input.reference, input.history); + if (!proofSearchRecordMatches(saved.checkpoint.basis.scope, input.scope) || + saved.checkpoint.assignmentKey && saved.checkpoint.assignmentKey !== input.assignmentKey || + input.requiredBasisDigest && saved.basisDigest !== input.requiredBasisDigest) throw new Error('math_proof_search_checkpoint_scope_changed'); - const directory = path.join(path.resolve(input.runDirectory), 'proof-search-artifacts'); - const usage = toolUsageSchema.safeParse(checkpoint.counters); try { - assertMathCanonicalPath(directory); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - assertMathCanonicalPath(directory); - const file = path.join(directory, `${input.reference.digest}.json`); - assertMathCanonicalPath(file); - writeMathTextDurable(file, bytes.toString('utf8'), 0o400); - return proofSearchRecordSchema.parse({ - schema: 'theorem-os.proof-search-record.v1', ...input.scope, - sourceDigest: checkpoint.basis.sourceDigest, projectionDigest: checkpoint.basis.projectionDigest, - backendDigest: checkpoint.basis.backendDigest, basisDigest, generation: checkpoint.generation, + const file = retainedCheckpointPath(input.runDirectory, input.reference.digest); + writeCheckpoint(file, saved.bytes.toString('utf8')); + return checkpointRecord(saved, { path: file, digest: input.reference.digest }, { history: input.history, workerId: input.workerId, assignmentKey: input.assignmentKey, createdAt: input.now ?? Date.now(), - checkpoint: { path: file, digest: input.reference.digest }, - ...(usage.success ? { toolUsage: usage.data } : {}), - evidence: 'advisory-proof-search', proofAcceptance: 'not-accepted', }); } catch { throw new Error('math_proof_search_checkpoint_unavailable'); } } +/** A delivery binds an older exact artifact to the worker and assignment that produced it. */ +export function historicalProofSearchRecord(input: { + digest: string; runDirectory: string; scope: ProofSearchScope; basisDigest?: string; + deliveries: readonly DeliveryRecord[]; nextChecks?: readonly NextCheckRecord[]; +}): ProofSearchRecord | undefined { + const { scope } = input; + for (const delivery of input.deliveries) { + const { searchCheckpoint, assignmentKey } = delivery; + if (delivery.kind !== 'progress' || delivery.status === 'superseded' || !assignmentKey || + searchCheckpoint?.digest !== input.digest) continue; + const owner = delivery.taskId === scope.taskId && delivery.taskDigest === scope.taskDigest; + const check = owner ? undefined : input.nextChecks?.find(record => record.taskId === delivery.taskId && + record.taskDigest === delivery.taskDigest && record.scope.target.taskId === scope.taskId && + record.scope.target.taskDigest === scope.taskDigest && record.scope.problemReceiptDigest === scope.problemReceiptDigest && + record.scope.environmentDigest === scope.environmentDigest && record.check.execution?.kind === 'proof-search'); + if (!owner && !check) continue; + try { + const saved = readRetainedCheckpoint(input.runDirectory, searchCheckpoint); + if (!proofSearchRecordMatches(saved.checkpoint.basis.scope, scope) || + saved.checkpoint.assignmentKey && saved.checkpoint.assignmentKey !== assignmentKey || + input.basisDigest && saved.basisDigest !== input.basisDigest || + check?.scope.executionBasisDigest && saved.basisDigest !== check.scope.executionBasisDigest) continue; + return checkpointRecord(saved, searchCheckpoint, { history: check?.id, workerId: delivery.producer, + assignmentKey, createdAt: delivery.createdAt }); + } catch { continue; } + } +} + /** Arrival order cannot roll back a newer generation of the same fixed search basis. */ export function latestProofSearchRecord(current: ProofSearchRecord | undefined, incoming: ProofSearchRecord): ProofSearchRecord { if (!current || current.basisDigest !== incoming.basisDigest || current.generation < incoming.generation) return incoming; @@ -155,19 +217,25 @@ export function projectProofSearchRecord(input: { if (!proofSearchRecordMatches(input.record, input.scope)) return; try { const record = proofSearchRecordSchema.parse(input.record); - const retained = path.join(path.resolve(input.runDirectory), 'proof-search-artifacts', `${record.checkpoint.digest}.json`); - if (record.checkpoint.path !== retained) return; - const { checkpoint, basisDigest, bytes } = parsedCheckpoint(record.checkpoint, retained); - if (basisDigest !== record.basisDigest || checkpoint.generation !== record.generation || - canonicalMathJson(checkpoint.basis.scope) !== canonicalMathJson(input.scope) || - checkpoint.basis.sourceDigest !== record.sourceDigest || checkpoint.basis.projectionDigest !== record.projectionDigest || - checkpoint.basis.backendDigest !== record.backendDigest) return; - const file = projectedProofSearchPath(path.resolve(input.projectRoot), basisDigest, record.generation, record.checkpoint.digest, + const text = readRetainedProofSearchText(input.runDirectory, record); + const file = projectedProofSearchPath(path.resolve(input.projectRoot), record.basisDigest, record.generation, record.checkpoint.digest, digest.optional().parse(input.history ?? record.history)); - assertMathCanonicalPath(file); - fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); - assertMathCanonicalPath(file); - writeMathTextDurable(file, bytes.toString('utf8'), 0o400); + writeCheckpoint(file, text); return { ...record, checkpoint: { path: file, digest: record.checkpoint.digest } }; } catch { return undefined; } } + +export function readRetainedProofSearchText(runDirectory: string, record: ProofSearchRecord) { + const saved = readRetainedCheckpoint(runDirectory, record.checkpoint); + assertRetainedCheckpoint(record, saved); + return saved.bytes.toString('utf8'); +} + +export function installRetainedProofSearchText(runDirectory: string, record: ProofSearchRecord, text: string) { + assertRetainedCheckpoint(record, parseCheckpoint(Buffer.from(text, 'utf8'), record.checkpoint.digest)); + writeCheckpoint(retainedCheckpointPath(runDirectory, record.checkpoint.digest), text); +} + +export function relocateRetainedProofSearchRecord(runDirectory: string, record: ProofSearchRecord): ProofSearchRecord { + return { ...record, checkpoint: { ...record.checkpoint, path: retainedCheckpointPath(runDirectory, record.checkpoint.digest) } }; +} diff --git a/src/solver/proofSearchTool.ts b/src/solver/proofSearchTool.ts index 68d69874..ced40492 100644 --- a/src/solver/proofSearchTool.ts +++ b/src/solver/proofSearchTool.ts @@ -54,15 +54,16 @@ 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); + const assignmentKey = assignmentDeliveryFile(context.assignment); const implicitResume = !request.resume && context.record; - if (implicitResume) request.resume = implicitResume.checkpoint; + if (implicitResume && !context.independentSearch) 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.', searchCheckpoint: reference }; const line = JSON.stringify(event) + '\n'; if (Buffer.byteLength(line) > MAX_DELIVERY_LINE_BYTES) throw new Error('proof_search_delivery_too_large'); - const output = path.join(context.worktree, assignmentDeliveryFile(context.assignment)); assertMathCanonicalPath(output); + const output = path.join(context.worktree, assignmentKey); assertMathCanonicalPath(output); const descriptor = fs.openSync(output, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW, 0o600); try { fs.writeFileSync(descriptor, line); fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); } }; @@ -71,7 +72,7 @@ export async function runProofSearchTool(input: { projectRoot: string; request: history: context.history, restartStaleImplicitResume: Boolean(implicitResume && !context.independentSearch), ...(context.independentSearch && context.record ? { retainedInput: { - basisDigest: context.record.basisDigest, checkpointDigest: context.record.checkpoint.digest } } : {}), + basisDigest: context.record.basisDigest, checkpoint: context.record.checkpoint, assignmentKey } } : {}), signal: input.signal, env: input.env, onCheckpoint: queueCheckpoint }); return { ...result, taskId: context.scope.taskId, taskDigest: context.scope.taskDigest, requestDigest: mathDigest(JSON.stringify(request)) }; diff --git a/tests/continuationSeed.test.ts b/tests/continuationSeed.test.ts index 685d754f..5f895065 100644 --- a/tests/continuationSeed.test.ts +++ b/tests/continuationSeed.test.ts @@ -28,7 +28,10 @@ import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; import { captureResearchBasis, researchSourceDigest, settleResearch } from '../src/solver/researchRecords'; import { researchSourceTasks, scopedResearchSources } from '../src/solver/researchSources'; import { bindMathematicalGap } from '../src/solver/mathematicalGaps'; -import { proposedNextChecks } from '../src/solver/nextChecks'; +import { currentNextCheck, proposedNextChecks } from '../src/solver/nextChecks'; +import { emptyProofSearchCheckpoint } from '../src/math/leanProofSearch'; +import { localProofSearchPath } from '../src/math/proofSearchCheckpointPath'; +import { proofSearchRecordForAssignment, projectProofSearchRecord, retainProofSearchCheckpoint } from '../src/solver/proofSearchRecords'; import { proposedDefinitionContractChecks } from '../src/solver/definitionContractChecks'; import { cooperativeResearch } from './helpers/cooperation'; import { WorkerProofLifecycle } from '../src/solver/workerProofLifecycle'; @@ -3013,4 +3016,67 @@ describe('continuation of a host-frozen unfinished delivery', () => { await f.seed(); expect(readSolverRunState(f.stateFile).cooperation!.nextChecks).toHaveLength(1); }); + + it.each(['pinned', 'legacy', 'missing'] as const)('restores a progress-origin proof search with a %s checkpoint', async mode => { + const f = fixture(), cooperation = f.oldState.cooperation!, goal = f.tasks[2]!, helper = f.tasks[0]!; + const identity = { problemReceiptDigest: f.oldState.problem.receiptDigest, environmentDigest: f.oldState.environmentDigest }; + const scope = { ...identity, taskId: helper.id, taskDigest: taskVersion(helper) }; + const saved = emptyProofSearchCheckpoint({ scope, sourceDigest: mathDigest('source'), projectionDigest: mathDigest('projection'), + backendDigest: mathDigest('backend'), target: { file: helper.proofPath!, theoremName: helper.theoremName!, type: helper.type! }, + environment: { environmentDigest: mathDigest('diagnostic env') }, sourceFiles: [] }); + saved.replaySources = [{ file: helper.proofPath!, source: helpers }]; + const basisDigest = mathDigest(canonicalMathJson(saved.basis)), sourceProject = path.join(f.sourceWorktree, f.projectRelative); + const retain = (generation: number, history?: string) => { + const file = localProofSearchPath(sourceProject, basisDigest, generation, history); + const bytes = canonicalMathJson({ ...saved, generation }); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, bytes, { mode: 0o400 }); + return retainProofSearchCheckpoint({ projectRoot: sourceProject, runDirectory: f.oldDirectory, + reference: { path: file, digest: mathDigest(bytes) }, scope, history, workerId: 'prover-1', assignmentKey: 'fixture' }); + }; + const owner = retain(0); + cooperation.proofSearchRecords = { [helper.id]: owner }; + const gap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, previousGap: 'Membership was assumed.', + reduced: 'The candidate is specified.', remaining: 'Membership remains unknown.', evidenceScope: 'Original assumptions.', + reconsiderWhen: [], nextCheck: { action: 'construction-check' as const, objective: 'Check one branch.', + expectedEvidence: 'A candidate or an open goal.', execution: { kind: 'proof-search' as const, + taskId: helper.id, taskDigest: scope.taskDigest, basis: basisDigest, + ...(mode === 'legacy' ? {} : { checkpoint: owner.checkpoint }), node: saved.nodes[0]!.id } } }; + cooperation.deliveries!.push({ id: 'search-gap', taskId: helper.id, taskDigest: taskVersion(helper), producer: 'prover-1', + kind: 'progress', status: 'conditional', statement: helper.objective, premises: [], dependencies: [], remainingObligations: [gap.remaining], + summary: 'Check the branch.', evidenceRefs: [], createdAt: 10, mathematicalGap: gap, + mathematicalGapScope: bindMathematicalGap(gap, helper, cooperation, identity) }); + const proposed = proposedNextChecks(cooperation, identity, 11)[0]!; + if (mode === 'legacy') delete proposed.record.proofSearchSeed; + cooperation.nextChecks = [proposed.record]; cooperation.tasks.push(proposed.node); + const working = mode === 'pinned' ? retain(1, proposed.record.id) : undefined; + if (working) cooperation.proofSearchRecords[proposed.record.taskId] = working; + if (mode === 'missing') fs.unlinkSync(owner.checkpoint.path); + expect(currentNextCheck(proposed.record, cooperation, identity)).toBe(true); + writeSolverRunState(f.sourceStateFile, f.oldState); + await f.seed(); + const restored = readSolverRunState(f.stateFile).cooperation!, check = restored.nextChecks![0]!; + expect(restored.deliveries!.find(delivery => delivery.id === 'search-gap')).toMatchObject({ kind: 'progress', status: 'conditional' }); + if (mode === 'missing') { + expect(currentNextCheck(check, restored, identity)).toBe(false); + expect(check.status).toBe('stale'); + expect(restored.tasks.find(node => node.nextCheckId === check.id)).toMatchObject({ status: 'blocked' }); + } else { + expect(currentNextCheck(check, restored, identity)).toBe(true); + const selected = proofSearchRecordForAssignment(restored.proofSearchRecords, scope, check); + expect(selected?.checkpoint.digest).toBe((working ?? owner).checkpoint.digest); + expect(Boolean(restored.proofSearchRecords?.[helper.id])).toBe(mode === 'legacy'); + const projected = projectProofSearchRecord({ record: selected, scope, runDirectory: f.directory, history: check.id, + projectRoot: path.join(f.newState.workers![1]!.worktree, f.projectRelative) }); + expect(projected?.checkpoint.digest).toBe(selected!.checkpoint.digest); + expect(fs.readFileSync(projected!.checkpoint.path)).toEqual(fs.readFileSync((working ?? owner).checkpoint.path)); + if (mode === 'pinned') { + expect(check.proofSearchSeed?.checkpoint.digest).toBe(owner.checkpoint.digest); + expect(check.proofSearchSeed?.checkpoint.path).toContain(f.directory); + } + for (const record of [owner, working]) if (record) fs.unlinkSync(record.checkpoint.path); + } + await f.seed(); + expect(readSolverRunState(f.stateFile).cooperation?.nextChecks).toEqual(restored.nextChecks); + }); }); diff --git a/tests/proofSearchRuntime.test.ts b/tests/proofSearchRuntime.test.ts index dbc36287..0ad5d4c3 100644 --- a/tests/proofSearchRuntime.test.ts +++ b/tests/proofSearchRuntime.test.ts @@ -9,7 +9,11 @@ import type { ProofSearchSession } from '../src/math/pantographSession'; import { latestProofSearchRecord, projectProofSearchRecord, proofSearchRecordForAssignment, readProofSearchCheckpoint, retainProofSearchCheckpoint } from '../src/solver/proofSearchRecords'; import { runProofSearchTool } from '../src/solver/proofSearchTool'; -import { assignmentDeliveryFile, taskVersion } from '../src/solver/tasks'; +import { assignmentDeliveryFile, taskVersion, type CooperativeTask, type TaskAssignment } from '../src/solver/tasks'; +import type { DeliveryRecord } from '../src/solver/deliveries'; +import { bindMathematicalGap } from '../src/solver/mathematicalGaps'; +import type { MathematicalGap } from '../src/solver/mathematicalGapContract'; +import { proposedNextChecks } from '../src/solver/nextChecks'; const boundary = vi.hoisted(() => ({ projection: vi.fn(), retainedProjection: vi.fn(), backend: vi.fn(), open: vi.fn() })); vi.mock('../src/math/leanSearchProjection', () => ({ @@ -105,6 +109,36 @@ beforeEach(() => { }); afterEach(() => { fs.rmSync(directory, { recursive: true, force: true }); }); +async function nextCheckFixture() { + const helper: CooperativeTask = { id: scope.taskId, kind: 'lemma', objective: 'Prove helper', revision: 0, proofPath: target.file, + theoremName: target.theoremName, type: target.type, dependsOn: [] }; + const goal: CooperativeTask = { id: 'original', kind: 'goal', revision: 0, objective: 'Prove original', + proofPath: 'Main.lean', theoremName: 'Original.target', dependsOn: [helper.id] }; + const identity = { problemReceiptDigest: scope.problemReceiptDigest, environmentDigest: scope.environmentDigest }; + const helperScope = { ...identity, taskId: helper.id, taskDigest: taskVersion(helper) }; + boundary.projection.mockImplementation(({ projectRoot }) => projection(projectRoot)); + boundary.retainedProjection.mockImplementation(({ projectRoot }) => projection(projectRoot)); + boundary.open.mockImplementation(async () => session()); + const result = await search({ scope: helperScope }); + const first = result.checkpoint!, retain = (projectRoot: string, reference: SearchCheckpointReference, + workerId: string, history?: string, assignmentKey = workerId) => retainProofSearchCheckpoint({ + projectRoot, runDirectory: directory, reference, scope: helperScope, workerId, assignmentKey, history, + }); + const seed = retain(project, first, 'owner'), tasks = [helper, goal].map(task => ({ task, status: 'pending' as const, attempts: 0 })); + const state = { tasks, deliveries: [] as DeliveryRecord[], proofSearchRecords: { [helper.id]: seed } }; + const gap: MathematicalGap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, previousGap: 'The helper is open.', + reduced: 'Introduction yields an open equality.', remaining: 'Close the equality.', evidenceScope: 'Current contracts.', + reconsiderWhen: [], nextCheck: { action: 'apply-lemma', objective: 'Check an open branch.', expectedEvidence: 'Open branch or proof.', + execution: { kind: 'proof-search', taskId: helper.id, taskDigest: taskVersion(helper), basis: seed.basisDigest, + checkpoint: { ...first }, node: result.frontier!.at(-1)!.node } } }; + const delivery = { id: 'gap-1', producer: 'owner', taskId: helper.id, taskDigest: taskVersion(helper), kind: 'progress' as const, + status: 'advisory' as const, statement: helper.objective, premises: [], dependencies: [], remainingObligations: [], + summary: 'An open branch', evidenceRefs: [], createdAt: seed.createdAt, mathematicalGap: gap, + mathematicalGapScope: bindMathematicalGap(gap, helper, state, identity) }; + state.deliveries.push(delivery); + return { helper, identity, helperScope, result, first, seed, state, retain, delivery }; +} + describe('proof-search runtime persistence with fake Lean boundaries', () => { it('rejects a 4.33.0 backend for a 4.33.1 project before preparing sources or opening a session', async () => { boundary.backend.mockReturnValue({ digest: backendDigest, toolchain: 'leanprover/lean4:v4.33.0', verify: vi.fn() }); @@ -192,7 +226,7 @@ describe('proof-search runtime persistence with fake Lean boundaries', () => { boundary.open.mockImplementation(async () => session()); const from = first.checkpoint.nodes[1]!.id; const authorization = (reference: SearchCheckpointReference) => - ({ basisDigest: seed.basisDigest, checkpointDigest: reference.digest }); + ({ basisDigest: seed.basisDigest, checkpoint: reference }); const [owner, checker] = await Promise.all([ search({ request: { resume: first.reference, branches: [{ from, tactics: ['rfl'] }] } }), search({ projectRoot: independent, history, retainedInput: authorization(seedCopy), @@ -221,6 +255,60 @@ describe('proof-search runtime persistence with fake Lean boundaries', () => { expect(readCheckpoint(migrated, end.checkpoint!).counters.replay).toBeGreaterThan(checker.counters!.replay); }); + it('resumes the latest local checkpoint before host projection only within the same independent assignment', async () => { + const f = await nextCheckFixture(), proposed = proposedNextChecks(f.state, f.identity, 2)[0]!; + const checker = makeProject('checker'); + let assignment: TaskAssignment = { taskId: proposed.node.task.id, taskDigest: proposed.record.taskDigest, + workerId: 'checker', seedCommit: 'seed', assignmentId: 'dispatch-1' }; + const projected = projectProofSearchRecord({ record: f.seed, scope: f.helperScope, projectRoot: checker, + runDirectory: directory, history: proposed.record.id })!; + const write = () => fs.writeFileSync(path.join(checker, 'COOPERATION.json'), JSON.stringify({ + ...f.state, tasks: [...f.state.tasks, proposed.node], nextChecks: [proposed.record], + researchDelivery: { assignment, projectRelative: '.', ownedFiles: [target.file], ...f.identity }, + proofSearchRecords: { [f.helper.id]: projected }, + })); + write(); + const run = (request: unknown) => runProofSearchTool({ projectRoot: checker, env, request }); + const first = await run({ branches: [{ from: f.result.frontier!.at(-1)!.node, tactics: ['simp'] }] }); + expect(first).toMatchObject({ status: 'exhausted', checkpoint: expect.anything() }); + const next = { branches: [{ from: first.frontier!.at(-1)!.node, tactics: ['rfl'] }] }; + const explicit = await run({ ...next, resume: first.checkpoint }); + expect(explicit).toMatchObject({ status: 'candidate', sourceBinding: 'host-retained-source-snapshot', + counters: { issued: 6, completed: 6, replay: 3 } }); + const implicit = await run(next); + expect(implicit).toMatchObject({ status: 'candidate', sourceBinding: 'host-retained-source-snapshot', + counters: { issued: 9, completed: 9, replay: 6 } }); + expect(boundary.retainedProjection).toHaveBeenLastCalledWith(expect.objectContaining({ + sources: readCheckpoint(project, f.first).replaySources, + })); + assignment = { ...assignment, assignmentId: 'dispatch-2' }; + write(); + await expect(run({ ...next, resume: implicit.checkpoint })).resolves.toMatchObject({ + status: 'stale', reason: 'proof_search_stale_retained_checkpoint', + }); + const restarted = await run({ branches: [{ from: f.result.frontier!.at(-1)!.node, tactics: ['rfl'] }] }); + expect(restarted).toMatchObject({ status: 'candidate', counters: { issued: 3, completed: 3, replay: 1 } }); + expect(readCheckpoint(checker, restarted.checkpoint!).generation).toBeGreaterThan(readCheckpoint(checker, implicit.checkpoint!).generation); + }); + + it('schedules an older exact checkpoint from its host-retained assignment delivery', async () => { + const f = await nextCheckFixture(); + const next = await search({ scope: f.helperScope, request: { resume: f.first, + branches: [{ from: f.result.frontier!.at(-1)!.node, tactics: ['simp'] }], + limits: { timeoutMs: 30_000, maxTransitions: 32 } } }); + const latest = f.retain(project, next.checkpoint!, 'owner'); + expect(latest.generation).toBeGreaterThan(f.seed.generation); + f.state.proofSearchRecords[f.helper.id] = latestProofSearchRecord(f.seed, latest); + const receipt = { ...f.delivery, id: 'checkpoint-accepted', mathematicalGap: undefined, mathematicalGapScope: undefined, + assignmentKey: f.seed.assignmentKey, searchCheckpoint: f.seed.checkpoint }; + f.state.deliveries.unshift({ ...receipt, searchCheckpoint: f.first }); + expect(proposedNextChecks(f.state, f.identity, 2, directory)).toEqual([]); + f.state.deliveries[0] = { ...receipt, taskDigest: mathDigest('stale task version') }; + expect(proposedNextChecks(f.state, f.identity, 2, directory)).toEqual([]); + f.state.deliveries[0] = receipt; + expect(proposedNextChecks(f.state, f.identity, 2, directory)[0]?.record.proofSearchSeed).toEqual(f.seed); + }); + it('keeps ordinary owner resumes stale when current source changes instead of restoring retained source', async () => { const first = await savedSearch(), changedSource = sources[0]!.source + '-- new owner edit\n'; fs.writeFileSync(path.join(project, target.file), changedSource); @@ -287,11 +375,12 @@ describe('proof-search runtime persistence with fake Lean boundaries', () => { it.each([ ['basisDigest', 'proof_search_stale_retained_basis'], - ['checkpointDigest', 'proof_search_stale_retained_checkpoint'], + ['checkpoint', 'proof_search_stale_retained_checkpoint'], ] as const)('rejects a retained-input %s mismatch before preparing sources or opening a backend', async (field, reason) => { const first = await savedSearch(); clearBoundaryCalls(); - const retainedInput = { basisDigest: first.result.basis!, checkpointDigest: first.reference.digest, - [field]: mathDigest('another authorization') }; + const other = mathDigest('another authorization'); + const retainedInput = { basisDigest: field === 'basisDigest' ? other : first.result.basis!, + checkpoint: field === 'checkpoint' ? { ...first.reference, digest: other } : first.reference }; const result = await search({ request: continuation(first.reference, first.checkpoint), retainedInput }); expect(result).toMatchObject({ status: 'stale', reason, proofAcceptance: 'not-accepted' }); expect(boundary.projection).not.toHaveBeenCalled(); expect(boundary.retainedProjection).not.toHaveBeenCalled(); @@ -307,7 +396,7 @@ describe('proof-search runtime persistence with fake Lean boundaries', () => { const output = projection(project), fake = session({ firstStateId: 500 }); boundary.retainedProjection.mockReturnValue(output); boundary.open.mockResolvedValue(fake); const result = await search({ request: continuation(first.reference, first.checkpoint), - retainedInput: { basisDigest: first.result.basis!, checkpointDigest: first.reference.digest } }); + retainedInput: { basisDigest: first.result.basis!, checkpoint: first.reference } }); expect(result).toMatchObject({ status: 'candidate', basis: first.result.basis, proofAcceptance: 'not-accepted', counters: { issued: 3, completed: 3, replay: 1 } }); expect(boundary.retainedProjection).toHaveBeenCalledWith(expect.objectContaining({ projectRoot: project, ...target, @@ -329,7 +418,7 @@ describe('proof-search runtime persistence with fake Lean boundaries', () => { const output = projection(project, override); boundary.retainedProjection.mockReturnValue(output); if (field === 'backendDigest') boundary.backend.mockReturnValue({ digest: changed, toolchain, verify: vi.fn() }); const result = await search({ request: continuation(first.reference, first.checkpoint), - retainedInput: { basisDigest: first.result.basis!, checkpointDigest: first.reference.digest } }); + retainedInput: { basisDigest: first.result.basis!, checkpoint: first.reference } }); expect(result).toMatchObject({ status: 'stale', reason: 'proof_search_stale_basis', proofAcceptance: 'not-accepted' }); expect(boundary.retainedProjection).toHaveBeenCalledTimes(1); expect(boundary.projection).not.toHaveBeenCalled(); expect(boundary.open).not.toHaveBeenCalled(); expect(output.compile).not.toHaveBeenCalled(); diff --git a/tests/proofSearchTool.test.ts b/tests/proofSearchTool.test.ts index 3dd6a66e..dfdc5732 100644 --- a/tests/proofSearchTool.test.ts +++ b/tests/proofSearchTool.test.ts @@ -152,9 +152,9 @@ describe('proof-search worker tool without Lean or model execution', () => { scope: { ...identity, taskId: helper.id, taskDigest: taskVersion(helper) } }); await runProofSearchTool({ projectRoot: f.project, request: request() }); const call = backend.search.mock.calls[0]![0] as SearchInput; - expect(call.request).toMatchObject({ resume: f.record.checkpoint }); - expect(call.request).not.toMatchObject({ resume: { path: '/previous-worker/checkpoint.json' } }); - expect(call.retainedInput).toEqual({ basisDigest: f.check.scope.executionBasisDigest, checkpointDigest: f.record.checkpoint.digest }); + expect(call.request).not.toHaveProperty('resume'); + expect(call.retainedInput).toEqual({ basisDigest: f.check.scope.executionBasisDigest, + checkpoint: f.record.checkpoint, assignmentKey: assignmentDeliveryFile(f.assignment) }); expect(call.history).toBe(f.check.id); expect(call.scope.taskId).toBe(helper.id); expect(f.assignment.taskId).not.toBe(helper.id); diff --git a/tests/webLifecyclePersistence.test.ts b/tests/webLifecyclePersistence.test.ts index 9ce5103c..cd20274e 100644 --- a/tests/webLifecyclePersistence.test.ts +++ b/tests/webLifecyclePersistence.test.ts @@ -3,6 +3,8 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { AgentActivity } from '../apps/web/client/agentActivity'; +import type { WebObservation } from '../apps/web/collaboration'; import { readWebConfig } from '../apps/web/config'; import { WebExplanations } from '../apps/web/explanations'; import { WebFormalizations } from '../apps/web/formalizations'; @@ -32,6 +34,7 @@ type Kind = 'research' | 'formalization' | 'explanation'; type Call = { id: string; input: { apiKey: string }; signal: AbortSignal; late(): void; end(): void; fail(error: Error): void }; class Runner implements WebRunner { calls: Call[] = []; + reportResearch?: (message: WorkerMessage) => void; delayAbort = new Set(); async readiness() { return { ready: true, message: 'fixture' }; } private wait(kind: Kind, id: string, input: { apiKey: string }, signal: AbortSignal, late: () => void) { @@ -41,6 +44,7 @@ class Runner implements WebRunner { }); } run(value: WorkerInput, send: (message: WorkerMessage) => void, signal: AbortSignal) { + this.reportResearch = send; return this.wait('research', value.id, value.input, signal, () => { send({ type: 'catalog', catalog: buildTheoremKnowledge([]) }); send({ type: 'result', result: { status: 'evaluated_passed', proof, report: {} } }); @@ -128,6 +132,87 @@ describe('research restart with partially written run state', () => { await jobs.close(); }); + const frame = (webRunId: string, solverRunId: string, sequence: number): WebObservation => { + const snapshot = { schema: 'theoremos.run-observation.v1' as const, runId: solverRunId, + stateDigest: mathDigest(`${solverRunId}:${sequence}`), resultDigest: null }; + return { schema: 'theorem-os.web-observation.v1', webRunId, solverRunId, sequence, + observedAt: new Date().toISOString(), evidence: 'recorded-not-replayed', acceptance: 'not-assessed', snapshot, + inspection: { runId: solverRunId, snapshot, tasks: [], workers: [], edits: [] } as unknown as WebObservation['inspection'], + plan: null, sources: [], checks: [], guidance: [], coverage: { sources: 'recorded', checks: 'recorded' } }; + }; + + it.each([false, true])('recovers the latest durable observation from the current solver attempt (new round: %s)', async newRound => { + const { service, storage, runner } = setup('research'); + const id = service.create('alice'); + await settle(); + runner.reportResearch!({ type: 'observation', observation: frame(id, 'first-solver', 1) }); + if (newRound) runner.reportResearch!({ type: 'library_restart', previousSolverRunId: 'first-solver', solverRunId: 'next-solver', round: 1 }); + const solverRunId = newRound ? 'next-solver' : 'first-solver'; + const latest = frame(id, solverRunId, 2); + expect(storage.getRun('alice', id)?.observation?.sequence).toBe(newRound ? undefined : 1); + const jobs = restart(storage.root!, crash => { + crash.saveObservation('alice', latest); + fs.writeFileSync(path.join(crash.ownerDirectory('alice')!, 'runs', id, 'observations', '3.json'), '{"sequence":'); + }); + expect(jobs.get('alice', id)).toMatchObject({ phase: 'interrupted', observation: latest, + solverAttempt: { solverRunId, round: Number(newRound), sequence: 2 } }); + expect(jobs.storage.getRun('alice', id)?.observation).toEqual(latest); + expect(jobs.storage.getObservation('alice', id)).toEqual(latest); + expect(jobs.storage.listObservations('alice', id).map(item => item.sequence)).toEqual([1, 2]); + await jobs.close(); + }); + + it('keeps the observation empty after a library restart until the new solver has produced one', async () => { + const { service, storage, runner } = setup('research'); + const id = service.create('alice'); + await settle(); + runner.reportResearch!({ type: 'observation', observation: frame(id, 'previous-solver', 1) }); + runner.reportResearch!({ type: 'library_restart', previousSolverRunId: 'previous-solver', solverRunId: 'new-solver', round: 1 }); + const jobs = restart(storage.root!); + expect(jobs.get('alice', id)?.solverAttempt).toEqual({ solverRunId: 'new-solver', round: 1, sequence: 1 }); + expect(jobs.get('alice', id)?.observation).toBeUndefined(); + await jobs.close(); + }); + + it('preserves the immutable observation when recovering a run with a legacy duplicate receipt', async () => { + const { service, storage } = setup('research'); + const id = service.create('alice'); + await settle(); + const run = storage.getRun('alice', id)!; + const original = frame(id, 'legacy-solver', 1); + const taskVersion = mathDigest('legacy-goal'); + const taskCheck = { id: 'task-check', taskId: 'goal', taskVersion, commit: 'a'.repeat(40), + sourceDigest: mathDigest(proof), environmentDigest: mathDigest('environment'), + record: { passed: false, statementHash: taskVersion, leanStatementHash: taskVersion } }; + const legacy = { ...original, checks: [taskCheck, { ...taskCheck, record: { ...taskCheck.record, originalProblemPassed: false } }] }; + storage.saveRun('alice', { ...run, observation: legacy }); + const file = (store: WebStorage) => path.join(store.ownerDirectory('alice')!, 'runs', id, 'observations', '1.json'); + const jobs = restart(storage.root!); + expect(jobs.get('alice', id)).toMatchObject({ phase: 'interrupted', observation: { checks: [taskCheck] } }); + expect(fs.readFileSync(file(jobs.storage), 'utf8')).toBe(fs.readFileSync(file(storage), 'utf8')); + await jobs.close(); + }); + + it('makes durable actions available to AgentActivity before the summary debounce has elapsed', async () => { + const { service, storage, runner } = setup('research'); + const id = service.create('alice'); + await settle(); + const action = { workerId: 'lead', itemId: 'saved', phase: 'completed', kind: 'message', status: 'done', text: 'Already on disk' } as const; + runner.reportResearch!({ type: 'action', action }); + expect(storage.getRun('alice', id)?.actions).toBeUndefined(); + const jobs = restart(storage.root!); + const run = jobs.get('alice', id)!; + expect(run).toMatchObject({ phase: 'interrupted', actions: { count: 1 } }); + const activity = new AgentActivity(async (url: string) => { + expect(url).toBe(`/api/runs/${id}/actions?after=0`); + return { actions: jobs.storage.listActionsAfter('alice', id, 0, 500), dropped: 0 } as T; + }); + activity.sync(run); + await settle(); + expect(activity.records(run).actions).toEqual([expect.objectContaining(action)]); + await jobs.close(); + }); + it.each([false, true])('preserves saved Lean acceptance across restart (finished event durable: %s)', async eventWritten => { const { service, storage, runner } = setup('research'); const id = service.create('alice'); @@ -150,6 +235,18 @@ describe('research restart with partially written run state', () => { }); }); +it('starts with committed sessions when an interrupted session write leaves a temporary file', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'web-session-crash-')); + cleanups.push(async () => { fs.rmSync(root, { recursive: true, force: true }); }); + const storage = new WebStorage(root); + const session = { id: 'alice', csrf: 'fixture', touchedAt: Date.now() }; + storage.saveSession(session); + fs.writeFileSync(path.join(root, 'sessions', `${mathDigest(session.id)}.json.${crypto.randomUUID()}.tmp`), ''); + const service = createWebService({ ...readWebConfig({}), dataRoot: root, staticRoot: root }, new Runner(), { sample: null }); + try { expect(service.storage.listSessions()).toEqual([session]); } + finally { await service.close(); } +}); + describe.each(['research', 'formalization', 'explanation'])('%s lifecycle with failed terminal persistence', kind => { it('stops its worker instead of throwing out of an asynchronous message callback when persistence fails', async () => { const { service, storage, runner } = setup(kind); diff --git a/tests/webResearchLibraryTrials.test.ts b/tests/webResearchLibraryTrials.test.ts index 0d20c1e9..fc1c16ca 100644 --- a/tests/webResearchLibraryTrials.test.ts +++ b/tests/webResearchLibraryTrials.test.ts @@ -25,7 +25,7 @@ afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); for (const directory of directories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }); }); -function setup(storage = new WebStorage()) { +function setup(storage = new WebStorage(), moduleSource = 'namespace Shared\ntheorem zero (n : Nat) : n + 0 = n := by simp\nend Shared\n') { const sample = structuredClone(loadWebSample()!), run = sample.run; run.id = 'trial-run'; run.title = 'Exact addition goal'; run.source = original; run.environment = 'standard'; run.status = 'completed'; delete run.researchConfiguration; @@ -53,7 +53,7 @@ function setup(storage = new WebStorage()) { async resolveMathematics() { return { environment: 'standard', environmentDigest: getLeanTaskEnvironment('standard').dependencyDigest, declarations: [{ name: 'Shared.zero', type: '(n : Nat) : n + 0 = n', file: 'Submission/Library/Shared.lean' }], pack: { schema: 'theorem-os.library-pack.v1', modules: [{ file: 'Submission/Library/Shared.lean', - source: 'namespace Shared\ntheorem zero (n : Nat) : n + 0 = n := by simp\nend Shared\n', + source: moduleSource, origin: { kind: 'run', runId: 'published-fixture', commit, file: 'Main.lean' } }] } }; }, async validateMathematics() { return { passed: true, receiptRefs: ['fixture-publication-check'] }; }, }); @@ -188,6 +188,24 @@ describe('isolated Library mathematics trials', () => { denied(() => fixture.trials.prepare(alice, release.assetId, 'v1', { ...input, requestId: 'conflicting-pack' }), 409); }); + it.each(['module\n', 'module -- Keep this comment\nprelude\n', 'module /- Keep this\nblock comment. -/\n'])('places new imports after the Lean header %j', async header => { + const f = setup(new WebStorage(), 'module\n\nnamespace Shared\npublic theorem zero (n : Nat) : n + 0 = n := by simp\nend Shared\n'); + const baseline = `-- User source\n${header}public import Init\n\n` + original.replace('theorem target', '/-- Addition by zero. -/\npublic theorem target'); + f.run.source = baseline; + advance(f, value => { value.sources[0].source = baseline; value.sources[0].sourceDigest = mathDigest(baseline); }); + const release = await publish(f), { draft } = candidate(f, release); + expect(draft.source).toBe(baseline.replace('public import Init', 'import Submission.Library.Shared\npublic import Init').replace('by sorry', proof)); + expect((await f.trials.check(alice, draft.id, checkInput(draft))).status).toBe('passed'); + }); + + it('keeps the first declaration’s documentation attached when inserting imports', async () => { + const f = setup(), header = 'module\n\n', baseline = header + '/-- A preserved fact. -/\n' + original; + f.run.source = baseline; + advance(f, value => { value.sources[0].source = baseline; value.sources[0].sourceDigest = mathDigest(baseline); }); + const release = await publish(f), { draft } = candidate(f, release); + expect(draft.source).toBe(baseline.replace('module\n', 'module\nimport Submission.Library.Shared\n').replace('by sorry', proof)); + }); + it('passes the fixed auxiliary-task type to the independent checker and refuses a missing type', async () => { const fixture = setup(), release = await publish(fixture); fixture.run.observation!.inspection.tasks[0].kind = 'lemma'; @@ -417,6 +435,36 @@ describe('private Library trial history and personal follow-through', () => { expect(f.trials.attachProposalAttempt(alice, shared.id, feedback.id, input).versions).toHaveLength(attached.versions.length); denied(() => f.projects.detail(carol, shared.id), 404); }); + it('creates and binds one statement version for the follow-up run’s exact environment', async () => { + const f = setup(), { shared, trial, feedback } = await proposal(f); + f.projects.candidateDelivery(bob, shared.id, feedback.id, { requestId: 'approve-environment', expectedRevision: feedback.revision, action: 'approve' }); + const source = trial.source.trim(); + const run = f.jobs.create(alice, { providerId: 'fixture', apiKey: 'sk-disposable-fixture', model: 'fixture', effort: 'high', + environment: 'standard', source, task: 'Follow-up in an updated runtime', maxTurns: 1, maxRunSeconds: 30, workers: 1, coordination: 'independent', + libraryProposalOrigin: { projectId: shared.id, feedbackId: feedback.id, trialDigest: trial.digest } }, + { id: 'fixture', name: 'Fixture', baseUrl: 'http://127.0.0.1/never-called' }); + const newDigest = mathDigest('updated runtime'); + run.observation = structuredClone(f.run.observation!); + run.observation.webRunId = run.id; + run.observation.inspection.configuration.environmentDigest = newDigest; + f.storage.saveRun(alice, run); + const before = f.projects.addVersion(alice, shared.id, { requestId: 'earlier-environment', + expectedRevision: f.projects.detail(alice, shared.id).revision, statement: 'Addition identity', source, environment: 'standard', environmentDigest }); + const input = { requestId: 'attach-environment', expectedRevision: before.revision, runId: run.id, + trialDigest: trial.digest, confirmed: true, createStatementVersion: true }; + const save = vi.spyOn(f.storage, 'saveRecord').mockImplementationOnce(() => { throw new Error('fixture storage unavailable'); }); + try { + expect(() => f.trials.attachProposalAttempt(alice, shared.id, feedback.id, input)).toThrow('fixture storage unavailable'); + expect(f.projects.detail(alice, shared.id)).toEqual(before); + } finally { save.mockRestore(); } + const attached = f.trials.attachProposalAttempt(alice, shared.id, feedback.id, input); + expect(attached).toMatchObject({ revision: before.revision + 1 }); + expect(attached.versions).toHaveLength(before.versions.length + 1); + const version = attached.versions.find(item => item.id === attached.currentStatementVersionId); + expect(version).toMatchObject({ source, environmentDigest: newDigest }); + expect(attached.runs.find(item => item.runId === run.id)?.statementVersionId).toBe(version?.id); + expect(f.trials.attachProposalAttempt(alice, shared.id, feedback.id, input)).toEqual(attached); + }); it('lists saved prepared/passed/failed trials by run, release and state without leaking them across owners', async () => { const f = setup(), release = await publish(f), prepared = candidate(f, release, alice, 'prepared').draft; const passed = candidate(f, release, alice, 'passed').draft; await f.trials.check(alice, passed.id, checkInput(passed)); @@ -467,6 +515,19 @@ describe('private Library trial history and personal follow-through', () => { denied(() => f.trials.preparePersonalAttempt(alice, draft.id, 'f'.repeat(64)), 409); denied(() => f.trials.preparePersonalAttempt(bob, draft.id, draft.digest), 404); }); + it('keeps passed evidence readable when unpublished source prevents a personal attempt', async () => { + const f = setup(), baseline = 'import Submission.Base\n' + original; + f.run.source = baseline; + advance(f, value => { value.sources[0].source = baseline; value.sources[0].sourceDigest = mathDigest(baseline); }); + const release = await publish(f), { draft } = candidate(f, release); + const checked = await f.trials.check(alice, draft.id, checkInput(draft)); + expect(checked.status).toBe('passed'); + expect(f.calls[0].dependencySources?.map(item => item.file)).toContain('Submission/Base.lean'); + const history = f.trials.history(alice, draft.id); + expect(history).toMatchObject({ current: true, trial: checked, personalAttempt: false, + personalAttemptReason: expect.stringContaining('尚未发布的多文件源码') }); + expect(() => f.trials.preparePersonalAttempt(alice, draft.id, checked.digest)).toThrow(history.personalAttemptReason); + }); it('refuses altered receipts and candidate source before preparing a personal attempt', async () => { const f = setup(), release = await publish(f), { draft } = candidate(f, release); await f.trials.check(alice, draft.id, checkInput(draft)); const path = ['owners', mathDigest(alice), 'library-trials', `${draft.id}.json`], saved = f.storage.getRecord<{ draft: ResearchLibraryTrial }>(path)!; diff --git a/tests/webTrajectory.test.ts b/tests/webTrajectory.test.ts index 991ca486..a5a925ad 100644 --- a/tests/webTrajectory.test.ts +++ b/tests/webTrajectory.test.ts @@ -111,6 +111,16 @@ describe('web trajectory index', () => { expect(webSampleResponse(sample, 'trajectory/version', 'GET', new URLSearchParams({ task: 'goal_1', commit: 'abc' })).status).toBe(404); expect(webSampleResponse(sample, 'trajectory/version', 'GET', new URLSearchParams()).status).toBe(400); }); + + it('serves the exact commit of a saved task source in the sample', () => { + const source = sample.observations.flatMap(frame => frame.sources).find(item => item.taskId === 'goal_1')!; + const route = `tasks/${source.taskId}/source`, version = source.taskVersion; + const newest = webSampleResponse(sample, route, 'GET', new URLSearchParams({ version })); + expect((newest.body as { source: typeof source }).source.commit).not.toBe(source.commit); + expect(webSampleResponse(sample, route, 'GET', new URLSearchParams({ version, commit: source.commit }))) + .toEqual({ status: 200, body: { source } }); + expect(webSampleResponse(sample, route, 'GET', new URLSearchParams({ version, commit: 'a'.repeat(40) })).status).toBe(404); + }); }); describe('web trajectory steps', () => { it('reads the sample as the mathematical steps of the run, each attempt with the version it checked', () => { diff --git a/tests/webWorkerBridge.test.ts b/tests/webWorkerBridge.test.ts index 3b9e9d2b..16ae8389 100644 --- a/tests/webWorkerBridge.test.ts +++ b/tests/webWorkerBridge.test.ts @@ -9,6 +9,7 @@ import { taskVersion } from '../src/solver/tasks'; import { readKnowledgeCatalog } from '../src/solver/theoremKnowledgeStore'; import { WebKnowledgeService } from '../apps/web/knowledgeService'; import { WebStorage } from '../apps/web/storage'; +import { WebTrajectories } from '../apps/web/trajectory'; import type { WorkerInput, WorkerMessage } from '../apps/web/shared'; import { webWorkerFixture } from './helpers/webWorkerBridge'; import { mathDigest, withMathRuntimeLease } from '../src/math/mathRuntimeIo'; @@ -179,6 +180,43 @@ describe('isolated Web worker bridge', () => { expect(observation.coverage).toEqual({ sources: 'recorded', checks: 'recorded' }); }); + it('keeps a cooperative goal failure explainable when the worker records the same task check', async () => { + const f = fixture(), owner = 'offline-owner', webRunId = 'web-fixture'; + const proof = f.proofFor(f.goal, f.currentCommit, f.source); + const receipt = { ...proof.verification.results[0]!, status: 'failed' as const, error: 'Lean rejected the local proof.' }; + const failed = { ...proof, passed: false, verification: { ...proof.verification, status: 'failed' as const, results: [receipt] } }; + f.state.cooperation!.tasks[1] = { task: f.goal, status: 'blocked', attempts: 1, proof: failed }; + f.state.workers![1]!.check = failed; + f.save(); + const bridge = createWebWorkerBridge({ webRunId, directory: f.directory, output: f.output }); + const { observation } = await bridge.capture(); + const checks = observation.checks.filter(check => check.taskId === f.goal.id); + expect(checks).toHaveLength(1); + const [check] = checks; + expect(check!.record).toMatchObject({ passed: false, error: receipt.error }); + expect(check!.record).not.toHaveProperty('originalProblemPassed'); + + // Simulate already frozen observations with the extra whole-problem projection. + const storage = new WebStorage(path.join(f.directory, 'stored-receipts')); + const directory = ['owners', mathDigest(owner), 'runs', webRunId, 'observations']; + const wronglyTagged = { ...check!, record: { ...check!.record, originalProblemPassed: false } }; + storage.saveRecord([...directory, '1.json'], { ...observation, checks: [...observation.checks, wronglyTagged] }, true); + const checkedAgainAt = failed.verification.checkedAt + 1000; + const checkedAgain = { ...check!, record: { ...check!.record, error: 'Lean rejected the recheck.', + verification: { ...(check!.record.verification as Record), checkedAt: checkedAgainAt } } }; + const wronglyTaggedAgain = { ...checkedAgain, record: { ...checkedAgain.record, originalProblemPassed: false } }; + storage.saveRecord([...directory, '2.json'], { ...observation, sequence: 2, checks: [wronglyTagged, wronglyTaggedAgain] }, true); + expect(storage.listObservations(owner, webRunId).map(frame => frame.checks)).toEqual([observation.checks, [...checks, checkedAgain]]); + const trajectories = new WebTrajectories(storage); + const selector = [owner, webRunId, f.goal.id, failed.commit, taskVersion(f.goal), receipt.receiptId] as const; + expect(trajectories.version(...selector, failed.verification.checkedAt)?.checks).toEqual(checks); + expect(trajectories.explanationVersion(...selector, failed.verification.checkedAt)) + .toMatchObject({ status: 'found', detail: { checks } }); + expect(trajectories.explanationVersion(...selector, checkedAgainAt)) + .toMatchObject({ status: 'found', detail: { checks: [checkedAgain] } }); + expect(trajectories.explanationVersion(...selector)).toEqual({ status: 'ambiguous' }); + }); + 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') };