diff --git a/src/math/leanSyntax.ts b/src/math/leanSyntax.ts index 492ab17a..f6849b4f 100644 --- a/src/math/leanSyntax.ts +++ b/src/math/leanSyntax.ts @@ -53,9 +53,12 @@ export function parseLeanDeclarationType(type: string, declarationNames: readonl if (!closing.length && character === ':' && masked[position + 1] !== '=') { // Removing binder comments prevents a trailing line comment from swallowing the inserted comma. const binders = maskLeanComments(type.slice(start, position)).trim(); - const conclusion = type.slice(position + 1).trim(); - if (!conclusion) return { type }; - return { type: binders ? `∀ ${binders}, ${conclusion}` : conclusion, ...(universes && { universes }) }; + const conclusion = type.slice(position + 1).trimEnd(); + if (!conclusion.trimStart()) return { type }; + // Lean uses the first line's indentation to distinguish a local binding's value from its body. + const multiline = /[\r\n]/u.test(conclusion); + const body = multiline ? conclusion : conclusion.trimStart(); + return { type: binders ? `∀ ${binders},${multiline ? '' : ' '}${body}` : body, ...(universes && { universes }) }; } if (character === closing.at(-1)) closing.pop(); else if (Object.hasOwn(pairs, character) && (closing.length || character !== '⟨')) closing.push(pairs[character]!); diff --git a/src/math/leanTask.ts b/src/math/leanTask.ts index 61593979..e0c23c78 100644 --- a/src/math/leanTask.ts +++ b/src/math/leanTask.ts @@ -5,7 +5,7 @@ import { canonicalMathProblemStatementPayloads, type MathProblemContract } from import { canonicalMathJson, mathDigest, readMathJson, writeMathJsonDurable } from './mathRuntimeIo'; import { inspectLegacyLeanWhereSource, inspectScopedLeanDeclarations } from './leanSource'; import { maskLeanCommentsAndStrings } from './leanSyntax'; -import { getLeanTaskEnvironment, type LeanTaskEnvironment } from './leanTaskEnvironment'; +import { getLeanTaskEnvironment, recordedLeanTaskEnvironment, type LeanTaskEnvironment, type LeanTaskEnvironmentConfig } from './leanTaskEnvironment'; import { installLibraryPack, isLibraryPackFile, libraryDeclarationConflict, libraryPackDigest, MAX_LIBRARY_MODULE_BYTES, parseLibraryPack, type LibraryPack } from './libraryPacks'; import { mathConstructionImports } from './mathConstructionSources'; @@ -112,10 +112,10 @@ function inspectLibraryPack(value: unknown, source: string): LibraryPack { return pack; } -function trustedSources(source: string, environment: LeanTaskEnvironment): Record { +function trustedSources(source: string, environment: LeanTaskEnvironmentConfig): Record { return { 'Challenge.lean': source, - ...getLeanTaskEnvironment(environment).files, + ...environment.files, }; } @@ -160,7 +160,7 @@ export function bootstrapLeanTask(workspace: string, input: LeanTaskInput, if (fs.existsSync(workspace)) throw new Error('Lean task workspace already exists; use a new directory.'); const projectRoot = path.join(workspace, projectRelative); fs.mkdirSync(projectRoot, { recursive: true, mode: 0o700 }); - const sources = trustedSources(inspected.source, environment.id); + const sources = trustedSources(inspected.source, environment); for (const [relative, contents] of Object.entries({ ...sources, 'Submission.lean': inspected.source })) fs.writeFileSync(path.join(projectRoot, relative), contents, { flag: 'wx', mode: 0o600 }); const libraryFiles = libraryPack && installLibraryPack(projectRoot, libraryPack, @@ -206,14 +206,14 @@ export function readLeanTaskReceipt(file: string): LeanTaskReceipt { const message = gitText(workspace, ['show', '-s', '--format=%B', parsed.baseCommit]); if (!message.startsWith(seedPrefix)) throw new Error('lean_task_seed_invalid'); const seed = seedSchema.parse(JSON.parse(message.slice(seedPrefix.length))); - const environment = getLeanTaskEnvironment(seed.environment ?? 'standard'); // Receipts prepared before environment selection existed retain the exact // standard-library inputs; only a seed can opt into a dependency environment. const legacy = seed.environment === undefined && seed.environmentDigest === undefined && parsed.environment === undefined && parsed.environmentDigest === undefined; - if (parsed.toolchain !== environment.toolchain || (!legacy && - (seed.environment !== environment.id || parsed.environment !== seed.environment || - seed.environmentDigest !== environment.dependencyDigest || parsed.environmentDigest !== seed.environmentDigest))) + const environment = legacy ? getLeanTaskEnvironment('standard') : + seed.environment && seed.environmentDigest && recordedLeanTaskEnvironment(seed.environment, seed.environmentDigest); + if (!environment || parsed.toolchain !== environment.toolchain || (!legacy && + (parsed.environment !== seed.environment || parsed.environmentDigest !== seed.environmentDigest))) throw new Error('lean_task_environment_changed'); const libraryFiles = Object.keys(seed.libraryPack?.files ?? {}).sort(); if (canonicalMathJson(parsed.libraryPack ?? null) !== canonicalMathJson(seed.libraryPack ?? null) || @@ -235,7 +235,7 @@ export function readLeanTaskReceipt(file: string): LeanTaskReceipt { throw new Error('lean_task_library_binding_mismatch'); } const entries = gitText(workspace, ['ls-tree', '-r', '-z', parsed.baseCommit]).split('\0').filter(Boolean); - const expectedFiles = [...Object.keys(trustedSources('', environment.id)), 'Submission.lean', ...libraryFiles].map(relative => `${projectRelative}/${relative}`).sort(); + const expectedFiles = [...Object.keys(trustedSources('', environment)), 'Submission.lean', ...libraryFiles].map(relative => `${projectRelative}/${relative}`).sort(); const actualFiles = entries.map(entry => { const match = /^100644 blob (?:[0-9a-f]{40}|[0-9a-f]{64})\t(.+)$/u.exec(entry); if (!match) throw new Error('lean_task_seed_invalid'); @@ -256,7 +256,7 @@ export function readLeanTaskReceipt(file: string): LeanTaskReceipt { })); const legacyWhere = canonicalMathJson(parsed.declarations) === canonicalMathJson(legacyDeclarations); const inspected = inspectInput({ source, task: seed.task, environment: environment.id, definitionTargets: seed.definitionTargets }, legacyWhere); - const sources = trustedSources(source, environment.id); + const sources = trustedSources(source, environment); if (canonicalMathJson(parsed.contract) !== canonicalMathJson(contractFor(source, inspected.task)) || canonicalMathJson(parsed.publicObligations) !== canonicalMathJson(inspected.publicObligations) || canonicalMathJson(parsed.declarations) !== canonicalMathJson(inspected.declarations) || diff --git a/src/math/verifier.ts b/src/math/verifier.ts index ae7e1486..050a403d 100644 --- a/src/math/verifier.ts +++ b/src/math/verifier.ts @@ -1954,7 +1954,7 @@ const prepareLeanDeclarationQuery = async ( 'run_cmd Lean.Elab.Command.liftTermElabM do', ` let parsedType <- match Lean.Parser.runParserCategory (<- Lean.getEnv) (Lean.Name.mkSimple "term") ${JSON.stringify(type)} with`, ' | .ok stx => pure stx', - ' | .error message => throwError "Invalid expected declaration type. Supply a closed Lean type, for example (∀ (n : Nat), n = n). Parser: {message}"', + ' | .error message => throwError "Invalid expected declaration type. Supply a closed Lean type or paste the full #check output. Preserve line breaks and indentation, especially around let and have. Parser: {message}"', ` let name := (${JSON.stringify(leanNameWithoutRoot(name))} : String).toName`, ...(universes ? [ ' let info <- Lean.getConstInfo name', diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 77a303fb..7f68f387 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -1218,7 +1218,9 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise close: closeSession, stopForFreeze: async () => { // An interrupt RPC acknowledgement does not settle the active turn. - if (completion || activeTurn || compacting || tools?.busy || nativeControl?.busy) + // Once closing, await shutdown instead: run and compact can await the + // same shutdown before clearing their local turn state. + if (!closing && (completion || activeTurn || compacting || tools?.busy || nativeControl?.busy)) return { status: 'unconfirmed', reason: 'turn-not-settled' }; try { await closeSession(); diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index 2c19c36b..d0b2c267 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -40,6 +40,7 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number): s export function agentTeamWorkerDeliveryHelp(): string { return 'This proof-writing member publishes through theoremos_team, operation submit. Save source and worktree-root RESEARCH.md, ' + 'then supply summary and declarations: [{"file":"OWNED_FILE.lean","name":"Qualified.helper","type":"COMPLETE_CLOSED_LEAN_TYPE"}]. ' + + 'For type, you can paste the full Lean #check output. Preserve line breaks and indentation, especially around let and have. ' + 'Use the member\'s own editable paths listed by the host; the same filename in Lead\'s workspace is a separate copy. New independent helper declarations may be added inside these files while frozen original statements remain fixed; put scratch results in an editable owned file before nomination. ' + 'List every changed declaration since the assignment deliveryBaseCommit, including earlier unpublished or rejected drafts. ' + 'For a new shared def or abbrev in an existing owned file, add kind:"definition". Its checked body is reusable; prove any claimed property separately. Each declaration may include description and explicit premises. Submit accepts 1–32 declarations, including original targets you have proved. ' + diff --git a/src/solver/continuationInput.ts b/src/solver/continuationInput.ts index bd77fa19..efed7756 100644 --- a/src/solver/continuationInput.ts +++ b/src/solver/continuationInput.ts @@ -8,7 +8,8 @@ import type { ContextSection } from './contextCompiler'; import { largestFittingPage, splitsSurrogate } from './textPage'; export const MAX_CONTINUATION_ATTACHMENT_BYTES = 16_000_000; -const maxTotalBytes = 64_000_000, maxManifestBytes = 1_000_000; +export const MAX_CONTINUATION_TOTAL_BYTES = 64_000_000; +const maxManifestBytes = 1_000_000; const digest = z.string().regex(/^[a-f0-9]{64}$/u); const provenance = z.object({ source: z.string().min(1).max(1000).optional(), @@ -42,7 +43,7 @@ export type ContinuationInput = Readonly<{ digest: string; manifest: Continuatio function validateAttachments(manifest: { attachments: ContinuationAttachment[] }) { if (new Set(manifest.attachments.map(item => item.id)).size !== manifest.attachments.length || - manifest.attachments.reduce((total, item) => total + item.bytes, 0) > maxTotalBytes) + manifest.attachments.reduce((total, item) => total + item.bytes, 0) > MAX_CONTINUATION_TOTAL_BYTES) throw new Error('math_continuation_attachments_invalid'); const sizes = new Map(); for (const item of manifest.attachments) { diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index aa1d3423..381c76a6 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -25,8 +25,13 @@ export const teamDeclarationListSchema = z.array(z.object({ file: z.string().refine(value => allowedKnowledgeFile(value) && value.endsWith('.lean')), name: z.string().min(1).max(1000).refine(isSimpleLeanName), kind: z.literal('definition').optional(), - type: z.string().trim().min(1).refine(value => Buffer.byteLength(value) <= MAX_LEAN_EXPECTED_TYPE_BYTES, - { message: `Expected declaration type must be at most ${MAX_LEAN_EXPECTED_TYPE_BYTES} UTF-8 bytes.` }), + type: z.string().min(1).transform(value => { + const type = value.trimEnd(); + // The first line's indentation can be significant in a multiline Lean term. + return /[\r\n]/u.test(type) ? type : type.trimStart(); + }).refine(value => value.length > 0, { message: 'Expected declaration type must not be blank.' }) + .refine(value => Buffer.byteLength(value) <= MAX_LEAN_EXPECTED_TYPE_BYTES, + { message: `Expected declaration type must be at most ${MAX_LEAN_EXPECTED_TYPE_BYTES} UTF-8 bytes.` }), description: z.string().max(8000).optional(), premises: z.array(z.string().max(8000)).max(128).optional(), }).strict()).min(1); export const declarationSubmissionSchema = z.object({ declarations: teamDeclarationListSchema.max(32) }).strict(); diff --git a/src/solver/run.ts b/src/solver/run.ts index e508318f..c5d145a4 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -44,7 +44,7 @@ import { readLibraryCatalog } from './libraryCatalog'; import { readLeanTaskReceipt } from '../math/leanTask'; import { copyContinuationSnapshot, freezeContinuationInput, readContinuationInput, readContinuationSnapshot, type ContinuationSnapshot } from './continuationInput'; -import { seedSingleSolverContinuation } from './singleContinuationSeed'; +import { continuationSourceStateFile, seedSingleSolverContinuation } from './singleContinuationSeed'; import { assertActiveResearchState, legacyCollaborationRetired } from './researchRetirement'; import { verifierFailureDiagnostic } from './verifierFailure'; import { generateSolverExplanations, type SolverExplanations } from './automaticExplanations'; @@ -256,7 +256,7 @@ export async function runSolver(args: string[], root: string, customModules?: So let ownedState: SolverRunState | undefined; let proofEnvironment: Awaited> | undefined; let continuationSeeding = false; - let continuationSourceRun = values['continuation-source-run']; + let continuationSourceRun = values['continuation-source-run'] && continuationSourceStateFile(values['continuation-source-run']); let ownsRun = false; let publishedExit: number | undefined; const emit = (event: string, details = {}) => console.log(JSON.stringify({ event, at: Date.now(), ...details, @@ -402,6 +402,9 @@ export async function runSolver(args: string[], root: string, customModules?: So }; if (values.resume) { state = resumedState!; + if (continuationSourceRun && state.pendingContinuationSource && + continuationSourceRun !== continuationSourceStateFile(state.pendingContinuationSource)) + throw new Error('math_resume_continuation_changed'); continuationSourceRun ??= state.pendingContinuationSource; assertAgentTeamProcessesStopped(state); if (canonicalMathJson(state.agentHarness ?? null) !== canonicalMathJson(agentHarness ?? null)) @@ -461,6 +464,7 @@ export async function runSolver(args: string[], root: string, customModules?: So transport: 'native-agent-control' as const, workers: [], events: [], deliveries: [], adoptions: [], operations: [] } } : {}), ...(continuation ? { continuationDigest: continuation.digest } : {}), + ...(continuationSourceRun ? { pendingContinuationSource: continuationSourceRun } : {}), worktree, phase: 'prepared', turns: 0, dispatchCounts: {}, workerCount: 1, coordination, ...(planApproval ? { planApproval } : {}), moduleConfiguration, tokenBudget: buildTokenBudget(maxTotalTokens, [], westlakeProfile ? 'provider-observed-upstream-request-limit' : undefined) }; @@ -645,6 +649,7 @@ export async function runSolver(args: string[], root: string, customModules?: So return prepareAccess(accessId, workerWorktree, workerProject, workerCorpusFile, prepareSkill(workerWorktree)); }; if (continuationSourceRun) { + state.pendingContinuationSource = continuationSourceRun; save(); continuationSeeding = true; await seedSingleSolverContinuation({ sourceRun: continuationSourceRun, run: stateFile, root, buildManifest: buildFile, signal, lease, preparedEnvironment: env, timeoutMs: maxRunMs === Infinity ? Infinity : Math.max(1, preparationMs - (Date.now() - preparationStarted)), diff --git a/src/solver/singleContinuationSeed.ts b/src/solver/singleContinuationSeed.ts index 4424d96b..4e215bb9 100644 --- a/src/solver/singleContinuationSeed.ts +++ b/src/solver/singleContinuationSeed.ts @@ -12,7 +12,8 @@ import { resolveMathematicsLakePackagesCache } from '../math/verifier'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from './archive'; import { inheritedContinuationText, singleContinuationHistory } from './continuationHistory'; import { readAgentTeamContinuationNote, type AgentTeamResearchArtifactReference, type AgentTeamContinuationOrigin } from './agentTeamResearch'; -import { freezeContinuationInput, MAX_CONTINUATION_ATTACHMENT_BYTES, readContinuationContents, type ContinuationManifest } from './continuationInput'; +import { freezeContinuationInput, MAX_CONTINUATION_ATTACHMENT_BYTES, MAX_CONTINUATION_TOTAL_BYTES, + readContinuationContents, type ContinuationManifest } from './continuationInput'; import { captureContinuationTaskDrafts, continuationOwnershipExtension, continuationSourcePolicyDigest, type ContinuationSeedReport, type ContinuationSeedOptions } from './continuationSeed'; import { createDeclarationArtifactChecker, readDeclarationArtifacts, writeDeclarationArtifacts, type DeclarationArtifact } from './declarationArtifacts'; @@ -39,6 +40,13 @@ const sourceSchema = z.object({ schema: z.literal('theorem-os.single-continuatio }).strict(); type SingleSource = z.infer; type SingleSeedReport = ContinuationSeedReport & { declarationFailures?: { id: string; name: string; error: string }[] }; +const sourceFilename = 'continuation-single-source.json'; +const declarationArchiveId = 'seed-declaration-artifacts'; +type DeclarationArchive = { + schema: 'theorem-os.continuation-declaration-archive.v2'; + artifacts: readonly DeclarationArtifact[]; + sourcesByCommit: Record>; +}; const configurationDigest = (state: SolverRunState) => mathDigest(canonicalMathJson({ runId: state.runId, taskDigest: state.taskDigest, buildDigest: state.buildDigest, environmentDigest: state.environmentDigest, @@ -52,6 +60,26 @@ const textFile = (file: string) => { const notesAt = (worktree: string, commit: string) => git(worktree, ['ls-tree', '--format=%(objectname)', commit, '--', 'RESEARCH.md']) ? committedSource(worktree, commit, 'RESEARCH.md') : null; +function declarationArchive(archived: SolverRunState, artifacts: readonly DeclarationArtifact[]): DeclarationArchive { + const commits = new Set(artifacts.map(artifact => artifact.proof.commit)); + return { schema: 'theorem-os.continuation-declaration-archive.v2', artifacts, + sourcesByCommit: Object.fromEntries([...commits].map(commit => [commit, + Object.fromEntries(archived.problem.ownedFiles.map(file => [file, + committedSource(archived.worktree, commit, `${archived.problem.projectRelative}/${file}`)]))])) }; +} + +function declarationArchiveIndex(text: string, source: SingleSource, sourceDigest: string): string { + const archive = JSON.parse(text) as DeclarationArchive | { artifact: DeclarationArtifact }[]; + // Interrupted legacy captures contain an array with a complete source map for every artifact. + const artifacts = Array.isArray(archive) ? archive.map(entry => entry.artifact) : archive.artifacts; + return canonicalMathJson({ + schema: 'theorem-os.continuation-declaration-archive-index.v1', + capture: { runId: source.destination.runId, file: sourceFilename, sha256: sourceDigest }, + declarations: artifacts.map(({ id, declaration, proof }) => + ({ id, name: declaration.name, file: declaration.file, commit: proof.commit })), + }); +} + function assertPrepared(state: SolverRunState, stateFile: string, seeded: boolean) { if (state.phase !== 'prepared' || state.turns !== 0 || state.solveStartedAt !== undefined || state.solveFinishedAt !== undefined || state.threadId || state.previousThreadIds?.length || state.workers?.length || (state.workerCount ?? 1) !== 1 || @@ -169,10 +197,8 @@ function captureSource(sourceStateFile: string, stateFile: string, state: Solver } const declarations = readDeclarationArtifacts(sourceDirectory, archived); if (declarations.length) { - documents.push({ id: 'seed-declaration-artifacts', kind: 'proof-source', provenance, - text: canonicalMathJson(declarations.map(artifact => ({ artifact, - sources: Object.fromEntries(archived.problem.ownedFiles.map(file => [file, - committedSource(archived.worktree, artifact.proof.commit, `${archived.problem.projectRelative}/${file}`)])) }))) }); + documents.push({ id: declarationArchiveId, kind: 'proof-source', provenance, + text: canonicalMathJson(declarationArchive(archived, declarations)) }); for (const artifact of declarations) { const declaration = artifact.declaration, key = canonicalMathJson([declaration.file, declaration.name, declaration.type]); if (!candidates.has(key)) candidates.set(key, { id: artifact.id, ...declaration }); @@ -188,35 +214,49 @@ function captureSource(sourceStateFile: string, stateFile: string, state: Solver ? declaration : { ...declaration, id: `${declaration.id}-${mathDigest(canonicalMathJson(declaration)).slice(0, 16)}` }) }); } -function freezeSource(source: SingleSource, directory: string) { - let documents = [{ id: 'seed-canonical', kind: 'proof-source' as const, - text: canonicalMathJson({ sources: source.canonicalSources, notes: source.canonicalNotes }), - provenance: { source: source.source.stateFile, runId: source.source.runId, evidence: 'recorded-not-replayed' as const, - commit: source.source.canonicalCommit } }, ...source.documents]; +function bundleDocuments(documents: SingleSource['documents'], source: SingleSource): SingleSource['documents'] { // Repeated migrations can exceed the existing 32-attachment manifest limit. // Keep the primary documents addressable; bundle overflow by kind with exact // text lengths and provenance so no old body needs to be discarded or rewritten. - if (documents.length > 32) { - const compact = documents.slice(0, 8), pending = documents.slice(8); - for (const kind of ['proof-source', 'research-notes', 'diagnostics', 'reference'] as const) { - let text = ''; - const flush = () => { - if (!text) return; - compact.push({ id: `seed-archive-${compact.length + 1}`, kind, text, provenance: { - source: source.source.stateFile, runId: source.source.runId, evidence: 'recorded-not-replayed', - commit: source.source.canonicalCommit } }); text = ''; - }; - for (const document of pending.filter(item => item.kind === kind)) { - const entry = canonicalMathJson({ schema: 'theorem-os.continuation-text-record.v1', id: document.id, - kind: document.kind, provenance: document.provenance, textLength: document.text.length, - textBytes: Buffer.byteLength(document.text), textSha256: mathDigest(document.text) }) + '\n' + document.text + '\n'; - if (Buffer.byteLength(text) + Buffer.byteLength(entry) > MAX_CONTINUATION_ATTACHMENT_BYTES) flush(); - if (Buffer.byteLength(entry) > MAX_CONTINUATION_ATTACHMENT_BYTES) compact.push(document); - else text += entry; - } - flush(); + if (documents.length <= 32) return documents; + const compact = documents.slice(0, 8), pending = documents.slice(8); + for (const kind of ['proof-source', 'research-notes', 'diagnostics', 'reference'] as const) { + let text = ''; + const flush = () => { + if (!text) return; + compact.push({ id: `seed-archive-${compact.length + 1}`, kind, text, provenance: { + source: source.source.stateFile, runId: source.source.runId, evidence: 'recorded-not-replayed', + commit: source.source.canonicalCommit } }); text = ''; + }; + for (const document of pending.filter(item => item.kind === kind)) { + const entry = canonicalMathJson({ schema: 'theorem-os.continuation-text-record.v1', id: document.id, + kind: document.kind, provenance: document.provenance, textLength: document.text.length, + textBytes: Buffer.byteLength(document.text), textSha256: mathDigest(document.text) }) + '\n' + document.text + '\n'; + if (Buffer.byteLength(text) + Buffer.byteLength(entry) > MAX_CONTINUATION_ATTACHMENT_BYTES) flush(); + if (Buffer.byteLength(entry) > MAX_CONTINUATION_ATTACHMENT_BYTES) compact.push(document); + else text += entry; } - documents = compact; + flush(); + } + return compact; +} + +function freezeSource(source: SingleSource, sourceDigest: string, directory: string) { + const draft: SingleSource['documents'] = [{ id: 'seed-canonical', kind: 'proof-source', + text: canonicalMathJson({ sources: source.canonicalSources, notes: source.canonicalNotes }), + provenance: { source: source.source.stateFile, runId: source.source.runId, evidence: 'recorded-not-replayed', + commit: source.source.canonicalCommit } }, ...source.documents]; + const sizes = draft.map(item => Buffer.byteLength(item.text)); + let documents: SingleSource['documents'] | undefined; + if (sizes.every(bytes => bytes <= MAX_CONTINUATION_ATTACHMENT_BYTES) && + sizes.reduce((total, bytes) => total + bytes, 0) <= MAX_CONTINUATION_TOTAL_BYTES) { + documents = bundleDocuments(draft, source); + } + if (!documents || documents.reduce((total, item) => total + Buffer.byteLength(item.text), 0) > MAX_CONTINUATION_TOTAL_BYTES) { + // Keep the full archive in the destination's immutable source capture. It must + // not consume the advisory attachment budget needed by the research notes. + documents = bundleDocuments(draft.map(item => item.id === declarationArchiveId + ? { ...item, text: declarationArchiveIndex(item.text, source, sourceDigest) } : item), source); } const manifest: ContinuationManifest = { schema: 'theorem-os.continuation-snapshot.v1', taskDigest: source.taskDigest, problemReceiptDigest: source.problemReceiptDigest, attachments: documents.map(item => { @@ -228,15 +268,19 @@ function freezeSource(source: SingleSource, directory: string) { contents: new Map(documents.map(item => [mathDigest(item.text), item.text])) }, directory); } +export function continuationSourceStateFile(sourceRun: string): string { + const absolute = path.resolve(sourceRun); + return path.basename(absolute) === 'state.json' ? absolute : `${absolute}.runtime/state.json`; +} + /** Import artifacts into a new idle single run; historical scheduling state is never recreated. */ export async function seedSingleSolverContinuation(options: ContinuationSeedOptions): Promise { const stateFile = readRunInspection(options.run).stateFile, directory = path.dirname(stateFile); - const sourceStateFile = path.basename(path.resolve(options.sourceRun)) === 'state.json' - ? path.resolve(options.sourceRun) : `${path.resolve(options.sourceRun)}.runtime/state.json`; + const sourceStateFile = continuationSourceStateFile(options.sourceRun); assertMathCanonicalPath(sourceStateFile); if (sourceStateFile === stateFile) throw new Error('math_continuation_seed_identity_changed'); const seed = async (lease: MathLease) => { - const state = readSolverRunState(stateFile), sourceFile = path.join(directory, 'continuation-single-source.json'); + const state = readSolverRunState(stateFile), sourceFile = path.join(directory, sourceFilename); const reportFile = path.join(directory, 'continuation-seed.json'), seeded = fs.existsSync(sourceFile); assertPrepared(state, stateFile, seeded); if (!state.researchSkill) throw new Error('math_research_skill_identity_missing'); @@ -267,15 +311,16 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti git(state.worktree, ['status', '--porcelain', '--untracked-files=no']) || actualNotes !== notesAt(state.worktree, head) || !seeded && actualNotes !== null) throw new Error('math_continuation_seed_destination_changed'); + const sourceDigest = mathDigest(canonicalMathJson(source)); lease.assertHeld(); if (!seeded) writeMathJsonDurable(sourceFile, source, 0o400); const report: SingleSeedReport = { schema: 'theorem-os.continuation-seed.v1', sourceRunId: source.source.runId, - runId: state.runId, sourceStateFile, stateFile, sourceDigest: mathDigest(canonicalMathJson(source)), stage: 'frozen', + runId: state.runId, sourceStateFile, stateFile, sourceDigest, stage: 'frozen', candidates: source.declarations.map(item => item.id), checked: [], failed: [], evidence: 'advisory-sources-require-recheck' }; const saveReport = () => { lease.assertHeld(); writeMathJsonDurable(reportFile, report); }; const emit = (event: string, details: Record = {}) => options.onProgress?.(event, details); let proofEnvironment: Awaited> | undefined; try { - const snapshot = freezeSource(source, directory); report.snapshotDigest = snapshot.digest; + const snapshot = freezeSource(source, sourceDigest, directory); report.snapshotDigest = snapshot.digest; if (state.continuationDigest && state.continuationDigest !== snapshot.digest) throw new Error('math_continuation_seed_destination_changed'); saveReport(); const canonical = previous?.canonicalCommit ?? await withSolverWorktree(state.worktree, state.problem.baseCommit, async checkout => { @@ -298,6 +343,10 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti report.sourcesInstalled = true; saveReport(); emit('continuation_seed_installed', { sourceRunId: source.source.runId, runId: state.runId, candidates: source.declarations.length, snapshotDigest: snapshot.digest, researchMode: 'skill', acceptance: 'not-assessed' }); + if (options.deferChecks && source.declarations.length) { + report.stage = 'awaiting-checks'; saveReport(); + options.onSeeded?.(state, []); return report; + } if (source.declarations.length) { const environmentFile = path.join(directory, 'environment-solver.json'); assertMathCanonicalPath(environmentFile); if ((fs.lstatSync(environmentFile).mode & 0o777) !== 0o400) throw new Error('math_continuation_seed_environment_not_frozen'); @@ -358,8 +407,11 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti offset = end; } } - assertPrepared(state, stateFile, true); writeSolverRunState(stateFile, state); - report.stage = 'complete'; saveReport(); options.onSeeded?.(state, []); return report; + assertPrepared(state, stateFile, true); + report.stage = 'complete'; saveReport(); + delete state.pendingContinuationSource; + writeSolverRunState(stateFile, state); + options.onSeeded?.(state, []); return report; } catch (error) { report.stage = 'interrupted'; report.error = error instanceof Error ? error.message : 'math_continuation_seed_failed'; lease.assertOwned(); writeMathJsonDurable(reportFile, report); throw error; diff --git a/src/solver/skillResearchContext.ts b/src/solver/skillResearchContext.ts index 4ad6fbe8..61ae38b8 100644 --- a/src/solver/skillResearchContext.ts +++ b/src/solver/skillResearchContext.ts @@ -79,6 +79,7 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl 'Only if you have at least one locally compiled standalone declaration ready for host checking, write ' + JSON.stringify(path.join(access.worktree, '.scratch/declaration-submission.json')) + ' containing ' + '{"declarations":[{"file":"OWNED_FILE.lean","name":"Qualified.helper","type":"COMPLETE_CLOSED_LEAN_TYPE"}]}, then stop editing and return. ' + + 'For type, you can paste the full Lean #check output. Preserve line breaks and indentation, especially around let and have. ' + 'Never write an empty declarations array. Optional description and premises describe scope. The host verifies each actual declaration and complete type independently. ' + 'Other incomplete goals may remain; a helper that depends on them or on new axioms is rejected. ' + 'The request is consumed after the turn, and its host feedback is saved at .scratch/declaration-feedback.json. ' + diff --git a/tests/codexSessionAgentControl.test.ts b/tests/codexSessionAgentControl.test.ts index a872db8d..a882c2d3 100644 --- a/tests/codexSessionAgentControl.test.ts +++ b/tests/codexSessionAgentControl.test.ts @@ -338,6 +338,35 @@ describe('native AgentControl stdio integration without model calls', () => { expect(record.writerStopUnconfirmed).toBeUndefined(); }); + it('confirms a closed writer while cancelled compaction is still unwinding', async () => { + const reachedRelease = deferred(), shutdownStarted = deferred(), release = deferred(); + session = await createCodexMathSession({ ...options, nativeAgentControl: { request: async (request, _connection, { signal }) => { + if (request.operation === 'releaseTurn' && request.payload.turnId === 'compact-turn') { + signal.addEventListener('abort', () => shutdownStarted.resolve(), { once: true }); + reachedRelease.resolve(); + await release.promise; + } + return { result: { admitted: request.operation === 'admitTurn' } }; + } } }); + const current = session, compact = current.compact!().catch((error: unknown) => error); + await reachedRelease.promise; + const record: { writerStopUnconfirmed?: { at: number; reason: string } } = {}; + const confirmed = vi.fn(); + const freezing = stopProofWriter({ session: current, record, workerId: 'lead', close: () => current.close(), save: () => {}, + deferred: () => {}, confirmed }); + try { + await shutdownStarted.promise; + expect(record.writerStopUnconfirmed?.reason).toBe('turn-not-settled'); + expect(confirmed).not.toHaveBeenCalled(); + } finally { + release.resolve(); + await freezing; + } + expect(confirmed).toHaveBeenCalledWith('turn-not-settled'); + expect(record.writerStopUnconfirmed).toBeUndefined(); + expect(await compact).toBeInstanceOf(Error); + }); + it('waits for the native terminal handoff and guard release before reporting a completed writer', async () => { let release!: () => void, entered!: () => void; const blocked = new Promise(resolve => { release = resolve; }); diff --git a/tests/declarationArtifacts.test.ts b/tests/declarationArtifacts.test.ts index a6611b8b..f7a0e6e4 100644 --- a/tests/declarationArtifacts.test.ts +++ b/tests/declarationArtifacts.test.ts @@ -467,6 +467,16 @@ describe('independent declaration checks with the real verifier and Lean', () => 'Artifact.reusable.{u} {α : Type} (x : α) : x = x', false, '', /different type or additional assumptions/u], ['declaration header with a line comment', 'theorem reusable (n : Nat) : n = n := by rfl\n', '(n : Nat) -- parameter\n : n = n', true, ''], + ['pasted signature with an indented let', 'theorem reusable :\n let k := 1\n k = 1 := by rfl\n', + 'Artifact.reusable :\n let k := 1\n k = 1', true, ''], + ['closed type with an indented let', 'theorem reusable :\n let k := 1\n k = 1 := by rfl\n', + ' let k := 1\n k = 1', true, ''], + ['closed type with lost indentation', 'theorem reusable :\n let k := 1\n k = 1 := by rfl\n', + 'let k := 1\n k = 1', false, '', /Invalid expected declaration type/u], + ['multiline signature with binders and a local let', 'theorem reusable (n : Nat)\n (m : Nat) :\n let k :=\n n + m\n k = n + m := by rfl\n', + 'Artifact.reusable (n : Nat)\n (m : Nat) :\n let k :=\n n + m\n k = n + m', true, ''], + ['different conclusion in an indented signature', 'theorem reusable :\n let k := 1\n k = 1 := by rfl\n', + 'Artifact.reusable :\n let k := 1\n k = 2', false, '', /different type or additional assumptions/u], ['long closed type', 'theorem reusable (n : Nat) : n = n := by rfl\n', '∀ n : Nat, /-' + 'a'.repeat(12_500) + '-/ n = n', true, ''], ['wrong pasted signature', 'theorem reusable (n : Nat) : n = n := by rfl\n', diff --git a/tests/leanTask.test.ts b/tests/leanTask.test.ts index 4d5ca47e..b2282b6e 100644 --- a/tests/leanTask.test.ts +++ b/tests/leanTask.test.ts @@ -5,7 +5,7 @@ import { spawnSync } from 'node:child_process'; import { afterEach, describe, expect, it } from 'vitest'; import { bootstrapLeanTask, readLeanTaskReceipt, LEAN_TASK_DECLARATIONS_MAX, LEAN_TASK_SOURCE_MAX_BYTES } from '../src/math/leanTask'; import { LOCAL_EXAMPLE_TOOLCHAIN } from '../src/math/localExample'; -import { getLeanTaskEnvironment, type LeanTaskEnvironment } from '../src/math/leanTaskEnvironment'; +import { getLeanTaskEnvironment, recordedLeanTaskEnvironment, type LeanTaskEnvironment } from '../src/math/leanTaskEnvironment'; import { canonicalMathProblemStatementPayloads } from '../src/math/contracts'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { LIBRARY_PACK_SCHEMA, libraryPackDigest, parseLibraryPack } from '../src/math/libraryPacks'; @@ -336,6 +336,23 @@ end User expect(() => readLeanTaskReceipt(receipt.activeProblemPath)).toThrow('lean_task_protected_file_changed:lake-manifest.json'); }); + it('reads a frozen Mathlib 4.33 receipt using its original dependency bytes', () => { + const { receipt } = fixture('mathlib'); + const environment = recordedLeanTaskEnvironment('mathlib', 'c3ba186edb3024032ca0d87fa85b0eaa4f62c5d71588936132acebc12625c7db')!; + for (const [file, bytes] of Object.entries(environment.files)) fs.writeFileSync(path.join(receipt.projectRoot, file), bytes); + const message = 'TheoremOS Lean task seed\n\n' + canonicalMathJson({ schema: 'theorem-os.lean-task-seed.v1', + sourceHash: mathDigest(source), task, environment: environment.id, environmentDigest: environment.dependencyDigest }); + git(receipt.workspaceRoot, ['add', '--', 'generated']); + git(receipt.workspaceRoot, ['-c', 'user.name=Test', '-c', 'user.email=test@localhost', + 'commit', '--amend', '--no-gpg-sign', '--quiet', '--cleanup=verbatim', '-m', message]); + const historical = { ...receipt, environmentDigest: environment.dependencyDigest, toolchain: environment.toolchain, + baseCommit: git(receipt.workspaceRoot, ['rev-parse', 'HEAD']) }; + saveReceipt(receipt, historical); + expect(readLeanTaskReceipt(receipt.activeProblemPath)).toEqual(historical); + fs.writeFileSync(path.join(receipt.projectRoot, 'lake-manifest.json'), getLeanTaskEnvironment('mathlib').files['lake-manifest.json']!); + expect(() => readLeanTaskReceipt(receipt.activeProblemPath)).toThrow('lean_task_protected_file_changed:lake-manifest.json'); + }); + it('keeps legacy standard-library receipts verifiable against their original seed bytes', () => { const { receipt } = fixture(); const message = 'TheoremOS Lean task seed\n\n' + JSON.stringify({ schema: 'theorem-os.lean-task-seed.v1', diff --git a/tests/singleContinuationSeed.test.ts b/tests/singleContinuationSeed.test.ts index 98c2b58b..c2c62701 100644 --- a/tests/singleContinuationSeed.test.ts +++ b/tests/singleContinuationSeed.test.ts @@ -8,8 +8,9 @@ import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { saveAgentTeamResearchArtifact } from '../src/solver/agentTeamResearch'; import { searchContinuation } from '../src/solver/continuationSearch'; import { seedSingleSolverContinuation } from '../src/solver/singleContinuationSeed'; -import { freezeContinuationInput, readContinuationContents, readContinuationPage, type ContinuationManifest } from '../src/solver/continuationInput'; -import { readDeclarationArtifacts } from '../src/solver/declarationArtifacts'; +import { freezeContinuationInput, MAX_CONTINUATION_ATTACHMENT_BYTES, readContinuationContents, readContinuationPage, + type ContinuationManifest } from '../src/solver/continuationInput'; +import { createDeclarationArtifactChecker, readDeclarationArtifacts } from '../src/solver/declarationArtifacts'; import { committedSource, commitSolverSources, git } from '../src/solver/problem'; import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; import { withVerificationCheckpoints } from '../src/solver/verificationCheckpoint'; @@ -198,17 +199,83 @@ describe('single researcher continuation', () => { it('retries an interrupted zero-turn import from the frozen capture even if the old run has changed', async () => { const f = fixture(); addHistoricalHelper(f, 'other_helper'); + f.state.pendingContinuationSource = f.sourceStateFile; + writeSolverRunState(f.stateFile, f.state); + const deferred = await seedSingleSolverContinuation({ ...f.options, deferChecks: true }); + expect(deferred).toMatchObject({ stage: 'awaiting-checks', candidates: ['other_helper', 'saved'], checked: [], + sourcesInstalled: true, evidence: 'advisory-sources-require-recheck' }); + expect(host.verify).not.toHaveBeenCalled(); + expect(readSolverRunState(f.stateFile)).toMatchObject({ continuationDigest: deferred.snapshotDigest, + pendingContinuationSource: f.sourceStateFile }); host.verify.mockRejectedValueOnce(new Error('fixture_interrupted_check')); await expect(f.seed()).rejects.toThrow('fixture_interrupted_check'); expect(host.verify).toHaveBeenCalledOnce(); + expect(readSolverRunState(f.stateFile).pendingContinuationSource).toBe(f.sourceStateFile); const frozen = fs.readFileSync(path.join(f.directory, 'continuation-single-source.json')); fs.appendFileSync(path.join(f.sourceWorktree, 'RESEARCH.md'), 'New old-run activity after capture'); f.archived.turns += 1; writeSolverRunState(f.sourceStateFile, f.archived); expect(await f.seed()).toMatchObject({ stage: 'complete', checked: ['other_helper', 'saved'] }); + expect(readSolverRunState(f.stateFile).pendingContinuationSource).toBeUndefined(); expect(fs.readFileSync(path.join(f.directory, 'continuation-single-source.json'))).toEqual(frozen); expect(fs.readFileSync(path.join(f.worktree, 'RESEARCH.md'), 'utf8')).toBe(f.canonicalNotes); }); + it('stores shared declaration source bytes once and resumes a legacy oversized capture from its frozen bytes', async () => { + const f = fixture(); + const key = 'Submission.lean', file = path.join(f.sourceWorktree, f.problem.projectRelative, key); + const name = 'Tutorial.saved_helper', source = f.sources + '\n/- ' + 'archive-source\n'.repeat(75_000) + '-/\n'; + fs.writeFileSync(file, source); + const commit = commitSolverSources(f.problem, f.sourceWorktree); + f.archived.cooperation!.canonicalCommit = commit; + writeSolverRunState(f.sourceStateFile, f.archived); + const check = createDeclarationArtifactChecker({ state: f.archived, worktree: f.sourceWorktree, commit, + env: f.options.preparedEnvironment, signal: f.options.signal, assertWriterStopped: () => {} }); + const [first] = await check([{ file: key, name, type: 'True' }]); + const { id: _id, ...receipt } = first!; + const artifacts = Array.from({ length: 17 }, (_, i) => { + const record = { ...receipt, declaration: { ...receipt.declaration, description: `Recorded note ${i}` } }; + return { ...record, id: mathDigest(canonicalMathJson(record)) }; + }); + const declarationFile = path.join(f.oldDirectory, 'declarations.json'); + fs.writeFileSync(declarationFile, canonicalMathJson({ schema: 'theorem-os.declaration-artifacts.v1', + runId: f.archived.runId, problemReceiptDigest: f.problem.receiptDigest, + environmentDigest: f.archived.environmentDigest, artifacts })); + const frozenFile = path.join(f.directory, 'continuation-single-source.json'); + const snapshotFile = path.join(f.directory, 'continuation.json'), archiveId = 'seed-declaration-artifacts'; + const fresh = await f.seed(); + expect(fresh).toMatchObject({ stage: 'complete', checked: ['saved'] }); + const frozen = JSON.parse(fs.readFileSync(frozenFile, 'utf8')); + const archive = frozen.documents.find((item: { id: string }) => item.id === archiveId)!; + expect(JSON.parse(archive.text)).toEqual({ schema: 'theorem-os.continuation-declaration-archive.v2', + artifacts, sourcesByCommit: { [commit]: { [key]: source } } }); + const firstSnapshot = readContinuationContents(snapshotFile, fresh.snapshotDigest!); + expect(firstSnapshot.contents.get(firstSnapshot.snapshot.manifest.attachments.find(item => item.id === archiveId)!.sha256)) + .toBe(archive.text); + + // Recreate a legacy failure after the source capture was written and before any destination install. + git(f.worktree, ['reset', '--hard', f.problem.baseCommit]); writeSolverRunState(f.stateFile, f.state); + for (const entry of ['continuation.json', 'continuation-seed.json', 'declarations.json']) + fs.unlinkSync(path.join(f.directory, entry)); + archive.text = canonicalMathJson(artifacts.map(artifact => ({ artifact, sources: { [key]: source } }))); + expect(Buffer.byteLength(archive.text)).toBeGreaterThan(MAX_CONTINUATION_ATTACHMENT_BYTES); + const legacy = canonicalMathJson(frozen), sourceDigest = mathDigest(legacy); + fs.unlinkSync(frozenFile); fs.writeFileSync(frozenFile, legacy, { mode: 0o400 }); + fs.unlinkSync(declarationFile); + fs.writeFileSync(file, '-- the source has changed since capture\n'); + host.verify.mockClear(); + const retried = await f.seed(); + expect(retried).toMatchObject({ stage: 'complete', sourceDigest, checked: ['saved'] }); + expect(host.verify).toHaveBeenCalledOnce(); + expect(mathDigest(fs.readFileSync(frozenFile))).toBe(sourceDigest); + expect(fs.readFileSync(path.join(f.worktree, f.problem.projectRelative, key), 'utf8')).toBe(source); + const index = JSON.parse(readContinuationPage(snapshotFile, retried.snapshotDigest!, archiveId).text); + expect(index).toEqual({ schema: 'theorem-os.continuation-declaration-archive-index.v1', + capture: { runId: f.state.runId, file: 'continuation-single-source.json', sha256: sourceDigest }, + declarations: artifacts.map(({ id }) => ({ id, name, file: key, commit })) }); + const repeated = await f.seed(); + expect(repeated).toMatchObject({ snapshotDigest: retried.snapshotDigest, sourceDigest, checked: ['saved'] }); + }, 30_000); + it('rejects changed destination source and started research instead of overwriting it', async () => { const f = fixture(); await f.seed(); const target = path.join(f.worktree, f.problem.projectRelative, 'Submission.lean'); fs.appendFileSync(target, '\n-- new work\n');