From f2313a91a721607c62a71a52e04e076012028e69 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:30:49 +0800 Subject: [PATCH] Fix checked declaration handoffs and recovery --- src/math/leanSource.ts | 7 +- src/math/leanSyntax.ts | 45 +++- src/math/leanTypeDiagnostics.ts | 7 +- src/math/verifier.ts | 46 ++-- src/solver/agentTeam.ts | 166 ++++++++++--- src/solver/agentTeamProof.ts | 89 ++++++- src/solver/agentTeamState.ts | 3 + src/solver/cooperativeProof.ts | 20 +- src/solver/declarationArtifacts.ts | 15 +- src/solver/incrementalHelpers.ts | 17 +- src/solver/research.ts | 14 +- src/solver/theoremKnowledgeConsumers.ts | 4 +- src/solver/theoremKnowledgeRelations.ts | 3 +- src/solver/theoremKnowledgeRuns.ts | 10 +- src/solver/theoremKnowledgeSearch.ts | 8 +- tests/agentTeamNativeLifecycle.test.ts | 85 +++++++ tests/agentTeamProof.test.ts | 80 ++++++ tests/agentTeamSourceRecovery.test.ts | 312 ++++++++++++++++++++++-- tests/declarationArtifacts.test.ts | 169 ++++++++++++- tests/leanTypeDiagnostics.test.ts | 16 ++ 20 files changed, 1005 insertions(+), 111 deletions(-) diff --git a/src/math/leanSource.ts b/src/math/leanSource.ts index f0ed252d..da8256f6 100644 --- a/src/math/leanSource.ts +++ b/src/math/leanSource.ts @@ -1,4 +1,4 @@ -import { maskLeanCommentsAndStrings, leanScopeCommands, leanScopeNamespace, updateLeanScopes, type LeanScope } from './leanSyntax'; +import { leanNameWithoutRoot, maskLeanCommentsAndStrings, leanScopeCommands, leanScopeNamespace, updateLeanScopes, type LeanScope } from './leanSyntax'; import { mathDigest } from './mathRuntimeIo'; export const inspectLeanSource = ( @@ -97,8 +97,9 @@ export function repeatedLeanLocalNames(names: readonly string[]): string { /** The declaration a closed type query reopens; a same-named declaration in another namespace is not it. */ export function findLeanTypeQueryDeclaration(source: string, theoremName: string) { const declarations = inspectScopedLeanDeclarations(source); - return declarations.find(declaration => declaration.qualifiedName === theoremName) ?? - declarations.find(declaration => declaration.name === theoremName); + const requested = leanNameWithoutRoot(theoremName); + return declarations.find(declaration => declaration.qualifiedName === requested) ?? + (requested === theoremName ? declarations.find(declaration => declaration.name === theoremName) : undefined); } /** Reopen a declaration's namespaces and active lookup scopes for a closed type query. */ diff --git a/src/math/leanSyntax.ts b/src/math/leanSyntax.ts index 2e68677e..492ab17a 100644 --- a/src/math/leanSyntax.ts +++ b/src/math/leanSyntax.ts @@ -2,12 +2,15 @@ export const isSimpleLeanName = (value: unknown): value is string => typeof value === 'string' && /^[\p{L}_][\p{L}\p{M}\p{N}_'?!]*(?:\.[\p{L}_][\p{L}\p{M}\p{N}_'?!]*)*$/u.test(value); +/** `_root_.` qualifies a Lean reference; it is not part of the constant's name. */ +export const leanNameWithoutRoot = (name: string): string => name.replace(/^_root_\./u, ''); + /** Recognize a single pasted declaration reference, without interpreting Lean expressions. */ export function leanLookupReference(query: string) { const reference = query.trim().replace(/^#check\s+/u, '').replace(/^@/u, ''); if (!isSimpleLeanName(reference)) return undefined; const rooted = reference.startsWith('_root_.'); - return { name: rooted ? reference.slice(7) : reference, rooted }; + return { name: leanNameWithoutRoot(reference), rooted }; } /** Ordinary qualified names explicitly written in prose; preserve first mention and normalize root prefixes. */ @@ -21,6 +24,46 @@ export function maskLeanCommentsAndStrings(source: string, onDocComment?: (start return maskLeanText(source, true, onDocComment); } +export const MAX_LEAN_EXPECTED_TYPE_BYTES = 24_000; + +/** Convert a pasted declaration signature to a type term. Lean still checks the type and universe parameters. */ +export function parseLeanDeclarationType(type: string, declarationNames: readonly string[]): { type: string; universes?: string[] } { + const masked = maskLeanCommentsAndStrings(type); + const first = masked.search(/\S/u); + if (first < 0) return { type }; + const nameStart = masked.startsWith('_root_.', first) ? first + '_root_.'.length : first; + const name = declarationNames.map(leanNameWithoutRoot).find(candidate => { + const end = nameStart + candidate.length; + return masked.startsWith(candidate, nameStart) && + (masked.startsWith('.{', end) || /[\s:([{⦃]/u.test(masked[end] ?? '')); + }); + let start = name ? nameStart + name.length : first; + let universes: string[] | undefined; + if (name && masked.startsWith('.{', start)) { + const end = masked.indexOf('}', start + 2); + if (end < 0) return { type }; + universes = masked.slice(start + 2, end).trim().split(/\s*,\s*/u); + if (!universes.every(universe => isSimpleLeanName(universe) && !universe.includes('.'))) return { type }; + start = end + 1; + } + const pairs: Readonly> = { '(': ')', '[': ']', '{': '}', '⦃': '⦄', '⟨': '⟩' }; + const closing: string[] = []; + for (let position = start; position < masked.length; position++) { + const character = masked[position]!; + 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 }) }; + } + if (character === closing.at(-1)) closing.pop(); + else if (Object.hasOwn(pairs, character) && (closing.length || character !== '⟨')) closing.push(pairs[character]!); + else if (!closing.length && !/\s/u.test(character)) return { type }; + } + return { type }; +} + /** Ordinary source scopes are lookup hints; Lean remains the authority on elaborated names. * A `mutual` block is closed by a bare `end` too, so it is tracked as a scope that opens no namespace. */ export const leanScopeCommands = (cleaned: string) => cleaned.matchAll( diff --git a/src/math/leanTypeDiagnostics.ts b/src/math/leanTypeDiagnostics.ts index 7997225e..b8ad24db 100644 --- a/src/math/leanTypeDiagnostics.ts +++ b/src/math/leanTypeDiagnostics.ts @@ -3,6 +3,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { assertMathConstructionSources, LAKE_CONFIGURATION_FILES as configs, mathLocalModuleBuildOrder } from './mathConstructionSources'; import { inspectLeanDeclarationRegions, leanDeclarationContextCommands } from './leanSource'; +import { MAX_LEAN_EXPECTED_TYPE_BYTES } from './leanSyntax'; import { bindLeanPackages, prepareLeanDiagnosticOverrides, runLeanDiagnostics } from './leanDiagnostics'; import { resolveMathematicsRuntimeEnvironment } from './mathRuntimeEnvironment'; import { resolveMathProofEnvironment } from './mathProofEnvironment'; @@ -22,7 +23,7 @@ export function leanTypeDiagnosticCommands(type: string, output: string, applica ' if expression.hasMVar || expression.hasFVar || expression.hasLooseBVars then', ' throwError "Requested type must be closed without free variables or metavariables"', ' let rendered := (<- Lean.Meta.ppExpr expression).pretty', - ' if rendered.utf8ByteSize > 24000 then throwError "Elaborated type exceeds its export bound"', + ` if rendered.utf8ByteSize > ${MAX_LEAN_EXPECTED_TYPE_BYTES} then throwError "Elaborated type exceeds its export bound"`, ...(application === undefined ? [' let report := Lean.Json.mkObj [("type", Lean.toJson rendered)]'] : [ ` let term <- match Lean.Parser.runParserCategory (<- Lean.getEnv) (Lean.Name.mkSimple "term") ${JSON.stringify(application)} with`, ' | .ok stx => pure stx', ' | .error message => throwError "{message}"', @@ -71,7 +72,7 @@ export type LeanTypeDiagnosticInput = { projectRoot: string; file: string; conte /** The host's advisory consumers and the executed clone must describe the same complete input. */ export function prepareLeanTypeDiagnostic(input: LeanTypeDiagnosticInput) { - if (!input.type.trim() || Buffer.byteLength(input.type) > 12000 || !input.context.trim() || input.context.length > 1000 || + if (!input.type.trim() || Buffer.byteLength(input.type) > MAX_LEAN_EXPECTED_TYPE_BYTES || !input.context.trim() || input.context.length > 1000 || input.expression !== undefined && (!input.expression.trim() || Buffer.byteLength(input.expression) > 12000)) throw new Error('math_type_diagnostics_input_invalid'); const project = fs.realpathSync(input.projectRoot); @@ -138,7 +139,7 @@ export async function checkLeanType(input: LeanTypeDiagnosticInput) { let elaboratedType: string | undefined, constants: string[] | undefined; if (diagnostics.exitCode === 0 && !diagnostics.timedOut && !diagnostics.aborted) { const value = readMathJson(path.join(clone, projection.output)) as Record; - if (typeof value.type !== 'string' || !value.type.trim() || Buffer.byteLength(value.type) > 24000) + if (typeof value.type !== 'string' || !value.type.trim() || Buffer.byteLength(value.type) > MAX_LEAN_EXPECTED_TYPE_BYTES) throw new Error('math_type_diagnostics_export_invalid'); elaboratedType = value.type; if (input.expression !== undefined) { diff --git a/src/math/verifier.ts b/src/math/verifier.ts index 2d325bac..ae7e1486 100644 --- a/src/math/verifier.ts +++ b/src/math/verifier.ts @@ -30,7 +30,8 @@ import { createMathOperationLimiter, forEachWithConcurrency } from "./concurrenc import { canonicalMathJson, mathDigest, mathFileIdentity, readMathFile, readMathText } from './mathRuntimeIo'; import { repositoryRelativePath } from './paths'; import { leanReferenceCommands, parseLeanReferences, type LeanDeclarationReferences } from './leanReferences'; -import { leanDeclarationContextCommands } from './leanSource'; +import { findLeanTypeQueryDeclaration, leanDeclarationContextCommands } from './leanSource'; +import { leanNameWithoutRoot, MAX_LEAN_EXPECTED_TYPE_BYTES, parseLeanDeclarationType } from './leanSyntax'; import { withVerifierCheckout, type VerifierCheckoutCleanupFailure } from './verifierCheckout'; export type MathematicsVerifierBatchItem = { @@ -237,6 +238,8 @@ type ResultBase = Omit< >; const MAX_OUTPUT = MATH_PROCESS_OUTPUT_LIMIT; +// A declaration export can carry two bounded reference reports along with its signature. +const LEAN_DECLARATION_QUERY_OUTPUT_LIMIT = MAX_LEAN_EXPECTED_TYPE_BYTES + 2 * MATH_PROCESS_OUTPUT_LIMIT; const MAX_PROOF_BYTES = 16 * 1024 * 1024; // Construction-time JSON adapters use stdin for one bounded request. Keep the // public sandbox entry point bounded too, so a future protocol adapter cannot @@ -1908,13 +1911,16 @@ const prepareLeanDeclarationQuery = async ( const queries = theoremQueries .map( ({ name, declarationBegin, declarationEnd, axiomBegin, axiomEnd }) => - `#eval IO.println ${JSON.stringify(declarationBegin)}\n#check ${name}\n#eval IO.println ${JSON.stringify(declarationEnd)}\n#eval IO.println ${JSON.stringify(axiomBegin)}\n#print axioms ${name}\n#eval IO.println ${JSON.stringify(axiomEnd)}` + `#eval IO.println ${JSON.stringify(declarationBegin)}\nset_option pp.deepTerms true in\n#check ${name}\n#eval IO.println ${JSON.stringify(declarationEnd)}\n#eval IO.println ${JSON.stringify(axiomBegin)}\n#print axioms ${name}\n#eval IO.println ${JSON.stringify(axiomEnd)}` ) .join('\n'); const expectedType = options?.expectedDeclarationType; const expectedTypes = theoremNames.flatMap(name => { const type = options?.expectedDeclarationTypes?.[name] ?? expectedType; - return type === undefined ? [] : [{ name, type, context: leanDeclarationContextCommands(file.source, name) }]; + if (type === undefined) return []; + const declaration = findLeanTypeQueryDeclaration(file.source, name); + return [{ name, rawType: type, context: leanDeclarationContextCommands(file.source, name), + ...parseLeanDeclarationType(type, [name, ...(declaration ? [declaration.name, declaration.qualifiedName] : [])]) }]; }); const dependencyCandidates = options?.dependencyCandidates; if ( @@ -1928,7 +1934,8 @@ const prepareLeanDeclarationQuery = async ( theoremNames.map((name) => [name, `DS_PROOF_DEPENDENCIES_${crypto.randomBytes(16).toString('hex')}:`]) ); const referenceMarkers = new Map(theoremNames.map(name => [name, `DS_DECL_REFERENCES_${crypto.randomBytes(16).toString('hex')}:`])); - if ((expectedType && theoremNames.length !== 1) || expectedTypes.some(item => !item.type || item.type.length > 12_000)) + if ((expectedType && theoremNames.length !== 1) || expectedTypes.some(item => !item.rawType || + Buffer.byteLength(item.rawType) > MAX_LEAN_EXPECTED_TYPE_BYTES)) throw new Error('Helper expected type requires one bounded declaration.'); const externalChecks = options ? [ @@ -1942,17 +1949,26 @@ const prepareLeanDeclarationQuery = async ( ' if forbidden.contains moduleName.toString then throwError "Forbidden helper dependency: {moduleName}"', ] : []), - ...expectedTypes.flatMap(({ name, type, context }) => [ + ...expectedTypes.flatMap(({ name, type, context, universes }) => [ ...context.before, '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 "{message}"', + ' | .error message => throwError "Invalid expected declaration type. Supply a closed Lean type, for example (∀ (n : Nat), n = n). Parser: {message}"', + ` let name := (${JSON.stringify(leanNameWithoutRoot(name))} : String).toName`, + ...(universes ? [ + ' let info <- Lean.getConstInfo name', + ` let levels : List Lean.Name := (${JSON.stringify(universes)} : List String).map String.toName`, + ' unless levels.length == info.levelParams.length && levels.eraseDups.length == levels.length do', + ' throwError "Helper declaration has different universe parameters"', + ' Lean.Elab.Term.setLevelNames levels', + ] : []), ' let expected <- Lean.Elab.Term.elabType parsedType', ' Lean.Elab.Term.synthesizeSyntheticMVarsNoPostponing', ' let expected <- Lean.instantiateMVars expected', ' if expected.hasMVar || expected.hasFVar then throwError "Helper expected type must be closed without metavariables"', - ` let declaration <- Lean.Meta.mkConstWithFreshMVarLevels (${JSON.stringify(name)}.toName)`, + universes ? ' let declaration := Lean.mkConst name (levels.map Lean.Level.param)' : + ' let declaration <- Lean.Meta.mkConstWithFreshMVarLevels name', ' let actual <- Lean.Meta.inferType declaration', ' unless (<- Lean.Meta.isDefEq actual expected) do throwError "Helper declaration has a different type or additional assumptions"', ...context.after, @@ -1961,7 +1977,7 @@ const prepareLeanDeclarationQuery = async ( ? theoremNames.flatMap((theoremName) => [ 'run_cmd do', ' let env <- Lean.getEnv', - ` let root <- Lean.getConstInfo (${JSON.stringify(theoremName)}.toName)`, + ` let root <- Lean.getConstInfo (${JSON.stringify(leanNameWithoutRoot(theoremName))}.toName)`, ' let some proof := root.value? (allowOpaque := true) | throwError "Declaration has no proof value"', ' let mut todo := Lean.Expr.getUsedConstants proof |>.toList', ' let mut visited : Lean.NameSet := {}', @@ -1981,11 +1997,11 @@ const prepareLeanDeclarationQuery = async ( ]) : []), ...(options.referenceModules ? theoremNames.flatMap(name => - leanReferenceCommands(name, options.referenceModules!, referenceMarkers.get(name)!)) : []), + leanReferenceCommands(leanNameWithoutRoot(name), options.referenceModules!, referenceMarkers.get(name)!)) : []), ...(options.directProof && options.referenceModules ? theoremNames.flatMap(name => [ 'run_cmd do', ' let env <- Lean.getEnv', ` let modules : List (String × String) := [${options.referenceModules!.map(item => `(${JSON.stringify(item.module)}, ${JSON.stringify(item.file)})`).join(', ')}]`, - ` let root <- Lean.getConstInfo (${JSON.stringify(name)}.toName)`, + ` let root <- Lean.getConstInfo (${JSON.stringify(leanNameWithoutRoot(name))}.toName)`, ' let some proof := root.value? (allowOpaque := true) | return', ' let refs := (Lean.Expr.getUsedConstants proof).toList.filterMap fun n => Id.run do', ' let m := match env.getModuleIdxFor? n with | some i => env.header.moduleNames[i.toNat]!.toString | none => ""', @@ -2042,8 +2058,7 @@ const prepareLeanDeclarationQuery = async ( } const elaboratedType = stdout .slice(start + query.declarationBegin.length, finish) - .trim() - .replace(/\s+/gu, ' '); + .trim(); if (!elaboratedType) return { error: `Lean exported an empty theorem declaration: ${query.name}` }; const hash = mathDigest(elaboratedType); types.set(query.name, elaboratedType); @@ -2294,7 +2309,7 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat const regions = new Map(inspectLeanDeclarationRegions(file.source).map(region => [region.startOffset, region])); const inspections = file.declarationInspections = new Map(); verifiableItems = verifiableItems.filter(item => { - const start = item.theoremName ? positions.get(item.theoremName) : undefined; + const start = item.theoremName ? positions.get(leanNameWithoutRoot(item.theoremName)) : undefined; const region = start === undefined ? undefined : regions.get(start); if (!item.theoremName || !item.expectedSourceDeclarationHash || !region) { reject('A helper check in a draft requires one exact source-bound declaration name.', [item]); @@ -2364,7 +2379,8 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat sandboxCapability: context.sandboxCapability, signal: options.signal, timeoutMs: Math.min(requestedTimeoutMs, availableMs), - outputLimit: MATH_PROCESS_OUTPUT_LIMIT * Math.min(64, verifiableItems.length), + outputLimit: (declarationQuery ? LEAN_DECLARATION_QUERY_OUTPUT_LIMIT : MATH_PROCESS_OUTPUT_LIMIT) * + Math.min(64, verifiableItems.length), captureSourceDiagnostics: true, lakePackagesPath, }); @@ -3021,7 +3037,7 @@ async function buildFormalVerificationCacheKey( const environment = Object.fromEntries(environmentEntries); const cacheKey = mathDigest( JSON.stringify({ - schema: 'deepscientist.formal-verification-cache.v1', + schema: 'deepscientist.formal-verification-cache.v3', projectRootHash: mathDigest(projectRoot), targetCommit: resolvedTarget, verifierCommandPath: options.verifierCommandPath || null, diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index 5dee24ec..bebe6971 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -8,10 +8,12 @@ import { NativeAgentControlInputError } from '../runtime/nativeAgentControl'; import { planApprovalStatus, publishNativeApprovalPlan } from './planApproval'; import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; import { bindLeanPackages } from '../math/leanDiagnostics'; +import { inspectScopedLeanDeclarations } from '../math/leanSource'; +import { leanNameWithoutRoot } from '../math/leanSyntax'; import type { SolverRunState } from './archive'; import type { WorkerAccess } from './research'; import type { SolverModules } from './modules'; -import { git, commitSolverSources, solverSourceConstraints, SolverSourceError, withSolverWorktree } from './problem'; +import { git, committedSource, commitSolverSources, solverSourceConstraints, SolverSourceError, withSolverWorktree } from './problem'; import { solverSourceFeedback } from './feedback'; import { prepareResearchSkill } from './researchSkill'; import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext'; @@ -23,10 +25,10 @@ import { prepareTacticBatteryFailureCacheRoot } from './tacticBatteryFailureCach import { ResearchUsage } from './researchUsage'; import { aggregateUsage, buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; import { agentTeamStateSchema, - type AgentTeamState, type AgentTeamWorker, type AgentTeamTask } from './agentTeamState'; + type AgentTeamAdoptionDependency, type AgentTeamState, type AgentTeamWorker, type AgentTeamTask } from './agentTeamState'; import { AgentTeamOperations } from './agentTeamOperations'; import { checkAgentTeamProofDelivery, integrateAgentTeamProofDelivery, readAgentTeamProofDelivery, - ReusedTeamCheckFailure, type TeamFailureCache } from './agentTeamProof'; + MissingAdoptionDependencyError, ReusedTeamCheckFailure, type TeamFailureCache } from './agentTeamProof'; import { ownedSourceDigest } from './cooperativeProof'; import { saveAgentTeamResearchArtifact, inspectAgentTeamResearchArtifact } from './agentTeamResearch'; import { agentTeamRouteSummary, agentTeamTaskHistory } from './agentTeamViews'; @@ -155,6 +157,10 @@ export class AgentResearchTeam { nativeAgentControlOptions(actor = 'lead') { return this.nativeControl.options(actor); } get reviewPlan() { return Boolean(this.input.state.planApproval); } get mayStartProofWork() { return !this.reviewPlan || planApprovalStatus(this.input.state) === 'approved'; } + get leadSourceRecoveryPending() { + const { pendingResearchFreeze, pendingDeclarationCheck, pendingProofCheck } = this.input.state; + return Boolean(pendingResearchFreeze || pendingDeclarationCheck || pendingProofCheck); + } private assertNativePlanApproved() { if (!this.mayStartProofWork) @@ -499,9 +505,8 @@ export class AgentResearchTeam { private pendingIntegration(worker: AgentTeamWorker) { if (worker.pendingDelivery || worker.tasks.some(task => task.helperSubmission)) return true; if (this.archive.adoptions.some(item => item.targetId === worker.id && ['queued', 'integrating'].includes(item.status))) return true; - return this.archive.deliveries.some(delivery => delivery.kind === 'helpers' && - !this.archive.adoptions.some(adoption => adoption.deliveryId === delivery.id && adoption.targetId === worker.id)) && - !solverSourceFeedback(this.input.state.problem, worker.worktree); + const helpers = this.helperAdoptions(worker.id, worker.worktree); + return helpers.canReadDraft() && (helpers.untried.length > 0 || helpers.readyInDraft().length > 0); } /** Native input is the instruction source; retain it for isolated-workspace resume. */ @@ -711,7 +716,6 @@ export class AgentResearchTeam { if (!exposures.some(item => item.deliveryId === reference.id && item.kind === kind)) { exposures.push({ deliveryId: reference.id, agentId: reference.agentId, taskId: reference.taskId, commit, kind, at: new Date().toISOString() }); - this.input.save(); } } @@ -1085,13 +1089,16 @@ export class AgentResearchTeam { private deliveryDeclarations(worker: AgentTeamWorker, task: AgentTeamTask) { const declarations = new Map[number]>(); + const record = (declaration: NonNullable[number]) => { + declarations.set(declaration.file + '\0' + leanNameWithoutRoot(declaration.name), declaration); + }; for (const id of worker.pendingPeerDeliveries ?? []) { const reference = this.archive.deliveries.find(delivery => delivery.id === id); if (!reference) throw new Error('math_team_delivery_unknown'); const peer = readAgentTeamProofDelivery(reference.path, this.input.state); - for (const declaration of peer.declarations) declarations.set(declaration.file + '\0' + declaration.name, declaration); + for (const declaration of peer.declarations) record(declaration); } - for (const declaration of task.declarations ?? []) declarations.set(declaration.file + '\0' + declaration.name, declaration); + for (const declaration of task.declarations ?? []) record(declaration); return [...declarations.values()]; } @@ -1185,11 +1192,14 @@ export class AgentResearchTeam { const signal = local ? AbortSignal.any([this.input.signal, local]) : this.input.signal; worker.activity = 'checking'; worker.phase = 'checking'; this.input.save(); try { - const explicit = new Set(task.declarations?.map(({ file, name }) => file + '\0' + name)); - const inferredHelperTypes = (worker.pendingPeerDeliveries ?? []).flatMap(id => { + const evidenceKey = ({ file, name }: { file: string; name: string }) => file + '\0' + name; + const explicit = new Set(task.declarations?.map(evidenceKey)); + const inheritedTypes = new Set((worker.pendingPeerDeliveries ?? []).flatMap(id => { const reference = this.archive.deliveries.find(delivery => delivery.id === id); return reference?.kind === 'helpers' ? readAgentTeamProofDelivery(reference.path, this.input.state).inferredHelperTypes ?? [] : []; - }).filter(key => !explicit.has(key)); + })); + // A submission can replace the inherited spelling (for example, with `_root_.`). + const inferredHelperTypes = pending.declarations.map(evidenceKey).filter(key => inheritedTypes.has(key) && !explicit.has(key)); const commit = commitSolverSources(this.input.state.problem, worker.worktree); const digest = solverSourceDigest(this.input.state.problem, worker.worktree); if (pending.commit && (pending.commit !== commit || pending.sourceDigest !== digest)) throw new Error('math_team_delivery_source_changed'); @@ -1238,6 +1248,38 @@ export class AgentResearchTeam { worker.phase = 'prepared'; this.input.save(); } + private helperAdoptions(targetId: string, worktree: string) { + const { problem } = this.input.state; + const deliveries = this.archive.deliveries.filter(delivery => delivery.kind === 'helpers'); + const helperOrder = new Map(deliveries.map((delivery, index) => [delivery.id, index])); + const latest = new Map(this.archive.adoptions.filter(item => item.targetId === targetId) + .map(item => [item.deliveryId, item])); + const untried = deliveries.filter(delivery => !latest.has(delivery.id)); + const failedHelper = (item: AgentTeamState['adoptions'][number]) => + item.status === 'failed' && helperOrder.has(item.deliveryId) && Boolean(item.missingDependencies?.length); + const blocked = [...latest.values()].filter(failedHelper); + const sourceNames = new Map>(); + const namesAt = (file: string, commit?: string) => { + const key = (commit ?? '') + '\0' + file; + let names = sourceNames.get(key); + if (!names) { + const relative = path.join(problem.projectRelative, file); + const source = commit ? committedSource(worktree, commit, relative) : fs.readFileSync(path.join(worktree, relative), 'utf8'); + names = new Set(inspectScopedLeanDeclarations(source).map(item => item.qualifiedName)); + sourceNames.set(key, names); + } + return names; + }; + const newlyAvailable = (before: string, after?: string) => ({ file, name }: AgentTeamAdoptionDependency) => + problem.ownedFiles.includes(file) && file.endsWith('.lean') && + namesAt(file, after).has(name) && !namesAt(file, before).has(name); + const hasDraftCandidates = untried.length > 0 || blocked.length > 0; + const canReadDraft = () => hasDraftCandidates && !solverSourceFeedback(problem, worktree); + const readyInDraft = () => blocked.filter(item => + item.expectedCommit && item.missingDependencies?.some(newlyAvailable(item.expectedCommit))); + return { helperOrder, latest, untried, failedHelper, newlyAvailable, hasDraftCandidates, canReadDraft, readyInDraft }; + } + /** Called only after the receiving writer has stopped; no running writer is overwritten. */ async flushAdoptions(targetId = 'lead') { const { state } = this.input; @@ -1246,26 +1288,56 @@ export class AgentResearchTeam { if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed)) throw new Error('math_team_target_writing'); const worktree = target?.worktree ?? state.worktree; - const helpers = target?.status === 'stopped' ? [] : this.archive.deliveries.filter(delivery => delivery.kind === 'helpers' && - !this.archive.adoptions.some(adoption => adoption.deliveryId === delivery.id && adoption.targetId === targetId)); - const queued = this.archive.adoptions.filter(item => item.targetId === targetId && ['queued', 'integrating'].includes(item.status)); - if (!helpers.length && !queued.length) return; + // A check already bound to Lead's source must finish before an adoption can advance it. + if (!target && (state.pendingProofCheck || state.pendingDeclarationCheck)) return; + // Multiple adoptions in one flush can leave a previous freeze and an in-flight intent. + // Recover that intent before freezing the source again. + const recoveringLead = !target && this.leadSourceRecoveryPending; + const helpers = this.helperAdoptions(targetId, worktree); + const { helperOrder, latest, untried, failedHelper, newlyAvailable, readyInDraft } = helpers; + const queued = this.archive.adoptions.filter(item => item.targetId === targetId && + (item.status === 'integrating' || !recoveringLead && item.status === 'queued')); + const inspectDraft = !recoveringLead && target?.status !== 'stopped' && helpers.hasDraftCandidates; + if (!queued.length && !inspectDraft) return; + // A restored idle member needs its pinned project metadata before source validation. const access = target ? this.workspaces.get(targetId)?.access ?? await this.prepare(target) : this.input.leadAccess; - if (helpers.length && !solverSourceFeedback(state.problem, worktree)) { - for (const delivery of helpers) { - const adoption = { id: crypto.randomUUID(), deliveryId: delivery.id, targetId, status: 'queued' as const }; - this.archive.adoptions.push(adoption); - queued.push(adoption); - } - this.input.save(); + const queueHelper = (deliveryId: string) => { + const retry = { id: crypto.randomUUID(), deliveryId, targetId, status: 'queued' as const }; + this.archive.adoptions.push(retry); latest.set(deliveryId, retry); + return retry; + }; + // A stopped writer can supply a prerequisite in its own saved draft. + if (inspectDraft && helpers.canReadDraft()) { + const queuedBefore = queued.length; + for (const failed of readyInDraft()) queued.push(queueHelper(failed.deliveryId)); + for (const delivery of untried) queued.push(queueHelper(delivery.id)); + if (queued.length > queuedBefore) this.input.save(); } - for (const adoption of queued) { + if (!queued.length) return; + // Resume a saved transition before moving HEAD. Install shared helpers in + // publication order before processing deliveries that may depend on them. + const pending = queued.filter(item => item.status === 'queued'); + const ordered = [ + ...queued.filter(item => item.status === 'integrating'), + ...pending.filter(item => helperOrder.has(item.deliveryId)) + .sort((a, b) => helperOrder.get(a.deliveryId)! - helperOrder.get(b.deliveryId)!), + ...pending.filter(item => !helperOrder.has(item.deliveryId)), + ]; + const deferred = new Map(); + const readyAfterTransfer = (before: string, after: string) => { + if (before === after || target?.status === 'stopped') return []; + return [...latest.values()].filter(failed => + (deferred.has(failed) || failedHelper(failed)) && + failed.missingDependencies?.some(newlyAvailable(before, after))); + }; + for (const [index, adoption] of ordered.entries()) { const reference = this.archive.deliveries.find(item => item.id === adoption.deliveryId)!; const delivery = readAgentTeamProofDelivery(reference.path, state); adoption.expectedCommit ??= commitSolverSources(state.problem, worktree); adoption.status = 'integrating'; if (target) target.activity = 'integrating'; this.input.save(); + let event: { to: string; kind: 'adopted' | 'failed'; text: string } | undefined; try { const result = await this.input.exclusiveCheck(() => integrateAgentTeamProofDelivery({ state, delivery, worktree, expectedCommit: adoption.expectedCommit!, env: access.environment, @@ -1274,24 +1346,35 @@ export class AgentResearchTeam { if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed)) throw new Error('math_team_target_writing'); } })); - adoption.status = 'completed'; adoption.commit = result.commit; adoption.receiptId = result.id; adoption.error = undefined; - this.recordExposure(targetId, reference, delivery.commit, 'adopted'); - if (targetId === 'lead') { + const ready = readyAfterTransfer(result.beforeCommit, result.commit); + if (!target) { state.check = undefined; // Save the next acceptance step with adoption completion, so restart needs no extra model turn. - if (reference.kind !== 'helpers' || state.pendingResearchFreeze) + if (reference.kind !== 'helpers' || result.commit !== adoption.expectedCommit || state.pendingResearchFreeze) state.pendingResearchFreeze = { commit: result.commit, sourceDigest: result.sourceDigest, problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest }; } else { // An adopted peer is part of the next transfer until the member's own draft // has been delivered. Retain the old ancestor instead of losing that draft. - if (target!.pendingSourceBase && ownedSourceDigest(state.problem, worktree, target!.pendingSourceBase) !== + if (target.pendingSourceBase && ownedSourceDigest(state.problem, worktree, target.pendingSourceBase) !== ownedSourceDigest(state.problem, worktree, adoption.expectedCommit!)) { - const peers = target!.pendingPeerDeliveries ??= []; + const peers = target.pendingPeerDeliveries ??= []; if (!peers.includes(delivery.id)) peers.push(delivery.id); - } else { target!.pendingSourceBase = undefined; target!.pendingPeerDeliveries = undefined; } + } else { target.pendingSourceBase = undefined; target.pendingPeerDeliveries = undefined; } + } + adoption.status = 'completed'; adoption.commit = result.commit; adoption.receiptId = result.id; adoption.error = undefined; + adoption.missingDependencies = undefined; + this.recordExposure(targetId, reference, delivery.commit, 'adopted'); + // Queue newly enabled retries in the same save as the prerequisite's completion. + for (const failed of ready) { + if (deferred.delete(failed)) { + ordered.push(failed); + } else { + const retry = queueHelper(failed.deliveryId); + if (!recoveringLead) ordered.push(retry); + } } - this.event(null, targetId, 'adopted', 'Checked declarations integrated at ' + result.commit, { deliveryId: adoption.deliveryId }); + event = { to: targetId, kind: 'adopted', text: 'Checked declarations integrated at ' + result.commit }; } catch (error) { adoption.error = error instanceof Error ? error.message : 'math_team_adoption_failed'; if (!correctableProofFailure(error) && !/^math_task_integration_(?:conflict|missing_context|missing_declaration)$/u.test(adoption.error) && @@ -1299,11 +1382,24 @@ export class AgentResearchTeam { // Leave the same expectedCommit queued for crash-safe retry; infrastructure failures are not proof feedback. this.input.save(); throw error; } - adoption.status = 'failed'; - this.event(null, 'lead', 'failed', adoption.error, { deliveryId: adoption.deliveryId }); + adoption.missingDependencies = error instanceof MissingAdoptionDependencyError && error.missing.length ? error.missing : undefined; + if (adoption.missingDependencies && index + 1 < ordered.length) { + // This rejection precedes the durable intent. The next successful source change + // can supply the dependency, so release the old revision and keep the adoption queued. + deferred.set(adoption, adoption.expectedCommit!); + adoption.status = 'queued'; adoption.expectedCommit = undefined; + } else { + adoption.status = 'failed'; + event = { to: 'lead', kind: 'failed', text: adoption.error }; + } } if (target) target.activity = target.tasks.some(task => task.status === 'paused') ? 'paused' : 'idle'; - this.input.save(); + if (event) this.event(null, event.to, event.kind, event.text, { deliveryId: adoption.deliveryId }); + else this.input.save(); + } + for (const [adoption, expectedCommit] of deferred) { + adoption.status = 'failed'; adoption.expectedCommit = expectedCommit; + this.event(null, 'lead', 'failed', adoption.error!, { deliveryId: adoption.deliveryId }); } } diff --git a/src/solver/agentTeamProof.ts b/src/solver/agentTeamProof.ts index abaabdae..696f2976 100644 --- a/src/solver/agentTeamProof.ts +++ b/src/solver/agentTeamProof.ts @@ -3,18 +3,19 @@ import path from 'node:path'; import { z } from 'zod'; import { canonicalMathJson, mathDigest, readMathText, writeMathTextDurable } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; -import { leanDeclarationKeys } from '../math/leanSource'; +import { inspectScopedLeanDeclarations, leanDeclarationKeys } from '../math/leanSource'; +import { leanNameWithoutRoot, maskLeanCommentsAndStrings } from '../math/leanSyntax'; import { bindLeanPackages } from '../math/leanDiagnostics'; import { formalVerificationToolIdentity } from '../math/verifier'; import { hasDeterministicLeanFailure, proofReuseEnvironment } from './proofReuse'; -import { applyTaskChanges, ownedSourceDigest, taskChanges, type DeclarationChange } from './cooperativeProof'; +import { applyTaskChanges, ownedSourceDigest, taskChanges, TaskIntegrationMissingDeclarationError, type DeclarationChange } from './cooperativeProof'; import { checkTeamDeclarationArtifacts, DeclarationArtifactCheckError, DeclarationSubmissionError, teamDeclarationListSchema, validateDeclarationArtifact, type DeclarationArtifact, type DeclarationArtifactIdentity, type DeclarationSubmission } from './declarationArtifacts'; import { assertSolverSources, committedSource, commitSolverSources, git, solverProofImports, withSolverWorktree } from './problem'; import { locateKnowledgeDeclaration } from './theoremKnowledge'; import { solverSourceDigest } from './modules/evidence'; import { archiveAgentTeamCommits, importAgentTeamCommit } from './agentTeamWorkspace'; -import { teamExposureKind, teamSpawnHistory } from './agentTeamState'; +import { teamExposureKind, teamSpawnHistory, type AgentTeamAdoptionDependency } from './agentTeamState'; type Identity = { runId: string; problemReceiptDigest: string; environmentDigest: string }; export type AgentTeamProofProvenance = z.infer; @@ -42,6 +43,11 @@ export class ReusedTeamCheckFailure extends DeclarationArtifactCheckError { super(error.declaration, error.verification); } } +export class MissingAdoptionDependencyError extends DeclarationSubmissionError { + constructor(message: string, readonly missing: AgentTeamAdoptionDependency[], cause: Error) { + super(message, { cause }); + } +} type IntegrationInput = CheckInput & { delivery: AgentTeamProofDelivery; worktree: string; expectedCommit: string }; type AdoptionLocation = Pick; const hash = z.string().regex(/^[a-f0-9]{64}$/u), commitHash = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u); @@ -199,6 +205,65 @@ function readDeliverySources(worktree: string, projectRelative: string) { }; } +function missingAdoptionDependency(error: unknown, delivery: AgentTeamProofDelivery, + problem: DeclarationArtifactIdentity['problem'], readProducer: ReturnType, + readRecipient: ReturnType, commit: string): MissingAdoptionDependencyError | undefined { + if (!(error instanceof DeclarationArtifactCheckError) || !hasDeterministicLeanFailure(error.verification)) return; + const unknown = [...error.message.matchAll(/Unknown (?:identifier|constant) `([^`\n]+)`|The identifier `([^`\n]+)` is unknown/giu)] + .map(match => match[1] ?? match[2]!); + if (!unknown.length) return; + const references = delivery.artifacts.find(item => item.declaration.name === error.declaration.name && + item.declaration.file === error.declaration.file)?.references; + const owned = problem.ownedFiles.filter(file => file.endsWith('.lean')); + const namesAt = (readSource: ReturnType, revision: string) => { + const namesByFile = new Map>(); + return (file: string) => { + let names = namesByFile.get(file); + if (!names) { + names = new Set(inspectScopedLeanDeclarations(readSource(revision, file)).map(item => item.qualifiedName)); + namesByFile.set(file, names); + } + return names; + }; + }; + const producerNamesIn = namesAt(readProducer, delivery.commit), recipientNamesIn = namesAt(readRecipient, commit); + // Lean may report a name relative to the current namespace, including a qualified suffix. + const matchesName = (reported: string, name: string) => reported.startsWith('_root_.') + ? leanNameWithoutRoot(reported) === name : reported === name || name.endsWith('.' + reported); + const candidates = new Map(); + const unmatched: string[] = []; + const inputs = references ? [...references.statement, ...references.proof].filter(({ file }) => owned.includes(file)) : []; + for (const reported of new Set(unknown)) { + // Lean references include generated constants. Only declarations spelled out in + // the producer can be supplied by a checked delivery. + const named = inputs.filter(({ file, name }) => matchesName(reported, name) && producerNamesIn(file).has(name) && + !recipientNamesIn(file).has(name)); + if (!named.length) unmatched.push(reported); + for (const entry of named) candidates.set(entry.file + '\0' + entry.name, entry); + } + if (unmatched.length) { + // Tactics can use names that disappear from the elaborated proof, such as an unused + // simp argument. Require the reported token in the checked source and a unique missing match. + const source = readProducer(delivery.commit, error.declaration.file); + const { bodyOffset, endOffset } = locateKnowledgeDeclaration(source, error.declaration.name); + const words = new Set(maskLeanCommentsAndStrings(source.slice(bodyOffset, endOffset)) + .match(/[\p{L}_][\p{L}\p{M}\p{N}_'?!]*(?:\.[\p{L}_][\p{L}\p{M}\p{N}_'?!]*)*/gu) ?? []); + for (const reported of unmatched) { + if (!words.has(reported)) continue; + const named = owned.flatMap(file => [...producerNamesIn(file)] + .filter(name => matchesName(reported, name) && !recipientNamesIn(file).has(name)).map(name => ({ file, name }))); + const [entry] = named; + if (entry && named.length === 1) candidates.set(entry.file + '\0' + entry.name, entry); + } + } + const missing = [...candidates.values()]; + if (missing.length) { + return new MissingAdoptionDependencyError( + `The recipient is missing ${missing.map(({ file, name }) => `${name} (${file})`).join(', ')}. ` + + 'Adopt the checked delivery for the missing declarations into this workspace, then retry.\n' + error.message, missing, error); + } +} + /** Every changed declaration must be named and independently checked; metadata never widens source ownership. */ function deliveryPatch(problem: DeclarationArtifactIdentity['problem'], worktree: string, seedCommit: string, commit: string, declarations: DeclarationSubmission['declarations'], readSource = readDeliverySources(worktree, problem.projectRelative)) { @@ -388,11 +453,25 @@ export async function integrateAgentTeamProofDelivery(input: IntegrationInput): return withSolverWorktree(input.worktree, input.expectedCommit, async checkout => { const packages = path.join(input.worktree, problem.projectRelative, '.lake', 'packages'); if (fs.existsSync(packages)) bindLeanPackages(path.join(checkout, problem.projectRelative), packages); - applyTaskChanges(problem, checkout, patch.changes, patch.imports); + try { applyTaskChanges(problem, checkout, patch.changes, patch.imports); } + catch (error) { + if (!(error instanceof TaskIntegrationMissingDeclarationError)) throw error; + const { name, file } = error.declaration; + const seed = readSource(delivery.seedCommit, file), keys = leanDeclarationKeys(seed); + const declaration = inspectScopedLeanDeclarations(seed).find(item => keys.get(item.startOffset) === name); + if (error.role === 'anchor' && !declaration) throw error; + const required = error.role === 'anchor' ? `the declaration anchor ${name}` : name; + throw new MissingAdoptionDependencyError(`${error.message}\nThis patch requires ${required} (${file}) at the delivery's seed revision ${delivery.seedCommit}. ` + + 'Adopt a checked delivery containing that previous declaration, then retry.', + declaration ? [{ file, name: declaration.qualifiedName }] : [], error); + } const commit = commitSolverSources(problem, checkout), checkoutStable = frozenSource(input, checkout, commit); const assertAdoptionSources = () => { stable(); checkoutStable(); }; const artifacts = await checkTeamDeclarationArtifacts({ ...input, worktree: checkout, commit, - declarations: delivery.declarations, inferredExpectedTypes: new Set(delivery.inferredHelperTypes), assertFrozenSource: assertAdoptionSources }); + declarations: delivery.declarations, inferredExpectedTypes: new Set(delivery.inferredHelperTypes), assertFrozenSource: assertAdoptionSources }) + .catch(error => { + throw missingAdoptionDependency(error, delivery, problem, readSource, readDeliverySources(checkout, problem.projectRelative), commit) ?? error; + }); assertAdoptionSources(); const record: AgentTeamProofAdoption = { schema: 'theorem-os.agent-team-proof-adoption.v1', id: '', ...identityOf(input.state), deliveryId: delivery.id, beforeCommit: input.expectedCommit, commit, diff --git a/src/solver/agentTeamState.ts b/src/solver/agentTeamState.ts index f28c6eac..148e2779 100644 --- a/src/solver/agentTeamState.ts +++ b/src/solver/agentTeamState.ts @@ -9,6 +9,7 @@ export const writerProcessSchema = z.object({ schema: z.literal('theorem-os.harn pid: z.number().int().positive(), startTime: z.string(), bootId: z.string(), pidNamespace: z.string() }).strict(); const declaration = z.object({ file: z.string(), name: z.string(), type: z.string(), kind: z.literal('definition').optional(), description: z.string().optional(), premises: z.array(z.string()).optional() }).strict(); +const adoptionDependency = z.object({ file: z.string().min(1), name: z.string().min(1) }).strict(); const nativeRuntimeConfiguration = z.object({ source: z.literal('thread-start-overrides'), overrides: z.object({ includeSkillInstructions: z.literal(false), deferMailboxPreemption: z.literal(true).optional(), rootAgentUsageHintText: z.literal('').optional(), subagentUsageHintText: z.literal('').optional(), @@ -132,6 +133,7 @@ export const agentTeamStateSchema = z.object({ schema: z.literal('theorem-os.age summary: z.string().max(200).optional() }).strict()), adoptions: z.array(z.object({ id: z.string(), deliveryId: z.string(), targetId: z.string(), status: z.enum(['queued', 'integrating', 'completed', 'failed']), expectedCommit: z.string().optional(), + missingDependencies: z.array(adoptionDependency).min(1).optional(), commit: z.string().optional(), receiptId: z.string().regex(/^[a-f0-9]{64}$/u).optional(), error: z.string().optional() }).strict()), operations: z.array(z.object({ key: z.string(), digest: z.string(), result: z.unknown() }).strict()), }).strict(); @@ -142,3 +144,4 @@ export type AgentTeamWorker = Stored['workers'][number] & SolverWorkerState & { }; export type AgentTeamState = Omit & { workers: AgentTeamWorker[] }; export type AgentTeamTask = Stored['workers'][number]['tasks'][number]; +export type AgentTeamAdoptionDependency = z.infer; diff --git a/src/solver/cooperativeProof.ts b/src/solver/cooperativeProof.ts index 30d937b5..145620de 100644 --- a/src/solver/cooperativeProof.ts +++ b/src/solver/cooperativeProof.ts @@ -56,6 +56,11 @@ export function projectedGoalInputs(project: ReturnType, readonly role: 'edited' | 'anchor' = 'edited') { + super(role === 'anchor' ? 'math_task_integration_missing_context' : 'math_task_integration_missing_declaration'); + } +} export type TaskProjectionReuse = Readonly<{ schema: 'theorem-os.task-projection-reuse.v1'; projectionCommit: string; checkedProjectionCommit: string; projectionTree: string; inputDigest: string }>; export type TaskProof = ProofCheck & { taskDigest: string; seedCommit: string; changes: DeclarationChange[]; @@ -383,7 +388,9 @@ export function createTaskSourceProjector(problem: SolverProblem, worktree: stri throw new Error((isDefinitionTask(task) ? 'math_task_requires_definition' : 'math_task_requires_theorem') + location + (isDefinitionTask(task) ? 'This task introduces a definition. Save one def with the requested name and type and a complete body, without sorry.' : 'Helper targets must be theorems or lemmas. A goal may fill its exact frozen original def or abbrev, preserving its declaration kind, name, parameters and type.')); - if (task.kind === 'lemma' && Object.values(problem.declarations).some(items => items.some(item => local(item.name) === local(task.theoremName!)))) + const matched = matches[0]; + if (task.kind === 'lemma' && (problem.declarations[task.proofPath!] ?? []).some(item => + item.name === matched.name && (item.qualifiedName === undefined || item.qualifiedName === matched.qualifiedName))) throw new Error('math_task_helper_is_original_declaration'); const sources = new Map(sourceSnapshot); const targetKey = (file: string, name: string) => key(file, declarations.find(item => item.file === file && @@ -1128,7 +1135,8 @@ export function applyTaskChanges(problem: SolverProblem, worktree: string, chang if (actual !== change.after && (!change.before || actual !== change.before)) throw new Error('math_task_integration_conflict'); if (change.afterName && change.before) { const anchor = named(regions, change.afterName); - if (!anchor || canonicalMathJson(leanDeclarationContextCommands(source, change.name)) !== + if (!anchor) throw new TaskIntegrationMissingDeclarationError({ file: change.file, name: change.afterName }, 'anchor'); + if (canonicalMathJson(leanDeclarationContextCommands(source, change.name)) !== canonicalMathJson(leanDeclarationContextCommands(source, change.afterName))) throw new Error('math_task_integration_missing_context'); const moveStart = declarationStartWithDoc(source, existing.startOffset); @@ -1142,12 +1150,16 @@ export function applyTaskChanges(problem: SolverProblem, worktree: string, chang source = source.slice(0, start) + change.after + source.slice(existing.endOffset); } } else { - if (change.before) throw new Error('math_task_integration_missing_declaration'); + if (change.before) throw new TaskIntegrationMissingDeclarationError({ file: change.file, name: change.name }); const anchor = change.beforeName && named(regions, change.beforeName); const sibling = change.afterName && named(regions, change.afterName); const offset = anchor ? declarationStartWithDoc(source, anchor.startOffset) : sibling ? sibling.endOffset : change.tail !== undefined && source.endsWith(change.tail) ? source.length - change.tail.length : -1; - if (offset < 0) throw new Error('math_task_integration_missing_context'); + if (offset < 0) { + const missing = change.beforeName ?? change.afterName; + if (missing) throw new TaskIntegrationMissingDeclarationError({ file: change.file, name: missing }, 'anchor'); + throw new Error('math_task_integration_missing_context'); + } const separator = sibling && offset > 0 && source[offset - 1] !== '\n' ? '\n' : ''; source = source.slice(0, offset) + separator + change.after + source.slice(offset); } diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index ea778998..aa1d3423 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -4,7 +4,7 @@ import { z } from 'zod'; import { canonicalMathJson, mathDigest, readMathJson, readMathText, writeMathJsonDurable, writeMathTextDurable } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; -import { isSimpleLeanName } from '../math/leanSyntax'; +import { isSimpleLeanName, leanNameWithoutRoot, MAX_LEAN_EXPECTED_TYPE_BYTES } from '../math/leanSyntax'; import { isMathFoundationalLeanAxiom } from '../math/contracts'; import type { SolverRunState } from './archive'; import { createTaskSourceProjector, ownedSourceDigest } from './cooperativeProof'; @@ -25,7 +25,8 @@ 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) <= 24000), + 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.` }), 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(); @@ -306,7 +307,8 @@ async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof d 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'); + if (new Set(declarations.map(item => `${item.file}\0${leanNameWithoutRoot(item.name)}`)).size !== declarations.length) + return submissionFail('duplicate_declaration'); const environment = proofReuseEnvironment(path.join(worktree, problem.projectRelative), input.env); const check = async (group: DeclarationSubmission['declarations']) => { const first = group[0]!, batched = group.length > 1; @@ -326,14 +328,15 @@ async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof d } 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); + const name = leanNameWithoutRoot(declaration.name); + const original = problem.targets.find(target => target.proofPath === declaration.file && leanNameWithoutRoot(target.theoremName) === 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 }; + theoremName: original?.theoremName ?? name, type, dependsOn: [], revision: 0 }; return { declaration, declarationHash, declarationDigest, task, checkHelperInDraft }; }); const { checkHelperInDraft, task } = prepared[0]!; @@ -357,7 +360,7 @@ async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof d 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, - ...(batched ? { expectedDeclarationTypes: Object.fromEntries(prepared.map(({ task }) => [task.theoremName!, task.type!])) } + ...(batched ? { expectedDeclarationTypes: Object.fromEntries(prepared.map(({ declaration, task }) => [declaration.name, task.type!])) } : { expectedDeclarationType: task.type }), prepareLocalDependencies: checkHelperInDraft || problem.kind === 'lean-eval', ...(checkHelperInDraft ? { checkDeclarationsInDraft: true } : {}), diff --git a/src/solver/incrementalHelpers.ts b/src/solver/incrementalHelpers.ts index af60f796..58fb1262 100644 --- a/src/solver/incrementalHelpers.ts +++ b/src/solver/incrementalHelpers.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import { z } from 'zod'; import { inspectScopedLeanDeclarations } from '../math/leanSource'; -import { isSimpleLeanName, maskLeanComments } from '../math/leanSyntax'; +import { isSimpleLeanName, maskLeanComments, MAX_LEAN_EXPECTED_TYPE_BYTES } from '../math/leanSyntax'; import { mathDigest } from '../math/mathRuntimeIo'; import { importAgentTeamCommit } from './agentTeamWorkspace'; import { applyTaskChanges, createTaskSourceProjector, taskChanges, type DeclarationChange } from './cooperativeProof'; @@ -19,7 +19,8 @@ const leanName = z.string().min(1).max(1000).refine(isSimpleLeanName); const leanFile = z.string().refine(value => value.endsWith('.lean') && allowedKnowledgeFile(value)); const commitHash = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u); export const helperNominationsSchema = z.array(z.object({ - file: leanFile, name: leanName, type: z.string().trim().min(1).max(12_000).optional(), + file: leanFile, name: leanName, type: z.string().trim().min(1) + .refine(value => Buffer.byteLength(value) <= MAX_LEAN_EXPECTED_TYPE_BYTES).optional(), kind: z.literal('definition').optional(), }).strict()).min(1).max(32); export type HelperNomination = z.infer[number]; @@ -230,11 +231,15 @@ export async function landVerifiedHelpers(input: VerifiedHelpersInput): Promise< if (!verification.passed) return reject('kernel_rejected', verification.verification.status); } current(); - const declarations = selection.added.map(declaration => ({ - ...declaration, type: checked.get(id(declaration.file, declaration.name))!, - })); + const declarations = selection.added.map(declaration => { + const type = checked.get(id(declaration.file, declaration.name))!; + if (Buffer.byteLength(type) <= MAX_LEAN_EXPECTED_TYPE_BYTES) return { ...declaration, type }; + // The printed signature adds the declaration name and layout to the checked type. + if (declaration.type !== undefined) return { ...declaration, type: declaration.type }; + return reject('type_export_too_large', `${declaration.name}: nominate an equivalent type of at most ${MAX_LEAN_EXPECTED_TYPE_BYTES} UTF-8 bytes.`); + }); const helpers = declarations.map(({ file, name, type, kind }) => landedHelperSchema.parse({ - file, qualifiedName: name, type: type.replace(/\s+/gu, ' ').slice(0, 1000), commit, ...(kind ? { kind } : {}), + file, qualifiedName: name, type: type.slice(0, 1000), commit, ...(kind ? { kind } : {}), })); return { commit, helpers, declarations, changes: selection.changes, imports: selection.imports }; }); diff --git a/src/solver/research.ts b/src/solver/research.ts index 178db4bc..bfced7ba 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -157,6 +157,7 @@ export async function runResearchLead(input: { const errors: unknown[] = []; const cleanupErrors: unknown[] = []; state.error = undefined; + let deferredLeadAdoptions = team?.leadSourceRecoveryPending; try { await team?.restore(); let session: MathAgentSession | undefined; @@ -644,6 +645,15 @@ export async function runResearchLead(input: { environment: access.environment, skill: access.researchSkill!, signal, proofTimeoutMs: input.proofTimeoutMs, writerStopped: () => !session && !research.writerStopUnconfirmed, sourceFeedback, exclusiveCheck, checkWhole, save, emit }) : undefined; + const resumeSkillProofWork = async () => { + if (team && !team.mayStartProofWork) return; + await skillProofLifecycle?.resumePending(); + if (!winner && !signal.aborted && deferredLeadAdoptions && team) { + deferredLeadAdoptions = false; + await team.flushAdoptions(); + await skillProofLifecycle!.resumePending(); + } + }; const awaitNativePlanApproval = async () => { if (planApprovalStatus(state) !== 'pending') return true; if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0) { @@ -672,7 +682,7 @@ export async function runResearchLead(input: { let deliveredApprovedPlan = false; try { await waitForRecovery(true); - if (!team || team.mayStartProofWork) await skillProofLifecycle?.resumePending(); + await resumeSkillProofWork(); if (winner) return winner; access.assertKnowledgeCurrent?.(); if ((!skillMode || fullSkillWorkflow) && !team && !access.commonResearchSkill && !research.turns && access.installedLibrary && modules.M2.applyLibrary && budget().remainingMs > 0) { @@ -696,7 +706,7 @@ export async function runResearchLead(input: { } while (!signal.aborted) { if (team?.reviewPlan && !await awaitNativePlanApproval()) break; - if (!team || team.mayStartProofWork) await skillProofLifecycle?.resumePending(); + await resumeSkillProofWork(); if (winner) break; if (research.phase === 'checking') { research.phase = 'running'; save(); } if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0) break; diff --git a/src/solver/theoremKnowledgeConsumers.ts b/src/solver/theoremKnowledgeConsumers.ts index 788bd27c..b2ffd9e9 100644 --- a/src/solver/theoremKnowledgeConsumers.ts +++ b/src/solver/theoremKnowledgeConsumers.ts @@ -1,4 +1,5 @@ import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; +import { leanNameWithoutRoot } from '../math/leanSyntax'; import type { TheoremKnowledgeBase, TheoremKnowledgeEntry } from './theoremKnowledge'; export type KnowledgeConsumersOptions = { offset?: number; limit?: number; maxBytes?: number }; @@ -36,8 +37,9 @@ export function getKnowledgeConsumers(base: TheoremKnowledgeBase, id: string, op const unknownEnvironments = contextEntries.filter(item => !item.environmentDigest?.trim()).length; const scope = knownEnvironment ? contextEntries.filter(item => item.environmentDigest === root.environmentDigest) : []; + const rootName = leanNameWithoutRoot(root.name); const uses = (entry: TheoremKnowledgeEntry) => (['statement', 'proof'] as const).filter(kind => - entry.dependencies[kind].some(reference => reference.file === root.file && reference.name === root.name)) + entry.dependencies[kind].some(reference => reference.file === root.file && leanNameWithoutRoot(reference.name) === rootName)) .map(kind => kind === 'statement' ? 'statement-use' as const : 'proof-use' as const); const matches = scope.map(entry => ({ entry, uses: uses(entry) })).filter(item => item.uses.length) .sort((left, right) => left.entry.name.localeCompare(right.entry.name) || left.entry.file.localeCompare(right.entry.file) || diff --git a/src/solver/theoremKnowledgeRelations.ts b/src/solver/theoremKnowledgeRelations.ts index 1f45b9a6..56313464 100644 --- a/src/solver/theoremKnowledgeRelations.ts +++ b/src/solver/theoremKnowledgeRelations.ts @@ -1,3 +1,4 @@ +import { leanNameWithoutRoot } from '../math/leanSyntax'; import type { TheoremKnowledgeBase, TheoremKnowledgeEntry } from './theoremKnowledge'; export type KnowledgeRelation = Readonly<{ @@ -16,7 +17,7 @@ export function createKnowledgeRelationIndex(base: RelationBase) { const endpoints = new Map(); const incoming = new Map(); const key = (item: TheoremKnowledgeEntry, file = item.file, name = item.name) => - JSON.stringify([item.contextDigest, item.environmentDigest, file, name]); + JSON.stringify([item.contextDigest, item.environmentDigest, file, leanNameWithoutRoot(name)]); const knownEnvironment = (item: TheoremKnowledgeEntry) => Boolean(item.environmentDigest?.trim()); let indexTruncated = false; for (const entry of base.entries) { diff --git a/src/solver/theoremKnowledgeRuns.ts b/src/solver/theoremKnowledgeRuns.ts index 2ae2cca2..05e00473 100644 --- a/src/solver/theoremKnowledgeRuns.ts +++ b/src/solver/theoremKnowledgeRuns.ts @@ -1,6 +1,7 @@ import path from 'node:path'; import fs from 'node:fs'; import { mathGitBytes } from '../math/mathGit'; +import { leanNameWithoutRoot, parseLeanDeclarationType } from '../math/leanSyntax'; import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath } from '../math/paths'; import { readSolverRunState, type SolverRunState } from './archive'; @@ -65,8 +66,13 @@ function declarationCandidate(state: SolverRunState, artifact: DeclarationArtifa const references = artifact.references; if (references && [...references.statement, ...references.proof].some(reference => !Object.hasOwn(files, reference.file))) return error('reference_mismatch'); - return { name: declaration.name, file: declaration.file, type: declaration.type, typeKind: 'closed-task-type', - kind: definition ? 'definition' : problem.targets.some(target => target.proofPath === declaration.file && target.theoremName === declaration.name) ? 'goal' : 'lemma', + const signature = parseLeanDeclarationType(declaration.type, [declaration.name, location.name, location.qualifiedName]); + const original = problem.targets.some(target => target.proofPath === declaration.file && + leanNameWithoutRoot(target.theoremName) === leanNameWithoutRoot(declaration.name)); + return { name: declaration.name, file: declaration.file, + type: signature.universes ? declaration.type : signature.type, + typeKind: signature.universes ? 'source-header' : 'closed-task-type', + kind: definition ? 'definition' : original ? 'goal' : 'lemma', description: declaration.description ?? `Independently checked declaration ${declaration.name}`, premises: [...(declaration.premises ?? [])], dependencies: { statement: references?.statement ?? [], proof: references?.proof ?? [], tasks: [], diff --git a/src/solver/theoremKnowledgeSearch.ts b/src/solver/theoremKnowledgeSearch.ts index 60e2a7fb..455e7374 100644 --- a/src/solver/theoremKnowledgeSearch.ts +++ b/src/solver/theoremKnowledgeSearch.ts @@ -1,5 +1,5 @@ import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { leanLookupReference, maskLeanCommentsAndStrings } from '../math/leanSyntax'; +import { leanLookupReference, maskLeanCommentsAndStrings, parseLeanDeclarationType } from '../math/leanSyntax'; import { knowledgeGoalSurfaceShape, knowledgeResidualViews, splitIffConclusion, splitStatement } from './theoremKnowledgeGoal'; import type { TheoremKnowledgeBase, TheoremKnowledgeEntry } from './theoremKnowledge'; import { createKnowledgeRelationIndex, type KnowledgeRelation } from './theoremKnowledgeRelations'; @@ -104,7 +104,11 @@ function textTerms(text: string, binders: boolean): string[] { export function knowledgeTypeExpression(item: Pick): string { if (item.typeKind !== 'source-header') return item.type; - const header = item.type.replace(/^(?:(?:theorem|lemma|def|abbrev|opaque)\s+)?[\p{L}_][\p{L}\p{M}\p{N}_'.]*\s*/u, ''); + const source = item.type.replace(/^(?:theorem|lemma|def|abbrev|opaque)\s+/u, ''); + const prefix = /^[\p{L}_][\p{L}\p{M}\p{N}_'.?!]*/u.exec(source)?.[0]; + if (prefix?.endsWith('.') && source[prefix.length] === '{') + return parseLeanDeclarationType(source, [prefix.slice(0, -1)]).type; + const header = source.replace(/^[\p{L}_][\p{L}\p{M}\p{N}_'.]*\s*/u, ''); let depth = 0; for (let index = 0; index < header.length; index++) { const character = header[index]!; diff --git a/tests/agentTeamNativeLifecycle.test.ts b/tests/agentTeamNativeLifecycle.test.ts index 69c6d1e0..b8347d31 100644 --- a/tests/agentTeamNativeLifecycle.test.ts +++ b/tests/agentTeamNativeLifecycle.test.ts @@ -415,6 +415,91 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => } finally { gate?.resolve(); } }, 60_000); + it.each([['standalone helper', true], ['proof delivery', false]] as const)( + 'installs a standalone prerequisite before an explicitly queued dependent %s on the first flush', async (_kind, helpersOnly) => { + const f = fixture(), leadSource = f.source(f.state.worktree); + const initialSource = fs.readFileSync(leadSource, 'utf8'); + const prerequisite = 'theorem prerequisite : True := by trivial\n'; + const downstream = 'theorem downstream : True := by exact prerequisite\n'; + const submit = async (agentId: string, name: string, source: string, standalone: boolean) => { + await f.spawn(agentId, 'Prove and share NativeTeam.' + name + '.'); + const worker = f.team.archive.workers.find(item => item.id === agentId)!; + const file = f.source(worker.worktree); + fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem original', source + 'theorem original')); + expect(await f.tool({ operation: 'submit', helpersOnly: standalone, summary: 'Checked declaration ' + name, + declarations: [{ file: 'Submission.lean', name: 'NativeTeam.' + name, type: 'True' }] }, agentId)) + .toMatchObject({ status: 'pending-writer-stop' }); + await f.sessions.at(-1)!.complete(); + await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); + const reference = f.team.archive.deliveries.find(item => item.agentId === agentId); + expect(reference).toBeDefined(); + expect(reference!.kind).toBe(standalone ? 'helpers' : undefined); + return { reference: reference!, evidence: readAgentTeamProofDelivery(reference!.path, f.state) }; + }; + + const first = await submit('producer', 'prerequisite', prerequisite, true); + const second = await submit('consumer', 'downstream', downstream, helpersOnly); + expect(second.evidence.declarations.map(item => item.name)).toEqual(['NativeTeam.downstream']); + expect(second.evidence.artifacts[0]!.references?.proof).toContainEqual({ file: 'Submission.lean', name: 'NativeTeam.prerequisite' }); + expect(fs.readFileSync(leadSource, 'utf8')).toBe(initialSource); + expect(await f.tool({ operation: 'adopt', deliveryId: second.reference.id })) + .toMatchObject({ ok: true, adoption: { targetId: 'lead', status: 'queued' } }); + + const priorEvents = f.team.archive.events.length; + await f.team.flushAdoptions(); + const leadEvents = f.team.archive.events.slice(priorEvents).filter(event => event.to === 'lead'); + expect(leadEvents.map(({ kind, deliveryId }) => [kind, deliveryId])).toEqual([ + ['adopted', first.reference.id], ['adopted', second.reference.id], + ]); + expect(fs.readFileSync(leadSource, 'utf8')).toBe( + initialSource.replace('theorem original', prerequisite + downstream + 'theorem original')); + }, 60_000); + + it('installs an ordinary prerequisite in an older member before retrying its dependent helper', async () => { + const f = fixture(); + await f.spawn('consumer'); + await f.sessions[0]!.complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + const consumerSource = f.source(f.team.archive.workers[0]!.worktree); + const initialSource = fs.readFileSync(consumerSource, 'utf8'); + + await f.spawn('producer'); + const producer = f.team.archive.workers[1]!; + const producerSource = f.source(producer.worktree); + const prerequisite = 'theorem prerequisite : True := by trivial\n'; + const downstream = 'theorem downstream : True := by exact prerequisite\n'; + const submit = async (name: string, source: string, helpersOnly: boolean) => { + fs.writeFileSync(producerSource, fs.readFileSync(producerSource, 'utf8').replace('theorem original', source + 'theorem original')); + expect(await f.tool({ operation: 'submit', helpersOnly, summary: 'Publish ' + name, + declarations: [{ file: 'Submission.lean', name: 'NativeTeam.' + name, type: 'True' }] }, producer.id)) + .toMatchObject({ status: 'pending-writer-stop' }); + await f.sessions.at(-1)!.complete(); + await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); + return f.team.archive.deliveries.at(-1)!; + }; + const first = await submit('prerequisite', prerequisite, false); + expect(first.kind).toBeUndefined(); + await f.tool({ operation: 'adopt', deliveryId: first.id }); + await f.team.flushAdoptions(); + expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain(prerequisite); + await f.native('send', { caller: ROOT, target: { kind: 'id', threadId: producer.native!.threadId }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Share the consequence as a standalone helper.' } } }); + const second = await submit('downstream', downstream, true); + expect(second.kind).toBe('helpers'); + expect(fs.readFileSync(consumerSource, 'utf8')).toBe(initialSource); + + const priorEvents = f.team.archive.events.length; + expect(await f.tool({ operation: 'adopt', deliveryId: first.id, targetId: 'consumer' })) + .toMatchObject({ ok: true }); + await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); + const events = f.team.archive.events.slice(priorEvents).filter(event => event.deliveryId); + expect(events.map(({ to, kind, deliveryId }) => [to, kind, deliveryId])).toEqual([ + ['consumer', 'adopted', first.id], ['consumer', 'adopted', second.id], + ]); + expect(fs.readFileSync(consumerSource, 'utf8')).toBe( + initialSource.replace('theorem original', prerequisite + downstream + 'theorem original')); + }, 60_000); + it('keeps a child accepted by the host when its initiating request is subsequently cancelled', async () => { const f = fixture(), caller = new AbortController(); await f.spawn('analyst', undefined, caller.signal); diff --git a/tests/agentTeamProof.test.ts b/tests/agentTeamProof.test.ts index 92ff20b1..76bce9c4 100644 --- a/tests/agentTeamProof.test.ts +++ b/tests/agentTeamProof.test.ts @@ -11,6 +11,8 @@ import { commitSolverSources, git, readSolverProblem } from '../src/solver/probl import { solverState } from './helpers/solver'; import { temporaryDirectory } from './helpers/files'; import { declarationSubmissionSchema } from '../src/solver/declarationArtifacts'; +import { AgentResearchTeam } from '../src/solver/agentTeam'; +import { directSolverModules } from '../src/solver/modules'; import { prepareAgentTeamWorkspace } from '../src/solver/agentTeamWorkspace'; import { buildAgentTeamContributions } from '../src/solver/agentTeamContributions'; import { teamDeclarationForwarding } from '../src/solver/agentTeamForwarding'; @@ -322,6 +324,84 @@ describe('agent-owned declaration deliveries with real Lean', () => { expect(f.state.check).toBeUndefined(); }, 90_000); + it.each(['lead', 'member'] as const)('persists recipient bookkeeping together with completed %s adoption', async targetId => { + const f = fixture(), member = targetId === 'member' ? consumerWithDraft(f, 'theorem ownDraft : True := by trivial\n') : undefined; + const evidenceDirectory = path.join(f.directory, 'agent-team/proofs'); + const delivery = await checkAgentTeamProofDelivery({ ...f.check, evidenceDirectory }); + f.state.agentTeam = { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', events: [], operations: [], + workers: member ? [{ id: targetId, role: 'researcher', worktree: member.worktree, seedCommit: f.problem.baseCommit, + pendingSourceBase: f.problem.baseCommit, status: 'idle', activity: 'idle', phase: 'prepared', cursor: 0, turns: 0, tasks: [] }] : [], + deliveries: [{ id: delivery.id, agentId: delivery.agentId, taskId: 'task', path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json') }], + adoptions: [{ id: 'adoption', deliveryId: delivery.id, targetId, status: 'queued' }] }; + const snapshots: (typeof f.state)[] = []; + const access = { environment: f.common.env, retrievalRoot: f.state.worktree }; + const team = new AgentResearchTeam({ state: f.state, root: process.cwd(), taskText: 'Check a local handoff.', + leadAccess: access, prepareWorker: async () => access, modules: directSolverModules, + executable: 'unused', profile: 'unused', signal: f.common.signal, maxAgents: 3, maxTurns: Infinity, + maxTurnMs: Infinity, maxTotalTokens: 0, proofTimeoutMs: f.common.timeoutMs, remainingMs: () => Infinity, + save: () => { snapshots.push(JSON.parse(JSON.stringify(f.state))); }, + emit: () => {}, exclusiveCheck: fn => fn() }); + try { + await team.flushAdoptions(targetId); + const completed = snapshots.find(s => s.agentTeam?.adoptions[0]?.status === 'completed')!; + const commit = completed.agentTeam!.adoptions[0]!.commit; + expect(commit).toBe(git(member?.worktree ?? f.state.worktree, ['rev-parse', 'HEAD'])); + expect(completed.agentTeam!.events.at(-1)).toMatchObject({ kind: 'adopted', to: targetId, deliveryId: delivery.id }); + if (member) expect(completed.agentTeam!.workers[0]).toMatchObject({ + activity: 'idle', pendingSourceBase: f.problem.baseCommit, pendingPeerDeliveries: [delivery.id] }); + else expect(completed.pendingResearchFreeze).toMatchObject({ commit, problemReceiptDigest: f.problem.receiptDigest }); + } finally { await team.close(); } + }, 90_000); + + it('names the missing previous declaration revision before running Lean on a patch', async () => { + const f = fixture(), prior = await checkAgentTeamProofDelivery(f.check); + const revised = peerHelper.replace('by rfl', 'by exact Eq.refl n'); + fs.writeFileSync(f.source(f.worktree), original.replace('end Team', revised + 'end Team')); + const delivery = await checkAgentTeamProofDelivery({ ...f.check, seedCommit: prior.commit }); + const target = { ...f.common, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; + const verify = vi.spyOn(evidence, 'checkProjectedDeclarations'); + await expect(integrateAgentTeamProofDelivery({ ...target, delivery })).rejects.toMatchObject({ + name: 'DeclarationSubmissionError', message: expect.stringContaining( + `reusable (Submission.lean) at the delivery's seed revision ${prior.commit}`) }); + expect(verify).not.toHaveBeenCalled(); + expect(git(target.worktree, ['rev-parse', 'HEAD'])).toBe(target.expectedCommit); + const adopted = await integrateAgentTeamProofDelivery({ ...target, delivery: prior }); + const result = await integrateAgentTeamProofDelivery({ ...target, delivery, expectedCommit: adopted.commit }); + expect(result.artifacts[0]!.proof.verification.status).toBe('kernel_verified'); + expect(fs.readFileSync(f.source(target.worktree), 'utf8')).toContain(revised); + }, 90_000); + + it.each([ + { + prerequisite: 'theorem reusable (n : Nat) : n = n := by rfl\n', + declaration: { name: 'Team.reusable', type: '∀ n : Nat, n = n' }, + dependent: 'theorem downstream (n : Nat) : n = n := by exact reusable n\n', + dependentType: '∀ n : Nat, n = n', + }, + { + prerequisite: 'def shift (n : Nat) : Nat := n + 1\n', + declaration: { name: 'Team.shift', type: 'Nat → Nat', kind: 'definition' as const }, + dependent: 'theorem downstream (n : Nat) : shift n = n + 1 := by rfl\n', + dependentType: '∀ n : Nat, Team.shift n = n + 1', + }, + ])('identifies missing $declaration.name and checks the delivery again after it is adopted', async (example) => { + const f = fixture(example.prerequisite); + const prerequisite = await checkAgentTeamProofDelivery({ ...f.check, + declarations: [{ file: 'Submission.lean', ...example.declaration }] }); + fs.writeFileSync(f.source(f.worktree), original.replace('end Team', example.prerequisite + example.dependent + 'end Team')); + const delivery = await checkAgentTeamProofDelivery({ ...f.check, seedCommit: prerequisite.commit, + declarations: [{ file: 'Submission.lean', name: 'Team.downstream', type: example.dependentType }] }); + const target = { ...f.common, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; + await expect(integrateAgentTeamProofDelivery({ ...target, delivery })).rejects.toThrow( + `The recipient is missing ${example.declaration.name} (Submission.lean).`); + expect(git(target.worktree, ['rev-parse', 'HEAD'])).toBe(target.expectedCommit); + expect(fs.readFileSync(f.source(target.worktree), 'utf8')).toBe(original); + const adopted = await integrateAgentTeamProofDelivery({ ...target, delivery: prerequisite }); + const result = await integrateAgentTeamProofDelivery({ ...target, delivery, expectedCommit: adopted.commit }); + expect(result.artifacts[0]!.proof.verification.results[0]).toMatchObject({ status: 'kernel_verified', theoremName: 'Team.downstream' }); + expect(fs.readFileSync(f.source(target.worktree), 'utf8')).toContain(example.dependent); + }, 90_000); + it('preserves a fixed unfinished consumer draft while adopting its missing peer dependency and recovering the same transition', async () => { const f = fixture(); fs.writeFileSync(f.source(f.worktree), original.replace('theorem original', peerHelper + 'theorem original')); diff --git a/tests/agentTeamSourceRecovery.test.ts b/tests/agentTeamSourceRecovery.test.ts index ed5f498f..74fa5b97 100644 --- a/tests/agentTeamSourceRecovery.test.ts +++ b/tests/agentTeamSourceRecovery.test.ts @@ -10,16 +10,18 @@ import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSes import type { NativeAgentControlConnection } from '../src/runtime/nativeAgentControl'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; +import { checkAgentTeamProofDelivery, readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; import { LEAN_MEMORY_LIMIT_ERROR } from '../src/math/verifier'; -import { DeclarationArtifactCheckError } from '../src/solver/declarationArtifacts'; +import { DECLARATION_SUBMISSION_FILE, DeclarationArtifactCheckError } from '../src/solver/declarationArtifacts'; import { directSolverModules } from '../src/solver/modules'; import * as evidence from '../src/solver/modules/evidence'; import { agentLibrary, LIBRARY_ACCESS_FILE, LIBRARY_REQUEST_FILE, type LibraryAccess, writeLibraryAccess } from '../src/solver/libraryAccess'; import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; -import { git, pinSolverResearchSkill, readSolverProblem } from '../src/solver/problem'; +import { commitSolverSources, git, pinSolverResearchSkill, readSolverProblem, withSolverWorktree } from '../src/solver/problem'; import { RESEARCH_TOOL_HELP_FILE } from '../src/solver/researchToolHelp'; +import { runResearchLead } from '../src/solver/research'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; +import { createSkillProofLifecycle } from '../src/solver/skillProofLifecycle'; import type { SoftSliceSettings } from '../src/solver/softSlice'; import { deferred } from './helpers/async'; import { temporaryDirectory } from './helpers/files'; @@ -53,6 +55,10 @@ function memoryLimit(declaration: typeof declarations[number], commit: string) { const original = 'namespace Recovery\ntheorem goal : True := by sorry\nend Recovery\n'; const helper = 'theorem helper : True := by trivial\n'; const declarations = [{ file: 'Submission.lean', name: 'Recovery.helper', type: 'True' }]; +const shadowFile = 'Submission/Library/Shadow.lean'; +const shadowPack = { schema: LIBRARY_PACK_SCHEMA, modules: [{ file: shadowFile, + source: 'namespace Shadow\ntheorem helper : True := by trivial\nend Shadow\n', + origin: { kind: 'upstream' as const, repository: 'offline-native-fixture', commit: 'a'.repeat(40), file: shadowFile } }] }; const fixtures: ReturnType[] = []; const rootThreadId = '00000000-0000-4000-8000-000000000001'; @@ -68,11 +74,13 @@ function nativeConnection(threadId: string, agentPath: string, cwd: string, noti }; } -function fixture({ maxAgents = 2, softSlice, stallInterrupt = false, librarySource, maxTotalTokens = 0 }: { +function fixture({ maxAgents = 2, softSlice, stallInterrupt = false, librarySource, maxTotalTokens = 0, + problemSource = original, libraryPack }: { maxAgents?: number; softSlice?: SoftSliceSettings; stallInterrupt?: boolean; librarySource?: string; maxTotalTokens?: number; + problemSource?: string; libraryPack?: Parameters[1]['libraryPack']; } = {}) { const directory = temporaryDirectory('agent-team-source-recovery-'); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { source: original, task: 'Prove True.' }); + const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { source: problemSource, task: 'Prove True.', libraryPack }); const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), root = path.resolve('.'); const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); const state = solverState(problem, receipt.workspaceRoot, { runId: 'agent-team-source-recovery', phase: 'running', @@ -100,7 +108,7 @@ function fixture({ maxAgents = 2, softSlice, stallInterrupt = false, librarySour const sessions: { options: MathAgentOptions; message: string; notices: string[]; complete: () => void }[] = []; const events: { event: string; details?: Record }[] = []; const stateFile = path.join(directory, 'run-state.json'); - const makeTeam = (current: SolverRunState) => { + const makeTeam = (current: SolverRunState, afterSave?: (state: SolverRunState) => void) => { const team = new AgentResearchTeam({ state: current, root, taskText: 'Prove True.', leadAccess: { environment, retrievalRoot: path.join(current.worktree, problem.projectRelative), researchSkill: skill, libraryCatalog }, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: async options => { @@ -130,7 +138,8 @@ function fixture({ maxAgents = 2, softSlice, stallInterrupt = false, librarySour executable: 'offline-no-model', profile: 'offline-no-credentials', signal: controller.signal, maxAgents, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens, remainingMs: () => Infinity, softSlice, - save: () => writeSolverRunState(stateFile, current), emit: (event, details) => { events.push({ event, details }); }, + save: () => { writeSolverRunState(stateFile, current); afterSave?.(current); }, + emit: (event, details) => { events.push({ event, details }); }, exclusiveCheck: operation => operation(), }); teams.push(team); return team; @@ -157,7 +166,7 @@ function fixture({ maxAgents = 2, softSlice, stallInterrupt = false, librarySour const followup = (agentId: string, message: string, target = team) => native('send', { target: { kind: 'path', reference: '/root/' + agentId }, input: input(message), }, target); - const current = { directory, state, stateFile, controller, sessions, teams, team, makeTeam, call, spawn, followup, events, problem, + const current = { directory, state, stateFile, controller, sessions, teams, team, makeTeam, call, spawn, followup, events, problem, environment, skill, source: (worktree: string) => path.join(worktree, problem.projectRelative, 'Submission.lean'), session: async (index: number) => { await expect.poll(() => sessions[index]?.message, { timeout: 10_000 }).toBeTruthy(); return sessions[index]!; @@ -179,6 +188,25 @@ async function idle(team: AgentResearchTeam) { await expect.poll(() => team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); } +const downstream = 'theorem downstream : True := by exact helper\n'; + +async function registerDependentHelper(f: ReturnType) { + const { worktree } = f.state; + const evidenceDirectory = path.join(f.team.directory, 'proofs'); + const delivery = await withSolverWorktree(worktree, f.problem.baseCommit, async producer => { + const file = f.source(producer); + fs.writeFileSync(file, original.replace('theorem goal', helper + 'theorem goal')); + const seedCommit = commitSolverSources(f.problem, producer); + fs.writeFileSync(file, original.replace('theorem goal', helper + downstream + 'theorem goal')); + return checkAgentTeamProofDelivery({ state: f.state, worktree: producer, agentId: 'producer', seedCommit, + declarations: [{ file: 'Submission.lean', name: 'Recovery.downstream', type: 'True' }], + env: f.environment, signal: f.controller.signal, evidenceDirectory, assertWriterStopped: () => {} }); + }); + f.team.archive.deliveries.push({ id: delivery.id, agentId: 'producer', taskId: 'fixture', kind: 'helpers', + path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json') }); + return delivery.id; +} + describe('native team source handling', () => { it('exposes the pinned math library to a member and reserves installation requests for Lead', async () => { const source = 'namespace TeamFixture\ntheorem library_helper : True := by trivial\nend TeamFixture\n'; @@ -307,7 +335,7 @@ describe('native team source handling', () => { }); it('lands standalone helpers with the producer task open and installs them in a peer with unpublished work', async () => { - const f = fixture({ maxAgents: 3 }); + const f = fixture({ maxAgents: 3, libraryPack: shadowPack }); await f.spawn('retired', 'Route: discarded\nExplore this route.'); const retired = f.team.archive.workers[0]!; expect(await f.call({ operation: 'retire_route', routeId: 'discarded', reason: 'Close this independent route.', @@ -341,11 +369,15 @@ describe('native team source handling', () => { expect(consumer.tasks[0]!.status).toBe('running'); expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).not.toContain('theorem second'); b.complete(); await idle(f.team); + expect(f.team.archive.adoptions.some(item => item.targetId === consumer.id)).toBe(false); await f.team.close(); const saved = readSolverRunState(f.stateFile), restored = f.makeTeam(saved); await restored.restore(); expect(restored.archive.adoptions.some(item => item.targetId === retired.id)).toBe(false); + expect(restored.archive.adoptions.filter(item => item.targetId === consumer.id)).toEqual([ + expect.objectContaining({ status: 'completed', receiptId: expect.any(String) }), + ]); expect(git(retired.worktree, ['rev-parse', 'HEAD'])).toBe(retiredHead); expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain('theorem goal : True := by sorry'); const seeded = fs.readFileSync(f.source(consumer.worktree), 'utf8'); @@ -356,16 +388,268 @@ describe('native team source handling', () => { expect(next.message).toContain('landedHelpers'); expect(next.message).toContain('Recovery.second'); fs.writeFileSync(f.source(consumer.worktree), seeded.replaceAll('by sorry', 'by exact second')); - await f.call({ operation: 'submit', summary: 'Reused the verified helpers.', declarations: [ + expect(await f.call({ operation: 'submit', summary: 'Reused the verified helpers.', declarations: [ { ...declarations[0]!, name: 'Recovery.goal' }, { ...declarations[0]!, name: 'Recovery.draft' }, - ] }, 'peer', restored); + { ...declarations[0]!, name: '_root_.Recovery.helper' }, + ] }, 'peer', restored)).toMatchObject({ ok: true }); next.complete(); await idle(restored); - const delivery = restored.archive.deliveries.find(item => item.agentId === 'peer')!; - expect(readAgentTeamProofDelivery(delivery.path, saved).artifacts.map(item => item.declaration.name)) - .toEqual(['Recovery.helper', 'Recovery.second', 'Recovery.goal', 'Recovery.draft']); + const peer = restored.archive.workers.find(item => item.id === 'peer')!; + expect(peer.error).toBeUndefined(); + const delivery = restored.archive.deliveries.find(item => item.agentId === 'peer'); + expect(delivery, peer.tasks.at(-1)?.error).toBeDefined(); + const checked = readAgentTeamProofDelivery(delivery!.path, saved); + expect(checked.artifacts.map(item => item.declaration.name)) + .toEqual(['_root_.Recovery.helper', 'Recovery.second', 'Recovery.goal', 'Recovery.draft']); + expect(checked.inferredHelperTypes).toEqual(['Submission.lean\0Recovery.second']); expect(saved.check).toBeUndefined(); }, 60_000); + it.each([ + { reason: 'unqualified name', prerequisiteName: 'helper', problemSource: original, insertion: 'theorem goal', + diagnostic: 'Unknown identifier `helper`' }, + { reason: 'a tactic argument absent from the elaborated proof', prerequisiteName: 'helper', + problemSource: 'import Submission.Library.Shadow\n' + original, + insertion: 'theorem goal', diagnostic: 'Unknown identifier `helper`', tacticOnly: true }, + { reason: 'partially qualified name', prerequisiteName: 'Nested.helper', problemSource: original, insertion: 'theorem goal', + diagnostic: 'Unknown identifier `Nested.helper`' }, + { reason: 'missing patch anchor', prerequisiteName: 'helper', insertion: 'end Recovery', + problemSource: original + 'namespace Neighbor\ntheorem other : True := by sorry\nend Neighbor\n', + diagnostic: 'math_task_integration_missing_context' }, + ])('retries a blocked helper with $reason after its delayed prerequisite is adopted across a restored checkpoint', async ({ + prerequisiteName, problemSource, insertion, diagnostic, tacticOnly = false, + }) => { + const f = fixture({ maxAgents: 3, problemSource, libraryPack: tacticOnly ? shadowPack : undefined }); + await f.spawn('consumer', 'Keep this earlier workspace for later use.'); + const consumer = await f.session(0); + consumer.complete(); await idle(f.team); + const consumerFile = f.source(consumer.options.workspace); + + await f.spawn('producer', 'Prove the prerequisite.'); + const first = await f.session(1), producerFile = f.source(first.options.workspace); + const prerequisiteSource = `theorem ${prerequisiteName} : True := by trivial\n`; + const unrelated = 'theorem unrelated : True := by trivial\n'; + const proof = tacticOnly ? `\n have h : True := by simp [${prerequisiteName}]\n exact Shadow.helper` : 'exact ' + prerequisiteName; + const downstream = `theorem downstream : True := by ${proof}\n`; + const submit = async (session: typeof first, name: string, source: string, helpersOnly = false) => { + const anchor = name === 'unrelated' ? 'theorem goal' : insertion; + fs.writeFileSync(producerFile, fs.readFileSync(producerFile, 'utf8').replace(anchor, source + anchor)); + expect(await f.call({ operation: 'submit', helpersOnly, summary: 'Share ' + name, + declarations: [{ file: 'Submission.lean', name: 'Recovery.' + name, type: 'True' }] }, 'producer')) + .toMatchObject({ ok: true }); + session.complete(); await idle(f.team); + return f.team.archive.deliveries.at(-1)!; + }; + const prerequisite = await submit(first, prerequisiteName, prerequisiteSource); + await f.call({ operation: 'adopt', deliveryId: prerequisite.id }); + await f.team.flushAdoptions(); + expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain(prerequisiteSource); + await f.followup('producer', 'Prove an independent fact.'); + const irrelevant = await submit(await f.session(2), 'unrelated', unrelated); + await f.followup('producer', 'Share the consequence of the prerequisite.'); + const dependent = await submit(await f.session(3), 'downstream', downstream, true); + expect(dependent.kind).toBe('helpers'); + if (tacticOnly) { + const references = readAgentTeamProofDelivery(dependent.path, f.state).artifacts[0]!.references!; + expect([...references.statement, ...references.proof].some(({ name }) => name === 'Recovery.' + prerequisiteName)).toBe(false); + expect(references.proof).toContainEqual({ file: shadowFile, name: 'Shadow.helper' }); + } + + const attempts = (team: AgentResearchTeam) => team.archive.adoptions.filter( + item => item.targetId === 'consumer' && item.deliveryId === dependent.id); + await f.team.flushAdoptions('consumer'); + const [failed] = attempts(f.team); + expect(failed).toMatchObject({ status: 'failed', expectedCommit: f.problem.baseCommit, + error: expect.stringContaining(diagnostic), + missingDependencies: [{ file: 'Submission.lean', name: 'Recovery.' + prerequisiteName }] }); + expect(fs.readFileSync(consumerFile, 'utf8')).toBe(problemSource); + + await f.team.close(); + const saved = readSolverRunState(f.stateFile); + pinSolverResearchSkill(saved.problem, saved.worktree, f.skill); + let prerequisiteCheckpoint: SolverRunState | undefined; + const restored = f.makeTeam(saved, current => { + if (prerequisiteCheckpoint || !current.agentTeam!.adoptions.some(item => + item.targetId === 'consumer' && item.deliveryId === prerequisite.id && item.status === 'completed')) return; + prerequisiteCheckpoint = readSolverRunState(f.stateFile); + throw new Error('fixture interruption after the prerequisite was saved'); + }); + await restored.restore(); + expect(attempts(restored)).toEqual([failed]); + + const adopt = async (deliveryId: string) => { + expect(await f.call({ operation: 'adopt', deliveryId, targetId: 'consumer' }, 'lead', restored)) + .toMatchObject({ ok: true }); + await idle(restored); + }; + await adopt(irrelevant.id); + expect(fs.readFileSync(consumerFile, 'utf8')).toContain(unrelated); + expect(attempts(restored)).toEqual([failed]); + const priorEvents = restored.archive.events.length; + await adopt(prerequisite.id); + expect(fs.readFileSync(consumerFile, 'utf8')).not.toContain(downstream); + expect(prerequisiteCheckpoint).toBeDefined(); + const interrupted = prerequisiteCheckpoint!; + expect(interrupted.agentTeam!.adoptions.filter(item => item.targetId === 'consumer' && item.deliveryId === dependent.id)) + .toEqual([failed, expect.objectContaining({ status: 'queued' })]); + await restored.close(); + pinSolverResearchSkill(interrupted.problem, interrupted.worktree, f.skill); + const resumed = f.makeTeam(interrupted); + await resumed.restore(); + expect(attempts(resumed)).toEqual([failed, expect.objectContaining({ status: 'completed' })]); + expect(resumed.archive.events.slice(priorEvents).filter(event => event.to === 'consumer' && event.kind === 'adopted') + .map(event => event.deliveryId)).toEqual([prerequisite.id, dependent.id]); + const source = fs.readFileSync(consumerFile, 'utf8'); + expect(source).toContain(unrelated); + expect(source).toContain(prerequisiteSource); + expect(source).toContain(downstream); + expect(source).toContain('theorem goal : True := by sorry'); + }, 60_000); + + it.each(['committed', 'saved draft'] as const)('retries a blocked helper when Lead supplies its prerequisite in a %s', async sourceState => { + const f = fixture(), { worktree } = f.state, { baseCommit } = f.problem; + const leadFile = f.source(worktree); + const deliveryId = await registerDependentHelper(f); + await f.team.flushAdoptions(); + const [failed] = f.team.archive.adoptions; + expect(failed).toMatchObject({ status: 'failed', expectedCommit: baseCommit, + missingDependencies: [{ file: 'Submission.lean', name: 'Recovery.helper' }] }); + await f.team.close(); + + const saved = readSolverRunState(f.stateFile); + pinSolverResearchSkill(saved.problem, saved.worktree, f.skill); + const restored = f.makeTeam(saved); + const unrelated = original.replace('theorem goal', 'theorem unrelated : True := by trivial\ntheorem goal'); + fs.writeFileSync(leadFile, unrelated); + commitSolverSources(saved.problem, worktree); + await restored.restore(); + expect(restored.archive.adoptions).toEqual([failed]); + + fs.writeFileSync(leadFile, unrelated.replace('theorem goal', helper + 'theorem goal')); + if (sourceState === 'committed') commitSolverSources(saved.problem, worktree); + await restored.flushAdoptions(); + expect(readSolverRunState(f.stateFile).agentTeam!.adoptions).toEqual([failed, expect.objectContaining({ + deliveryId, targetId: 'lead', status: 'completed', receiptId: expect.any(String), + })]); + expect(fs.readFileSync(leadFile, 'utf8')).toBe(unrelated.replace('theorem goal', helper + downstream + 'theorem goal')); + }, 60_000); + + it.each(['followup', 'restore'] as const)('retries a blocked helper after the member supplies its prerequisite and yields, via %s', async entry => { + const f = fixture(); + await f.spawn('consumer', 'Work in the original workspace.'); + const first = await f.session(0), file = f.source(first.options.workspace); + const deliveryId = await registerDependentHelper(f); + first.complete(); await idle(f.team); + const repair = 'Supply the prerequisite in your own draft.'; + await expect(f.followup('consumer', repair)).rejects.toThrow('math_team_native_member_busy'); + await idle(f.team); + const attempts = (team: AgentResearchTeam) => team.archive.adoptions.filter( + item => item.targetId === 'consumer' && item.deliveryId === deliveryId); + const [failed] = attempts(f.team); + expect(failed).toMatchObject({ status: 'failed', expectedCommit: f.problem.baseCommit, + missingDependencies: [{ file: 'Submission.lean', name: 'Recovery.helper' }] }); + + await f.followup('consumer', repair); + const second = await f.session(1); + const localDraft = 'theorem localDraft : True := by exact helper\n'; + const draft = original.replace('theorem goal', helper + localDraft + 'theorem goal'); + fs.writeFileSync(file, draft); + expect(await f.call({ operation: 'yield', reason: 'The prerequisite is available.' }, 'consumer')) + .toMatchObject({ status: 'pending-writer-stop' }); + second.complete(); await idle(f.team); + const draftCommit = git(second.options.workspace, ['rev-parse', 'HEAD']); + expect(f.team.archive.workers[0]!.tasks.at(-1)).toMatchObject({ status: 'paused', sourceCommit: draftCommit }); + expect(draftCommit).not.toBe(f.problem.baseCommit); + expect(attempts(f.team)).toEqual([failed]); + + const continueProof = 'Use the adopted downstream fact.'; + let team = f.team; + if (entry === 'restore') { + await team.close(); + const saved = readSolverRunState(f.stateFile); + pinSolverResearchSkill(saved.problem, saved.worktree, f.skill); + team = f.makeTeam(saved); + await team.restore(); + } else { + await expect(f.followup('consumer', continueProof)).rejects.toThrow('math_team_native_member_busy'); + await idle(team); + } + expect(f.sessions).toHaveLength(2); + expect(attempts(team)).toEqual([failed, expect.objectContaining({ + status: 'completed', expectedCommit: draftCommit, receiptId: expect.any(String), + })]); + expect(fs.readFileSync(file, 'utf8')).toContain(localDraft); + expect(fs.readFileSync(file, 'utf8')).toContain(downstream); + + await f.followup('consumer', continueProof, team); + await f.session(2); + expect(fs.readFileSync(file, 'utf8')).toContain('theorem goal : True := by sorry'); + }, 60_000); + + it.each(['proof', 'declaration'] as const)('recovers the frozen Lead %s check before installing a later child helper', async pending => { + const f = fixture(), { state, environment, skill } = f; + await f.spawn('member', 'Prove the standalone helper.'); + const child = await f.session(0), worker = f.team.archive.workers[0]!; + const leadSource = f.source(state.worktree); + const leadFact = 'theorem leadFact : True := by trivial\n'; + const requestFile = path.join(state.worktree, '.scratch', DECLARATION_SUBMISSION_FILE); + const save = () => writeSolverRunState(f.stateFile, state); + const stopBeforeCheck = new Error('fixture interruption before declaration checking'); + const lifecycle = createSkillProofLifecycle({ state, worktree: state.worktree, environment, skill, + signal: f.controller.signal, writerStopped: () => true, sourceFeedback: () => undefined, + exclusiveCheck: async () => { throw stopBeforeCheck; }, + checkWhole: async () => { throw new Error('Whole-proof check belongs to the recovery.'); }, save, emit: () => {}, + }); + if (pending === 'proof') { + fs.writeFileSync(leadSource, original.replace('by sorry', 'by trivial')); + expect((await lifecycle.freezeSources()).wholeProofReady).toBe(true); + } else { + fs.writeFileSync(leadSource, original.replace('theorem goal', leadFact + 'theorem goal')); + fs.mkdirSync(path.dirname(requestFile), { recursive: true }); + fs.writeFileSync(requestFile, JSON.stringify({ + declarations: [{ file: 'Submission.lean', name: 'Recovery.leadFact', type: 'True' }], + })); + await expect(lifecycle.freezeSources()).rejects.toBe(stopBeforeCheck); + } + const frozenCommit = git(state.worktree, ['rev-parse', 'HEAD']); + expect(state.pendingProofCheck?.commit ?? state.pendingDeclarationCheck?.commit).toBe(frozenCommit); + + fs.writeFileSync(f.source(worker.worktree), original.replace('theorem goal', helper + 'theorem goal')); + expect(await f.call({ operation: 'submit', helpersOnly: true, declarations, summary: 'Reusable fact.' }, worker.id)) + .toMatchObject({ ok: true }); + child.complete(); await idle(f.team); await f.team.close(); + const restored = readSolverRunState(f.stateFile), delivery = restored.agentTeam!.deliveries[0]!; + expect(delivery.kind).toBe('helpers'); + expect(restored.agentTeam!.adoptions.some(item => item.targetId === 'lead')).toBe(false); + + const open = vi.fn(async () => { throw new Error('Recovery must not use a model.'); }); + const winner = await runResearchLead({ + state: restored, access: { environment, retrievalRoot: state.worktree, researchSkill: skill }, + modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, + root: process.cwd(), buildFile: path.join(f.directory, 'unused-build.json'), taskText: 'Prove True.', + executable: 'unused', profile: 'unused', signal: f.controller.signal, deadline: Infinity, + maxTurns: 0, maxTurnMs: Infinity, maxTotalTokens: 0, proofTimeoutMs: 30_000, + save: () => writeSolverRunState(f.stateFile, restored), emit: (event, details) => { f.events.push({ event, details }); }, + }); + expect(open).not.toHaveBeenCalled(); + expect(restored.pendingProofCheck).toBeUndefined(); + expect(restored.pendingDeclarationCheck).toBeUndefined(); + if (pending === 'proof') { + expect(winner?.check).toMatchObject({ passed: true, commit: frozenCommit }); + expect(git(restored.worktree, ['rev-parse', 'HEAD'])).toBe(frozenCommit); + expect(fs.readFileSync(leadSource, 'utf8')).not.toContain(helper); + } else { + expect(winner).toBeUndefined(); + const checked = f.events.findIndex(event => event.event === 'declarations_checked' && + event.details?.passed === true && event.details.commit === frozenCommit); + const adopted = f.events.findIndex(event => event.event === 'team_event' && event.details?.kind === 'adopted' && + event.details.to === 'lead' && event.details.deliveryId === delivery.id); + expect(checked).toBeGreaterThanOrEqual(0); + expect(adopted).toBeGreaterThan(checked); + expect(fs.readFileSync(leadSource, 'utf8')).toContain(helper); + expect(fs.readFileSync(leadSource, 'utf8')).toContain(leadFact); + } + }, 60_000); + it('rechecks the frozen standalone helper on restore after the verifier was unavailable', async () => { const f = fixture(); await f.spawn('member', 'Prove the helper.'); diff --git a/tests/declarationArtifacts.test.ts b/tests/declarationArtifacts.test.ts index c6302247..a6611b8b 100644 --- a/tests/declarationArtifacts.test.ts +++ b/tests/declarationArtifacts.test.ts @@ -5,14 +5,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { projectWebDeclarationArtifacts } from '../apps/web/declarationArtifacts'; import { bootstrapLeanTask } from '../src/math/leanTask'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; +import { MAX_LEAN_EXPECTED_TYPE_BYTES } from '../src/math/leanSyntax'; import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; +import { checkAgentTeamProofDelivery, integrateAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; import { writeSolverRunState } from '../src/solver/archive'; import { checkDeclarationArtifacts, DECLARATION_SUBMISSION_FILE, declarationSubmissionSchema, DeclarationSubmissionError, readDeclarationArtifacts, readDeclarationSubmission, validateDeclarationArtifact, writeDeclarationArtifacts, type DeclarationArtifact } from '../src/solver/declarationArtifacts'; -import { buildTheoremKnowledge } from '../src/solver/theoremKnowledge'; -import { importKnowledgeRuns } from '../src/solver/theoremKnowledgeRuns'; -import { commitSolverSources, git, readSolverProblem } from '../src/solver/problem'; +import { landVerifiedHelpers } from '../src/solver/incrementalHelpers'; +import { buildTheoremKnowledge, getKnowledgeConsumers } from '../src/solver/theoremKnowledge'; +import { createKnowledgeRelationIndex } from '../src/solver/theoremKnowledgeRelations'; +import { importKnowledgeRuns, importTeamKnowledgeDeliveries } from '../src/solver/theoremKnowledgeRuns'; +import { knowledgeTypeExpression } from '../src/solver/theoremKnowledgeSearch'; +import { commitSolverSources, git, readSolverProblem, withSolverWorktree } from '../src/solver/problem'; import { inspectStoredRun } from '../src/solver/storedRunInspection'; import { solverState } from './helpers/solver'; import { temporaryDirectory } from './helpers/files'; @@ -101,6 +106,15 @@ describe('declarations independent of a task graph', () => { expect(host.verify).not.toHaveBeenCalled(); }); + it('rejects an oversized UTF-8 type as submission feedback before starting the verifier', async () => { + const f = fixture(); + const type = '∀ n : Nat, /-' + 'é'.repeat(MAX_LEAN_EXPECTED_TYPE_BYTES / 2) + '-/ n = n'; + f.options.declarations[0]!.type = type; + expect(type.length).toBeLessThan(MAX_LEAN_EXPECTED_TYPE_BYTES); + await expect(checkDeclarationArtifacts(f.options)).rejects.toThrow(DeclarationSubmissionError); + expect(host.verify).not.toHaveBeenCalled(); + }); + it('marks a definition submitted as a theorem as correctable', async () => { const f = fixture('def reusable (n : Nat) : Nat := n\n'); await expect(checkDeclarationArtifacts(f.options)).rejects.toBeInstanceOf(DeclarationSubmissionError); @@ -331,26 +345,159 @@ describe('durable declaration archive growth', () => { }); describe('independent declaration checks with the real verifier and Lean', () => { - it.each([ - ['independent', 'theorem reusable (n : Nat) : n = n := by rfl\n', '∀ n : Nat, n = n', true, ''], - ['wrong type', 'theorem reusable (n : Nat) : n = n := by rfl\n', 'False', false, ''], - ['unproved original', 'theorem reusable : True := original\n', 'True', false, ''], - ['non-foundational axiom', 'theorem reusable : False := unjustified\n', 'False', false, 'axiom unjustified : False\n'], - ] as const)('accepts only a complete %s declaration with the requested full type', async (_kind, helper, type, passes, context) => { + async function realFixture(helper: string, context = '') { const f = fixture(helper, context); const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Lean 4.33.0 is required for declaration artifact regressions.'); const actual = await vi.importActual('../src/math/verifier'); host.verify.mockImplementation(actual.checkManyFormalVerifications); f.options.env = { ...f.options.env, PATH: `${toolchain}/bin:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap' }; + ELAN_HOME: toolchain, DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap' }; + return f; + } + + async function archiveStandaloneHelper(f: Awaited>, type: string) { + const { file, name } = f.declaration; + const { worktree, env, signal } = f.options, seedCommit = f.state.problem.baseCommit; + const landed = await landVerifiedHelpers({ state: f.state, worktree, sourceWorktree: worktree, + sourceCommit: f.commit, seedCommit, expectedCommit: seedCommit, declarations: [{ file, name, type }], env, signal }); + const runtime = path.join(f.directory, 'runtime'), evidenceDirectory = path.join(runtime, 'agent-team', 'proofs'); + const delivery = await withSolverWorktree(worktree, landed.commit, checkout => + checkAgentTeamProofDelivery({ state: f.state, worktree: checkout, agentId: 'producer', seedCommit, env, signal, + declarations: landed.declarations, inferredHelperTypes: ['Submission.lean\0Artifact.reusable'], + evidenceDirectory, assertWriterStopped: () => {} })); + f.state.agentTeam = { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], + operations: [], adoptions: [], deliveries: [{ id: delivery.id, taskId: 'helper', agentId: 'producer', kind: 'helpers', + path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json') }] }; + const stateFile = path.join(runtime, 'state.json'); writeSolverRunState(stateFile, f.state); + return importTeamKnowledgeDeliveries(stateFile, [delivery.id]).candidates[0]; + } + + it('captures and archives a kernel declaration near the submission byte limit', async () => { + const literal = JSON.stringify('é'.repeat(Math.floor((MAX_LEAN_EXPECTED_TYPE_BYTES - 7) / 4))); + const type = `${literal} = ${literal}`; + const f = await realFixture(`theorem reusable : ${type} := by rfl\n`); + f.declaration.type = type; + const [record] = await checkDeclarationArtifacts(f.options); + const result = record!.proof.verification.results[0]!; + expect(result.status).toBe('kernel_verified'); + expect(result.elaboratedDeclarationType?.match(/"[^"]*"/gu)).toEqual([literal, literal]); + expect(await archiveStandaloneHelper(f, type)).toMatchObject({ type, typeKind: 'closed-task-type' }); + }, 60_000); + + it('preserves whitespace inside string literals through standalone helper delivery and knowledge import', async () => { + const type = '"a b" = "a b"'; + const f = await realFixture(`theorem reusable : ${type} := by rfl\n`); + expect(await archiveStandaloneHelper(f, type)).toMatchObject({ type, typeKind: 'closed-task-type' }); + }, 60_000); + + it('exports deep declaration types without pretty-printer omissions', async () => { + const application = 'f ('.repeat(67) + 'x' + ')'.repeat(67); + const type = `∀ (f : Nat → Nat) (x : Nat), ${application} = ${application}`; + const f = await realFixture(`theorem reusable (f : Nat → Nat) (x : Nat) : ${application} = ${application} := by rfl\n`); + const entry = await archiveStandaloneHelper(f, type); + expect(entry.type).not.toContain('⋯'); + expect(entry.typeKind).toBe('closed-task-type'); + await expect(checkDeclarationArtifacts({ ...f.options, + declarations: [{ ...f.declaration, type: entry.type }] })).resolves.toHaveLength(1); + }, 60_000); + + it('checks and adopts root-qualified declaration names while preserving their receipt identity', async () => { + const f = await realFixture('theorem reusable (n : Nat) : n = n := by rfl\n'); + fs.writeFileSync(f.file, f.source.replace('by sorry', 'by trivial')); + const { state, worktree, env, signal } = f.options, seedCommit = state.problem.baseCommit; + const commit = commitSolverSources(state.problem, worktree); + const declarations = [ + { file: 'Submission.lean', name: '_root_.Artifact.original', type: 'True' }, + { file: 'Submission.lean', name: '_root_.Artifact.reusable', type: '_root_.Artifact.reusable (n : Nat) : n = n' }, + ]; + const common = { state, env, signal, evidenceDirectory: path.join(f.directory, 'proofs'), assertWriterStopped: () => {} }; + const delivery = await withSolverWorktree(worktree, commit, checkout => checkAgentTeamProofDelivery({ + ...common, worktree: checkout, agentId: 'producer', seedCommit, declarations, + })); + const adoption = await withSolverWorktree(worktree, seedCommit, checkout => integrateAgentTeamProofDelivery({ + ...common, worktree: checkout, expectedCommit: seedCommit, delivery, + })); + for (const artifacts of [delivery.artifacts, adoption.artifacts]) { + expect(artifacts.map(artifact => artifact.proof.verification.results[0])).toEqual(declarations.map(({ name }) => + expect.objectContaining({ theoremName: name, status: 'kernel_verified' }))); + expect(artifacts.map(artifact => artifact.references?.root.name)).toEqual(declarations.map(({ name }) => name)); + } + }, 60_000); + + it('joins archived proof references to a root-qualified entry in both directions', async () => { + const f = await realFixture('theorem reusable : True := by trivial\ntheorem downstream : True := reusable\n'); + const [helper, consumer] = [ + { file: 'Submission.lean', name: '_root_.Artifact.reusable', type: 'True' }, + { file: 'Submission.lean', name: 'Artifact.downstream', type: 'True' }, + ]; + const artifacts = await checkDeclarationArtifacts({ ...f.options, declarations: [helper, consumer] }); + expect(artifacts[1]!.references?.proof).toContainEqual({ file: helper.file, name: 'Artifact.reusable' }); + const output = path.join(f.directory, 'runtime'); + fs.mkdirSync(output, { mode: 0o700 }); + writeDeclarationArtifacts(output, f.state, artifacts); + const stateFile = path.join(output, 'state.json'); writeSolverRunState(stateFile, f.state); + const imported = importKnowledgeRuns([stateFile]); + expect(imported.skipped).toEqual([]); + const base = buildTheoremKnowledge(imported.candidates); + const root = base.entries.find(entry => entry.name === helper.name)!; + const downstream = base.entries.find(entry => entry.name === consumer.name)!; + const index = createKnowledgeRelationIndex(base); + expect(index.expand([downstream.id], 4)).toMatchObject({ unresolved: [], + relations: [{ entryId: root.id, direction: 'dependency', kind: 'proof' }] }); + expect(index.expand([root.id], 4)).toMatchObject({ unresolved: [], + relations: [{ entryId: downstream.id, direction: 'consumer', kind: 'proof' }] }); + expect(getKnowledgeConsumers(base, root.id)).toMatchObject({ total: 1, + consumers: [{ id: downstream.id, uses: ['proof-use'] }] }); + }, 60_000); + + it.each([ + ['independent', 'theorem reusable (n : Nat) : n = n := by rfl\n', '∀ n : Nat, n = n', true, ''], + ['pasted signature', 'theorem reusable {α : Type} [DecidableEq α] (x : α) : x = x := by rfl\n', + '{α : Type} [DecidableEq α]\n (x : α) : x = x', true, ''], + ['qualified check output', 'theorem reusable (n : Nat) : n = n := by rfl\n', + 'Artifact.reusable (n : Nat) : n = n', true, ''], + ['root-qualified check output', 'theorem reusable (n : Nat) : n = n := by rfl\n', + '_root_.Artifact.reusable (n : Nat) : n = n', true, ''], + ['universe-annotated check output', 'theorem reusable.{u} {α : Type u} (x : α) : x = x := by rfl\n', + 'Artifact.reusable.{v} {α : Type v} (x : α) : Eq.{v + 1} x x', true, ''], + ['incorrect universe arity', 'theorem reusable.{u} {α : Type u} (x : α) : x = x := by rfl\n', + 'Artifact.reusable.{u, v} {α : Type u} (x : α) : x = x', false, '', /different universe parameters/u], + ['specialized universe', 'theorem reusable.{u} {α : Type u} (x : α) : x = x := by rfl\n', + '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, ''], + ['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', + '(n : Nat) : n = 0', false, '', /different type or additional assumptions/u], + ['different declaration name', 'theorem reusable (n : Nat) : n = n := by rfl\n', + 'Artifact.other (n : Nat) : n = n', false, '', /Invalid expected declaration type/u], + ['wrong type', 'theorem reusable (n : Nat) : n = n := by rfl\n', 'False', false, ''], + ['unproved original', 'theorem reusable : True := original\n', 'True', false, ''], + ['non-foundational axiom', 'theorem reusable : False := unjustified\n', 'False', false, 'axiom unjustified : False\n'], + ] as const)('accepts only a complete %s declaration with the requested full type', async (_kind, helper, type, passes, context, failure?) => { + const f = await realFixture(helper, context); f.options.declarations[0]!.type = type; const result = checkDeclarationArtifacts(f.options); if (passes) { const records = await result; expect(records[0]!.proof.verification.results[0]).toMatchObject({ status: 'kernel_verified', sorryCount: 0, admitCount: 0, elaboratedDeclarationType: expect.any(String) }); - } else await expect(result).rejects.toThrow(); + if (_kind === 'qualified check output' || _kind === 'universe-annotated check output') { + const output = path.join(f.directory, 'runtime'); + fs.mkdirSync(output, { mode: 0o700 }); + writeDeclarationArtifacts(output, f.state, records); + const stateFile = path.join(output, 'state.json'); writeSolverRunState(stateFile, f.state); + const entry = importKnowledgeRuns([stateFile]).candidates[0]!; + if (_kind === 'qualified check output') { + expect(entry).toMatchObject({ type: '∀ (n : Nat), n = n', typeKind: 'closed-task-type' }); + } else { + expect(entry).toMatchObject({ type, typeKind: 'source-header' }); + expect(knowledgeTypeExpression(entry)).toBe('∀ {α : Type v} (x : α), Eq.{v + 1} x x'); + } + } + } else await expect(result).rejects.toThrow(failure); expect(fs.readFileSync(f.file, 'utf8')).toBe(f.source); }, 60_000); }); diff --git a/tests/leanTypeDiagnostics.test.ts b/tests/leanTypeDiagnostics.test.ts index 7cf766e8..d208d4c3 100644 --- a/tests/leanTypeDiagnostics.test.ts +++ b/tests/leanTypeDiagnostics.test.ts @@ -3,6 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { checkLeanType, leanTypeDiagnosticCommands, leanTypeDiagnosticProjection } from '../src/math/leanTypeDiagnostics'; +import { MAX_LEAN_EXPECTED_TYPE_BYTES } from '../src/math/leanSyntax'; import { mathLocalModuleBuildOrder } from '../src/math/mathConstructionSources'; import { runLeanProcess } from '../src/math/mathProcess'; import { mathDigest } from '../src/math/mathRuntimeIo'; @@ -75,6 +76,21 @@ describe.skipIf(!lean)('local Lean closed-type preflight', () => { afterEach(() => fs.rmSync(root, { recursive: true, force: true })); const check = (type: string) => checkLeanType({ projectRoot: root, file: 'Submission.lean', context: 'Geometry.original', type, timeoutMs: 30_000 }); + it('preflights a type at the declaration byte limit and rejects one byte more before Lean', async () => { + const type = 'True /-' + 'é'.repeat((MAX_LEAN_EXPECTED_TYPE_BYTES - Buffer.byteLength('True /- -/')) / 2) + ' -/'; + expect(Buffer.byteLength(type)).toBe(MAX_LEAN_EXPECTED_TYPE_BYTES); + const task: CooperativeTask = { id: 'helper', kind: 'lemma', objective: 'Prove helper', dependsOn: [], revision: 0, + theoremName: 'Geometry.helper', proofPath: 'Submission.lean', type }; + const problem = { targets: [{ theoremName: 'Geometry.original', proofPath: 'Submission.lean' }] } as SolverProblem; + const { result } = await new TaskTypePreflightCache().check({ task, problem, dependencies: [], projectRoot: root, + environmentDigest: 'test-environment', env: { DEEPSCIENTIST_MATH_ENV_FILE: path.join(root, 'fixture.env') }, timeoutMs: 30_000 }); + expect(result.status, result.reason).toBe('elaborated'); + expect(result.type).toBe('True'); + const commands = run.mock.calls.length; + await expect(check(type.replace(' -/', 'x -/'))).rejects.toThrow('math_type_diagnostics_input_invalid'); + expect(run).toHaveBeenCalledTimes(commands); + }); + it('prepares missing local dependencies, restores open scopes, and preserves active source and proof artifacts', async () => { const before = fs.readFileSync(path.join(root, 'Submission.lean')); const modules = mathLocalModuleBuildOrder(root, 'Submission.lean');