From b4124ed186715a6017e7e03cfabf37dd4dc43de3 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Sat, 28 Nov 2026 14:08:44 +0800 Subject: [PATCH] Batch Lean checks for team handoffs and continuation --- src/solver/declarationArtifacts.ts | 139 ++++++++++++++++++--------- src/solver/singleContinuationSeed.ts | 31 ++++-- src/solver/taskProjection.ts | 10 +- tests/agentTeamProof.test.ts | 30 +++++- tests/singleContinuationSeed.test.ts | 57 +++++++---- tests/taskSourceProjection.test.ts | 19 ++++ 6 files changed, 212 insertions(+), 74 deletions(-) diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index c8d9e42b..0e89dcf5 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -11,7 +11,7 @@ import { createTaskSourceProjector, ownedSourceDigest } from './cooperativeProof import { checkProjectedDeclarations, type ProofCheck } from './modules/evidence'; import { assertSolverSources, commitSolverProjection, git, withSolverWorktree } from './problem'; import { captureProofReferences, type ProofReferences } from './proofReferences'; -import { proofReuseEnvironment } from './proofReuse'; +import { hasDeterministicLeanFailure, hasLeanResourceLimitFailure, proofReuseEnvironment } from './proofReuse'; import { allowedKnowledgeFile, locateKnowledgeDeclaration } from './theoremKnowledge'; import type { CooperativeTask } from './tasks'; @@ -263,7 +263,7 @@ export async function checkDeclarationArtifacts(input: StoppedDeclarationCheckIn return createDeclarationArtifactChecker(input)(input.declarations); } -/** Reuse source preparation for sequential checks of one stopped writer's fixed commit. */ +/** Reuse source preparation across checks of one stopped writer's fixed commit. */ export function createDeclarationArtifactChecker(input: Omit) { const { state, worktree, commit, signal } = input, { problem } = state; const identity = canonicalMathJson(identityOf(state)); @@ -274,8 +274,18 @@ export function createDeclarationArtifactChecker(input: Omit path.join(problem.projectRelative, file))])) return fail('source_changed'); }; - return (declarations: DeclarationSubmission['declarations']) => - checkArtifacts({ ...input, declarations, assertFrozenSource }, declarationSubmissionSchema, false, snapshot); + const check = (declarations: DeclarationSubmission['declarations'], batchOnly = false) => + checkArtifacts({ ...input, declarations, assertFrozenSource }, declarationSubmissionSchema, false, snapshot, batchOnly); + return Object.assign((declarations: DeclarationSubmission['declarations']) => check(declarations), { + /** The continuation importer handles each candidate separately when a batch cannot be checked. */ + async tryBatch(declarations: DeclarationSubmission['declarations']) { + try { return await check(declarations, true); } + catch (error) { + if (error instanceof DeclarationSubmissionError) return []; + throw error; + } + }, + }); } /** Host deliveries can include checked peer declarations in addition to a bounded member submission. */ @@ -284,72 +294,111 @@ export async function checkTeamDeclarationArtifacts(input: TeamDeclarationCheckI } async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof declarationSubmissionSchema, - allowAuxiliaryDefinitions: boolean, snapshot: DeclarationCheckSnapshot = {}) { + allowAuxiliaryDefinitions: boolean, snapshot: DeclarationCheckSnapshot = {}, batchOnly = false) { const declarations = parseDeclarationSubmission({ declarations: input.declarations }, schema).declarations; const { state, worktree, commit, signal, assertFrozenSource } = input, { problem } = state; commitHash.parse(commit); assertFrozenSource(); if (new Set(declarations.map(item => `${item.file}\0${item.name}`)).size !== declarations.length) return submissionFail('duplicate_declaration'); const environment = proofReuseEnvironment(path.join(worktree, problem.projectRelative), input.env); - const records: DeclarationArtifact[] = []; - for (const declaration of declarations) { + const check = async (group: DeclarationSubmission['declarations']) => { + const first = group[0]!, batched = group.length > 1; assertFrozenSource(); - if (!problem.ownedFiles.includes(declaration.file)) return submissionFail('outside_ownership'); + if (!problem.ownedFiles.includes(first.file)) return submissionFail('outside_ownership'); const checked = await withSolverWorktree(worktree, commit, async checkout => { - const source = fs.readFileSync(path.join(checkout, problem.projectRelative, declaration.file), 'utf8'); - const location = submissionContent(() => locateKnowledgeDeclaration(source, declaration.name), - ['math_knowledge_declaration_missing_or_ambiguous']); - const definition = declaration.kind === 'definition'; - if (definition) { - if (!allowAuxiliaryDefinitions) return submissionFail('requires_theorem'); - if (location.kind !== 'definition' || !/^(?:def|abbrev)\s/u.test(source.slice(location.startOffset, location.bodyOffset))) - return submissionFail('requires_definition'); - } else if (location.kind !== 'theorem') return submissionFail('requires_theorem'); - const declarationHash = mathDigest(location.declarationType); - const declarationDigest = declarationIdentity(declaration, declarationHash); - const original = problem.targets.some(target => target.proofPath === declaration.file && target.theoremName === declaration.name); - if (definition && original) return submissionFail('definition_must_be_auxiliary'); - // A transient projection request reuses source isolation, not cooperation state or scheduling. - const checkHelperInDraft = input.inferredExpectedTypes?.has(declaration.file + '\0' + declaration.name) === true; - const type = checkHelperInDraft ? undefined : declaration.type; - const task: CooperativeTask = { id: `declaration-${declarationDigest}`, kind: original ? 'goal' : 'lemma', - ...(definition && { declaration: 'definition' }), objective: declaration.description || `Check ${declaration.name}`, proofPath: declaration.file, - theoremName: declaration.name, type, dependsOn: [], revision: 0 }; + const projectRoot = path.join(checkout, problem.projectRelative); + const source = fs.readFileSync(path.join(projectRoot, first.file), 'utf8'); + const prepared = group.map(declaration => { + const location = submissionContent(() => locateKnowledgeDeclaration(source, declaration.name), + ['math_knowledge_declaration_missing_or_ambiguous']); + const definition = declaration.kind === 'definition'; + if (definition) { + if (!allowAuxiliaryDefinitions) return submissionFail('requires_theorem'); + if (location.kind !== 'definition' || !/^(?:def|abbrev)\s/u.test(source.slice(location.startOffset, location.bodyOffset))) + return submissionFail('requires_definition'); + } else if (location.kind !== 'theorem') return submissionFail('requires_theorem'); + const declarationHash = mathDigest(location.declarationType); + const declarationDigest = declarationIdentity(declaration, declarationHash); + const original = problem.targets.some(target => target.proofPath === declaration.file && target.theoremName === declaration.name); + if (definition && original) return submissionFail('definition_must_be_auxiliary'); + // A transient projection request reuses source isolation, not cooperation state or scheduling. + const checkHelperInDraft = input.inferredExpectedTypes?.has(declaration.file + '\0' + declaration.name) === true; + const type = checkHelperInDraft ? undefined : declaration.type; + const task: CooperativeTask = { id: `declaration-${declarationDigest}`, kind: original ? 'goal' : 'lemma', + ...(definition && { declaration: 'definition' }), objective: declaration.description || `Check ${declaration.name}`, proofPath: declaration.file, + theoremName: declaration.name, type, dependsOn: [], revision: 0 }; + return { declaration, declarationHash, declarationDigest, task, checkHelperInDraft }; + }); + const { checkHelperInDraft, task } = prepared[0]!; let checkedCommit = commit; if (!checkHelperInDraft) { - const projector = snapshot.project ??= createTaskSourceProjector(problem, worktree, commit, { compact: true }); - const sources = submissionContent(() => projector(task, []), ['math_task_type_invalid', 'math_task_missing_declaration', + const projector = batched ? createTaskSourceProjector(problem, worktree, commit) + : snapshot.project ??= createTaskSourceProjector(problem, worktree, commit, { compact: true }); + const project = (target: CooperativeTask) => submissionContent(() => projector(target, []), + ['math_task_type_invalid', 'math_task_missing_declaration', 'math_task_ambiguous_declaration', 'math_task_requires_theorem', 'math_task_requires_definition', 'math_task_helper_is_original_declaration']); - for (const [file, text] of sources) fs.writeFileSync(path.join(checkout, problem.projectRelative, file), text); - checkedCommit = commitSolverProjection(problem, checkout, `Check declaration ${declaration.name}`); + const sources = project(task); + // Full projections retain shared helpers. Only combine targets whose isolated inputs match. + for (const item of prepared.slice(1)) { + const other = project(item.task); + if (sources.size !== other.size || [...sources].some(([file, text]) => other.get(file) !== text)) return; + } + for (const [file, text] of sources) fs.writeFileSync(path.join(projectRoot, file), text); + checkedCommit = commitSolverProjection(problem, checkout, batched ? 'Check declarations' : `Check declaration ${first.name}`); } const result = await checkProjectedDeclarations(problem, checkout, worktree, checkedCommit, - [{ proofPath: declaration.file, theoremName: declaration.name, digest: declarationDigest, - missingError: 'math_declaration_artifact_declaration_missing' }], + prepared.map(({ declaration, declarationDigest }) => ({ proofPath: declaration.file, theoremName: declaration.name, + digest: declarationDigest, missingError: 'math_declaration_artifact_declaration_missing' })), { env: environment.env, signal, timeoutMs: input.timeoutMs ?? Infinity, - expectedDeclarationType: type, prepareLocalDependencies: checkHelperInDraft || problem.kind === 'lean-eval', + ...(batched ? { expectedDeclarationTypes: Object.fromEntries(prepared.map(({ task }) => [task.theoremName!, task.type!])) } + : { expectedDeclarationType: task.type }), + prepareLocalDependencies: checkHelperInDraft || problem.kind === 'lean-eval', ...(checkHelperInDraft ? { checkDeclarationsInDraft: true } : {}), collectDeclarationReferences: true }).catch(error => { if (error instanceof Error && error.message === 'math_declaration_artifact_declaration_missing') throw new DeclarationSubmissionError(error.message, { cause: error }); throw error; }); - if (!result.passed) throw new DeclarationArtifactCheckError(declaration, result.verification); - const references = result.verification.results[0]?.declarationReferences; - const record: DeclarationArtifact = { schema: 'theorem-os.declaration-artifact.v1', id: '', ...identityOf(state), - declaration, declarationHash, declarationDigest, - proof: { commit, sourceDigest: snapshot.sourceDigest ??= ownedSourceDigest(problem, worktree, commit), - passed: true, verification: result.verification }, - ...(references ? { references: captureProofReferences(problem, checkout, commit, - { file: declaration.file, name: declaration.name }, references, state.environmentDigest) } : {}) }; - return { ...record, id: artifactId(record) }; + if (!result.passed) { + if (!batched) throw new DeclarationArtifactCheckError(first, result.verification); + const index = result.attributions.findIndex(item => !item.passed); + const failure = result.attributions[index]!; + // A shared file can fail because of an unrelated draft declaration. Retry in isolation + // and keep the per-declaration diagnostic. Operational failures still stop the check. + if (failure.verification.status === 'failed' && (hasDeterministicLeanFailure(result.verification) || + hasLeanResourceLimitFailure(result.verification))) return; + throw new DeclarationArtifactCheckError(group[index]!, failure.verification); + } + const sourceDigest = snapshot.sourceDigest ??= ownedSourceDigest(problem, worktree, commit); + return prepared.map(({ declaration, declarationHash, declarationDigest }, index): DeclarationArtifact => { + const verification = batched ? result.attributions[index]!.verification : result.verification; + const references = verification.results[0]?.declarationReferences; + const record: DeclarationArtifact = { schema: 'theorem-os.declaration-artifact.v1', id: '', ...identityOf(state), + declaration, declarationHash, declarationDigest, proof: { commit, sourceDigest, passed: true, verification }, + ...(references ? { references: captureProofReferences(problem, checkout, commit, + { file: declaration.file, name: declaration.name }, references, state.environmentDigest) } : {}) }; + return { ...record, id: artifactId(record) }; + }); }); assertFrozenSource(); const after = proofReuseEnvironment(path.join(worktree, problem.projectRelative), input.env); if (canonicalMathJson({ reusable: after.reusable, digest: after.digest, env: after.env }) !== canonicalMathJson({ reusable: environment.reusable, digest: environment.digest, env: environment.env })) return fail('environment_changed'); - validateDeclarationArtifact(checked); - fresh.set(checked, checked.id); records.push(checked); + for (const artifact of checked ?? []) { + validateDeclarationArtifact(artifact); + fresh.set(artifact, artifact.id); + } + return checked; + }; + // The verifier accepts at most 64 targets. Keep single-declaration and inferred-type checks + // on their existing path, including when an older team delivery exceeds the batch bound. + if ((allowAuxiliaryDefinitions || batchOnly) && declarations.length > 1 && declarations.length <= 64 && + declarations.every(({ file, name }) => file === declarations[0]!.file && !input.inferredExpectedTypes?.has(file + '\0' + name))) { + const checked = await check(declarations); + if (checked) return checked; } + if (batchOnly) return []; + const records: DeclarationArtifact[] = []; + for (const declaration of declarations) records.push(...(await check([declaration]))!); return records; } diff --git a/src/solver/singleContinuationSeed.ts b/src/solver/singleContinuationSeed.ts index a0856a22..4424d96b 100644 --- a/src/solver/singleContinuationSeed.ts +++ b/src/solver/singleContinuationSeed.ts @@ -15,7 +15,7 @@ import { readAgentTeamContinuationNote, type AgentTeamResearchArtifactReference, import { freezeContinuationInput, MAX_CONTINUATION_ATTACHMENT_BYTES, readContinuationContents, type ContinuationManifest } from './continuationInput'; import { captureContinuationTaskDrafts, continuationOwnershipExtension, continuationSourcePolicyDigest, type ContinuationSeedReport, type ContinuationSeedOptions } from './continuationSeed'; -import { createDeclarationArtifactChecker, readDeclarationArtifacts, writeDeclarationArtifacts } from './declarationArtifacts'; +import { createDeclarationArtifactChecker, readDeclarationArtifacts, writeDeclarationArtifacts, type DeclarationArtifact } from './declarationArtifacts'; import { readRunInspection } from './inspection'; import { assertSolverSources, committedSource, commitSolverSources, git, pinSolverResearchSkill, readSolverProblem, withSolverWorktree } from './problem'; import { isDefinitionTask, type TaskRecord } from './tasks'; @@ -319,14 +319,19 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti const assertWriterStopped = () => { lease.assertHeld(); assertPrepared(state, stateFile, true); }; const checkDeclarations = createDeclarationArtifactChecker({ state, worktree: state.worktree, commit: canonical, env, signal: lease.signal, timeoutMs, assertWriterStopped }); - for (const declaration of source.declarations) { + const publish = (declarations: SingleSource['declarations'], artifacts: readonly DeclarationArtifact[]) => { + assertWriterStopped(); writeDeclarationArtifacts(directory, state, artifacts); + report.evidence = 'fresh-helper-receipts'; + for (const { id, name } of declarations) { + report.checked.push(id); + emit('continuation_seed_declaration_checked', { id, name, passed: true }); + } + }; + const checkOne = async (declaration: SingleSource['declarations'][number]) => { lease.signal.throwIfAborted(); const { id, ...submission } = declaration; try { - const artifacts = await checkDeclarations([submission]); - assertWriterStopped(); writeDeclarationArtifacts(directory, state, artifacts); - report.checked.push(id); report.evidence = 'fresh-helper-receipts'; - emit('continuation_seed_declaration_checked', { id, name: declaration.name, passed: true }); + publish([declaration], await checkDeclarations([submission])); } catch (error) { const message = error instanceof Error ? error.message : ''; if (!message.startsWith('math_declaration_artifact_check_failed:') && @@ -337,6 +342,20 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti emit('continuation_seed_declaration_checked', { id, name: declaration.name, passed: false, error: message }); } saveReport(); + }; + for (let offset = 0; offset < source.declarations.length;) { + const file = source.declarations[offset]!.file; + let end = offset + 1; + while (end < offset + 32 && source.declarations[end]?.file === file) end++; + const batch = source.declarations.slice(offset, end); + const artifacts = batch.length > 1 ? await checkDeclarations.tryBatch(batch.map(({ id: _id, ...submission }) => submission)) : []; + if (artifacts.length) { + publish(batch, artifacts); + saveReport(); + } else { + for (const declaration of batch) await checkOne(declaration); + } + offset = end; } } assertPrepared(state, stateFile, true); writeSolverRunState(stateFile, state); diff --git a/src/solver/taskProjection.ts b/src/solver/taskProjection.ts index 3ca356cf..e39da76d 100644 --- a/src/solver/taskProjection.ts +++ b/src/solver/taskProjection.ts @@ -42,8 +42,14 @@ export function compactTaskSources(problem: SolverProblem, sources: ReadonlyMap< const retain = (id: string) => { if (!keep.has(id)) { keep.add(id); pending.push(id); } }; const references = (text: string) => { // Strings are intentionally scanned too: tactics can look up quoted declaration names. - for (const token of identifiers(text)) for (const name of new Set([token, leaf(token)])) - for (const id of names.get(name) ?? []) retain(id); + for (const token of identifiers(text)) { + // A dotted name can use a declaration prefix as its receiver, as in lemma.mpr. + for (let end = token.length; end > 0; end = token.lastIndexOf('.', end - 1)) { + const prefix = token.slice(0, end); + for (const name of new Set([prefix, leaf(prefix)])) + for (const id of names.get(name) ?? []) retain(id); + } + } }; for (const file of files) { let cursor = 0; diff --git a/tests/agentTeamProof.test.ts b/tests/agentTeamProof.test.ts index a5db0068..92ff20b1 100644 --- a/tests/agentTeamProof.test.ts +++ b/tests/agentTeamProof.test.ts @@ -133,6 +133,14 @@ describe('agent-owned declaration deliveries with real Lean', () => { worktree: consumer.worktree, expectedCommit: consumer.commit }); expect(adoption.artifacts.map(a => [a.declaration.kind, a.proof.commit, a.proof.verification.status])) .toEqual(declarations.map(() => ['definition', adoption.commit, 'kernel_verified'])); + const delivered = delivery.artifacts.map(a => a.proof.verification); + const adopted = adoption.artifacts.map(a => a.proof.verification); + for (const batch of [delivered, adopted]) { + expect(new Set(batch.map(v => v.sessionId)).size).toBe(1); + expect(batch.map(v => v.results.map(r => r.theoremName))).toEqual(declarations.map(d => [d.name])); + expect(new Set(batch.map(v => v.results[0]!.receiptId)).size).toBe(2); + } + expect(delivered[0]!.sessionId).not.toBe(adopted[0]!.sessionId); const merged = fs.readFileSync(f.source(consumer.worktree), 'utf8'); expect(merged).toContain(def); expect(merged.match(/by sorry/gu)).toHaveLength(2); expect(f.state.check).toBeUndefined(); @@ -142,6 +150,21 @@ describe('agent-owned declaration deliveries with real Lean', () => { expect(later.artifacts.at(-1)!.proof.verification.status).toBe('kernel_verified'); }, 90_000); + it('adopts two checked helpers even when an unrelated consumer draft fails to elaborate', async () => { + const f = fixture(peerHelper + 'theorem second : True := by trivial\n'); + const declarations = [...f.check.declarations, { file: 'Submission.lean', name: 'Team.second', type: 'True' }]; + const delivery = await checkAgentTeamProofDelivery({ ...f.check, declarations }); + const draft = 'theorem unresolved : True := by exact missing_proof\n'; + const consumer = consumerWithDraft(f, 'theorem established : True := by trivial\n' + draft); + const verify = vi.spyOn(evidence, 'checkProjectedDeclarations'); + const adoption = await integrateAgentTeamProofDelivery({ ...f.common, delivery, + worktree: consumer.worktree, expectedCommit: consumer.commit }); + expect(verify.mock.calls.map(([, , , , targets]) => targets.map(target => target.theoremName))) + .toEqual([['Team.reusable', 'Team.second'], ['Team.reusable'], ['Team.second']]); + expect(adoption.artifacts.map(a => a.proof.verification.status)).toEqual(['kernel_verified', 'kernel_verified']); + expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toContain(draft); + }, 90_000); + it('refuses incorrect types, incomplete bodies and replacement of an existing definition', async () => { const body = 'def encode (n : Nat) : Nat := n + 1\n', f = fixture(body); const decl = { file: 'Submission.lean', name: 'Team.encode', type: 'Nat → Nat', kind: 'definition' as const }; @@ -437,10 +460,11 @@ describe('agent-owned declaration deliveries with real Lean', () => { const f = fixture('theorem reusable (n : Nat) : n = n := by exact False.elim (by trivial)\n'); await expect(checkAgentTeamProofDelivery(f.check)).rejects.toThrow('math_declaration_artifact_check_failed'); expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - fs.writeFileSync(f.source(f.worktree), original.replace('end Team', - 'theorem reusable (n : Nat) : n = n := by rfl\nend Team')); + fs.writeFileSync(f.source(f.worktree), original.replace('end Team', peerHelper + + 'theorem second : True := by trivial\nend Team')); await expect(checkAgentTeamProofDelivery({ ...f.check, - declarations: [{ ...f.check.declarations[0]!, type: 'False' }] })).rejects.toThrow('math_declaration_artifact_check_failed'); + declarations: [...f.check.declarations, { file: 'Submission.lean', name: 'Team.second', type: 'False' }] })) + .rejects.toThrow('math_declaration_artifact_check_failed:Team.second'); expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); expect(fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8')).toBe(original); }, 90_000); diff --git a/tests/singleContinuationSeed.test.ts b/tests/singleContinuationSeed.test.ts index 92e2b02d..ee71f559 100644 --- a/tests/singleContinuationSeed.test.ts +++ b/tests/singleContinuationSeed.test.ts @@ -84,6 +84,20 @@ beforeEach(() => { }); afterEach(() => { vi.restoreAllMocks(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); +function addHistoricalHelper(f: ReturnType, name: string, type = 'True') { + const file = path.join(f.sourceWorktree, f.problem.projectRelative, 'Submission.lean'); + const source = f.sources.replace('lemma saved_helper', `lemma ${name} : True := by trivial\nlemma saved_helper`); + fs.writeFileSync(file, source); + const commit = commitSolverSources(f.problem, f.sourceWorktree); + const cooperation = f.archived.cooperation!; + cooperation.canonicalCommit = commit; + const helper = { ...f.helper, id: name, theoremName: `Tutorial.${name}`, type }; + cooperation.tasks.unshift({ ...cooperation.tasks[0]!, task: helper, + integratedCheck: { ...cooperation.tasks[0]!.integratedCheck!, commit, taskDigest: taskVersion(helper) } }); + writeSolverRunState(f.sourceStateFile, f.archived); + return source; +} + describe('single researcher continuation', () => { it('imports canonical bytes, records drafts and costs, and independently checks helpers without restoring a task graph', async () => { const f = fixture(), oldState = fs.readFileSync(f.sourceStateFile), oldNotes = fs.readFileSync(path.join(f.peer, 'RESEARCH.md')); @@ -106,28 +120,33 @@ describe('single researcher continuation', () => { expect(fs.readFileSync(path.join(f.peer, 'RESEARCH.md'))).toEqual(oldNotes); }); + it('checks two historical helpers in one session and publishes independent receipts', async () => { + const f = fixture(); + addHistoricalHelper(f, 'other_helper'); + expect(await f.seed()).toMatchObject({ stage: 'complete', checked: ['other_helper', 'saved'], failed: [] }); + expect(host.verify).toHaveBeenCalledOnce(); + expect(host.verify.mock.calls[0]![1].expectedDeclarationTypes) + .toEqual({ 'Tutorial.other_helper': 'True', 'Tutorial.saved_helper': 'True' }); + const artifacts = readDeclarationArtifacts(f.directory, readSolverRunState(f.stateFile)); + expect(artifacts.map(item => item.proof.verification.results.map(receipt => receipt.receiptId))) + .toEqual([['fresh-Tutorial.other_helper'], ['fresh-Tutorial.saved_helper']]); + }); + it('keeps a rejected helper advisory and checks the next helper against the same frozen source', async () => { const f = fixture(); - const file = path.join(f.sourceWorktree, f.problem.projectRelative, 'Submission.lean'); - const source = f.sources.replace('lemma saved_helper', 'lemma rejected_helper : True := by trivial\nlemma saved_helper'); - fs.writeFileSync(file, source); - const canonical = commitSolverSources(f.problem, f.sourceWorktree); - const cooperation = f.archived.cooperation!; - cooperation.canonicalCommit = canonical; - const rejected = { ...f.helper, id: 'rejected', theoremName: 'Tutorial.rejected_helper' }; - cooperation.tasks.unshift({ ...cooperation.tasks[0], task: rejected, - integratedCheck: { ...cooperation.tasks[0].integratedCheck!, commit: canonical, taskDigest: taskVersion(rejected) } }); - writeSolverRunState(f.sourceStateFile, f.archived); - host.verify.mockImplementationOnce((request: MathematicsVerifierBatchRequest) => failedBatch(receiptBatch(request, - { sessionId: 'failed-check', receiptId: () => 'failed-receipt' }), { stdoutPreview: () => 'not proved' })); + const source = addHistoricalHelper(f, 'rejected_helper', 'False'); + const typeRejection = (request: MathematicsVerifierBatchRequest) => failedBatch(receiptBatch(request, + { sessionId: 'failed-check', receiptId: index => `failed-${index}` }), + { stdoutPreview: () => 'Query.lean:5:1: error: Helper declaration has a different type' }); + host.verify.mockImplementationOnce(typeRejection).mockImplementationOnce(typeRejection); const report = await f.seed(); - expect(report).toMatchObject({ stage: 'complete', checked: ['saved'], failed: ['rejected'], - evidence: 'fresh-helper-receipts', declarationFailures: [{ id: 'rejected', name: 'Tutorial.rejected_helper', - error: expect.stringContaining('not proved') }] }); + expect(report).toMatchObject({ stage: 'complete', checked: ['saved'], failed: ['rejected_helper'], + evidence: 'fresh-helper-receipts', declarationFailures: [{ id: 'rejected_helper', name: 'Tutorial.rejected_helper', + error: expect.stringContaining('different type') }] }); const artifacts = readDeclarationArtifacts(f.directory, readSolverRunState(f.stateFile)); expect(artifacts.map(item => item.proof.verification.results[0].receiptId)).toEqual(['fresh-Tutorial.saved_helper']); expect(host.verify.mock.calls.map(([request]) => request.items.map(item => item.theoremName))) - .toEqual([['Tutorial.rejected_helper'], ['Tutorial.saved_helper']]); + .toEqual([['Tutorial.rejected_helper', 'Tutorial.saved_helper'], ['Tutorial.rejected_helper'], ['Tutorial.saved_helper']]); expect(fs.readFileSync(path.join(f.worktree, f.problem.projectRelative, 'Submission.lean'), 'utf8')).toBe(source); }); @@ -138,12 +157,14 @@ 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(); host.verify.mockRejectedValueOnce(new Error('fixture_interrupted_check')); + const f = fixture(); addHistoricalHelper(f, 'other_helper'); + host.verify.mockRejectedValueOnce(new Error('fixture_interrupted_check')); await expect(f.seed()).rejects.toThrow('fixture_interrupted_check'); + expect(host.verify).toHaveBeenCalledOnce(); 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: ['saved'] }); + expect(await f.seed()).toMatchObject({ stage: 'complete', checked: ['other_helper', 'saved'] }); 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); }); diff --git a/tests/taskSourceProjection.test.ts b/tests/taskSourceProjection.test.ts index a76aafb1..9e9dd559 100644 --- a/tests/taskSourceProjection.test.ts +++ b/tests/taskSourceProjection.test.ts @@ -291,6 +291,25 @@ describe('immutable source dependency hint caching', () => { }); describe('owned source projection through dot notation', () => { + it.skipIf(!newestLeanBinary())('checks a submitted helper with local and qualified dot notation after compaction', () => { + const source = 'namespace Fixture\ntheorem original : True := by sorry\nend Fixture\n'; + const solved = source.replace('theorem original', [ + 'def anchor : Nat := 0', + 'theorem iffWitness : True ↔ True := Iff.rfl', + 'theorem Support.pairWitness : True ∧ (True ∧ True) := ⟨trivial, trivial, trivial⟩', + 'theorem unrelated : True := by trivial', + 'theorem reusable : True := iffWitness.mpr _root_.Fixture.Support.pairWitness.right.left', + 'theorem original', + ].join('\n\n')); + const f = fixture(source, solved); + const task = { ...f.task('Fixture.reusable'), kind: 'lemma' as const, type: 'True' }; + leanCheck(f, f.project(task, []).get('Submission.lean')!, 'Fixture.reusable'); + const compact = createTaskSourceProjector(f.problem, f.receipt.workspaceRoot, f.commit, { compact: true }); + const projected = compact(task, []).get('Submission.lean')!; + leanCheck(f, projected, 'Fixture.reusable'); + expect(projected).not.toContain('theorem unrelated'); + }); + it.skipIf(!newestLeanBinary()).each([ ['function application', '(f i)', false], ['nested application', '((fun n : Nat => f n) i)', false],