From 868e8222b4024282318a2456716d722d9aef5268 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:05:03 +0800 Subject: [PATCH] Try the tactic battery on submitted sorry helpers Since #52 the host tactic battery had no caller. The native team now runs it on each declared theorem whose body still contains `sorry` or `admit`, against the exact submitted type, before the ordinary Lean check of a helper submission or of the first check of a proof delivery. A closure is written and committed in the stopped writer's worktree and the member is told; the ordinary check still decides acceptance. A failed or unavailable attempt leaves the submission unchanged. All declarations of one submission share a single 120 s bound. `grind` is appended last to the battery and to the vacuity probe when the project's lean-toolchain is v4.24 or newer. The M2 version gains `submitted-helper-tactic-battery-v1` and `battery-grind-v1`, so the pinned method digests are refreshed. The standalone sorry-helper rejection test now uses a `False` helper, since the battery closes `True`. Co-Authored-By: Claude Opus 5.5 --- src/solver/agentTeam.ts | 75 +++++++++++++++++++++++++- src/solver/modules/moduleIdentity.ts | 2 +- src/solver/tacticBattery.ts | 34 ++++++++---- tests/agentTeamNativeLifecycle.test.ts | 49 ++++++++++++++++- tests/agentTeamSourceRecovery.test.ts | 6 ++- tests/tacticBattery.test.ts | 33 +++++++++++- tests/webModuleIdentity.test.ts | 20 +++---- 7 files changed, 191 insertions(+), 28 deletions(-) diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index bebe6971..98da5a93 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -8,7 +8,7 @@ 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 { inspectLeanSource, inspectScopedLeanDeclarations } from '../math/leanSource'; import { leanNameWithoutRoot } from '../math/leanSyntax'; import type { SolverRunState } from './archive'; import type { WorkerAccess } from './research'; @@ -22,6 +22,9 @@ import { solverSourceDigest } from './modules/evidence'; import { writeOwnedDeclarationIndex } from './declarationIndex'; import { recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter'; import { prepareTacticBatteryFailureCacheRoot } from './tacticBatteryFailureCache'; +import { TACTIC_BATTERY_TIMEOUT_MS } from './tacticBattery'; +import { locateKnowledgeDeclaration } from './theoremKnowledge'; +import type { CooperativeTask } from './tasks'; import { ResearchUsage } from './researchUsage'; import { aggregateUsage, buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; import { agentTeamStateSchema, @@ -1121,8 +1124,9 @@ export class AgentResearchTeam { const { state } = this.input; try { assertWriterStopped(); - const sourceCommit = task.sourceCommit ?? commitSolverSources(state.problem, worker.worktree); await this.input.exclusiveCheck(async () => { + const closed = await this.closeSubmittedSorries(worker, task, nominations, access.environment, signal, assertWriterStopped); + const sourceCommit = closed || !task.sourceCommit ? commitSolverSources(state.problem, worker.worktree) : task.sourceCommit; const expectedCommit = this.archive.canonicalCommit ?? git(state.worktree, ['rev-parse', 'HEAD']); const result = await landVerifiedHelpers({ state, worktree: state.worktree, expectedCommit, sourceWorktree: worker.worktree, sourceCommit, seedCommit: task.seedCommit ?? worker.seedCommit, @@ -1180,6 +1184,67 @@ export class AgentResearchTeam { } } + /** + * Before the Lean check of a submission, try the fixed tactic battery on each nominated theorem whose body is still + * `sorry` or `admit`, against its exact submitted type. A closure is written into the stopped writer's sources and + * committed there; the ordinary check still decides acceptance. A failed or unavailable attempt changes nothing. + * Returns whether any source changed. + */ + private async closeSubmittedSorries(worker: AgentTeamWorker, task: AgentTeamTask, + declarations: readonly { file?: string; name?: string; type?: string; kind?: 'definition' }[], env: NodeJS.ProcessEnv, + signal: AbortSignal, assertWriterStopped: () => void): Promise { + const closeTask = this.input.modules.M2.closeTask, { problem } = this.input.state; + if (!closeTask) return false; + // One shared bound per submission, so several open helpers cannot multiply the host delay. + const deadline = Date.now() + Math.min(this.input.proofTimeoutMs ?? Infinity, TACTIC_BATTERY_TIMEOUT_MS); + let changed = false; + for (const declaration of declarations) { + const remaining = deadline - Date.now(); + if (remaining <= 0) break; + const { file, name, type } = declaration; + if (declaration.kind === 'definition' || !file || !name || !type || !problem.ownedFiles.includes(file)) continue; + const relative = path.join(problem.projectRelative, file); + let theoremName: string; + try { + const source = fs.readFileSync(path.join(worker.worktree, relative), 'utf8'); + const located = locateKnowledgeDeclaration(source, name); + const body = inspectLeanSource(source.slice(located.bodyOffset, located.endOffset)); + if (located.kind !== 'theorem' || !body.sorryCount && !body.admitCount) continue; + theoremName = located.qualifiedName; + } catch { continue; } + assertWriterStopped(); + let seedCommit: string; + try { seedCommit = commitSolverSources(problem, worker.worktree); } catch { break; } + const helper: CooperativeTask = { id: 'submitted-helper', kind: 'lemma', objective: 'Close submitted helper ' + theoremName, + proofPath: file, theoremName, type, dependsOn: [], revision: 0 }; + const started = Date.now(); + const battery = await closeTask({ problem, task: helper, worktree: worker.worktree, seedCommit, context: theoremName, + env, signal, timeoutMs: remaining }); + signal.throwIfAborted(); + let applied = false; + if (battery.status === 'closed' && battery.commit) { + assertWriterStopped(); + fs.writeFileSync(path.join(worker.worktree, relative), committedSource(worker.worktree, battery.commit, relative)); + commitSolverSources(problem, worker.worktree); + applied = changed = true; + } + this.input.emit('task_tactic_battery', { taskId: task.id, workerId: worker.id, declaration: theoremName, seedCommit, + status: battery.status, reason: battery.reason, durationMs: Date.now() - started, applied, + ...(battery.cacheHit ? { cacheHit: true, cacheKey: battery.cacheKey, originDiagnosticDigest: battery.originDiagnosticDigest } : {}), + ...(battery.commit ? { commit: battery.commit } : {}), ...(battery.artifact ? { artifact: battery.artifact } : {}), + ...(battery.vacuous ? { vacuous: true } : {}) }); + if (applied) { + const vacuity = battery.vacuous ? ' Host vacuity probe: its hypotheses alone derive False, so no consumer can discharge them; ' + + 'revise the helper unless it is an intended impossible case.' : ''; + this.event(null, worker.id, 'message', 'The host tactic battery closed the sorry in ' + theoremName + + ' against its submitted type, and your source now contains that proof. The ordinary Lean check still decides the submission.' + vacuity, + { taskId: task.id }); + if (battery.vacuous) this.event(null, 'lead', 'message', worker.id + ' submitted ' + theoremName + '.' + vacuity, { taskId: task.id }); + } + } + return changed; + } + private async finishDelivery(worker: AgentTeamWorker) { await this.closeNativeIdle(worker); const pending = worker.pendingDelivery; @@ -1200,6 +1265,12 @@ export class AgentResearchTeam { })); // 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)); + // A recorded commit is a retry of the same sources; the battery only runs before the first check. + if (!pending.commit && task.declarations?.length) await this.input.exclusiveCheck(() => this.closeSubmittedSorries(worker, task, + task.declarations!, access.environment, signal, () => { + signal.throwIfAborted(); + if (worker.writerStopUnconfirmed || this.live.get(worker.id)?.session) throw new Error('math_writer_stop_unconfirmed:' + worker.id); + })); 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'); diff --git a/src/solver/modules/moduleIdentity.ts b/src/solver/modules/moduleIdentity.ts index 2219fa1d..ffc57e73 100644 --- a/src/solver/modules/moduleIdentity.ts +++ b/src/solver/modules/moduleIdentity.ts @@ -8,7 +8,7 @@ export const directSolverModuleIdentity: SolverModuleIdentity = { id: 'direct-v1', versions: { M1: 'bounded-codex-turn-v15/distinct-recovery-delivery-v1/provider-diagnostics-v1/saved-plan-recovery-v1/closed-writer-ownership-v1/advisory-draft-recovery-v1/session-admission-v1/closed-statement-ownership-v1/feasibility-session-v1/observed-turn-ledger-v1/session-scoped-usage-v1/persistent-provider-cooldown-v1/context-overflow-recovery-v1/initial-planning-budget-v1/trusted-local-stop-v1/initial-plan-publication-v1/observed-knowledge-use-v1/diagnostic-log-ownership-v1/turn-ledger-removed-v1/advisory-scratch-ownership-v1/durable-reasoning-checkpoint-v1/lead-thread-continuation-v1/bounded-coordination-checkpoints-v1/live-saved-context-yield-v1/published-context-checkpoint-v1/compaction-aware-checkpoints-v1/cooperative-stray-quarantine-v1/bounded-proof-search-v1/installed-library-before-model-v1/installed-library-reference-observation-v1/agent-library-request-v1/context-proof-ready-handoff-v1/scoped-research-save-notice-v1/early-initial-plan-notice-v1/scoped-advisory-backoff-v1/conditional-connection-checkpoints-v1/sent-responsibility-context-v1/checkpoint-research-handoff-v1/durable-research-handoff-wait-v1/retained-notes-attribution-v1/feasibility-notice-only-handoff-v1/host-library-before-research-v1/final-review-checkpoint-v1', - M2: 'lean-kernel-v14/declaration-prefix-projection-v1/task-root-references-v1/conditional-child-changes-v1/scoped-conditional-projection-v1/exact-input-failure-reuse-v1/conditional-projection-identity-v1/attributed-batch-evidence-v1/fixed-candidate-references-v1/exact-projection-cache-v1/shared-source-index-v1/host-consumer-connection-v1/content-projection-reuse-v1/ready-integration-batches-v1/coded-lean-diagnostics-v1/live-exact-projection-recheck-v1/lean-diagnostic-word-classification-v1/advisory-scratch-checkout-v1/host-tactic-battery-v1/definition-tasks-v1/battery-vacuity-probe-v1/untouched-seed-request-failure-v1/isolated-module-builds-v1/frozen-library-modules-v1/host-family-assembly-v1/projection-dependency-diagnostics-v1/installed-library-application-v1/installed-library-candidate-pool-v1/installed-library-iff-application-v1/installed-library-equality-application-v1/installed-library-named-requests-v1/installed-library-rewrite-v1/installed-library-lemma-pool-v1/installed-library-premise-application-v1/installed-library-premise-retrieval-v1/installed-library-fair-premise-pool-v1/installed-library-composed-applications-v1/import-closure-diagnostics-cache-v1/proof-import-before-theorem-v1/typed-helper-command-rejection-v1/installed-library-conclusion-relevance-v1/notation-source-inputs-v1/implicit-instance-cleanup-v1/persistent-tactic-failure-reuse-v1/notation-quotation-context-v1/static-notation-analysis-v1/conditional-source-context-v1/universe-polymorphic-conditional-projection-v1/original-definition-kind-canonical-check-v1/conditional-lemma-macro-normalization-v1', + M2: 'lean-kernel-v14/declaration-prefix-projection-v1/task-root-references-v1/conditional-child-changes-v1/scoped-conditional-projection-v1/exact-input-failure-reuse-v1/conditional-projection-identity-v1/attributed-batch-evidence-v1/fixed-candidate-references-v1/exact-projection-cache-v1/shared-source-index-v1/host-consumer-connection-v1/content-projection-reuse-v1/ready-integration-batches-v1/coded-lean-diagnostics-v1/live-exact-projection-recheck-v1/lean-diagnostic-word-classification-v1/advisory-scratch-checkout-v1/host-tactic-battery-v1/definition-tasks-v1/battery-vacuity-probe-v1/untouched-seed-request-failure-v1/isolated-module-builds-v1/frozen-library-modules-v1/host-family-assembly-v1/projection-dependency-diagnostics-v1/installed-library-application-v1/installed-library-candidate-pool-v1/installed-library-iff-application-v1/installed-library-equality-application-v1/installed-library-named-requests-v1/installed-library-rewrite-v1/installed-library-lemma-pool-v1/installed-library-premise-application-v1/installed-library-premise-retrieval-v1/installed-library-fair-premise-pool-v1/installed-library-composed-applications-v1/import-closure-diagnostics-cache-v1/proof-import-before-theorem-v1/typed-helper-command-rejection-v1/installed-library-conclusion-relevance-v1/notation-source-inputs-v1/implicit-instance-cleanup-v1/persistent-tactic-failure-reuse-v1/notation-quotation-context-v1/static-notation-analysis-v1/conditional-source-context-v1/universe-polymorphic-conditional-projection-v1/original-definition-kind-canonical-check-v1/conditional-lemma-macro-normalization-v1/submitted-helper-tactic-battery-v1/battery-grind-v1', M3: 'route-budget-v12/blocker-or-routes-v1/structured-provider-failure-v1/assignable-work-v1/advisory-settlement-v3/goal-scoped-advancement-v1/early-route-checks-v1/ready-consumers-v1/evidence-ranked-routes-v2/capacity-free-ranking-v1/active-or-frontier-v1/context-overflow-recovery-v1/pending-validation-v1/trusted-local-stop-v1/host-consumer-connection-v1/definition-task-readiness-v1/scoped-next-checks-v1/yielded-advisory-proof-frontier-v1/consumer-goal-attribution-v1/fixed-review-requests-v1', M4: 'task-interface-context-v31/original-goal-frontier-v3/finished-objective-refs-v1/work-contract-v2/research-handoff-batches-v3/resume-drafts-v1/assignment-knowledge-hints-v1/deferred-handoff-inputs-v1/mathematical-route-planning-v1/complete-research-findings-v1/consumer-interfaces-v1/current-feedback-v1/complete-checkpoints-v1/early-feasibility-v1/parallel-questions-v2/local-attempt-feedback-v1/compact-handoff-sources-v1/exact-interface-diversity-v1/bounded-route-focus-v1/compact-inline-manifest-v1/adopted-research-use-v1/bounded-knowledge-metadata-v1/interface-idf-v1/overflow-optional-budget-v1/initial-planning-budget-v1/required-research-challenges-v1/initial-plan-publication-v1/scoped-route-findings-v1/observed-knowledge-use-v1/lean-json-diagnostics-v1/host-consumer-connection-v1/finite-boolean-evidence-v1/live-research-publication-v1/current-residual-goal-v1/continuation-attachments-v1/accepted-consumer-knowledge-v1/single-delivery-protocol-v1/route-focused-knowledge-v1/independent-goal-knowledge-batch-v1/route-finding-batch-v1/primary-led-removed-v1/assigned-proof-only-diagnostics-v1/lean-prover-v1/host-capacity-exploration-v1/explicit-handoff-publication-v1/advisory-scratch-roots-v1/exact-gap-checkpoint-context-v1/lead-continuation-context-v1/shared-new-helper-ownership-v1/compact-proof-role-context-v1/precise-gap-correction-context-v1/full-plan-adoption-context-v1/coordination-first-context-v1/explicit-research-source-context-v1/short-challenge-assessments-v1/live-plan-rejection-feedback-v1/request-scoped-checkpoint-feedback-v1/worker-checkpoint-feedback-v1/lead-planning-inputs-v1/plan-revision-context-v1/lead-inbox-context-v1/definition-task-context-v1/reference-search-context-v1/definition-knowledge-context-v1/math-tools-context-v1/kernel-certificates-v1/goal-path-review-v1/blueprint-fields-v1/theory-modules-v1/definition-sanity-lemmas-v1/goal-path-decisions-context-v1/owned-declaration-index-v1/library-packs-v1/task-families-v1/team-progress-review-context-v1/source-dependency-review-context-v1/atomic-observations-and-application-hints-v1/scoped-relation-pool-v1/executable-next-check-v1/proof-search-context-v1/installed-library-retrieval-v1/installed-library-application-context-v1/reusable-knowledge-index-v1/installed-library-named-requests-v1/conclusion-focused-knowledge-v1/agent-full-library-context-v1/critical-premise-context-v1/executable-initial-plan-context-v1/bounded-owned-declaration-lookup-v1/continuation-query-batches-v1/critical-inference-guidance-v1/plan-connection-guidance-v1/warm-lead-plan-rejection-v1/host-library-context-revalidation-v1/knowledge-candidate-refill-v1/mathematical-knowledge-ranking-v1/scoped-finding-relevance-v1/decorated-quantifier-fallback-v1/bounded-mathematical-reference-recall-v1/review-independence-context-v1/optional-final-review-context-v1/fixed-review-questions-v1', M5: 'route-cooperation-v33/persistent-failed-input-v1/continuous-frontier-input-v1/research-handoff-batches-v3/assignable-work-v1/resumable-lead-drafts-v1/assignment-deliveries-v1/scoped-research-drafts-v1/review-dispatches-v1/recoverable-delivery-cursors-v1/recoverable-human-edits-v1/recoverable-proof-integration-v1/deferred-handoff-reactivation-v1/concurrent-frontier-recovery-v1/complete-research-findings-v1/consumer-interface-projection-v1/independent-feasibility-v1/ranked-assignment-v1/local-checkpoint-evidence-v1/stable-handoff-inputs-v1/local-attempt-identity-v1/exact-inflight-questions-v1/description-source-recheck-v1/conditional-restore-v1/live-capacity-exploration-v1/snapshot-statement-review-reuse-v1/concurrent-merged-check-v1/adopted-research-use-v1/fixed-candidate-statement-scope-v1/semantic-dependency-review-v1/nonblocking-plan-validation-v1/exact-projection-cache-v1/required-research-challenges-v1/initial-plan-publication-v1/observed-knowledge-use-v1/host-consumer-connection-v1/live-research-publication-v1/typed-helper-preflight-v1/stale-preflight-cancellation-v1/type-projection-preflight-reuse-v1/stale-plan-recheck-stop-v1/shared-statement-preparation-v1/scoped-statement-types-v1/empty-route-list-v1/route-evidence-obligations-v1/primary-led-removed-v1/source-contract-local-repair-v1/unlimited-dispatch-recovery-v1/assignment-condition-snapshot-v1/conditional-dependency-order-v1/original-goal-capacity-coverage-v1/assigned-source-diagnostic-preflight-v1/current-batch-projection-v1/stalled-plan-continuous-recovery-v1/actual-dependency-invalidation-v1/lean-prover-v1/host-capacity-exploration-v1/explicit-handoff-publication-v1/semantic-lead-checkpoints-v1/continuation-handoff-provenance-v1/advisory-stagnation-recovery-v1/explicit-mathematical-gap-recovery-v1/shared-responsibility-assessment-v1/recorded-dispatch-waits-v1/full-plan-explicit-adoption-v1/scoped-delivery-correction-chain-v1/legacy-research-without-finding-v1/research-source-snapshots-v1/source-bound-mathematical-gap-v1/large-delivery-lines-v1/executable-work-assessment-v1/lead-planning-only-v1/plan-revision-patches-v1/lead-inbox-v1/stopped-worker-release-v1/definition-task-dependencies-v1/goal-path-stall-wake-v1/goal-path-answer-coverage-v1/substantive-goal-path-decisions-v1/source-dependency-connect-v1/active-goal-progress-review-v1/executable-goal-review-v1/host-search-checkpoint-v1/executable-next-check-v1/installed-library-dispatch-v1/ascii-forall-statement-shapes-v1/missing-declaration-environment-stability-v1/fresh-goal-progress-v1/missing-research-delivery-recovery-v1/superseded-reservation-release-v1/reseeded-connection-permission-v1/question-bound-advisory-blockers-v1/plan-helper-type-contract-v1/library-probe-advisory-feedback-v1/conditional-research-screening-v1/typed-connection-draft-resume-v1/task-draft-continuation-v1/checkpoint-research-handoff-v1/canonical-dependency-snapshots-v1/verified-canonical-publication-v1/saved-research-transfer-v1/retained-notes-attribution-v1/host-definition-contract-checks-v1/negative-outcome-decisions-v1/definite-type-parser-errors-v1/retained-source-input-discovery-isolation-v1/source-bound-feasibility-drafts-v1/lead-plan-rejection-inbox-v1/checkpointed-connection-prerequisite-yield-v1/fresh-conditional-continuation-reuse-v1/frozen-import-preflight-v1/successor-checked-proof-handoff-v1/final-review-priority-v1/optional-final-review-v1/consumer-finding-notice-v1/fixed-review-requests-v1', diff --git a/src/solver/tacticBattery.ts b/src/solver/tacticBattery.ts index c58e8ac1..f354ea5a 100644 --- a/src/solver/tacticBattery.ts +++ b/src/solver/tacticBattery.ts @@ -19,9 +19,15 @@ const CORE_TACTICS = ['rfl', 'trivial', 'omega', '(simp; done)', '(intros; simp_ const MATHLIB_TACTICS = ['(intros; norm_num; done)', '(intros; linarith)', '(intros; positivity)', '(intros; ring_nf; done)', 'tauto', '(intros; aesop; done)']; -/** The battery is fixed bytes; a project without Mathlib cannot parse its tactic names. */ -export function tacticBatteryProof(mathlib: boolean): string { - return `by first | ${[...CORE_TACTICS, ...(mathlib ? MATHLIB_TACTICS : [])].join(' | ')}`; +// `grind` goes last: it is the costliest to fail, and every earlier alternative keeps its prior cost and order. +const GRIND = 'grind'; + +/** + * The battery is fixed bytes. A project without Mathlib cannot parse its tactic names, and a toolchain without + * `grind` rejects the whole `first` block as an unknown tactic. + */ +export function tacticBatteryProof(mathlib: boolean, grind = false): string { + return `by first | ${[...CORE_TACTICS, ...(mathlib ? MATHLIB_TACTICS : []), ...(grind ? [GRIND] : [])].join(' | ')}`; } // Each alternative must close `False` from the introduced hypotheses alone. @@ -32,9 +38,17 @@ const MATHLIB_CONTRADICTIONS = ['linarith', '(norm_num at *; done)', 'tauto', '( * Proves the type only by deriving `False` from its introduced hypotheses. A type whose conclusion is * already `False` asks for a refutation, so the guard keeps that from being reported as vacuous. */ -export function vacuityProbeProof(mathlib: boolean): string { +export function vacuityProbeProof(mathlib: boolean, grind = false): string { return 'by intros; (fail_if_success guard_target =ₛ False); exfalso; first | ' + - [...CORE_CONTRADICTIONS, ...(mathlib ? MATHLIB_CONTRADICTIONS : [])].join(' | '); + [...CORE_CONTRADICTIONS, ...(mathlib ? MATHLIB_CONTRADICTIONS : []), ...(grind ? [GRIND] : [])].join(' | '); +} + +/** `grind` is checked on Lean 4.24.0 through 4.36.0; an unreadable, unrecognized or older toolchain omits it. */ +export function toolchainHasGrind(projectRoot: string): boolean { + let toolchain: string; + try { toolchain = fs.readFileSync(path.join(projectRoot, 'lean-toolchain'), 'utf8').trim(); } catch { return false; } + const match = /^leanprover\/lean4:v(\d+)\.(\d+)\.\d+(?:-rc\d+)?$/u.exec(toolchain); + return !!match && (Number(match[1]) > 4 || (Number(match[1]) === 4 && Number(match[2]) >= 24)); } function importsMathlib(projectRoot: string, file: string): boolean { @@ -100,8 +114,8 @@ export async function closeTaskByTactics(input: { problem: SolverProblem; task: if (task.kind !== 'lemma' || isDefinitionTask(task) || !task.type?.trim() || !task.proofPath || !task.theoremName) return { ...base, status: 'skipped', reason: 'not-typed-lemma' }; const project = path.join(input.worktree, problem.projectRelative); - const mathlib = importsMathlib(project, task.proofPath); - const proof = tacticBatteryProof(mathlib), started = Date.now(); + const mathlib = importsMathlib(project, task.proofPath), grind = toolchainHasGrind(project); + const proof = tacticBatteryProof(mathlib, grind), started = Date.now(); let edited: string | undefined; try { edited = tacticBatterySource(problem, committedSource(input.worktree, input.seedCommit, @@ -151,7 +165,7 @@ export async function closeTaskByTactics(input: { problem: SolverProblem; task: return commitSolverSources(problem, checkout); }); } catch { return { ...base, status: 'unavailable', reason: 'candidate-commit-unavailable', artifact: checked.artifact }; } - const vacuous = await contradictoryHypotheses(project, task, input, mathlib, input.timeoutMs - (Date.now() - started)); + const vacuous = await contradictoryHypotheses(project, task, input, mathlib, grind, input.timeoutMs - (Date.now() - started)); return { ...base, status: 'closed', reason: 'battery-closed-erased-type', commit, artifact: checked.artifact, ...(vacuous ? { vacuous } : {}) }; } @@ -185,11 +199,11 @@ export async function assembleFamilyTask(input: { problem: SolverProblem; task: /** Advisory only: a failed, timed-out or unavailable probe reports nothing rather than non-vacuity. */ async function contradictoryHypotheses(project: string, task: CooperativeTask, input: { context: string; env: NodeJS.ProcessEnv; - signal?: AbortSignal }, mathlib: boolean, timeoutMs: number): Promise { + signal?: AbortSignal }, mathlib: boolean, grind: boolean, timeoutMs: number): Promise { if (timeoutMs <= 0 || input.signal?.aborted) return; try { const probe = await checkLeanType({ projectRoot: project, file: task.proofPath!, context: input.context, type: task.type!, - expression: vacuityProbeProof(mathlib), env: input.env, signal: input.signal, timeoutMs }); + expression: vacuityProbeProof(mathlib, grind), env: input.env, signal: input.signal, timeoutMs }); return probe.status === 'elaborated' && probe.constants !== undefined && !probe.constants.includes('sorryAx') ? true : undefined; } catch { return; } } diff --git a/tests/agentTeamNativeLifecycle.test.ts b/tests/agentTeamNativeLifecycle.test.ts index b8347d31..4b378110 100644 --- a/tests/agentTeamNativeLifecycle.test.ts +++ b/tests/agentTeamNativeLifecycle.test.ts @@ -30,8 +30,9 @@ const fixtures: ReturnType[] = []; const ROOT = '00000000-0000-4000-8000-000000000001'; /** Only model execution is controlled; task state, worktree isolation, source freezing and Lean checks are real. */ -function fixture({ earlyCompletion = false, beforeOpen, beforeVerification }: { +function fixture({ earlyCompletion = false, beforeOpen, beforeVerification, emit = () => {} }: { earlyCompletion?: boolean; beforeOpen?: () => Promise; beforeVerification?: () => Promise; + emit?: (name: string, payload: Json) => void; } = {}) { const directory = temporaryDirectory('native-team-lifecycle-'), root = path.resolve('.'); const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { @@ -111,7 +112,7 @@ function fixture({ earlyCompletion = false, beforeOpen, beforeVerification }: { leadAccess: { environment, retrievalRoot: path.join(state.worktree, problem.projectRelative), researchSkill: skill }, modules, executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, maxAgents: 3, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens: 0, remainingMs: () => Infinity, - save: () => writeSolverRunState(path.join(directory, 'state.json'), state), emit: () => {}, + save: () => writeSolverRunState(path.join(directory, 'state.json'), state), emit, exclusiveCheck: async operation => { await beforeVerification?.(); return operation(); }, }); const rootOptions = team.nativeAgentControlOptions()!; @@ -455,6 +456,50 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => initialSource.replace('theorem original', prerequisite + downstream + 'theorem original')); }, 60_000); + it.each([['standalone helper', true], ['proof delivery', false]] as const)( + 'closes a submitted sorry helper with the host tactic battery before the ordinary %s check', async (_kind, helpersOnly) => { + const emitted: Json[] = []; + const f = fixture({ emit: (name, payload) => { if (name === 'task_tactic_battery') emitted.push(payload); } }); + await f.spawn('prover', 'Prove and share NativeTeam.shifted.'); + const worker = f.team.archive.workers[0]!, file = f.source(worker.worktree); + fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem original', + 'theorem shifted (n : Nat) : n + 0 = n := by sorry\ntheorem original')); + expect(await f.tool({ operation: 'submit', helpersOnly, summary: 'Helper with an open body.', + declarations: [{ file: 'Submission.lean', name: 'NativeTeam.shifted', type: '∀ n : Nat, n + 0 = n' }] }, 'prover')) + .toMatchObject({ status: 'pending-writer-stop' }); + await f.sessions[0]!.complete(); + await expect.poll(() => f.team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); + expect(emitted).toEqual([expect.objectContaining({ workerId: 'prover', declaration: 'NativeTeam.shifted', + status: 'closed', applied: true })]); + const source = fs.readFileSync(file, 'utf8'); + expect(source).toContain('theorem shifted (n : Nat) : n + 0 = n := by first |'); + expect(source.match(/sorry/gu)).toHaveLength(1); // only the untouched original statement + expect(f.team.archive.events).toContainEqual(expect.objectContaining({ to: 'prover', kind: 'message', + text: expect.stringContaining('host tactic battery closed the sorry in NativeTeam.shifted') })); + const delivery = f.team.archive.deliveries.find(item => item.agentId === 'prover'); + expect(delivery?.kind).toBe(helpersOnly ? 'helpers' : undefined); + expect(readAgentTeamProofDelivery(delivery!.path, f.state).declarations.map(item => item.name)).toContain('NativeTeam.shifted'); + }, 90_000); + + it('leaves a submitted sorry helper unchanged when the host tactic battery cannot close it', async () => { + const emitted: Json[] = []; + const f = fixture({ emit: (name, payload) => { if (name === 'task_tactic_battery') emitted.push(payload); } }); + await f.spawn('prover', 'Prove and share NativeTeam.wrong.'); + const worker = f.team.archive.workers[0]!, file = f.source(worker.worktree); + fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem original', + 'theorem wrong (n : Nat) : n = n + 1 := by sorry\ntheorem original')); + const before = fs.readFileSync(file, 'utf8'); + expect(await f.tool({ operation: 'submit', helpersOnly: true, summary: 'Helper with an open body.', + declarations: [{ file: 'Submission.lean', name: 'NativeTeam.wrong', type: '∀ n : Nat, n = n + 1' }] }, 'prover')) + .toMatchObject({ status: 'pending-writer-stop' }); + await f.sessions[0]!.complete(); + await expect.poll(() => emitted.length, { timeout: 90_000 }).toBe(1); + expect(emitted[0]).toMatchObject({ declaration: 'NativeTeam.wrong', status: 'failed', applied: false }); + await expect.poll(() => f.team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); + expect(fs.readFileSync(file, 'utf8')).toBe(before); + expect(f.team.archive.deliveries.filter(item => item.agentId === 'prover')).toEqual([]); + }, 150_000); + it('installs an ordinary prerequisite in an older member before retrying its dependent helper', async () => { const f = fixture(); await f.spawn('consumer'); diff --git a/tests/agentTeamSourceRecovery.test.ts b/tests/agentTeamSourceRecovery.test.ts index 74fa5b97..f364250a 100644 --- a/tests/agentTeamSourceRecovery.test.ts +++ b/tests/agentTeamSourceRecovery.test.ts @@ -684,8 +684,10 @@ describe('native team source handling', () => { const f = fixture(); await f.spawn('member', 'Prove the helper.'); const first = await f.session(0), worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('theorem goal', helper.replace('trivial', 'sorry') + 'theorem goal')); - expect(await f.call({ operation: 'submit', helpersOnly: true, declarations, summary: 'Check this draft.' }, worker.id)) + // The host tactic battery cannot close False, so the sorry remains for the author. + fs.writeFileSync(f.source(worker.worktree), original.replace('theorem goal', 'theorem helper : False := by sorry\ntheorem goal')); + expect(await f.call({ operation: 'submit', helpersOnly: true, summary: 'Check this draft.', + declarations: [{ file: 'Submission.lean', name: 'Recovery.helper', type: 'False' }] }, worker.id)) .toMatchObject({ ok: true }); first.complete(); await idle(f.team); expect(worker.tasks[0]!.error).toContain('Helper source contains sorry or admit.'); diff --git a/tests/tacticBattery.test.ts b/tests/tacticBattery.test.ts index 8d8fa094..b8abbfa4 100644 --- a/tests/tacticBattery.test.ts +++ b/tests/tacticBattery.test.ts @@ -6,7 +6,7 @@ import { checkLeanType } from '../src/math/leanTypeDiagnostics'; import { inspectScopedLeanDeclarations } from '../src/math/leanSource'; import { runLeanProcess } from '../src/math/mathProcess'; import type { SolverProblem } from '../src/solver/problem'; -import { tacticBatteryProof, tacticBatterySource, vacuityProbeProof } from '../src/solver/tacticBattery'; +import { tacticBatteryProof, tacticBatterySource, toolchainHasGrind, vacuityProbeProof } from '../src/solver/tacticBattery'; import type { CooperativeTask } from '../src/solver/tasks'; import { newestLeanBinary } from './helpers/lean'; @@ -37,6 +37,22 @@ describe('tactic battery placement', () => { expect(vacuityProbeProof(true).startsWith(`${vacuityProbeProof(false)} | linarith | `)).toBe(true); }); + it('appends grind last to both batteries only when requested', () => { + expect(tacticBatteryProof(false, true)).toBe(`${proof} | grind`); + expect(tacticBatteryProof(true, true)).toBe(`${tacticBatteryProof(true)} | grind`); + expect(vacuityProbeProof(true, true)).toBe(`${vacuityProbeProof(true)} | grind`); + }); + + it.each([['leanprover/lean4:v4.36.0', true], ['leanprover/lean4:v4.24.0-rc1', true], ['leanprover/lean4:v5.0.0', true], + ['leanprover/lean4:v4.23.0', false], ['leanprover/lean4:v4.8.0', false], ['leanprover/lean4:nightly', false], + [undefined, false]] as const)('gates grind on the project toolchain %s', (toolchain, expected) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tactic-battery-toolchain-')); + try { + if (toolchain) fs.writeFileSync(path.join(root, 'lean-toolchain'), `${toolchain}\n`); + expect(toolchainHasGrind(root)).toBe(expected); + } finally { fs.rmSync(root, { recursive: true, force: true }); } + }); + it('inserts a new helper before the anchor with a namespace-relative name', () => { const edited = place(original)!; expect(edited).toBe('namespace Tutorial\n\ntheorem helper : True\n := ' + proof + @@ -123,5 +139,20 @@ describe.skipIf(!lean)('local Lean tactic battery elaboration', () => { it.each(['∀ n : Nat, n + 0 = n', '∀ n : Nat, n = 0 → n + 1 = 1', '∀ n : Nat, n < 0 → False', 'False', '∀ n : Nat, ¬ (n < 0)']) ('does not report the satisfiable or refutation-shaped type %s as vacuous', async type => { expect((await check(type, vacuityProbeProof(false))).status).toBe('failed'); + expect((await check(type, vacuityProbeProof(false, true))).status).toBe('failed'); + }); + + const grindLean = /---v4\.(?:2[4-9]|[3-9]\d)\./u.test(lean ?? ''); + it.runIf(grindLean)('closes an order-plus-congruence goal only once grind is in the battery', async () => { + const type = '∀ (f : Int → Int) (x y : Int), x ≤ y → y ≤ x → f x = f y'; + expect((await check(type)).status).toBe('failed'); + const result = await check(type, tacticBatteryProof(false, true)); + expect(result.status, result.stdout + result.stderr).toBe('elaborated'); + expect(result.constants).not.toContain('sorryAx'); + }); + + it.runIf(grindLean)('keeps grind from closing a false goal', async () => { + const result = await check('∀ n : Nat, n = n + 1', tacticBatteryProof(false, true)); + expect(result.status).toBe('failed'); }); }); diff --git a/tests/webModuleIdentity.test.ts b/tests/webModuleIdentity.test.ts index e4d179f5..f796eed9 100644 --- a/tests/webModuleIdentity.test.ts +++ b/tests/webModuleIdentity.test.ts @@ -16,12 +16,12 @@ describe('one frozen identity for executable research modules and the optional w it('pins the method digests for both executable modules and shared identity functions', () => { // These digests include the module versions for final review and research handoffs. const original: [ResearchModulePlan['scheduler'], ResearchModulePlan['context'], string][] = [ - ['plan', 'full', '3a13f06557273451d404a55d577b91950370f4fc4382094903cbe39aa8de8c9a'], - ['plan', 'essential', 'dd421930f1956a64fc43b82b8c93caec63167a9d2ca520ddd3c053284d104715'], - ['critical-path', 'full', '52efdc4399312deadc2bf540aa4e06ce83f76cdfc0a1cbc611513cc385c04814'], - ['critical-path', 'essential', '8dd6d1453840acf9f77ca2e4bd800f2e9abc7fb272cd846c063bf51ec2e4fcff'], - ['continuation', 'full', 'd8b7b8e2720ac897bb6a266345bce9b6db16e2ad7d1b7ceff607fc6033aa7e00'], - ['continuation', 'essential', '2b3f0dfb1abad52360d1b167f1fb598a96f1be29c7faf741f65caab2cfd052cb'], + ['plan', 'full', '0bdde07fc4dd90b2f7458f2cc8c57c3d3551c44b95c2106fd297a29169242b2b'], + ['plan', 'essential', '4fe61fa5157c3f224876f7ae8be37cdb7d94481bf78a7378d6553b446d86fa74'], + ['critical-path', 'full', '773a24254088ac08e655d80888d9e9ba5a8f73520cd1b24ed42ad20630fdfcc1'], + ['critical-path', 'essential', '142f708638367302fa1f2afe687e7ed36d458fcec5b87570d22cc9de4c95fda1'], + ['continuation', 'full', 'f874054c0e17a07909a54c25753e07ccc2b0f10b86cc0f0270c73cf5841775df'], + ['continuation', 'essential', 'c0333782b36f87770061420c7685a620eb8b3269d31e0dbdabe1024135440f09'], ]; for (const [scheduler, context, digest] of original) { const plan = { scheduler, context, custom: [] }; @@ -29,10 +29,10 @@ describe('one frozen identity for executable research modules and the optional w expect(solverIdentityMethodDigest(configuredResearchModuleIdentity(plan).identity, 'cooperative')).toBe(digest); } const advised: ['cooperative' | 'independent', number, string][] = [ - ['cooperative', 1, '743afc2c24dab56ee088ff6d0c4ecac49bf3c28feb3cc2e75539711167282d0b'], - ['cooperative', 4, '3c0a4d4d40f2b9596c72d1f7b976e866c23b86dfffb6a5a967d7d53bb03b2f62'], - ['independent', 1, '3398b370d5cc7a05566eca9f9ba39deaba425d658845688b32c9d21f0d9229df'], - ['independent', 4, '3398b370d5cc7a05566eca9f9ba39deaba425d658845688b32c9d21f0d9229df'], + ['cooperative', 1, '37886f8a3a14e944680a6ba4e02712ef55fdc39041f686132200169dd7dfd315'], + ['cooperative', 4, 'e0a82486e24ca4fa7280cd93579974cf823579bbc83d33d5362ac2b473c8c413'], + ['independent', 1, 'ca9a7f433e3e67bbd63c41297147e62d16de07cf3eaade0aa002d7d66364648e'], + ['independent', 4, 'ca9a7f433e3e67bbd63c41297147e62d16de07cf3eaade0aa002d7d66364648e'], ]; for (const [coordination, workers, digest] of advised) { const plan: ResearchModulePlan = { scheduler: 'continuation', context: 'essential', custom };