From 009db4eaef3025824245c07d105561c6275b110b Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Sat, 28 Nov 2026 01:25:06 +0800 Subject: [PATCH 1/7] Unify TheoremOS collaboration on Codex native teams --- .github/workflows/verify.yml | 14 +- AGENTS.md | 2 +- README.md | 11 +- README_EN.md | 11 +- apps/web/Dockerfile | 1 + apps/web/client/app.ts | 123 +- apps/web/client/chatSession.ts | 45 +- apps/web/client/draft.ts | 2 +- apps/web/client/formalize.ts | 10 +- apps/web/client/guide.html | 10 +- apps/web/client/index.html | 16 +- apps/web/client/moduleView.tsx | 2 +- apps/web/client/productFlow.ts | 2 +- apps/web/client/productFlowView.tsx | 2 +- apps/web/client/research-conversation.css | 2 + apps/web/client/researchSelection.ts | 3 +- apps/web/client/serverModulePlans.tsx | 30 +- apps/web/client/ui/ChatWorkspace.tsx | 33 +- apps/web/client/ui/RunHeader.tsx | 12 +- apps/web/formalizationTypes.ts | 2 + apps/web/i18n/app.ts | 2 +- apps/web/i18n/common.ts | 4 +- apps/web/i18n/errors.ts | 12 +- apps/web/i18n/formalize.ts | 7 +- apps/web/i18n/guide.ts | 20 +- apps/web/i18n/pages.ts | 1 - apps/web/i18n/release.ts | 4 +- apps/web/jobs.ts | 50 +- apps/web/libraryResearch.ts | 20 +- apps/web/presentation.ts | 7 +- apps/web/problemDraftSubmission.ts | 3 +- apps/web/researchApi.ts | 46 +- apps/web/researchMode.ts | 29 +- apps/web/researchProjects.ts | 28 +- apps/web/researchWorkspace.ts | 5 +- apps/web/runner.ts | 31 +- apps/web/server.ts | 151 +- apps/web/shared.ts | 9 +- apps/web/worker.ts | 22 +- apps/web/workerBridge.ts | 91 +- bin/math.ts | 14 +- docs/agensh-adoption-plan.md | 6 +- docs/agensh-module-design.md | 2 +- docs/agensh-offline-baseline.md | 4 +- docs/codex-skill-runtime.md | 81 +- docs/formalization.md | 2 +- docs/generic-cli.md | 2 +- docs/harness-portability.md | 26 +- docs/library-catalog.md | 2 +- docs/math-tools/catalog.md | 2 +- docs/native-skill-comparison.md | 2 +- docs/solver-modules.md | 6 +- docs/theorem-knowledge.md | 4 +- docs/usage.md | 113 +- docs/web-operations.md | 7 +- docs/web-workbench.md | 100 +- examples/components/EXPERIMENTS.md | 2 + examples/components/README.md | 5 +- examples/imo2026/COMPARISON.md | 6 + examples/imo2026/README.md | 31 +- examples/imo2026/reproduce.sh | 18 +- examples/putnambench/README.md | 6 +- package.json | 9 +- research/PROTOCOL.md | 6 +- .../decisions/0009-native-codex-team-only.md | 17 + .../0010-native-team-runtime-only.md | 16 + scripts/build-agent-tools.ts | 3 +- scripts/build-web-sample.ts | 6 +- scripts/build.ts | 1 - scripts/codex-backend/README.md | 23 +- scripts/mathematics/autoLibrary.ts | 7 +- scripts/mathematics/compareMathRuns.ts | 11 +- scripts/mathematics/component.ts | 2 +- scripts/mathematics/cooperativeReplay.ts | 309 -- scripts/mathematics/editMathRun.ts | 17 +- scripts/mathematics/importProofFragment.ts | 21 - scripts/mathematics/planApply.ts | 3 - scripts/mathematics/planCommand.ts | 12 +- scripts/mathematics/planValidate.ts | 2 +- scripts/mathematics/proofSearch.ts | 35 - scripts/mathematics/researchObserve.ts | 50 - scripts/mathematics/runExample.ts | 6 +- scripts/mathematics/runGoalsFirst.ts | 2 +- scripts/mathematics/runMathProof.ts | 2 +- scripts/mathematics/samplePutnamRuns.ts | 11 +- scripts/mathematics/seedContinuation.ts | 4 +- scripts/test-codex-backend-delivery.ts | 9 +- scripts/test-codex-backend.ts | 2 +- scripts/test-web-candidate-continuity.ts | 3 +- scripts/test-web-chat-cancel-recovery.ts | 2 +- scripts/test-web-chat-mathematics.ts | 6 +- scripts/test-web-chat-recovery.ts | 4 +- scripts/test-web-chat-session.ts | 2 +- scripts/test-web-collaboration-actions.ts | 3 +- scripts/test-web-collaboration-continuity.ts | 3 +- scripts/test-web-cooperative-runtime.ts | 219 - scripts/test-web-first-research-sharing.ts | 9 +- scripts/test-web-formalize.ts | 2 +- scripts/test-web-inline-annotations.ts | 3 +- scripts/test-web-key-memory.ts | 2 +- .../test-web-library-personal-continuity.ts | 4 +- scripts/test-web-message-stage-continuity.ts | 4 +- scripts/test-web-native-team.ts | 152 +- scripts/test-web-natural-first.ts | 2 +- scripts/test-web-plan-approval.ts | 67 +- scripts/test-web-plan-ownership.ts | 192 - scripts/test-web-plan-recovery.ts | 456 -- scripts/test-web-problem-drafts.ts | 10 +- scripts/test-web-problem-lifecycle.ts | 8 +- scripts/test-web-proof-thinking.ts | 17 +- scripts/test-web-research-completion.ts | 2 +- .../test-web-research-decisions-lifecycle.ts | 3 +- scripts/test-web-research-library-trials.ts | 2 +- scripts/test-web-review-regressions.ts | 2 +- scripts/test-web-round10-collaboration.ts | 178 - scripts/test-web-round10-workbench.ts | 71 +- scripts/test-web-round5-collaboration.ts | 5 +- scripts/test-web-round5-workbench.ts | 5 +- scripts/test-web-round6-collaboration.ts | 9 +- scripts/test-web-round8-approval.ts | 15 +- scripts/test-web-round8-budget.ts | 2 +- scripts/test-web-round8-keys.ts | 2 +- scripts/test-web-round9-availability.ts | 16 +- scripts/test-web-round9-collaboration.ts | 139 - scripts/test-web-saved-key.ts | 2 +- scripts/test-web-solve-process.ts | 9 +- scripts/web-cooperative-fixture.ts | 20 + scripts/web-i18n.ts | 6 +- skills/theoremos-research/SKILL.md | 7 +- .../references/parallel-work.md | 78 +- src/math/mathBuildManifest.ts | 2 +- src/math/mathRuntimeIo.ts | 22 +- src/runtime/agentSession.ts | 5 +- src/runtime/agentSessionPlan.ts | 8 +- src/runtime/agentTeamTools.ts | 5 +- src/runtime/cliSession.ts | 1 - src/runtime/codexSession.ts | 87 +- src/runtime/harnessProcess.ts | 12 +- src/runtime/nativeDelegation.ts | 180 - src/solver/agentTeam.ts | 599 +-- src/solver/agentTeamBudget.ts | 38 +- src/solver/agentTeamContext.ts | 54 +- src/solver/agentTeamNative.ts | 63 +- src/solver/agentTeamOperations.ts | 22 + src/solver/agentTeamProof.ts | 100 +- src/solver/agentTeamTool.ts | 113 +- src/solver/agentTeamViews.ts | 199 +- src/solver/archive.ts | 19 +- src/solver/componentTemplate.ts | 2 +- src/solver/contextCompiler.ts | 16 +- src/solver/continuationSeed.ts | 1505 +----- src/solver/cooperation.ts | 1840 ------- src/solver/cooperationCore.ts | 1146 ----- src/solver/cooperationInputs.ts | 558 -- src/solver/cooperationIntegration.ts | 733 --- src/solver/cooperationPlanning.ts | 636 --- src/solver/cooperationRoutes.ts | 64 - src/solver/cooperationStatements.ts | 197 - src/solver/cooperationTaskProofs.ts | 1471 ------ src/solver/cooperativeProof.ts | 11 +- src/solver/declarationArtifacts.ts | 57 +- src/solver/freshContinuationChecks.ts | 31 - src/solver/knowledgeContext.ts | 2 +- src/solver/libraryAccess.ts | 7 +- src/solver/modules/context.ts | 27 +- src/solver/planApproval.ts | 75 + src/solver/planTool.ts | 57 +- src/solver/portfolioExploration.ts | 303 +- src/solver/proofImport.ts | 244 - src/solver/research.ts | 2490 +++------ src/solver/researchGuidance.ts | 4 +- src/solver/researchObservation.ts | 60 - src/solver/researchRetirement.ts | 13 + src/solver/researchToolGuide.ts | 23 +- src/solver/researchUsage.ts | 46 +- src/solver/run.ts | 230 +- src/solver/singleContinuationSeed.ts | 9 +- src/solver/skillResearchContext.ts | 32 +- src/solver/usageBudget.ts | 20 +- src/solver/workerProofLifecycle.ts | 95 - tests/agentResearchTeam.test.ts | 1738 ------- tests/agentSessionPlan.test.ts | 8 - tests/agentTeamBudget.test.ts | 65 +- tests/agentTeamContextContract.test.ts | 72 +- tests/agentTeamHandoffs.test.ts | 12 +- tests/agentTeamMessaging.test.ts | 249 - tests/agentTeamNativeControl.test.ts | 25 +- tests/agentTeamNativeTools.test.ts | 142 +- tests/agentTeamProof.test.ts | 33 +- tests/agentTeamRouteSummary.test.ts | 32 +- tests/agentTeamSolver.test.ts | 454 +- tests/agentTeamSourceRecovery.test.ts | 246 +- tests/agentTeamTool.test.ts | 168 +- tests/agentTeamTransportFallback.test.ts | 224 +- tests/agentTools.test.ts | 2 +- tests/campaignLibraryNative.test.ts | 14 +- tests/certificateSlots.test.ts | 2 +- tests/chatSessionWorkspace.test.ts | 1 + tests/claudeCodeSession.test.ts | 1 - tests/cliSession.test.ts | 1 - tests/codexSession.test.ts | 2 + tests/codexSessionAgentControl.test.ts | 47 +- tests/commonResearchGuidance.test.ts | 18 +- tests/componentTemplate.test.ts | 12 +- tests/consumerConnections.test.ts | 339 +- tests/contextCheckpoint.test.ts | 65 +- tests/contextCompiler.test.ts | 38 - tests/continuationSeed.test.ts | 3082 ----------- tests/cooperativeReplay.test.ts | 170 - tests/coordinationSimulation.test.ts | 223 - tests/definitionStatementReview.test.ts | 77 - tests/deliveryReceipts.test.ts | 30 +- tests/evaluatorRun.test.ts | 2 +- tests/exactSourceIntegration.test.ts | 159 - tests/fixtures/agentTeamFollowupPeer.cjs | 205 - tests/fixtures/agentTeamHandoffPeer.cjs | 213 - tests/fixtures/agentTeamPeer.cjs | 188 - tests/formalizationRelay.test.ts | 2 +- tests/frontierPriorityContext.test.ts | 4 +- tests/fullSkillWorkflow.test.ts | 1 - tests/goalProgressCooperation.test.ts | 308 -- tests/goalProgressResearch.test.ts | 237 +- tests/harnessProcess.test.ts | 20 + tests/harnessProofAcceptance.test.ts | 10 +- tests/helpers/cooperation.ts | 42 - tests/helpers/solver.ts | 4 + tests/helpers/solverAtomicPlanRejection.ts | 91 - tests/helpers/solverTeamRouteRetirement.ts | 176 - tests/hostProofPublication.test.ts | 145 - tests/humanGuidance.test.ts | 131 - tests/installedLibraryContext.test.ts | 4 +- tests/installedLibraryUsage.test.ts | 83 - tests/knowledgeContext.test.ts | 2 +- tests/leadCheckpointHandoff.test.ts | 384 -- tests/leadPlanRejectionFeedback.test.ts | 48 +- tests/libraryApplication.test.ts | 84 +- tests/nativeDelegation.test.ts | 205 - tests/nativeInvestigations.test.ts | 70 - tests/nativeSkillComparison.test.ts | 2 +- tests/nativeTurnUsage.test.ts | 2 +- tests/nextChecks.test.ts | 312 -- tests/openCodeSession.test.ts | 3 +- tests/portableCooperation.test.ts | 115 - tests/proofSearchRecords.test.ts | 57 +- tests/repeatedDelivery.test.ts | 752 --- tests/researchArchive.test.ts | 17 +- tests/researchDurableCheckpoint.test.ts | 292 -- tests/researchObservation.test.ts | 175 - tests/researchUsage.test.ts | 32 +- tests/runContinuationSeed.test.ts | 343 -- tests/runLeaseSafety.test.ts | 2 +- tests/singleContinuationSeed.test.ts | 2 +- tests/skillContextContinuation.test.ts | 3 +- tests/skillProcessRecovery.test.ts | 9 +- tests/skillResearchRuntime.test.ts | 47 +- tests/skillSolver.test.ts | 135 +- tests/solver.test.ts | 4574 +---------------- tests/solverAdvisoryPriority.test.ts | 312 -- tests/solverAssemblyLeadYield.test.ts | 129 - tests/solverAssignmentRelease.test.ts | 175 - tests/solverAtomicPlanApply.test.ts | 88 +- tests/solverCanonicalGoalProof.test.ts | 302 -- tests/solverCanonicalTaskProof.test.ts | 298 -- tests/solverCapabilityFeedback.test.ts | 269 - tests/solverCapacityCli.test.ts | 14 +- tests/solverCapacityExploration.test.ts | 671 --- tests/solverCompactProjection.test.ts | 20 - tests/solverCompletedGuidance.test.ts | 175 - tests/solverConditionalIntegration.test.ts | 268 - tests/solverConditionalLibraryImports.test.ts | 120 - tests/solverContinuation.test.ts | 1279 ----- tests/solverContinuationCapacity.test.ts | 310 -- tests/solverContinuousResearch.test.ts | 122 - tests/solverCooperativeCheckpoints.test.ts | 2110 -------- tests/solverDefinitionContractChecks.test.ts | 112 - tests/solverDependencyScheduling.test.ts | 337 -- tests/solverDispatch.test.ts | 115 - tests/solverDispatchWait.test.ts | 229 - tests/solverFamilyAssembly.test.ts | 135 - tests/solverFinalReviewScope.test.ts | 304 -- tests/solverHumanEditRecovery.test.ts | 246 - tests/solverIncrementalHelperLanding.test.ts | 152 - tests/solverInitialPlan.test.ts | 291 -- tests/solverIntegrationBatch.test.ts | 858 ---- tests/solverIntegrationConcurrency.test.ts | 516 -- tests/solverIntegrationRecovery.test.ts | 653 --- tests/solverKnowledgeConcurrency.test.ts | 435 -- tests/solverLeadCheckpointSemantics.test.ts | 443 -- ...solverLeadInheritedDraftCorrection.test.ts | 130 - tests/solverLibraryRequest.test.ts | 95 +- tests/solverLivenessRecovery.test.ts | 543 -- tests/solverMathematicalContext.test.ts | 52 +- tests/solverMathematicalGaps.test.ts | 236 - tests/solverNextCheckPlanLifecycle.test.ts | 204 - tests/solverOriginalDefinitionGoals.test.ts | 172 - tests/solverPlanApproval.test.ts | 398 -- tests/solverPlanApprovalProcess.test.ts | 63 - tests/solverPlanConcurrency.test.ts | 481 -- tests/solverPlanPatch.test.ts | 235 - tests/solverPlanPublication.test.ts | 234 - tests/solverPlanPublicationFeedback.test.ts | 443 -- tests/solverPortfolioGate.test.ts | 285 - tests/solverProjectionPreparation.test.ts | 193 - tests/solverProjectionReuse.test.ts | 153 - tests/solverProofImport.test.ts | 255 - tests/solverProofReady.test.ts | 372 -- tests/solverProofReadyIntake.test.ts | 231 - tests/solverProverRoles.test.ts | 11 - tests/solverRecheckReuse.test.ts | 268 - tests/solverResearchBasisDispatch.test.ts | 350 -- tests/solverResearchDrafts.test.ts | 932 ---- tests/solverResearchPublication.test.ts | 581 --- tests/solverResearchTransfer.test.ts | 235 - tests/solverRestore.test.ts | 277 - tests/solverRetainedSourceGoals.test.ts | 354 -- tests/solverRoutePreflightScheduling.test.ts | 168 - tests/solverRouteRetirement.test.ts | 329 +- tests/solverSavedPlan.test.ts | 331 -- tests/solverSessionAdmission.test.ts | 130 - tests/solverSingleProofHandoff.test.ts | 6 +- tests/solverSoftSliceCompaction.test.ts | 15 +- tests/solverSourceRecovery.test.ts | 7 +- tests/solverStagnationRecovery.test.ts | 441 -- tests/solverStaleFailure.test.ts | 355 -- tests/solverStoppedOwner.test.ts | 92 - tests/solverTacticBattery.test.ts | 190 - tests/solverTaskTypePreflight.test.ts | 262 - tests/solverUsageReceipts.test.ts | 22 +- tests/solverWorkerCheckpointFeedback.test.ts | 265 - tests/solverWorkerExitDispatch.test.ts | 107 - tests/statementSnapshotBatch.test.ts | 182 - tests/taskConsumerInterfaces.test.ts | 38 +- tests/taskFamilies.test.ts | 24 - tests/taskLifecycle.test.ts | 53 - tests/taskWorkspaceResume.test.ts | 188 - tests/theoryModules.test.ts | 2 +- tests/usageBudget.test.ts | 7 +- tests/verificationCheckpoint.test.ts | 19 - tests/verifiedProofPublication.test.ts | 167 - tests/webCollaboration.test.ts | 270 +- tests/webContinuationIdentity.test.ts | 8 +- tests/webConversations.test.ts | 2 +- tests/webFormalizations.test.ts | 30 +- tests/webJobs.test.ts | 28 + tests/webKnowledgeApi.test.ts | 8 +- tests/webLibraryResearch.test.ts | 37 + tests/webOperationsApi.test.ts | 8 +- tests/webResearchApi.test.ts | 221 +- tests/webResearchProjects.test.ts | 26 + tests/webResearchWorkspace.test.ts | 10 + tests/webRunner.test.ts | 50 +- tests/webServer.test.ts | 75 +- tests/webSkillResearch.test.ts | 41 +- tests/webWorkerBridge.test.ts | 165 +- tests/workerDeliveryIdentity.test.ts | 384 -- tests/workerDeliveryRecovery.test.ts | 270 - tests/workerProofCheckpoint.test.ts | 128 - tests/workerRecovery.test.ts | 163 - 358 files changed, 4170 insertions(+), 54887 deletions(-) create mode 100644 research/decisions/0009-native-codex-team-only.md create mode 100644 research/decisions/0010-native-team-runtime-only.md delete mode 100644 scripts/mathematics/cooperativeReplay.ts delete mode 100644 scripts/mathematics/importProofFragment.ts delete mode 100644 scripts/mathematics/planApply.ts delete mode 100644 scripts/mathematics/proofSearch.ts delete mode 100644 scripts/mathematics/researchObserve.ts delete mode 100644 scripts/test-web-cooperative-runtime.ts delete mode 100644 scripts/test-web-plan-ownership.ts delete mode 100644 scripts/test-web-plan-recovery.ts delete mode 100644 scripts/test-web-round10-collaboration.ts delete mode 100644 scripts/test-web-round9-collaboration.ts create mode 100644 scripts/web-cooperative-fixture.ts delete mode 100644 src/runtime/nativeDelegation.ts create mode 100644 src/solver/agentTeamOperations.ts delete mode 100644 src/solver/cooperation.ts delete mode 100644 src/solver/cooperationCore.ts delete mode 100644 src/solver/cooperationInputs.ts delete mode 100644 src/solver/cooperationIntegration.ts delete mode 100644 src/solver/cooperationPlanning.ts delete mode 100644 src/solver/cooperationRoutes.ts delete mode 100644 src/solver/cooperationStatements.ts delete mode 100644 src/solver/cooperationTaskProofs.ts delete mode 100644 src/solver/freshContinuationChecks.ts delete mode 100644 src/solver/proofImport.ts delete mode 100644 src/solver/researchObservation.ts create mode 100644 src/solver/researchRetirement.ts delete mode 100644 src/solver/workerProofLifecycle.ts delete mode 100644 tests/agentResearchTeam.test.ts delete mode 100644 tests/agentTeamMessaging.test.ts delete mode 100644 tests/continuationSeed.test.ts delete mode 100644 tests/cooperativeReplay.test.ts delete mode 100644 tests/coordinationSimulation.test.ts delete mode 100644 tests/definitionStatementReview.test.ts delete mode 100644 tests/fixtures/agentTeamFollowupPeer.cjs delete mode 100644 tests/fixtures/agentTeamHandoffPeer.cjs delete mode 100644 tests/fixtures/agentTeamPeer.cjs delete mode 100644 tests/goalProgressCooperation.test.ts delete mode 100644 tests/helpers/cooperation.ts delete mode 100644 tests/helpers/solverAtomicPlanRejection.ts delete mode 100644 tests/helpers/solverTeamRouteRetirement.ts delete mode 100644 tests/hostProofPublication.test.ts delete mode 100644 tests/installedLibraryUsage.test.ts delete mode 100644 tests/leadCheckpointHandoff.test.ts delete mode 100644 tests/nativeDelegation.test.ts delete mode 100644 tests/nativeInvestigations.test.ts delete mode 100644 tests/nextChecks.test.ts delete mode 100644 tests/portableCooperation.test.ts delete mode 100644 tests/repeatedDelivery.test.ts delete mode 100644 tests/researchDurableCheckpoint.test.ts delete mode 100644 tests/researchObservation.test.ts delete mode 100644 tests/runContinuationSeed.test.ts delete mode 100644 tests/solverAdvisoryPriority.test.ts delete mode 100644 tests/solverAssemblyLeadYield.test.ts delete mode 100644 tests/solverAssignmentRelease.test.ts delete mode 100644 tests/solverCanonicalGoalProof.test.ts delete mode 100644 tests/solverCanonicalTaskProof.test.ts delete mode 100644 tests/solverCapabilityFeedback.test.ts delete mode 100644 tests/solverCapacityExploration.test.ts delete mode 100644 tests/solverCompletedGuidance.test.ts delete mode 100644 tests/solverConditionalIntegration.test.ts delete mode 100644 tests/solverConditionalLibraryImports.test.ts delete mode 100644 tests/solverContinuation.test.ts delete mode 100644 tests/solverContinuationCapacity.test.ts delete mode 100644 tests/solverContinuousResearch.test.ts delete mode 100644 tests/solverCooperativeCheckpoints.test.ts delete mode 100644 tests/solverDefinitionContractChecks.test.ts delete mode 100644 tests/solverDependencyScheduling.test.ts delete mode 100644 tests/solverDispatch.test.ts delete mode 100644 tests/solverDispatchWait.test.ts delete mode 100644 tests/solverFamilyAssembly.test.ts delete mode 100644 tests/solverFinalReviewScope.test.ts delete mode 100644 tests/solverHumanEditRecovery.test.ts delete mode 100644 tests/solverIncrementalHelperLanding.test.ts delete mode 100644 tests/solverInitialPlan.test.ts delete mode 100644 tests/solverIntegrationBatch.test.ts delete mode 100644 tests/solverIntegrationConcurrency.test.ts delete mode 100644 tests/solverIntegrationRecovery.test.ts delete mode 100644 tests/solverKnowledgeConcurrency.test.ts delete mode 100644 tests/solverLeadCheckpointSemantics.test.ts delete mode 100644 tests/solverLeadInheritedDraftCorrection.test.ts delete mode 100644 tests/solverLivenessRecovery.test.ts delete mode 100644 tests/solverMathematicalGaps.test.ts delete mode 100644 tests/solverNextCheckPlanLifecycle.test.ts delete mode 100644 tests/solverOriginalDefinitionGoals.test.ts delete mode 100644 tests/solverPlanApproval.test.ts delete mode 100644 tests/solverPlanApprovalProcess.test.ts delete mode 100644 tests/solverPlanConcurrency.test.ts delete mode 100644 tests/solverPlanPatch.test.ts delete mode 100644 tests/solverPlanPublication.test.ts delete mode 100644 tests/solverPlanPublicationFeedback.test.ts delete mode 100644 tests/solverPortfolioGate.test.ts delete mode 100644 tests/solverProjectionPreparation.test.ts delete mode 100644 tests/solverProjectionReuse.test.ts delete mode 100644 tests/solverProofImport.test.ts delete mode 100644 tests/solverProofReady.test.ts delete mode 100644 tests/solverProofReadyIntake.test.ts delete mode 100644 tests/solverRecheckReuse.test.ts delete mode 100644 tests/solverResearchBasisDispatch.test.ts delete mode 100644 tests/solverResearchDrafts.test.ts delete mode 100644 tests/solverResearchPublication.test.ts delete mode 100644 tests/solverResearchTransfer.test.ts delete mode 100644 tests/solverRestore.test.ts delete mode 100644 tests/solverRetainedSourceGoals.test.ts delete mode 100644 tests/solverRoutePreflightScheduling.test.ts delete mode 100644 tests/solverSavedPlan.test.ts delete mode 100644 tests/solverSessionAdmission.test.ts delete mode 100644 tests/solverStagnationRecovery.test.ts delete mode 100644 tests/solverStaleFailure.test.ts delete mode 100644 tests/solverStoppedOwner.test.ts delete mode 100644 tests/solverTacticBattery.test.ts delete mode 100644 tests/solverTaskTypePreflight.test.ts delete mode 100644 tests/solverWorkerCheckpointFeedback.test.ts delete mode 100644 tests/solverWorkerExitDispatch.test.ts delete mode 100644 tests/statementSnapshotBatch.test.ts delete mode 100644 tests/taskLifecycle.test.ts delete mode 100644 tests/taskWorkspaceResume.test.ts delete mode 100644 tests/verifiedProofPublication.test.ts delete mode 100644 tests/workerDeliveryIdentity.test.ts delete mode 100644 tests/workerDeliveryRecovery.test.ts delete mode 100644 tests/workerProofCheckpoint.test.ts diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 322d0ce4..582f295b 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -41,7 +41,9 @@ jobs: timeout-minutes: 5 run: bun scripts/test-web-proof-thinking.ts --simple-reading - name: Verify the browser's login and research flows with local fixtures - run: bun run test:web-login && bun run test:web-natural-first && bun run test:web-chat-session && bun run test:web-chat-cancel-recovery && bun run test:web-key-memory && bun run test:web-saved-key && bun run test:web-solve-process && bun run test:web-review-regressions && bun run test:web-plan-recovery && bun run test:web-plan-ownership && bun run test:web-explain && bun run test:web-explain-recovery + run: bun run test:web-login && bun run test:web-natural-first && bun run test:web-chat-session && bun run test:web-chat-cancel-recovery && bun run test:web-key-memory && bun run test:web-saved-key && bun run test:web-solve-process && bun run test:web-review-regressions && bun run test:web-explain && bun run test:web-explain-recovery + - name: Verify native team creation, approval and library continuation with local fixtures + run: bun scripts/test-web-native-team.ts && bun run test:web-plan-approval && bunx vitest run tests/webLibraryResearch.test.ts - name: Verify paper drafting and download with local fixtures run: bun scripts/test-web-paper.ts - name: Verify research account switching and interrupted frontend operations @@ -136,12 +138,12 @@ jobs: run: bun run test:solver-reliability - name: Verify dependency snapshots and receipt cache bindings run: bunx vitest run --maxWorkers=4 tests/verifierSealedEnvironmentCache.test.ts tests/mathProofEnvironment.test.ts tests/leanProbeSnapshot.test.ts - - name: Verify sealed roles, independent audits and native delegation without models + - name: Verify sealed roles, native team sessions and historical inspection without models if: matrix.lean == '4.33.0' - run: bunx vitest run --maxWorkers=1 tests/formalizationSandbox.test.ts tests/formalizationAudit.test.ts tests/agentSessionPlan.test.ts tests/nativeInvestigations.test.ts tests/nativeDelegation.test.ts tests/workflowHarness.test.ts + run: bunx vitest run --maxWorkers=1 tests/formalizationSandbox.test.ts tests/formalizationAudit.test.ts tests/agentSessionPlan.test.ts tests/codexSession.test.ts tests/skillRunInspection.test.ts tests/workflowHarness.test.ts tests/agentTeamTransportFallback.test.ts tests/codexSessionAgentControl.test.ts - name: Verify projected proof contracts and retained source contexts - run: bunx vitest run --maxWorkers=4 tests/taskTypeContract.test.ts tests/projectionNotation.test.ts tests/taskSourceImplicitInstances.test.ts tests/taskSourceMacroProjection.test.ts tests/taskSourceNotationHints.test.ts tests/taskSourceNotationContext.test.ts tests/solverRetainedSourceGoals.test.ts tests/solverConditionalLibraryImports.test.ts tests/solverCanonicalGoalProof.test.ts + run: bunx vitest run --maxWorkers=4 tests/taskTypeContract.test.ts tests/projectionNotation.test.ts tests/taskSourceImplicitInstances.test.ts tests/taskSourceMacroProjection.test.ts tests/taskSourceNotationHints.test.ts tests/taskSourceNotationContext.test.ts - name: Verify search tools, failure reuse and completed research delivery - run: bunx vitest run --maxWorkers=4 tests/declarationSearch.test.ts tests/continuationSearch.test.ts tests/tacticBatteryFailureCache.test.ts tests/solverAssemblyLeadYield.test.ts tests/solverCompletedGuidance.test.ts tests/codexCompletedResponse.test.ts + run: bunx vitest run --maxWorkers=4 tests/declarationSearch.test.ts tests/continuationSearch.test.ts tests/tacticBatteryFailureCache.test.ts tests/codexCompletedResponse.test.ts - name: Verify definition contracts, conditional publication and research continuation - run: bunx vitest run --maxWorkers=4 tests/conditionalProjectionElaborator.test.ts tests/customSolverModules.test.ts tests/definitionContractChecks.test.ts tests/nextCheckNegativeDecisions.test.ts tests/planResearchConnections.test.ts tests/planningEvidence.test.ts tests/researchDurableCheckpoint.test.ts tests/solver.test.ts tests/solverDefinitionContractChecks.test.ts tests/solverKnowledgeConcurrency.test.ts tests/solverNextCheckPlanLifecycle.test.ts tests/solverResearchPublication.test.ts tests/solverResearchTransfer.test.ts tests/taskConditionalUniverses.test.ts tests/taskSourceConditionalContext.test.ts tests/verifiedProofPublication.test.ts tests/webModuleIdentity.test.ts + run: bunx vitest run --maxWorkers=4 tests/conditionalProjectionElaborator.test.ts tests/customSolverModules.test.ts tests/definitionContractChecks.test.ts tests/nextCheckNegativeDecisions.test.ts tests/planResearchConnections.test.ts tests/planningEvidence.test.ts tests/solver.test.ts tests/taskConditionalUniverses.test.ts tests/taskSourceConditionalContext.test.ts tests/webModuleIdentity.test.ts diff --git a/AGENTS.md b/AGENTS.md index a175f999..8de12016 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ Keep the CLI and mathematics proof behavior independent of the original DeepScientist checkout. The optional `apps/web` workbench is a separate BYOK HTTP service and Docker supervisor; it must not become a dependency of the CLI or mathematics services. There is no Electron or desktop build. -`src/math` owns mathematics services. `src/solver/modules` separates M1–M5 research decisions; `src/solver/run.ts` prepares and evaluates runs, and `src/solver/research.ts` executes cooperative role sessions with shared budgets and run-local checkpoints. `src/solver/archive.ts` owns S1 records; `src/solver/evaluation.ts` owns fixed S3 final acceptance. `src/runtime/codexSession.ts` connects to Codex through stdio. Do not reintroduce the original Core, Team services, HTTP services, role queues, or MCP orchestration into the runtime. M3 selects ready tasks, M5 assigns Lead, Researcher, Engineer and fixed-version Reviewer responsibilities; `cooperation.ts` runs the asynchronous task and integration loop, and `cooperativeProof.ts` checks and merges partial declarations; S2 learning remains a future extension. +`src/math` owns mathematics services. `src/solver/run.ts` prepares and evaluates proof runs, `src/solver/research.ts` runs researcher sessions with shared budgets and checkpoints, and `src/solver/agentTeam.ts` connects Codex collaboration to isolated proof writers and checked handoffs. Codex Lead assigns responsibilities using the pinned Skill. `src/solver/archive.ts` owns S1 records and `src/solver/evaluation.ts` owns fixed S3 final acceptance. `src/runtime/codexSession.ts` connects to Codex through stdio. Keep historical collaboration records readable. Resume and reproduce retired host scheduling workflows with their pinned historical runtime. Do not reintroduce the original Core, Team services, HTTP services, role queues, or MCP orchestration into the runtime. S2 learning remains a future extension. Preserve frozen problem/source identities, isolated solver worktrees, Lean receipts, independent evaluation, and resumable runs. A model's completed message is never proof acceptance. diff --git a/README.md b/README.md index d70a71b3..53fa9197 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ https://github.com/user-attachments/assets/57562769-aa15-474c-87ff-73265f097ec8 | 网页工作台与人机协同 | 零信任独立 Lean 验收 (`S1` / `S3`) | M1–M5 可替换策略与实验对比 | | :--- | :--- | :--- | -| 内置 [`apps/web`](./apps/web/) 科研工作台,支持自然语言、TeX 与单文件 Lean 输入、后台语义审查、共同推进/自动推进模式与实时 Lean 反馈视图。 | 模型输出“已完成”或局部引理通过**从不替代最终验收**;[`evaluation.ts`](./src/solver/evaluation.ts) 固定完整原题与环境独立重验,[`archive.ts`](./src/solver/archive.ts) 完整保留每轮尝试、报错与用量以便断点续跑。 | 将证明构造、检查反馈、搜索调度、上下文筛选与协作分工拆分为 5 个带版本的 TypeScript 组件,可在不改宿主运行时和验收规则的前提下开展对照消融实验。 | +| 内置 [`apps/web`](./apps/web/) 科研工作台,支持自然语言、TeX 与单文件 Lean 输入、后台语义审查、Codex 原生团队、可选的首轮路线审批与实时 Lean 反馈视图。 | 模型输出“已完成”或局部引理通过**从不替代最终验收**;[`evaluation.ts`](./src/solver/evaluation.ts) 固定完整原题与环境独立重验,[`archive.ts`](./src/solver/archive.ts) 完整保留每轮尝试、报错与用量以便断点续跑。 | 将证明构造、检查反馈、搜索调度、上下文筛选与协作分工拆分为 5 个带版本的 TypeScript 组件,历史对照消融实验可用各自固定的版本复现。 | | 仓库 | 定位与内容 | 许可证 | | --- | --- | --- | @@ -115,13 +115,10 @@ docker compose -f apps/web/compose.yml -f apps/web/compose.ghcr.yml up -d --no-b ```bash bun run math component init --name my-search bun run math component check --name my-search - -export THEOREMOS_COMPONENT_CASE="$PWD/../theorem-os-runs/my-search" -bun run math example prepare --dir "$THEOREMOS_COMPONENT_CASE" --component my-search --workers 3 -bun run math example check --dir "$THEOREMOS_COMPONENT_CASE" -bun run math example resume --dir "$THEOREMOS_COMPONENT_CASE" ``` +新版协作由 Codex Lead 派工。旧宿主协作的档案继续可查,续跑和 M3 调度对照使用各自固定的历史版本。[续跑说明](./docs/usage.md#4-恢复运行) + --- @@ -174,7 +171,7 @@ bun run math example resume --dir "$THEOREMOS_COMPONENT_CASE" ## 五个可替换研究组件与核心文档 -系统将“策略决策”与“结果验收”严格隔离(完整契约见 [`docs/solver-modules.md`](./docs/solver-modules.md) 与 [`src/solver/modules/index.ts`](./src/solver/modules/index.ts)): +系统将策略决策与结果验收分开。下表也列出了解读历史调度实验所需的 M3 任务排序与 M5 固定角色契约。新版团队的分工由 Codex Lead 决定。[模块说明](./docs/solver-modules.md) | 组件 / 层级 | 核心职责 | 实现入口 | 文档与示例 | | --- | --- | --- | --- | diff --git a/README_EN.md b/README_EN.md index a1a3d4ef..7a048a80 100644 --- a/README_EN.md +++ b/README_EN.md @@ -53,7 +53,7 @@ https://github.com/user-attachments/assets/57562769-aa15-474c-87ff-73265f097ec8 | Web Workbench & Human Control | Zero-Trust Acceptance (`S1` / `S3`) | Replaceable M1–M5 Modules | | :--- | :--- | :--- | -| Built-in [`apps/web`](./apps/web/) UI supporting natural language, TeX, or single-file Lean input, background semantic review, cooperative/autonomous modes, and live Lean diagnostics. | A model claiming completion or local helper passes **never counts as theorem acceptance**; [`evaluation.ts`](./src/solver/evaluation.ts) re-verifies the frozen original problem cleanly, while [`archive.ts`](./src/solver/archive.ts) checkpoints every attempt for pause and resume. | Decouples proof construction, evidence checks, search scheduling, context assembly, and role assignment into versioned TypeScript interfaces for controlled ablation studies under identical problems and acceptance checks. | +| Built-in [`apps/web`](./apps/web/) UI supporting natural language, TeX, or single-file Lean input, background semantic review, native Codex teams, optional initial route approval, and live Lean diagnostics. | A model claiming completion or local helper passes **never counts as theorem acceptance**; [`evaluation.ts`](./src/solver/evaluation.ts) re-verifies the frozen original problem cleanly, while [`archive.ts`](./src/solver/archive.ts) checkpoints every attempt for pause and resume. | Decouples proof construction, evidence checks, search scheduling, context assembly, and role assignment into versioned TypeScript interfaces used by past ablation studies. Use the pinned revision to reproduce a study. | | Repository | Scope & Contents | License | | --- | --- | --- | @@ -116,13 +116,10 @@ Swap individual research policies without altering the host verification loop or ```bash bun run math component init --name my-search bun run math component check --name my-search - -export THEOREMOS_COMPONENT_CASE="$PWD/../theorem-os-runs/my-search" -bun run math example prepare --dir "$THEOREMOS_COMPONENT_CASE" --component my-search --workers 3 -bun run math example check --dir "$THEOREMOS_COMPONENT_CASE" -bun run math example resume --dir "$THEOREMOS_COMPONENT_CASE" ``` +The Codex Lead assigns work in current collaborative runs. You can still inspect older host-scheduled runs. Resume them and reproduce M3 scheduling experiments with their respective pinned historical revisions. [Resume guide](./docs/harness-portability.md#resume-and-isolation) + --- @@ -175,7 +172,7 @@ bun run math example resume --dir "$THEOREMOS_COMPONENT_CASE" ## Five Replaceable Research Components -TheoremOS separates high-level search strategy from proof verification (full contracts in [`docs/solver-modules.md`](./docs/solver-modules.md) and [`src/solver/modules/index.ts`](./src/solver/modules/index.ts)): +TheoremOS separates research decisions from proof verification. The table includes the historical M3 task ordering and M5 fixed-role contracts used to interpret scheduling experiments. The Codex Lead assigns work in current teams. [Module guide](./docs/solver-modules.md) | Component / Layer | Responsibility | Implementation | Guide & Examples | | --- | --- | --- | --- | diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 7e85d337..af113e7b 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -109,6 +109,7 @@ ENV THEOREMOS_CODEX_BACKEND_EXECUTABLE=/opt/theoremos-codex-backend/codex USER 10001:10001 RUN timeout 30s python3 scripts/codex-backend/check-capabilities.py "$THEOREMOS_CODEX_BACKEND_EXECUTABLE" LABEL org.theoremos.native-agent-control=v1 +LABEL org.theoremos.native-team-workflow=v1 LABEL org.theoremos.team-profile-preferences=v1 LABEL org.theoremos.team-expert-cards=v1 LABEL org.theoremos.worker-control=v1 diff --git a/apps/web/client/app.ts b/apps/web/client/app.ts index 383e4283..ef92cc5f 100644 --- a/apps/web/client/app.ts +++ b/apps/web/client/app.ts @@ -7,7 +7,7 @@ import { LogOut, Plus, RefreshCw, RotateCcw, Save, Search, ShieldCheck, SlidersHorizontal, Square, SquarePen, Sun, Trash2, TriangleAlert, Undo2, Upload, X, } from 'lucide'; import type { WebAdminOverview, WebContinuation, WebCoordination, WebEffort, WebEnvironment, WebPrecheck, WebPrecheckDiagnostic, WebProofOutline, WebRun, WebRunRequest, WebSavedKey, WebSession } from '../shared'; -import { accountLogin, loginHref } from '../shared'; +import { accountLogin, loginHref, retiredResearchCoordinationCode } from '../shared'; import { webTaskEnvironment } from '../environment'; import { configurationRefs, ResearchSelection } from './researchSelection'; import type { ResearchAsset } from '../researchAssetTypes'; @@ -44,9 +44,11 @@ import { RunUpdates } from './runUpdates'; import { retainLatestRun } from './runSnapshot'; import type { WebCommandResult, WebObservation } from '../collaboration'; import { ServerModulePlans } from './serverModulePlans'; +import type { KnowledgeCatalog } from './knowledgeView'; import { ModulePlanLibrary, modulePlanLibraryStorageKey } from './modulePlanLibrary'; import { ModulePlanLibraryView } from './modulePlanLibraryView'; import type { ResearchModuleSlot } from '../../../src/solver/modules/policy'; +import { MIN_TEAM_AGENTS } from '../../../src/solver/teamCapacity'; import { draftOwnerStorageKey, OwnedDrafts, researchEntryStorageKey, webDraftOwner } from './ownedDrafts'; import { SubmissionIdentity } from './submissionIdentity'; import { automaticExplanationSettings } from './automaticExplanation'; @@ -540,6 +542,7 @@ function clearOwnedDrafts() { chatWorkspace?.bindOwner(''); renderProblemDraftPanel(problemDraftHost); problemDraftHost.hidden = true; researchSelection.reset(); + serverModulePlans.setKnowledgeCatalogs(); collaborationView?.clearPlanDrafts(); submissionSequence++; draftReady = false; draftDirty = false; clearTimeout(draftTimer); @@ -629,7 +632,7 @@ function renderRunViewsLoading(panel: HTMLElement) { const runUpdates = new RunUpdates(version => { if (pageActive && state.connected && !document.hidden && version !== state.runsEtag) requestRunsRefresh(); }, schedulePoll); -const serverModulePlans = new ServerModulePlans(element('#module-plan'), api, () => modulePlanEditor.value(), +const serverModulePlans = new ServerModulePlans(element('#module-plan'), element('#draft-knowledge-catalog'), api, () => modulePlanEditor.value(), plan => modulePlanEditor.setValue(plan), () => draftChanged()); const modulePlanLibrary = new ModulePlanLibraryView(element('#module-plan-library'), new ModulePlanLibrary(() => localStorage), () => modulePlanEditor.value(), plan => { modulePlanEditor.setValue(plan); draftChanged(); }); @@ -704,7 +707,7 @@ const pause = (ms: number, signal: AbortSignal) => new Promise((resolve, r }); /** `message` is what the reader sees; `reason` keeps the server's own text for checks such as sessionFailure. */ class ApiError extends Error { - constructor(readonly reason: string, readonly status: number, readonly retryAt = 0) { super(localizeMessage(reason)); } + constructor(readonly reason: string, readonly status: number, readonly retryAt = 0, readonly code?: string) { super(localizeMessage(reason)); } } type ApiInit = RequestInit & { timeoutMs?: number; firstResponseTimeoutMs?: number }; const sameSession = (session: WebSession | undefined) => session?.draftOwner === state.session?.draftOwner && session?.csrfToken === state.session?.csrfToken; @@ -802,7 +805,7 @@ async function api(url: string, { timeoutMs = 15_000, firstResponseTimeoutMs, } const body = payload && typeof payload === 'object' - ? payload as { error?: unknown; cloudflare_error?: unknown; error_code?: unknown; retryable?: unknown; retry_after?: unknown } + ? payload as { error?: unknown; code?: unknown; cloudflare_error?: unknown; error_code?: unknown; retryable?: unknown; retry_after?: unknown } : undefined; const cloudflare = body?.cloudflare_error === true ? body : undefined; const limited = response.status === 429 || cloudflare?.error_code === 1015; @@ -823,7 +826,8 @@ async function api(url: string, { timeoutMs = 15_000, firstResponseTimeoutMs, else if (!cloudflare && typeof body?.error === 'string') reason = body.error; else if (limited) reason = limitMessage; else if (retryable) reason = t('服务暂时不可用,请稍后重试'); - const error = new ApiError(reason, limited && !challenged ? 429 : response.status, retryAt); + const code = !challenged && !cloudflare && typeof body?.code === 'string' ? body.code : undefined; + const error = new ApiError(reason, limited && !challenged ? 429 : response.status, retryAt, code); if (retryAt > now) { if (!challenged && !cloudflare && limited && response.headers.get('X-Theoremos-Rate-Limit-Scope') === 'api') { @@ -960,13 +964,15 @@ function openSettings(focusId?: string) { document.body.dataset.draftPreview = 'false'; element('#open-draft-preview').setAttribute('aria-expanded', 'false'); } - modulePlanLibrary.refresh(); - void serverModulePlans.refresh(); if (!dialog.open && (preview || document.body.dataset.mobileView === 'runs')) { settingsWorkspaceReturn = { focus: document.activeElement instanceof HTMLElement ? document.activeElement : undefined, preview }; setMobileView('compose'); } showDialog(dialog); + const session = state.session; + if (session && state.connected) void api<{ catalogs: KnowledgeCatalog[] }>('/api/knowledge/catalogs') + .then(({ catalogs }) => { if (sameSession(session)) serverModulePlans.setKnowledgeCatalogs(catalogs); }) + .catch(() => { /* Keep the selected digest and the default choices if catalogs are unavailable. */ }); if (focusId) { // The field's section starts at the top of the pane, so the end of the section above does not show over it. const control = element(`#${focusId}`), section = control.closest('.settings-content .form-section'); @@ -1279,7 +1285,9 @@ function sourceChanged() { draftChanged(); } function captureDraft(): TaskDraft { - const modulePlan = modulePlanEditor.value(); + // Retain a legacy draft's exact settings while its last submission is unresolved. + const replayUncertain = submissionIdentity.unresolved; + const modulePlan = replayUncertain ? modulePlanEditor.value() : undefined; const knowledgeDigest = serverModulePlans.knowledgeDigest(); const nativeTeam = field('research-mode').value === 'native-team'; const skillMode = nativeTeam || field('research-mode').value === 'skill'; @@ -1288,15 +1296,15 @@ function captureDraft(): TaskDraft { ...(draftExplanationLanguage === undefined ? {} : { explanationLanguage: draftExplanationLanguage }), effort: field('effort').value as WebEffort, environment: field('environment').value as WebEnvironment, source: field('source').value, task: field('task').value, templateId: field('template').value, - maxTurns: field('max-turns').value, maxRunSeconds: field('max-seconds').value, workers: nativeTeam ? '1' : field('workers').value, + maxTurns: field('max-turns').value, maxRunSeconds: field('max-seconds').value, workers: nativeTeam || !replayUncertain ? '1' : field('workers').value, ...(field('max-tokens').value ? { maxTotalTokens: field('max-tokens').value } : {}), - coordination: nativeTeam ? 'independent' : element('input[name="coordination"]:checked').value as WebCoordination, + coordination: nativeTeam || !replayUncertain ? 'independent' : element('input[name="coordination"]:checked').value as WebCoordination, ...(nativeTeam ? { nativeTeamCapacity: Number(field('native-team-capacity').value) } : {}), ...(nativeTeam && draftTeamProfiles.length ? { nativeTeamPreferredProfiles: [...draftTeamProfiles] } : {}), ...(skillMode ? { researchMode: 'skill' as const, skillLoading: field('skill-loading').value as 'native' | 'file' } : {}), - ...(!nativeTeam && element('#plan-approval').checked ? { planApproval: true as const } : {}), + ...((nativeTeam || replayUncertain) && element('#plan-approval').checked ? { planApproval: true as const } : {}), ...(knowledgeDigest !== undefined ? { knowledgeDigest } : {}), - ...(!nativeTeam && (modulePlan.custom.length || modulePlan.scheduler !== 'plan' || modulePlan.context !== 'full') ? { modulePlan } : {}), + ...(!nativeTeam && modulePlan && (modulePlan.custom.length || modulePlan.scheduler !== 'plan' || modulePlan.context !== 'full') ? { modulePlan } : {}), ...(draftContinuation ? { continueFrom: draftContinuation } : {}), ...(budgetDraftOrigin && budgetDraftOrigin.source === field('source').value && budgetDraftOrigin.environment === field('environment').value ? { problemBudget: { runId: budgetDraftOrigin.runId, ...(budgetDraftOrigin.projectId ? { projectId: budgetDraftOrigin.projectId } : {}) } } : {}), @@ -1413,16 +1421,20 @@ async function recoverDraft() { toast(tx('暂时无法恢复固定依赖,两份草稿均已保留,请重新撤销。', 'Could not restore the fixed dependencies. Your drafts are preserved; retry Undo. ') + message(error)); } finally { restoringDraft = false; renderDraftRecovery(); } } -/** 先审计划 holds the Agents after the Lead's plan, so it needs a Lead and at least one other Agent. */ -const planApprovalAvailable = () => field('research-mode').value !== 'native-team' && element('input[name="coordination"]:checked').value === 'cooperative' && Number(field('workers').value) >= 2; +const defaultNativeTeamCapacity = 3; +const planApprovalAvailable = () => field('research-mode').value === 'native-team' && Boolean(state.session?.runtime.nativeTeam); +function usesNativeTeam(providerId: string) { + const harness = state.session?.providers.find(item => item.id === providerId)?.harness; + return !harness || harness === 'codex'; +} function syncResearchMode() { const provider = state.session?.providers.find(item => item.id === field('provider').value); - const portable = Boolean(provider?.harness && provider.harness !== 'codex'); + const portable = !usesNativeTeam(field('provider').value); const mode = field('research-mode') as HTMLSelectElement, loading = field('skill-loading') as HTMLSelectElement; const teamAvailable = Boolean(provider && !portable && state.session?.runtime.nativeTeam); - for (const option of mode.options) option.disabled = option.value === 'native-team' ? !teamAvailable : portable && option.value === 'legacy'; + if (!submissionIdentity.unresolved) mode.value = portable ? 'skill' : 'native-team'; for (const option of loading.options) option.disabled = portable && option.value === 'native'; - if (portable && mode.value !== 'native-team') { mode.value = 'skill'; loading.value = 'file'; } + if (portable && mode.value === 'skill') loading.value = 'file'; const efforts = field('effort') as HTMLSelectElement; for (const option of efforts.options) { const supported = provider?.harness === 'cli' ? Boolean(provider.efforts?.includes(option.value as WebEffort)) : option.value !== 'none'; @@ -1431,19 +1443,15 @@ function syncResearchMode() { if (Array.from(efforts.options).find(option => option.value === efforts.value)?.disabled) efforts.value = provider?.efforts?.[0] ?? 'high'; const team = mode.value === 'native-team', skill = team || mode.value === 'skill'; - field('workers').disabled = team; - field('workers').parentElement!.hidden = team; - element('fieldset.coordination').hidden = team; - for (const radio of document.querySelectorAll('input[name="coordination"]')) radio.disabled = team; + field('workers').disabled = true; + for (const radio of document.querySelectorAll('input[name="coordination"]')) radio.disabled = true; + patchText(element('#current-research-mode'), team ? t('Codex 原生团队') : t('单 Agent 研究')); element('#native-team-field').hidden = !team; if (team) refreshPersonalExperts(); element('#native-team-profiles').hidden = !state.session?.runtime.nativeTeamPreferences && !draftTeamProfiles.length; element('#native-team-unavailable').hidden = !team || teamAvailable; - element('#research-mode-note').hidden = !skill || team; - element('#skill-loading-field').hidden = !skill; - element('.plan-approval-option').hidden = team; - element('#module-plan').hidden = team; - element('[data-settings-section="module-plan"]').hidden = team; + element('#skill-loading-field').hidden = !skill || portable; + element('.plan-approval-option').hidden = !team; } function draftChanged(persist = true) { syncResearchMode(); @@ -1506,7 +1514,7 @@ function applyTaskDraft(draft: TaskDraft, fixedEnvironment?: WebEnvironment) { field('template').value = template?.id ?? ''; element(`input[name="coordination"][value="${draft.coordination}"]`).checked = true; field('research-mode').value = draft.nativeTeamCapacity ? 'native-team' : draft.researchMode ?? 'legacy'; - field('native-team-capacity').value = String(draft.nativeTeamCapacity ?? 3); + field('native-team-capacity').value = String(draft.nativeTeamCapacity ?? defaultNativeTeamCapacity); setDraftTeamProfiles(draft.nativeTeamPreferredProfiles); field('skill-loading').value = draft.skillLoading ?? 'native'; element('#plan-approval').checked = Boolean(draft.planApproval); @@ -1549,12 +1557,18 @@ async function importTaskFile(file: File) { const sequence = ++taskImportSequence, revision = draftRevision; element('#draft-error').hidden = true; try { - const draft = editableTaskDraft(await readTaskDraftFile(file), submissionIdentity.unresolved); + const fileDraft = await readTaskDraftFile(file); + const unresolved = submissionIdentity.unresolved; + const draft = editableTaskDraft(fileDraft, unresolved); if (sequence !== taskImportSequence) return; if (revision !== draftRevision || state.submitting) { toast(t('草稿已变化,未导入文件')); return; } pendingImport = { draft, revision }; element('#import-filename').textContent = file.name; const provider = state.session?.providers.find(provider => provider.id === draft.providerId); + const portable = Boolean(provider?.harness && provider.harness !== 'codex'); + const nativeTeam = unresolved ? Boolean(draft.nativeTeamCapacity) : !portable; + const teamSize = draft.nativeTeamCapacity ?? defaultNativeTeamCapacity; + const workers = unresolved ? draft.workers : '1'; const plan = draft.modulePlan; const schedulerLabels = { plan: t('按研究计划'), 'critical-path': t('优先关键路径'), continuation: t('延续证明前沿') }; const planSummary = [schedulerLabels[plan?.scheduler ?? 'plan'], plan?.context === 'essential' ? t('精简研究上下文') : t('完整研究上下文'), @@ -1563,12 +1577,12 @@ async function importTaskFile(file: File) { [t('服务商'), provider?.name ?? t('{0} · 当前不可用', draft.providerId || t('未选择'))], [t('模型'), draft.model || t('未填写'), true], [t('推理强度'), effortLabels[draft.effort] ?? draft.effort], [t('轮次上限'), Number(draft.maxTurns) ? draft.maxTurns : t('不限')], [t('解题预算 / 秒'), Number(draft.maxRunSeconds) ? draft.maxRunSeconds : t('不限')], - [draft.nativeTeamCapacity ? t('团队人数上限(含 Lead)') : t('Agent 数量'), String(draft.nativeTeamCapacity ?? (draft.workers || t('未填写')))], - ...(draft.nativeTeamPreferredProfiles?.length ? [[t('角色偏好(可选)'), draft.nativeTeamPreferredProfiles.join(', ')] as [string, string]] : []), + [nativeTeam ? t('团队人数上限(含 Lead)') : t('Agent 数量'), nativeTeam ? String(teamSize) : workers || t('未填写')], + ...(nativeTeam && draft.nativeTeamPreferredProfiles?.length ? [[t('角色偏好(可选)'), draft.nativeTeamPreferredProfiles.join(', ')] as [string, string]] : []), [t('用量上限 / 万 Token'), Number(draft.maxTotalTokens) ? draft.maxTotalTokens! : t('不限')], - ...(!draft.nativeTeamCapacity ? [[t('模块方案'), planSummary] as [string, string]] : []), - [t('协作模式'), draft.nativeTeamCapacity ? t('Codex 原生团队') : draft.coordination === 'cooperative' ? t('任务协作') : t('独立并行')], - ...(draft.planApproval ? [[t('先审计划'), t('开启')] as [string, string]] : [])]); + ...(!nativeTeam && unresolved && plan ? [[t('模块方案'), planSummary] as [string, string]] : []), + [t('研究方式'), nativeTeam ? t('Codex 原生团队') : workers === '1' ? t('单 Agent 研究') : draft.coordination === 'cooperative' ? t('任务协作') : t('独立并行')], + ...(draft.planApproval && (nativeTeam || unresolved) ? [[t('先审路线再开工'), t('开启')] as [string, string]] : [])]); element('#import-task-preview').textContent = draft.task || t('未填写'); element('#import-source-preview').textContent = draft.source || t('未填写'); renderImportState(); @@ -2209,14 +2223,14 @@ function renderPanel(force = false) { } onDetailLevel(() => { if (state.tab === 'result') renderPanel(true); }); function moduleInput(run?: WebRun): ModuleViewInput { + const draft = run ? undefined : captureDraft(); return { id: run?.id ?? 'draft', run, model: run?.model ?? field('model').value, - researchMode: run ? run.researchMode : captureDraft().researchMode, - nativeTeamCapacity: run ? run.nativeTeamCapacity : captureDraft().nativeTeamCapacity, - workers: run?.workers ?? Number(captureDraft().workers), - coordination: run?.coordination ?? element('input[name="coordination"]:checked').value as WebCoordination, + researchMode: run ? run.researchMode : draft?.researchMode, + nativeTeamCapacity: run ? run.nativeTeamCapacity : draft?.nativeTeamCapacity, + workers: run?.workers ?? Number(draft?.workers), + coordination: run?.coordination ?? draft?.coordination ?? 'independent', environment: environmentName(run?.environment ?? field('environment').value), connected: state.connected, - editable: !run && Boolean(state.session) && !state.submitting, - modulePlan: run ? run.modulePlan : captureDraft().modulePlan }; + editable: false, modulePlan: run ? run.modulePlan : draft?.modulePlan }; } function renderDraftPreview(force = false) { if (currentRun() || !state.session || opening()) return; @@ -2440,14 +2454,15 @@ async function checkWorkbenchApproval(run: WebRun, retry = true) { } /** The banner also stays available to reconcile an older decision after the current plan changes. */ function approvalProps(run: WebRun): RunHeaderProps['approval'] { - if (webSkillWithoutCooperation(run)) return; + if (!run.nativeTeamCapacity && webSkillWithoutCooperation(run)) return; const approval = planAwaitingApproval(run), observation = run.observation; if (!observation || isSample(run) || !approval && !run.planApproval && !observation.inspection.planApproval?.required) return; const identity = personalApprovalOwner(), view = identity?.owner ? personalApprovalView(identity.owner, run) : undefined; if (!approval && !view?.pending) return; const needsReview = Boolean(view?.reviewRequired || view?.reviewedVersion && view.reviewedVersion !== approval?.planVersion); const error = identity?.error ?? view?.error; - return { tasks: observation.inspection.tasks.length, revising: approval?.leadRevising ?? false, + return { tasks: observation.plan?.tasks.length ?? observation.inspection.tasks.length, + nativeTeam: Boolean(run.nativeTeamCapacity), revising: approval?.leadRevising ?? false, busy: !identity?.owner || Boolean(view?.pending || view?.storageError || needsReview || view?.busy), checking: identity?.loading || view?.busy, reviewable: Boolean(approval && observation.plan && observation.plan.baseVersion === approval.planVersion && observation.plan.baseVersion === observation.inspection.planVersion), ...(error ? { error } : {}), ...(view?.pending ? { original: { ...view.pending, ...(view.receipt ? { status: view.receipt.status } : {}) } } : {}), @@ -2853,7 +2868,7 @@ async function openBudgetAttemptDraft() { } const configuration = own ? run.researchConfiguration : undefined; const refs = configurationRefs(configuration); - const selected = refs.length ? await researchSelection.prepare(refs, run.environment, Boolean(run.nativeTeamCapacity)) : undefined; + const selected = refs.length ? await researchSelection.prepare(refs, run.environment, usesNativeTeam(isSample(run) ? field('provider').value : run.providerId)) : undefined; if (!state.session || ownerOfSession(state.session) !== owner || draftRevision !== revision || state.submitting) throw new Error(t('草稿已变化,未载入预算规划。请核对后重新准备。')); const issue = submissionIssues({ ...captureDraft(), source: run.source, task: run.task }, '', state.session).find(issue => issue.field === 'source' || issue.field === 'task'); @@ -3496,7 +3511,7 @@ element('#run-form').addEventListener('submit', async event => const epoch = state.connectionEpoch; const returnFocus = document.activeElement instanceof HTMLElement && document.activeElement !== document.body ? document.activeElement : field('task'); const submission = ++submissionSequence; - let sent = false, failed = false; + let requestId: string | undefined, sent = false, failed = false; const issues = currentSubmissionIssues(); if (issues.length) { for (const issue of issues) validationShown.add(issue.field); @@ -3521,7 +3536,7 @@ element('#run-form').addEventListener('submit', async event => ...(capturedDraft.nativeTeamCapacity ? { nativeTeamCapacity: capturedDraft.nativeTeamCapacity } : {}), ...(capturedDraft.nativeTeamPreferredProfiles?.length ? { nativeTeamPreferredProfiles: capturedDraft.nativeTeamPreferredProfiles } : {}), ...(capturedDraft.researchMode ? { researchMode: capturedDraft.researchMode, skillLoading: capturedDraft.skillLoading } : {}), - ...(element('#plan-approval').checked && planApprovalAvailable() ? { planApproval: true } : {}), + ...(capturedDraft.planApproval ? { planApproval: true } : {}), ...(capturedDraft.modulePlan ? { modulePlan: capturedDraft.modulePlan } : {}), ...(capturedDraft.knowledgeDigest !== undefined ? { knowledgeDigest: capturedDraft.knowledgeDigest } : {}), ...(draftContinuation ? { continueFrom: draftContinuation } : {}), @@ -3535,7 +3550,7 @@ element('#run-form').addEventListener('submit', async event => syncKeyMemory(); closeSettings(false); state.submitting = true; renderRuntime(); - input.requestId = await submissionIdentity.prepare(input); + requestId = input.requestId = await submissionIdentity.prepare(input); if (!currentConnection(epoch)) return; saveDraft(); sent = true; @@ -3575,7 +3590,15 @@ element('#run-form').addEventListener('submit', async event => if (submission !== submissionSequence) return; const key = field('api-key').value.trim(); const uncertain = sent && (!(error instanceof ApiError) || error.status >= 500); - const text = uncertain ? t('提交结果尚未确认,请先核对运行记录后再决定是否重新提交。') : message(error); + const retired = sent && currentConnection(epoch) && error instanceof ApiError && error.status === 400 + && error.code === retiredResearchCoordinationCode; + if (retired) { + // The server checked for a replay and refused creation. Save the migrated draft for a new explicit submission. + submissionIdentity.clear(requestId); + draftChanged(); saveDraft(); + } + const text = retired ? t('旧协作请求没有创建运行。草稿已切换到当前研究方式,可以重新提交。') + : uncertain ? t('提交结果尚未确认,请先核对运行记录后再决定是否重新提交。') : message(error); errorBox.textContent = key ? text.split(key).join(t('[已隐藏]')) : text; errorBox.hidden = false; if (sent && currentConnection(epoch) && (uncertain || sessionFailure(error))) { @@ -3804,7 +3827,7 @@ async function copyText(text: string, success: string) { } catch { toast(t('无法访问剪贴板')); } } const recoveryFields: Record, string> = { - retry: 'api-key', key: 'api-key', budget: 'max-seconds', tokens: 'max-tokens', turns: 'max-turns', workers: 'workers', source: 'source', task: 'task' }; + retry: 'api-key', key: 'api-key', budget: 'max-seconds', tokens: 'max-tokens', turns: 'max-turns', workers: 'native-team-capacity', source: 'source', task: 'task' }; /** 提高: twice the run's own limit, up to what a run may ask for. */ const raised = (value: number, highest: number) => Math.min(highest, Math.max(1, value) * 2); async function recoverRun(run: WebRun, action: string, button: HTMLButtonElement) { @@ -3838,7 +3861,7 @@ async function reuseRun(run: WebRun, recovery: Exclude(`input[name="coordination"][value="${run.coordination}"]`).checked = true; field('research-mode').value = run.nativeTeamCapacity ? 'native-team' : run.researchMode ?? 'legacy'; - field('native-team-capacity').value = String(run.nativeTeamCapacity ?? 3); + const capacity = run.nativeTeamCapacity ?? defaultNativeTeamCapacity; + field('native-team-capacity').value = String(recovery === 'workers' ? Math.max(MIN_TEAM_AGENTS, capacity - 1) : capacity); setDraftTeamProfiles(run.nativeTeamPreferredProfiles); field('skill-loading').value = run.skillLoading ?? 'native'; element('#plan-approval').checked = Boolean(run.planApproval); @@ -3941,7 +3965,6 @@ element('#run-detail').addEventListener('click', event => { return; } const draftAction = (event.target as Element).closest('[data-draft-action]'); - if ((event.target as Element).closest('[data-module-configure]') && !currentRun()) { openSettings('module-plan'); return; } if (draftAction?.dataset.draftAction === 'edit') { if (currentRun()) return; const source = field('source').value, position = sourceReader.editingPosition('draft', source); diff --git a/apps/web/client/chatSession.ts b/apps/web/client/chatSession.ts index ebd3a154..04bc57c3 100644 --- a/apps/web/client/chatSession.ts +++ b/apps/web/client/chatSession.ts @@ -99,7 +99,7 @@ export class ChatSession { private researchEffort: 'low' | 'high' | 'max' = 'high'; private autoExplain: ChatDraftSettings['autoExplain'] = true; private explanationLanguage: ChatDraftSettings['explanationLanguage'] = locale; - private participation: 'guided' | 'automatic' = 'guided'; + private participation: 'guided' | 'automatic' = 'automatic'; private apiKey = ''; private keyBusy = false; private keyNotice = ''; @@ -224,7 +224,7 @@ export class ChatSession { this.summaries = []; this.historyLoaded = false; this.historyFailed = false; this.capabilities = undefined; this.formalizations = []; this.providerId = ''; this.model = ''; this.environment = 'mathlib'; this.effort = 'high'; this.researchEffort = 'high'; this.autoExplain = true; this.explanationLanguage = locale; - this.participation = 'guided'; this.budgets = structuredClone(webFormalizationDefaults); this.hasDraftSettings = false; + this.participation = 'automatic'; this.budgets = structuredClone(webFormalizationDefaults); this.hasDraftSettings = false; this.keyBusy = false; this.lastTaskRefresh = 0; this.lastListRefresh = 0; this.lastActionPoll = 0; this.liveShown.clear(); this.liveSelected.clear(); this.solveCache = undefined; @@ -420,6 +420,14 @@ export class ChatSession { } finally { if (ownerRevision === this.ownerRevision) { this.keyBusy = false; this.draw(); } } } private activeProviderId() { return this.run?.providerId ?? this.formalization?.providerId ?? this.providerId; } + private guidedAvailable() { + const session = this.options.session(); + const provider = session?.providers.find(item => item.id === this.activeProviderId()); + return Boolean(session?.runtime.nativeTeam && provider && (provider.harness ?? 'codex') === 'codex'); + } + private requestedParticipation() { + return this.seed || this.submissionIdentity.unresolved || this.guidedAvailable() ? this.participation : 'automatic'; + } private activeModel() { return this.run?.model ?? this.formalization?.model ?? this.model; } private get tabKeyProvider() { const session = this.options.session(); @@ -858,7 +866,7 @@ export class ChatSession { const settings = { providerId: this.providerId, model: this.model.trim(), environment: this.environment, effort: this.effort, autoExplain: this.autoExplain, explanationLanguage: this.explanationLanguage, ...(this.researchEffort !== this.effort ? { researchEffort: this.researchEffort } : {}), ...this.budgets, - ...(this.participation === 'guided' ? { humanReview: true } : {}) }; + ...(this.requestedParticipation() === 'guided' ? { humanReview: true } : {}) }; const input = { original: text, ...settings, apiKey: key, solve: true }; let formalization = seed; if (!formalization) { @@ -1222,9 +1230,10 @@ export class ChatSession { private draw() { this.refreshGuidanceFeedback(); const pending = Boolean(this.conversation?.messages.some(message => message.kind === 'text' && message.status === 'pending')); - const canDecide = !!this.run && ['queued', 'running'].includes(this.run.status) && this.run.coordination === 'cooperative' - && this.run.workers > 1 && !this.options.isSample(this.run); - const showGuidance = canDecide && !!this.conversation; + const activeRun = !!this.run && ['queued', 'running'].includes(this.run.status) && !this.options.isSample(this.run); + const canEditPlan = activeRun && this.run?.coordination === 'cooperative' && this.run.workers > 1; + const canDecide = canEditPlan || activeRun && Boolean(this.run?.nativeTeamCapacity && this.run.planApproval); + const showGuidance = canEditPlan && !!this.conversation; const canGuide = showGuidance && this.run?.status === 'running' && !!this.run.observation?.plan; const guidance = this.activeGuidance, taskRef = guidance?.taskRef; const task = this.run?.observation?.inspection.tasks.find(item => item.id === taskRef?.id); @@ -1239,7 +1248,8 @@ export class ChatSession { if (newProblem && !this.seed && !pendingSubmission) this.environment = webTaskEnvironment; const busyFormalization = newProblem && !this.seed && !pendingSubmission && !!this.capabilities && this.formalizations.filter(item => running(item)).length >= this.capabilities.limits.perOwner; - const unavailable = newProblem && !pendingSubmission && this.capabilities?.available === false; + const solveAvailable = this.capabilities?.solveAvailable ?? this.capabilities?.available; + const unavailable = newProblem && !pendingSubmission && solveAvailable === false; document.body.dataset.chatEmpty = String(newProblem && !this.loading && !this.seed); const solve = this.solve(); const formalization = this.formalization ?? this.seed; @@ -1297,7 +1307,8 @@ export class ChatSession { } : {}), ...(canGuide ? { onGuidance: (text?: string, taskId?: string) => this.beginGuidance(text, taskId) } : {}), ...(canDecide ? { planDecision: { approval: this.options.planApproval(this.run!), connected: this.options.connected(), - onReview: () => this.options.onPlan(this.run!, false), onEdit: () => this.options.onPlan(this.run!, true), + onReview: () => this.options.onPlan(this.run!, false), + ...(canEditPlan ? { onEdit: () => this.options.onPlan(this.run!, true) } : {}), onApprove: () => this.options.onApprovePlan(this.run!) } } : {}), ...(this.conversation && !this.loading && !this.submitting && !guidance && !(this.run && this.options.isSample(this.run)) ? { onQuestion: (entry: ThinkingStep) => this.questionStep(entry) } : {}), @@ -1364,20 +1375,26 @@ export class ChatSession { || this.awaitingDiscussionModel || editedSubmission || !guidance && !pendingSubmission && !this.pendingMessage && Boolean(this.options.session()?.maintenance) - || newProblem && ((!this.capabilities?.available && !pendingSubmission) || busyFormalization) + || newProblem && ((!solveAvailable && !pendingSubmission) || busyFormalization) || !!guidance && (!canGuide || !this.run?.observation || guidanceRunChanged || staleTarget || !!unresolvedGuidance), hasConversation: Boolean(this.currentId || this.conversation), newProblem, environment: this.environment, effort: this.run?.effort ?? this.formalization?.effort ?? this.effort, apiKey: this.apiKey, ...(editedSubmission ? { submissionRecovery: { busy: this.submitting, onRecover: () => void this.submit(this.seed!.original), onPrepareEdited: () => void this.submit(this.seed!.original, true) } } : {}), - participation: this.participation, participationLocked: Boolean(this.seed || this.submissionIdentity.unresolved || this.run), + participation: this.requestedParticipation(), guidedAvailable: this.guidedAvailable(), + participationLocked: Boolean(this.seed || this.submissionIdentity.unresolved || this.run), onParticipation: value => { this.participation = value; this.rememberDraft(); this.draw(); }, keyRequired: guidance || pendingSubmission || this.pendingMessage || this.tabKey ? false : this.options.keyRequired(this.activeProviderId()), ...(this.tabKeyProvider ? { tabKeyMemory: { remembered: Boolean(this.tabKey), notice: this.keyNotice, onChange: (remember: boolean) => { this.keyNotice = ''; this.setRememberedKey(remember); this.clearConnection(); this.draw(); } } } : {}), providers: this.providers(), providerId: this.activeProviderId(), model: this.activeModel(), - onProvider: value => { this.providerId = value; this.model = this.providers().find(item => item.id === value)?.defaultModel ?? ''; this.apiKey = ''; this.keyNotice = ''; this.clearConnection(); this.rememberDraft(); this.draw(); }, + onProvider: value => { + this.providerId = value; + this.model = this.providers().find(item => item.id === value)?.defaultModel ?? ''; + this.participation = this.requestedParticipation(); + this.apiKey = ''; this.keyNotice = ''; this.clearConnection(); this.rememberDraft(); this.draw(); + }, onModel: value => { this.model = value; this.clearConnection(); this.rememberDraft(); this.draw(); }, quota: this.options.session()?.quota, cost: { owner: this.options.session()?.draftOwner ?? 'anonymous', account: Boolean(this.options.session()?.account), request: this.options.request }, @@ -1412,7 +1429,9 @@ export class ChatSession { : busyFormalization ? t("当前账号的形式化队列已满,输入内容会保留。") : unavailable ? this.capabilities?.reason === 'provider' ? t('当前服务未配置自然语言解题的模型,请联系管理员;也可切换到 Lean 输入。') - : this.options.session()?.runtime.ready + : this.capabilities?.available && this.capabilities.solveAvailable === false + ? t('当前运行镜像未安装原生团队后端。') + : this.options.session()?.runtime.ready ? t('当前服务暂不支持自然语言解题,可切换到 Lean 输入。') : t('运行环境暂未就绪,原题会保留;恢复后可继续发送。') : newProblem && !this.capabilities ? t("正在连接…") @@ -1436,7 +1455,7 @@ export class ChatSession { } this.reading.rendered(); this.drawHistory(); this.drawOriginal(); this.drawLive(solve, { guide: canGuide && !unresolvedGuidance, - edit: canDecide && !!this.run?.observation?.plan && this.options.connected() && !this.options.planApproval(this.run!)?.busy && !this.options.planApproval(this.run!)?.revising }); + edit: canEditPlan && !!this.run?.observation?.plan && this.options.connected() && !this.options.planApproval(this.run!)?.busy && !this.options.planApproval(this.run!)?.revising }); } private drawOriginal() { renderChatOriginal(this.originalPanel, { formalization: this.formalization, run: this.run }); } /** The panel beside the conversation; it keeps the process it was last drawn with while the task did not change. */ diff --git a/apps/web/client/draft.ts b/apps/web/client/draft.ts index 60f48ae6..1eb3269a 100644 --- a/apps/web/client/draft.ts +++ b/apps/web/client/draft.ts @@ -29,7 +29,7 @@ export type TaskDraft = { skillLoading?: 'native' | 'file'; nativeTeamCapacity?: number; nativeTeamPreferredProfiles?: string[]; - /** 先审计划: hold the Agents until the plan is approved. Only `true` is stored; it applies to cooperative runs of 2+ Agents. */ + /** Hold proof work until the initial route is approved. Only `true` is stored. */ planApproval?: true; templateId: string; modulePlan?: ResearchModulePlan; diff --git a/apps/web/client/formalize.ts b/apps/web/client/formalize.ts index f8fa4c42..e268b5a7 100644 --- a/apps/web/client/formalize.ts +++ b/apps/web/client/formalize.ts @@ -165,13 +165,14 @@ function controls() { const usable = state.item?.status === 'confirmed' && !changed && !state.busy; const guided = Boolean(state.item?.humanReview); use.textContent = guided ? t('返回对话') : embedded ? t('继续证明研究') : t('带入研究草稿'); - $('#formalize-confirmed .field-note').textContent = guided ? t('在原对话中启动双 Agent 研究,并审核研究计划。') + $('#formalize-confirmed .field-note').textContent = guided ? t('返回原对话继续研究并审核初始路线。') : t('带入后可设置研究要求,不会自动启动证明。'); use.setAttribute('aria-disabled', String(!usable)); if (usable) use.href = guided ? '/' : `/?formalization=${encodeURIComponent(state.item!.id)}`; else use.removeAttribute('href'); const queueFull = !retry && !!caps && state.items.filter(active).length >= caps.limits.perOwner; - $('#formalize-start').disabled = state.busy || !caps || !caps.available && !retry || !original.value.trim() || queueFull + const available = embedded ? caps?.solveAvailable ?? caps?.available : caps?.available; + $('#formalize-start').disabled = state.busy || !caps || !available && !retry || !original.value.trim() || queueFull || (!embedded && !retry && caps?.key === 'required' && !key.value.trim()); const sendStatus = $('#formalize-send-status'); sendStatus.hidden = !embedded || Boolean(caps) && !queueFull && !state.busy; @@ -197,9 +198,10 @@ function drawCapabilities() { research.maxRunSeconds ? t('{0} 分钟', Math.ceil(research.maxRunSeconds / 60)) : t('不限'), research.maxTurns || t('不限'), research.maxTotalTokens ? research.maxTotalTokens.toLocaleString(localeTag) : t('不限')))); } - const note = $('#formalize-unavailable'); note.hidden = caps.available; + const available = embedded ? caps.solveAvailable ?? caps.available : caps.available; + const note = $('#formalize-unavailable'); note.hidden = available; note.textContent = caps.reason === 'provider' ? t('当前未配置支持形式化的服务商,请联系管理员配置。') : t('当前运行环境尚未支持在线形式化。已有结果仍可查看。'); - if (embedded && !caps.available) $('#formalize-settings').open = true; + if (embedded && !available) $('#formalize-settings').open = true; controls(); } function drawList() { diff --git a/apps/web/client/guide.html b/apps/web/client/guide.html index 287b2222..c74e3c08 100644 --- a/apps/web/client/guide.html +++ b/apps/web/client/guide.html @@ -41,7 +41,7 @@

五步开始

  • 写下原题

    直接在首页输入完整的自然语言或 TeX 原题,包括对象、假设与结论。已有 Lean 文件时,在顶栏「导航」或题目输入方式栏切换到「Lean 源码」粘贴或导入文件,待证部分用 sorry 留空。

  • 选择服务商与模型

    打开输入框下方的「配置模型」(Lean 模式点「研究配置」)选择模型服务商、模型与证明环境。模型名必须是该服务商为你的账号提供的名称;切换服务商会清空未保存的 Key。

  • 连接模型

    填写所选服务商的 API Key。OpenAI 提供创建 Key 的链接;网关账号与 Key 请向该网关管理员获取。可以先点「检查 Key 与模型」,确认账号能访问哪些模型;不支持模型列表的服务需在发送时确认。

  • -
  • 设定预算并发送

    形式化与证明各有时间和 Token 预算,发送前可在「配置模型」或「研究配置」调整。默认「共同推进」由你确认题意,再由 2 个 Agent 拟定初始计划,等你批准后展开证明;「自动推进」由 1 个 Agent 在模型核对后直接开始。费用由模型服务商收取,进行中的请求可能超过设定用量。

  • +
  • 设定预算并发送

    形式化与证明各有时间和 Token 预算,发送前可在「配置模型」或「研究配置」调整。使用 Codex 时,原生团队默认自动推进。其他支持的执行器使用单 Agent 项目技能。费用由模型服务商收取,进行中的请求可能超过设定用量。

  • @@ -63,7 +63,7 @@

    Lean 与自然语言

    原意与 Lean 对照
    在「协作」的「原意与 Lean」分区选择一份声明审阅,查看数学原意、Lean 形式声明、独立回译和审阅结论。研究进行中就能查看已记录的审阅;没有记录时会显示空态。声明审阅通过后,完整证明仍需独立验收。
    Lean → 自然语言
    验收通过且原题含义审核完成后,系统会自动生成讲解,并在对话中显示进度与详细解答。也可点「结果」或「源码」中的「Lean → 自然语言」打开讲解页,切换目标与中英文,逐步对照 Lean 行、引理和自然语言,下载已通过审核的 Markdown。自动生成未完成时,可在讲解页查看原因并重新生成。
    -
    自然语言 → Lean
    首页发送原题后,系统生成 Lean 陈述,并独立回译、审核。在「共同推进」中,你会先看到回译的题意,可核对原题与 Lean、修改题目,或确认后拟定研究计划。「完整审核」保留每次模型审核的结论。
    +
    自然语言 → Lean
    首页发送原题后,系统生成 Lean 陈述,并独立回译、审核。选择「先审路线再开工」后,你可以先核对原题与 Lean,修改题目或确认题意。确认后,原生团队会拟定路线并等你批准。「完整审核」保留每次模型审核的结论。

    证明讲解目前仅支持使用 Sub2API 与 deepseek-flash 的已验收运行,服务也需提供讲解运行环境;不支持时页面会说明原因。示例运行可以打开对照页,但没有预生成讲解,也不能生成。

    @@ -71,8 +71,8 @@

    Lean 与自然语言

    @@ -82,7 +82,7 @@

    看懂结果

    完整原题通过
    所有冻结的 Lean 目标都通过了独立验收。自然语言输入还会单独显示陈述是由模型审核,还是由你确认;Lean 验收本身不验证翻译是否忠实。
    验收未通过
    Agent 交出了候选证明,但独立验收没有通过。报告会写明是哪项检查失败。
    运行结束
    到达轮次、时间或用量上限时还没有完成证明,标签会写明原因,例如「解题时间用完」。已检查的成果保留在报告里,可以提高预算后重新运行。
    -
    运行失败
    Key 无效、服务商限流或环境故障等原因让运行无法继续。对话里会给出对应的处理按钮,例如「更换 API Key」或「减少 Agent 数量」。
    +
    运行失败
    Key 无效、服务商限流或环境故障等原因让运行无法继续。对话里会给出对应的处理按钮,例如「更换 API Key」或「减少团队人数」。
    已取消
    你主动停止了这次运行。

    「候选证明」和「有条件结果」都不算完成:前者还没经过验收,后者依赖一条尚未证明的引理。

    diff --git a/apps/web/client/index.html b/apps/web/client/index.html index 9055efd1..caf5e9ba 100644 --- a/apps/web/client/index.html +++ b/apps/web/client/index.html @@ -100,7 +100,7 @@
    @@ -124,18 +124,18 @@

    执行配置

    - +

    Codex 原生团队

    - -
    +

    -
    协作模式
    -
    -

    需要任务协作及至少 2 个 Agent。等待确认不计入证明预算。

    + + +
    -
    +
    -

    {intent === 'statement' ? tx('写清对象、假设和结论。先核对 Lean 陈述,再批准证明计划。', 'State the objects, assumptions and claim. Review the Lean statement, then approve the proof plan.') +

    {intent === 'statement' ? tx('写清对象、假设和结论。核对 Lean 陈述后,可选择先审初始路线再开始证明。', 'State the objects, assumptions and claim. After reviewing the Lean statement, you can choose to approve the initial route before proving.') : tx('准备完整的 import、定理声明和未完成证明,选择匹配环境后继续。', 'Prepare the imports, theorem statement and unfinished proof, then select the matching environment.')}

    {tx('完成后可阅读证明路线、Lean 源码与独立验收记录。', 'Read the proof route, Lean source and independent acceptance record when the run finishes.')}

    diff --git a/apps/web/client/research-conversation.css b/apps/web/client/research-conversation.css index abca5fd7..f6123af9 100644 --- a/apps/web/client/research-conversation.css +++ b/apps/web/client/research-conversation.css @@ -190,6 +190,8 @@ body[data-chat-empty=true] #research-conversation-panel #natural-research{margin /* The border and ring identify the active editor in both themes. */ #natural-research .chat-composer #formalize-form:has(#formalize-original:focus){border-color:var(--blue-600);box-shadow:0 0 0 1px var(--blue-600),0 18px 42px -18px color-mix(in srgb,var(--blue-600) 28%,transparent),var(--shadow-card)} #natural-research .chat-composer #formalize-original{display:block;width:100%;min-width:0;min-height:92px;max-height:260px;margin:0;padding:12px 14px 10px;border:0;border-radius:10px;background:transparent;color:var(--ink);font:inherit;font-size:16px;line-height:1.75;resize:none;box-shadow:none;overflow-y:auto} +/* The draft restores its own scroll offset, which must survive font swaps. */ +#natural-research .chat-composer #formalize-original{overflow-anchor:none} #natural-research .chat-composer[data-chat-followup=true] #formalize-original{min-height:56px} #natural-research .chat-composer #formalize-original:focus{outline:none} .chat-quote-notice{display:flex;align-items:center;gap:12px;margin:2px 4px 0;padding:2px 10px 6px;border-bottom:1px solid var(--line);color:var(--muted);font-size:12px;line-height:1.5} diff --git a/apps/web/client/researchSelection.ts b/apps/web/client/researchSelection.ts index d6f9e7d1..169b8306 100644 --- a/apps/web/client/researchSelection.ts +++ b/apps/web/client/researchSelection.ts @@ -93,7 +93,8 @@ export class ResearchSelection { })); if (this.releases.filter(release => release.type === 'agent').length > 1) throw new Error(t('每次研究只能选择一个 Agent,请在 Library 调整选择。')); const agent = this.releases.find(release => release.type === 'agent')?.content as { environment?: WebEnvironment } | undefined; - const selectedEnvironment = nativeTeam ? environment : savedEnvironment ?? this.releases.find(release => release.mathematics)?.mathematics?.environment ?? agent?.environment ?? environment; + const libraryEnvironment = this.releases.find(release => release.mathematics)?.mathematics?.environment; + const selectedEnvironment = savedEnvironment ?? libraryEnvironment ?? (nativeTeam ? undefined : agent?.environment) ?? environment; const { item } = await this.api<{ item: FrozenResearchConfiguration }>('/api/research/configuration', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ environment: selectedEnvironment, selection: this.value(), ...(nativeTeam ? { nativeTeam: true } : {}) }) }); this.selectedEnvironment = item.environment; diff --git a/apps/web/client/serverModulePlans.tsx b/apps/web/client/serverModulePlans.tsx index e6c20047..61cc5b76 100644 --- a/apps/web/client/serverModulePlans.tsx +++ b/apps/web/client/serverModulePlans.tsx @@ -8,7 +8,7 @@ import { localizeText, t } from '../i18n'; type SavedPlan = { id: string; name: string; plan: ResearchModulePlan; updatedAt: string; configuration: { methodDigest?: string } }; type Registry = { entries: Array<{ id: string; slot: string; name: string; version: string; fixed: boolean; inputs: string[]; outputs: string[] }> }; -/** Server plans and registered code selections apply to the next run. */ +/** Historical module settings and the knowledge directory for the next run. */ export class ServerModulePlans { private root = createElement('div', 'server-module-plans'); private plans: SavedPlan[] = []; @@ -20,25 +20,30 @@ export class ServerModulePlans { private registry?: Registry; private digest = ''; private catalogs?: KnowledgeCatalog[]; - constructor(host: HTMLElement, private api: WebApi, private getPlan: () => ResearchModulePlan, private setPlan: (plan: ResearchModulePlan) => void, private changed: () => void) { + constructor(host: HTMLElement, private knowledgeRoot: HTMLElement, private api: WebApi, private getPlan: () => ResearchModulePlan, + private setPlan: (plan: ResearchModulePlan) => void, private changed: () => void) { const heading = host.querySelector('.module-plan-heading'); if (heading) heading.after(this.root); else host.prepend(this.root); this.render(); + this.renderKnowledge(); } knowledgeDigest() { return this.digest === '__none__' ? null : this.digest || undefined; } setKnowledgeDigest(digest?: string | null) { - this.digest = digest === null ? '__none__' : digest ?? ''; this.render(); + this.digest = digest === null ? '__none__' : digest ?? ''; this.renderKnowledge(); + } + setKnowledgeCatalogs(catalogs?: KnowledgeCatalog[]) { + this.catalogs = catalogs; + this.renderKnowledge(); } async refresh() { if (this.loading) return; this.pendingDelete = undefined; this.loading = true; this.render(); try { const results = await Promise.allSettled([ - this.api<{ plans: SavedPlan[] }>('/api/module-plans'), this.api('/api/modules'), this.api<{ catalogs: KnowledgeCatalog[] }>('/api/knowledge/catalogs'), + this.api<{ plans: SavedPlan[] }>('/api/module-plans'), this.api('/api/modules'), ]); - const [plans, registry, catalogs] = results; + const [plans, registry] = results; if (plans.status === 'fulfilled') this.setPlans(plans.value.plans); else throw plans.reason; if (registry.status === 'fulfilled') this.registry = registry.value; else this.notice = errorText(registry.reason); - if (catalogs.status === 'fulfilled') this.catalogs = catalogs.value.catalogs; else this.notice = errorText(catalogs.reason); if (results.every(result => result.status === 'fulfilled')) this.notice = t('方案列表已刷新'); } catch (error) { this.notice = errorText(error); } finally { this.loading = false; this.render(); } @@ -65,7 +70,7 @@ export class ServerModulePlans { this.render(); this.focus('[data-server-plan-delete-cancel]'); }; private readonly cancelDelete = () => { this.pendingDelete = undefined; this.render(); this.focus('[data-server-plan-delete]'); }; - private readonly chooseCatalog = (digest: string) => { this.digest = digest; this.render(); this.changed(); }; + private readonly chooseCatalog = (digest: string) => { this.digest = digest; this.renderKnowledge(); this.changed(); }; private async remove() { const selected = this.pendingDelete; if (this.loading || !selected) return; @@ -107,7 +112,8 @@ export class ServerModulePlans { } private catalogOptions() { const options = (this.catalogs ?? []).map(catalog => ); - if (this.digest && !this.catalogs?.some(catalog => catalog.digest === this.digest)) options.push(); + if (this.digest && this.digest !== '__none__' && !this.catalogs?.some(catalog => catalog.digest === this.digest)) + options.push(); return options; } private render() { @@ -143,10 +149,14 @@ export class ServerModulePlans { {entry.id} @ {entry.version}{t('输入 {0} → 输出 {1}', entry.inputs.join(', '), entry.outputs.join(', '))})} } - -

    {t('自动选择本账户最新的非空目录;创建时固定版本,历史证据需要重新检查。')}

    +

    {t('自动选择本账户最新的非空目录;创建时固定版本,历史证据需要重新检查。')}

    ); } } diff --git a/apps/web/client/ui/ChatWorkspace.tsx b/apps/web/client/ui/ChatWorkspace.tsx index dc470527..c87e056f 100644 --- a/apps/web/client/ui/ChatWorkspace.tsx +++ b/apps/web/client/ui/ChatWorkspace.tsx @@ -67,7 +67,7 @@ export type ChatThreadProps = { onCancelTask?(): void; onStartResearch?(): void; onConfirmStatement?(): void; - planDecision?: { approval?: PlanApprovalProps; connected: boolean; onReview(): void; onEdit(): void; onApprove(): void }; + planDecision?: { approval?: PlanApprovalProps; connected: boolean; onReview(): void; onEdit?(): void; onApprove(): void }; startingResearch?: boolean; onRetry?(): void; onRetryAnswer?(message: WebConversationMessage): void; @@ -86,7 +86,7 @@ function StatementDecision(props: ChatThreadProps) {

    {item.status === 'review' ? t('先确认:这是不是你要证明的题目?') : t('题意已由你确认')}

    {!!report.backtranslation?.assumptions.length &&
      {report.backtranslation.assumptions.map((assumption, index) =>
    • )}
    } -

    {t('确认后,2 个 Agent 会拟定研究计划,等你批准再展开证明。')}

    +

    {t('确认题意后,团队会拟定路线,等你批准再开始证明。')}

    {props.onEditProblem && } @@ -105,13 +105,15 @@ function PlanDecision(props: ChatThreadProps & { simple: boolean }) { const plan = run.observation?.plan, approval = decision.approval; // 简洁 keeps this card for the decision itself; afterwards the plan and its editing live in the workspace's roadmap. if (props.simple && !approval && (plan || !run.planApproval)) return null; - const approved = run.observation?.inspection.planApproval?.status === 'approved'; + const approved = Boolean(run.initialPlanApproval) || run.observation?.inspection.planApproval?.status === 'approved'; return

    {approval ? approval.revising ? t('正在按你的意见修改计划') : t('研究计划,等你决定') - : !plan && run.planApproval ? t('正在拟定研究计划') : t('你可以调整这次研究')}

    + : !plan && run.planApproval && !approved ? t('正在拟定研究计划') : t('你可以调整这次研究')}

    {approval ? approval.revising ? t('正在按你的指导修改计划,修改期间计入执行预算。完成后等你确认。') - : t('先核对任务与依赖。等待确认不计入证明预算,批准后继续本次研究。') - : approved ? t('初始计划已由你批准。后续仍可修改任务、依赖和研究方向。') + : run.nativeTeamCapacity ? tx('请核对 Lead 的初始路线,批准后团队开始证明。', 'Review the Lead’s initial route, then approve it to start proving.') + : t('先核对任务与依赖。等待确认不计入证明预算,批准后继续本次研究。') + : approved ? run.nativeTeamCapacity ? tx('初始路线已批准,团队将继续证明。', 'The initial route is approved. The team will continue proving.') + : t('初始计划已由你批准。后续仍可修改任务、依赖和研究方向。') : run.planApproval && !plan ? t('计划拟好后会停下来,等你确认。') : t('修改任务会更新研究计划;指导意见会发送给研究组。')}

    {plan && props.onArtifact('roadmap', { taskId: id })} />} @@ -124,7 +126,7 @@ function PlanDecision(props: ChatThreadProps & { simple: boolean }) {
    {plan && <> - + {decision.onEdit && } } {props.onGuidance && } {approval &&
    {props.connection &&

    {props.connection.message}

    }
    - {props.newProblem &&
    - {t('研究方式')} - - -
    } + {props.newProblem && (props.guidedAvailable || props.participationLocked && props.participation === 'guided') && +
    + {t('研究方式')} + + +
    }
    {tx('环境与预算', 'Environment and limits')}
    diff --git a/apps/web/client/ui/RunHeader.tsx b/apps/web/client/ui/RunHeader.tsx index db279e4f..9def91d7 100644 --- a/apps/web/client/ui/RunHeader.tsx +++ b/apps/web/client/ui/RunHeader.tsx @@ -30,6 +30,7 @@ export type RunHeaderProps = { export type PlanApprovalProps = { /** The visible plan is the exact version awaiting this decision. */ reviewable?: boolean; /** Tasks in the plan waiting for approval. */ tasks: number; + nativeTeam?: boolean; /** The Lead is revising the plan after a note from the owner; approving waits for the revised version. */ revising: boolean; /** The owner's approval was sent and the run has not answered yet. */ busy: boolean; /** Why the owner's last approval did not take effect. */ error?: string; @@ -163,8 +164,9 @@ function ApprovalBanner({ approval, connected }: { approval: PlanApprovalProps;

    {approval.revising ? t('Lead 正在按你的留言修改计划') : t('研究计划等你批准')}

    {approval.revising ? t('修改完成后可以再看一遍再批准。') - : t('Lead 把题目拆成了 {0} 项任务。批准后 Agent 才开始工作;也可以先改计划,或给 Lead 留言让它修改。', approval.tasks)}

    -

    {t('等待确认不计入证明预算;拟定和修改计划正常计时。')}

    + : approval.nativeTeam ? tx('请核对 Lead 的初始路线,批准后团队开始证明。', 'Review the Lead’s initial route, then approve it to start proving.') + : t('Lead 把题目拆成了 {0} 项任务。批准后 Agent 才开始工作;也可以先改计划,或给 Lead 留言让它修改。', approval.tasks)}

    + {!approval.nativeTeam &&

    {t('等待确认不计入证明预算;拟定和修改计划正常计时。')}

    } {approval.error && } {approval.original &&

    {tx('原批准版本:', 'Original approval version: ')}{approval.original.planVersion}

    @@ -179,8 +181,10 @@ function ApprovalBanner({ approval, connected }: { approval: PlanApprovalProps; {approval.onReviewCurrent && } - - + {!approval.nativeTeam && <> + + + }
    ; diff --git a/apps/web/formalizationTypes.ts b/apps/web/formalizationTypes.ts index 31b58529..bf4db517 100644 --- a/apps/web/formalizationTypes.ts +++ b/apps/web/formalizationTypes.ts @@ -41,6 +41,8 @@ export type WebFormalization = { backgroundReview?: WebFormalizationBackgroundReview; }; export type WebFormalizationCapabilities = { available: boolean; reason?: 'provider' | 'runtime'; providerId?: string; + /** The current worker can run the proof stage after compiling the statement. */ + solveAvailable?: boolean; model: string; key: 'required' | 'saved' | 'server'; limits: typeof webFormalizationLimits; providers?: (WebProvider & { defaultModel: string; key: 'required' | 'saved' | 'server'; keyUrl?: string })[]; defaults?: typeof webFormalizationDefaults }; diff --git a/apps/web/i18n/app.ts b/apps/web/i18n/app.ts index 2af49b6d..2d5b4f2f 100644 --- a/apps/web/i18n/app.ts +++ b/apps/web/i18n/app.ts @@ -17,7 +17,6 @@ export const app: Record = { '没有匹配的角色': 'No matching profiles', '正在读取角色目录…': 'Loading profile catalog…', '当前执行器或运行镜像不支持原生团队。': 'The selected harness or worker image does not support native teams.', - '使用固定项目技能研究;可选择独立或协作安排,独立引理与完整原题分别验收。': 'Research with the frozen project skill. Choose independent or cooperative work; independent lemmas and the complete original problem are checked separately.', '不设置': 'Not set', '技能加载': 'Skill loading', '技能版本': 'Skill digest', @@ -400,6 +399,7 @@ export const app: Record = { "研究已提交,连接已变化,请核对运行记录": "Research submitted but the connection changed; check your runs", "研究已提交": "Research submitted", "提交结果尚未确认,请先核对运行记录后再决定是否重新提交。": "The submission is not confirmed yet. Check your runs before deciding whether to submit again.", + "旧协作请求没有创建运行。草稿已切换到当前研究方式,可以重新提交。": "The previous collaboration settings did not create a run. Your draft now uses the current research mode and is ready to submit again.", "[已隐藏]": "[hidden]", "连接需要恢复,未提交内容已保留。": "The connection needs to recover; unsubmitted work was kept.", "研究已结束": "Research finished", diff --git a/apps/web/i18n/common.ts b/apps/web/i18n/common.ts index b221e651..62019bf8 100644 --- a/apps/web/i18n/common.ts +++ b/apps/web/i18n/common.ts @@ -137,8 +137,8 @@ export const common: Record = { "服务商拒绝了这个 API Key。请确认密钥属于所选服务商、没有过期且有模型权限,然后换一个密钥重新运行。": "The provider rejected this API key. Check that it belongs to the selected provider, has not expired and can use the model, then run again with a different key.", "更换 API Key": "Change API key", "服务商限制了请求": "The provider throttled requests", - "账户额度不足,或同时发出的请求超过了服务商的并发上限。请检查余额和并发配额,减少 Agent 数量,或稍后再试。": "The account is out of credit, or concurrent requests exceeded the provider's limit. Check your balance and concurrency quota, use fewer Agents, or try again later.", - "减少 Agent 数量": "Use fewer Agents", + "账户额度不足,或同时发出的请求超过了服务商的并发上限。请检查余额和并发配额,或稍后再试。": "The account is out of credit, or concurrent requests exceeded the provider's limit. Check your balance and concurrency quota, or try again later.", + "减少团队人数": "Use a smaller team", "多次重试后仍无法连上模型服务,或请求超时。已检查的成果保存在报告中。请确认服务商状态后重新运行。": "The model service could not be reached after several retries, or requests timed out. Checked results are saved in the report. Check the provider's status and run again.", "已达到模型用量上限": "Model usage cap reached", "本次运行的模型用量已到上限,后续调用已停止。已检查的成果保存在报告中。": "This run reached its model usage cap and further calls stopped. Checked results are saved in the report.", diff --git a/apps/web/i18n/errors.ts b/apps/web/i18n/errors.ts index b321de1c..da63f16d 100644 --- a/apps/web/i18n/errors.ts +++ b/apps/web/i18n/errors.ts @@ -33,8 +33,6 @@ export const errors: Record = { '原生团队容量必须为 2 至 8 人(含 Lead)。': 'Choose a native team capacity of 2 to 8, including Lead.', '原生团队需要 Codex 执行器。': 'Native teams require the Codex harness.', '角色偏好仅适用于 Codex 原生团队。': 'Profile preferences require a native Codex team.', - '路线探索至少需要两名研究员。': 'Portfolio exploration requires at least two researchers.', - '路线探索时长必须在启用路线探索时设为 1 至 86400 秒的整数。': 'Set an exploration duration of 1 to 86400 whole seconds with portfolio exploration enabled.', '当前运行镜像不支持个人专家资料。请移除专家资产或更新运行镜像。': 'This worker image does not support personal experts. Remove the selected expert assets or update the worker image.', '每个个人专家在一次运行中只能选择一个发布版本。': 'Select only one release of each personal expert per run.', '每次运行最多选择 32 个个人专家。': 'Select up to 32 personal experts per run.', @@ -42,7 +40,13 @@ export const errors: Record = { '原生团队的角色目录不可用。': 'The native team profile catalog is unavailable.', '当前运行镜像不支持角色偏好。清空偏好后仍可使用原生团队。': 'This worker image does not support profile preferences. Clear the preferences to run a native team.', '无法选择角色偏好:{0}。请从当前角色目录中选择。': 'Unknown profile: {0}. Choose a profile from the current catalog.', - '原生团队由一名 Lead 自主派工,不能与宿主协作、审计划或自定义模块方案一起使用。': 'Native teams use a single Lead for delegation and do not support host collaboration, plan approval or custom module plans.', + '原生团队由一名 Lead 自主派工,不能与宿主协作或自定义模块方案一起使用。': 'The Lead coordinates the native team. Host collaboration and custom module plans are unavailable with native teams.', + '原生团队不使用自定义模块方案。': 'Native teams do not use custom module plans.', + '此研究安排不支持该协作操作。': 'This research mode does not support that collaboration action.', + '当前运行镜像未安装支持原生团队与路线审批的 worker,请更新运行镜像。': 'Update the worker image to support native teams and route approval.', + '这次运行的 Codex 模型服务已不在配置中。': 'This run’s Codex model provider is no longer configured.', + '旧协作任务请使用对应的历史版本继续。新建多人研究使用 Codex 原生团队。': 'Continue old collaboration runs from the matching historical release. New multi-agent runs use Codex native teams.', + '旧版独立路线探索已停用;新研究可由 Codex 原生团队探索路线。': 'Standalone route scouting is retired. Codex native teams can explore routes in new runs.', '技能加载方式无效。': 'Invalid skill loading mode.', '技能加载选项需要 Skill 研究方式。': 'Skill loading requires Skill research mode.', "当前账号的形式化队列已满,请等待已有任务结束。": "Your formalization queue is full. Wait for an existing task to finish.", @@ -190,7 +194,7 @@ export const errors: Record = { "检查已被更新的版本取代。": "A newer version replaced this check.", "请检查题目、API Key、模型、模块方案及运行预算。": "Check the problem, API key, model, module plan and run budget.", "该模型服务尚未配置。": "This model provider is not configured.", - "先审计划需要协作模式和至少 2 个 Agent。": "Reviewing the plan first needs collaboration mode and at least 2 agents.", + "先审计划需要 Codex 原生团队。": "Reviewing the plan before starting requires a Codex native team.", "请填写 API Key。": "Enter an API key.", "运行环境尚未就绪,请先构建 worker 镜像。": "The run environment is not ready; build the worker image first.", "这个版本的代码没有记录或已超出保留范围。": "The code of this version was not recorded or is no longer kept.", diff --git a/apps/web/i18n/formalize.ts b/apps/web/i18n/formalize.ts index 45825bb2..a5f76bde 100644 --- a/apps/web/i18n/formalize.ts +++ b/apps/web/i18n/formalize.ts @@ -10,10 +10,9 @@ export const formalize: Record = { '错误代码': 'Error code', '查看原题与 Lean 陈述': 'View the problem and Lean statement', '人工审核模式需要启用证明研究。': 'Human review requires proof research to be enabled.', - '在原对话中启动双 Agent 研究,并审核研究计划。': 'Return to the conversation to start research with 2 Agents and review the plan.', + '返回原对话继续研究并审核初始路线。': 'Return to the conversation to continue research and review the initial route.', '先确认:这是不是你要证明的题目?': 'First, is this the problem you want to prove?', '题意已由你确认': 'You confirmed the problem statement', - '确认后,2 个 Agent 会拟定研究计划,等你批准再展开证明。': 'After you confirm, 2 Agents will draft a research plan and wait for your approval before proving.', '核对原题与 Lean': 'Compare the problem and Lean', '正在拟定计划…': 'Preparing the plan…', '题意正确,拟定计划': 'Confirm statement and draft plan', @@ -32,11 +31,9 @@ export const formalize: Record = { '调整研究方向': 'Guide the research', '等待修改完成': 'Waiting for revisions', '批准计划,开始证明': 'Approve plan and start proving', + '确认题意后,团队会拟定路线,等你批准再开始证明。': 'After you confirm the statement, the team drafts the route and waits for your approval.', '研究方式': 'Research mode', - '共同推进': 'Work together', - '题意和初始计划由你确认 · 2 个 Agent': 'You approve the statement and initial plan · 2 Agents', '自动推进': 'Run automatically', - '自动核对并开始证明 · 1 个 Agent': 'Checks the statement and starts proving · 1 Agent', '消息用途': 'Message purpose', '讨论思路': 'Discuss ideas', '研究指导': 'Research guidance', diff --git a/apps/web/i18n/guide.ts b/apps/web/i18n/guide.ts index 213ec813..64e60090 100644 --- a/apps/web/i18n/guide.ts +++ b/apps/web/i18n/guide.ts @@ -31,8 +31,8 @@ export const guide: Record = { "填写所选服务商的 API Key。OpenAI 提供创建 Key 的链接;网关账号与 Key 请向该网关管理员获取。可以先点「检查 Key 与模型」,确认账号能访问哪些模型;不支持模型列表的服务需在发送时确认。": "Enter the selected provider’s API key. OpenAI has a link to create one; ask the gateway administrator for a gateway account and key. “Check key and model” confirms which models your account can reach. Providers without that endpoint are checked when you send.", "设定预算并发送": "Set a budget and send", - "形式化与证明各有时间和 Token 预算,发送前可在「配置模型」或「研究配置」调整。默认「共同推进」由你确认题意,再由 2 个 Agent 拟定初始计划,等你批准后展开证明;「自动推进」由 1 个 Agent 在模型核对后直接开始。费用由模型服务商收取,进行中的请求可能超过设定用量。": - "Set separate time and token budgets for formalization and proof in Configure model or Research settings before sending. Work together is the default: you confirm the statement, then 2 Agents draft an initial plan and wait for your approval before proving. Run automatically uses 1 Agent and starts after model review. Your model provider bills usage; requests already in progress can exceed the limit.", + "形式化与证明各有时间和 Token 预算,发送前可在「配置模型」或「研究配置」调整。使用 Codex 时,原生团队默认自动推进。其他支持的执行器使用单 Agent 项目技能。费用由模型服务商收取,进行中的请求可能超过设定用量。": + "Set separate time and token budgets for formalization and proof in Configure model or Research settings before sending. On Codex, the native team proceeds automatically by default. Other supported runtimes use the project skill with a single agent. Your model provider bills usage, and in-flight requests can exceed the limit.", "顶栏「历史」可展开研究记录。打开一次运行后,对话主栏直接展示题意确认、研究计划、实时进展与验收结果;展开右侧「研究与证明」分栏可进一步查看结果、路线图、协作、源码和活动五个视图。运行中随时可点「取消运行」停下。": "Open History in the top bar to see your research runs. Once you open a run, the main conversation shows statement confirmation, the research plan, live progress and acceptance results. Expand the Research and proof pane on the right for five views: Result, Roadmap, Collaboration, Source and Activity. Stop a run at any time with Cancel run.", "谁在做哪个子任务、在等什么。从分区导航查看任务、原意与 Lean、Agent、指导和知识;详细视图还包含任务合同、交付、变更和归档记录。": @@ -50,15 +50,15 @@ export const guide: Record = { "验收通过且原题含义审核完成后,系统会自动生成讲解,并在对话中显示进度与详细解答。也可点「结果」或「源码」中的「Lean → 自然语言」打开讲解页,切换目标与中英文,逐步对照 Lean 行、引理和自然语言,下载已通过审核的 Markdown。自动生成未完成时,可在讲解页查看原因并重新生成。": "Once the proof is accepted and the problem statement review has passed, the system automatically generates explanations and shows progress and the detailed solution in the conversation. You can also open Lean → Natural language from Result or Source to switch targets and languages, compare steps with Lean lines and lemmas, and download approved Markdown. If automatic generation did not finish, open the explanation page to see why and generate it again.", "自然语言 → Lean": "Natural language → Lean", - "首页发送原题后,系统生成 Lean 陈述,并独立回译、审核。在「共同推进」中,你会先看到回译的题意,可核对原题与 Lean、修改题目,或确认后拟定研究计划。「完整审核」保留每次模型审核的结论。": - "Send a problem from the home page to generate a Lean statement with independent back-translation and review. In Work together, read the translated meaning first. Compare the problem and Lean, edit the problem, or confirm it to draft a research plan. Full review preserves each model’s verdict.", + "首页发送原题后,系统生成 Lean 陈述,并独立回译、审核。选择「先审路线再开工」后,你可以先核对原题与 Lean,修改题目或确认题意。确认后,原生团队会拟定路线并等你批准。「完整审核」保留每次模型审核的结论。": + "Send a problem from the home page to generate a Lean statement with independent back-translation and review. Choose Review the route before starting to compare the problem with Lean first, then edit or confirm the statement. After you confirm, the native team drafts the route and waits for your approval. Full review preserves each model’s verdict.", "证明讲解目前仅支持使用 Sub2API 与 deepseek-flash 的已验收运行,服务也需提供讲解运行环境;不支持时页面会说明原因。示例运行可以打开对照页,但没有预生成讲解,也不能生成。": "Proof explanations currently require an accepted run using Sub2API and deepseek-flash, with an explanation runtime provided by the service. The page explains why generation is unavailable when these conditions are not met. Sample runs can open the comparison page, but have no pre-generated explanations and cannot generate them.", "审阅研究计划": "Review the research plan", - "「共同推进」使用 2 个 Agent,初始计划直接显示在对话中。你可以查看全部任务、修改任务与依赖,再批准开始证明。拟定和修改计划计入证明预算;等待你审阅或批准时证明计时暂停,批准后继续同一次运行,关闭再打开页面也无需重建。后续修改计划会继续生效,不会每次重新等待批准。Lean 入口也可在执行配置中勾选「先审计划再开始」。": - "Work together uses 2 Agents and shows the initial plan in the conversation. Review tasks and dependencies, request changes, then approve the plan to start proving. Drafting and revisions consume the proof budget. While the plan waits for your review or approval the proof timer is paused. Approval continues the same run, even after closing and reopening the page. Later edits update the plan without another approval gate. The Lean entry also offers Review plan before starting under Execution.", - "运行中在对话输入框选择「指导 Agent」,给负责人或具体任务发送方法建议,并查看送达回执。指导供 Agent 参考;「讨论思路」用于交流想法,不会改动运行计划。协作区还可向具体 Agent 留言、引用代码与检查记录。": - "During a run, choose Guide the Agents in the chat composer to suggest methods to the lead or a task, then check delivery receipts. Agents consider this guidance. Discuss ideas is for exploring the problem and does not change the running plan. In Collaboration, you can also address an Agent and reference code and checks.", + "使用 Codex 时,可在自然语言研究设置或 Lean 的执行配置中开启「先审路线再开工」。初始路线显示在对话中,核对后点击批准即可开始证明。拟定路线计入证明预算,等待批准期间暂停证明计时。关闭页面后,可以从历史记录返回同一次运行并批准。": + "On Codex, enable Review the route before starting in the natural-language research settings or the Lean execution settings. The initial route appears in the conversation. Review it and approve it to start proving. Drafting uses the proof budget, and the proof timer pauses while waiting for approval. If you close the page, you can return to the same run from History and approve it there.", + "用「讨论思路」交流想法,讨论与当前运行分开。采用旧调度器的历史运行会按原配置显示「指导 Agent」、任务编辑和相应记录。": + "Use Discuss ideas to explore the problem separately from the active run. Historical runs using the previous scheduler show Guide the Agents, task editing, and the associated records according to their saved configuration.", "归档与知识": "Archives and knowledge", "协作区可归档研究证据、下载归档包,并在「知识」中搜索历史定理、引理与路线发现。引用知识时会带上来源和记录环境;历史检查通过不代表当前题目通过,使用前仍需重新检查。": "In Collaboration, archive research evidence, download an archive and search historical theorems, lemmas and route findings under Knowledge. References include their source and recorded environment. A historical check does not establish the current problem; reused work must be checked again.", @@ -67,8 +67,8 @@ export const guide: Record = { "Agent 交出了候选证明,但独立验收没有通过。报告会写明是哪项检查失败。": "The Agents submitted a candidate proof, but independent acceptance rejected it. The report says which check failed.", "到达轮次、时间或用量上限时还没有完成证明,标签会写明原因,例如「解题时间用完」。已检查的成果保留在报告里,可以提高预算后重新运行。": "The turn, time or usage limit was reached before the proof was complete, and the badge names it, such as \"Solve time used up\". Checked work stays in the report, and you can rerun with a larger budget.", - "Key 无效、服务商限流或环境故障等原因让运行无法继续。对话里会给出对应的处理按钮,例如「更换 API Key」或「减少 Agent 数量」。": - "Something such as an invalid key, provider rate limits or an environment fault stopped the run. The chat offers a matching action, such as \"Change API key\" or \"Use fewer Agents\".", + "Key 无效、服务商限流或环境故障等原因让运行无法继续。对话里会给出对应的处理按钮,例如「更换 API Key」或「减少团队人数」。": + "Something such as an invalid key, provider rate limits or an environment fault stopped the run. The chat offers a matching action, such as \"Change API key\" or \"Use a smaller team\".", "你主动停止了这次运行。": "You stopped this run.", "「候选证明」和「有条件结果」都不算完成:前者还没经过验收,后者依赖一条尚未证明的引理。": "Neither a candidate proof nor a conditional result counts as done: the first has not been accepted yet, and the second depends on a lemma that is still unproved.", diff --git a/apps/web/i18n/pages.ts b/apps/web/i18n/pages.ts index 9721d2c2..b26b79a1 100644 --- a/apps/web/i18n/pages.ts +++ b/apps/web/i18n/pages.ts @@ -266,7 +266,6 @@ export const pages: Record = { "清除已记住的 Key": "Forget the remembered key", "新运行会把这一版的代码交给每个 Agent 参考;它不是证据,仍要重新通过 Lean 检查。": "The new run gives this version's code to every Agent as a reference; it is not evidence and must pass the Lean check again.", "不从这一版继续": "Don't continue from this version", - "先审计划再开始": "Review the plan before starting", "我已阅读并同意": "I have read and agree to ", "与": " and ", "使用条款": "Terms of Use", diff --git a/apps/web/i18n/release.ts b/apps/web/i18n/release.ts index 178c40d6..2329480b 100644 --- a/apps/web/i18n/release.ts +++ b/apps/web/i18n/release.ts @@ -75,7 +75,9 @@ export const release: Record = { '留空使用管理员 Key。': 'Leave blank to use the admin key.', '关闭标签页后清除,限当前服务商使用。': 'Cleared when this tab closes. Used for this provider only.', '模型费用由所选服务商收取。': 'Model calls are billed by your provider.', - '需要任务协作及至少 2 个 Agent。等待确认不计入证明预算。': 'Requires task collaboration and at least 2 Agents. Waiting for approval pauses the proof budget.', + '先审路线再开工': 'Review the route before proving', + 'Lead 提交初始路线后,团队会等你批准再开始证明。': 'After Lead submits the initial route, the team waits for your approval before proving.', + '单 Agent 研究': 'Single-agent research', '根据最近 {0} 次 {1} 运行,预计约 {2} Token。': 'Estimated at about {2} tokens from your last {0} runs with {1}.', '按已报告用量在 {0} Token 停止,在途请求可能超额;不代表金额封顶。': 'Stops at {0} reported tokens. Requests in progress may exceed the cap; it is not a spending limit.', '完整原题须通过独立 Lean 验收。': 'The complete original problem must pass independent Lean acceptance.', diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index 912f99bf..781100ad 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -3,7 +3,7 @@ import crypto from 'node:crypto'; import type { WebConfig } from './config'; import type { WebRunner } from './runner'; import type { WebEvent, WebEventDetails, WebProvider, WebResult, WebWorkerProvider, WebRun, WebRunInput, WorkerInput, WorkerMessage } from './shared'; -import { webResearchModeError, webSkillWithoutCooperation, webDefaultSkillLoading } from './researchMode'; +import { webResearchModeError, webDefaultSkillLoading } from './researchMode'; import { normalizeWebTeamPreferences } from './nativeTeamProfiles'; import { personalExpertCardsDigest } from '../../src/solver/personalExperts'; import { isProgressEvent, parseWebFailure, webAgentActionLimits, webLimits, webRunEventLimit } from './shared'; @@ -111,7 +111,6 @@ export class WebJobs { }; } private creation(input: WebRunInput, provider: WebWorkerProvider, requestId: string): WebCreation { - if (!/^[A-Za-z0-9_-]{1,128}$/u.test(requestId)) throw new WebStorageError(400, '提交请求标识无效。'); const normalized = webProviderHarness(provider) === 'codex' ? input : { ...input, researchMode: input.researchMode ?? 'skill', skillLoading: input.skillLoading ?? 'file' }; const { apiKey: _key, ...visible } = normalized; @@ -122,11 +121,13 @@ export class WebJobs { } replay(owner: string, input: WebRunInput, provider: WebWorkerProvider, requestId?: string, legacyEnvironmentOmitted = false): WebRun | undefined { if (!requestId) return; - input = normalizeWebTeamPreferences(input); - const expected = this.creation(input, provider, requestId); + if (!/^[A-Za-z0-9_-]{1,128}$/u.test(requestId)) throw new WebStorageError(400, '提交请求标识无效。'); const stored = this.creations.get(JSON.stringify([owner, requestId])); const previous = stored ?? this.storage.deletedCreation(owner, requestId); if (!previous) return; + // New submissions have nothing to compare. Hash the full source only for a saved identity. + input = normalizeWebTeamPreferences(input); + const expected = this.creation(input, provider, requestId); // Older HTTP clients could omit the environment when its default was standard. // Match that frozen identity only on a replay; new submissions keep the current default. if (previous.digest !== expected.digest && (!legacyEnvironmentOmitted || @@ -139,7 +140,7 @@ export class WebJobs { /** The source goes only to the worker; its exact host-resolved identity stays with the visible run. */ create(owner: string, input: WebRunInput, provider: WebWorkerProvider, continuation?: WorkerInput['continuation'], requestId?: string, formalization?: { evidence?: unknown; compiled?: unknown; provenance: NonNullable }, - researchConfiguration?: WorkerInput['researchConfiguration']): WebRun { + researchConfiguration?: WorkerInput['researchConfiguration'], creationInput: WebRunInput = input): WebRun { input = normalizeWebTeamPreferences(input); if (webProviderHarness(provider) !== 'codex') input = { ...input, researchMode: input.researchMode ?? 'skill', skillLoading: input.skillLoading ?? 'file' }; @@ -147,7 +148,7 @@ export class WebJobs { const harnessError = webHarnessResearchError(provider, input); if (harnessError) throw new WebStorageError(400, harnessError); if (modeError) throw new WebStorageError(400, modeError); - const previous = this.replay(owner, input, provider, requestId); + const previous = this.replay(owner, creationInput, provider, requestId); if (previous) return previous; if (this.closing) throw new Error('服务正在停止,请稍后重试。'); const count = (status: string) => [...this.jobs.values()].filter(job => job.run.status === status).length; @@ -183,7 +184,7 @@ export class WebJobs { run.title = (formalization?.provenance.original.trim() || run.task).split('\n')[0].slice(0, 60) || 'Lean 研究'; if (provider.harness || provider.execution) { run.harness = webProviderHarness(provider); run.harnessConfigurationDigest = webProviderExecutionDigest(provider); } if (input.researchMode !== 'skill' || input.workers > 1 || input.modulePlan) run.moduleConfiguration = freezeModuleConfiguration(run.modulePlan, run.coordination, run.workers, provider.harness); - const creation = requestId ? this.creation(input, provider, requestId) : undefined; + const creation = requestId ? this.creation(normalizeWebTeamPreferences(creationInput), provider, requestId) : undefined; this.event(run, 'queued', '任务已进入队列'); // Persist the identity and initial run atomically before a worker can be queued. this.storage.saveRun(owner, run, creation); @@ -344,6 +345,10 @@ export class WebJobs { run.researchSkill = { ...skill }; } if (actualHarness) run.agentHarness = { ...actualHarness }; + const approval = observation.inspection.planApproval; + if (run.nativeTeamCapacity && run.planApproval && !run.initialPlanApproval && (current?.round ?? 0) === 0 && + approval?.status === 'approved' && approval.approvedId && approval.approvedVersion && approval.approvedAt !== undefined) + run.initialPlanApproval = { solverRunId: observation.solverRunId, receipt: approval }; run.solverAttempt = { solverRunId: observation.solverRunId, round: current?.round ?? 0, sequence: observation.sequence }; run.observation = projectStoredObservationChecks(observation); run.updatedAt = observation.observedAt; @@ -368,21 +373,22 @@ export class WebJobs { affectedTaskIds: edit.affectedTasks ?? saved.affectedTaskIds, edit }; // An approval is settled once the running solver records it as the approval, or rejects it. const approval = run.observation?.inspection.planApproval; - if (approval?.approvedId === id) return { ...saved, status: 'approved', reason: undefined, planVersion: approval.approvedVersion }; + const approved = [run.initialPlanApproval?.receipt, approval].find(item => item?.approvedId === id); + if (approved) return { ...saved, status: 'approved', reason: undefined, planVersion: approved.approvedVersion }; const rejected = approval?.rejections.find(item => item.id === id); if (rejected) return { ...saved, status: 'rejected', reason: rejected.reason, planVersion: rejected.planVersion ?? saved.planVersion }; return saved; } - async command(owner: string, runId: string, command: Exclude): Promise { + async command(owner: string, runId: string, command: Extract): Promise { const job = this.jobs.get(runId); if (!job || job.owner !== owner) throw new Error('运行不存在或不属于当前会话。'); - if (webSkillWithoutCooperation(job.run)) throw new WebStorageError(409, '此研究安排不支持协作计划、逐题指导或计划审批。'); - const id = command.type === 'guidance' ? command.guidance.id : command.type === 'guidance-withdraw' ? command.id - : command.type === 'plan-approval' ? command.approval.id : command.proposal.id; - const key = `${runId}/${command.type === 'edit-preview' ? 'preview/' : ''}${id}`; + if (command.type !== 'plan-approval' || !job.run.nativeTeamCapacity || !job.run.planApproval) + throw new WebStorageError(409, '此研究安排不支持计划审批。'); + const { id } = command.approval; + const key = `${runId}/${id}`; const digest = crypto.createHash('sha256').update(canonicalMathJson(command)).digest('hex'); const previous = this.commandReceipt(owner, runId, id); - if (command.type !== 'edit-preview' && previous) { + if (previous) { if (previous.commandDigest !== digest) throw new Error('命令 ID 已用于另一份内容,请使用新的 ID。'); return previous; } @@ -400,27 +406,19 @@ export class WebJobs { const receipt = clean(await this.runner.command!(runId, command), apiKey); if (this.jobs.get(runId) !== job) throw new WebStorageError(404, '运行不存在或不属于当前会话。'); if (receipt.id !== id) throw new Error('命令回执身份不匹配。'); - if (command.type === 'edit-preview') receipt.commandDigest = crypto.createHash('sha256') - .update(canonicalMathJson({ type: 'edit', proposal: command.proposal })).digest('hex'); if (receipt.observation) this.observe(job, receipt.observation); if (job.run.observation) receipt.observation = job.run.observation; - if (command.type !== 'edit-preview') { - this.storage.saveCommand(owner, runId, id, { ...receipt, commandDigest: digest }); + this.storage.saveCommand(owner, runId, id, { ...receipt, commandDigest: digest }); + if (receipt.status === 'queued') { try { - if (command.type === 'plan-approval') { - if (receipt.status === 'queued') this.event(job.run, 'plan_approval_queued', '计划批准已提交;运行确认后 Agent 才开始工作,未生效会另行记录。'); - } else if (command.type === 'guidance-withdraw') { - if (receipt.status === 'withdrawn') this.event(job.run, 'guidance_withdrawn', '一条尚未送达的数学指导已撤回,Agent 不会收到它。'); - } else this.event(job.run, command.type === 'guidance' ? 'guidance_queued' : 'human_edit_queued', - command.type === 'guidance' ? '数学指导已提交;投递和采纳结果另行记录。' : '计划修改已提交;应用与证明重查结果另行记录。'); + this.event(job.run, 'plan_approval_queued', '计划批准已提交;运行确认后 Agent 才开始工作,未生效会另行记录。'); } catch { job.run.error = '运行状态未能保存;服务恢复后请重新查看。'; this.changed(owner); } } - return command.type === 'edit-preview' ? receipt : this.commandReceipt(owner, runId, id) ?? receipt; + return this.commandReceipt(owner, runId, id) ?? receipt; } catch (error) { // Deleted runs/accounts must stay deleted even when a transport fails after removal. if (this.jobs.get(runId) !== job) throw new WebStorageError(404, '运行不存在或不属于当前会话。'); const reason = clean(error instanceof Error ? error.message : '命令回执暂不可用。', apiKey); - if (command.type === 'edit-preview') throw new Error(reason); const receipt = { id, status: 'unknown', reason, commandDigest: digest, ...(job.run.observation ? { observation: job.run.observation } : {}) }; this.storage.saveCommand(owner, runId, id, receipt); diff --git a/apps/web/libraryResearch.ts b/apps/web/libraryResearch.ts index 02aec709..c2e2509c 100644 --- a/apps/web/libraryResearch.ts +++ b/apps/web/libraryResearch.ts @@ -6,6 +6,7 @@ import { readSolverRunState, type SolverRunState, type SolverWorkerState } from import { readContinuationInput, type ContinuationAttachmentKind } from '../../src/solver/continuationInput'; import { requestedLibraryPack, type LibraryAccess, type LibraryRequest } from '../../src/solver/libraryAccess'; import type { LibrarySelection } from '../../src/solver/libraryCatalog'; +import { nativeApprovalPlanBrief, planApprovalStatus } from '../../src/solver/planApproval'; import { git, readSolverProblem } from '../../src/solver/problem'; import { aggregateUsage, buildTokenBudget } from '../../src/solver/usageBudget'; import { prepareWebProblem } from './formalizationSeed'; @@ -16,6 +17,7 @@ type Seed = ReturnType; type Limits = { maxTurns: number; maxRunSeconds: number; maxTotalTokens: number }; export type WebLibraryRound = { round: number; seed: Seed; output: string; continuationFile?: string; limits: Limits; + planApproval?: boolean; libraryCatalog?: LibraryAccess; previousSolverRunId?: string; requestedNames?: string[]; }; type Material = { kind: ContinuationAttachmentKind; text: string; @@ -90,7 +92,8 @@ export async function runWebLibraryResearch(options: { const allowance: Limits = { maxTurns: options.request.input.maxTurns, maxRunSeconds: options.request.input.maxRunSeconds, maxTotalTokens: options.request.input.maxTotalTokens ?? 0 }; let current: WebLibraryRound = { round: 0, seed: options.seed, output: options.output, - continuationFile: options.continuationFile, limits: allowance, libraryCatalog: options.libraryCatalog }; + continuationFile: options.continuationFile, limits: allowance, libraryCatalog: options.libraryCatalog, + planApproval: options.request.input.planApproval }; const materials = new Map(); if (options.continuationFile) { const input = readContinuationInput(options.continuationFile, { @@ -138,6 +141,18 @@ export async function runWebLibraryResearch(options: { if (!value || typeof value.worktree !== 'string' || ![state.worktree, ...(state.workers ?? []).map(worker => worker.worktree)].includes(value.worktree) || !isMathPathWithin(options.directory, value.worktree)) throw new Error('math_library_request_worker_changed'); + const initialNativeApproval = options.request.input.nativeTeamCapacity && current.planApproval; + if (initialNativeApproval) { + const approved = state.cooperation?.planApproval; + if (planApprovalStatus(state) !== 'approved' || !approved?.approvedId || + !approved.approvedVersion || approved.approvedVersion !== state.cooperation?.planVersion) + throw new Error('math_library_request_plan_not_approved'); + const text = `This route was approved before proof work began. Continue the research with the installed library.\n` + + nativeApprovalPlanBrief(state.cooperation.tasks); + materials.set(mathDigest(text), { kind: 'research-notes', text, provenance: { + source: `Approved initial route, version ${approved.approvedVersion}`, evidence: 'recorded-not-replayed', runId: state.runId, + } }); + } const next = requestedLibraryPack(problem, value.request, options.libraryCatalog, value.worktree); Object.assign(rounds.at(-1)!, { libraryRequest: next.request, librarySelection: next.selection }); const limits: Limits = { maxTurns: allowance.maxTurns ? Math.max(0, allowance.maxTurns - turns) : 0, @@ -161,6 +176,7 @@ export async function runWebLibraryResearch(options: { rounds, turns, solveWallMs, solveExecutionMs, tokenBudget, pending: { round, previousSolverRunId: state.runId, problemReceiptDigest: continued.receiptDigest, selection: next.selection, request: next.request } }); current = { round, seed, output: path.join(directory, 'result.json'), limits, continuationFile, - libraryCatalog: options.libraryCatalog, previousSolverRunId: state.runId, requestedNames: next.request.names }; + libraryCatalog: options.libraryCatalog, previousSolverRunId: state.runId, requestedNames: next.request.names, + planApproval: initialNativeApproval ? false : current.planApproval }; } } diff --git a/apps/web/presentation.ts b/apps/web/presentation.ts index 0c91f72e..d7cb0167 100644 --- a/apps/web/presentation.ts +++ b/apps/web/presentation.ts @@ -1,5 +1,6 @@ import { webLimits, webPreparationSeconds, type WebEffort, type WebFailureKind, type WebRun } from './shared'; import { locale, localeTag, localizeMessage, localizeText, t, translator } from './i18n'; +import { MIN_TEAM_AGENTS } from '../../src/solver/teamCapacity'; export const isAcceptedRun = (run: WebRun) => run.status === 'completed' && run.result?.status === 'evaluated_passed'; /** A compiled candidate can pass Lean while its correspondence to the original is still unapproved. */ @@ -190,8 +191,8 @@ const report: RecoveryAction = { id: 'report', label: t('查看报告') }; const guides: Record = { authentication: { title: t('API Key 未通过认证'), detail: t('服务商拒绝了这个 API Key。请确认密钥属于所选服务商、没有过期且有模型权限,然后换一个密钥重新运行。'), actions: [{ id: 'key', label: t('更换 API Key') }] }, - rate_limit: { title: t('服务商限制了请求'), detail: t('账户额度不足,或同时发出的请求超过了服务商的并发上限。请检查余额和并发配额,减少 Agent 数量,或稍后再试。'), - actions: [{ id: 'workers', label: t('减少 Agent 数量') }, retry] }, + rate_limit: { title: t('服务商限制了请求'), detail: t('账户额度不足,或同时发出的请求超过了服务商的并发上限。请检查余额和并发配额,或稍后再试。'), + actions: [retry] }, network: { title: t('模型服务连接失败'), detail: t('多次重试后仍无法连上模型服务,或请求超时。已检查的成果保存在报告中。请确认服务商状态后重新运行。'), actions: [retry, report] }, budget: { title: t('已达到模型用量上限'), detail: t('本次运行的模型用量已到上限,后续调用已停止。已检查的成果保存在报告中。'), @@ -238,6 +239,8 @@ export function failureGuide(run: WebRun): FailureGuide | undefined { : run.result?.status === 'limit_reached' ? 'time_limit' : undefined); if (kind) { if (kind === 'time_limit' && preparationStopped(run)) return preparationGuide(run); + if (kind === 'rate_limit' && (run.nativeTeamCapacity ?? 0) > MIN_TEAM_AGENTS) + return { ...guides.rate_limit, kind, actions: [{ id: 'workers', label: t('减少团队人数') }, retry] }; const guide = kind === 'time_limit' ? timeGuide(run) : guides[kind], detail = run.failure?.reason && reasonDetails[run.failure.reason]; // A stop before approval can include planning/revision work, or a historical run whose wait used its old budget. const unapproved = kind === 'time_limit' && run.observation?.inspection.planApproval?.status === 'pending' diff --git a/apps/web/problemDraftSubmission.ts b/apps/web/problemDraftSubmission.ts index 09daea19..dec177c0 100644 --- a/apps/web/problemDraftSubmission.ts +++ b/apps/web/problemDraftSubmission.ts @@ -28,7 +28,8 @@ export function matchesProblemRun(value: ProblemDraftValue, run: WebRun): boolea || !equal(run.nativeTeamPreferredProfiles ?? [], [...new Set(draft.nativeTeamPreferredProfiles ?? [])].sort()) || run.maxTurns !== Number(draft.maxTurns) || run.maxRunSeconds !== Number(draft.maxRunSeconds) || run.workers !== Number(draft.workers) || (run.maxTotalTokens ?? 0) !== Math.round(Number(draft.maxTotalTokens ?? '') * 10_000) - || Boolean(run.planApproval) !== Boolean(draft.planApproval && draft.coordination === 'cooperative' && Number(draft.workers) >= 2) + || Boolean(run.planApproval) !== Boolean(draft.planApproval && + (draft.nativeTeamCapacity || draft.coordination === 'cooperative' && Number(draft.workers) >= 2)) || draft.knowledgeDigest !== undefined && (run.knowledgeDigest ?? null) !== draft.knowledgeDigest) return false; const refs = [...(config?.agent ? [config.agent.ref] : []), ...(config?.skills.map(item => item.ref) ?? []), ...(config?.libraries.map(item => item.ref) ?? [])]; const sameRef = (a: ResearchReleaseRef, b: ResearchReleaseRef) => a.assetId === b.assetId && a.version === b.version && (!a.digest || a.digest === b.digest); diff --git a/apps/web/researchApi.ts b/apps/web/researchApi.ts index 86b4318d..a3dead83 100644 --- a/apps/web/researchApi.ts +++ b/apps/web/researchApi.ts @@ -28,8 +28,8 @@ import type { WebKnowledgeService } from './knowledgeService'; import type { WebRunner } from './runner'; import type { ResearchCandidateCheckReceipt, ResearchCandidateReview, ResearchFeedback, ResearchQuery } from './researchProjectTypes'; import type { ResearchAssetRelease, ResearchConfigurationSelection, ResearchLibraryUse } from './researchAssetTypes'; -import type { WebRun } from './shared'; -import { webGuidanceSchema, webPlanApprovalSchema, webPlanProposalSchema } from './collaborationValidation'; +import { retiredResearchCoordinationMessage, type WebRun } from './shared'; +import { webPlanApprovalSchema } from './collaborationValidation'; import { leanDiagnostics } from './precheck'; import { shareSnapshot } from './share'; import type { WebCommandResult, WebObservation } from './collaboration'; @@ -153,22 +153,20 @@ export class WebResearchApi { }); } private dispatch(viewer: string, projectId: string, feedback: ResearchFeedback): Promise | ResearchFeedback { - if (feedback.kind === 'discussion') return feedback; if (feedback.kind === 'proof-submission') { const key = `${projectId}:${feedback.id}`; const pending = this.pendingProofs.get(key); if (pending) return pending; const checked = (feedback.proofCheck ? Promise.resolve(feedback) : this.checkProof(viewer, projectId, feedback)) - .then(checked => checked.proofCheck?.status === 'checked' ? this.dispatchCommand(viewer, projectId, checked) : checked) .finally(() => this.pendingProofs.delete(key)); this.pendingProofs.set(key, checked); return checked; } - return this.dispatchCommand(viewer, projectId, feedback); - } - private dispatchCommand(viewer: string, projectId: string, feedback: ResearchFeedback): Promise | ResearchFeedback { + if (feedback.kind !== 'plan-approval') return feedback; + if (feedback.target && !this.projects.resolveBinding(viewer, projectId, feedback.target.runId, 'approve').run.nativeTeamCapacity) + fail(409, retiredResearchCoordinationMessage); const command = this.projects.commandForFeedback(viewer, projectId, feedback.id); - if (!command) return feedback; + if (command?.command.type !== 'plan-approval') return feedback; return this.jobs.command(command.runOwner, command.runId, command.command) .then(receipt => this.projects.recordCommand(viewer, projectId, feedback.id, receipt)); } @@ -398,9 +396,14 @@ export class WebResearchApi { if (method === 'GET') { const project = this.refreshProject(viewer, id); return ref ? item(this.projects.feedback(viewer, id, ref)) : { status: 200, body: { items: project.feedback } }; } if (ref && subaction === 'decision' && method === 'POST') return item(this.projects.decideFeedback(viewer, id, ref, await body())); - if (ref && subaction === 'candidate-delivery' && method === 'POST') return item(await this.dispatch(viewer, id, this.projects.candidateDelivery(viewer, id, ref, await body()))); + if (ref && subaction === 'candidate-delivery' && method === 'POST') fail(409, retiredResearchCoordinationMessage); if (!ref && method === 'POST') { const input = await body() as Record; + if (['guidance', 'plan-edit', 'route-control'].includes(String(input.kind))) fail(409, retiredResearchCoordinationMessage); + const target = input.target as { runId?: unknown } | undefined; + if (input.kind === 'plan-approval' && typeof target?.runId === 'string' && + !this.projects.resolveBinding(viewer, id, target.runId, 'approve').run.nativeTeamCapacity) + fail(409, retiredResearchCoordinationMessage); if (input.libraryTrialId && input.shareLibraryTrial !== true) fail(403, '请明确确认向项目成员共享这份固定试用证据。'); const attachment = input.kind === 'proof-submission' && typeof input.libraryTrialId === 'string' ? this.libraryTrials.resolveCandidateAttachment(viewer, id, input.libraryTrialId, String(input.libraryTrialDigest ?? ''), true) : undefined; @@ -417,30 +420,17 @@ export class WebResearchApi { if (method === 'POST' && ['guidance', 'edits', 'plan-approval'].includes(subaction)) { const permission = subaction === 'guidance' ? 'guidance' : subaction === 'edits' ? 'edit' : 'approve'; const resolved = this.projects.resolveBinding(viewer, id, ref, permission); - const input = await body(); - const authorized = this.projects.resolveBinding(viewer, id, ref, permission); - // A preview has no side effects and no feedback contribution. - if (subaction === 'edits' && parts[5] === 'preview') return { status: 200, body: { receipt: - await this.jobs.command(authorized.runOwner, ref, { type: 'edit-preview', proposal: parse(webPlanProposalSchema, input) }) } }; - const requestId = parse(z.object({ id: z.string() }).passthrough(), input).id; + if (subaction !== 'plan-approval' || !resolved.run.nativeTeamCapacity) + fail(409, retiredResearchCoordinationMessage); + const approval = parse(webPlanApprovalSchema, await body()); + const requestId = approval.id; const existing = this.projects.detail(viewer, id).feedback.find(feedback => feedback.requestId === requestId && feedback.author.id === this.projects.identity(viewer)); if (existing?.target?.runId && existing.target.runId !== ref) fail(409, '同一命令标识不能用于另一运行。'); const observation = resolved.run.observation; const target = existing?.target ?? { runId: ref, statementVersionId: resolved.binding.statementVersionId, observationRef: observation ? { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } : fail(409, '运行尚无可操作观测。') }; - let submitted: ResearchFeedback; - if (subaction === 'guidance') { - const guidance = parse(webGuidanceSchema, input); - submitted = this.projects.submitFeedback(viewer, id, { requestId: guidance.id, kind: 'guidance', text: guidance.text, - recipient: guidance.recipient, target: { ...target, observationRef: guidance.observationRef, ...(guidance.taskRef ? { taskRef: guidance.taskRef } : {}) } }); - } else if (subaction === 'edits') { - const { id: requestId, ...proposal } = parse(webPlanProposalSchema, input); - submitted = this.projects.submitFeedback(viewer, id, { requestId, kind: 'plan-edit', text: '提交计划修改', target, proposal }); - } else { - const approval = parse(webPlanApprovalSchema, input); - submitted = this.projects.submitFeedback(viewer, id, { requestId: approval.id, kind: 'plan-approval', text: '批准当前研究计划', - target, planVersion: approval.planVersion }); - } + const submitted = this.projects.submitFeedback(viewer, id, { requestId, kind: 'plan-approval', text: '批准当前研究计划', + target, planVersion: approval.planVersion }); const feedback = await this.dispatch(viewer, id, submitted); const receipt = feedback.delivery.commandId && this.jobs.commandReceipt(resolved.runOwner, ref, feedback.delivery.commandId); return { status: 200, body: { receipt: receipt ? this.commandView(viewer, id, receipt) : null, feedback } }; diff --git a/apps/web/researchMode.ts b/apps/web/researchMode.ts index b989a1b8..fa786036 100644 --- a/apps/web/researchMode.ts +++ b/apps/web/researchMode.ts @@ -1,6 +1,6 @@ import { z } from 'zod'; import { MIN_TEAM_AGENTS, MAX_TEAM_AGENTS } from '../../src/solver/teamCapacity'; -import type { WebProvider, WebRunInput } from './shared'; +import { retiredPortfolioMessage, retiredResearchCoordinationMessage, type WebProvider, type WebRunInput } from './shared'; export const nativeTeamCapacitySchema = z.number().int().min(MIN_TEAM_AGENTS).max(MAX_TEAM_AGENTS); export const nativeTeamPreferencesSchema = z.array(z.string().trim().min(1).max(100)).max(256); @@ -11,28 +11,26 @@ export function webAgentTeamPreset(capacity = 3): Pick): boolean { - return input.portfolioExploration ?? (input.nativeTeamCapacity ?? input.workers) >= 2; +const requestsRetiredPortfolio = (input: Pick) => + input.portfolioExploration === true || input.portfolioSeconds !== undefined; + +export function retiredWebRunInputError(input: Partial>) { + if ((input.workers ?? 1) > 1) return retiredResearchCoordinationMessage; + if (requestsRetiredPortfolio(input)) return retiredPortfolioMessage; } /** The optional research engine is frozen with each new run, never changed by an observation. */ export function webResearchModeError(input: Pick, provider?: Pick): string | undefined { - if (input.portfolioExploration && (input.nativeTeamCapacity ?? input.workers) < 2) - return '路线探索至少需要两名研究员。'; - if (input.portfolioSeconds !== undefined && - (!input.portfolioExploration || !webPortfolioSecondsSchema.safeParse(input.portfolioSeconds).success)) - return '路线探索时长必须在启用路线探索时设为 1 至 86400 秒的整数。'; + if (requestsRetiredPortfolio(input)) return retiredPortfolioMessage; if (input.nativeTeamPreferredProfiles?.length && input.nativeTeamCapacity === undefined) return '角色偏好仅适用于 Codex 原生团队。'; if (input.nativeTeamCapacity !== undefined) { if (!nativeTeamCapacitySchema.safeParse(input.nativeTeamCapacity).success) return '原生团队容量必须为 2 至 8 人(含 Lead)。'; if (provider?.harness && provider.harness !== 'codex') return '原生团队需要 Codex 执行器。'; - if (input.researchMode !== 'skill' || input.workers !== 1 || input.coordination !== 'independent' || - input.planApproval || input.modulePlan) - return '原生团队由一名 Lead 自主派工,不能与宿主协作、审计划或自定义模块方案一起使用。'; + if (input.researchMode !== 'skill' || input.workers !== 1 || input.coordination !== 'independent' || input.modulePlan) + return '原生团队由一名 Lead 自主派工,不能与宿主协作或自定义模块方案一起使用。'; } if (input.researchMode !== undefined && !['legacy', 'skill'].includes(input.researchMode)) return '研究方式无效。'; if (input.skillLoading !== undefined && !['native', 'file'].includes(input.skillLoading)) return '技能加载方式无效。'; @@ -40,15 +38,12 @@ export function webResearchModeError(input: Pick): string[] { - const error = webResearchModeError(input, provider); + const error = retiredWebRunInputError(input) ?? webResearchModeError(input, provider); if (error) throw new Error(error); - const research = input.researchMode === 'skill' + return input.researchMode === 'skill' ? ['--research-mode', 'skill', '--skill-loading', input.skillLoading ?? webDefaultSkillLoading(provider), ...(input.nativeTeamCapacity ? ['--skill-delegation', 'team', '--skill-max-agents', String(input.nativeTeamCapacity)] : []), ...(input.nativeTeamPreferredProfiles?.length ? ['--skill-preferred-profiles', input.nativeTeamPreferredProfiles.join(',')] : [])] : []; - if (input.portfolioExploration === undefined) return research; - return [...research, input.portfolioExploration ? '--portfolio-exploration' : '--skip-portfolio', - ...(input.portfolioSeconds === undefined ? [] : ['--portfolio-seconds', String(input.portfolioSeconds)])]; } /** A Skill changes research methods; only the execution arrangement controls collaboration. */ diff --git a/apps/web/researchProjects.ts b/apps/web/researchProjects.ts index ed779b96..ee2676c4 100644 --- a/apps/web/researchProjects.ts +++ b/apps/web/researchProjects.ts @@ -2,7 +2,7 @@ import crypto from 'node:crypto'; import { z } from 'zod'; import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo'; import { webGuidanceSchema, webPlanApprovalSchema, webPlanProposalSchema } from './collaborationValidation'; -import type { WebCommandResult, WebGuidanceRecord, WebInspectedTask, WebObservation } from './collaboration'; +import type { WebCommandResult, WebGuidanceRecord, WebInspectedTask, WebObservation, WebPlanApproval } from './collaboration'; import { webLimits } from './shared'; import { WebStorage, WebStorageError } from './storage'; import type { ResearchCollaborationInbox, ResearchCollaborationState, ResearchCollaborationView, ResearchHandoff, @@ -925,7 +925,7 @@ export class WebResearchProjects { if (record.candidateDelivery && ['queued', 'delivered', 'deferred'].includes(record.delivery.status)) record.candidateDelivery.status = 'dispatched'; const observed = receipt.observation ?? resolved.run.observation; this.observeDecision(record, receipt.guidance ?? observed?.guidance.find(item => item.id === record.id)); - this.observeExecution(record, observed); + this.observeExecution(record, observed, resolved.run.initialPlanApproval?.receipt); if (canonicalMathJson(record) !== before) { record.revision++; record.updatedAt = now(); this.event(stored, viewer, 'feedback-updated', '更新反馈投递与执行回执', { feedbackId }); this.save(stored); @@ -942,7 +942,16 @@ export class WebResearchProjects { evidenceRefs: decision.evidenceRefs.map(ref => ref.kind === 'edit' ? `edit:${ref.id}` : ref.kind === 'plan' ? `plan:${ref.version}` : `task:${ref.id}@${ref.version}`) }; } - private observeExecution(record: ResearchFeedback, observation?: WebObservation) { + private observeExecution(record: ResearchFeedback, observation?: WebObservation, initialApproval?: WebPlanApproval) { + if (record.kind === 'plan-approval') { + const approval = [initialApproval, observation?.inspection.planApproval].find(item => item?.approvedId === record.id); + if (approval) { + record.delivery = { status: 'delivered', commandId: record.id }; + record.execution = { status: 'completed', planVersion: approval.approvedVersion, taskRefs: [], + resultRefs: [...new Set([...record.execution.resultRefs, `plan-approval:${record.id}`])] }; + } + return; + } if (!observation || record.kind === 'proof-submission' && record.proofCheck?.status !== 'checked') return; const previous = record.execution; if (record.kind === 'proof-submission') { @@ -964,12 +973,6 @@ export class WebResearchProjects { return; } if (edit?.status === 'rejected') { record.execution.status = 'failed'; return; } - const approval = observation.inspection.planApproval; - if (approval?.approvedId === record.id) { - record.execution = { status: 'completed', planVersion: approval.approvedVersion, taskRefs: [], - resultRefs: [...new Set([...previous.resultRefs, `plan-approval:${record.id}`])] }; - return; - } if (record.decision.status !== 'accepted' || record.kind !== 'guidance') return; const tasks = new Map([...(observation.history ?? []), ...observation.inspection.tasks] .map(task => [`task:${task.id}@${task.version}`, task])); @@ -1036,15 +1039,16 @@ export class WebResearchProjects { /** Refreshes from server-owned observations. It does not submit commands or infer adoption from temporal proximity. */ syncRunObservation(viewer: string, projectId: string, runId: string): void { const resolved = this.resolveBinding(viewer, projectId, runId), observation = resolved.run.observation; - if (!observation) return; + const initialApproval = resolved.run.initialPlanApproval?.receipt; + if (!observation && !initialApproval) return; const stored = this.readable(viewer, projectId); let changed = false; for (const record of stored.feedback.filter(item => item.target?.runId === runId)) { - const before = canonicalMathJson(record), guidance = observation.guidance.find(item => item.id === record.id); + const before = canonicalMathJson(record), guidance = observation?.guidance.find(item => item.id === record.id); if (guidance && !['delivered', 'failed'].includes(record.delivery.status)) record.delivery = { status: guidance.status, commandId: record.id, reason: guidance.reason }; this.observeDecision(record, guidance); - this.observeExecution(record, observation); + this.observeExecution(record, observation, initialApproval); if (canonicalMathJson(record) !== before) { record.revision++; record.updatedAt = now(); changed = true; this.event(stored, resolved.runOwner, 'feedback-updated', '同步运行反馈证据', { feedbackId: record.id }); diff --git a/apps/web/researchWorkspace.ts b/apps/web/researchWorkspace.ts index 6079f781..071a1ad3 100644 --- a/apps/web/researchWorkspace.ts +++ b/apps/web/researchWorkspace.ts @@ -234,6 +234,7 @@ export class WebResearchWorkspace { })() : data.runs.find(view => view.run.id === runId && view.owned); if (!view) throw new WebStorageError(404, '运行不存在或不属于当前会话。'); const { run } = view, observation = run.observation; + const approval = run.initialPlanApproval?.receipt ?? observation?.inspection.planApproval; const runOwner = view.owned ? viewer : this.projects.resolveBinding(viewer, projectId!, runId).runOwner; const recorded = this.storage.listObservations(runOwner, runId); const project = projectId ? data.projects.find(project => project.id === projectId) @@ -267,8 +268,8 @@ export class WebResearchWorkspace { tasks: observation?.inspection.tasks.map(task => researchBriefTask(task, observation, checks, task => runHref(view, task))) ?? [], routes: (observation?.plan?.proofRoutes ?? []).map(route => ({ id: route.id, prerequisites: [...route.prerequisiteTaskIds], closingTaskId: route.closingTaskId, targetTaskId: route.targetTaskId })), decisions, - ...(observation?.inspection.planApproval ? { planApproval: { status: observation.inspection.planApproval.status, - planVersion: observation.inspection.planApproval.planVersion } } : {}), + ...(approval ? { planApproval: { status: approval.status, + planVersion: run.initialPlanApproval?.receipt.approvedVersion ?? approval.planVersion } } : {}), blockers: (observation?.inspection.mathematics.snapshot.blockers ?? []).filter(blocker => observation?.inspection.tasks.some(task => task.id === blocker.taskId && task.version === blocker.taskDigest)) .map(blocker => ({ id: blocker.id, taskId: blocker.taskId, taskVersion: blocker.taskDigest, mechanism: blocker.mechanism, diff --git a/apps/web/runner.ts b/apps/web/runner.ts index 3b3b929d..2f906934 100644 --- a/apps/web/runner.ts +++ b/apps/web/runner.ts @@ -1,3 +1,4 @@ +import { retiredWebRunInputError } from './researchMode'; import type { WorkerFormalizationAuditInput } from './formalizationAuditTypes'; import { spawn } from 'node:child_process'; import { execFile } from 'node:child_process'; @@ -9,7 +10,7 @@ import { promisify } from 'node:util'; import { z } from 'zod'; import type { WebConfig } from './config'; import type { WorkerExplanationInput, WorkerExplanationMessage, WorkerInput, WorkerMessage } from './shared'; -import { webArtifactMaxBytes, webExplanationPhases, webExplanationReason, webFailureKinds, webFailureReason, webPaperLimits } from './shared'; +import { retiredResearchCoordinationCode, webArtifactMaxBytes, webExplanationPhases, webExplanationReason, webFailureKinds, webFailureReason, webPaperLimits } from './shared'; import { isWebEventDetails } from './moduleTelemetry'; import { explanationCheckpointSchema, maxExplanationMessageBytes } from './explanationCheckpoint'; import { isWebAgentActionBody } from './agentActions'; @@ -215,7 +216,7 @@ export function parseFormalizationMessage(line: string): WorkerFormalizationMess } export class DockerWebRunner implements WebRunner { - private cached?: { at: number; result: Awaited>; workerControl: boolean }; + private cached?: { at: number; result: Awaited>; workerControl: boolean; imageId?: string }; private active = new Set(); constructor(private readonly config: Pick & Partial>) {} @@ -289,6 +290,7 @@ export class DockerWebRunner implements WebRunner { }; async command(id: string, command: WebCommand): Promise { + if (command.type !== 'capture' && command.type !== 'plan-approval') throw new Error(retiredResearchCoordinationCode); if (!this.active.has(id)) throw new Error('运行环境尚未就绪或已结束。'); return new Promise((resolve, reject) => { const child = spawn('docker', ['exec', '--interactive', `theoremos-web-${id}`, @@ -427,19 +429,32 @@ export class DockerWebRunner implements WebRunner { async readiness() { if (this.cached && Date.now() - this.cached.at < 10_000) return this.cached.result; - const metadata = await execute('docker', ['image', 'inspect', '--format', '{{index .Config.Labels "org.theoremos.native-agent-control"}}|{{index .Config.Labels "org.theoremos.team-profile-preferences"}}|{{index .Config.Labels "org.theoremos.team-expert-cards"}}|{{index .Config.Labels "org.theoremos.worker-control"}}', + const metadata = await execute('docker', ['image', 'inspect', '--format', '{{index .Config.Labels "org.theoremos.native-agent-control"}}|{{index .Config.Labels "org.theoremos.team-profile-preferences"}}|{{index .Config.Labels "org.theoremos.team-expert-cards"}}|{{index .Config.Labels "org.theoremos.worker-control"}}|{{index .Config.Labels "org.theoremos.native-team-workflow"}}|{{.Id}}', this.config.workerImage], { timeout: 5_000, maxBuffer: 4096 }).catch(() => undefined); const ready = Boolean(metadata); - const [team, preferences, expertCards, workerControl] = metadata?.stdout.trim().split('|') ?? []; - const result = { ready, nativeTeam: team === 'v1', nativeTeamPreferences: team === 'v1' && preferences === 'v1', - nativeTeamExpertCards: team === 'v1' && expertCards === 'v1', + const [team, preferences, expertCards, workerControl, workflow, id] = metadata?.stdout.trim().split('|') ?? []; + const imageId = /^sha256:[a-f0-9]{64}$/u.test(id ?? '') ? id : undefined; + const nativeTeam = team === 'v1' && workflow === 'v1' && Boolean(imageId); + const result = { ready, nativeTeam, nativeTeamPreferences: nativeTeam && preferences === 'v1', + nativeTeamExpertCards: nativeTeam && expertCards === 'v1', message: ready ? '运行环境就绪' : '运行镜像尚未就绪,请先构建 theorem-os-worker 镜像。' }; - this.cached = { at: Date.now(), result, workerControl: workerControl === 'v1' }; + this.cached = { at: Date.now(), result, workerControl: workerControl === 'v1', imageId }; return result; } async run(input: WorkerInput, onMessage: (message: WorkerMessage) => void, signal: AbortSignal): Promise { signal.throwIfAborted(); + if (retiredWebRunInputError(input.input)) throw new Error(retiredResearchCoordinationCode); + let workerImage = this.config.workerImage; + if (input.input.nativeTeamCapacity) { + await this.readiness(); + const capability = this.cached; + if (!capability?.result.nativeTeam || !capability.imageId) + throw new Error('当前运行镜像未安装支持原生团队与路线审批的 worker,请更新运行镜像。'); + // Launch the checked image even if a local tag changes while the run is queued. + workerImage = capability.imageId; + signal.throwIfAborted(); + } const name = `theoremos-web-${input.id}`; const environment = input.input.environment ?? 'standard'; const mathlib = environment === 'mathlib'; @@ -462,7 +477,7 @@ export class DockerWebRunner implements WebRunner { ...(workerControl ? ['--env', 'THEOREMOS_WORKER_CONTROL=1'] : []), ...(mathlib ? ['--device=/dev/fuse:/dev/fuse:rw', '--mount', 'type=volume,destination=/var/tmp'] : ['--tmpfs', '/var/tmp:rw,nosuid,nodev,size=536870912,uid=10001,gid=10001,mode=0700']), - this.config.workerImage, environment]; + workerImage, environment]; // Create first so cancellation always has a known container to remove. try { await execute('docker', args, { timeout: 30_000, maxBuffer: 8_192 }); diff --git a/apps/web/server.ts b/apps/web/server.ts index ce17a249..551b4369 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -1,5 +1,6 @@ import { publicWebProvider, webProviderHarness, webHarnessResearchError } from './harness'; -import { nativeTeamCapacitySchema, nativeTeamPreferencesSchema, webDefaultSkillLoading, webPortfolioSecondsSchema } from './researchMode'; +import { nativeTeamCapacitySchema, nativeTeamPreferencesSchema, webAgentTeamPreset, webDefaultSkillLoading, + retiredWebRunInputError, webPortfolioSecondsSchema, webResearchModeError } from './researchMode'; import { webTeamProfiles } from './nativeTeamProfiles'; import http, { type IncomingMessage, type ServerResponse } from 'node:http'; import fs from 'node:fs'; @@ -11,13 +12,13 @@ import { z } from 'zod'; import { getWebEnvironments, readWebConfig, webDefaults, webExplanationLimits, webLimits, webTemplates, webProvidersForAccount, type WebConfig } from './config'; import { DockerWebRunner, type WebRunner } from './runner'; import { WebJobs } from './jobs'; -import { accountLogin, webAgentActionLimits, webContinuationLabelMax, type WebAccountIdentity, type WebAdminOverview, type WebContinuation, type WebEffort, +import { accountLogin, retiredResearchCoordinationCode, retiredResearchCoordinationMessage, webAgentActionLimits, webContinuationLabelMax, type WebAccountIdentity, type WebAdminOverview, type WebContinuation, type WebEffort, type WebExplanationLanguage, type WebExplanationOverview, type WebProvider, type WebRun, type WebRunInput, type WebSession, workbenchReturn } from './shared'; import { researchModulePlanSchema, type ResearchModulePlan } from '../../src/solver/modules/policy'; import { WebStorage, WebStorageError } from './storage'; import { WebKnowledgeService, type WebKnowledgeDetailOptions } from './knowledgeService'; import { WebModuleRegistry } from './moduleRegistry'; -import { webGuidanceSchema, webPlanApprovalSchema, webPlanProposalSchema } from './collaborationValidation'; +import { webPlanApprovalSchema } from './collaborationValidation'; import { WebAuth, WebAuthError, type WebMailer, type WebMilestone } from './auth'; import { WebSessionAdmission, WebAdmissionError } from './admission'; import { WebOperations } from './operations'; @@ -54,7 +55,6 @@ import { selectWebLibraryPack } from './frozenLibrary'; import type { ResearchConfigurationSelection, ResearchLibraryPack } from './researchAssetTypes'; import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo'; import { researchLibraryProposalOriginSchema } from './researchLibraryProposalOrigin'; -import { webResearchModeError } from './researchMode'; const inputSchema = z.object({ requestId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/u).optional(), @@ -151,7 +151,7 @@ const formalizationProvider = (provider: WebProvider | undefined) => !!provider const providerModel = (provider: WebProvider) => provider.id === SUB2API_PROVIDER.id ? SUB2API_PROVIDER.defaultModel : 'gpt-6.1-sol'; class HttpError extends Error { - constructor(readonly status: number, message: string) { super(message); } + constructor(readonly status: number, message: string, readonly code?: string) { super(message); } } function paperPdfHttpError(error: WebPaperPdfError): HttpError { const location = error.file && Number.isSafeInteger(error.line) ? `${error.file}:${error.line}` : ''; @@ -251,6 +251,9 @@ type Session = { id: string; csrf: string; touchedAt: number; account?: WebAccou const objectBody = (value: unknown) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {}) as Record; export function createWebService(config: WebConfig, runner: WebRunner = new DockerWebRunner(config), options: { mailer?: WebMailer; captchaAnswer?: () => string; sample?: WebSampleFile | null } = {}) { + const rejectRetiredCoordination = (): never => { + throw new HttpError(409, retiredResearchCoordinationMessage, retiredResearchCoordinationCode); + }; const storage = new WebStorage(config.dataRoot); const operations = new WebOperations(storage, config.dataRoot); const productBuild = readProductBuild(config.staticRoot); @@ -351,8 +354,8 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock !['rejected', 'interrupted', 'superseded'].includes(run.formalization?.confirmation ?? '') && (!run.formalization?.candidateDigest || run.formalization.candidateDigest === digest)); if (existing) return existing.id; - const run = jobs.create(owner, { ...webDefaults, ...webFormalizationDefaults.research, ...formalization.research, - ...(formalization.humanReview ? { workers: 2, coordination: 'cooperative' as const, planApproval: true } : {}), + const run = jobs.create(owner, { ...webDefaults, ...webFormalizationDefaults.research, ...formalization.research, ...webAgentTeamPreset(), + ...(formalization.humanReview ? { planApproval: true } : {}), providerId: input.provider.id, apiKey: input.apiKey, autoExplain: formalization.autoExplain, explanationLanguage: formalization.explanationLanguage, model: input.model, effort: formalization.researchEffort ?? input.effort, source: evidence.candidate.source, environment: evidence.request.environment, @@ -368,7 +371,7 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock const existing = jobs.list(owner).find(run => run.formalizationId === formalization.id && !run.continueFrom && run.formalization?.candidateDigest === digest && run.source === compiled.candidate.source && run.environment === compiled.request.environment); if (existing) return existing.id; - const run = jobs.create(owner, { ...webDefaults, ...webFormalizationDefaults.research, ...formalization.research, + const run = jobs.create(owner, { ...webDefaults, ...webFormalizationDefaults.research, ...formalization.research, ...webAgentTeamPreset(), providerId: input.provider.id, apiKey: input.apiKey, model: input.model, effort: formalization.researchEffort ?? input.effort, autoExplain: formalization.autoExplain, explanationLanguage: formalization.explanationLanguage, source: compiled.candidate.source, environment: compiled.request.environment, formalizationId: formalization.id, @@ -487,8 +490,10 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (request.url === '/healthz') { json(response, 200, { ok: true, ...config.sourceCommit ? { commit: config.sourceCommit } : {} }); return; } if (request.url === '/readyz' && request.method === 'GET') { const maintenance = operations.maintenance; - const ready = !maintenance && operations.writable() && (await runner.readiness()).ready; - json(response, ready ? 200 : 503, { ready, maintenance, ...(config.sourceCommit ? { commit: config.sourceCommit } : {}) }); return; + const runtime = await runner.readiness(); + const nativeTeam = runtime.ready && runtime.nativeTeam === true; + const ready = !maintenance && operations.writable() && nativeTeam; + json(response, ready ? 200 : 503, { ready, maintenance, nativeTeam, ...(config.sourceCommit ? { commit: config.sourceCommit } : {}) }); return; } if (request.headers.host !== origin.host) throw new HttpError(403, '访问地址与服务配置不一致。'); if (request.headers.origin && request.headers.origin !== origin.origin) throw new HttpError(403, '跨站请求已拒绝。'); @@ -518,8 +523,9 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock json(response, 200, { share: share.snapshot }); return; } if (url.pathname === '/api/product/status' && request.method === 'GET') { + const runtime = await runner.readiness(); json(response, 200, productStatus({ build: productBuild, commit: config.sourceCommit, maintenance: operations.maintenance, - writable: operations.writable(), runtimeReady: (await runner.readiness()).ready })); return; + writable: operations.writable(), runtimeReady: runtime.ready && runtime.nativeTeam === true })); return; } let session = cookieSession(request); if (request.method === 'GET' && url.pathname === '/api/session') { @@ -668,7 +674,8 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (!auth || !session.account || !auth.isAdmin(accountLogin(session.account))) throw new HttpError(403, '需要管理员账号。'); if (url.pathname === '/api/admin/overview' && request.method === 'GET') { json(response, 200, adminOverview(auth, quota)); return; } if (url.pathname === '/api/admin/operations' && request.method === 'GET') { - const ready = operations.writable() && (await runner.readiness()).ready; + const runtime = await runner.readiness(); + const ready = operations.writable() && runtime.ready && runtime.nativeTeam === true; let disk: ReturnType; try { disk = operations.disk(); } catch { /* ready reports an inaccessible data volume. */ } json(response, 200, { maintenance: operations.maintenance, ready, ...(disk ? { disk } : {}), failures: operations.failures(), @@ -773,21 +780,9 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock conversations.delete(owner, id); json(response, 200, { deleted: true }); return; } if (action === 'stop' && request.method === 'POST') { json(response, 200, { conversation: conversations.stop(owner, id) }); return; } - if (action === 'guidance' && request.method === 'POST') { - const { runId, ...input } = objectBody(await readBody()); - const expectedRun = z.string().uuid().optional().safeParse(runId); - const parsed = webGuidanceSchema.safeParse(input); - if (!parsed.success || !expectedRun.success) throw new HttpError(400, '请检查指导对象、任务版本与内容。'); - const conversation = await conversations.guide(owner, id, parsed.data, - (runId, guidance) => jobs.command(owner, runId, { type: 'guidance', guidance }), expectedRun.data); - json(response, 200, { conversation }); return; - } - if (action === 'guidance-withdraw' && request.method === 'POST') { - const commandId = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/u); - const parsed = z.object({ id: commandId, guidanceId: commandId }).strict().safeParse(await readBody()); - if (!parsed.success) throw new HttpError(400, '请检查要撤回的指导。'); - json(response, 200, await conversations.withdrawGuidance(owner, id, - { id: parsed.data.id, guidanceId: parsed.data.guidanceId }, (runId, command) => jobs.command(owner, runId, command))); return; + if (request.method === 'POST' && (action === 'guidance' || action === 'guidance-withdraw')) { + conversations.read(owner, id); + rejectRetiredCoordination(); } if (action === 'messages' && request.method === 'POST') { const conversation = conversations.read(owner, id); @@ -814,8 +809,10 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock savedKeysFor(session).some(item => item.providerId === provider.id) ? 'saved' : serverKeysFor(session)?.includes(provider.id) ? 'server' : 'required'; if (request.method === 'GET') { - const formalizationReady = Boolean(runner.formalize) && (await runner.readiness()).ready; - const generation: WebFormalizationCapabilities = { available: !!defaultProvider && formalizationReady, + const runtime = await runner.readiness(); + const formalizationReady = Boolean(runner.formalize) && runtime.ready; + const available = !!defaultProvider && formalizationReady; + const generation: WebFormalizationCapabilities = { available, solveAvailable: available && runtime.nativeTeam === true, ...(!defaultProvider ? { reason: 'provider' as const } : !formalizationReady ? { reason: 'runtime' as const } : {}), ...(defaultProvider ? { providerId: defaultProvider.id } : {}), model: defaultProvider ? providerModel(defaultProvider) : SUB2API_PROVIDER.defaultModel, key: defaultProvider ? keyKind(defaultProvider) : 'required', limits: webFormalizationLimits, @@ -839,11 +836,12 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock throw new HttpError(400, 'Sub2API 形式化目前支持 deepseek-flash 模型。'); const previous = formalizations.replay(owner, input as WebFormalizationRequest, provider, model); if (previous) { json(response, 200, { formalization: previous }); return; } - const ready = Boolean(runner.formalize) && (await runner.readiness()).ready; + const runtime = await runner.readiness(); // Readiness yields to concurrent requests; replay again before spending quota. const raced = formalizations.replay(owner, input as WebFormalizationRequest, provider, model); if (raced) { json(response, 200, { formalization: raced }); return; } - if (!ready) throw new HttpError(503, '形式化运行环境尚未就绪。'); + if (!runner.formalize || !runtime.ready) throw new HttpError(503, '形式化运行环境尚未就绪。'); + if (input.solve && !runtime.nativeTeam) throw new HttpError(503, '当前运行镜像未安装原生团队后端。'); const apiKey = parsed.data.apiKey || heldKey(session, provider); if (!apiKey) throw new HttpError(400, '请填写 API Key。'); // A confirmed formalization starts its proof through jobs.create itself, so it costs this kind only. @@ -879,10 +877,12 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock const item = formalizations.read(owner, id); if (item.runId) { json(response, 200, { formalization: item }); return; } const provider = providersFor(session).find(provider => provider.id === (item.providerId ?? SUB2API_PROVIDER.id)); - if (!provider) throw new HttpError(409, '这次运行的模型服务已不在配置中。'); + if (!provider || !formalizationProvider(provider)) throw new HttpError(409, '这次运行的 Codex 模型服务已不在配置中。'); const apiKey = parsed.data.apiKey || heldKey(session, provider); if (!apiKey) throw new HttpError(400, '请填写 API Key。'); - if (!(await runner.readiness()).ready) throw new HttpError(503, '自动证明运行环境尚未就绪。'); + const runtime = await runner.readiness(); + if (!runtime.ready) throw new HttpError(503, '自动证明运行环境尚未就绪。'); + if (!runtime.nativeTeam) throw new HttpError(503, '当前运行镜像未安装原生团队后端。'); admitWork(); try { json(response, 200, { formalization: formalizations.retryResearch(owner, id, provider, apiKey) }); } catch (error) { @@ -1011,32 +1011,49 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (!parsed.success) throw new HttpError(400, '请检查题目、API Key、模型、模块方案及运行预算。'); const provider = providersFor(session).find(item => item.id === parsed.data.providerId); if (!provider) throw new HttpError(400, '该模型服务尚未配置。'); - const { saveKey, requestId: bodyRequestId, ...input } = parsed.data; - const legacyEnvironmentOmitted = input.environment === undefined; - input.environment ??= webDefaults.environment; + const { saveKey, requestId: bodyRequestId, ...submitted } = parsed.data; + const legacyEnvironmentOmitted = submitted.environment === undefined; + submitted.environment ??= webDefaults.environment; const headerId = request.headers['idempotency-key']; if (headerId !== undefined && (typeof headerId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/u.test(headerId) || bodyRequestId && bodyRequestId !== headerId)) throw new HttpError(400, '提交请求标识无效或不一致。'); const requestId = bodyRequestId ?? (typeof headerId === 'string' ? headerId : undefined); // Confirmed statements retain their exact artifact bytes; ordinary Lean drafts keep the existing normalization. - if (!input.formalizationId) input.source = input.source.trim(); + if (!submitted.formalizationId) submitted.source = submitted.source.trim(); if (webProviderHarness(provider) !== 'codex') { - input.researchMode ??= 'skill'; input.skillLoading ??= 'file'; + submitted.researchMode ??= 'skill'; submitted.skillLoading ??= 'file'; } - const harnessError = webHarnessResearchError(provider, input as WebRunInput); - if (harnessError) throw new HttpError(400, harnessError); - const researchModeError = webResearchModeError(input as WebRunInput, provider); - if (researchModeError) throw new HttpError(400, researchModeError); - if (input.researchMode === 'skill') input.skillLoading ??= webDefaultSkillLoading(provider); - if (input.planApproval && (input.coordination !== 'cooperative' || input.workers < 2)) - throw new HttpError(400, '先审计划需要协作模式和至少 2 个 Agent。'); - if (!input.planApproval) delete input.planApproval; - const typed = input.apiKey; + if (submitted.researchMode === 'skill') submitted.skillLoading ??= webDefaultSkillLoading(provider); + if (!submitted.planApproval) delete submitted.planApproval; + // Retry the exact submitted identity before considering migration defaults or runtime capabilities. + const creationInput = submitted as WebRunInput; + const typed = submitted.apiKey; const submissionKeys = (failed = false) => vault ? { savedKeys: savedKeysFor(session), ...(failed || saveKey && typed && session.account && vault.get(session.account.id, provider.id, provider.baseUrl) !== typed ? { keySaveFailed: true } : {}) } : {}; - const previous = jobs.replay(owner, input as WebRunInput, provider, requestId, legacyEnvironmentOmitted); + const previous = jobs.replay(owner, creationInput, provider, requestId, legacyEnvironmentOmitted); if (previous) { json(response, 200, { run: previous, ...submissionKeys() }); return; } + const retiredInput = retiredWebRunInputError(submitted); + if (retiredInput) throw new HttpError(400, retiredInput, retiredResearchCoordinationCode); + const harnessError = webHarnessResearchError(provider, creationInput); + if (harnessError) throw new HttpError(400, harnessError); + const researchModeError = webResearchModeError(creationInput, provider); + if (researchModeError) throw new HttpError(400, researchModeError); + if (submitted.planApproval && webProviderHarness(provider) !== 'codex') + throw new HttpError(400, '先审计划需要 Codex 原生团队。'); + // A typed key wins; an empty one uses the account's saved key, then the server's key for admins. + const apiKey = typed || heldKey(session, provider); + if (!apiKey) throw new HttpError(400, '请填写 API Key。'); + const readiness = await runner.readiness(); + const raced = jobs.replay(owner, creationInput, provider, requestId, legacyEnvironmentOmitted); + if (raced) { json(response, 200, { run: raced, ...submissionKeys() }); return; } + if (!readiness.ready) throw new HttpError(503, '运行环境尚未就绪,请先构建 worker 镜像。'); + if ((submitted.nativeTeamCapacity || submitted.planApproval) && !readiness.nativeTeam) + throw new HttpError(503, '当前运行镜像未安装原生团队后端。'); + const input = { ...submitted, apiKey, environment: submitted.environment ?? webDefaults.environment, coordination: 'independent' as const, + ...(webProviderHarness(provider) === 'codex' && readiness.nativeTeam ? webAgentTeamPreset(submitted.nativeTeamCapacity) : {}) }; + if (input.nativeTeamCapacity && input.modulePlan) + throw new HttpError(400, '原生团队不使用自定义模块方案。'); if (input.libraryProposalOrigin) research.validateLibraryProposalOrigin(owner, input.libraryProposalOrigin); if (input.budgetOrigin) { const origin = research.projects.resolveBinding(owner, input.budgetOrigin.projectId, input.budgetOrigin.runId); @@ -1057,18 +1074,6 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock const { digest: _digest, ...configuration } = frozenResearch; frozenResearch.digest = mathDigest(canonicalMathJson(configuration)); } - // A typed key wins; an empty one uses the account's saved key, then the server's key for admins. - if (!typed) { - const held = heldKey(session, provider); - if (!held) throw new HttpError(400, '请填写 API Key。'); - input.apiKey = held; - } - const readiness = await runner.readiness(); - // Another request can be accepted while readiness is being checked. - const raced = jobs.replay(owner, input as WebRunInput, provider, requestId, legacyEnvironmentOmitted); - if (raced) { json(response, 200, { run: raced, ...submissionKeys() }); return; } - if (!readiness.ready) throw new HttpError(503, '运行环境尚未就绪,请先构建 worker 镜像。'); - if (input.nativeTeamCapacity && !readiness.nativeTeam) throw new HttpError(503, '当前运行镜像未安装原生团队后端。'); if (frozenResearch?.personalExperts?.length && !readiness.nativeTeamExpertCards) throw new HttpError(503, '当前运行镜像不支持个人专家资料。请移除专家资产或更新运行镜像。'); if (input.nativeTeamPreferredProfiles?.length && !readiness.nativeTeamPreferences) throw new HttpError(503, '当前运行镜像不支持角色偏好。清空偏好后仍可使用原生团队。'); @@ -1099,7 +1104,7 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock approved ? { evidence: approved.evidence, provenance: { id: approved.formalization.id, evidenceSha256: approved.formalization.report!.evidenceSha256, original: approved.formalization.original, confirmedAt: approved.formalization.confirmedAt!, confirmation: approved.formalization.confirmation ?? 'manual' } } : undefined, - frozenResearch); + frozenResearch, creationInput); } catch (error) { // A submit that never became a run gives the allowance back. @@ -1368,29 +1373,18 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (!receipt) throw new HttpError(404, '命令回执尚不可用。'); json(response, 200, { receipt }); return; } - if (operation === 'guidance' && request.method === 'POST') { - const parsed = webGuidanceSchema.safeParse(await readBody()); - if (!parsed.success) throw new HttpError(400, '请检查指导对象、任务版本与内容。'); - try { json(response, 200, { receipt: await jobs.command(owner, run.id, { type: 'guidance', guidance: parsed.data }) }); } - catch (error) { throw new HttpError(409, error instanceof Error ? error.message : '指导未能提交。'); } - return; - } + if (request.method === 'POST' && ['guidance', 'edits/preview', 'edits'].includes(operation ?? '')) + rejectRetiredCoordination(); if (operation === 'plan-approval' && request.method === 'POST') { + if (!run.nativeTeamCapacity && run.planApproval) rejectRetiredCoordination(); + if (!run.nativeTeamCapacity || !run.planApproval) + throw new HttpError(409, '此研究安排不支持计划审批。'); const parsed = webPlanApprovalSchema.safeParse(await readBody()); if (!parsed.success) throw new HttpError(400, '请重新读取当前计划后再批准。'); try { json(response, 200, { receipt: await jobs.command(owner, run.id, { type: 'plan-approval', approval: parsed.data }) }); } catch (error) { throw new HttpError(409, error instanceof Error ? error.message : '计划批准未能提交。'); } return; } - if (['edits/preview', 'edits'].includes(operation ?? '') && request.method === 'POST') { - const parsed = webPlanProposalSchema.safeParse(await readBody()); - if (!parsed.success) throw new HttpError(400, '计划草稿格式无效,请保留完整计划与基线版本。'); - try { json(response, 200, { receipt: await jobs.command(owner, run.id, { - type: operation === 'edits/preview' ? 'edit-preview' : 'edit', proposal: parsed.data, - }) }); } - catch (error) { throw new HttpError(409, error instanceof Error ? error.message : '计划未能提交。'); } - return; - } if (operation === 'archive' && request.method === 'POST') { json(response, 200, { archive: await jobs.archive(owner, run.id) }); return; } @@ -1477,7 +1471,8 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock const known = error instanceof HttpError || error instanceof WebStorageError || error instanceof WebAuthError || error instanceof WebAdmissionError || error instanceof WebProviderCheckError; if (!response.headersSent) json(response, known ? error.status : invalidKnowledgeInput ? 400 : 500, - { error: known ? error.message : invalidKnowledgeInput ? '知识查询或分页参数无效。' : '服务暂时不可用。' }); + { error: known ? error.message : invalidKnowledgeInput ? '知识查询或分页参数无效。' : '服务暂时不可用。', + ...(error instanceof HttpError && error.code ? { code: error.code } : {}) }); else response.end(); } }); diff --git a/apps/web/shared.ts b/apps/web/shared.ts index 1f63f311..64f0e204 100644 --- a/apps/web/shared.ts +++ b/apps/web/shared.ts @@ -1,5 +1,5 @@ import type { ResearchModulePlan, ResearchModuleSlot } from '../../src/solver/modules/policy'; -import type { WebObservation, WebArchive, WebLibraryRestart } from './collaboration'; +import type { WebObservation, WebArchive, WebLibraryRestart, WebPlanApproval } from './collaboration'; import type { WebFormalizationBackgroundReview } from './formalizationTypes'; import type { ResearchLibraryProposalOrigin } from './researchLibraryProposalOrigin'; import { webTaskEnvironment } from './environment'; @@ -7,6 +7,9 @@ import { webTaskEnvironment } from './environment'; export type WebEffort = 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'; export type WebCoordination = 'cooperative' | 'independent'; export type WebResearchMode = 'legacy' | 'skill'; +export const retiredResearchCoordinationCode = 'math_legacy_collaboration_retired'; +export const retiredResearchCoordinationMessage = '旧协作任务请使用对应的历史版本继续。新建多人研究使用 Codex 原生团队。'; +export const retiredPortfolioMessage = '旧版独立路线探索已停用;新研究可由 Codex 原生团队探索路线。'; export type WebSkillLoading = 'native' | 'file'; export type WebTeamProfile = { id: string; name: string; kind: 'work' | 'domain'; nameZh?: string; alias?: string }; export type WebRunStatus = 'queued' | 'running' | 'completed' | 'cancelled' | 'error'; @@ -83,7 +86,7 @@ export type WebRunInput = { /** Optional bounded scouting stage before ordinary proof dispatch. */ portfolioExploration?: boolean; portfolioSeconds?: number; - /** AgentResearchTeam capacity includes Lead. The host starts one Lead with native tools and can fall back to host tools. */ + /** AgentResearchTeam capacity includes Lead. New teams use native Codex tools. */ nativeTeamCapacity?: number; /** Advisory Skill profile IDs requested before starting; actual assignments belong to Lead. */ nativeTeamPreferredProfiles?: string[]; @@ -192,6 +195,8 @@ export type WebRun = { confirmation?: 'automatic' | 'manual' | 'pending' | 'rejected' | 'interrupted' | 'superseded'; reviewMode?: 'direct' }; /** Host-declared solver attempt; observation sequences continue across library restarts. */ solverAttempt?: { solverRunId: string; round: number; sequence: number }; + /** Approval recorded by the first solver, retained when the Web run installs a library and continues. */ + initialPlanApproval?: { solverRunId: string; receipt: WebPlanApproval }; observation?: WebObservation; archives?: WebArchive[]; knowledgeCatalogDigest?: string; diff --git a/apps/web/worker.ts b/apps/web/worker.ts index 28d8961c..749276af 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -20,13 +20,14 @@ import { runSolver } from '../../src/solver/run'; import { readKnowledgeCatalog } from '../../src/solver/theoremKnowledgeStore'; import { createWebProgressForwarder } from './progress'; import { withoutCheckMarkers } from './report'; -import { webArtifactMaxBytes, webPreparationSeconds, type WebAgentActionBody, type WebArtifact, type WorkerInput } from './shared'; +import { retiredResearchCoordinationCode, + webArtifactMaxBytes, webPreparationSeconds, type WebAgentActionBody, type WebArtifact, type WorkerInput } from './shared'; import { createAgentActionStream, sanitizeAgentItem } from './agentActions'; import { createWebWorkerBridge, freezeWebKnowledge, writeWebActiveRun } from './workerBridge'; import { webByokModuleIdentity } from './webModuleIdentity'; import { webAgentLibraryAccess } from './frozenLibrary'; import { runWebLibraryResearch } from './libraryResearch'; -import { webResearchArguments } from './researchMode'; +import { retiredWebRunInputError, webResearchArguments } from './researchMode'; import { webProofMessageSink } from './proofJournal'; import { createWebHostDisconnectWatchdog, webWorkerShutdownMs } from './workerDisconnect'; import { bindWebWorkerProfile, pinWebWorkerSession, prepareWebNativeProfile, webHarnessEnvironment, @@ -203,7 +204,6 @@ Continue the assigned work in this same turn after each update. Updates need no export function webSolverModules(request: WorkerInput, actions?: { sink: (action: WebAgentActionBody) => void; hidden: readonly string[]; solverRunId?: () => string | undefined }, isolation?: WebAgentIsolation): SolverModules { - webResearchArguments(request.input, request.provider); const base = configurableSolverModules(request.input.modulePlan, request.input.coordination, request.input.workers); const identity = webByokModuleIdentity(solverModuleConfiguration(base)); let sessions = 0; @@ -286,6 +286,13 @@ async function main(watchdog: ReturnType const write = webProofMessageSink(process.stdout, key, journalDirectory ? { directory: journalDirectory, webRunId: request.id } : undefined); const send: typeof write = (message, frame) => write(message, request.observationSourceRefs === true ? frame : undefined); + const retiredInput = retiredWebRunInputError(request.input); + if (retiredInput) { + send({ type: 'error', message: retiredInput, + failure: { kind: 'protocol', reason: retiredResearchCoordinationCode } }); + process.exitCode = 1; + return; + } const workspaceRoot = process.env.THEOREMOS_WORKER_ROOT || '/work'; const directory = fs.mkdtempSync(path.join(workspaceRoot, 'run-')); let output = path.join(directory, 'result.json'); @@ -326,6 +333,7 @@ async function main(watchdog: ReturnType }; console.error = () => {}; try { + const researchArguments = webResearchArguments(request.input, request.provider); const environment = getLeanTaskEnvironment(request.input.environment ?? 'standard'); configureWebProofSearchEnvironment(environment.id); const receipt = prepareWebProblem(directory, request); @@ -372,17 +380,17 @@ async function main(watchdog: ReturnType '--receipt-file', round.seed.activeProblemPath, '--build-manifest', buildIndex.buildManifestRef, '--model', webHarnessModel(request.provider, request.input.model), '--effort', request.input.effort, '--workers', String(request.input.workers), '--no-explanations', '--coordination', request.input.coordination, '--max-turns', String(round.limits.maxTurns), - ...webResearchArguments(request.input, request.provider), + ...researchArguments, ...expertCardArguments, ...(request.input.nativeTeamCapacity ? ['--harness-profile', profile] : harness !== 'codex' || request.provider.execution?.executable ? ['--harness', harness, '--harness-profile', profile, '--harness-executable', webHarnessExecutable(request.provider)] : []), - ...(request.input.planApproval ? ['--plan-approval'] : []), + ...(round.planApproval ? ['--plan-approval'] : []), ...(knowledgeFile ? ['--knowledge-base', knowledgeFile] : []), ...(round.continuationFile ? ['--continuation-manifest', round.continuationFile] : []), ...(round.libraryCatalog ? ['--library-catalog', round.libraryCatalog.file, '--library-catalog-sha256', round.libraryCatalog.digest] : []), - // Cooperative role checkpoints preserve streaming requests and saved decisions; the shared run budget still applies. + // The remaining shared budget follows the run into the new library environment. '--max-run-seconds', String(round.limits.maxRunSeconds), - '--max-turn-seconds', request.input.coordination === 'cooperative' ? '0' : String(round.limits.maxRunSeconds), + '--max-turn-seconds', String(round.limits.maxRunSeconds), ...(round.limits.maxTotalTokens ? ['--max-total-tokens', String(round.limits.maxTotalTokens)] : []), '--prepare-timeout-seconds', String(round.limits.maxRunSeconds === 0 ? 0 : webPreparationSeconds[environment.id === 'mathlib' ? 'mathlib' : 'standard']), ...(round.limits.maxRunSeconds === 0 ? ['--proof-timeout-seconds', '0'] : []), diff --git a/apps/web/workerBridge.ts b/apps/web/workerBridge.ts index be55a9a8..f4c643b0 100644 --- a/apps/web/workerBridge.ts +++ b/apps/web/workerBridge.ts @@ -7,15 +7,15 @@ import { canonicalMathJson, mathDigest, readMathText, withMathRuntimeLease, writ import { assertMathCanonicalPath } from '../../src/math/paths'; import type { SolverRunState } from '../../src/solver/archive'; import { buildRunInspection, exportRunPlan, readRunInspection } from '../../src/solver/inspection'; -import { queuePlanApproval, queueRunEdit } from '../../src/solver/humanEdit'; +import { queuePlanApproval } from '../../src/solver/humanEdit'; import { planApprovalInputSchema } from '../../src/solver/planApproval'; -import { humanGuidanceInputSchema, queueHumanGuidance, readHumanGuidance, withdrawHumanGuidance } from '../../src/solver/humanGuidance'; +import { readHumanGuidance } from '../../src/solver/humanGuidance'; import { taskVersion, type TaskRecord } from '../../src/solver/tasks'; import { allowedKnowledgeFile, buildTheoremKnowledge, validateTheoremKnowledge, type TheoremKnowledgeBase } from '../../src/solver/theoremKnowledge'; import { importKnowledgeRuns } from '../../src/solver/theoremKnowledgeRuns'; import { proofReceiptsMatch, type ProofCheck } from '../../src/solver/modules/evidence'; -import type { WebCheckReceipt, WebCommand, WebCommandResult, WebLibraryRestart, WebObservation, WebTaskSource } from './collaboration'; -import type { WorkerMessage } from './shared'; +import type { WebCheckReceipt, WebCommandResult, WebLibraryRestart, WebObservation, WebTaskSource } from './collaboration'; +import { retiredResearchCoordinationCode, type WorkerMessage } from './shared'; import { projectWebDeclarationArtifacts } from './declarationArtifacts'; import { projectWebNativeTeam } from './nativeTeamObservation'; import { maxWorkerObservationBytes, standaloneObservationFrame, type WorkerObservationFrame } from './observationSources'; @@ -31,7 +31,8 @@ type ActiveRun = { webRunId: string; directory: string; output: string; libraryR const metaSchema = z.object({ schema: z.literal('theorem-os.web-bridge.v1'), webRunId: z.string(), solverRunId: z.string(), libraryRound: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(), sequence: z.number().int().nonnegative(), contentDigest: z.string(), - observations: z.array(z.object({ sequence: z.number().int().nonnegative(), stateDigest: z.string() })), + // Older worker metadata may include the observation references once used by guidance writes. + observations: z.unknown().optional(), catalogKey: z.string().optional(), catalogDigest: z.string().optional(), }).strict(); type BridgeMeta = z.infer; @@ -277,8 +278,7 @@ export function createWebWorkerBridge(options: { if (Buffer.byteLength(frameJson) > maxWorkerObservationBytes) throw new Error('web_observation_too_large'); const meta: BridgeMeta = { schema: 'theorem-os.web-bridge.v1', webRunId: options.webRunId, solverRunId: state.runId, libraryRound: options.libraryRestart?.round ?? previous?.libraryRound ?? 0, - sequence, contentDigest, observations: [...(restarted ? [] : previous?.observations ?? []), - ...(changed ? [{ sequence, stateDigest: inspection.snapshot.stateDigest }] : [])].slice(-64), + sequence, contentDigest, ...(previous?.catalogKey ? { catalogKey: previous.catalogKey } : {}), ...(previous?.catalogDigest ? { catalogDigest: previous.catalogDigest } : {}) }; let catalog: TheoremKnowledgeBase | undefined; @@ -327,79 +327,26 @@ export function createWebWorkerBridge(options: { } const commandSchema = z.discriminatedUnion('type', [ - z.object({ type: z.literal('edit-preview'), proposal: z.record(z.unknown()) }).strict(), - z.object({ type: z.literal('edit'), proposal: z.record(z.unknown()) }).strict(), - z.object({ type: z.literal('guidance'), guidance: humanGuidanceInputSchema }).strict(), - z.object({ type: z.literal('guidance-withdraw'), id: z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/u), - guidanceId: z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/u) }).strict(), z.object({ type: z.literal('plan-approval'), approval: planApprovalInputSchema }).strict(), z.object({ type: z.literal('capture') }).strict(), ]); export async function handleWebWorkerCommand(value: unknown, options: { activeRunFile?: string } = {}): Promise { - const command = commandSchema.parse(value) as WebCommand; + if (value && typeof value === 'object' && 'type' in value && + ['edit-preview', 'edit', 'guidance', 'guidance-withdraw'].includes(String(value.type))) + throw new Error(retiredResearchCoordinationCode); + const command = commandSchema.parse(value); const active = readActiveRun(options.activeRunFile ?? webActiveRunFile); - const bridge = createWebWorkerBridge({ ...active, libraryRestart: command.type === 'capture' ? active.libraryRestart : undefined }); if (command.type === 'capture') return { id: 'capture', status: 'captured', - ...await bridge.capture({ includeCatalog: true, force: true, waitMs: 5_000 }) }; - if (command.type === 'guidance') { - const { state, stateFile } = readRunInspection(active.output); - try { - const previous = bridgeMeta(path.join(active.directory, 'web-bridge.json'), active.webRunId, state.runId); - const alreadyQueued = readHumanGuidance(stateFile, state.runId).some(record => record.id === command.guidance.id); - if (!alreadyQueued && !previous?.observations.some(item => item.sequence === command.guidance.observationRef.sequence && - item.stateDigest === command.guidance.observationRef.stateDigest)) throw new Error('web_guidance_observation_unknown'); - const guidance = await queueHumanGuidance(active.output, command.guidance); - return { id: guidance.id, status: guidance.status, guidance }; - } catch (error) { - // These validations finish before the queue write. Transport and persistence failures remain uncertain. - const reason = error instanceof Error ? error.message : ''; - if (['web_guidance_observation_unknown', 'math_guidance_invalid', 'math_guidance_id_conflict', - 'math_guidance_run_inactive', 'math_guidance_task_superseded', 'math_guidance_worker_missing', - 'math_guidance_lead_missing', 'math_guidance_limit', 'math_guidance_candidate_environment_changed', - 'math_guidance_candidate_file_mismatch', 'math_guidance_candidate_base_mismatch'].includes(reason)) - return { id: command.guidance.id, status: 'rejected', reason }; - throw error; - } - } - if (command.type === 'guidance-withdraw') { - try { - const guidance = await withdrawHumanGuidance(active.output, command.guidanceId); - // A fresh observation carries the settled note so readers see it at once; the withdrawal itself is already durable. - const observation = await bridge.capture({ force: true }).then(result => result.observation, () => undefined); - return { id: command.id, status: 'withdrawn', guidance, ...(observation ? { observation } : {}) }; - } catch (error) { - // Decided under the delivery lock before anything is written. - const reason = error instanceof Error ? error.message : ''; - if (['math_guidance_invalid', 'math_guidance_unknown', 'math_guidance_already_delivered', 'math_guidance_already_failed'].includes(reason)) { - // A note delivered first should read as delivered now, not after the next periodic capture. - const observation = await bridge.capture({ force: true }).then(result => result.observation, () => undefined); - return { id: command.id, status: 'rejected', reason, ...(observation ? { observation } : {}) }; - } - throw error; - } - } - if (command.type === 'plan-approval') { - try { return { ...await queuePlanApproval(active.output, command.approval) }; } - catch (error) { - // Each of these is decided from the saved checkpoint before anything is written. - const reason = error instanceof Error ? error.message : ''; - if (['math_plan_approval_invalid', 'math_plan_approval_id_conflict', 'math_plan_approval_not_required', - 'math_plan_approval_run_inactive', 'math_plan_approval_already_approved', 'math_plan_approval_plan_unavailable', - 'math_plan_approval_version_conflict', 'math_plan_approval_limit'].includes(reason)) - return { id: command.approval.id, status: 'rejected', reason, planVersion: command.approval.planVersion }; - throw error; - } - } - try { - const commandDigest = mathDigest(canonicalMathJson(command.proposal)); - const result = await queueRunEdit(active.output, command.proposal, command.type === 'edit-preview'); - return { ...result, commandDigest }; - } catch (error) { - // Plan errors are decided before appending. Lease and persistence failures still propagate. + ...await createWebWorkerBridge(active).capture({ includeCatalog: true, force: true, waitMs: 5_000 }) }; + try { return { ...await queuePlanApproval(active.output, command.approval) }; } + catch (error) { + // Each of these is decided from the saved checkpoint before anything is written. const reason = error instanceof Error ? error.message : ''; - if (/^math_plan_[a-z_]+(?::|$)/u.test(reason)) - return { id: command.proposal.id, status: 'rejected', reason, baseVersion: command.proposal.baseVersion }; + if (['math_plan_approval_invalid', 'math_plan_approval_id_conflict', 'math_plan_approval_not_required', + 'math_plan_approval_run_inactive', 'math_plan_approval_already_approved', 'math_plan_approval_plan_unavailable', + 'math_plan_approval_version_conflict', 'math_plan_approval_limit'].includes(reason)) + return { id: command.approval.id, status: 'rejected', reason, planVersion: command.approval.planVersion }; throw error; } } diff --git a/bin/math.ts b/bin/math.ts index 079bdf39..9b07d039 100644 --- a/bin/math.ts +++ b/bin/math.ts @@ -22,11 +22,8 @@ const commands: Readonly> = { knowledge: 'scripts/mathematics/theoremKnowledge.ts', hub: 'scripts/mathematics/huggingMath.ts', 'check-lean': 'scripts/mathematics/checkLean.ts', - 'proof-search': 'scripts/mathematics/proofSearch.ts', - 'research-observe': 'scripts/mathematics/researchObserve.ts', checkpoint: 'scripts/mathematics/checkpoint.ts', 'plan-validate': 'scripts/mathematics/planValidate.ts', - 'plan-apply': 'scripts/mathematics/planApply.ts', 'check-finite': 'scripts/mathematics/checkFinite.ts', 'kernel-certificate': 'scripts/mathematics/kernelCertificate.ts', 'library-pack': 'scripts/mathematics/libraryPack.ts', @@ -38,7 +35,6 @@ const commands: Readonly> = { inspect: 'scripts/mathematics/inspectMathRun.ts', recover: 'scripts/mathematics/recoverMathSnapshot.ts', edit: 'scripts/mathematics/editMathRun.ts', - 'import-proof': 'scripts/mathematics/importProofFragment.ts', compare: 'scripts/mathematics/compareMathRuns.ts', 'sample-putnam': 'scripts/mathematics/samplePutnamRuns.ts', 'first-proof': 'scripts/mathematics/firstProof.ts', @@ -66,11 +62,8 @@ if (!command || ['help', '--help', '-h'].includes(command)) { knowledge Build and query previously checked theorem sources hub Export frozen results and import private HuggingMath drafts check-lean Check changed Lean files with bounded diagnostics - proof-search Explore bounded tactic branches and retain resumable proof states - research-observe Validate and publish one research finding with retained Lean probes checkpoint Save the acknowledgment requested by the active host plan-validate Check a cooperative Lead plan and report field-level issues - plan-apply Validate and save or publish a cooperative Lead plan check-finite Replay finite Boolean constraints and return witnesses kernel-certificate Generate chunked decide +kernel certificate modules library-pack Extract checked run modules or backport upstream files as a frozen library @@ -81,10 +74,9 @@ if (!command || ['help', '--help', '-h'].includes(command)) { continuation-seed Initialize a new prepared run from advisory sources and fresh helper checks inspect Read a research report or export a versioned task plan recover Restore a research snapshot and recheck saved helpers - edit Validate and queue a human plan edit - import-proof Queue a Lean fragment for host-checked task delivery - compare Compare fixed-budget coordination arms or module plans - sample-putnam Prepare and report reproducible PutnamBench samples + edit Approve the exact version of a native team's initial route + compare Read and check saved comparison reports + sample-putnam Read and check saved PutnamBench sample reports first-proof Audit and prepare the First Proof Batch 3 Lean adaptation offline formalize Formalize an informal problem and review its Lean statement informalize Explain a checked Lean proof in natural language, step by step with audits diff --git a/docs/agensh-adoption-plan.md b/docs/agensh-adoption-plan.md index b2106a67..b7cdbfb2 100644 --- a/docs/agensh-adoption-plan.md +++ b/docs/agensh-adoption-plan.md @@ -38,7 +38,7 @@ Agensh 的大规模结果主要支持固定墙钟下增加并行投入的可行 完成条件:能从原始记录解释至少一个“有任务却未派发”的场景及一个成果交接场景;缺失记录可见;任务数量、消息数量和 worker 忙碌程度不被计为数学进展。 -主要入口:[inspection.ts](../src/solver/inspection.ts)、[archive.ts](../src/solver/archive.ts)、[cooperationCore.ts](../src/solver/cooperationCore.ts)、[cooperationIntegration.ts](../src/solver/cooperationIntegration.ts)。 +主要入口:[inspection.ts](../src/solver/inspection.ts)、[archive.ts](../src/solver/archive.ts)、[cooperationCore.ts](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/src/solver/cooperationCore.ts)、[cooperationIntegration.ts](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/src/solver/cooperationIntegration.ts)。 **阶段二:让现有工作更容易被领取和消费** @@ -56,7 +56,7 @@ Agensh 的大规模结果主要支持固定墙钟下增加并行投入的可行 交付:每项实际变更、对应回归和使用说明,以及阶段一口径下的等待变化。离线回归只能证明流程行为,解题收益留待阶段四判断。 -主要入口:[organization.ts](../src/solver/modules/organization.ts)、[context.ts](../src/solver/modules/context.ts)、[cooperationInputs.ts](../src/solver/cooperationInputs.ts)、[handoffPublication.ts](../src/solver/handoffPublication.ts)、[taskConnections.ts](../src/solver/taskConnections.ts)。 +主要入口:[organization.ts](../src/solver/modules/organization.ts)、[context.ts](../src/solver/modules/context.ts)、[cooperationInputs.ts](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/src/solver/cooperationInputs.ts)、[handoffPublication.ts](../src/solver/handoffPublication.ts)、[taskConnections.ts](../src/solver/taskConnections.ts)。 **阶段三:评估 Lead 故障后的有限收尾** @@ -73,7 +73,7 @@ Agensh 的大规模结果主要支持固定墙钟下增加并行投入的可行 交付:明确的暂停/收尾/恢复语义及端到端故障回归。若无法在现有生命周期内保持这些约束,保留当前中止行为并记录原因,不先扩大容错范围。 -主要入口:[research.ts](../src/solver/research.ts)、[cooperation.ts](../src/solver/cooperation.ts)、[workerProofLifecycle.ts](../src/solver/workerProofLifecycle.ts)、[evaluation.ts](../src/solver/evaluation.ts)。 +主要入口:[research.ts](../src/solver/research.ts)、[cooperation.ts](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/src/solver/cooperation.ts)、[workerProofLifecycle.ts](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/src/solver/workerProofLifecycle.ts)、[evaluation.ts](../src/solver/evaluation.ts)。 **阶段四:用对照决定是否扩大投入** diff --git a/docs/agensh-module-design.md b/docs/agensh-module-design.md index 0f7dea40..b54cd5dc 100644 --- a/docs/agensh-module-design.md +++ b/docs/agensh-module-design.md @@ -14,7 +14,7 @@ M3.ready(完整任务图) → host 过滤准备/同步状态 → M5.assign(完 → await 后复检 → 创建或延续 assignment → 模型请求前准入 ``` -同一组职责知识散在 [M5 资格筛选](../src/solver/modules/organization.ts)、[nextPeer 与预检复检](../src/solver/cooperation.ts)。它适合深化;Git、Lean 和模型会话仍留在现有执行路径。 +同一组职责知识散在 [M5 资格筛选](../src/solver/modules/organization.ts)、[nextPeer 与预检复检](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/src/solver/cooperation.ts)。它适合深化;Git、Lean 和模型会话仍留在现有执行路径。 以下判断保持各自含义:M3 ready 表示现在数学上可尝试;M5 matches 表示 worker 职责匹配;host admission 表示此刻允许实际执行;M2/S3 才决定证明接受。`hasAssignableTask` 判断现在可派发,`researchCanAdvance` 遍历未来依赖是否仍可推进,不能互换。 diff --git a/docs/agensh-offline-baseline.md b/docs/agensh-offline-baseline.md index ff9e4e65..ef19cbb1 100644 --- a/docs/agensh-offline-baseline.md +++ b/docs/agensh-offline-baseline.md @@ -48,7 +48,7 @@ **模拟与后续验证口径** -[solverDispatchWait.test.ts](../tests/solverDispatchWait.test.ts) 使用可丢弃 fixture 验证等待观察合同,属于模拟证据。忙碌 owner 场景记录 owner 原因,完整计划显式改为共享后空闲 peer 可以领取;保存过的 assignment 仍然独占。用例还覆盖自定义策略拒选、越权建议、预检竞争、预算门控、停止结束及私有范围投影。它们不能补写旧运行的等待原因,也不能证明实际等待减少或解题提速。 +[solverDispatchWait.test.ts](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/tests/solverDispatchWait.test.ts) 使用可丢弃 fixture 验证等待观察合同,属于模拟证据。忙碌 owner 场景记录 owner 原因,完整计划显式改为共享后空闲 peer 可以领取;保存过的 assignment 仍然独占。用例还覆盖自定义策略拒选、越权建议、预检竞争、预算门控、停止结束及私有范围投影。它们不能补写旧运行的等待原因,也不能证明实际等待减少或解题提速。 新观察保存在 worker.scheduling.wait,经现有 inspect 展示,并产生去重的 dispatch_wait / dispatch_wait_ended 事件。observedAt 是观察时间,endedAt 是结束时间;两者都不证明该原因在首次观察前已持续多久。旧记录显示 unknown,已记录计划或任务身份失效显示 stale;每次最多列出 16 个候选,其余及 scope 隐藏项计入 omittedCandidates。 @@ -76,7 +76,7 @@ 2026-10-24 按用户要求修复上述失败。三个 frontier 用例的超限来自固定证明角色说明增长;[context.ts](../src/solver/modules/context.ts) 压缩与基础指示重复的文字,保留精确任务类型、数学推理、原声明保护、原始 def 只填写 body、条件前提约束及独立检查要求。20 KiB 上限和必需数学接口保持原有断言,M4 追加版本 `compact-proof-role-context-v1`。 -另两项修正过时夹具:[solverContinuationCapacity.test.ts](../tests/solverContinuationCapacity.test.ts) 先确认续跑保留精确研究 advisory,再显式清空 live deliveries,继续验证完整笔记从不可变附件恢复;[solver.test.ts](../tests/solver.test.ts) 先确认仅修改已采纳目标的 revision 仍保留采纳,再改变真实前置引理合同,验证相同 handoff id 在新 context 下重新待决,以及失败请求恢复和重复交付幂等性。研究交付保留和 handoff 生产逻辑均未为迁就断言而改变。 +另两项修正过时夹具:[solverContinuationCapacity.test.ts](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/tests/solverContinuationCapacity.test.ts) 先确认续跑保留精确研究 advisory,再显式清空 live deliveries,继续验证完整笔记从不可变附件恢复;[solver.test.ts](../tests/solver.test.ts) 先确认仅修改已采纳目标的 revision 仍保留采纳,再改变真实前置引理合同,验证相同 handoff id 在新 context 下重新待决,以及失败请求恢复和重复交付幂等性。研究交付保留和 handoff 生产逻辑均未为迁就断言而改变。 修复后的聚焦验证通过:上下文 111 项,continuation 98 项,handoff 154 项,solver 局部 handoff 6 项,原始 definition 目标的独立验收 2 项。各组存在交集,不能相加作为独立用例总数。`bun run typecheck` 和 `bun run build` 通过。最终构建 ID 为 `aebc62ea-7886-4be9-a723-da551878424c`,[冻结 manifest](/home/lzh/.deepscientist-math-standalone-state/builds/aebc62ea-7886-4be9-a723-da551878424c/manifest.json) 的 SHA256 为 `13bb0218ccca14f439996463906c4847a9b8469c7d798c02da80bed96d521236`。与首次构建一样,它包含工作树中其他修改,不构成真实模型效果比较。 diff --git a/docs/codex-skill-runtime.md b/docs/codex-skill-runtime.md index 093df928..109674b6 100644 --- a/docs/codex-skill-runtime.md +++ b/docs/codex-skill-runtime.md @@ -1,6 +1,6 @@ # Skill research mode -This branch separates pinned Skill research methods from execution and coordination. A native agent harness executes research and tools; a project skill supplies methods. The host keeps the frozen problem, source policy, resource accounting, writer shutdown, independent Lean acceptance and persistent artifacts. Skill methods work in single, independent and cooperative runs through Codex, Claude Code, OpenCode or a configured headless CLI; see [harness configuration and verified limits](harness-portability.md). +This branch separates pinned Skill research methods from execution and coordination. A native agent harness executes research and tools; a project skill supplies methods. The host keeps the frozen problem, source policy, resource accounting, writer shutdown, independent Lean acceptance and persistent artifacts. New collaborative runs use the Codex native team. Codex, Claude Code, OpenCode and a configured headless CLI also support single-researcher workloads; see [harness configuration and verified limits](harness-portability.md). ## Start and resume @@ -12,9 +12,9 @@ bun bin/math.ts run --research-mode skill \ --output NEW_RESULT_FILE --build-manifest BUILD_MANIFEST ``` -New `--research-mode skill` runs default to one independent researcher. Explicit `--workers` above 1 defaults to cooperative coordination; explicit `--coordination cooperative` defaults to 4 workers. Independent attempts remain selectable. Schedulers, module plans and plan approval retain their existing contracts. Cooperative Skill runs keep the complete task graph, ownership, typed delivery, fixed Reviewer and integration loop. All existing budget options apply; their unlimited defaults are preserved. New Skill runs use the existing library application and task automation where applicable, checked through the original acceptance path. +New Codex runs default to a native team with capacity for four members including Lead. Set `--agent-team N` for a different capacity or `--workers 1` for a solo researcher. Teams work autonomously unless the owner enables `--plan-approval`. Then Lead publishes the initial route and waits for approval of the displayed version before starting proof work. Existing budget options keep their defaults. New Skill runs use the existing library application and task automation where applicable, checked through the original acceptance path. -The normal `--resume` command inherits the saved research mode, skill loading, workers and coordination. It continues the saved native thread when the frozen contract permits. Mode, skill content, loading mode, provider, environment and other frozen identities cannot be changed in place. New runs save `researchSkillWorkflow: full` and an execution plan. Historical Skill checkpoints without that marker keep their original single-only workflow; resume does not silently upgrade their strategy. A different strategy starts a new run and thread from saved artifacts. +The `--resume` command continues solo runs and native teams with their saved research mode, Skill loading, provider and environment. The host checks the frozen identities before resuming the thread. New runs save `researchSkillWorkflow: full` and an execution plan. Historical single-researcher checkpoints without that marker keep their original workflow. Inspect older host-scheduled archives with the current CLI and use the original pinned runtime to resume them. A new strategy can start a separate run from the saved artifacts. For Codex sessions metered by upstream request receipts, the host sends `excludeTurns: true` on resume. Codex restores the thread internally and returns metadata without sending the full transcript over stdio. Direct providers whose budget gate uses native thread totals still request turn history so Codex can replay saved usage. @@ -30,17 +30,17 @@ File handoffs use native `fs/watch` on the existing parent directory before the New Codex report workflows prefer native `outputSchema` and the final response bound to the completed turn. The host closes the session, validates the response and saves the frozen output file. `outputDelivery` freezes this choice; older requests without the field retain their file protocol and instruction hashes. Replay, other harnesses, the DeepSeek/Westlake Chat bridge and early proof handoffs retain file delivery. The audit reads the session's final-response record instead of collecting a second copy of agent messages. -The legacy non-Skill research path uses native `thread/compact/start` between settled turns before rotating a thread for context capacity. The adapter waits for the `contextCompaction` item and the successful terminal event for that turn before it resumes research. Its maintenance requests are accounted for separately from proof turns; failed compaction retains the existing fresh-thread recovery. Skill research keeps Codex's own automatic compaction behavior. Ordinary peer-status notices in the legacy cooperative path also use advisory native history; assignment changes and other effective instructions keep their steering contract. +The non-Skill solo path uses native `thread/compact/start` between settled turns before rotating a thread for context capacity. The adapter waits for the `contextCompaction` item and the successful terminal event before it resumes research. Its maintenance requests are accounted for separately from proof turns. Failed compaction retains the existing fresh-thread recovery. Skill research keeps Codex's own automatic compaction behavior. -Teams using host tools use `thread/inject_items` for ordinary advisory updates and `turn/steer` for effective amendments with the existing paid-request settlement fence. Native teams deliver through Codex's mailbox and attributed input. Queue-only delivery never starts an idle turn; acceptance transfers queue ownership and is not a read receipt. An amendment uses exact-turn steering so a late notification cannot start another writer. Uncertain delivery after worker loss stays explicitly uncertain. +Native teams deliver through Codex's mailbox and attributed input. Queue-only delivery leaves an idle turn waiting. Codex accepting a message confirms queue ownership. The receiver's read status is tracked separately. Anchoring an active update to its turn prevents a late notification from starting another writer. Delivery can remain uncertain after worker loss. Native team runs use the separately built [Codex AgentControl backend](../scripts/codex-backend/README.md). Official `spawn_agent`, `send_message`, `followup_task`, `list_agents`, `wait_agent` and `interrupt_agent` handlers stay installed. The adapter connects them over stdio to TheoremOS's isolated writer lifecycle. The host prepares a separate process and worktree before the first child model request; trusted bootstrap preserves native tree identity, captured instructions, parent lineage and native fork history. Workspace relocation revokes the parent's writable worktree and permits the destination isolated workspace while retaining other restrictions. Per-worker provider settings stay local to the worker process. Codex's generic root/subagent role messages are deliberately suppressed: their defaults assume a shared working directory and allow recursive child teams. TheoremOS supplies the actual flat-team identities, isolated workspace permissions and native usage guidance through the pinned context instead. This does not remove native tool descriptions. Deferred mailbox preemption preserves delivery at the next model boundary after the current response and tools settle; it does not require a host coordination acknowledgment. -Native team sessions also set Codex's existing `features.multi_agent_v2.multi_agent_mode_hint_text`. Lead receives explicit authorization to proactively delegate useful complementary work; members receive a flat-team policy that permits messages and forbids further dispatch or peer interruption. This replaces the default explicit-request-only mode message emitted at `high` effort, which otherwise follows the host's team authorization. The override is recorded with the runtime configuration and reapplied on new and resumed writer sessions. Single-agent and host-tool sessions keep their existing native mode settings. This adds no dispatch gate, required team size or model-choice override. +Native team sessions set Codex's `features.multi_agent_v2.multi_agent_mode_hint_text`. Lead receives authorization to delegate useful complementary work. Members can exchange messages. Lead alone can dispatch or interrupt members. The override is recorded with the runtime configuration and reapplied on new and resumed writer sessions. -Build the pinned backend to start a native team. It defaults to `out/codex-backend/codex`. Set `THEOREMOS_CODEX_BACKEND_EXECUTABLE` to select another build. The run pins the executable's real path and digest. New teams using the direct Westlake Chat profile start with host tools. Other new teams start with native collaboration and can switch to `theoremos_team` host tools on eligible app-server startup failures before the Lead starts research. Resume uses the recorded transport. Checkpoints that predate the transport field use host tools. Building does not switch or restart running solves, and no global Codex profile or binary is replaced. The host confirms writer shutdown before freezing sources, checking them in Lean and making them available for Lead adoption. See the [backend startup and fallback rules](../scripts/codex-backend/README.md). +Build the pinned backend to start a native team. It defaults to `out/codex-backend/codex`. Set `THEOREMOS_CODEX_BACKEND_EXECUTABLE` to select another build. The run pins the executable's real path and digest. Native teams require a compatible profile such as the Responses gateway. The host confirms writer shutdown before freezing sources, checking them in Lean and making them available for Lead adoption. See the [backend startup rules](../scripts/codex-backend/README.md). The backend's real-binary [loopback fixture](../scripts/test-codex-backend.ts) covers isolated native spawn, attributed messages, idle queues, cold resume with first-request FIFO mail, full-history fork, loaded-agent listing, mailbox wakeup, changes to a running member's expertise and idle/active interruption. It verifies writer shutdown, checked delivery, adoption and final proof references. Provider responses are fixed local data. Installing the CLI backend does not upgrade an existing Web worker image. @@ -48,16 +48,15 @@ Real installed-Codex tests with local fixed Responses replies cover native shell ## Agent-organized proof-writing team -For a new Codex run, select the persistent team explicitly: +To set the capacity of a new Codex team, pass `--agent-team`: ```sh -bun bin/math.ts run --research-mode skill \ - --skill-delegation team --skill-max-agents 3 \ +bun bin/math.ts run --agent-team 3 \ --workspace NEW_PROBLEM_WORKSPACE --task-file TASK_FILE \ --output NEW_RESULT_FILE --build-manifest BUILD_MANIFEST ``` -`--skill-max-agents` counts persistent members, including Lead, and accepts 2–8 (CLI default 4): at most one Lead and seven members. An idle or interrupted member retains its place; Lead can use `followup_task` to assign that member a new gap and expertise. Team mode uses one host Lead: `--workers 1 --coordination independent`. These are the Skill defaults; host cooperative coordination, module plans and plan approval cannot be combined with this mode. Native team execution requires the pinned Codex backend. Other harnesses retain their supported host-managed workflows. +`--agent-team` sets capacity from 2 to 8, including Lead, and defaults to 4. An idle or interrupted member retains its place. Lead can use `followup_task` to give that member a new assignment. Use `--plan-approval` to review the initial route before proof work. Native teams require the pinned Codex backend. Other harnesses can start solo runs. Before starting a team, optionally select preferred roles in the Web form or pass a comma-separated list, e.g. `--skill-preferred-profiles researcher,engineer,D011`. Work roles and domain specialties come from the [pinned Skill catalogue](../skills/theoremos-research/references/team-roles.md); a domain ID or its slug is accepted. A preference tells the Lead what expertise you would like considered. It does not reserve seats, start members, restrict other roles, or mark any expertise as used. The run saves these preferences for resume. Leave the list empty for ordinary autonomous selection. @@ -65,19 +64,19 @@ You can also select a released personal Skill or Agent as a source of expertise. For CLI runs, `--skill-expert-cards-file FILE` takes a JSON array with string fields `assetId`, `version`, `digest` (the release's SHA-256), `name`, `summary` and `knowledge`. Lead sees the available names and summaries; a dispatch such as `Profiles: researcher, asset:topology` supplies the selected knowledge to that assignment. The run retains its frozen cards on resume. A card supplies background; it cannot grant tools or certify a claim. -Lead chooses the mathematical decomposition, delegates proof work, changes routes and selects results for adoption. The default Skill guidance uses a flat team working on complementary gaps in the shared proof effort, with alternative-route investigations when useful. Members can discuss findings and interfaces directly; Lead retains dispatch and adoption authority. Each child has an isolated writable worktree, the same pinned Skill and a native thread that persists across assignments. Native collaboration tools carry delegation, instructions and communication. The host provides `theoremos_team` only for mathematical evidence, source handoffs and checked-result adoption. This path is separate from the existing host-cooperative task graph, fixed roles and worker scheduling. +Lead chooses the mathematical decomposition, delegates proof work, changes routes and selects results for adoption. The default Skill guidance uses a flat team working on complementary gaps in the shared proof effort, with alternative-route investigations when useful. Members can discuss findings and interfaces directly. Each child has an isolated writable worktree, the same pinned Skill and a native thread that persists across assignments. Codex tools handle delegation, instructions and communication. The host's `theoremos_team` handles mathematical evidence, source handoffs and checked-result adoption. -The Skill guides Lead to look for complementary work early; a useful research question can be assigned before a complete proof route or exact helper type is known. Lead uses normal collaboration and research tools at its discretion. There is no outer coordination protocol, tool restriction or coordination-only turn interruption in either transport. Native `send_message` carries findings, route changes and status; native `followup_task` supplies further instructions and `interrupt_agent` stops a member's turn. Lead chooses tasks, methods, when to reassess and team size within capacity, without forced delegation or a required reporting ritual. +The Skill guides Lead to look for complementary work early. A useful research question can be assigned before a complete proof route or exact helper type is known. Lead chooses tasks, methods, when to reassess and team size within capacity. `send_message` carries findings, route changes and status. `followup_task` supplies further instructions, and `interrupt_agent` stops a member's turn. Lead and member contexts report remaining run milliseconds, the stage checkpoint and the hard turn limit; continuation recompiles the remaining-time observation. A finite `--max-turn-seconds` remains a hard ceiling. Team turns start handing back control at 80% of that limit: new paid requests stop at the next admission boundary, after the in-flight response and its native tools have finished. For a 300-second turn, the stage checkpoint is at 240 seconds, leaving up to 60 seconds for settlement. A normal native completion is retained; a checkpoint preserves the saved thread and sources. The hard turn deadline, overall deadline and explicit cancellation can still interrupt an unfinished request. Missing usage remains unknown and blocks finite-budget continuation. With no turn limit, no timed stage checkpoint is added. Team identity is stable: Lead owns the original problem and may also write proofs; each child is a mathematical researcher and Lean proof writer. The pinned Skill's [specialist profiles](../skills/theoremos-research/references/domain-experts.md) supply specialized knowledge: concepts and structures, relevant theories with their conditions, important distinctions and connections to neighboring subjects. Each member chooses its reasoning and proof approach for the assigned question. The catalog contains 100 domain profiles and 24 work or supporting-expertise profiles; these can be combined and are separate from the runtime's agent capacity. Lead provides the question and members read the relevant knowledge sections. The [work profiles](../skills/theoremos-research/references/team-roles.md), including Researcher, Lean Prover, Lean Engineer and Reviewer, describe responsibilities that can accompany a specialization. Lead selects, combines or changes expertise and responsibilities in native spawn and followup messages; no separate `role` or `domain` parameter or host authority is added. Independent review requires a non-producing member and fixed evidence; a role change alone does not make the producing thread independent. This is a Skill collaboration requirement, not an additional host review gate. The host refreshes developer identity and source permissions, while the pinned Skill supplies domain knowledge and collaboration guidance. Each child dispatch starts with a bounded current-assignment section containing its task ID, objective, source and delivery baselines, own prior feedback, peer work and addressed inbox. The inbox cursor advances only after turn-start acknowledgment. See the [source research and prompt design](../research/agent-team-prompts.md). -Start a specialized native `spawn_agent` or `followup_task` message with `Profiles:` followed by comma-separated domain and work-profile IDs or slugs selected for the actual gap. A work profile alone is valid; no domain is selected by default. The child receives the selected profile text and the locations of local reading notes; it can read those notes on demand. When Lead changes the expertise of a running member, the same attributed followup delivers the new profile context to the current turn. The host records the change after the native backend accepts the input; acceptance does not establish that the model used the material. The record includes the pinned Skill digest, requested and loaded IDs, and unresolved names. Teams using host tools use the same opening line in `spawn.message` or `assign.message`. Source permissions, agent capacity and proof acceptance do not change. +Start a specialized `spawn_agent` or `followup_task` message with `Profiles:` followed by comma-separated domain and work-profile IDs or slugs selected for the gap. A work profile alone is valid. The child receives the selected profile text and the locations of local reading notes. When Lead changes the expertise of a running member, the same attributed followup delivers the new profile context to the current turn. The host records the pinned Skill digest, the requested and loaded IDs, and any unresolved names after the native backend accepts the input. The record establishes which material was supplied. The Lead charter assigns concrete gaps with a consumer and first usable result, with one owner per active obligation including Lead. While a member owns a gap, Lead advances its consumer or other work; different methods for proving the same target still overlap. Whole-target delegation has one owner while others provide targeted support, integration or review. Alternative routes start with the smallest finding that resolves a specific uncertainty. Members receive the original problem as background to their current assignment and send useful intermediate findings before the complete proof. These are Skill and native role instructions, without a host scheduler or delegation gate. -Native followup retains the member's workspace, thread and draft while the adapter records the latest accepted task instructions and retains earlier instructions in history. It preserves the current profile selection when the message has no new `Profiles:` header, and switches knowledge when an explicit header is supplied. Native submit omits `objectiveRevision`; the host binds the member's current task. Profile records retain exact loaded passage identities; a member can explain a passage's application in its messages or saved research notes. Supplied context, reported knowledge use and checked proof evidence remain distinct. Host tools provide `amend` and optional structured `progress` records, including their objective revisions, work kinds and source-anchor reports. +Native followup retains the member's workspace, thread and draft while the adapter records the latest accepted task instructions and retains earlier instructions in history. A new `Profiles:` header changes the selection. The host binds a `submit` call to the member's current task. Profile records retain exact loaded passage identities. A member can explain a passage's application in its messages or saved research notes. Members use independent Git object stores; each writer's namespace hides the peer-workspace parent and rebinds only its own workspace. Checked fixed commits and evidence are archived outside writer visibility and imported by exact version for explicit adoption. `inspect` records exposure to a peer delivery, and completed adoption records reuse. These records persist across tasks and accompany later deliveries with the source producer, task and commit. They record explicit source transfers, not complete reasoning independence or independent authorship of reused declarations. @@ -87,46 +86,30 @@ Each domain profile also links [collected domain materials](../skills/theoremos- Collaboration follows useful milestones. Lead keeps the shared route and gap ownership visible through native messages when needed, and assesses findings, probes, blockers and route changes when they affect the next decision. A member messages usable findings and blockers promptly, submits independent helpers once they answer the assignment and returns for checking before expanding its scope. These instructions guide Agent choices without a timed polling loop, forced proof method, task quota or automatic adoption. Waiting is useful when progress depends on an outstanding member result; an empty loaded team alone is not a reason to wait. -The native transport leaves identity, dispatch, instructions, messaging, waiting and interruption to Codex collaboration tools. Both Lead and members can call `history`, `inspect`, `inspect-research` and `route_summary` through `theoremos_team`. Lead can also call `finish`, `adopt` and `retire_route`. Members can call `yield` and `submit`. Set `helpersOnly: true` on `submit` to share standalone helpers and keep the assignment open. Native `followup_task` resumes a yielded draft or assigns work to a completed member. `list_agents` lists loaded agents. The saved overview retains members and their task and evidence identities after their writer process stops. - -Host tools add Lead operations for `spawn`, `assign`, `amend`, `coordinate`, `resume`, `cancel`, `publish` and `stop`, plus `message`, `poll` and `wait` for both roles and `progress` for members. `budget` and its parameters are available to Lead with a finite token or turn allowance. The tool description lists the required and optional fields for each operation, and the host checks each call against its operation and role. The pinned [parallel-work reference](../skills/theoremos-research/references/parallel-work.md) documents both transports. Spawn and assign queue work and return a task ID. Poll and wait return individual arrivals and a durable cursor while other members continue. Wait is bounded to 30 seconds. Inspect retrieves checked declaration interfaces, source excerpts, commits and proof evidence so Lead can make an informed adoption decision. - -The host-tool operations `coordinate` and `publish` provide optional notes and summaries. Saved coordination decisions, observations and presentations remain readable historical records; they do not gate tools, create collaboration stages or schedule turn handoffs. - -The host tool `message(agentId, message, relatedTaskId?, researchRevision?)` durably saves its event before returning. Native notification is queued asynchronously, so a receiver waiting on its own tool call cannot block all team mutations. The reply distinguishes saved inbox delivery from notification availability; neither confirms reading. Child message events automatically carry the sender's current `sourceTaskId` and `dispatchResearchRevision`, the summary version injected at that sender's dispatch. An explicitly referenced `researchRevision` can be newer; the dispatch revision never asserts that later updates have been read. Native transport uses attributed Codex messages and queue-only mailbox updates instead; accepted mail does not establish that it was read. - -Lead/worker dispatch contexts and host-tool poll/wait share a bounded [overview projection](../src/solver/agentTeamViews.ts): selected members, each member's current/next/recent tasks, recent research/proof references and current integration status. Long objectives, summaries and errors have previews and truncation markers; omission counts and retrieval instructions identify what is not shown. `activity` distinguishes preparing, running, stopping, checking, integrating, paused and idle without claiming mathematical progress. `history(agentId?, offset?, limit?)` returns complete task text and any saved legacy summary, with source/evidence IDs; declaration arrays remain available through checked delivery inspection. The default page limit is 4, maximum 8, with a 256 KiB soft byte limit ending at whole-task boundaries and `nextOffset` pointing to the first unreturned task. A single large task is still returned. Global history uses host-assigned task sequences, stable as new tasks are appended; a task's `historyOffset` indexes its member's history. - -Context inboxes contain at most eight event previews. A truncated message and later previews are not acknowledged: `through` remains the last completely shown prefix, and `previewThrough` is explicitly not a receive cursor. The host tools `poll` and `wait` return at most eight complete events and can stop earlier at a byte limit; their cursor advances only past returned events. Native messages use Codex's attributed mailbox delivery. Long-lived task history, reference indexes and inbox previews remain bounded, with complete content retrievable. +Codex collaboration tools handle identity, dispatch, instructions, messaging, waiting and interruption. Lead and members can call `history`, `inspect`, `inspect-research` and `route_summary` through `theoremos_team`. Lead can also call `finish`, `adopt` and `retire_route`. When first-route approval is enabled, Lead calls `publish_plan` with a route covering every original goal, then waits for approval before writing proofs or dispatching members. Members can call `yield` and `submit`. Set `helpersOnly: true` on `submit` to share standalone helpers and keep the assignment open. `followup_task` resumes a yielded draft or assigns work to a completed member. `list_agents` lists loaded agents. The saved overview retains members and their task and evidence identities after their writer process stops. -Host tools provide `publish(summary)`, which updates `researchState` with a new revision and publication time and sends members a `research-updated` event. The saved summary is advisory and may describe routes, assumptions, findings and gaps; it is neither a host task graph nor checked mathematical evidence. Native teams use ordinary native messages for these updates and save reproducible notes in RESEARCH.md. +Lead and member contexts use a bounded [overview projection](../src/solver/agentTeamViews.ts) of current and recent assignments, research and proof references, and integration status. `activity` reports execution states such as preparing, running, checking and paused. `history(agentId?, offset?, limit?)` pages through complete task instructions and saved summaries with source and evidence IDs. `inspect` returns checked declaration interfaces, source excerpts, commits and proof evidence for adoption decisions. Share route changes through native messages and save reproducible findings in `RESEARCH.md`. After an executed child task's writer stops, its result records the stable `sourceCommit` and `researchArtifactId`. The artifact contains the task's summary and status, plus the root RESEARCH.md when present; missing notes return `notes:null`. The `researchArtifacts` index exposes artifact ID, producer, task and commit without host storage paths. Any member can use `inspect-research(artifactId, offset?, limit?)` to read paginated saved notes at that fixed commit, using Unicode code point offsets and `nextOffset`. This preserves inspectable counterexamples, literature mappings, calculations and failed routes even when no Lean declaration was submitted. An artifact remains advisory and separate from a checked proof delivery. Historical checkpoints can omit these new fields; the context then has no invented summary or artifact. -Host tools provide `cancel(agentId, taskId, reason?, replacement?)` for withdrawing a task or queuing a replacement, and `stop(agentId)` for retiring a member. A cancellation request and queued replacement do not assert writer shutdown. Native teams use `interrupt_agent` to stop a turn and `followup_task` for further instructions, preserving identity and saved work; a subsequent writer still waits for confirmed shutdown. +For a temporary dependency or Lead decision, a child saves its draft and notes, calls `yield(reason)` and returns. The host confirms writer shutdown before marking the task paused. Lead can adopt needed results and use `followup_task` to continue in the same worktree and thread, with the original delivery baseline and cumulative usage. A normal return completes the investigation, and a submitted proof enters checking. -For a temporary dependency or Lead decision, a child saves its draft and notes, calls `yield(reason)` and returns. The host confirms writer shutdown before making the task paused. Lead can adopt needed results and use native `followup_task`, or the host tool `resume(agentId, taskId)`, to continue the task, worktree and native thread. This preserves the original delivery baseline and cumulative task consumption. A normal return still completes the investigation; a submitted proof is checked through the submission path rather than yielding it. - -Runs have no token, turn or solving-time budget by default. Without a finite host token or turn allowance, Lead cannot invent local task caps or an integration reserve: the tool omits those capabilities and the host rejects budget requests before creating or queuing a task. Usage accounting continues independently of limits. Older saved task caps and reserves are preserved as history and are not enforced while the host has no finite token or turn allowance. Removing a global token limit on resume requires explicit `--max-total-tokens 0`, because omission retains the old run's value. - -Native team tools expose no task-budget or reserve controls. Host tools provide optional `budget:{tokens?,turns?}` on spawn/assign and `budget(leadReserve?, agentId?, taskId?, budget?)` only with an explicitly configured finite host allowance. These replace cumulative local allowances without resetting consumption or resuming paused work. Shared configured limits still govern the whole run. The overview reports observed usage and any saved finite allowances; historical turn limits remain unknown when no host limit was saved. Token caps govern subsequent request admission using observed receipts, so an admitted request may finish beyond a cap. A missing receipt is preserved as unavailable usage. +Any configured token, turn or solving-time allowance is shared by the run. The default is unlimited and usage is recorded independently of limits. Token caps govern subsequent requests based on observed receipts, so an admitted request may finish beyond the cap. Removing a saved token limit on resume requires `--max-total-tokens 0`. A child saves its sources, calls submit with exact declarations and returns. Submission and yield also checkpoint at the next unpaid request boundary, after the current paid response and tool group settle; submission enters checking, while yielding retains the task for resume. The host confirms writer shutdown, freezes those bytes and checks the delivery independently. Adopt defaults to Lead and queues integration. Lead saves sources and notes before requesting it; a pending Lead adoption triggers an automatic checkpoint before the next model request. Lead normally saves the complete proof and returns for independent checking. Lead can call `finish(summary)` after saving to request early handoff. Remaining holes or errors return normal feedback. The paid response and its tools finish and usage settles before confirmed writer shutdown; the host then freezes sources, rechecks and integrates the delivery and continues the saved thread. No token, time or turn allowance is added. Adoption into an idle child also queues and returns immediately; its safe work loop integrates before dispatching the next assignment, allowing native messages and interruption during slow checking. Lead can send the consumer instructions after requesting adoption and inspect the resulting status and feedback. Changed source versions, conflicts or failed checks return feedback. Checked declarations and completed adoptions never replace independent whole-problem acceptance. -In native runs, `send_message` binds the sender to the issuing native thread. Use `/root` for Lead and canonical paths or native IDs for peers. Relative paths follow upstream Codex resolution. Teams using host tools send `message` with `agentId`, with receipts and deduplication. +`send_message` binds the sender to the issuing native thread. Use `/root` for Lead and canonical paths or native IDs for peers. Relative paths follow Codex resolution. For native teams, `result.teamContributions` and `inspect` distinguish checked declarations and their adoption from use in each original proof. The report ties a delivered source version to its transfer into Lead's worktree and to final Lean evidence. Where the evidence permits, it distinguishes a delivered target proof, a direct reference, an indirect reference, and a declaration absent from the proof's references. An older receipt may establish a reference without its depth; missing or ambiguous evidence stays unknown. Member messages are separate advisory records, not proof of adoption or mathematical use. For long declarations, `inspect` returns a preview for each source change. Pass the same `deliveryId`, its `changeIndex` and `offset: nextOffset` to read the next page at the fixed commit without adopting it. Native spawn evidence distinguishes a fresh thread, a thread with parent history and an unknown history. A parent's inspection before a full-history fork is recorded as possible exposure through the parent. It is neither a direct read by the child nor proof that the source reached the model after context compaction. -Lead and children share the original run's time, turn and token allowances, with cumulative usage saved in host state. Team writers use Linux bubblewrap isolation with separate PID namespaces; host-controlled process identities allow recovery to confirm previous writers stopped before sources are reused. Native runs use the official collaboration handlers with host-backed isolation; host-tool teams keep built-in spawn/fork disabled. Native threads, messages, tasks, delivery identities and adoption progress persist on resume. A previously running assignment becomes interrupted and requires an explicit Lead assignment to continue; pending proof checking and adoption use their saved source identities. An unconfirmed writer stop blocks further use of that workspace. +Team writers use Linux bubblewrap isolation with separate PID namespaces. On recovery, the host uses saved process identities to confirm previous writers stopped before reusing their sources. Native threads, messages, tasks, delivery identities and adoption progress persist on resume. Lead explicitly reassigns interrupted work. Pending proof checks and adoption use their saved source identities. An unconfirmed writer stop blocks further use of that workspace. -Deferred or rejected source drafts keep their original delivery baseline across assignments, so a corrected helper remains transferable. A stopped child can adopt checked peer work while retaining its own unpublished draft. The host merges against fixed commits, preserves the child's draft and baseline, tracks adopted peer declarations and freshly checks the subsequent combined delivery; the child still names all its own unpublished declarations. Each submit remains limited to 32 declarations; larger host-composed sets are checked in batches, with full-set source-delta and duplicate validation. Conflicts and unconfirmed writer shutdown remain explicit failures. Successful deliveries advance the baseline. Lead adoption completion durably records the next source freeze. If the host exits before whole-proof checking, resume verifies a complete adopted original candidate before admitting another model turn, including when the turn allowance is exhausted. +Deferred or rejected source drafts keep their original delivery baseline across assignments, so a corrected helper remains transferable. A stopped child can adopt checked peer work while retaining its own unpublished draft. The host merges against fixed commits, preserves the child's draft and baseline, tracks adopted peer declarations and freshly checks the subsequent combined delivery; the child still names all its own unpublished declarations. Each submit accepts up to 32 declarations. For larger sets assembled by the host, source changes and duplicates are checked across the full set. Each declaration receives an independent Lean check against the same frozen source and environment. Conflicts and unconfirmed writer shutdown remain explicit failures. Successful deliveries advance the baseline. Lead adoption completion durably records the next source freeze. If the host exits before whole-proof checking, resume verifies a complete adopted original candidate before admitting another model turn, including when the turn allowance is exhausted. Child completion and its proof nomination are saved in one transition. A durable submit acknowledged before a crash is also recovered when the final model response was not saved: after confirming writer shutdown, the host freezes and checks the nomination while leaving the interrupted task's status truthful. Historical completion-before-pending checkpoints are repaired only when their fixed source commit is still the current HEAD. The run inspection includes the same bounded runtime overview, fresh aggregate usage, task allowances, pending delivery identities and message provenance; these observations never confer original-problem acceptance. -`--skill-delegation read-only` remains available for bounded advisory investigations through `theoremos_investigate`. It waits for the batch and provides no persistent proof-writing team. Neither mode currently supplies evidence of a mathematical success-rate or efficiency advantage; this stage validates collaboration functionality. - ## Skill and host responsibilities `skills/theoremos-research/SKILL.md` contains stable research methods with references loaded as needed. It has no specific problem answers or universal task graph. The full directory, including references, participates in build and run identity. A run gets its own copy under `.agents/skills/theoremos-research`; the host checks its identity before dispatch and after writer shutdown. Only a host-pinned projection is allowed by source ownership. Legacy runs do not gain a new editable directory. @@ -188,7 +171,7 @@ Catalog records retain their complete source and provenance, are labeled recorde ## Continue from old research -For a new single Skill run, `--continuation-source-run OLD_RESULT_OR_STATE` uses the single-researcher importer; cooperative runs use the existing cooperative importer. It pins the old canonical commit, preserves worker drafts, research notes, old costs and historical proof snapshots separately, and freshly checks available helpers. The new history attachment records source identity and usage without copying the host's full run state or its personal expert cards. To use a personal expert in the new team, select its release for that run. This restriction concerns host-generated history; deliberately written notes and proof sources remain research material. Same-run `--resume` retains its own frozen configuration. A failed or conditional historical claim remains advisory. +Start a new native team or solo Skill run with `--continuation-source-run OLD_RESULT_OR_STATE`. The importer pins the old canonical commit, preserves worker drafts, research notes, old costs and historical proof snapshots separately, and checks available helpers in the new run. The history attachment records source identity and usage. To use a personal expert in the new team, select its release for that run. Same-run `--resume` retains its frozen configuration. A failed or conditional historical claim remains advisory. When the source was a native team, a same-problem Skill continuation can also search members' archived `RESEARCH.md` notes. Use the continuation search command @@ -198,7 +181,9 @@ route. These notes do not create an assignment or mark any proof as checked. Initialization can resume from its frozen capture after interruption. It rejects changed destination research or configuration instead of overwriting new work. Live source drafts are captured with explicit stability checks and labeled as separate observations, not as a globally atomic snapshot. This command does not stop or migrate the old run. -## Comparison and rollout status +## Historical comparisons + +Use the pinned revision of the original experiment to prepare and execute host scheduling comparisons. The current CLI can read and check their saved reports. `compare --skill-baseline native|file --phase prepare ...` replaces the legacy single arm with skill research. Preparation freezes skill identity in the plan and launch files without starting a model. The existing independent and cooperative arms share the planned model, tools, environment and total token allowance. Reports retain all planned attempts and missing usage. @@ -206,15 +191,13 @@ The `--skill-baseline` comparisons remain **system-mode** comparisons: legacy pr Comparison preparation and solver startup share resource binding for the retrieval corpus, installed mathematics tools and proof-search backend before computing the environment digest. Changed pinned resource bytes remain an error. The first preregistered three-arm diagnostic exposed the previous missing tools binding: all three observations were rejected for an environment identity mismatch and had already stopped at their dispatch allowance. Their frozen plan and raw report remain unchanged. Observed consumption was 8,733 tokens for skill, 17,583 for independent and 11,285 for cooperative; these are costs of invalid attempts, not accepted comparison results. The repair is checked with disposable startup processes without rerunning the observed paid sample. -The existing cooperative engine and readers remain supported. Codex Skill single research can select `--skill-delegation read-only --skill-max-agents 2..4`, counting the primary researcher. The `theoremos_investigate` dynamic tool accepts a bounded questions array and waits for advisory results. The host starts each question in an independent native thread with a verified `math-investigator` read-only permission profile and disabled shell networking. All provider requests share the primary allowance and durable receipts; explicit native thread metadata supplies attribution when available. Native thread totals are observations, not additional charges or proof evidence. - -In this separate read-only investigation mode, stock Codex V1 and V2 spawn inherit the primary writer's permission and remain disabled. Its host-mediated native threading uses an app-server dynamic tool and independent thread/start. The native team backend described above instead routes official collaboration handlers to isolated proof writers. Delegation sessions require `experimentalApi:true`. A cold resume retains the original investigation tool. An investigator is archived before capacity is released: unsubscribe and turn/interrupt do not reap native background commands. Parent completion with unsettled investigations or a permission/archive failure closes the owned app-server tree; source freeze still requires confirmed process shutdown. Saved unresolved observations become unknown on host recovery and are not automatically replayed. +Saved records of the old fixed task graph, `host-tools` teams and `theoremos_investigate` remain available for inspection and export. Use the run's original runtime to execute those methods again. The cooperation fields in an old archive describe what happened in that run. ## Web workflow -Web proof requests can select AgentResearchTeam or host-managed cooperative workers. Use `webAgentTeamPreset(N)` to set the team fields for a Web request, or `math run --agent-team N` on the CLI. Capacity is 2–8 including Lead. Web starts one host Lead and requires a Codex provider and a worker image labeled `org.theoremos.native-agent-control=v1` after its backend passes the image capability check. The same team can retry eligible native startup failures before the Lead starts research using `theoremos_team` host tools. The saved transport is used on resume. Existing cooperative requests retain their plan and approval workflow. Browser requests select neither host binaries nor CLI profiles. +New collaborative Web proof requests use the Codex native team. Capacity is 2–8 including Lead. Web starts one host Lead and requires a Codex provider and a worker image with both `org.theoremos.native-agent-control=v1` and `org.theoremos.native-team-workflow=v1`. The runner starts the image ID it checked. The owner can enable initial route approval for direct Lean input and after natural-language formalization. Historical cooperative requests can still be viewed, including their saved plan and approval records. Resuming them requires the original service and Worker versions. -The skill view displays the actual researcher and independent declaration source, full type, premises, checked commit, environment and receipt references. Recorded evidence requires a fresh consumer check; it never turns an unfinished original goal into an accepted result. Large declaration collections have an explicit byte allowance and report omitted records. Plan, cooperative guidance and approval actions require actual cooperative execution; single researchers keep their declaration workflow. Capture and archive remain supported. All context builders use the host-projected agent tool bundle, including when Docker hides application source. +The Skill view displays the researcher and declaration source, full type, premises, checked commit, environment and receipt references. Recorded evidence requires a fresh consumer check. Large collections report omitted declaration records. Single researchers keep their declaration workflow. Capture and archive remain supported. Context builders use the host-projected agent tools, including when Docker hides application source. ## Completion and rollout status @@ -225,11 +208,11 @@ The skill view displays the actual researcher and independent declaration source | Actual skill execution | An isolated real provider read the pinned native/file skill and reference, reproduced their hashes and a fresh tag, resumed each saved thread, and confirmed all four stops. A separate native compaction also completed. | Raw reports retain their captured runtime hashes. Subsequent delegation guard changes are covered by local regressions; the reports are not relabeled as a test of different bytes. | | Process recovery and context continuity | Twelve isolated Linux process-death cases cover preparation, request acknowledgment, tool writes, freeze, pending helper verification, both declaration-consumption windows and complete original candidates before/after source commit and independent verification, using actual SIGKILL, flock, adapter processes and durable state. A separate SIGKILL case interrupts first skill projection. Unknown usage blocks replay; pending helpers and original candidates use real Lean. | Protocol peers control model responses; this is not a prolonged paid-provider resilience benchmark. | | Knowledge consumption | Three real Lean cases exercise a separate consumer searching, reading, adapting and independently checking a saved declaration, including rejection of changed premises and stale evidence. | A measured research-performance gain from transferred knowledge still needs a matched experiment. | -| Fair comparisons | Common mathematical guidance and generic frozen Lean input are implemented with frozen plans, launches and reports. After the resource-binding repair, a fresh prepare and three actual startup-only runs have matching environment identities and zero model turns. The original invalid diagnostic and its actual costs remain recorded separately. | No repaired paid comparison has been run. A single diagnostic does not support an efficiency claim or default selection. | -| Read-only investigation | Installed Codex 0.169.0 verifies independent read-only threads, dynamic-tool cold resume, denied file/Unix-socket writes, and archive/process-group cleanup using local fixed replies. Shared accounting and recorded recovery use the existing request ledger. | Built-in V1/V2 spawn remains disabled. This is a host-mediated tool, and no mathematical performance gain has been measured. | +| Historical comparisons | After a resource-binding repair in the historical runtime, a fresh plan and three startup-only runs had matching environment identities and zero model turns. The rejected earlier diagnostic and its actual costs remain recorded. | A repaired paid comparison has yet to be run. | +| Historical read-only investigation | The retired host-mediated tool was verified with Codex 0.169.0 and local fixed replies, covering independent read-only threads, cold resume, denied writes and process cleanup. | Use the historical runtime to reproduce those checks. | | Web workflow | Creation, draft restoration, configuration freezing, declaration display, supported controls and translated desktop/mobile browser flows are covered. A private image derived from an immutable baseline rebuilt the branch's headless runtime and agent tools; native/file startup-only, statement elaboration and pinned skill projection pass. A separate offline probe runs the image's actual Codex 0.162.0 and adapter: native discovery, both actual shell readbacks, bundled tool usage and confirmed stops pass with application source hidden. | The packaged probe binds that immutable image, before the later recovery fixes. Its provider replies are fixed loopback data; actual provider authentication, metered relay behavior and mathematical performance inside the image remain untested. | -The single researcher still shares session execution and accounting in `research.ts`. Its stopped-source freeze, declaration delivery and pending-proof recovery now live in `skillProofLifecycle.ts`, behind `freezeSources`, `resumePending` and `checkFrozenWholeProof`. Recovery runs before another model dispatch, including when the model allowance is exhausted. This separates the ordering involved in the reproduced freeze/recovery failures from cooperative task scheduling without duplicating the model loop, budget ledger or acceptance implementation. The existing `checkWhole` callback retains knowledge-use checking, winner selection and the loop's successful abort; the lifecycle finishes its durable cleanup after that abort. Retiring old strategy code remains conditional on comparison results and the absence of supported consumers. +The single researcher shares session execution and accounting in `research.ts`. Its source freeze, declaration delivery and pending-proof recovery live in `skillProofLifecycle.ts`. Recovery runs before another model dispatch, including when the model allowance is exhausted. Current verification covers the retained solo and native team paths. Historical scheduling comparisons remain tied to the builds used by their original runs. ## Verification @@ -237,8 +220,6 @@ Focused tests exercise native skill requests and discovery errors, full-director The 2026-11-16 real-model Putnam 1963 A4 diagnostic used runtime `7284f3b`, `deepseek-flash/high`, a 1200-second run allowance and a 300-second hard turn limit. It created no child and completed no proof: the first turn was interrupted at 300 seconds, and the final request had no usage receipt, so finite-budget admission stopped the run. That observation informed early collaboration guidance and earlier host coordination checkpoints, which current team execution no longer uses. Collaboration decisions now stay with Lead as described above. Local regressions and the native transport test do not replace a separately recorded real-model retest. -The implementation also runs the affected legacy acceptance, proof-ready, budget, knowledge and continuation regressions and the four-bundle headless build. Full-repository type checking passes after fixing the optional archive asset existence check, observation coverage fixture values and unused declarations in `scripts/test-classic-global-trajectory.ts` and `scripts/test-web-proof-map.ts`. A separate check of the CLI/runtime/mathematics source surface also verifies this branch's headless types. - Historical archives can retain coordination decisions, observations and presentation identities. These remain recorded data and advance neither an inbox cursor nor a Lead decision. Current team execution does not use them to require acknowledgments, restrict tools or schedule coordination-only handoffs. Deterministic source-policy rejection is corrective feedback, including exact outside-ownership paths when available. Team members retain invalid draft files and notes in their own workspace, clear the rejected nomination and can receive an explicit correction assignment against the last actual source commit. Invalid drafts create no proof/research acceptance artifact. Lead receives the same precise feedback and can correct its workspace; arbitrary Git, I/O and environment faults retain their error behavior. diff --git a/docs/formalization.md b/docs/formalization.md index ab2aec97..a2fca7a7 100644 --- a/docs/formalization.md +++ b/docs/formalization.md @@ -160,7 +160,7 @@ The first complete schema-valid OUTPUT.json is an explicit role submission. The bun run math formalize --phase inspect --directory /tmp/theorem-os-formalization-bounded ``` -An approved run returns the artifact directory, `workspaceRoot`, `receiptFile`, `taskFile`, and `runArguments` for the existing proof solver. The artifact preserves `original.txt`, `Statement.lean` and `evidence.json`; changing the original, source, targets, environment or review breaks its identity checks. Pass the returned `runArguments` to `bun run math run`, adding the desired native proof-search configuration and budget. Formalization approval alone never counts as solving the problem. +An approved run returns the artifact directory, `workspaceRoot`, `receiptFile`, `taskFile`, and `runArguments` for the proof solver. The artifact preserves `original.txt`, `Statement.lean` and `evidence.json`. Identity checks cover the original, source, targets, environment and review. Pass the returned `runArguments` to `bun run math run`, adding team capacity, initial route approval or budget options as needed. Solving still requires independent Lean acceptance. `report` writes a compiled direct run or an independently reviewed run as one offline comparison page. Direct reports show the original, Lean statement and compiler status, mark semantic review as not performed, and omit absent backtranslation and review sections. It calls no model and needs `bun run build:web` first: diff --git a/docs/generic-cli.md b/docs/generic-cli.md index e7033121..ed05c64c 100644 --- a/docs/generic-cli.md +++ b/docs/generic-cli.md @@ -29,7 +29,7 @@ bun bin/math.ts run --harness cli --harness-profile DEDICATED_PROFILE \ --output RESULT_FILE --build-manifest BUILD_MANIFEST ``` -`--harness-executable` optionally overrides `executable`. The CLI harness defaults to Skill mode, file loading and one independent researcher. Explicit workers/coordination select host-managed independent or cooperative execution; explicit legacy research remains supported. Build the standalone runtime normally with an external `--state-root` and use its build manifest. Web operators can configure the same backend, and `compare` freezes a fresh configuration-only profile per attempt. Sealed formalization and audit roles retain their stronger isolation requirement; see [complete workflows](portable-workflows.md). +`--harness-executable` optionally overrides `executable`. The CLI harness defaults to a solo researcher with file-loaded Skill guidance. Build the standalone runtime with an external `--state-root` and use its build manifest. Web operators can configure the same backend. Sealed formalization and audit roles retain their stronger isolation requirement. See [complete workflows](portable-workflows.md). ## Input and session contract diff --git a/docs/harness-portability.md b/docs/harness-portability.md index 06cf1ee1..cdbc4035 100644 --- a/docs/harness-portability.md +++ b/docs/harness-portability.md @@ -1,19 +1,17 @@ # Portable research harnesses -Research supports Codex, Claude Code, OpenCode and a configurable [headless CLI harness](generic-cli.md). Mathematical methods live in one pinned `skills/theoremos-research` directory and can be selected separately from the backend and host coordination. The solver uses `MathAgentSession` for dispatch, native session IDs, activity, usage and confirmed process shutdown. Mathematical acceptance, declaration artifacts, saved sources and independent verification remain host responsibilities. +Research supports Codex, Claude Code, OpenCode and a configurable [headless CLI harness](generic-cli.md). New collaboration uses the Codex native team. Additional harnesses support solo workloads. Mathematical methods live in one pinned `skills/theoremos-research` directory and can be selected separately from the backend and host coordination. The solver uses `MathAgentSession` for dispatch, native session IDs, activity, usage and confirmed process shutdown. Mathematical acceptance, declaration artifacts, saved sources and independent verification remain host responsibilities. | Harness | Native transport | Skill loading | Research arrangement | Usage basis | | --- | --- | --- | --- | --- | -| Codex | app-server over stdio | native or file | Single, independent, host cooperative and Agent-organized proof-writing team | Provider requests when the existing relay supplies receipts; otherwise native cumulative thread totals | -| Claude Code | print mode with stream-json | file | Single, independent and host cooperative | One final native invocation total, including all API calls inside that invocation | -| OpenCode | native server, session API and SSE | file | Single, independent and host cooperative | Deduplicated assistant request totals belonging to the dispatched native message | -| Configured CLI | argv + stdin/file/argument; text, JSON or JSONL | file | Single, independent and host cooperative | Explicitly mapped invocation or cumulative session totals; unknown unless complete native coverage is configured | +| Codex | app-server over stdio | native or file | Solo and native proof-writing team | Provider requests when the existing relay supplies receipts; otherwise native cumulative thread totals | +| Claude Code | print mode with stream-json | file | Solo for new runs | One final native invocation total, including all API calls inside that invocation | +| OpenCode | native server, session API and SSE | file | Solo for new runs | Deduplicated assistant request totals belonging to the dispatched native message | +| Configured CLI | argv + stdin/file/argument; text, JSON or JSONL | file | Solo for new runs | Explicitly mapped invocation or cumulative session totals; unknown unless complete native coverage is configured | -CLI research, trusted Web provider configuration, automatic-library proof backends, comparison and batch launches share this selection. Complete role workflows reuse the same dispatch interface and hermetic role sandbox across all four backends. The generic CLI requires an explicit executable/resource projection and role relay mapping; see [complete workflows](portable-workflows.md). Host cooperation preserves Lead, task ownership, fixed Reviewer, integration, recovery and independent acceptance on all four research backends. +CLI research, trusted Web provider configuration, automatic-library proof backends and batch launches share this selection. Formalization, review and other sealed roles reuse the same dispatch interface and sandbox across all four backends. The generic CLI requires an explicit executable/resource projection and role relay mapping. See [complete workflows](portable-workflows.md). -Codex Skill single research can additionally select `--skill-delegation read-only --skill-max-agents 2..4`. A native dynamic tool dispatches independent named read-only threads through the host, with one shared request gate and accounting ledger. This is host-mediated native threading; Codex's built-in V1/V2 spawn remains disabled because both inherit the primary writer's permission. Each investigator is archived before returning advisory findings. Parent shutdown confirms that the owned process group stopped before source freeze. Native permission profiles and dynamic tools require the app-server experimental capability, verified against Codex 0.169.0. Unsupported protocols or permission bindings fail explicitly and stop the owned tree. - -Codex also supports `--research-mode skill --skill-delegation team --skill-max-agents 3`, with a total of 2–8 agents including Lead. It uses one host Lead (`workers=1`, `coordination=independent`). Native teams use Codex collaboration tools for dispatch and messaging and `theoremos_team` for proof handoffs. Teams using host tools also coordinate through `theoremos_team`. Lead decides decomposition and adoption; children retain native threads, write Lean in isolated worktrees and communicate or deliver asynchronously. The host checks exact deliveries after writer shutdown and rechecks them during integration. See the [team launch and delivery protocol](codex-skill-runtime.md#agent-organized-proof-writing-team). This bridge is Codex-only; host-cooperative workflows remain available across all four harnesses. Checked team artifacts do not grant whole-problem acceptance. +Codex runs default to a native team of four including Lead. Use `--agent-team N` for a capacity of 2–8 or `--workers 1` for a solo researcher. Native teams use Codex collaboration tools for dispatch and messaging and `theoremos_team` for proof handoffs. Lead decides decomposition and adoption. Children retain native threads, write Lean in isolated worktrees and deliver asynchronously. The host checks exact deliveries after writer shutdown, rechecks them during integration and independently verifies the whole problem. See the [team launch and delivery protocol](codex-skill-runtime.md#agent-organized-proof-writing-team). ## Launch @@ -35,7 +33,7 @@ bun bin/math.ts run --harness opencode \ --output ANOTHER_RESULT_FILE --build-manifest BUILD_MANIFEST ``` -Additional harnesses default to `--research-mode skill --skill-loading file --workers 1 --coordination independent`. Add `--workers 4 --coordination cooperative` for host cooperation, or `--workers 4 --coordination independent` for independent attempts. Explicit legacy methods also work; unsupported native Skill loading or delegation is rejected. They require a separately created profile directory and explicit model. OpenCode requires `opencode.json` in that directory, with the selected provider configured and the requested effort present in the native model's variants. Unsupported efforts are rejected. Claude uses its explicit native model/effort flags and API authentication environment. +Additional harnesses default to `--research-mode skill --skill-loading file --workers 1 --coordination independent`. Explicit legacy methods also work; unsupported native Skill loading or delegation is rejected. They require a separately created profile directory and explicit model. OpenCode requires `opencode.json` in that directory, with the selected provider configured and the requested effort present in the native model's variants. Unsupported efforts are rejected. Claude uses its explicit native model/effort flags and API authentication environment. Only explicit provider definitions enter the OpenCode configuration. Project configuration, plugins, MCP, title models and child agents are disabled for this execution path. Claude disables project settings, hooks, plugins and child tools. The host points both agents to the identical frozen Skill file and generated command help. It does not translate mathematical methods into a separate backend-specific prompt library. @@ -43,7 +41,9 @@ Native credentials enter an execution-only environment overlay and are excluded ## Resume and isolation -Use the normal `--resume` command with the same workspace, task, output and build manifest. The saved harness, model, profile, executable and Skill loading are inherited. The host pins the executable's canonical path and file digest, native configuration bytes and endpoint environment identity. It checks this binding before dispatch and after writer shutdown, as well as on resume. Mutable native session/cache files may grow. Changing the harness or frozen configuration requires a new run; a native conversation cannot move between harnesses. Historical Codex checkpoints without the new binding retain their existing interpretation. Explicit `--harness-profile` or `--harness-executable` also opts Codex into the new binding; `--codex` remains its compatible executable alias. +Use `--resume` for solo runs and Codex native teams with the same workspace, task, output and build manifest. The saved harness, model, profile, executable and Skill loading are inherited. The host pins the executable's canonical path and file digest, native configuration bytes and endpoint environment identity. It checks this binding before dispatch, after writer shutdown and on resume. Changing the harness or frozen configuration requires a new run. Explicit `--harness-profile` or `--harness-executable` also opts Codex into the binding. `--codex` remains its compatible executable alias. + +For old fixed-task-graph runs, `host-tools` teams and host-mediated read-only investigators, use the original pinned TheoremOS revision and build manifest to resume. The current CLI still reads their saved records with `inspect`. To start a new native team or solo Skill run from old sources and notes, use `--continuation-source-run`. `planMathAgentSession` resolves Skill loading, role isolation, structured delivery and continuation before dispatch. New runs freeze that plan and compare it with the actual adapter plan. A CLI without native resume explicitly uses source-context continuation; a CLI without native schema enforcement uses a validated output file when the workflow supplies a validator. Neither is reported as a native capability. Historical Skill checkpoints without `researchSkillWorkflow: full` retain their original single-researcher workflow. @@ -57,6 +57,6 @@ For research-workspace sessions, native invocation totals are added once per act Validation uses installed Claude Code 2.1.322 and OpenCode 1.19.5 with fixed loopback provider replies, plus disposable native protocol peers. It covers actual Skill reads, shell execution, native session resume, hidden-root denial, missing usage and confirmed shutdown without external model calls. Shared integration tests run each real adapter through the Skill solver and check correct proofs, wrong proofs and reusable helpers with real isolated Lean 4.33.0. These tests establish execution and acceptance behavior; they do not measure mathematical success rate or an efficiency advantage over direct harness use. -Complete-cooperation regressions additionally run Claude Code, OpenCode and CLI adapters as real local processes with fixed responses: persist and restore the Lead plan, deliver original targets through an Engineer, obtain an independent Reviewer decision, accept through real Lean, reject an incorrect proof despite native completion, and stop process descendants. No external model is used. +Historical complete-cooperation regressions ran Claude Code, OpenCode and CLI adapters as real local processes with fixed responses to verify the Lead plan, Engineer delivery, independent Reviewer decision, real Lean acceptance and shutdown. Use the corresponding historical revision to reproduce those regressions. -For a portable comparison, prepare with `--harness ID --harness-profile CONFIG_TEMPLATE --harness-executable COMMAND --model MODEL`. Each arm receives only allowlisted frozen configuration in a fresh directory; native sessions and credential stores are not copied. Template and attempt identities are checked before the batch, and observed states must match their planned backend. Non-Codex common-Skill comparisons require file loading. This prepares an experiment; it does not provide measured efficiency results. +In the pinned historical version, prepare a portable comparison with `--harness ID --harness-profile CONFIG_TEMPLATE --harness-executable COMMAND --model MODEL`. Each arm receives the allowed frozen configuration in a fresh directory. Template, attempt and backend identities are checked before launch and reporting. Non-Codex common-Skill comparisons require file loading. diff --git a/docs/library-catalog.md b/docs/library-catalog.md index dd9a9e9a..5ec34657 100644 --- a/docs/library-catalog.md +++ b/docs/library-catalog.md @@ -57,7 +57,7 @@ Web 默认使用 `resources/theorem-os-library/release/catalog.json`。私有 wo 应用尝试 `exact` / `apply`,也可用 `Iff.mp` / `Iff.mpr` 消费双向命题的一侧,通过 `Eq.symm` 应用方向相反的等式,或用一次正向 `rw` 将库结论改写到目标的子表达式中。另有一个显式展开全部参数的 `refine'` 分支,使只出现在前提中的关系或谓词可以由局部假设确定;隐式参数、类实例和其余前提都必须关闭。这些主定理应用方式都可逐项尝试同一候选池中的其他定理来关闭前提或转换后的目标;辅助定理只应用一层,其剩余前提须由局部假设或 `rfl` 关闭,不递归展开。带前提的双向定理先形成显式证明目标,关闭其前提后再处理被转换的一侧,避免内部证明失败阻断后续尝试。重写后的目标和定理前提都必须关闭,每个分支必须关闭全部目标才算成功,总检查预算仍为 30 秒;界面和模型上下文保持最多三条简要推荐。最终证明引用才进入实际使用记录。 -Web 的 Mathlib 解题 agent 还可主动检索整个固定版本,包括本题尚未安装的模块。宿主每回合写入 `LIBRARY.json`,绑定目录摘要、当前题目回执、seed commit 与已冻结模块;agent 使用独立工具: +Web 的 Mathlib 解题 Agent 可检索整个固定版本,包括本题尚未安装的模块。`LIBRARY.json` 绑定目录摘要、当前题目回执、seed commit 与已冻结模块。Lead 和成员都可用 `search`、`get`。需要补装时,成员通过原生消息把声明名、用途和所需前提发给 Lead,由 Lead 提交 `request`。单人运行可直接提交请求。 ```bash theorem-os library search --worktree WORKTREE --query '数学关键词' --goal 'Lean 目标及局部假设' diff --git a/docs/math-tools/catalog.md b/docs/math-tools/catalog.md index 4712e430..d2bd74db 100644 --- a/docs/math-tools/catalog.md +++ b/docs/math-tools/catalog.md @@ -17,7 +17,7 @@ ## 项目里的现成入口 -TheoremOS 已有 `search-lean`、`check-lean`、`proof-search`、`check-finite` 和 `kernel-certificate`。Skill 会按宿主的工具清单介绍可用命令。如果运行清单提供 `math-python`,它可携带 NumPy、SciPy、SymPy 和 PySAT。Web worker 的构建文件明确安装了固定 Lean、Mathlib 和 Pantograph,各运行的 Python 工具可用性取决于镜像和清单。固定 Mathlib 的依赖包含 Plausible、LeanSearchClient、import-graph、ProofWidgets4 和 Aesop。 [CLI](../../bin/math.ts) · [工具清单](../../docs/solver-modules.md) · [Skill 入口](../../src/solver/skillResearchContext.ts) · [Web worker](../../apps/web/Dockerfile) · [依赖清单](../../resources/mathlib/environment.json) +TheoremOS 提供 `search-lean`、`check-lean`、`check-finite` 和 `kernel-certificate`。Skill 按运行的工具清单介绍命令。如果清单提供 `math-python`,它可携带 NumPy、SciPy、SymPy 和 PySAT。Web worker 提供固定 Lean 和 Mathlib。Mathlib 的依赖包含 Plausible、LeanSearchClient、import-graph、ProofWidgets4 和 Aesop。依赖固定任务图的 `proof-search` 使用对应的历史版本。 [CLI](../../bin/math.ts) · [工具清单](../../docs/solver-modules.md) · [Skill 入口](../../src/solver/skillResearchContext.ts) · [Web worker](../../apps/web/Dockerfile) · [依赖清单](../../resources/mathlib/environment.json) 工作台的 Proof Map 读派工、试用、交付、采纳和验收回执。Lean 的 tactic 步骤、编译后声明依赖和模块 import 是另外三种关系,分别由语言服务器、编译产物和模块清单提供。图形可以引用同一份源码版本。原题是否通过由独立 Lean 验收确定。 [Proof Map](../../apps/web/client/proofMapModel.ts) · [原题验收](../../src/solver/evaluation.ts) diff --git a/docs/native-skill-comparison.md b/docs/native-skill-comparison.md index 8005c982..df8863e1 100644 --- a/docs/native-skill-comparison.md +++ b/docs/native-skill-comparison.md @@ -6,7 +6,7 @@ | 臂 | 执行方式 | 本轮边界 | | --- | --- | --- | -| `native-skill` | 直接 `createCodexMathSession`,一次 `session.run` | 绕过 `runSolver`、`runResearchWorkers` 和 M1–M5;任务内由原生 Codex 自主调用工具,返回后做验收 | +| `native-skill` | 直接 `createCodexMathSession`,一次 `session.run` | 直接启动单个 Codex 会话,由它自主调用工具,返回后做验收 | | `runtime-skill` | 普通 `bin/math.ts run --research-mode skill` | 现有 Skill 研究循环、停止写入、反馈与后续 dispatch | 原生基线复用现有 app-server adapter,以对齐权限、Lean diagnostics、原生 Skill 和上游请求计费。它不是默认的 `codex exec`。共享的静态数学指导和工具帮助由 `buildCommonResearchGuide` 产生;两臂自己的交付协议仍然不同。native 侧不会处理任务内 helper 提交或发出纠正 turn,runtime 侧保留当前循环的行为。 diff --git a/docs/solver-modules.md b/docs/solver-modules.md index 8398cccc..4dbd0908 100644 --- a/docs/solver-modules.md +++ b/docs/solver-modules.md @@ -1,5 +1,7 @@ # 解题模块与交接协议 +固定任务图、M3 任务排序和 M5 角色派发说明用于解读旧档案与实验。执行旧协作时使用对应历史版本。新版由 Codex Lead 派工,宿主负责上下文、隔离、交付检查和独立验收。[原生团队交付协议](codex-skill-runtime.md#agent-organized-proof-writing-team) + M1–M5 表示运行时的决策边界,不是五个依次执行的解题步骤,也不等于五个 agent。研究检索、路线规划、引理证明、原题集成和独立验收都会使用其中多个模块。增加角色数量不能替代明确的数学产物和消费关系。 ## 模块边界 @@ -19,10 +21,10 @@ M1–M5 表示运行时的决策边界,不是五个依次执行的解题步骤 | 实现入口 | 职责 | | --- | --- | | `src/solver/research.ts` | 编排会话启动、执行、恢复和交付;串行化整题检查入口 | -| `src/solver/workerProofLifecycle.ts` | 统一证明就绪后的 writer 停止确认、源码冻结与固定快照检查 | +| `src/solver/skillProofLifecycle.ts` | 管理单人 Skill 工作区的停写、源码冻结与待检查证明恢复 | | `src/solver/researchUsage.ts` | 管理当前模型轮次和会话的用量事件、请求准入与收据结算 | | `src/solver/usageBudget.ts` | 计算累计用量与共享预算状态,不执行模型或证明检查 | -| `src/solver/cooperation.ts` | 管理任务、交付、集成与通知;分别处理 Lead、peer 派发,共用等待和前沿恢复逻辑 | +| `src/solver/agentTeam.ts` | 把 Codex 原生团队连接到各自的隔离工作树和证明交付,保存任务与成果来源 | | `src/math/verifier.ts` | 核对固定源码与目标身份,执行 Lean 检查和官方验收,生成回执 | | `src/math/verifierCheckout.ts` | 负责验证工作树的创建与回收;失败、异常和取消均进入同一清理路径 | diff --git a/docs/theorem-knowledge.md b/docs/theorem-knowledge.md index 96b500e7..10f39035 100644 --- a/docs/theorem-knowledge.md +++ b/docs/theorem-knowledge.md @@ -366,7 +366,7 @@ bun bin/math.ts run \ --workspace /PATH/problem-workspace \ --task-file /PATH/task.md \ --knowledge-base /PATH/knowledge/catalog-v2.json \ - --workers 4 \ + --agent-team 4 \ --max-run-seconds 0 --max-turns 0 --max-turn-seconds 0 \ --evaluator-timeout-seconds 0 \ --output /PATH/new-run-with-knowledge/result.json \ @@ -387,7 +387,7 @@ by the context budget. The checkpoint retains 128 retrieval observations and a dropped count; full observations are emitted as events. Old checkpoints without these observations have unknown coverage, rather than zero inferred lookups. -`compare --phase prepare` and `sample-putnam --phase prepare` also accept +In the pinned historical experiment revision, `compare --phase prepare` and `sample-putnam --phase prepare` also accept `--knowledge-base FILE`. They freeze the catalog, its source objects, digest and `--knowledge-mode transfer|recovery` in the experiment plan and pass the frozen snapshot to every launch. The default `transfer` mode rejects recorded target diff --git a/docs/usage.md b/docs/usage.md index 61c61380..5c1de124 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -2,7 +2,7 @@ [返回 README](../README.md) · [组件替换示例](../examples/components/README.md) -这里保留手动准备题目、配置运行环境、恢复实验和调整协作计划的完整说明。第一次使用可以先跑[小题示例](../examples/getting-started/README.md),再尝试 [IMO2026 Q1](../examples/imo2026/README.md)。 +这里介绍如何准备题目、配置环境、运行原生团队、审核首轮路线和读取历史档案。第一次使用可以先跑[小题示例](../examples/getting-started/README.md),再尝试 [IMO2026 Q1](../examples/imo2026/README.md)。 ## 环境诊断与小题示例 @@ -40,11 +40,11 @@ bun install --frozen-lockfile bun run build ``` -构建生成 `out/main/math-solver.js`、`search-lean.js`、`check-lean.js` 和 `proof-search.js`,并输出 JSON。记录其中的 **`buildManifestRef`**,运行时需要传入这个文件的绝对路径。源码与 bundle 均校验哈希,修改运行时代码后需重新构建。 +构建生成 `out/main/math-solver.js`、`out/main/search-lean.js` 和 `out/main/check-lean.js`,并输出 JSON。运行时传入 `buildManifestRef` 对应的绝对路径。源码与 bundle 均按哈希校验,修改运行时代码后需重新构建。 CLI 默认使用 `~/.config/deepscientist/math-sol-codex` 中的 Codex profile,通过本地 Sub2API 网关 `http://127.0.0.1:8080/v1` 调用模型。`run` 的默认模型为 `deepseek-flash`,新运行的默认推理强度为 `high`。本机 profile 的认证命令按需读取已有部署的 Westlake 号池密钥,无需复制密钥或手动 export。也可通过 `CODEX_HOME` 指向其他已有 profile。 -`compare --provider sub2api` 和 `sample-putnam` 创建的独立 profile 使用环境变量 `SUB2API_WESTLAKE_API_KEY`;启动这些实验前需要在调用环境中设置它。密钥不会写入实验 profile 或数学工具环境文件。 +在历史版本中重跑使用 `compare --provider sub2api` 或 `sample-putnam` 的实验时,通过 `SUB2API_WESTLAKE_API_KEY` 提供认证。密钥不会写入实验 profile 或数学工具环境文件。 项目原名 DeepScientist Math。CLI 入口为 `theorem-os`,同时保留 `deepscientist-math` 别名与 `bun run math`;已有环境变量、默认配置路径和运行档案格式继续兼容。 @@ -97,11 +97,11 @@ bun run math run \ --build-manifest "$MATH_BUILD_MANIFEST" \ --workspace "$MATH_RUN_ROOT/workspace" \ --task-file "$MATH_RUN_ROOT/task.md" \ - --workers 4 \ + --agent-team 4 \ --output "$MATH_RUN_ROOT/result.json" ``` -默认启用四个 Agent。CLI 默认不限制解题时间、模型调度次数和 token 用量。需要限制时,可设置 `--max-run-seconds`、`--max-turns` 或 `--max-total-tokens`。Web worker 会传入该次运行的预算。运行向标准输出发送 JSON 进度事件,并将结果写入 `result.json`。 +新建 Codex 运行默认使用原生团队,最多四人(含 Lead)。设置 `--plan-approval` 可在开工前审批 Lead 提交的路线。CLI 默认不限制解题时间、模型调度次数和 token 用量。需要限制时,可设置 `--max-run-seconds`、`--max-turns` 或 `--max-total-tokens`。Web worker 会传入该次运行的预算。运行向标准输出发送 JSON 进度事件,并将结果写入 `result.json`。 首次配置环境时,可在上述命令末尾加 `--startup-only`,只检查准备条件,不调用模型。预检会创建运行状态;之后使用相同参数加 `--resume` 开始求解。 @@ -112,14 +112,15 @@ bun run math run \ --build-manifest "$MATH_BUILD_MANIFEST" \ --workspace "$MATH_RUN_ROOT/workspace" \ --task-file "$MATH_RUN_ROOT/task.md" \ - --workers 4 \ --output "$MATH_RUN_ROOT/result.json" \ --resume ``` 恢复时使用原有题目、构建、环境、模型和 Agent 数量。宿主校验运行身份,并重新验证已有证明;会话、失败记录和累计用量保留在运行档案中。 -新建续跑可用 `--continuation-manifest FILE` 明确附加历史证明、笔记或诊断。任务文件继续逐字作为必需题面,宿主不会按 Markdown 标题拆分或删除文字。附件清单例如: +新版的 `--resume` 适用于单人运行和 Codex 原生团队。旧固定任务图、`host-tools` 团队和宿主只读调查可用 `inspect` 查看。若要续跑同一旧任务,请从它原来固定的 TheoremOS 版本,用相同的构建清单、工作区、任务文件和结果路径运行上面的命令。Web 旧任务的续跑也需要对应旧版本的服务和 Worker。 + +要在新版以旧资料开始一次独立研究,可用 `--continuation-manifest FILE` 显式附加历史证明、笔记或诊断。任务文件继续逐字作为必需题面,宿主不会按 Markdown 标题拆分或删除文字。 ```json { @@ -151,17 +152,15 @@ bun run math run \ bun run math run \ --workspace "$MATH_RUN_ROOT/workspace" \ --task-file "$MATH_RUN_ROOT/task.md" \ - --workers 4 \ + --agent-team 4 \ --output /runs/continued/result.json \ --build-manifest "$MATH_BUILD_MANIFEST" \ --continuation-source-run /runs/previous/result.json ``` -宿主持有同一个目标运行锁和 proof environment,核对题目、任务摘要、原始源码约束和新构建身份,冻结旧 canonical 源码、任务图及工人草稿,再生成新的 Lean 收据并开始求解。同进程继续使用刚验证的无条件辅助证明收据,避免初始化后立即重复检查;条件性证明保留原来的待证义务。旧线程和工人的 assignment 不复用。附件同步到每个工人的项目,原运行与原构建保持原样。`--prepare-timeout-seconds` 仍约束准备与初始化阶段,解题阶段独立使用原有预算参数。 - -普通 research/sketch 的交付记录保存本次实际上下文的输入身份,包括任务、传递依赖的 finding 与证明状态、环境、检索/知识库和可见源码。续跑只比较并沿用这份原记录;输入变化会重开调查并保留旧 finding 的历史,重新调查即使结论文字相同也保留新的交付身份。新 Lean 收据编号不构成输入变化,独立重检失败的依赖则会使研究重开。无法从存档确认原分工的源码可见范围时,也会保守地重新调查。该状态只结束研究,不授予任何证明验收。旧快照缺少真实交付输入身份时按待办恢复,原始 finding 仍保存在历史附件中。 +宿主持有新运行的锁,核对题目、任务摘要、原始源码约束和构建身份。旧运行的规范源码按 commit 固定,旧任务和草稿独立保存为研究资料。宿主为可用的辅助声明生成新的 Lean 收据,再开始新研究。附带的条件性证明和笔记供研究参考。`--prepare-timeout-seconds` 约束准备与初始化阶段。 -该入口只支持至少两个工人的协作运行,不能与 `--continuation-manifest` 同用。新团队无法承担的任务负责人(`ownerId`)会被释放,任务版本不变,由当前成员重新领取。加 `--startup-only` 会冻结续跑材料并保存零轮 checkpoint。待核验的辅助证明在移除 `--startup-only` 并加 `--resume` 后检查一次,随后直接在同一进程中开始求解。开始求解前,初始化、快照读取、工人附件分发或启动结果发布失败都保留可恢复的 `prepared` 状态,在原参数上加 `--resume` 可继续使用首次冻结的材料。开始过求解后,恢复时省略 `--continuation-source-run`,按普通 `--resume` 流程重新验证存档证明。 +该入口支持原生团队和单人 Skill 运行,与 `--continuation-manifest` 二选一。加 `--startup-only` 会冻结材料并保存零轮 checkpoint。移除 `--startup-only` 并加 `--resume` 后,宿主核验辅助证明并开始求解。准备过程若中断,可用 `--resume` 继续使用首次冻结的材料。开始求解后,按普通 `--resume` 流程恢复。 也可以保留分步流程:先用新构建执行 `run --startup-only`,再运行独立初始化命令: @@ -173,7 +172,7 @@ bun run math continuation-seed \ --timeout-seconds 0 ``` -独立命令只接受零轮、未开始求解的新预备运行。它创建并释放本次 proof environment,不复用已经结束的准备进程的临时 lease。完整源码投影及前提相同的 helper 每批最多合并 32 项检查,各批顺序执行,每个目标仍生成独立收据并保存进度。新的无条件收据通过后才标记 `integrated`,失败项保持未验收,可在报告中查看。 +独立命令只接受零轮、尚未开始求解的预备运行。它在临时环境中核对固定源码,为通过检查的辅助声明保存新的 Lean 收据,并在报告中列出失败项。 初始化成功后,以新预备运行的原参数加 `--resume` 开始求解。中断的初始化可以用相同命令重试,重试复用首次冻结的快照;源运行后来产生的成果不会自动加入该快照。正式切换前应让源运行保存退出,再捕获最终快照。更换构建后直接 `--resume` 旧 checkpoint 仍会被身份校验拒绝。 @@ -203,34 +202,7 @@ bun run math inspect --run "$MATH_RUN_ROOT/result.json" \ 报告还会分别记录数学义务闭合、原题前沿变化、替代路线与局部障碍重开。局部阻塞、必需上下文与省略清单、`proofRoutes` 的 AND/OR 规则见[协作路线、上下文与数学进展](cooperative-proof-routes.md)。 -Lead 创建计划后,可以导出并修改引理类型、任务依赖、路线或暂停状态,然后提交修改: - -```bash -bun run math edit --run "$MATH_RUN_ROOT/result.json" \ - --plan "$MATH_RUN_ROOT/plan.json" --dry-run -bun run math edit --run "$MATH_RUN_ROOT/result.json" \ - --plan "$MATH_RUN_ROOT/plan.json" -``` - -保留导出计划的 `baseVersion` 和全部原题目标。`edit` 校验计划并追加到修改队列;运行中或恢复后的求解器继续检查版本、应用修改和重检受影响证明。`queued`、`applied` 与证明重检结果分别展示;过期计划需要重新导出。导出文件默认拒绝覆盖已有文件。 - -已有外部 Lean 证明片段时,可交给宿主导入待处理的引理任务。先导出当前计划,读取其中的 `baseVersion`,再计算片段的 SHA-256: - -```bash -FRAGMENT="/absolute/path/to/fragment.lean" -FRAGMENT_SHA256="$(sha256sum "$FRAGMENT" | cut -d ' ' -f 1)" -PLAN_BASE_VERSION="$(node -p 'JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8")).baseVersion' "$MATH_RUN_ROOT/plan.json")" -bun run math import-proof --run "$MATH_RUN_ROOT/result.json" \ - --task TASK_ID --fragment "$FRAGMENT" --sha256 "$FRAGMENT_SHA256" \ - --base-version "$PLAN_BASE_VERSION" --dry-run -bun run math import-proof --run "$MATH_RUN_ROOT/result.json" \ - --task TASK_ID --fragment "$FRAGMENT" --sha256 "$FRAGMENT_SHA256" \ - --base-version "$PLAN_BASE_VERSION" -``` - -仅支持计划中启用、状态为 `pending` 且有 `proofPath` / `theoremName` 的 `lemma` 任务;运行中的任务不能被导入抢占。片段只能包含具名 `theorem` / `lemma` 声明,不能含 `sorry`、`admit`、公理、导入、作用域命令、选项或定义;声明在任务已有源码上下文内追加,保留原声明。`--dry-run` 只校验;可选 `--id ID` 指定请求身份,完全相同的重试返回 `already_queued`,同一任务不能同时排队多个未结束请求。过期计划或哈希不符会被拒绝。 - -命令捕获片段内容及运行、任务、计划、源码与环境身份,追加到运行目录的 `proof-imports.jsonl`,不直接修改 checkpoint。运行中或恢复后的求解器在正常任务派发后、打开模型前读取该队列;排队本身不唤醒等待者,也不绕过任务依赖、负责人、路线或预算门控,因此不保证立即处理。宿主冻结导入提交,再沿现有 proof-ready 流程独立检查 Lean 和规范源码合并;后续修改外部片段或工作文件不会替换已冻结内容,导入本身不计模型轮次或证明尝试。CLI 的 `queued` 仅表示已排队;消费后的 `proofImports`、proof-ready 检查和任务集成结果可用 `inspect --format json` 分别查看,排队或冻结都不等于证明已接纳。 +启用原生团队路线审批时,用 `inspect --format plan` 读取待审路线和版本,再用 `edit --run RESULT --approve-plan VERSION` 提交批准。旧宿主计划与证明导入记录仍可通过 `inspect --format json` 查看。复现旧任务图编辑(`plan-apply`)、证明导入(`import-proof`)和固定探路实验(`--portfolio-exploration`)时,使用对应历史版本。要把旧研究带入新运行,可以通过 `--continuation-source-run` 附入保存的源码和笔记,由新运行重新检查可用的 Lean 声明。 ### 6. 同时求解多道题 @@ -238,7 +210,7 @@ bun run math import-proof --run "$MATH_RUN_ROOT/result.json" \ ```json { - "args": ["bun", "/absolute/path/to/theorem-os/out/main/math-solver.js", "--workspace", "/runs/q1/workspace", "--task-file", "/runs/q1/task.md", "--output", "/runs/q1/result.json", "--build-manifest", "/absolute/path/to/manifest.json", "--workers", "4"] + "args": ["bun", "/absolute/path/to/theorem-os/out/main/math-solver.js", "--workspace", "/runs/q1/workspace", "--task-file", "/runs/q1/task.md", "--output", "/runs/q1/result.json", "--build-manifest", "/absolute/path/to/manifest.json", "--agent-team", "4"] } ``` @@ -255,10 +227,16 @@ bun run math batch \ 默认不限制空闲时间(`--idle-timeout-seconds 0`)。显式设置后,某题日志连续 N 秒没有增长时会被终止并记为 `stalled`:它不占用并发槽,也不会让批次退出码变为失败,便于无人值守批跑在有限尝试后继续后面的题。模型单轮可能长时间没有输出,阈值应大于最慢的单轮耗时。 -启动文件可选 `cwd` 和 `envFile`,路径相对启动文件所在目录解析;默认工作目录为启动文件所在目录,环境继承调用者。需要恢复时在对应题目的参数中添加 `--resume`,并为新批次指定新的 `--output`。Ctrl+C 会通知运行中的求解器保存退出,并停止启动排队题目;30 秒后仍未退出的进程会被强制停止。并发题数与每题 `--workers` 一起决定资源占用。 +启动文件可选 `cwd` 和 `envFile`,路径相对启动文件所在目录解析;默认工作目录为启动文件所在目录,环境继承调用者。需要恢复时在对应题目的参数中添加 `--resume`,并为新批次指定新的 `--output`。Ctrl+C 会通知运行中的求解器保存退出,并停止启动排队题目;30 秒后仍未退出的进程会被强制停止。并发题数与每题 `--agent-team` 一起决定资源占用。 ## 协作方式 +新建协作由 Codex Lead 通过原生工具派工、通信和恢复任务。TheoremOS 提供隔离工作区、证明交付检查、成果采纳、共享预算和独立 Lean 验收。Lead 按题目选择角色和分工,团队人数参数设置名额上限。 + +### 历史宿主调度器 + +以下固定角色和任务图用于解读已保存的旧运行。续跑、修改任务计划和复现对照实验均使用对应的固定历史版本。 + ```mermaid flowchart LR P[公开题目与固定环境] --> L[Lead:任务与依赖] @@ -347,11 +325,11 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 | --- | --- | --- | | `--model` | `deepseek-flash` | 所选 provider 提供的模型 ID | | `--effort` | `high` | 推理强度(Sub2API DeepSeek 支持 low/high/max) | -| `--workers` | `4` | Agent 总数,支持 1–8;四人以上增加专门的辅助引理 Prover | +| `--agent-team` | `4`(Codex) | 原生团队人数上限,含 Lead,支持 2–8 人 | +| `--workers 1` | 无 | 显式启动单人研究。其他后端默认单人 | +| `--plan-approval` | 关闭 | 审批 Lead 的首轮路线后开始证明 | | `--method` | `direct` | 仅支持 `direct`,保留以兼容已有命令 | -| `--coordination` | `cooperative` | 协作,或 `independent` 独立并行尝试 | | `--continuation-manifest` | 无 | 新建时绑定显式历史附件;恢复时沿用同一只读快照 | -| `--scheduler` | `plan` | 按计划顺序调度;`critical-path` 按依赖链排序;`continuation` 优先承接已证成果的主路径任务 | | `--prepare-timeout-seconds` | `0` | 环境准备与依赖预编译预算 | | `--max-run-seconds` | `0` | 准备完成后的共享解题时间预算 | | `--max-turns` | `0` | 所有 Agent 合计模型调度次数 | @@ -360,6 +338,8 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 | `--proof-timeout-seconds` | `0` | 单次宿主证明检查预算;超时保存可恢复检查点 | | `--evaluator-timeout-seconds` | `0` | 集成后 Lean 复核与最终评测共享的独立时间预算 | +CLI 先用 `inspect --run RESULT --format plan` 查看待审路线和版本,再用 `edit --run RESULT --approve-plan VERSION` 提交批准。等待批准时暂停解题计时。旧调度器的对照实验使用生成原计划时固定的版本。新版可以读取已有实验报告。 + `--prepare-timeout-seconds`、`--max-run-seconds`、`--max-turns`、`--max-turn-seconds`、`--proof-timeout-seconds` 与 `--evaluator-timeout-seconds` 在 CLI 中均默认为 `0`,表示不限。可以分别设置解题、证明检查和最终评测的时限。显式设置证明检查时限后,同一源码、任务和环境的检查超时会保留候选,恢复时逐次延长检查时间,最多 24 小时。 `--max-total-tokens` 包含规划、研究、证明和审阅角色,按跨线程累计消费计算;恢复时继续使用历史用量,省略参数时保留已存额度。它依据 provider 的事后通知阻止新请求,不能保证并发在途消费不超过阈值。报告保留超额与用量完整性;有限额度下缺失已执行请求的用量会停止继续派发。旧运行未记录逐轮用量完整性,不能直接当作严格 token 对照。默认不限 token,不为已有长跑增加停止条件。原生 provider 的用量按完整 turn 记账:turn 被 `--max-turn-seconds` 截断时该轮用量记为不完整,有限额度会以 usage-unavailable 停止;需要有限 token 额度时应同时放宽 `--max-turn-seconds`(或设为 0)。 @@ -402,13 +382,10 @@ bun run math bootstrap-lean-eval --help | `informalize` | 已编译的 Lean 证明 → 逐步对应 Lean 声明的自然语言证明,宿主校验引用与原文摘录,独立审核查漏步与编造;见 [证明讲解](informalization.md) | | `library-pack` | 从保存运行抽取已检查的 owned 模块,或从本地上游仓库原样回移文件,生成库包([规则](solver-modules.md)) | | `run` | 启动、预检或恢复运行 | -| `inspect` | 查看存档研究报告,导出 JSON 或带版本的可编辑计划 | -| `edit` | 校验并提交人工计划修改,支持 `--dry-run` | -| `import-proof` | 将纯 Lean 声明排队给待处理引理,由宿主冻结、检查并合并,支持 `--dry-run` | -| `compare` | 准备、运行并汇总固定预算的单 Agent / 独立并行 / 协作对照 | +| `inspect` | 查看存档研究报告,导出 JSON 或带版本的路线 | +| `edit` | 批准原生团队发布的首轮路线版本 | +| `compare` | 读取和检查已保存的对照实验报告 | | `check-lean` | 获取局部诊断、预检闭合类型或具体应用表达式 | -| `proof-search` | 在当前分配的 helper 上执行有界 Lean tactic 分支,保存并恢复完整证明状态 | -| `research-observe` | 即时交付研究观察和完整 Lean 探针,可同时保留当前 owned 源码 | | `continuation` | 按摘要及附件 ID 分页读取冻结的续跑材料 | | `search-lean` | 检索已验证的本地 Lean 包声明 | | `knowledge` | [导入、搜索和读取历史已检查定理](theorem-knowledge.md);显式 enrich 补采类型与引用,consumers 回读历史应用链 | @@ -426,21 +403,7 @@ bun run math check-lean \ `check-lean` 默认超时为 `0`(等待完成),保留失败退出码和最早错误;其诊断仅用于局部修复。 -`proof-search` 从当前 worker 的 `COOPERATION.json` 读取任务、目标和环境身份,仅支持已分配的闭合 helper lemma。请求文件指定分支和本次预算,例如: - -```json -{"branches":[{"tactics":["intro n","rfl"]}],"limits":{"timeoutMs":30000,"maxTransitions":8}} -``` - -```bash -bun run math proof-search --worktree /PATH/worker --request-file /PATH/request.json -``` - -返回的 `checkpoint: {path,digest}` 可放入下次请求的 `resume`;分支的 `from` 可指向已保存节点。恢复所需的 tactic 重放计入预算。宿主保留断点与源码,任务或环境改变时拒绝套用旧状态。候选仅为建议,仍须写入任务文件并经过 ready、停写冻结、Lean 检查和原目标 S3 验收。 - -搜索后端使用固定 Pantograph 源码构建,清单由 `DEEPSCIENTIST_MATH_PANTOGRAPH_MANIFEST` 显式指定。当前接受分别为 Lean 4.33.0 或 4.33.1 编译的产物,项目工具链必须与后端精确一致;需要宿主提供的 sealed 依赖环境和隔离 worker。Web 镜像为 Mathlib 环境装配 4.33.0 后端,标准 Lean 环境暂不启用。未配置或不兼容时命令返回 `unavailable`,不自动下载或升级。导入 Aesop 的项目可使用 `aesop (config := { terminal := false })` 保留未闭合状态。 - -研究者可用 `research-observe --worktree /PATH/worker --finding /PATH/finding.json --probe /PATH/probe.lean` 即时交付观察,`--probe` 可重复,`--snapshot-sources` 保留当前 owned 源码。结构化 `nextCheck` 由宿主绑定当前任务和环境后派发;检查结果仍需 Lead 作出继续、修改或停止的决定。 +旧任务图的 `proof-search` 与 `research-observe` 依赖固定的 worker assignment。复现实验时使用对应历史运行时。原生团队可在独立工作树运行 Lean 探针,通过 Codex 消息分享诊断,并保存可复查的源码与研究笔记。 数学 worker 的临时目录为工作树根的 `.scratch/tmp`,由 shell 的 `TMPDIR` 指向;`/tmp` 在沙箱内只读。创建探针前运行 `mkdir -p "$TMPDIR"`,并把临时 Lean 文件、备份和诊断输出保存在该目录。宿主检查前会清理 `.scratch`,可复用代码和结论需先保存在根目录 `RESEARCH.md` 或已有的 owned Lean 文件中。 @@ -461,32 +424,30 @@ bun run math check-lean \ 对照报告可用 `compare --phase check-report --directory DIR` 只读核对快照;续跑后旧报告标为过期,重新生成会保留 `report.json.history/`。预算等身份改变的续跑即使通过,也不会计入原固定预算对照。 -`compare` 和 `sample-putnam` 的 `--phase prepare` 支持 `--knowledge-base FILE`,冻结目录及源码对象,并向每次运行透传同一快照。`--knowledge-mode transfer` 为默认,拒绝可识别的目标题目来源、目标条目和源码声明及同题路线记忆;同题历史恢复显式使用 `--knowledge-mode recovery`。后续 run/report 沿用计划,目录或身份变化不能静默续跑。报告中的 `knowledgeFunnel` 区分检索命中、进入上下文、模型选择、应用检查与原题闭合;旧记录缺失保持未知,观测本身不证明解题收益。完整用法见[定理知识库](theorem-knowledge.md)。 +在实验固定的历史版本中,`compare` 和 `sample-putnam` 的 `--phase prepare` 支持 `--knowledge-base FILE`,冻结目录及源码对象,并向每次运行透传同一快照。`--knowledge-mode transfer` 为默认,拒绝可识别的目标题目来源、目标条目和源码声明及同题路线记忆;同题历史恢复显式使用 `--knowledge-mode recovery`。后续 run/report 沿用计划,目录或身份变化不能静默续跑。报告中的 `knowledgeFunnel` 区分检索命中、进入上下文、模型选择、应用检查与原题闭合;旧记录缺失保持未知,观测本身不证明解题收益。完整用法见[定理知识库](theorem-knowledge.md)。 ## 架构与开发 -研究组件的职责见[组件模型](../README.md#组件模型),输入、产物及验收边界见[解题模块与交接协议](solver-modules.md),扩展示例见[替换一个组件](../examples/components/README.md)。入口在 [run.ts](../src/solver/run.ts),Agent 执行循环在 [research.ts](../src/solver/research.ts),异步协作与集成在 [cooperation.ts](../src/solver/cooperation.ts)。 +运行入口在 [run.ts](../src/solver/run.ts),会话执行和恢复在 [research.ts](../src/solver/research.ts),原生团队的隔离与交付在 [agentTeam.ts](../src/solver/agentTeam.ts)。旧任务图实验的契约与验收边界见[解题模块与交接协议](solver-modules.md)。 | 模块 | 职责 | 实现 | | --- | --- | --- | | M1 执行 | 在指定隔离工作区执行模型轮次,记录候选与来源 | [execution.ts](../src/solver/modules/execution.ts) | | M2 证据 | 固定版本、精确声明的 Lean 证据与局部义务检查 | [evidence.ts](../src/solver/modules/evidence.ts)、[cooperativeProof.ts](../src/solver/cooperativeProof.ts) | -| M3 搜索调度 | 检查依赖与分配可行性、路线预算、继续 / 停止及重试 | [search.ts](../src/solver/modules/search.ts)、[value.ts](../src/solver/modules/value.ts) | +| M3 搜索调度 | 原生团队由 Lead 选择路线。旧任务图使用依赖与任务排序策略 | [search.ts](../src/solver/modules/search.ts)、[value.ts](../src/solver/modules/value.ts) | | M4 上下文 | 完整必需接口、工作契约、未决提案、反馈与省略清单 | [context.ts](../src/solver/modules/context.ts)、[contextCompiler.ts](../src/solver/contextCompiler.ts) | -| M5 职责分配 | 在存活工作槽中匹配职责、显式负责人和路线约束 | [organization.ts](../src/solver/modules/organization.ts) | +| M5 职责分配 | 原生团队由 Lead 分派职责。旧任务图匹配工作槽、负责人和路线约束 | [organization.ts](../src/solver/modules/organization.ts) | | S1 任务与成果档案 | 保存与恢复候选、回执、失败和运行状态 | [archive.ts](../src/solver/archive.ts) | | S3 环境与评测合同 | 冻结题目,集成后重检并独立评测 | [problem.ts](../src/solver/problem.ts)、[evaluation.ts](../src/solver/evaluation.ts)、[src/math/](../src/math/) | -[index.ts](../src/solver/modules/index.ts) 绑定默认模块与版本;`runSolver(args, root, modules)` 支持替换模块,模块版本参与恢复身份。宿主固定执行源码边界检查、总预算限制和最终验收。当前 M3 采用规则与依赖调度,S2 跨任务学习尚未实现。 - -命令行可用 `--scheduler critical-path` 同时替换 M3 排序和 M5 分配,按通往未完成原题目标的最长依赖链排序,同长度时优先覆盖更多目标的任务,由 Researcher 和 Engineer 共同领取。显式负责人、路线限制和恢复归属仍然生效;链长只作启发式排序,不预测证明耗时。模块版本写入状态,恢复时校验。这些策略尚无性能提升结论。[三组对照实验](../examples/imo2026/COMPARISON.md) 提供固定题目、模型和总预算的准备、运行与汇总步骤,保留失败、缺失记录和用量缺口。 +[index.ts](../src/solver/modules/index.ts) 记录模块契约和版本。宿主继续执行源码边界检查、总预算限制和独立验收。S2 跨任务学习尚未实现。 -`--scheduler continuation` 优先推进通往未完成原题、能够使用当前已证引理的就绪任务,再推进主路径的核心缺口;两项主路径工作并行时,为其他就绪路线保留一个探索机会。负责人、依赖、路线和固定版本检查继续生效。Lead、证明角色与 `inspect` 报告会看到原题的未闭合依赖前沿,并分别列出计划消费者、Lean 回执中的证明引用、声明引用和条件性引用。未记录消费者不代表引理无用;这些摘要不提供完成百分比或新的证明验收。重复两次交付未更新的继承研究笔记会交给 Lead 决策,正常长研究与 checkpoint 不按此计数。 +历史 `--scheduler critical-path` 和 `--scheduler continuation` 用于比较两种固定任务选择策略。各实验记录保留模型、预算、模块版本和用量缺口。复现步骤见[三组对照实验](../examples/imo2026/COMPARISON.md)。 Codex stdio 协议适配在 [codexSession.ts](../src/runtime/codexSession.ts)。
    -Agent 交付协议与提前共享 +旧任务图档案中的 Agent 交付协议与提前共享 agent 的常用协议只有两步:读取任务,写出成果。需要结构化回复时,在 `RESEARCH.md` 中保留一个 `math` JSON 代码块;普通说明可写在代码块外。 diff --git a/docs/web-operations.md b/docs/web-operations.md index 20f09ed0..eed27f80 100644 --- a/docs/web-operations.md +++ b/docs/web-operations.md @@ -12,7 +12,7 @@ 推送 `v*` 标签或运行 `gh workflow run images.yml --ref main` 会触发 `Publish workbench images`。发布流程在同一提交上调用上述验证,通过后分别构建和推送 web、worker、tex。三个镜像都使用完整源码 SHA 作为 GHCR 标签,并写入 OCI revision。Web 和 worker 还设置 `THEOREMOS_SOURCE_COMMIT`,Web 前端的 `build-info.json` 也记录这个 SHA。三张镜像均推送成功后,流程才上传 `image-release-`,其中 `image-release.json` 记录提交及三个 registry digest。 -本地可执行同一组无模型求解器回归,包含协作回放脚本的研究决策协议检查。Linux CI 与 Worker 构建使用 `scripts/install-elan.sh` 安装固定的 elan 4.2.4,校验官方发布包 SHA-256,并通过 Lean 的发布 JSON 获取工具链,避免旧版 elan 抓取 GitHub 发布页面失败。先安装相应 elan 工具链,再显式选择版本,避免机器上较新的 Lean 候选版替代实际支持的版本: +本地可执行同一组无模型求解器回归。Linux CI 与 Worker 构建使用 `scripts/install-elan.sh` 安装固定的 elan 4.2.4,校验官方发布包 SHA-256,并通过 Lean 的发布 JSON 获取工具链。先安装相应工具链,再显式选择版本。 ```bash THEOREMOS_TEST_LEAN_VERSION=4.33.0 bun run test:solver-reliability @@ -172,11 +172,12 @@ bun scripts/web-operations.ts capacity --research-concurrency 1 默认同时开启一个研究、一个形式化生成、一个后台形式化审核、一个讲解与两个预检查时,容器内存上限合计 **56 GiB**、CPU 上限合计 **12 核**,建议工作盘余量 **120 GiB**。这是配置上限之和,不代表实际使用量或性能承诺。调整研究并发时,必须一起考虑其他队列和模型网关限制。 -发布演练使用离线 fixture 驱动已有真实 Docker/Lean 测试,不使用真实 Key: +发布演练可分别运行真实 Docker 与 Lean 检查,以及原生团队的浏览器回归。两项测试均使用离线夹具。 ```bash bun scripts/test-web-runtime.ts --case mathlib-valid -bun run test:web-cooperative-runtime +bun run build:web +bun scripts/test-web-native-team.ts ``` 默认模型的首次流程另用隔离、匿名的本地工作台验收;先构建同一源码的 web / worker 镜像并启动独立数据目录,然后显式允许真实调用: diff --git a/docs/web-workbench.md b/docs/web-workbench.md index 1ba62262..dc590042 100644 --- a/docs/web-workbench.md +++ b/docs/web-workbench.md @@ -14,9 +14,7 @@ 首次构建需联网下载 Bun、Codex CLI、固定 Lean 工具链、Mathlib 源码和预编译依赖,镜像较大,下载可能较慢。构建会复用下载缓存、重试失败下载,并执行完整 Mathlib 构建和 `import Mathlib` / `ring` 探针。 -worker 还通过 `scripts/build-pantograph.ts` 从固定 Pantograph commit `0ee70917fb93a5421157119362ecde806a4d881b` 构建 `repl`。脚本校验源码归档 SHA-256,使用镜像已安装的 Lean 4.33.0 重新编译,并将可执行文件、Lean 库、许可证、构建来源和逐文件摘要清单安装到只读的 `/opt/theoremos-pantograph`。上游源码的 4.33.1 工具链选择只在临时构建目录改为 4.33.0;题目和 Mathlib 的固定环境保持原样,运行时不会下载或构建后端。 - -目前仅 Mathlib worker 注入 `DEEPSCIENTIST_MATH_PANTOGRAPH_MANIFEST`,由运行时校验产物并把后端摘要纳入运行身份。Agent 通过独立工具包中的 `proof-search` 对已物化、类型闭合的普通 helper lemma 执行有预算的 tactic 搜索。候选和断点是 advisory,仍须经过 ready、停写、冻结、独立 Lean 检查、集成和 S3。标准库 worker 没有 sealed/FUSE 环境,因此保持后端未配置,调用会返回 `proof_search_backend_not_configured`;未放宽其设备或文件权限。 +固定任务图曾通过 Pantograph 的 `proof-search` 分支搜索已分配的 Lean 引理。复现该流程时使用原 Worker 镜像。原生团队在固定 Lean 和 Mathlib 环境中通过自己的工作树探索证明并送交独立检查。 ```bash git clone https://github.com/HuggingMath/theorem-os.git @@ -39,7 +37,7 @@ docker compose -f apps/web/compose.yml -f apps/web/compose.ghcr.yml up -d --no-b 浏览器打开 ,首页显示问题输入框;不预填例题,也不要求先导入原题。TheoremOS 数学环境与 high 是默认值。输入框的「设置」可填写 Key;账号已有 Key 时直接使用。首页的输入框在页面中部,设置向下展开,不盖住标题和输入框,屏幕太矮时滚到可见;对话中的输入框在底部,设置向上展开。在输入框里打字时边框加粗为 2 像素,颜色与静止边框、页面和输入框底色的对比度都在 3:1 以上(浅色 3.68 / 5.05 / 5.42,深色 3.65 / 6.42 / 5.94)。新对话清空输入,普通刷新保留当前标签页的草稿,顶部 Logo 和「新对话」均回到首页。 -输入框优先展示题目,参与方式收在下方紧凑菜单中。默认沿用「共同推进」,题意与初始计划由用户确认;可明确切换为「自动推进」。预算默认留空表示不限,选择与预算随当前草稿保存。 +输入框优先展示题目。新的多人证明由 Codex 原生团队自动推进。输入框下方可选择「先审路线再开工」。从自然语言开始时,先确认生成的 Lean 陈述,再审核 Lead 发布的首轮路线。直接提交 Lean 时只需审核路线。等待批准期间暂停解题计时。预算默认留空表示不限,审批选择与预算随草稿保存。 - **默认版**:直接输入自然语言或 TeX 原题,发送后直接生成 Lean 陈述,编译通过后立即提供代码并启动证明研究,语义审核在后台并行进行;最后显示证明与独立验收结果。 - **进阶版**:通过输入框旁的 Lean 入口直接编写、粘贴或导入形式化题目,只有此模式校验源码。自然语言与 Lean 草稿分别保留。 @@ -67,7 +65,7 @@ docker compose -f apps/web/compose.yml -f apps/web/compose.ghcr.yml up -d --no-b 消息提到当前任务中真实存在的定理时,附上对应引理入口。点击后路线图定位到该任务节点,可继续查看 Lean 源码与检查记录;尚未集成的引理打开对应任务版本的已保存源码。返回对话恢复来源消息、焦点和草稿;不会把模型随口提到的名字编成路线图节点。 -追问用于解释和讨论,回答本身不执行 Lean 或修改原题。运行中可在输入框点「发给证明任务」,或把已有追问「作为证明要求」,选择任务负责人或具体引理后提交;原文、目标版本、观察身份和真实投递回执保存在会话中。排队、送达、暂缓或拒绝状态随原回执更新;结果未知时只核对原提交,不换 ID 重复投递。任务版本变化时须核对内容并确认新版本。修改题目创建新任务,不覆盖冻结原题。「停止回答」只中止当前问答,「停止解题」使用任务取消流程。切换或新建会话不会取消后台研究。消息回答完成不表示证明通过,只有完整原题的独立 Lean 验收通过才显示通过。 +追问用于解释和讨论。当前团队由 Lead 接续证明工作,需要用户审核时会显示待审的首轮路线。旧任务的指导内容和实际投递回执仍随会话显示。修改题目会创建新的冻结任务。「停止回答」中止当前问答,「停止解题」取消证明运行。切换或新建会话时,原证明继续在后台运行。独立 Lean 验收通过后才显示证明通过。 公开解题说明中的「追问这一步」将所选说明、前提、Lean 陈述及记录的完整任务或候选版本放到讨论草稿中,保留原有问题文字。引用是点击时的快照,详情收起时也会带上已保存的数学内容;重复点击同一份内容不会重复插入。输入框聚焦到草稿末尾,进展暂停自动跟随,阅读位置与展开选择保留。引用可直接编辑,刷新或切回会话后仍在;点击引用只准备草稿,由用户发送。证明指导模式下隐藏此入口。 @@ -89,7 +87,7 @@ docker compose -f apps/web/compose.yml -f apps/web/compose.ghcr.yml up -d --no-b 例题数据统一维护在 `apps/web/problemExamples.ts`。「自然数加零」使用 `theorem add_zero_trial (n : Nat) : n + 0 = n := by sorry`,模板及替换为 `by rfl` 的证明均通过固定 Lean 4.33.0 标准库检查;其余四个 Lean 声明已通过固定 Mathlib 环境的离线编译检查。界面中的例题证明位置保留 `sorry`,声明可编译不表示证明已完成。`test:web-formalize` 覆盖两种入口、中英文原文、替换确认、环境匹配、显式提交和窄屏布局。 -提交后停留在对话内,点击结果入口查看「研究协作」。任务依赖、Agent 分工、源码与检查回执、人工指导、计划修改和知识检索均读取实际运行;尚未建立计划时显示等待状态。独立并行运行也可查看已有观测,协作计划编辑需要运行时提供对应计划。 +提交后停留在对话内,点击结果入口查看「研究协作」。这里显示实际保存的任务、Agent 分工、源码与检查回执,也可检索知识库。旧任务的计划修改和指导记录仍可查阅。 工作台顶栏、欢迎页和命令面板提供「经典题库」入口,所有账户均可查看同一份 OpenAI Math 本地验收通过的解答,包含原题、最终 Lean 证明、辅助模块、验收证据和历史解题过程。浏览与下载无需 API Key,也无需先创建研究。题库是随 Web 镜像构建的共享只读档案,不计入个人运行记录或配额;个人研究仍按账户隔离。题库支持中英文和按题下载,返回工作台保留原标签页中的草稿与研究。 @@ -115,6 +113,8 @@ docker compose -f apps/web/compose.yml -f apps/web/compose.ghcr.yml up -d --no-b ## 数学协作流程 +原生团队由 Codex Lead 分工。如已选择「先审路线再开工」,先查看并批准 Lead 发布的路线版本。批准后由团队继续求解。依赖图、指导和计划编辑记录只在档案提供相应证据时显示。要再次使用旧任务图的指导和编辑功能,使用对应的历史服务与 Worker。 + 「研究协作」以数学任务组织证明过程。实线表示同一路线所需的前置任务,虚线表示可选择的证明路线;桌面可切换依赖图和任务列表,手机直接显示列表。可组合路线、任务状态和关键词筛选,关键词覆盖任务、类型、负责人和分组。界面显示匹配数量,空结果提供清除筛选入口;当前路线从计划移除时保留标记,等待重新选择。筛选不会改动检查器中的选择,所选任务不在结果中时提供明确提示和显示入口;历史合同保留记录版本。 选择任务后可查看完整类型、前提、计划依赖、实际记录的引用、条件性结果、阻塞、负责 Agent 和交付材料。列表中选择任务会直接定位详情,「返回任务列表」恢复原入口、筛选和阅读位置;宽屏依赖图保留卡片焦点,切换任务时将检查器滚回标题。视图选择和阅读状态按研究分别保留,轮询不主动跳转。Agent 面板显示固定角色、当前会话角色、任务和等待原因,点击任务可返回检查器。 @@ -143,25 +143,7 @@ docker compose -f apps/web/compose.yml -f apps/web/compose.ghcr.yml up -d --no-b 在任务检查器打开源码后,可从同一任务实际保存的快照中选择基线和对照,查看逐行差异或完整源码。同一任务版本的不同 commit 也分别保留,两侧显示任务版本、commit、源码摘要、环境摘要和文件。轮询新增快照时保留已选两侧及阅读位置;切换任务后清除旧产物。只有一份快照时显示源码,差异超出展示预算时仍可分别读取完整文本。对比本身不执行检查,也不改变验收状态。 -自由指导可发给 Lead、指定 Agent 或指定版本的任务。指导记录区分排队、暂缓、已投递与失败,显示投递对象及原因;已投递表示运行时接受通知,采纳与证明结果另行判断。指导不会直接修改任务合同。 - -每份指导最多 4000 字符。知识、数学变化或审阅引用若超出剩余空间,会保留原草稿和接收方并提示未加入;缩短草稿后可重新引用,不截断引用身份。 - -输入时显示当前字数;发送期间显示处理状态。断线、运行结束、等待观察、任务版本变化或原提交待核对时,输入区会说明无法发送的原因,草稿继续保留。 - -选择任务后,指导草稿固定到当时的任务版本。轮询发现版本变化时,展示草稿版本与当前版本,须核对内容并点击「确认当前任务版本」后发送;任务或 Agent 被移除时保留原目标,等待明确改选。每条已记录指导展示任务版本及其依据的观测序号和摘要。 - -指导提交响应丢失或结果未知时,保留原 ID、接收方、任务版本、内容与观测引用,并先只读查询命令回执。可继续编辑下一份草稿,原提交确认前不能发送第二份指导。「核对指导回执」不会重发;只有读取明确返回 404 时显示「重试原提交」,点击后再次读取,仍缺失才按原内容和 ID 重试。读取失败或已存 unknown 回执均不会触发重发。运行时明确拒绝会保留草稿并解除等待,传输或存储失败仍需核对;已有指导可按原 ID 读取,不因观测保留窗口过期而误报拒绝。各研究分别保留草稿和等待状态,迟到回执不会清空后续编辑;这些未提交草稿与待核对提交仅保留在当前页面,刷新前应完成核对。 - -「编辑计划」支持任务暂停/恢复、owner 和组 engineer 调整、任务及依赖增删、证明路线变更,也保留完整计划 JSON 编辑。先预览变化与受影响任务,再提交带 `baseVersion` 的计划。版本冲突时保留草稿,须显式重新核对基线;提交结果、host 应用状态、相关证明的重新检查分别显示。运行中的固定 Agent 人数及身份不在此处修改。命令响应不确定时按原命令 ID 查询回执,不自动创建第二份修改。 - -常用表单可新增研究、证明草图或引理,调整类型、负责人、目标、AND 依赖、前提、证明位置、任务分组和共享范围。「OR 证明路线」分别设置原始目标、收尾引理与路线前提;路线前提还须属于收尾引理的普通依赖闭包。「任务分组与 Engineer」可增删分组、指定 Engineer、调整组调度及轮次和并发上限。新增分组会保留隐式的默认 main 组;跨组依赖需要对应材料允许整个问题共享。原始目标的声明、文件和类型只读,不能由常用表单删除。切换研究或草图为引理时需补充精确类型;切回提示性任务时清除证明专用字段。既有负责人会保留,是否可接受仍由运行时校验。 - -删除仍被任务或路线引用的辅助任务、删除仍有成员的分组时,表单列出引用并保留草稿,先调整引用或迁移成员再删除。所有结构操作只改本地完整提案,修改后须重新预览才能提交;表单与高级 JSON 双向同步,JSON 无法解析时暂停表单编辑以保留原文。轮询不会覆盖正在编辑的合同。 - -计划提交响应丢失或状态未知时,页面先只读查询原命令回执。后续观察一旦记录同 ID 的应用或拒绝,编辑器自动确认并清除待核对提示,不需要手动刷新;重新检查的进度与各任务回执也原位更新,保留本地草稿、焦点和已展开的记录。关闭编辑器或切换研究后,重新打开会用当前运行的最新观察核对。 - -仍未确认时,可「核对提交回执」,查询不会重新执行命令。暂未找到回执时,可审阅原提交,再明确选择「重试原提交」:重试先查询,并保留原 ID 与原内容。期间继续修改的草稿单独保留,待原命令结果确认后再预览提交。不同研究的计划草稿、等待状态和回执分别保存;迟到的排队、未知或读取失败响应不会覆盖已观察到的应用结果与重新检查记录。 +历史指导显示投递对象、任务版本和回执状态。历史编辑记录保留请求、应用状态和相关证明的重新检查结果。两类记录均可在归档中复核。 知识检索提供声明、前提、来源、源码、依赖和消费者,区分已记录检查的定理与 advisory finding。可以把引用加入指导草稿。新研究默认使用本账号最新的非空知识目录,并在创建时固定不可变 catalog digest;也可明确选择历史版本或选择不使用历史知识。基于旧运行继续研究时,未明确改选的目录沿用旧运行的固定版本;新环境仍需重新检查历史证据。运行结束或取消前,worker 会尝试导出实际成果,服务保存新 catalog 版本。「归档知识」另保存当前运行的观测、全部已记录事件、各版本源码、检查及命令回执,下载包带摘要和覆盖说明。归档成功或收到新的成果目录后,知识检索会更新可选目录;选择「最新知识目录」时更新当前搜索,明确选择的历史版本会保留。切换目录或搜索时清除旧详情,引用始终绑定实际查看的记录和目录。归档不是可直接恢复执行的 solver checkpoint。 @@ -171,7 +153,7 @@ worker 镜像通过 `scripts/prepare-web-library.ts` 直接调用固定 Lean 编 知识检索以所选任务的精确类型或目标和当前记录的环境摘要作对照,显示历史环境一致、不同或缺失;当前环境缺失时明确显示无法比较。检索保留其他问题中的可复用材料,不自动限定来源问题。切换任务、任务版本或环境会清除旧详情并重新检索,引用附上关联任务及版本。环境或目标文本一致仍属于历史证据,路线发现的适用范围没有完整记录时继续标为未确认。 -研究配置内除浏览器本地方案库外,还提供服务端方案库和实际模块注册表。服务端方案可保存、更新、另存、载入和确认删除,最多保留 12 项;删除释放方案容量并保留当前模块草稿。其他页面修改后的方案须刷新核对再删除;删除响应丢失时先读取服务器结果,不自动重发。注册表列出实现 ID、版本、输入输出合同与适用范围;仅可选择已安装实现,不接受浏览器上传执行代码。M3 的调度实现与 M4 的上下文实现可以选择,自定义文本仍属于策略建议。运行创建时固定实际组件与 method digest,保存方案或编辑草稿只影响后续新运行。 +已有模块方案和实际组件身份随旧运行保存。模块调度对照实验使用各自固定的历史版本。 直接启动默认持久目录为 `out/web-data`;Compose 使用 `research-data` 命名卷保存到 `/var/lib/theorem-os`。同一浏览器会话可在服务重启后继续查看记录、知识和服务端方案。服务重启不会自动恢复求解:未完成运行明确标为中断;正常停止会取消运行,并在删除临时容器前尝试采集证据。默认持久会话闲置 30 天到期,可通过 `THEOREMOS_WEB_SESSION_TTL_SECONDS` 调整。未启用登录时,Cookie 丢失或会话到期后记录随会话删除,没有找回入口;启用登录后记录归属账号,见下节。删除运行会删除其归档及原始运行记录,已导入的知识 catalog 保留为独立版本。 @@ -218,9 +200,8 @@ SMTP 密码只放在环境变量或 `.env` 中,不要写进仓库。服务在 | `GET /api/runs/:id/events?after=N` | 按序号分页读取已保存事件,返回保留范围 | | `GET /api/runs/:id/tasks/:taskId/source?version=V` | 指定任务版本的 owned-file 源码与身份 | | `GET /api/runs/:id/checks/:receiptId` | 已记录的检查回执 | -| `POST /api/runs/:id/guidance` | 提交带幂等 ID 和观测引用的指导 | -| `GET /api/runs/:id/guidance/:guidanceId` | 指导投递状态 | -| `POST /api/runs/:id/edits/preview`、`POST /api/runs/:id/edits` | 预览或提交完整版本化计划 | +| `POST /api/runs/:id/plan-approval` | 用 `{ id, planVersion }` 批准原生团队发布的路线 | +| `GET /api/runs/:id/guidance/:guidanceId` | 查询历史指导投递状态 | | `GET /api/runs/:id/commands/:commandId` | 查询原命令回执、应用或投递状态 | | `POST /api/runs/:id/archive`、`GET /api/runs/:id/archives/:archiveId` | 保存与下载可复核归档 | | `GET /api/runs/:id/download`、`GET /api/runs/:id/snapshot` | 下载完整研究归档或运行快照 | @@ -230,35 +211,12 @@ SMTP 密码只放在环境变量或 `.env` 中,不要写进仓库。服务在 | `POST /api/precheck` | 提交前编译原题:`{ environment, source }` → 状态、待证 sorry 数与诊断;被同一会话的新检查取代时返回 409 | | `GET /api/runs/:id/outline` | 候选证明的结构:原题目标与求解新增的辅助声明、各目标的阐释后类型与公理、已记录的引用关系;没有候选证明时 409 | | `GET /api/runs/:id/verification-kit` | 本地复核压缩包(ZIP):固定版本的 `lean-toolchain` / `lakefile.toml` / `lake-manifest.json`、`Submission.lean`、`Original.lean`、逐目标 `#print axioms` 的 `Check.lean`、中英文 README 与 `report.json`;找不到原题目标时 409 | -| `GET/POST /api/module-plans`、`DELETE /api/module-plans/:id` | 持久方案库与版本冲突检查 | 直接下载和新保存的完整归档使用 `theorem-os.web-archive.v2`。任务、依赖和原生团队证明的源码使用 `{"sha256":"…"}` 引用,按摘要在同一文件的 `sourceBlobs` 对象中查找原文。历史观测、最近观测、命令回执附带的观测和顶层源码索引共用这份原文表。早期 v2 归档的原生团队源码为内联文本。摘要继续记录覆盖范围和证据数量,`summary.digest` 绑定实际导出的内容。旧 v1 归档按保存时的格式和摘要下载。工作台可以从两版归档和 `theorem-os.web-export.v1` 运行快照导入任务草稿,并保留明确选择的「不使用历史知识」。 -### 配置研究模块 - -打开「研究配置 → 模块方案」,或点击草稿模块图中的配置图标,可选择 M3 搜索策略与 M4 上下文范围,并新增自定义策略。每项策略包含名称、所属模块、规则、启用开关及「补充默认建议 / 替换默认建议」。支持 M1 证明构造、M3 搜索决策、M4 上下文选择和 M5 协作与复用;M2 检查及 S3 最终验收保持固定。 +### 历史模块方案 -「模块方案 → 方案库」可命名保存、更新、另存、载入和删除模块组合,同一浏览器最多保留 12 项,每项名称最多 40 个字符。方案库独立于任务草稿,刷新或新建研究后仍保留;仅保存模块配置,不保存任务、Lean 源码、API Key、模型或执行预算。未完成的模块规则也可保存为方案,载入后仍需通过提交校验。 - -载入方案只替换当前模块配置,同步草稿自动保存与模块图。载入后可撤销,恢复载入前的模块配置并保留任务、源码及预算等其他编辑;继续编辑模块、替换草稿、重置、刷新或提交研究后清除该撤销记录。删除已保存方案不修改当前配置,支持恢复最近删除的一项;恢复时若已满 12 项或名称冲突,会保留原库并提示原因。更新或删除其他标签页已经修改的方案时,需要重新选择,避免覆盖较新的内容。 - -方案库使用 `localStorage`,写入通过浏览器 Web Locks 协调多标签页操作,因此需要支持 Web Locks 的浏览器,并以 HTTPS 或 localhost(包括 `127.0.0.1`)访问。缺少支持、存储被禁用或容量不足时会显示失败,损坏的库不会被空库覆盖;研究工作台的其他功能仍可使用。方案保存在当前浏览器,暂不跨设备同步。 - -新增策略默认停用。点击策略右上角的复制按钮,可保留所属模块、策略方式和规则,创建独立副本;副本自动命名并默认停用,可改名、调整规则后再启用。最多保存 8 项,名称最多 40 个字符,单项规则最多 4,000 UTF-8 字节,规则合计最多 16,000 字节;同一模块最多启用一项替换策略,可同时启用多项补充策略。替换仅影响该模块的可配置建议,原题约束、必需数学上下文、角色协议、Lean 检查与独立验收仍会执行。自定义规则作为研究上下文交给模型,不支持上传可执行插件。M5 规则仅在多 Agent、协同模式且实际进入协作上下文时参与;M3 的任务调度预设也仅在协作任务中发挥调度作用。「精简上下文」移除可选材料,保留必需上下文。 - -策略可单项或全部展开、收起,收起时保留名称、所属模块、策略方式及启用开关。通过上下箭头调整列表位置;同一模块的规则按列表顺序加入上下文,跨模块排序不改变研究模块的执行结构。排序随方案保存和复用,校验时会自动展开并定位有问题的策略。 - -删除策略后,可通过模块方案底部的撤销图标恢复最近删除的一项,保留规则、原位置、启用及折叠状态,不覆盖其他策略的新编辑。达到 8 项上限时暂不能恢复。撤销记录仅在当前页面内保留,关闭配置后仍可使用;重置、导入、复用或恢复草稿、刷新及实际提交任务时清除。恢复的策略继续接受替换冲突和规则大小校验。 - -草稿模块图中,点击自定义策略会展开对应规则并定位到详情;详情中的编辑按钮可直接打开该项配置,关闭后返回对应策略。更换所属模块后会定位到新模块,删除后回到模块节点。M1、M3、M4、M5 详情中的新增按钮会创建归属于当前模块的停用策略;达到 8 项上限后禁用新增。已有运行中的模块方案只供查看,不提供编辑或新增入口。 - -草稿模块图的策略列表可直接启停规则,开关与研究配置、草稿保存同步。普通启停保留当前查看的模块、焦点和阅读位置;启用缺少规则或存在替换冲突的策略时,打开配置并定位待修正字段。已有运行隐藏开关,提交期间禁用编辑。 - -手机上从工作区打开研究配置时,关闭配置会返回原工作区;即使未修改配置,也会保留所选模块和策略的阅读状态。提交时回到对话;研究任务校验失败时定位到输入框,配置的关闭事件不会覆盖此次跳转。 - -模块方案随草稿自动保存,并随任务导入、导出、恢复与「基于此题新建研究」复用。提交时固定本次方案,后续草稿修改不影响已有运行。模块图显示停用、不适用、待应用和已应用次数;次数来自规则实际加入编译上下文的事件,不代表模型调用或证明成功,活动日志轮转后仍可查看累计记录。 - -更新已有 Docker 部署时,需要重新构建 worker 和 web 镜像,使两端使用同一版模块配置协议。 +已有运行仍可查看保存在归档中的模块方案和调度记录。新建原生团队由 Lead 负责路线和任务分工。模块方案编辑和调度对照实验使用固定的历史版本,参见[模块对照实验](../examples/components/EXPERIMENTS.md)。 ```bash # 停止服务;未完成任务会被取消并清理容器 @@ -345,7 +303,7 @@ bun run web - 运行中每 1.5 秒采样隔离求解目录中的 `Submission.lean`,变更后通知页面读取最新记录并刷新右侧候选源码,保留滚动位置;实时连接不可用时由轮询同步。快照最多 128 KiB,显示采样时间和 Agent,始终标记尚未验收;最终结果中的证明优先于运行快照。源码支持行号、原题切换、差异对比、复制与下载;只有完整原题通过独立验收才显示“验收证明”。 - 草稿编辑、候选源码刷新和对话追加采用局部更新,保留未变化的节点、焦点与选区;分栏拖动按动画帧合并更新。新进展在对话底部自动跟随,阅读历史时保留位置;手机切换视图期间也保留跟随状态,主动跳到最新进展时遵循减少动态效果设置。 - 新会话、主动切换视图和弹窗使用短过渡;跟随最新进展时,仅最后三条新增事件入场。阅读历史、源码候选更新和无变化轮询不会重复播放;页面隐藏、切换手机面板或启用减少动态效果时会清理动效,立即恢复完整内容。 -- 详情右上角或研究反馈下方可基于此题新建研究,重新载入该次任务固定的原始源码、研究任务、证明环境、模型、知识目录绑定和执行预算,API Key 需重新输入。左侧发送仍创建独立研究,同一运行内的介入使用研究协作中的指导与计划编辑。 +- 详情右上角或研究反馈下方可基于此题新建研究,重新载入原始源码、研究任务、证明环境、模型、知识目录绑定和执行预算。运行内需要的人工确认通过待审的首轮路线完成。 - 「轨迹」里有记录代码的尝试和完整证明可点“从这一版继续”:用同一道题开新草稿,提交后服务器从该账号自己的运行里读出这一版的文件,作为 `theorem-os.continuation-input.v1` 附件(`recorded-not-replayed`)交给每个 Agent 参考;它不是证据,仍要重新通过 Lean 检查。请求只带运行、任务、commit 和名称,源码不经过浏览器,也不写进新运行的记录;新运行的标题下注明从哪一版继续并可回到原运行。 - 未通过的尝试在“看 Lean 反馈”旁有“问为什么”:网页服务读出这一版的代码、未通过检查的 Lean 输出和原题,用这次运行的模型和服务商回答读者的问题(`POST /api/runs/:id/explain`)。Key 依次取本次填写、账号保存、管理员的服务器 Key;每个问题按服务商计费,不计入运行预算,也不会送到运行里。问答只留在当前页面,服务器不保存;每个账号同时只答一个问题、10 分钟内最多 20 个,单次最长 3 分钟,关闭面板即停止。回答只作解释,没有经过 Lean 检查。 - 有候选源码的运行支持逐行差异对比,展示原题 / 候选行号与新增、删除统计,默认折叠未改动内容并保留三行上下文,可展开和跳转更改位置。换行格式、末尾缺失换行分别标明;复制与下载仍保留完整候选原文。对比不改变验收结论。浏览器内使用 `diff` 库,在 80 ms / 2,000 编辑步骤预算内生成对比,最多展示 2,000 行;超限会提示,完整源码仍可查看和下载。 @@ -360,7 +318,7 @@ bun run web - 历史记录可组合关键词和状态筛选,关键词匹配题目、研究任务、模型、运行 ID、源码和证明环境;只有完成独立验收的记录会进入“验收通过”。状态刷新复用已有记录,保留焦点与未变化文字的选区;新增或移除上方记录时保留正在阅读的行,关闭抽屉再打开也可继续阅读。聚焦记录退出筛选时,焦点转到邻近记录,列表为空则返回搜索框,不自动切换当前详情。主动改变搜索或状态筛选时回到列表顶部;筛选不会清掉当前查看的详情,新任务提交成功后会清除筛选并选中新运行。 - 活动页支持本地关键词与事件类型组合筛选,关键词按文本匹配内容和事件名,不区分大小写。最新记录在前,默认跟随顶部;向下阅读会自动暂停,新增匹配以数量提示,可点击“返回最新”继续跟随。刷新复用已有记录并保持阅读行、选区和筛选框焦点;同一运行切换标签或手机面板后可继续阅读,换运行时重置筛选。仅保留最近 200 条活动,早期记录移出时明确提示,当前选中的事件类型即使没有剩余记录也会保留。可在运行中下载当前筛选结果的活动 JSON,包含运行 ID、筛选条件与保留范围;下载在浏览器生成,不包含 API Key,也不代表完整运行档案。 - 报告页默认展示验收摘要,分别列出候选检查与独立验收、定理级诊断、已有的研究轮次 / 耗时 / Token 统计和验收凭据。单条诊断超过 4000 字符时显示截断提示,可直接打开原始报告;原始 JSON 保留报告中收到的字段,可查看、复制和下载,不代表执行器未提供的日志也已保存。诊断按完整文本去重,相同开头、不同结尾的记录分别保留。缺失的统计不会被补成零,候选检查、单个定理或验收阶段的通过记录不会替代最终结论;最终成功同时要求任务结束和 `evaluated_passed`。 -- 首次进入(账号或会话还没有运行记录)时,欢迎页依次给出示例运行入口和三步说明:写下原题、连接模型、等待验收。示例运行 `00000000-0000-4000-8000-00000000a001` 无需 API Key,打开后停在概览页,标为「示例 · 只读」。它不在 `/api/runs` 中、不计入运行数量,也不会成为恢复位置;读取接口与普通运行相同(详情、观察、任务源码、检查回执、活动、下载),写入一律返回 403。页面写明其中的 Agent 是离线脚本,环境、任务协作、Lean 检查和独立验收是真实执行的。「用这道题开始研究」会把题目、环境和执行配置填进新草稿,保留访问者自己的服务商、模型和推理强度。示例文件是 `apps/web/sample/run.json`,由 `test:web-cooperative-runtime` 的档案生成:`bun scripts/build-web-sample.ts [archive.json]`。脚本会替换运行 ID 和容器路径,并检查文件里没有宿主路径、镜像摘要或 Key;文件缺失或格式不符时入口自动隐藏。 +- 首次进入(账号或会话还没有运行记录)时,欢迎页依次给出示例运行入口和三步说明:写下原题、连接模型、等待验收。示例运行 `00000000-0000-4000-8000-00000000a001` 无需 API Key,打开后停在概览页,标为「示例 · 只读」。它不在 `/api/runs` 中、不计入运行数量,也不会成为恢复位置;读取接口与普通运行相同(详情、观察、任务源码、检查回执、活动、下载),写入一律返回 403。页面写明其中的 Agent 是离线脚本,环境、任务协作、Lean 检查和独立验收是真实执行的。「用这道题开始研究」会把题目、环境和执行配置填进新草稿,保留访问者自己的服务商、模型和推理强度。示例文件是 `apps/web/sample/run.json`。使用 `bun scripts/build-web-sample.ts /path/to/archive.json` 可以从已有的历史档案重新生成。脚本会替换运行 ID 和容器路径,并检查文件里没有宿主路径、镜像摘要或 Key;文件缺失或格式不符时入口自动隐藏。 - 运行时术语(原题、独立验收、任务计划、观察、回执、模块方案等)在 `apps/web/client/glossary.ts` 统一用白话解释。界面上的 `?` 按钮打开一条说明:焦点留在按钮上,Esc 或点击别处关闭;在设置对话框里也能显示在最上层。顶栏的帮助按钮、命令面板「术语说明」和欢迎页都能打开完整术语表;从某条说明进入时,术语表直接定位到这一项。 - 使用说明页 `guide.html` 是一份静态页面:五步开始、运行时的六个标签页、各种结果的含义、运行结束后的复核 / 分享 / 复用 / 导入导出、快捷键、Key 与记录的归属。欢迎页、术语表顶部和命令面板「使用说明」在新标签页打开它,正在编辑的草稿不受影响。页面不需要登录,跟随外观与界面语言(英文在 `apps/web/i18n/guide.ts`),右上角可回到工作台。界面文案改动时要同步这页的描述。 - 工作台、登录页和分享页有中文与英文两种界面。首次访问按浏览器语言选择(`zh*` 用中文,其余用英文);顶栏、登录页底部、分享页右上角和命令面板都能切换,选择保存在 `localStorage` 的 `theorem-os.web-locale.v1`,切换前先保存草稿。中文原文就是翻译键:`t('中文', …)` 查 `apps/web/i18n/` 下的英文词典,`{0}` 依次替换参数,数量为 1 时英文名词取单数。服务端仍只存中文:事件消息、运行状态、模板名、分享标签和模块方案校验在浏览器里经 `localizeText` 按原文对照翻译,服务端错误信息保持中文。研究任务、标题、Lean 源码和 Agent 产出不翻译,相应元素带 `translate="no"`。`bun scripts/web-i18n.ts` 列出缺少英文的界面文字和写在 `t()` 之外的中文,`tests/webI18n.test.ts` 要求两者都为空、英文里没有中文、占位符一致且没有多余词条。 @@ -371,7 +329,7 @@ bun run web - 已完成、已取消或发生错误的历史记录可在确认后单条删除,删除前可下载包含原始题目与诊断的运行档案,即使任务尚未生成结果。排队或运行中的任务不能删除;删除不会自动取消任务。删除后释放会话的历史容量,不影响其他任务。删除请求的响应丢失时只刷新历史核对,不自动重发。 - 网络中断或请求超过 15 秒时显示连接状态并禁用提交,已有表单仍可编辑;网络恢复、返回页面或手动重连时自动刷新会话和历史。创建任务与取消请求均不自动重发;提交响应丢失时提示结果未确认,并通过历史列表核对,避免重复创建任务。恢复连接不重置未提交的源码、任务或模型配置。 - 取消请求等待期间,对话停止按钮、详情操作和运行状态栏同步显示正在取消,重复操作不会再次发送请求。若轮询已确认该任务取消或结束,迟到的取消响应错误不会再将结果标为未知,也不会因此断线重连;无法确认时仍保留核对提示,不自动重发取消请求。 -- 可配置 1–4 个 Agent、任务协作 / 独立并行、1–20 轮和 30–900 秒解题预算。Mathlib 冷准备最长 600 秒,标准库准备和最终验收各有独立时限,均不计入解题预算;轮次和时间不等于 API 费用上限,服务商按自己的计费规则收费。 +- 原生团队人数上限可设为 2–8,包含 Lead,可另设轮数、时间和 Token 预算。Mathlib 冷准备最长 600 秒,标准库准备和最终验收各有独立时限,均不计入解题预算。服务商按照其计费规则收费。 - 模型结束和网页显示“运行结束”都不代表证明成立。只有 `evaluated_passed` 才显示“验收通过”;这是本地独立 Lean 验收,不是 Lean-Eval 官方成绩。 - 浏览器不把 Key 写入 localStorage / sessionStorage;提交成功后清空输入框。保存到账号的 Key 只以密文存在服务器上,浏览器只拿到末四位。Key 经同源后端内存、Docker stdin 与 Codex 子进程环境传递,不写入 Docker 参数、容器环境配置、Codex 配置文件、任务档案或服务日志。每个任务使用新的 Codex profile,不读取部署者的认证文件;工具 shell 环境排除该 Key。 - 默认将运行记录、完整事件、观测、源码、回执、知识和服务端方案保存到私有持久目录。每个会话最多保留 40 条运行记录,可删除已结束的记录以释放容量;这是保存记录的容量,与账号在配额周期内可发起的次数、运行队列和并发限制分别计算。有效 API 请求延长服务端会话的闲置有效期;匿名运行同时续期 Cookie,启用登录时仅在登录时写入身份 Cookie。同一会话在有效期内可跨服务重启读取历史,启用登录后也可跨设备查看账号历史;服务不会自动恢复执行。测试中不设置持久目录的嵌入式服务仍仅使用内存。 @@ -397,6 +355,8 @@ Lean 标准库模板保留自然数加法和命题逻辑示例。网页默认 Ma ## 无模型费用的验证 +旧调度和模块编辑的浏览器检查使用迁移前的 TheoremOS 提交 `ef08987d6f686856c6fe9ecf86676ebbaa632546`。其中包括 `test:web-collaboration`、`test:web-plan-structure`、`test:web-collaboration-layers`、`test:web-preparation`、`test:web-module-plan`、`test:web-server-plans` 和 `test:web-drafts`。 + 基础 worker 构建完成后,可执行: ```bash @@ -407,11 +367,9 @@ bun run typecheck bun run typecheck:web bun run build:web bun run build -bun run test:web-collaboration bun run test:web-task-source bun run test:web-knowledge-context -bun run test:web-plan-recovery -bun run test:web-plan-structure +bun scripts/test-web-round8-approval.ts bun run test:web-guidance-recovery bun run test:web-research-progress bun run test:web-mathematical-changes @@ -430,7 +388,6 @@ bun run test:web-i18n bun run test:web-a11y bun run test:web-precheck bun run test:web-readable-results -bun run test:web-collaboration-layers bun run test:web-key-memory bun run test:web-load bun run test:web-theme @@ -438,10 +395,8 @@ bun run test:web-guide bun run test:web-admin bun run build:web-preview bun run test:web-preview -bun run test:web-preparation bun run test:web-recovery bun run test:web-results -bun run test:web-drafts bun run test:web-draft-recovery bun run test:web-run-monitor bun run test:web-history @@ -453,22 +408,20 @@ bun run test:web-editor-review bun run test:web-source-handoff bun run test:web-activity bun run test:web-modules -bun run test:web-module-plan -bun run test:web-server-plans bun run test:web-performance bun run test:web-motion -bun run test:web-cooperative-runtime bun run test:web-solve-process +bun scripts/test-web-native-team.ts +bun run test:web-plan-approval bun scripts/test-web-runtime.ts ``` -`test:web-ui` 使用 Playwright Chromium 与真实本地 HTTP 服务,通过可控 worker fixture 检查进度计时、日志轮转、刷新、取消、配置复用、源码切换、复制下载、本地文件导入、展开编辑、历史筛选,以及 320–1440 像素布局。`test:web-recovery` 检查离线、401 / CSRF 403、请求超时、POST 响应丢失、过时响应和页面恢复。`test:web-results` 检查可读报告、候选与最终验收的区别、诊断转义、JSON 导出,以及删除确认、失败和响应丢失。`test:web-drafts` 检查刷新恢复、草稿与档案导入导出、密钥排除、存储异常和导入预览布局。`test:web-source-diff` 检查逐行差异、上下文与更改导航、换行、原文复制下载和大输入边界。这些浏览器验证均不调用 Docker、Lean 或模型,报告和截图写入 `out/web-ui-smoke/`。首次使用需安装 Playwright Chromium:`bunx playwright install chromium`。 +`test:web-ui` 使用 Playwright Chromium 与真实本地 HTTP 服务,通过可控 worker fixture 检查进度计时、日志轮转、刷新、取消、配置复用、源码切换、复制下载、本地文件导入、展开编辑、历史筛选,以及 320–1440 像素布局。`test:web-recovery` 检查离线、401 / CSRF 403、请求超时、POST 响应丢失、过时响应和页面恢复。`test:web-results` 检查可读报告、候选与最终验收的区别、诊断转义、JSON 导出,以及删除确认、失败和响应丢失。`test-web-native-team.ts` 检查旧草稿迁移、导入预览及未确认提交的恢复。`test:web-source-diff` 检查逐行差异、上下文与更改导航、换行、原文复制下载和大输入边界。这些浏览器验证均不调用 Docker、Lean 或模型,报告和截图写入 `out/web-ui-smoke/`。首次使用需安装 Playwright Chromium:`bunx playwright install chromium`。 `test:web-a11y` 以中英文界面检查欢迎页、示例运行的每个标签页、研究配置 / 术语 / 研究记录对话框、命令面板和 375 像素布局:控件都有可读名称,label 与 ARIA 引用指向真实元素,id 不重复,无正 tabindex、嵌套控件或 aria-hidden 内的可聚焦元素;第一个 Tab 落在跳转链接,后续焦点都有可见焦点环;详情标签页支持方向键、Home 和 End;对话框(包括顶栏搜索按钮打开的命令面板)按 Esc 关闭并把焦点还给打开它的按钮;强制颜色模式下当前对话、输入框焦点、命令面板当前项和选中的标签页都有 Highlight 描边,Lean 源码不做语法着色,退出后恢复。同一套规则(`scripts/web-a11y.ts`)也用于 `test:web-login` 的登录页与账号对话框和 `test:web-share` 的分享对话框与分享页。 `test:web-precheck` 使用不启动 Docker 的编译夹具,在中英文下检查:编辑后自动检查;Lean 错误按行列出、点击及提交时在编辑器中选中原范围(含宽字符前的列);有错误时不创建运行,忽略后可提交;结构检查不调用编译且不可忽略;新编辑取代并停止慢检查;检查不可用时不阻止提交;375 / 320 像素下不溢出并通过无障碍规则。`bun run smoke:web-precheck` 需本机 Docker 和 `theorem-os-worker:local`,用真实 Lean 编译几道标准库与 Mathlib 题目,并验证取消后容器被删除。 `test:web-readable-results` 用不调用模型和 Lean 的运行夹具检查:通过的运行列出目标、辅助声明、引用与公理(只标出含非标准公理的目标),下载的复核包可解压且证明逐字一致,结构只读取一次;结构读取失败后可重试,未记录引用时不推断用法;卡住的运行列出前沿子目标、转义模型文本,并在研究协作中聚焦该任务;英文界面;375 / 320 像素下不溢出。 -`test:web-collaboration-layers` 检查协作页两层:首次进入只显示简洁层且不写入选择,切换就地生效、刷新后保留、焦点留在切换按钮上,从简洁层或报告页打开任务会切到完整层并把焦点放到任务上,已结束的运行指向报告,英文与 375/320 宽度不溢出,截图写到 `out/web-collaboration-layers`。 `test:web-key-memory` 检查记住 Key:默认不记住且不落任何存储;勾选后后续提交与同标签页刷新沿用、另一个标签页拿不到、只有记忆条目含 Key;换服务商地址不带 Key、用户自己填的 Key 不被覆盖;取消勾选、清除按钮、认证失败后更换 Key 都会立即清除;英文与 375/320 宽度。 `test:web-saved-key` 检查保存到账号:Lean「保存到我的账号」默认不勾选,默认提交及刷新都不产生账号 Key;主动保存后输入框清空、只显示末四位、浏览器存储和页面都不含 Key;自然语言独立保存、替换、删除不启动 worker;刷新和另一台设备留空即可提交并用上保存的 Key;另一个账号看不到且仍须填写;删除后恢复必填、服务器上的文件删除;英文和深色主题下无中文、对比度达标。 @@ -485,15 +438,12 @@ bun scripts/test-web-runtime.ts 组件预览 `bun run build:web-preview` 把 `apps/web/preview/` 构建到 `out/web-preview/`,用固定数据展示每个工作台组件(基础控件、Section 辅助组件、顶栏、对话、运行监视、运行头部、概览、研究协作);在页面上可切换中英文。它只用于开发,不进入 `out/web` 或镜像。`test:web-preview` 在中英文、1440 与 375 像素下检查每个组件渲染无报错、英文界面无未翻译文字、页面不溢出并通过上述无障碍规则,截图写入 `out/web-preview-check/`。 -`test:web-collaboration` 使用真实本地 HTTP 服务、可控 runner 和实际知识目录检查任务/路线筛选、Agent 分工、版本化源码与检查、指导投递、计划冲突/预览/应用、重新检查、知识引用、服务端方案和归档下载,同时检查轮询中的焦点/选区和 320 / 375 / 1440 像素布局。报告及截图写入 `out/web-collaboration/`。运行桥接、指导 host、持久化和模块身份分别由 `webWorkerBridge`、`humanGuidance`、`webCollaboration`、`webKnowledgeApi`、`webPersistence` 和 `webModuleIdentity` 测试覆盖;这些 fixture 不调用模型,模拟回执不作为真实 Lean 验收证据。 `test:web-live-sync` 使用真实本地 HTTP 服务、可控 runner、Chromium 和浏览器原生 EventSource,验证连续变化合并、旧读取期间的新通知、双标签页更新与取消、SSE 不可用时的轮询、连接中断后的自动重连、页面隐藏与恢复,以及迟到的创建响应不覆盖新状态,共 7 个场景。同时检查草稿、焦点和滚动保留及写入不重放;报告写入 `out/web-live-sync/report.json`。`tests/webRunStream.test.ts` 覆盖通知鉴权、会话隔离、版本与 ETag 一致、删除、心跳、退订、过期和服务关闭。两者均不调用模型、Docker 或 Lean。 -`test:web-server-plans` 使用真实本地 HTTP 服务与 Chromium 检查服务端方案的保存、删除确认与取消、并发版本冲突、响应丢失后的读取核对、重复提交锁定、12 项容量释放、当前草稿保留,以及 320 / 375 像素布局。不启动 worker 或调用模型,报告及截图写入 `out/web-server-plans/`。 -`test:web-task-source` 验证同任务真实 Git 快照的源码比较、同版本不同 commit、身份绑定、轮询与迟到请求隔离,以及手机布局和大差异降级。`test:web-knowledge-context` 验证检索传入真实任务与环境、保留跨问题材料、环境匹配、版本化引用及切换后的请求隔离。`test:web-plan-recovery` 验证实时观察自动确认、重新检查进度、迟到提交与查询响应、丢失响应后的只读核对、原 ID/内容重试、草稿和焦点保留、跨研究重开及手机操作,共 14 个场景。它们均使用真实本地 HTTP 与 Chromium,报告分别写入 `out/web-task-source/`、`out/web-knowledge-context/`、`out/web-plan-recovery/`;不调用模型或重新执行 Lean。 +`test:web-task-source` 验证同任务真实 Git 快照的源码比较、同版本不同 commit、身份绑定、轮询与迟到请求隔离,以及手机布局和大差异降级。`test:web-knowledge-context` 验证检索传入真实任务与环境、保留跨问题材料、环境匹配、版本化引用及切换后的请求隔离。`test-web-round8-approval.ts` 验证原生团队的项目审批在路线修订期间暂停,旧审批请求及回执仍可核对,批准新版本需要再次确认。它们均使用本地 HTTP 与 Chromium,报告分别写入 `out/web-task-source/`、`out/web-knowledge-context/`、`out/frontend-round8/approval/`。 -`test:web-plan-structure` 使用真实本地 HTTP 与 Chromium,通过常用表单编辑任务、分组和 OR 路线,并用实际 `parseCooperationPlan` 校验完整提案。覆盖任务类型转换、前提与证明位置、分组及共享、删除前引用核对、固定原始目标、JSON 同步与无效输入保留、预览失效、草稿轮询保留与 320 / 375 像素布局。可控 runner 的应用回执只验证交互,不调用模型、Docker 或 Lean;报告和截图写入 `out/web-plan-structure/`。 `test:web-guidance-recovery` 使用真实本地 HTTP 与 Chromium,覆盖指导的 unknown 到已投递或失败、丢失响应、原快照重试、读取失败不重发、任务版本人工确认、失效目标、同文字更换接收方、跨研究迟到回执及 320 / 375 像素布局,共 12 个场景。报告与截图写入 `out/web-guidance-recovery/`;worker 桥的明确拒绝、原 ID 幂等核对和未知存储错误另由 `tests/webWorkerBridge.test.ts` 覆盖。不调用模型或重新执行 Lean。 @@ -505,7 +455,6 @@ bun scripts/test-web-runtime.ts `test:web-task-browser` 使用 20 个任务的本地 HTTP 场景与 Chromium,检查依赖图/列表切换、路线与状态组合筛选、无结果与清除、所选任务被筛除、路线移除、精确历史合同,以及列表到详情的往返、轮询和跨研究状态保留。共 8 个场景,覆盖桌面及 320 / 375 像素布局;报告与截图写入 `out/web-task-browser/`。数学材料为 fixture,不调用模型、Docker 或 Lean。 -`test:web-preparation` 检查首次提交提示、模型与 Key 的字段校验、UTF-8 字节限制、执行预算、设置与编辑器焦点、选中行缩进及原生撤销重做、键盘导航、Unicode 光标位置、浏览器编辑不可用时的保留行为、导入后的密钥定位,以及 320 / 375 / 1440 像素布局。源码编辑还核对未应用修改的关闭确认、继续编辑后的选区与滚动保留、确认框内的 Esc / Enter、撤销回原文后直接关闭、无效输入、延迟文件读取和关闭后立即重开的边界。使用本地 fixture runner 验证一次有效提交,校验失败和编辑操作不发送 POST;报告与截图写入 `out/web-ui-smoke/`。 `test:web-draft-recovery` 检查各个替换入口的一步恢复、刷新后的备份、密钥排除、存储失败与超限草稿、迟到读取和编辑器失效、恢复后的焦点,以及有效提交清除备份与无效提交保留备份的边界。使用本地 fixture runner 和 Chromium,不调用模型、Docker 或 Lean;同时验证桌面与手机布局。 @@ -527,7 +476,6 @@ bun scripts/test-web-runtime.ts `test:web-modules` 使用本地 HTTP、可控 runner 与 Chromium 检查草稿结构、真实模块事件、最近活动定位与跟随、并发 Agent 记录与活动轮转、候选和最终验收边界、选择与阅读状态、文本转义及桌面和手机布局。浏览与切换模块不创建运行,也不调用模型、Docker 或 Lean;报告和截图写入 `out/web-modules/`。模块协议、事件翻译与摘要另由 `tests/webModuleTelemetry.test.ts` 覆盖,展示的验收边界和最近活动顺序由 `tests/webModuleView.test.ts` 覆盖。 -`test:web-module-plan` 检查模块新增、编辑、启停、复制、删除与撤销、排序、折叠、数量上限、替换冲突、错误定位、模块图中的策略定位、直接编辑与启停、提交锁定、草稿持久化与导入导出、实际界面提交、固定方案及配置复用,并验证应用事件、日志轮转、刷新与不适用的 M5 规则。撤销检查覆盖原内容、顺序和折叠状态恢复、后续编辑保留、重复操作、容量限制,以及草稿替换和提交时的清理。使用本地 HTTP、可控 runner 与 Chromium,不调用模型、Docker 或 Lean;报告及 320 / 375 / 1440 像素截图写入 `out/web-module-plan/`。策略的编译顺序、运行身份和固定验收边界由 `tests/customSolverModules.test.ts` 覆盖。 同一浏览器检查还覆盖方案库的命名保存、更新、另存、载入与撤销、删除与恢复、未完成规则、重置后独立保存、刷新、多标签页并发写入、旧版本冲突、存储失败、损坏数据及缺少 Web Locks 的情况。`tests/webModulePlanLibrary.test.ts` 单独检查库的数据格式、容量、快照隔离及失败后保留数据。 @@ -537,7 +485,7 @@ bun scripts/test-web-runtime.ts 最后一项派生带明确 fixture 标记的测试镜像,用模拟 Codex app-server 生成候选,执行真实 Lean 检查。共 7 个场景:标准库正确 / 错误候选、运行中取消、创建时取消,以及 Mathlib 正确 / 错误候选和运行中取消;Mathlib 取消场景还核对设备权限、匿名卷和删除结果。不会调用模型或使用真实 Key。可用 `--case mathlib-valid` 单独排查;Mathlib 冷准备可能持续数分钟。报告写入 `out/web-runtime-smoke/report.json`,测试镜像默认自动删除。 -`test:web-cooperative-runtime` 单独验证真实 Docker 多 Agent 协作,使用离线 Codex 替身生成工作材料,执行真实 host、命令通道和 Lean 检查:Lead 发布计划,Engineer 实际接收指定任务版本的指导并完成第一个目标;人工修改计划后,已检查任务的版本失效,两个目标重新检查;完整候选通过 Lean 检查后直接由 S3 验收原题。测试还核对预览只读、重复 edit 只应用一次、归档证据和容器清理。默认从 `theorem-os-worker:local` 派生一次性测试镜像,可用 `--base-image TAG` 指定已构建镜像;报告与原始证据写入 `out/web-cooperative-smoke/`。本机此流程已通过,两个目标的 recheck 与最终 `evaluated_passed` 均由真实 Lean 产生。 +新版工作台用 `bun scripts/test-web-native-team.ts` 检查原生团队提交、请求重试、知识设置和旧草稿导入。历史 `test:web-cooperative-runtime` 用 Docker 和 Lean 检查旧任务图的派工、指导和修改。复现这份测试或重新生成原始示例档案时,使用迁移前的提交 `ef08987d6f686856c6fe9ecf86676ebbaa632546`。 已验证标准库和 Mathlib 的正确 / 错误证明、取消及容器清理;浏览器到 HTTP、Docker 和真实 Mathlib/Lean 的完整流程也通过验收,并检查了下载和 320–1440 像素布局。实际运行结果写入各次测试报告。不同服务商的 Responses API 兼容性与付费模型行为需要使用者通过自己的账户验证。 @@ -571,7 +519,7 @@ Web 容器是 Docker supervisor,挂载 Docker socket,有权限创建和删 | 密钥 | `THEOREMOS_WEB_KEY_SECRET` 已设(否则不能保存 Key),`THEOREMOS_WEB_ADMINS` 用于兜底 | `/api/session` 的 `account.keyVault` 为 true | | 地址 | `THEOREMOS_WEB_CLIENT_IP_HEADER=cf-connecting-ip`(仅在端口只对代理开放时) | 两个不同访客的限流互不影响 | | 容量 | `THEOREMOS_WEB_CONCURRENCY`、`THEOREMOS_WEB_QUEUE_LIMIT` 与网关并发相符 | 管理面板的漏斗与队列 | -| 健康 | `/healthz` 返回 `ok` 和提交号 | `curl -fsS https://…/healthz` | +| 健康 | `/healthz` 返回 `ok` 和提交号,`/readyz` 返回 `ready: true` 和 `nativeTeam: true` | 访问 `/healthz` 和 `/readyz` | | 回滚 | 部署前打过 `theorem-os-web:<提交>`、`theorem-os-worker:<提交>` 标签,最多保留三组 | `docker image ls theorem-os-web theorem-os-worker` | | 记录 | 部署后运行 `scripts/web-deploy-record.sh`,`clean` 为 true | `deploys.jsonl` 最后一行 | diff --git a/examples/components/EXPERIMENTS.md b/examples/components/EXPERIMENTS.md index f22800d8..97067460 100644 --- a/examples/components/EXPERIMENTS.md +++ b/examples/components/EXPERIMENTS.md @@ -1,5 +1,7 @@ # 模块对照实验 +使用实验固定的历史 TheoremOS 版本准备和执行下列调度对照。当前版本可读取并检查已保存的对照报告。 + 目前还没有完成的模块效果实验。模块编辑、可视化、排序合同测试和预设回放, 均不能作为模块提高解题率或降低成本的证据。 diff --git a/examples/components/README.md b/examples/components/README.md index 4296ed12..e38905be 100644 --- a/examples/components/README.md +++ b/examples/components/README.md @@ -20,8 +20,9 @@ bun run math component check --name my-search `check` 不调用模型或 Lean,用几个本地任务检查排序是否保留了依赖、暂停、路线和预算约束。 它只检查这个排序模板的基本约定,策略是否有效仍需要实验。 改变策略后,更新 `id` 和 M3 的 `version`,再运行检查。 +当前版本生成的组件运行脚本用于恢复已有运行。 -可以把组件接到[小题示例](../getting-started/README.md)中。先配置好 Codex 和 Lean 环境,再使用一个仓库外的新目录: +以下运行命令用于复现历史调度器中的组件实验。在实验固定的 TheoremOS 版本中,先配置 Codex 和 Lean 环境,再使用一个仓库外的新目录。 ```bash export THEOREMOS_COMPONENT_CASE="$PWD/../theorem-os-runs/my-search" @@ -75,7 +76,7 @@ const modules: SolverModules = { `goalsFirstResearchTasks` 先调用原有就绪筛选,再排序,保留依赖、暂停与路线预算检查。 可以在此基础上实现自己的排序规则;返回值必须来自当前可启动任务。 -按[快速开始](../../README.md#快速开始)准备依赖、题目和任务文件后,从仓库根目录执行: +在实验固定的历史版本中,按[快速开始](../../README.md#快速开始)准备依赖、题目和任务文件后,从仓库根目录执行。 ```bash bun run build diff --git a/examples/imo2026/COMPARISON.md b/examples/imo2026/COMPARISON.md index 7258261c..24ffb9fe 100644 --- a/examples/imo2026/COMPARISON.md +++ b/examples/imo2026/COMPARISON.md @@ -1,5 +1,11 @@ # Compare single, independent and cooperative solving +These are historical host scheduling experiments. To prepare a new instance of +the protocol below, run its commands from TheoremOS revision +`ef08987d6f686856c6fe9ecf86676ebbaa632546`, before the switch to native teams. +For an existing experiment, use the original revision and build recorded in its +build manifest. The current CLI can read and check saved comparison reports. + For module-plan comparisons with fixed cooperative workers, including optional context and custom-rule treatments, see [module experiments](../components/EXPERIMENTS.md). diff --git a/examples/imo2026/README.md b/examples/imo2026/README.md index 724cd212..84c50cfc 100644 --- a/examples/imo2026/README.md +++ b/examples/imo2026/README.md @@ -19,8 +19,9 @@ these formalizations. The underlying Olympiad problems belong to the International Mathematical Olympiad. This notice grants no new rights in the original problem texts. -The case uses `gpt-6.1-sol`, `xhigh`, four agents, the direct method, a shared -30-minute solving limit and 20 total turns. A completed run is accepted only if +The case uses `gpt-6.1-sol`, `xhigh`, a Codex native team of up to four members +including Lead, a shared 30-minute solving limit and 20 total turns. +A completed run is accepted only if all original targets pass host Lean verification after integration. This is a local evaluation (`official: false`). A demonstration run can remain incomplete within its budget; the example does not promise a solved task. @@ -40,7 +41,8 @@ zstd-capable `squashfuse`/`snapfuse` and complete the actual startup preflight. Install dependencies with `bun install --frozen-lockfile` from the project root. Authenticate your existing Codex profile separately. The default profile is `~/.config/deepscientist/math-sol-codex`; `CODEX_HOME` can select another existing -profile with access to the configured model. +profile with access to the configured model. Use the +[native team backend](../../scripts/codex-backend/README.md) for this example. The [environment template](math.env.example) describes tool and cache settings. Copy it to a local file, replace the paths, and set @@ -92,8 +94,10 @@ For an existing pinned benchmark checkout, set `MATH_EXAMPLE_REPO` before `MATH_EXAMPLE_SKIP_CACHE=1` and configure its trusted root in your math environment file. These options reuse local resources; the task and target identities stay pinned. Preserve the original build and environment to resume a run. +Use the original TheoremOS revision and build for a saved historical case. +To try the native team, prepare a separate case directory. -## Inspect and intervene +## Inspect the run ```bash bun run math inspect --run /absolute/new/imo-q1-case/result.json @@ -105,20 +109,5 @@ The report separates recorded proof checks, open conditions, review, and final evaluation. It can inspect a running checkpoint before `result.json` exists. It reads stored evidence and does not rerun Lean. -Once the Lead has created a plan, edit the exported task objectives, helper -types, dependencies or route settings. Retain `baseVersion`, all original goals, -and an acyclic dependency graph. Then validate and queue the edit: - -```bash -bun run math edit --run /absolute/new/imo-q1-case/result.json \ - --plan /absolute/new/imo-q1-case/plan.json --dry-run -bun run math edit --run /absolute/new/imo-q1-case/result.json \ - --plan /absolute/new/imo-q1-case/plan.json -``` - -`queued` means the request was appended to the existing edit protocol. The live -or resumed solver checks the plan version, applies the edit and separately -rechecks affected proofs. Inspect again to distinguish `received`, `applied`, -`rejected` and the proof recheck outcome. Stale plans must be re-exported against -the current plan version. Fully accepted terminal runs are not new experiments; -prepare a fresh case to measure a different method. +The native Lead owns the route and member assignments. Start a separate case +if you want to measure a different configuration. diff --git a/examples/imo2026/reproduce.sh b/examples/imo2026/reproduce.sh index e5413446..317164cb 100644 --- a/examples/imo2026/reproduce.sh +++ b/examples/imo2026/reproduce.sh @@ -8,7 +8,7 @@ Usage: bash examples/imo2026/reproduce.sh prepare|check|solve|resume /absolute/c prepare Build the CLI, bootstrap pinned public IMO2026 Q1, and fetch Lean caches. check Prepare the proof environment without invoking a model. solve Start a fresh model run; use resume after check or an interrupted run. -resume Resume with the same case, model, worker count, and build manifest. +resume Resume with the saved team configuration and build manifest. Optional environment: MATH_EXAMPLE_REPO Existing Humanfia checkout at the pinned commit. @@ -51,9 +51,9 @@ TASK const bootstrap = await Bun.file(root + "/bootstrap.json").json(); const build = await Bun.file(root + "/build.json").json(); await Bun.write(root + "/case.json", JSON.stringify({ - schema: "deepscientist.math.public-example.v1", problem: bootstrap.problemId, + schema: "deepscientist.math.public-example.v2", problem: bootstrap.problemId, sourceCommit: bootstrap.sourceCommit, buildManifestRef: build.buildManifestRef, - model: "gpt-6.1-sol", effort: "xhigh", workers: 4, + model: "gpt-6.1-sol", effort: "xhigh", nativeTeamCapacity: 4, method: "direct", maxRunSeconds: 1800, maxTurns: 20, taskSha256: new Bun.CryptoHasher("sha256").update(await Bun.file(root + "/task.md").arrayBuffer()).digest("hex"), evaluator: "host-lean-kernel-all-targets", official: false @@ -79,7 +79,7 @@ bun -e ' manifest=$(bun -e 'console.log((await Bun.file(process.argv[1]).json()).buildManifestRef)' "$case_root/case.json") args=(run --build-manifest "$manifest" --workspace "$case_root/workspace" - --task-file "$case_root/task.md" --workers 4 --method direct + --task-file "$case_root/task.md" --method direct --model gpt-6.1-sol --effort xhigh --max-run-seconds 1800 --max-turns 20 --output "$case_root/result.json") if [[ $mode == check ]]; then @@ -88,4 +88,14 @@ if [[ $mode == check ]]; then elif [[ $mode == resume ]]; then args+=(--resume) fi +if [[ $mode == solve || ( $mode == check && ! -f $case_root/result.json.runtime/state.json ) ]]; then + capacity=$(bun -e ' + const example = await Bun.file(process.argv[1]).json(); + if (example.schema !== "deepscientist.math.public-example.v2") { + throw new Error("Prepare a new case for the native team or use the original TheoremOS revision for this historical case."); + } + console.log(example.nativeTeamCapacity); + ' "$case_root/case.json") + args+=(--agent-team "$capacity") +fi bun run math "${args[@]}" diff --git a/examples/putnambench/README.md b/examples/putnambench/README.md index feb07ef7..f26d242f 100644 --- a/examples/putnambench/README.md +++ b/examples/putnambench/README.md @@ -1,8 +1,12 @@ # PutnamBench 小样本模块实验 +本页的准备和运行命令属于旧调度器实验。重新准备本页方案时,请在 TheoremOS +提交 `ef08987d6f686856c6fe9ecf86676ebbaa632546` 的检出目录中执行。 +已有实验使用构建清单记录的原始版本和构建产物。当前 CLI 仍可汇总已保存的实验记录。 + 从 [PutnamBench](https://github.com/trishullab/PutnamBench) 的 Lean 原题中固定抽取三道, 每题分别准备默认方案、精简上下文、关键路径组合和自定义规则四组,共 12 次计划运行。 -新计划默认使用本地 Sub2API 的 `deepseek-flash` / `max`。准备与汇总命令不调用模型。 +该版本的计划默认使用本地 Sub2API 的 `deepseek-flash` / `max`。准备与汇总命令不调用模型。 已完成一题默认方案的[请求级预算真实校准](CALIBRATION-REQUEST-BUDGET-20261019.md): 两次请求完整上报 38,104 token,后续请求被本地拒绝,尚无通过验收的证明。 [此前的调度级校准](CALIBRATION-20261019.md)保留为历史记录。 diff --git a/package.json b/package.json index 7c3eb9d0..508fe78e 100644 --- a/package.json +++ b/package.json @@ -35,8 +35,8 @@ "test:frontend-round6": "bun scripts/test-web-round6-people.ts && bun scripts/test-web-round6-collaboration.ts && bun scripts/test-web-round6-library.ts && bun scripts/test-web-round6-routes.ts", "test:frontend-round7": "bun scripts/test-web-round7-session.ts && bun scripts/test-web-round7-people.ts && bun scripts/test-web-round7-library.ts && bun scripts/test-web-round7-routes.ts", "test:frontend-round8": "bun scripts/test-web-round8-budget.ts && bun scripts/test-web-round8-keys.ts && bun scripts/test-web-round8-approval.ts && bun scripts/test-web-round8-routes.ts", - "test:frontend-round9": "bun scripts/test-web-round9-availability.ts && bun scripts/test-web-round9-collaboration.ts && bun scripts/test-web-round9-mobile.ts && bun scripts/test-web-round9-routes.ts", - "test:frontend-round10": "bun scripts/test-web-round10-workbench.ts && bun scripts/test-web-round10-math.ts && bun scripts/test-web-round10-routes.ts && bun scripts/test-web-round10-collaboration.ts", + "test:frontend-round9": "bun scripts/test-web-round9-availability.ts && bun scripts/test-web-round9-mobile.ts && bun scripts/test-web-round9-routes.ts", + "test:frontend-round10": "bun scripts/test-web-round10-workbench.ts && bun scripts/test-web-round10-math.ts && bun scripts/test-web-round10-routes.ts", "test:web-ui": "bun scripts/test-web-ui.ts", "test:web-product-flow": "bun scripts/test-web-product-flow.ts", "test:web-login": "bun scripts/test-web-login.ts", @@ -55,8 +55,6 @@ "test:web-collaboration": "bun scripts/test-web-collaboration.ts", "test:web-task-source": "bun scripts/test-web-task-source.ts", "test:web-knowledge-context": "bun scripts/test-web-knowledge-context.ts", - "test:web-plan-recovery": "bun scripts/test-web-plan-recovery.ts", - "test:web-plan-ownership": "bun scripts/test-web-plan-ownership.ts", "test:web-plan-approval": "bun scripts/test-web-plan-approval.ts", "test:web-plan-structure": "bun scripts/test-web-plan-structure.ts", "test:web-guidance-recovery": "bun scripts/test-web-guidance-recovery.ts", @@ -72,7 +70,6 @@ "test:web-task-browser": "bun scripts/test-web-task-browser.ts", "test:web-interaction-flow": "bun scripts/test-web-interaction-flow.ts", "test:web-live-sync": "bun scripts/test-web-live-sync.ts", - "test:web-cooperative-runtime": "bun scripts/test-web-cooperative-runtime.ts", "test:web-preparation": "bun scripts/test-web-preparation.ts", "test:web-recovery": "bun scripts/test-web-recovery.ts", "test:web-results": "bun scripts/test-web-results.ts", @@ -119,7 +116,7 @@ "smoke:web-precheck": "bun scripts/smoke-web-precheck.ts", "test": "vitest run", "test:codex-backend": "bun scripts/test-codex-backend.ts", - "test:solver-reliability": "THEOREMOS_TEST_REQUIRE_LEAN=1 vitest run --maxWorkers=4 tests/leanTestEnvironment.test.ts tests/continuationSeed.test.ts tests/continuationInput.test.ts tests/continuationContext.test.ts tests/continuationSearch.test.ts tests/taskSourceProjection.test.ts tests/taskTypePreflight.test.ts tests/solverTaskTypePreflight.test.ts tests/leanTypeDiagnostics.test.ts tests/leanTypeDiagnosticsEnvironment.test.ts tests/verificationCheckpoint.test.ts tests/workerProofCheckpoint.test.ts tests/solverProofReady.test.ts tests/solverProofReadyIntake.test.ts tests/solverProofImport.test.ts tests/solverRestore.test.ts tests/solverCooperativeCheckpoints.test.ts tests/solverHumanEditRecovery.test.ts tests/solverIntegrationRecovery.test.ts tests/solverIntegrationConcurrency.test.ts tests/solverIntegrationBatch.test.ts tests/solverCanonicalTaskProof.test.ts tests/solverConditionalIntegration.test.ts tests/proofReuseEnvironment.test.ts tests/cooperativeReplay.test.ts", + "test:solver-reliability": "THEOREMOS_TEST_REQUIRE_LEAN=1 vitest run --maxWorkers=4 tests/leanTestEnvironment.test.ts tests/continuationInput.test.ts tests/continuationContext.test.ts tests/continuationSearch.test.ts tests/taskSourceProjection.test.ts tests/taskTypePreflight.test.ts tests/leanTypeDiagnostics.test.ts tests/leanTypeDiagnosticsEnvironment.test.ts tests/verificationCheckpoint.test.ts tests/proofReuseEnvironment.test.ts", "test:formalization": "bun scripts/test-formalization.ts", "typecheck": "tsc --noEmit", "test:frontend-product-continuity": "bun scripts/test-web-research-entry.ts && bun scripts/test-web-collaboration-actions.ts && bun scripts/test-web-collaboration-entry-permissions.ts && bun scripts/test-web-collaboration-continuity.ts && bun scripts/test-web-candidate-continuity.ts && bun scripts/test-web-research-library-trials.ts && bun scripts/test-web-research-collections.ts && bun scripts/test-web-research-workspace.ts && bun scripts/test-web-research-problem.ts && bun scripts/test-web-practice.ts && bun scripts/test-web-first-research-sharing.ts && bun scripts/test-web-research-journey.ts && bun scripts/test-web-inline-annotations.ts && bun scripts/test-web-research-depth.ts && bun scripts/test-web-research-personal.ts && bun scripts/test-web-research-completion.ts && bun scripts/test-web-research-draft-lifecycle.ts && bun scripts/test-web-library-personal-continuity.ts && bun scripts/test-web-message-stage-continuity.ts && bun scripts/test-web-research-run-continuity.ts && bun scripts/test-web-research-start-planning.ts && bun scripts/test-web-discovery-invites.ts && bun scripts/test-web-share-continuity.ts && bun run test:frontend-followthrough && bun run test:frontend-lifecycle", diff --git a/research/PROTOCOL.md b/research/PROTOCOL.md index 72e2d5c4..38e540ce 100644 --- a/research/PROTOCOL.md +++ b/research/PROTOCOL.md @@ -2,7 +2,7 @@ Version: v1 Status: Implemented(隔离分支的本地功能验收;未启用真实求解) -Updated: 2026-11-24 +Updated: 2026-11-27 ## 已确认的目标 @@ -10,6 +10,8 @@ Updated: 2026-11-24 依据:[决策 0001](decisions/0001-agent-led-skill-multiagent.md)、[决策 0002](decisions/0002-persistent-proof-workers.md)。 +新版解题协作使用 Codex 原生团队,默认由 Lead 自主推进。开启人工路线审核时,Lead 发布固定初始路线,获得这一版本的批准后才开工。宿主仍核验全部原始 Lean 目标。旧调度的档案继续可读,续跑和对照实验使用各自固定的历史版本。见[决策 0010](decisions/0010-native-team-runtime-only.md)。 + ## 角色与成果语义 | 对象 | 职责与含义 | @@ -100,7 +102,7 @@ Updated: 2026-11-24 | 范围 | 验证 | | --- | --- | | 本地数学工具(2026-11-23) | 真实模型在同一构建、扩展工具配置和 Skill 下完成两道新题,均通过本地独立 Lean 验收。整数题用系统 Python 自写计算得到见证,曾因未使用 `math-python` 导入 SymPy 失败;命题题仅用假设。两题均未派工。另一次脚本回放验证原生成员用 Gfan 计算、Lead 收件后用 SymPy 复核,不能据此认定模型会自主协作。[盲测报告](/data/lzh/workspace/outputs/theoremos/20261123-native-tool-blind.Kq7sliPu/report.md) | -| 持续协作 | [管理层测试](../tests/agentResearchTeam.test.ts):真实 Git/Lean,受控会话;覆盖异步到达、线程跟进、消息、成员复用、预算、恢复、错误反馈与停写。 | +| 持续协作 | [管理层测试](https://github.com/HuggingMath/theorem-os/blob/ef08987d6f686856c6fe9ecf86676ebbaa632546/tests/agentResearchTeam.test.ts):真实 Git/Lean,受控会话;覆盖异步到达、线程跟进、消息、成员复用、预算、恢复、错误反馈与停写。 | | 正式交付 | [证明测试](../tests/agentTeamProof.test.ts):真实 Git/Lean;覆盖精确声明、未授权改动、冲突、过期证据、来源变更及合并前后退出恢复。 | | 原生执行 | [协议端到端测试](../tests/agentTeamSolver.test.ts):实际 Codex adapter、动态工具 RPC、bwrap 和四份冻结 bundle;双子 Agent 提交 helper,Lead 两次恢复并采纳。错误 helper 经真实 Lean 拒绝后,Lead 显式派工,同一 child thread 收到自身错误及新任务并修正,Lead 采纳后完成原题;同时核对身份及角色工具。实际 CLI 入口完成 Lead/子 Agent 依赖准备、环境投影、全部原目标的独立 S3 Lean 验收及结果保存。回复由本地协议 peer 控制,健康检查仅访问临时本机服务。 | | 生命周期 | [工具测试](../tests/agentTeamTools.test.ts):调用绑定、并发、取消、停止与宿主 SIGKILL 后后台写者退出。 | diff --git a/research/decisions/0009-native-codex-team-only.md b/research/decisions/0009-native-codex-team-only.md new file mode 100644 index 00000000..f6886dd4 --- /dev/null +++ b/research/decisions/0009-native-codex-team-only.md @@ -0,0 +1,17 @@ +--- +id: "0009" +title: 新建解题协作统一使用 Codex 原生团队 +status: superseded by 0010 +date: "2026-11-27" +decided_by: 用户(本次对话) +related: + - research/PROTOCOL.md + - research/decisions/0001-agent-led-skill-multiagent.md + - docs/codex-skill-runtime.md +--- + +# 0009 — 新建解题协作统一使用 Codex 原生团队 + +新版只为新建协作解题提供 Codex 原生团队。Lead 使用 Codex 的派工、通信和线程管理工具。现有的证明交付、采纳、隔离、预算、持久化与独立 Lean 验收由 TheoremOS 提供。两套调度器并行维护曾支持跨后端协作和模块消融,现在这些旧对照实验改用各自固定的历史版本。 + +团队默认自主推进。用户可选在证明开工前审核 Lead 发布的首轮路线。批准绑定这一版路线,之后由 Lead 自主推进。已有任务读取保存的调度和来源身份。 diff --git a/research/decisions/0010-native-team-runtime-only.md b/research/decisions/0010-native-team-runtime-only.md new file mode 100644 index 00000000..d9d7ded8 --- /dev/null +++ b/research/decisions/0010-native-team-runtime-only.md @@ -0,0 +1,16 @@ +--- +id: "0010" +title: 新版运行时只执行 Codex 原生团队协作 +status: accepted +date: "2026-11-27" +decided_by: 用户(本次对话) +related: + - research/decisions/0009-native-codex-team-only.md + - research/PROTOCOL.md +--- + +# 0010 — 新版运行时只执行 Codex 原生团队协作 + +决策 0009 曾为旧任务保留原调度的续跑入口。用户确认将旧任务的执行也交回其历史版本,避免新版继续维护固定任务图、`host-tools` 团队和宿主派发的只读调查历史流程。旧的固定路线探索也使用历史版本。原生团队可以按需要开展并行路线调查。新版继续读取和导出历史记录。要原样续跑旧任务,使用对应的冻结构建、工作区和配置。要用旧证据开始新研究,可将保存的资料带入独立的原生团队运行。 + +新研究默认由 Codex Lead 自主分工,可选首轮路线审批。单人运行、按需查库和冻结依赖、证明交付与采纳、隔离、预算和独立 Lean 验收继续由现有运行时提供。旧调度对照使用实验固定的版本。 diff --git a/scripts/build-agent-tools.ts b/scripts/build-agent-tools.ts index 8f2d3a4b..a1d3254a 100644 --- a/scripts/build-agent-tools.ts +++ b/scripts/build-agent-tools.ts @@ -15,9 +15,8 @@ const agentToolCommands = { 'check-lean': 'checkLean.ts', 'search-lean': 'searchLean.ts', knowledge: 'theoremKnowledge.ts', library: 'library.ts', declarations: 'readDeclarations.ts', hub: 'huggingMath.ts', - 'research-observe': 'researchObserve.ts', 'proof-search': 'proofSearch.ts', checkpoint: 'checkpoint.ts', - 'plan-validate': 'planValidate.ts', 'plan-apply': 'planApply.ts', + 'plan-validate': 'planValidate.ts', 'check-finite': 'checkFinite.ts', 'kernel-certificate': 'kernelCertificate.ts', continuation: 'readContinuation.ts', } as const; fs.rmSync(output, { recursive: true, force: true }); diff --git a/scripts/build-web-sample.ts b/scripts/build-web-sample.ts index afcb1f3a..0ef9723c 100644 --- a/scripts/build-web-sample.ts +++ b/scripts/build-web-sample.ts @@ -1,6 +1,6 @@ -// Turns the archive written by test:web-cooperative-runtime into the workbench's read-only sample run. -// That run uses the real Docker host, command pipe and Lean checks, with a scripted offline agent in place of a model, -// so the sample needs no API key and the page says so. Usage: bun scripts/build-web-sample.ts [archive.json] +// Converts a saved historical Web archive into the workbench's read-only sample. +// The archived fixture used Docker, offline agents and real Lean checks. +// Usage: bun scripts/build-web-sample.ts [archive.json] import fs from 'node:fs'; import path from 'node:path'; import { webSampleRunId, webSampleSchema, type WebSampleFile } from '../apps/web/sample'; diff --git a/scripts/build.ts b/scripts/build.ts index 0748803e..98e688a9 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -32,7 +32,6 @@ if (args.includes('--help') || args.includes('-h')) { 'math-solver': path.join(root, 'scripts/mathematics/runMathProof.ts'), 'search-lean': path.join(root, 'scripts/mathematics/searchLean.ts'), 'check-lean': path.join(root, 'scripts/mathematics/checkLean.ts'), - 'proof-search': path.join(root, 'scripts/mathematics/proofSearch.ts'), }, outdir: bundleRoot, bundle: true, diff --git a/scripts/codex-backend/README.md b/scripts/codex-backend/README.md index e195bba6..3de6bf12 100644 --- a/scripts/codex-backend/README.md +++ b/scripts/codex-backend/README.md @@ -51,16 +51,11 @@ All Cargo targets, logs and binaries stay under `--output`. On success, not restarted. Source edits beyond the checked-in patches are preserved and rejected, so freeze the adapter patch before running a final build. -New native team runs pin the executable's real path and digest and record -`agentTeam.transport: native-agent-control`. On certain compatibility or transport -errors during initial app-server startup, the solver can retry with -`theoremos_team` host tools. The failed writer must have stopped, and the Lead -must have no open session, saved thread, started turn or model request, or team -member. The solver emits `team_transport_fallback` and saves `host-tools` for -resume. Authentication failures and cancellation follow the normal error path. -A missing binary can fail earlier during configuration. New teams using the -direct Westlake Chat profile start with host tools. Checkpoints that predate the -transport field also use host tools. +New team runs pin the executable's real path and digest and record +`agentTeam.transport: native-agent-control`. Startup failures are reported +through the native backend. Use a compatible provider profile such as the +Responses gateway. Resume native team checkpoints with their pinned backend. +Resume historical host-tool team checkpoints with the original TheoremOS build. After the ordinary headless runtime build, exercise the real binary with fixed loopback Responses and independent process/workspace isolation: @@ -89,10 +84,10 @@ The Web worker Dockerfile builds the same pinned source on Debian Bookworm and installs a separate binary at `/opt/theoremos-codex-backend/codex`. Ordinary runs keep the stock Codex binary. The worker build probes the native app-server's capabilities as the worker user before labeling the image -`org.theoremos.native-agent-control=v1`. The Web service uses this label to -offer native teams only with a compatible worker; existing deployments are -unchanged until their images are rebuilt and selected. A host output symlink -is not a portable installation. +`org.theoremos.native-agent-control=v1`. The Web service also checks +`org.theoremos.native-team-workflow=v1`, which identifies support for native +team scheduling and initial route approval. It launches the image by its +verified ID. Rebuild both Web and worker images to roll out this workflow. Cargo resolves V8 host manifests even though the CLI does not link that runtime. The build-local Git helper fetches the exact locked submodule commits without diff --git a/scripts/mathematics/autoLibrary.ts b/scripts/mathematics/autoLibrary.ts index 9a3c1c1b..9382b8bb 100644 --- a/scripts/mathematics/autoLibrary.ts +++ b/scripts/mathematics/autoLibrary.ts @@ -44,6 +44,9 @@ const readFile = (value: string, limit: number) => { }; function prepare(flags: ReadonlyMap, directory: string) { + const workers = integerFlag(flags, 'workers', 1); + if (workers !== 1 || flags.get('coordination') === 'cooperative') + throw new Error('New automatic library builds use one prover. Prepare legacy multi-worker builds from their pinned historical revision.'); const buildManifestRef = path.resolve(required(flags, 'build-manifest')); readMathBuildManifest(buildManifestRef, root, path.join(root, 'out/main')); const codex = flags.get('codex') ?? process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE ?? 'codex'; @@ -60,7 +63,7 @@ function prepare(flags: ReadonlyMap, directory: string) { environment: flags.get('environment') ?? 'mathlib', pool: externalPath(required(flags, 'pool')), buildManifestRef, planner, prover: { model: prover.model, effort: prover.effort, executable: prover.executable, - ...(prover.agentHarness ? { agentHarness: prover.agentHarness } : {}), workers: integerFlag(flags, 'workers', 1), coordination, + ...(prover.agentHarness ? { agentHarness: prover.agentHarness } : {}), workers, coordination, maxRunSeconds: integerFlag(flags, 'prover-max-run-seconds', 3600), maxTurns: integerFlag(flags, 'prover-max-turns', 200), maxTurnSeconds: integerFlag(flags, 'prover-max-turn-seconds', 180), maxTotalTokens: integerFlag(flags, 'prover-max-total-tokens', 0), prepareTimeoutSeconds: integerFlag(flags, 'prepare-timeout-seconds', 1800) }, @@ -115,7 +118,7 @@ export async function autoLibrary(argv: string[]): Promise { + ' [--definition-targets Qualified.name,Other.name] (original definitions to solve)\n' + ' [--prover-harness ID --prover-harness-profile DIR --prover-harness-executable FILE] selects a separate proof backend. Sealed planner roles currently require Codex.\n' + ' [--model deepseek-flash --effort high] (planner) [--prover-model M --prover-effort E] [--profile DIR] [--codex FILE] [--harness ID --harness-profile DIR --harness-executable FILE]\n' - + ' [--workers 1] [--coordination independent|cooperative] [--max-modules 1] [--max-rounds 3]\n' + + ' [--max-modules 1] [--max-rounds 3]\n' + ' [--max-run-seconds 7200] [--max-total-tokens 0] [--planner-turn-seconds 1800]\n' + ' [--prover-max-run-seconds 3600] [--prover-max-turns 200] [--prover-max-turn-seconds 180] [--prover-max-total-tokens 0]\n' + ' [--prepare-timeout-seconds 1800] (0 = unlimited for run, token and turn limits)\n' diff --git a/scripts/mathematics/compareMathRuns.ts b/scripts/mathematics/compareMathRuns.ts index ab765e79..6f4cdffd 100644 --- a/scripts/mathematics/compareMathRuns.ts +++ b/scripts/mathematics/compareMathRuns.ts @@ -450,13 +450,18 @@ export function writeComparisonReport(file: string, report: unknown) { writeMathJsonDurable(file, report); } -export async function compareMathRuns(argv: string[]): Promise { +export async function compareMathRuns(argv: string[], historicalReportsOnly = false): Promise { const flags = parseFlags(argv, ['phase', 'directory', 'repo', 'problem', 'task-file', 'build-manifest', 'repetitions', 'model', 'effort', 'method', 'scheduler', 'workers', 'max-turns', 'max-run-seconds', 'max-turn-seconds', 'max-total-tokens', 'evaluator-timeout-seconds', 'proof-environment-cache-dir', 'module-experiment', 'provider', 'dataset', 'knowledge-base', 'knowledge-mode', 'skill-baseline', 'common-research-skill', 'source-file', 'harness', 'harness-profile', 'harness-executable']); if (flags.has('help')) { + if (historicalReportsOnly) { + console.log('Usage: theorem-os compare --phase report|check-report --directory DIR\n' + + 'Prepare and execute legacy comparisons from their pinned historical TheoremOS revision.'); + return 0; + } console.log('Usage: theorem-os compare --phase prepare|run|report|check-report --directory DIR\n' + 'prepare also requires --problem ID --task-file FILE --build-manifest FILE\n' + '--dataset imo2026|putnambench requires --repo PINNED_REPO (default: imo2026).\n' @@ -482,6 +487,8 @@ export async function compareMathRuns(argv: string[]): Promise { } const phase = required(flags, 'phase'); if (!['prepare', 'run', 'report', 'check-report'].includes(phase)) throw new Error('invalid --phase'); + if (historicalReportsOnly && (phase === 'prepare' || phase === 'run')) + throw new Error('Prepare and execute legacy comparisons from their pinned historical TheoremOS revision.'); const directory = path.resolve(required(flags, 'directory')); const planFile = path.join(directory, 'comparison.json'); for (const name of ['harness', 'harness-profile', 'harness-executable']) if (phase !== 'prepare' && flags.has(name)) @@ -693,7 +700,7 @@ export async function compareMathRuns(argv: string[]): Promise { } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - compareMathRuns(process.argv.slice(2)).then(code => { process.exitCode = code; }, error => { + compareMathRuns(process.argv.slice(2), true).then(code => { process.exitCode = code; }, error => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); } diff --git a/scripts/mathematics/component.ts b/scripts/mathematics/component.ts index d55dce7e..86275331 100644 --- a/scripts/mathematics/component.ts +++ b/scripts/mathematics/component.ts @@ -9,7 +9,7 @@ async function main(): Promise { name: { type: 'string' }, help: { type: 'boolean' }, } }); if (values.help) { - console.log('Usage: theorem-os component init|check --name my-search\ninit creates src/components/my-search.ts and scripts/components/my-search.ts without overwriting files.\ncheck checks ordering, dependency and route gates with a small local fixture; no model or Lean calls.\nEdit the ready function, update its version, then build and use a new problem case.'); + console.log('Usage: theorem-os component init|check --name my-search\ninit creates src/components/my-search.ts and scripts/components/my-search.ts without overwriting files.\ncheck checks ordering, dependency and route gates with a small local fixture; no model or Lean calls.\nStart component scheduling experiments from a pinned historical TheoremOS revision.'); return 0; } if (positionals.length !== 1 || !['init', 'check'].includes(positionals[0]) || !values.name) diff --git a/scripts/mathematics/cooperativeReplay.ts b/scripts/mathematics/cooperativeReplay.ts deleted file mode 100644 index f22b0b64..00000000 --- a/scripts/mathematics/cooperativeReplay.ts +++ /dev/null @@ -1,309 +0,0 @@ -#!/usr/bin/env bun -import fs from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { parseFlags, required } from './arguments'; -import { bootstrapLeanTask } from '../../src/math/leanTask'; -import { readMathBuildManifest } from '../../src/math/mathBuildManifest'; -import { canonicalMathJson, mathDigest, readMathText, writeMathJsonDurable } from '../../src/math/mathRuntimeIo'; -import type { MathAgentOptions, MathAgentSession } from '../../src/runtime/codexSession'; -import { readSolverRunState, type SolverRunState } from '../../src/solver/archive'; -import { directSolverModules, type SolverModules } from '../../src/solver/modules'; -import { proofReceiptsMatch, type ProofCheck } from '../../src/solver/modules/evidence'; -import { runSolver } from '../../src/solver/run'; -import { inspectStoredRun } from '../../src/solver/storedRunInspection'; -import { leadPlanDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask, type TaskRecord } from '../../src/solver/tasks'; -import type { NextCheckRecord } from '../../src/solver/nextCheckContract'; -import { queueResearchObservation } from '../../src/solver/researchObservation'; -import { runLeanDiagnostics } from '../../src/math/leanDiagnostics'; - -/** Local arithmetic only: no benchmark statement, answer, model or search service is used. */ -export const COOPERATIVE_REPLAY_SOURCE = `namespace Replay - -def climb : Nat → Nat - | 0 => 0 - | n + 1 => climb n + 1 - -theorem target (n : Nat) : climb n + climb n = n + n := by - sorry - -end Replay -`; -export const COOPERATIVE_REPLAY_TASK = 'Prove Replay.target. Research a precise reusable helper, check it, and apply it to the original target.'; -const HELPER: CooperativeTask = { id: 'climb_identity', kind: 'lemma', ownerId: 'engineer', - objective: 'Induct on n to prove climb is the identity; Replay.target consumes two instances at n.', - proofPath: 'Submission.lean', theoremName: 'Replay.climb_eq', type: '∀ n : Nat, Replay.climb n = n', - dependsOn: [], revision: 0 }; -const QUESTION: CooperativeTask = { id: 'research_bridge', kind: 'research', ownerId: 'researcher-2', - objective: 'Read the frozen recursion for climb and propose its closed induction invariant and its application to Replay.target.', - dependsOn: [], revision: 0 }; -const GOAL: CooperativeTask = { id: 'original', kind: 'goal', ownerId: 'engineer', - objective: 'Prove the original Replay.target using the checked climb identity.', proofPath: 'Submission.lean', - theoremName: 'Replay.target', status: 'paused', conditional: false, dependsOn: [], revision: 0 }; -const HELPER_PROOF = 'by\n intro n\n induction n with\n | zero => rfl\n | succ n ih =>\n change climb n + 1 = n + 1\n exact congrArg (fun value : Nat => value + 1) ih'; -const BAD_HELPER_PROOF = 'by\n intro n\n exact Nat.zero_ne_one'; - -export type CooperativeReplayScenario = 'clean' | 'repair-once' | 'next-check'; -type ScopedCooperation = { tasks: TaskRecord[]; nextChecks?: NextCheckRecord[] }; -type ReplayResearchInput = { deliveryId: string; finding?: string; lemmaRequests?: CooperativeTask[] }; -export type CooperativeReplayTurn = { index: number; workerId: string; role: 'lead' | 'researcher' | 'engineer' | 'reviewer'; - threadId: string; turnId: string; action: CooperativeAction; context: string; output: string; source: string; - injectedFailure: boolean }; - -/** Use the dispatched assignment, including the current nonce on saved-thread continuations. */ -export function cooperativeReplayAssignment(message: string): CooperativeAction { - const matches = [...message.matchAll(/(?:^|\n)(?:Current )?[Cc]ooperative assignment(?: \([^\n]*\))?:\n([^\n]+)/gu)]; - if (!matches.length) throw new Error('cooperative_replay_assignment_missing'); - const action = JSON.parse(matches.at(-1)![1]) as CooperativeAction; - if (!['lead', 'task', 'review'].includes(action?.kind)) throw new Error('cooperative_replay_unexpected_assignment'); - return action; -} - -/** Answer the publications actually shown on this turn, including saved-thread continuations. */ -function replayResearchInputs(message: string): ReplayResearchInput[] { - const matches = [...message.matchAll(/(?:^|\n)Research inputs for this planning decision[^\n]*\n([^\n]+)/gu)]; - return matches.length ? JSON.parse(matches.at(-1)![1]).inputs : []; -} -const exactHelper = (task: CooperativeTask) => taskVersion(task) === taskVersion({ ...HELPER, groupId: task.groupId }); - -/** Only M1.open changes. M1.execute, scheduling, proof checks, integration and S3 remain the normal runtime. */ -export function cooperativeReplayActors(scenario: CooperativeReplayScenario, traceDirectory: string) { - fs.mkdirSync(traceDirectory, { recursive: true, mode: 0o700 }); - const turns: CooperativeReplayTurn[] = []; - let sessions = 0, helperAttempts = 0; - const open = async (options: MathAgentOptions): Promise => { - const workerId = options.environment?.DEEPSCIENTIST_MATH_WORKER_ID; - if (!workerId) throw new Error('cooperative_replay_worker_identity_missing'); - const threadId = options.threadId ?? `scripted-${workerId}-${++sessions}`; - return { threadId, interrupt: async () => {}, close: async () => {}, run: async (message, _id, worktree, onStarted) => { - const action = cooperativeReplayAssignment(message), index = turns.length + 1; - const turnId = `scripted-turn-${index}`; - onStarted(turnId); - const viewFile = path.join(worktree, 'COOPERATION.json'); - const view = fs.existsSync(viewFile) ? JSON.parse(readMathText(viewFile)) as ScopedCooperation : { tasks: [] }; - const sourceFile = path.join(worktree, 'generated/problem/Submission.lean'); - let output: unknown, role: CooperativeReplayTurn['role'], injectedFailure = false; - if (action.kind === 'lead') { - role = 'lead'; - if (!view.tasks.length) output = { tasks: [QUESTION, GOAL] }; - else { - const helper = view.tasks.find(node => node.task.id === HELPER.id); - const inputs = replayResearchInputs(message); - const proposal = inputs.flatMap(input => input.lemmaRequests ?? []).find(exactHelper); - // Keep a live original frontier; conditional:false waits for genuine helper integration. - const changes = !helper && proposal - ? [proposal, { id: GOAL.id, status: 'active', dependsOn: [HELPER.id] }] : []; - output = { baseVersion: action.planVersion, upsert: changes, - researchDecisions: inputs.map(input => !helper && proposal && input.lemmaRequests?.some(exactHelper) - ? { deliveryId: input.deliveryId, outcome: 'adopt', taskIds: [proposal.id], - reason: 'Assign the exact universally quantified climb identity and connect it to the original target.' } - : { deliveryId: input.deliveryId, outcome: 'decline', - reason: scenario === 'next-check' && input.finding && JSON.parse(input.finding).conclusion === 'inconclusive' - ? 'The inconclusive invariant is handled by the host next-check before assigning its formal proof.' - : helper ? 'The exact climb identity is already assigned; this finding needs no further task change.' - : 'This finding does not supply the exact universally quantified climb identity needed by Replay.target.' }), - ...(scenario === 'next-check' ? { nextCheckDecisions: (view.nextChecks ?? []) - .filter(check => check.status === 'awaiting-decision').map(check => ({ checkId: check.id, - outcomeDeliveryId: check.outcome!.deliveryId, action: 'continue', - reason: 'The saved Lean probe checks the induction invariant. Adopt the exact helper for independent proof checking.' })) } : {}) }; - } - // Publish through the same nonce-bound live intake used by a real Lead. - const file = leadPlanDeliveryFile(action); - if (!file) throw new Error('cooperative_replay_plan_delivery_missing'); - fs.appendFileSync(path.join(worktree, file), JSON.stringify({ kind: 'plan', - dispatchNonce: action.planNonce ?? action.initialPlanNonce, baseVersion: action.planVersion, - summary: 'Adopt the exact research interface, then connect the independently checked helper to the original goal.', - ...output as Record }) + '\n', { mode: 0o600 }); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), 'The recursion is closed by induction; the target uses the checked identity twice.\n\n' + - '```math-plan\n' + JSON.stringify(output) + '\n```\n'); - } else if (action.kind === 'review') { - role = 'reviewer'; - output = { commit: action.seedCommit, verdict: 'accepted', - summary: 'The fixed original target uses the checked climb identity; its premises and frozen statement are preserved.', - evidenceRefs: ['Replay.target', 'Replay.climb_eq'] }; - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), '```math-review\n' + JSON.stringify(output) + '\n```\n'); - } else if (action.kind === 'task' && action.task.id === QUESTION.id) { - role = 'researcher'; - output = scenario === 'next-check' ? { - summary: 'Test the induction invariant before assigning its formal proof.', conclusion: 'inconclusive', needsDecision: true, - mathematicalGap: { consumer: { taskId: GOAL.id, taskDigest: taskVersion(view.tasks.find(node => node.task.id === GOAL.id)!.task) }, - previousGap: 'The recursion must be connected to the target.', reduced: 'The two occurrences share one candidate invariant.', - remaining: 'Prove climb n = n for every natural number n and then apply it twice.', evidenceScope: 'Proposed invariant, not yet checked.', - reconsiderWhen: ['A Lean check of the induction invariant.'], - nextCheck: { action: 'construction-check', objective: 'Check the induction proof for climb n = n in a disposable probe.', - expectedEvidence: 'A complete saved Lean probe compiling without errors, or its exact failed goal.', targetTaskId: GOAL.id } }, - } : { summary: 'Induction proves climb n = n. Rewrite both climb applications in Replay.target.', - conclusion: 'supporting', needsDecision: true, lemmaRequests: [HELPER], - evidenceRefs: ['generated/problem/Challenge.lean:Replay.climb', 'Nat.rec'], remainingObligations: [], - finding: 'Base case is reflexivity. In the successor case apply congrArg (fun value : Nat => value + 1) to the induction hypothesis. ' + - 'The consumer is Replay.target; rewriting by the resulting identity closes both occurrences.' }; - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), JSON.stringify(output) + '\n'); - } else if (action.kind === 'task' && scenario === 'next-check' && view.nextChecks?.some(check => check.taskId === action.task.id)) { - role = 'researcher'; - const check = view.nextChecks.find(check => check.taskId === action.task.id)!; - const project = path.join(worktree, 'generated/problem'); - const probe = path.join(project, 'InvariantProbe.lean'); - fs.mkdirSync(path.dirname(probe), { recursive: true }); - fs.writeFileSync(probe, COOPERATIVE_REPLAY_SOURCE.replace('theorem target (n : Nat) : climb n + climb n = n + n := by\n sorry', - 'theorem climb_eq : ∀ n : Nat, climb n = n := ' + HELPER_PROOF)); - const diagnostics = await runLeanDiagnostics({ projectRoot: project, files: [path.basename(probe)], - env: process.env, timeoutMs: 60_000, signal: new AbortController().signal }); - if (diagnostics.exitCode !== 0 || diagnostics.timedOut) throw new Error('cooperative_replay_probe_failed:' + JSON.stringify(diagnostics)); - output = { summary: 'The complete induction probe passed Lean; the formal helper still needs host acceptance.', - conclusion: 'supporting', needsDecision: true, lemmaRequests: [HELPER], - checkOutcome: { checkId: check.id, conclusion: 'supporting', summary: 'The local induction probe compiles.', evidenceRefs: ['RESEARCH.md:Replay.climb_eq'] }, - leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['Replay.climb_eq'] }] }; - queueResearchObservation({ worktree, finding: output, probes: [probe] }); - fs.rmSync(probe); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), 'The observation has been published with its retained probe. Read its host receipt.\n'); - } else if (action.kind === 'task' && action.task.id === HELPER.id) { - role = 'engineer'; - injectedFailure = scenario === 'repair-once' && helperAttempts++ === 0; - const declaration = 'theorem climb_eq : ∀ n : Nat, climb n = n := ' + - (injectedFailure ? BAD_HELPER_PROOF : HELPER_PROOF) + '\n\n'; - const source = readMathText(sourceFile); - fs.writeFileSync(sourceFile, source.includes('theorem climb_eq') - ? source.replace(/theorem climb_eq[\s\S]*?(?=theorem target)/u, declaration) - : source.replace('theorem target', declaration + 'theorem target')); - output = { summary: injectedFailure ? 'One intentionally invalid induction proof tests normal host rejection and repair.' - : 'The exact typed helper is proved by induction. The original target can now use the checked identity.', - evidenceRefs: ['Replay.climb_eq'] }; - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), JSON.stringify(output) + '\n'); - } else if (action.kind === 'task' && action.task.id === GOAL.id) { - role = 'engineer'; - fs.writeFileSync(sourceFile, readMathText(sourceFile).replace( - /theorem target[^]*?(?=\nend Replay)/u, - 'theorem target (n : Nat) : climb n + climb n = n + n := by\n rw [climb_eq n]\n')); - output = { summary: 'Replay.target applies the independently checked climb identity to both summands.', - evidenceRefs: ['Replay.climb_eq', 'Replay.target'] }; - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), JSON.stringify(output) + '\n'); - } else throw new Error(`cooperative_replay_unexpected_task:${action.kind === 'task' ? action.task.id : action.kind}`); - options.onUsage({ inputTokens: 0, outputTokens: 0, totalTokens: 0 }); - const prefix = path.join(traceDirectory, String(index).padStart(3, '0')); - fs.writeFileSync(prefix + '.context.txt', options.instructions + '\n\n' + message, { mode: 0o600 }); - fs.writeFileSync(prefix + '.output.md', readMathText(path.join(worktree, 'RESEARCH.md')), { mode: 0o600 }); - fs.writeFileSync(prefix + '.lean', readMathText(sourceFile), { mode: 0o600 }); - turns.push({ index, workerId, role, threadId, turnId, action, context: prefix + '.context.txt', - output: prefix + '.output.md', source: prefix + '.lean', injectedFailure }); - writeMathJsonDurable(path.join(traceDirectory, 'turns.json'), turns); - return 'completed'; - } }; - }; - const modules: SolverModules = { ...directSolverModules, id: `${directSolverModules.id}/scripted-zero-model-${scenario}`, - M1: { ...directSolverModules.M1, version: `scripted-zero-model-${scenario}-v1`, open } }; - return { modules, turns }; -} - -/** Read only recorded acceptance. A scripted completed/verdict string never establishes this value. */ -export function cooperativeReplayAccepted(state: SolverRunState, result: Record) { - const evaluator = result.evaluator as { status?: string; method?: string; verification?: ProofCheck } | undefined; - const check = evaluator?.verification; - return state.phase === 'finished' && result.status === 'evaluated_passed' && result.completion_signal_valid === true && - result.solver_ready_receipt_valid === true && state.check?.passed === true && result.solution_commit === state.check.commit && - evaluator?.status === 'passed' && evaluator.method === 'host-lean-kernel-all-targets' && check?.passed === true && - check.commit === state.check.commit && check.sourceDigest === state.check.sourceDigest && state.problem.targets.length > 0 && - proofReceiptsMatch(check.verification, check.commit, state.problem.targets.map(target => ({ - proofPath: target.proofPath, theoremName: target.theoremName, expectedSourceDeclarationHash: target.declarationHash, - statementHash: state.problem.contract.statementHash, leanStatementHash: state.problem.contract.leanStatementHash, claim: 'statement' }))); -} - -async function replayScenario(directory: string, root: string, buildManifestRef: string, scenario: CooperativeReplayScenario) { - fs.mkdirSync(directory, { mode: 0o700 }); - const workspace = path.join(directory, 'workspace'), output = path.join(directory, 'result.json'); - const task = path.join(directory, 'task.md'), log = path.join(directory, 'events.jsonl'); - fs.writeFileSync(task, COOPERATIVE_REPLAY_TASK + '\n', { mode: 0o400 }); - bootstrapLeanTask(workspace, { source: COOPERATIVE_REPLAY_SOURCE, task: COOPERATIVE_REPLAY_TASK, environment: 'standard' }); - const actors = cooperativeReplayActors(scenario, path.join(directory, 'turns')); - const previousLog = console.log; - let code: number; - // runSolver's normal event sink is stdout. Persist every line and restore it even on failure. - console.log = (...values: unknown[]) => { - fs.appendFileSync(log, values.map(value => typeof value === 'string' ? value : JSON.stringify(value)).join(' ') + '\n', { mode: 0o600 }); - }; - try { - code = await runSolver(['--workspace', workspace, '--task-file', task, '--output', output, - '--build-manifest', buildManifestRef, '--workers', '4', '--coordination', 'cooperative', - '--max-turns', '24', '--max-run-seconds', '600', '--max-turn-seconds', '120', - '--model', 'scripted-zero-model', '--effort', 'none', '--codex', 'scripted-zero-model', '--no-explanations'], root, actors.modules); - } finally { console.log = previousLog; } - const stateFile = path.join(output + '.runtime', 'state.json'); - const state = readSolverRunState(stateFile), result = JSON.parse(readMathText(output)) as Record; - const events = readMathText(log).trim().split('\n').flatMap(line => { - try { const event = JSON.parse(line) as Record; return typeof event.event === 'string' ? [event] : []; } - catch { return []; } - }); - const inspection = await inspectStoredRun(output, { journal: { logFile: log } }); - const inspectionFile = path.join(directory, 'inspection.json'); - writeMathJsonDurable(inspectionFile, inspection); - const helper = state.cooperation?.tasks.find(node => node.task.id === HELPER.id); - const goal = state.cooperation?.tasks.find(node => node.task.id === GOAL.id); - const helperUsed = goal?.integratedCheck?.references?.proof.some(reference => reference.name === HELPER.theoremName) ?? false; - const count = (name: string) => events.filter(event => event.event === name).length; - const report = { scenario, mode: 'scripted-zero-model' as const, modelInvoked: false, exitCode: code, - accepted: cooperativeReplayAccepted(state, result), status: result.status, runId: state.runId, - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, buildDigest: state.buildDigest, - roles: ['lead', 'researcher', 'engineer', 'reviewer'].map(role => ({ role, - turns: actors.turns.filter(turn => turn.role === role).length, - workerIds: [...new Set(actors.turns.filter(turn => turn.role === role).map(turn => turn.workerId))] })), - dispatchCounts: state.dispatchCounts, workerDispatches: state.workers?.map(worker => ({ id: worker.id, - role: worker.role, turns: worker.turns, dispatchCounts: worker.dispatchCounts })), - planPublications: count('initial_plan_published') + count('plan_published'), planRevisions: count('plan_published'), - failedChecks: events.filter(event => event.event === 'task_checked' && event.passed === false).length, - failedInputRecords: (state.cooperation?.failedTaskInputs ?? []).length, - repeatedFailures: count('task_attempt_repeated_advisory'), - injectedFailures: actors.turns.filter(turn => turn.injectedFailure).length, - waits: { observations: count('dispatch_wait'), ended: count('dispatch_wait_ended'), - duration: 'not-inferred-from-observation-times' }, - helper: { integrated: helper?.status === 'integrated' && helper.integratedCheck?.passed === true, usedByOriginal: helperUsed }, - reviewer: state.cooperation?.review, evaluation: result.evaluator, - nextChecks: (state.cooperation?.nextChecks ?? []).map(check => ({ id: check.id, status: check.status, - outcome: check.outcome?.conclusion, decision: check.decision?.action, - decisionApplied: Boolean(check.decision && events.some(event => event.event === 'next_check_decided' && - event.checkId === check.id && event.outcomeDeliveryId === check.outcome?.deliveryId && event.action === check.decision!.action)) })), - artifacts: { output, stateFile, log, inspection: inspectionFile, turns: path.join(directory, 'turns/turns.json') } }; - writeMathJsonDurable(path.join(directory, 'report.json'), report); - return report; -} - -/** Same local mathematics through clean proof, proof repair and the research next-check loop. */ -export async function replayCooperative(directory: string, root: string, buildManifestRef: string) { - if (fs.existsSync(directory)) throw new Error('Replay directory already exists; use a new directory.'); - const manifest = readMathBuildManifest(buildManifestRef, root, path.join(root, 'out/main')); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - writeMathJsonDurable(path.join(directory, 'fixture.json'), { schema: 'theorem-os.cooperative-replay-fixture.v1', - source: COOPERATIVE_REPLAY_SOURCE, task: COOPERATIVE_REPLAY_TASK, - sourceDigest: mathDigest(COOPERATIVE_REPLAY_SOURCE), taskDigest: mathDigest(COOPERATIVE_REPLAY_TASK + '\n'), - buildManifestRef, buildManifestDigest: mathDigest(canonicalMathJson(manifest)), - roles: 'default four workers; researcher-1 supplies the independently assigned fixed-candidate review', - configuration: { workers: 4, maxTurns: 24, maxRunSeconds: 600, maxTurnSeconds: 120 }, - scenarios: ['clean', 'repair-once', 'next-check'] }); - const runs = []; - for (const scenario of ['clean', 'repair-once', 'next-check'] as const) - runs.push(await replayScenario(path.join(directory, scenario), root, buildManifestRef, scenario)); - const passed = runs.every(run => run.accepted && run.exitCode === 0 && run.helper.integrated && run.helper.usedByOriginal && - run.roles.every(role => role.turns > 0)) && runs[1].injectedFailures === 1 && runs[1].failedChecks >= 1 && - // Adopting the helper changes the consumer contract: the consumed historical check becomes stale. - runs[2].nextChecks.some(check => check.decisionApplied && check.outcome === 'supporting' && check.decision === 'continue'); - const report = { schema: 'theorem-os.cooperative-replay.v1', mode: 'scripted-zero-model', modelInvoked: false, - passed, directory, runs, comparisonKind: 'controlled-fault-recovery', - evidence: 'Fresh Git commits, real Lean checks, independent fixed-candidate review and S3; only model transport is scripted.', - limitation: 'These controlled scenarios verify collaboration and rejection/recovery. They do not estimate model solve rates, token savings, or a causal improvement over another solver policy.' }; - writeMathJsonDurable(path.join(directory, 'report.json'), report); - return report; -} - -export async function cooperativeReplay(argv: string[], root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')) { - const flags = parseFlags(argv, ['directory', 'build-manifest']); - if (flags.has('help')) { - console.log('Usage: bun scripts/mathematics/cooperativeReplay.ts --directory NEW_EXTERNAL_DIR --build-manifest FILE\n' + - 'Uses an existing current build; writes no runtime bundle and invokes no model. Saves all three complete four-role scenarios.'); - return 0; - } - const report = await replayCooperative(path.resolve(required(flags, 'directory')), root, fs.realpathSync(required(flags, 'build-manifest'))); - console.log(JSON.stringify(report, null, 2)); - return report.passed ? 0 : 1; -} - -if (import.meta.main) cooperativeReplay(process.argv.slice(2)).then(code => { process.exitCode = code; }, error => { - console.error(error); process.exitCode = 1; -}); diff --git a/scripts/mathematics/editMathRun.ts b/scripts/mathematics/editMathRun.ts index 2a505f6d..a4ede007 100644 --- a/scripts/mathematics/editMathRun.ts +++ b/scripts/mathematics/editMathRun.ts @@ -1,17 +1,22 @@ #!/usr/bin/env bun import { parseArgs } from 'node:util'; -import { readMathText } from '../../src/math/mathRuntimeIo'; -import { queueRunEdit } from '../../src/solver/humanEdit'; +import { randomUUID } from 'node:crypto'; +import { queuePlanApproval } from '../../src/solver/humanEdit'; +import { readRunInspection } from '../../src/solver/inspection'; +import { assertActiveResearchState, legacyCollaborationRetired } from '../../src/solver/researchRetirement'; try { const { values } = parseArgs({ args: process.argv.slice(2), options: { run: { type: 'string' }, plan: { type: 'string' }, 'dry-run': { type: 'boolean' }, help: { type: 'boolean' }, + 'approve-plan': { type: 'string' }, } }); - if (values.help) console.log('Usage: theorem-os edit --run RESULT_OR_STATE --plan FILE [--dry-run]\nValidates and queues a versioned plan edit. The running or resumed solver applies it and separately rechecks affected proofs.'); + if (values.help) console.log('Usage: theorem-os edit --run RESULT_OR_STATE --approve-plan VERSION\n' + + 'Inspect the exact route version before approving it. Use the historical release for legacy plan edits.'); else { - if (!values.run || !values.plan) throw new Error('--run and --plan are required'); - const { id, status, baseVersion } = await queueRunEdit(values.run, JSON.parse(readMathText(values.plan, 1024 * 1024)), values['dry-run']); - console.log(JSON.stringify({ id, status, baseVersion })); + if (values.plan !== undefined || values['dry-run']) throw new Error(legacyCollaborationRetired); + if (!values.run || !values['approve-plan']) throw new Error('--run and --approve-plan are required'); + assertActiveResearchState(readRunInspection(values.run).state); + console.log(JSON.stringify(await queuePlanApproval(values.run, { id: randomUUID(), planVersion: values['approve-plan'] }))); } } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; diff --git a/scripts/mathematics/importProofFragment.ts b/scripts/mathematics/importProofFragment.ts deleted file mode 100644 index 6baf53e1..00000000 --- a/scripts/mathematics/importProofFragment.ts +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env bun -import { parseArgs } from 'node:util'; -import { queueProofImport } from '../../src/solver/proofImport'; - -try { - const { values } = parseArgs({ args: process.argv.slice(2), options: { - run: { type: 'string' }, task: { type: 'string' }, fragment: { type: 'string' }, sha256: { type: 'string' }, - 'base-version': { type: 'string' }, id: { type: 'string' }, 'dry-run': { type: 'boolean' }, help: { type: 'boolean' }, - 'before-theorem': { type: 'string' }, - } }); - if (values.help) console.log('Usage: theorem-os import-proof --run RESULT_OR_STATE --task TASK --fragment FILE --sha256 SHA256 --base-version VERSION [--id ID] [--before-theorem NAME] [--dry-run]\nQueues pure theorem/lemma declarations for a pending lemma task. --before-theorem places the fragment before an existing declaration in the same namespace so earlier consumers can use it. The assigned worker imports them before opening a model; the host independently checks the frozen proof and canonical merge. Existing source context and declarations are preserved.'); - else { - if (!values.run || !values.task || !values.fragment || !values.sha256 || !values['base-version']) - throw new Error('--run, --task, --fragment, --sha256 and --base-version are required'); - console.log(JSON.stringify(await queueProofImport(values.run, { taskId: values.task, fragmentFile: values.fragment, - sha256: values.sha256, baseVersion: values['base-version'], id: values.id, - beforeTheorem: values['before-theorem'] }, values['dry-run']))); - } -} catch (error) { - console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; -} diff --git a/scripts/mathematics/planApply.ts b/scripts/mathematics/planApply.ts deleted file mode 100644 index 055c9b26..00000000 --- a/scripts/mathematics/planApply.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { runPlanCommand } from './planCommand'; - -runPlanCommand('plan-apply', process.argv.slice(2)); diff --git a/scripts/mathematics/planCommand.ts b/scripts/mathematics/planCommand.ts index 0997679b..bc3e01a8 100644 --- a/scripts/mathematics/planCommand.ts +++ b/scripts/mathematics/planCommand.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import { parseArgs } from 'node:util'; import { MAX_RESEARCH_NOTES_BYTES } from '../../src/solver/deliveries'; -import { applyCooperationPlanFile, publishCooperationPlanFile, validateCooperationPlanFile } from '../../src/solver/planTool'; +import { validateCooperationPlanFile } from '../../src/solver/planTool'; function readStandardInput(): string { const bytes = Buffer.alloc(MAX_RESEARCH_NOTES_BYTES + 1); @@ -15,19 +15,18 @@ function readStandardInput(): string { return new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length)); } -export function runPlanCommand(command: 'plan-validate' | 'plan-apply', args: string[]): void { - const usage = `theorem-os ${command} [--file FILE] [--workspace DIR]` + (command === 'plan-apply' ? ' [--publish]' : ''); +export function runPlanCommand(args: string[]): void { + const usage = 'theorem-os plan-validate [--file FILE] [--workspace DIR]'; let field = 'arguments'; try { const { values } = parseArgs({ args, options: { file: { type: 'string' }, workspace: { type: 'string' }, worktree: { type: 'string' }, - ...(command === 'plan-apply' ? { publish: { type: 'boolean' as const } } : {}), help: { type: 'boolean', short: 'h' }, } }); if (values.help) { console.log(JSON.stringify({ usage, description: 'Read a complete plan or revision from --file or stdin. ' + 'Use the Lead workspace with COOPERATION.json, or a prepared workspace with active-problem.json. ' + - (command === 'plan-apply' ? 'Save a validated draft in RESEARCH.md, or use --publish to queue it for the current Lead dispatch.' : 'Report validation issues.') })); + 'Report validation issues.' })); return; } if (values.worktree && values.workspace) throw new Error('Choose --workspace or --worktree.'); @@ -37,8 +36,7 @@ export function runPlanCommand(command: 'plan-validate' | 'plan-apply', args: st field = 'stdin'; input = { workspace, text: readStandardInput() }; } else input = { workspace, file: values.file }; - const result = values.publish ? publishCooperationPlanFile(input) : - command === 'plan-apply' ? applyCooperationPlanFile(input) : validateCooperationPlanFile(input); + const result = validateCooperationPlanFile(input); console.log(JSON.stringify(result)); if (!result.ok) process.exitCode = 1; } catch (error) { diff --git a/scripts/mathematics/planValidate.ts b/scripts/mathematics/planValidate.ts index b9fe057b..a899ccef 100644 --- a/scripts/mathematics/planValidate.ts +++ b/scripts/mathematics/planValidate.ts @@ -1,3 +1,3 @@ import { runPlanCommand } from './planCommand'; -runPlanCommand('plan-validate', process.argv.slice(2)); +runPlanCommand(process.argv.slice(2)); diff --git a/scripts/mathematics/proofSearch.ts b/scripts/mathematics/proofSearch.ts deleted file mode 100644 index e74df6e8..00000000 --- a/scripts/mathematics/proofSearch.ts +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bun -import { parseArgs } from 'node:util'; -import { readMathText } from '../../src/math/mathRuntimeIo'; -import { runProofSearchTool } from '../../src/solver/proofSearchTool'; -import { currentWorkerProject } from '../../src/solver/workerProject'; - -async function main() { - const args = process.argv.slice(2); if (args[0] === 'proof-search') args.shift(); - const { values } = parseArgs({ args, options: { workspace: { type: 'string' }, worktree: { type: 'string' }, file: { type: 'string' }, - theorem: { type: 'string' }, 'request-file': { type: 'string' }, help: { type: 'boolean' } } }); - if (values.help) { - console.log('Usage: theorem-os proof-search (--workspace PROJECT | --worktree ROOT) --request-file JSON [--file FILE --theorem NAME]\n' - + 'Requires a host-assigned closed helper lemma in COOPERATION.json and an explicitly pinned compatible Pantograph backend.\n' - + 'Request: {"branches":[{"tactics":["intro n","simp"]}],"limits":{"timeoutMs":30000,"maxTransitions":64}}\n' - + 'To continue, add resume:{path,digest} and optionally branches[].from (the logical node digest).\n' - + 'Each call replays required prefixes and releases its backend. Checkpoints and candidates are advisory; existing ready/freeze/checker/S3 acceptance is required.\n' - + 'Partial Aesop candidate: "aesop (config := { terminal := false })". No model calls or package installation.'); - return; - } - if (Boolean(values.workspace) === Boolean(values.worktree) || !values['request-file']) - throw new Error('Exactly one of --workspace/--worktree, and --request-file, are required'); - const controller = new AbortController(), abort = () => controller.abort(); - process.once('SIGINT', abort); process.once('SIGTERM', abort); - try { - const result = await runProofSearchTool({ projectRoot: values.workspace ?? currentWorkerProject(values.worktree!), file: values.file, theoremName: values.theorem, - request: JSON.parse(readMathText(values['request-file'], 256_000)), signal: controller.signal }); - console.log(JSON.stringify(result)); - process.exitCode = ['candidate', 'exhausted', 'budget-exhausted'].includes(result.status) ? 0 : result.status === 'cancelled' ? 130 : 1; - } finally { process.removeListener('SIGINT', abort); process.removeListener('SIGTERM', abort); } -} -void main().catch(error => { - console.error(JSON.stringify({ authority: 'advisory-proof-search', proofAcceptance: 'not-accepted', - status: 'unavailable', reason: error instanceof Error ? error.message : 'proof_search_failed' })); - process.exitCode = 1; -}); diff --git a/scripts/mathematics/researchObserve.ts b/scripts/mathematics/researchObserve.ts deleted file mode 100644 index a77b17a5..00000000 --- a/scripts/mathematics/researchObserve.ts +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bun -import { parseArgs } from 'node:util'; -import { readMathText } from '../../src/math/mathRuntimeIo'; -import { ResearchAdmissionError } from '../../src/solver/researchAdmission'; -import { queueResearchObservation } from '../../src/solver/researchObservation'; - -const example = `mkdir -p .scratch -printf '%s\\n' '{"conclusion":"inconclusive","summary":"The construction remains unresolved.","remainingObligations":["Establish the missing bound."]}' > .scratch/finding.json -theorem-os research-observe --worktree "$PWD" --finding .scratch/finding.json`; - -function readFinding(file: string): unknown { - const reject = (code: string, message: string): never => { - throw new ResearchAdmissionError({ status: 'rejected', code, issues: [{ path: '--finding', message }], - recovery: 'correct-and-resubmit' }); - }; - if (/^\s*[\[{]/u.test(file)) reject('math_observation_finding_file_required', - '--finding expects a JSON file path. Save the finding in .scratch/finding.json, then pass --finding .scratch/finding.json. Run --help for a complete example.'); - let text: string; - try { text = readMathText(file, 1_000_000); } - catch (error) { - reject('math_observation_finding_file_unreadable', - 'Cannot read the --finding JSON file. Use an existing regular file path relative to the current directory or an absolute path. ' + - (error instanceof Error ? error.message : 'File read failed.')); - } - try { return JSON.parse(text); } - catch { return reject('math_observation_finding_json_invalid', - 'The --finding file must contain one JSON object, without Markdown fences or surrounding notes. Correct the file and resubmit.'); } -} - -export function main(argv: string[]) { - const { values } = parseArgs({ args: argv, options: { - worktree: { type: 'string' }, finding: { type: 'string' }, probe: { type: 'string', multiple: true }, - 'snapshot-sources': { type: 'boolean' }, help: { type: 'boolean' }, - } }); - if (values.help) return { usage: 'theorem-os research-observe --worktree DIR --finding FILE [--probe FILE ...] [--snapshot-sources]', - description: 'Validate and queue one advisory finding from a JSON file. Replace the example content with your actual finding and run it from your worktree. Retain complete Lean probes before restoring scratch files. The host binds the event and independently checks formal proofs.', - example }; - if (!values.worktree || !values.finding) throw new Error('--worktree and --finding are required'); - return queueResearchObservation({ worktree: values.worktree, finding: readFinding(values.finding), - probes: values.probe, snapshotSources: values['snapshot-sources'] }); -} - -if (import.meta.main) { - try { console.log(JSON.stringify(main(process.argv.slice(2)))); } - catch (error) { - console.error(JSON.stringify(error instanceof ResearchAdmissionError ? error.admission : { - status: 'rejected', code: error instanceof Error ? error.message : 'math_observation_failed', recovery: 'correct-and-resubmit' })); - process.exitCode = 1; - } -} diff --git a/scripts/mathematics/runExample.ts b/scripts/mathematics/runExample.ts index 016c8066..1a6bbac0 100644 --- a/scripts/mathematics/runExample.ts +++ b/scripts/mathematics/runExample.ts @@ -58,7 +58,7 @@ async function main(): Promise { component: { type: 'string' }, workers: { type: 'string' }, help: { type: 'boolean' }, } }); if (values.help) { - console.log(`Usage: theorem-os example prepare|check|solve|resume|replay --dir DIR [--component NAME] [--workers 1..${MAX_RESEARCH_WORKERS}] [--model MODEL] [--effort LEVEL] [--codex FILE]\nprepare: create a small Lean-only problem and freeze the build and configuration.\ncheck: run the startup preflight without a model.\nsolve / resume: use the saved configuration (default: single agent, unlimited dispatches, time and tokens).\nreplay: prepare a NEW directory and check two preset candidates with real Lean; no model or provider connection.\n--component uses src/components/NAME.ts; M3.ready ordering is exercised by cooperative model runs with at least 3 workers.\nInstall leanprover/lean4:v4.33.0 first. Keep the same build and environment when resuming.`); + console.log(`Usage: theorem-os example prepare|check|solve|resume|replay --dir DIR [--model MODEL] [--effort LEVEL] [--codex FILE]\nprepare: create a small Lean-only problem and freeze the build and configuration.\ncheck: run the startup preflight without a model.\nsolve / resume: use the saved configuration (default: single agent, unlimited dispatches, time and tokens).\nreplay: prepare a NEW directory and check two preset candidates with real Lean; no model or provider connection.\nUse the pinned historical revision to prepare cooperative or custom-component examples.\nInstall leanprover/lean4:v4.33.0 first. Keep the same build and environment when resuming.`); return 0; } const action = positionals[0]; @@ -77,6 +77,8 @@ async function main(): Promise { assertMathCanonicalPath(file); fs.accessSync(file, fs.constants.R_OK); } + if (action === 'prepare' && (workers > 1 || values.component)) + throw new Error('Prepare cooperative or custom-component examples from their pinned historical TheoremOS revision.'); if (action === 'prepare' || action === 'replay') await prepare(directory, { mode: action === 'replay' ? 'replay' : 'model', component: values.component, workers, model: values.model || 'deepseek-flash', effort: values.effort || 'high', codex: values.codex, @@ -99,6 +101,8 @@ async function main(): Promise { args.push('--startup-only'); if (fs.existsSync(`${output}.runtime/state.json`)) args.push('--resume'); } else if (action === 'resume') args.push('--resume'); + if (config.mode === 'model' && !args.includes('--resume') && (config.workers > 1 || config.component)) + throw new Error('Start this prepared example from its pinned historical TheoremOS revision.'); const custom = config.component ? (await import(pathToFileURL(componentPaths(root, config.component).source).href)).modules as SolverModules : undefined; if (config.component && typeof custom?.M3?.ready !== 'function') throw new Error('The component must export modules with M3.ready.'); const stateFile = `${output}.runtime/state.json`; diff --git a/scripts/mathematics/runGoalsFirst.ts b/scripts/mathematics/runGoalsFirst.ts index d20c9f86..7b2fb074 100644 --- a/scripts/mathematics/runGoalsFirst.ts +++ b/scripts/mathematics/runGoalsFirst.ts @@ -18,7 +18,7 @@ const modules: SolverModules = { process.env.CODEX_HOME ||= path.join(os.homedir(), '.config', 'deepscientist', 'math-sol-codex'); const root = path.resolve(path.dirname(fs.realpathSync(process.argv[1])), '../..'); -runSolver(process.argv.slice(2), root, modules).then( +runSolver(process.argv.slice(2), root, modules, undefined, 'historical-component').then( code => { process.exitCode = code; }, error => { console.error(error instanceof Error ? error.message : 'math_run_failed'); process.exitCode = 1; } ); diff --git a/scripts/mathematics/runMathProof.ts b/scripts/mathematics/runMathProof.ts index 0b279d82..8e84bdae 100644 --- a/scripts/mathematics/runMathProof.ts +++ b/scripts/mathematics/runMathProof.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import fs from 'node:fs'; import { runSolver } from '../../src/solver/run'; -runSolver(process.argv.slice(2), path.resolve(path.dirname(fs.realpathSync(process.argv[1])), '../..')).then( +runSolver(process.argv.slice(2), path.resolve(path.dirname(fs.realpathSync(process.argv[1])), '../..'), undefined, undefined, 'cli').then( code => { process.exitCode = code; }, error => { console.error(error instanceof Error ? error.message : 'math_run_failed'); process.exitCode = 1; } ); diff --git a/scripts/mathematics/samplePutnamRuns.ts b/scripts/mathematics/samplePutnamRuns.ts index 6603e69e..774868d1 100644 --- a/scripts/mathematics/samplePutnamRuns.ts +++ b/scripts/mathematics/samplePutnamRuns.ts @@ -34,9 +34,14 @@ const prepareOptions = ['repo', 'count', 'seed', 'build-manifest', 'module-exper 'evaluator-timeout-seconds', 'proof-environment-cache-dir', 'knowledge-base', 'knowledge-mode']; type ComparisonPlan = Parameters[1]; -export async function samplePutnamRuns(argv: string[]): Promise { +export async function samplePutnamRuns(argv: string[], historicalReportsOnly = false): Promise { const flags = parseFlags(argv, ['phase', 'directory', ...prepareOptions]); if (flags.has('help')) { + if (historicalReportsOnly) { + console.log('Usage: theorem-os sample-putnam --phase report|check-report --directory DIR\n' + + 'Prepare legacy samples from their pinned historical TheoremOS revision.'); + return 0; + } console.log('Usage: theorem-os sample-putnam --phase prepare|report|check-report --directory DIR\n' + 'prepare requires --repo PUTNAM_REPO --build-manifest FILE; defaults to 3 proof-only problems, a fixed sampling seed, ' + 'sub2api deepseek-flash/max and the four module plans.\n' @@ -47,6 +52,8 @@ export async function samplePutnamRuns(argv: string[]): Promise { } const phase = required(flags, 'phase'); if (!['prepare', 'report', 'check-report'].includes(phase)) throw new Error('sample-putnam supports only --phase prepare, report or check-report'); + if (historicalReportsOnly && phase === 'prepare') + throw new Error('Prepare legacy PutnamBench comparisons from their pinned historical TheoremOS revision.'); const directory = path.resolve(required(flags, 'directory')); assertMathCanonicalPath(directory); if (isMathPathWithin(root, directory)) throw new Error('Keep PutnamBench experiments outside the source checkout.'); @@ -177,7 +184,7 @@ export async function samplePutnamRuns(argv: string[]): Promise { } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - samplePutnamRuns(process.argv.slice(2)).then(code => { process.exitCode = code; }).catch(error => { + samplePutnamRuns(process.argv.slice(2), true).then(code => { process.exitCode = code; }).catch(error => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); } diff --git a/scripts/mathematics/seedContinuation.ts b/scripts/mathematics/seedContinuation.ts index 9b647a05..374c220a 100644 --- a/scripts/mathematics/seedContinuation.ts +++ b/scripts/mathematics/seedContinuation.ts @@ -2,7 +2,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseFlags, required } from './arguments'; -import { seedSolverContinuation } from '../../src/solver/continuationSeed'; +import { seedSingleSolverContinuation } from '../../src/solver/singleContinuationSeed'; try { const flags = parseFlags(process.argv.slice(2), ['source-run', 'run', 'build-manifest', 'timeout-seconds']); @@ -13,7 +13,7 @@ try { const controller = new AbortController(), abort = () => controller.abort(); process.once('SIGINT', abort); process.once('SIGTERM', abort); try { - const report = await seedSolverContinuation({ sourceRun: required(flags, 'source-run'), run: required(flags, 'run'), + const report = await seedSingleSolverContinuation({ sourceRun: required(flags, 'source-run'), run: required(flags, 'run'), buildManifest: required(flags, 'build-manifest'), root: path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'), signal: controller.signal, timeoutMs: timeout === 0 ? Infinity : timeout * 1000, onProgress: (event, details) => console.log(JSON.stringify({ event, ...details })) }); diff --git a/scripts/test-codex-backend-delivery.ts b/scripts/test-codex-backend-delivery.ts index 4d0e8d91..e791ea52 100644 --- a/scripts/test-codex-backend-delivery.ts +++ b/scripts/test-codex-backend-delivery.ts @@ -20,7 +20,7 @@ import { buildAgentTeamContributions } from '../src/solver/agentTeamContribution import { evaluateSolverProof } from '../src/solver/evaluation'; import { directSolverModules } from '../src/solver/modules'; import { git, readSolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { runResearchLead } from '../src/solver/research'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; type Json = Record; @@ -35,7 +35,7 @@ function freezeRuntime(repository: string, runtime: string) { fs.cpSync(path.join(repository, relative), destination, { recursive: true }); } const bundleRoot = path.join(runtime, 'out/main'); - buildSync({ entryPoints: Object.fromEntries(['runMathProof', 'searchLean', 'checkLean', 'proofSearch'] + buildSync({ entryPoints: Object.fromEntries(['runMathProof', 'searchLean', 'checkLean'] .map((name, index) => [MATH_RUNTIME_BUNDLES[index].replace(/\.js$/u, ''), path.join(runtime, 'scripts/mathematics', name + '.ts')])), outdir: bundleRoot, bundle: true, platform: 'node', format: 'cjs', @@ -269,7 +269,7 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; const modules = input.webProvider ? webSolverModules(webRequest, { sink: action => webActions.push(action), hidden: [directory], solverRunId: () => state?.runId }) : directSolverModules; - const winner = await runResearchWorkers({ state, root: runtime, buildFile, + const winner = await runResearchLead({ state, root: runtime, buildFile, taskText: 'Prove NativeProof.original by consuming one independently checked child declaration.', executable: input.executable, profile, modules: { ...modules, M1: { ...modules.M1, open: async options => { @@ -282,8 +282,7 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe return session; } } }, signal, deadline: Infinity, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens: 0, - workers: [{ id: 'solver', role: 'lead', worktree, ownedFiles: problem.ownedFiles }], - access: new Map([['solver', { environment, researchSkill: skill, retrievalRoot: path.join(worktree, problem.projectRelative) }]]), + access: { environment, researchSkill: skill, retrievalRoot: path.join(worktree, problem.projectRelative) }, save: () => { for (const current of [state!.writerProcess, ...(state!.agentTeam?.workers.map(worker => worker.writerProcess) ?? [])]) if (current) processes.set(current.pid + ':' + current.startTime, current); diff --git a/scripts/test-codex-backend.ts b/scripts/test-codex-backend.ts index 3285d3e5..1ddc128c 100644 --- a/scripts/test-codex-backend.ts +++ b/scripts/test-codex-backend.ts @@ -401,7 +401,7 @@ try { lead = await open({ executable, profile, workspace: worktree, proofProjectRoot: path.join(worktree, problem.projectRelative), model: state.model, effort: state.effort, environment, skills: [skill], tools: team.tools(), nativeAgentControl: team.nativeAgentControlOptions(), isolateProcess: true, hiddenRoots: team.hiddenRoots, - instructions: agentTeamInstructions({ id: 'lead', role: 'lead' }, maxAgents, 'native-agent-control'), + instructions: agentTeamInstructions({ id: 'lead', role: 'lead' }, maxAgents), signal: controller.signal, onUsage: () => {} }); team.setLeadSession(lead); state.writerProcess = lead.processIdentity; save(); if (largeForkTest) for (const index of [1, 2, 3, 4]) { diff --git a/scripts/test-web-candidate-continuity.ts b/scripts/test-web-candidate-continuity.ts index 183412aa..6a4a4185 100644 --- a/scripts/test-web-candidate-continuity.ts +++ b/scripts/test-web-candidate-continuity.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Disposable HTTP/Chromium state and a controlled runner. No models, Lean or mail. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -84,7 +85,7 @@ try { const projectPath = `/api/research/theorems/${project.id}`; project = (await http<{ item: ResearchProjectDetail }>(reviewer, 'PUT', `${projectPath}/members/${authorSession.researcherId}`, { requestId: crypto.randomUUID(), expectedRevision: project.revision, role: 'collaborator' })).item; project = (await http<{ item: ResearchProjectDetail }>(reviewer, 'POST', `${projectPath}/versions`, { requestId: crypto.randomUUID(), expectedRevision: project.revision, source, statement: 'Prove True', environment: 'standard' })).item; - const { run } = await http<{ run: { id: string } }>(reviewer, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-candidate-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); + const run = await seedCooperativeRun(service, reviewer.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-candidate-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); await reviewer.waitForFunction(async id => (await (await fetch(`/api/runs/${id}`)).json()).run.observation, run.id); project = (await http<{ item: ResearchProjectDetail }>(reviewer, 'POST', `${projectPath}/runs`, { requestId: crypto.randomUUID(), expectedRevision: project.revision, runId: run.id, statementVersionId: project.currentStatementVersionId, grants: { guidance: true, edit: true, approve: true, proof: true } })).item; const href = `${origin}/theorems.html?${new URLSearchParams({ id: project.id, version: project.currentStatementVersionId!, run: run.id, task: 'goal', taskVersion: 'goal-v1' })}`; diff --git a/scripts/test-web-chat-cancel-recovery.ts b/scripts/test-web-chat-cancel-recovery.ts index 5a6d1aec..c61d3554 100644 --- a/scripts/test-web-chat-cancel-recovery.ts +++ b/scripts/test-web-chat-cancel-recovery.ts @@ -17,7 +17,7 @@ await fs.mkdir(output, { recursive: true }); const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-chat-cancel-')); const controls = new Map(); const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable cancellation fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable cancellation fixture' }; }, async run() { throw new Error('Cancellation must not launch proof research'); }, async formalize(input, _send, signal) { controls.set(input.id, signal); diff --git a/scripts/test-web-chat-mathematics.ts b/scripts/test-web-chat-mathematics.ts index bc3bbb6d..1ada5e4d 100644 --- a/scripts/test-web-chat-mathematics.ts +++ b/scripts/test-web-chat-mathematics.ts @@ -27,7 +27,7 @@ const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-chat-mathem const forbiddenCalls: string[] = [], writes: string[] = [], external: string[] = [], errors: string[] = [], reads: string[] = []; const forbidden = (name: string): never => { forbiddenCalls.push(name); throw new Error(`Read-only mathematics cannot invoke runner.${name}`); }; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Local mathematics display fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Local mathematics display fixture' }; }, async run() { return forbidden('run'); }, async formalize() { return forbidden('formalize'); }, async check() { return forbidden('check'); }, async command() { return forbidden('command'); }, async explain() { return forbidden('explain'); }, }; @@ -349,7 +349,7 @@ try { const participation = page.locator('[data-chat-participation]'), input = page.locator('#formalize-original'); await participation.waitFor({ state: 'attached', timeout: 15_000 }); assert.equal(await participation.isVisible(), false); - assert.equal(await participation.locator('input[value="guided"]').isChecked(), true); + assert.equal(await participation.locator('input[value="automatic"]').isChecked(), true); assert.equal(await participation.evaluate(element => element.closest('#formalize-settings') !== null), true); assert.equal(await input.evaluate(element => !!(element.compareDocumentPosition(document.querySelector('[data-chat-participation]')!) & Node.DOCUMENT_POSITION_FOLLOWING)), true); const inputBox = await input.boundingBox(); assert.ok(inputBox && inputBox.y >= 0 && inputBox.y < 1000, 'the task input is immediately visible'); @@ -367,7 +367,7 @@ try { for (const selector of budgetInputs) { assert.equal(await page.locator(selector).inputValue(), ''); assert.equal(await page.locator(selector).getAttribute('placeholder'), '不限'); } await fit(page); await screenshot(page, `${width}-unlimited-settings.png`); await advanced.locator(':scope > summary').click({ timeout: 15_000 }); - mark(`${width}: visible task input, collapsed guided participation and empty unlimited budgets`); + mark(`${width}: visible task input, collapsed participation with automatic mode selected and empty unlimited budgets`); const modelMenu = page.locator('#chat-model-settings > summary'); await modelMenu.click(); for (const selector of ['#formalize-provider', '#formalize-model', '#formalize-effort']) diff --git a/scripts/test-web-chat-recovery.ts b/scripts/test-web-chat-recovery.ts index ce34aa67..dddf5dba 100644 --- a/scripts/test-web-chat-recovery.ts +++ b/scripts/test-web-chat-recovery.ts @@ -21,7 +21,7 @@ const mark = (name: string) => { checks.push(name); console.log(`PASS ${name}`); let proofCalls = 0, runtimeReady = true, browser: Browser | undefined, page: Page | undefined; const credential = 'sk-chat-recovery-disposable-secret'; const runner: WebRunner = { - async readiness() { return { ready: runtimeReady, message: 'Local recovery fixture' }; }, + async readiness() { return { ready: runtimeReady, nativeTeam: runtimeReady, message: 'Local recovery fixture' }; }, async run() { proofCalls++; throw new Error('Recovery checks must not start proof research'); }, async formalize(input, send) { formalizations.push(input.id); @@ -161,6 +161,7 @@ try { page = await defaultsContext.newPage(); await page.goto(origin); await initialized(); await page.locator('#formalize-original').fill(webFormalizationStatement); await clickWorkbenchAction(page, '#open-settings'); + await participation('guided'); await openAdvancedChatSettings(page); await page.locator('#formalize-environment').selectOption('mathlib'); await page.locator('#formalize-key').fill(credential); let defaultRequestId = '', defaultDropped = false; @@ -186,6 +187,7 @@ try { await page.reload(); await initialized(); await page.locator('#topbar-draft').click(); await page.locator('#formalize-original').fill(webFormalizationStatement); await clickWorkbenchAction(page, '#open-settings'); await page.locator('#formalize-key').fill(credential); + await participation('guided'); await page.locator('#formalize-settings > summary').click(); let releaseConversation!: () => void, conversationHeld = false; const gate = new Promise(resolve => { releaseConversation = resolve; }); diff --git a/scripts/test-web-chat-session.ts b/scripts/test-web-chat-session.ts index 61220a56..f55fe370 100644 --- a/scripts/test-web-chat-session.ts +++ b/scripts/test-web-chat-session.ts @@ -68,7 +68,7 @@ const provider = Bun.serve({ hostname: '127.0.0.1', port: 0, idleTimeout: 0, asy type Pending = { input: WorkerFormalizationInput; send(message: WorkerFormalizationMessage): void; resolve(): void }; const formalizations: Pending[] = [], runs: WorkerInput[] = []; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable chat browser fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable chat browser fixture' }; }, formalize(input, send, signal) { return new Promise(resolve => { formalizations.push({ input: structuredClone(input), send, resolve }); signal.addEventListener('abort', () => resolve(), { once: true }); }); diff --git a/scripts/test-web-collaboration-actions.ts b/scripts/test-web-collaboration-actions.ts index 14fc9e88..3ff2abfe 100644 --- a/scripts/test-web-collaboration-actions.ts +++ b/scripts/test-web-collaboration-actions.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Chromium + disposable HTTP state; controlled checks fail without running Lean or models. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -92,7 +93,7 @@ try { for (const person of sessions.slice(1)) project = (await http<{ item: ResearchProjectDetail }>(owner, 'PUT', `${projectPath}/members/${person.researcherId}`, { requestId: crypto.randomUUID(), role: 'collaborator', expectedRevision: project.revision })).item; project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/versions', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statement: 'Prove True', source, environment: 'standard' })).item; const version = project.currentStatementVersionId!; - const createdRun = (await http<{ run: { id: string } }>(owner, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-actions', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Collaboration actions', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' })).run; + const createdRun = await seedCooperativeRun(service, owner.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-actions', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Collaboration actions', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); for (let attempt = 0; attempt < 100 && !controls.has(createdRun.id); attempt++) await new Promise(resolve => setTimeout(resolve, 20)); const control = controls.get(createdRun.id)!; assert.ok(control); project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/runs', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: version, runId: createdRun.id, exposure: 'members', grants: { guidance: true, edit: true, approve: true, proof: true } })).item; diff --git a/scripts/test-web-collaboration-continuity.ts b/scripts/test-web-collaboration-continuity.ts index 771db915..463dfaa7 100644 --- a/scripts/test-web-collaboration-continuity.ts +++ b/scripts/test-web-collaboration-continuity.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Chromium + disposable HTTP state; controlled checks fail without running Lean or models. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -82,7 +83,7 @@ try { const projectPath = '/api/research/theorems/' + project.id; project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/versions', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statement: 'Prove True', source, environment: 'standard' })).item; const version = project.currentStatementVersionId!; - const createdRun = (await http<{ run: { id: string } }>(owner, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-collaboration', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Collaboration continuity', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' })).run; + const createdRun = await seedCooperativeRun(service, owner.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-collaboration', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Collaboration continuity', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); for (let attempt = 0; attempt < 100 && !controls.has(createdRun.id); attempt++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(controls.has(createdRun.id)); project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/runs', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: version, runId: createdRun.id, exposure: 'members', grants: { guidance: true, edit: true, approve: true, proof: true } })).item; diff --git a/scripts/test-web-cooperative-runtime.ts b/scripts/test-web-cooperative-runtime.ts deleted file mode 100644 index 8a837522..00000000 --- a/scripts/test-web-cooperative-runtime.ts +++ /dev/null @@ -1,219 +0,0 @@ -import assert from 'node:assert/strict'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { execFile } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; -import { parseArgs, promisify } from 'node:util'; -import { WebJobs } from '../apps/web/jobs'; -import { DockerWebRunner } from '../apps/web/runner'; -import { WebStorage } from '../apps/web/storage'; -import type { WebGuidanceInput, WebObservation, WebPlanProposal } from '../apps/web/collaboration'; -import type { WebRun, WebRunInput, WorkerMessage } from '../apps/web/shared'; -import { assertWebContainerBoundary, assertWebEnvironmentReport, standardRuntimeTemplate } from './test-web-runtime'; - -const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const execute = promisify(execFile); -const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); -const editId = 'web-cooperative-edit', guidanceId = 'web-cooperative-direction'; -const proveMarker = 'WEB_COOPERATIVE_PROVE_FIRST', secondProofMarker = 'WEB_COOPERATIVE_PROVE_SECOND'; -const terminal = (run: WebRun) => ['completed', 'error', 'cancelled'].includes(run.status); -const docker = (args: string[], timeout = 30_000) => execute('docker', args, - { cwd: root, timeout, maxBuffer: 16 * 1024 * 1024 }); - -/** Real isolated host, real command pipe, real Lean; only Codex work products are deterministic. */ -export async function runWebCooperativeSmoke(argv = process.argv.slice(2)) { - const { values } = parseArgs({ args: argv, options: { - 'base-image': { type: 'string', default: 'theorem-os-worker:local' }, - image: { type: 'string', default: `theorem-os-worker:web-cooperative-smoke-${process.pid}` }, - 'skip-build': { type: 'boolean', default: false }, 'keep-image': { type: 'boolean', default: false }, - help: { type: 'boolean', default: false }, - } }); - if (values.help) { - console.log('bun scripts/test-web-cooperative-runtime.ts [--base-image TAG] [--image TAG] [--skip-build] [--keep-image]'); - console.log('Three real host roles, offline Codex, human guidance/edit commands, independent Lean and final S3 acceptance.'); - return; - } - const image = values.image!; - assert.notEqual(image, values['base-image']); - const outputRoot = path.join(root, 'out/web-cooperative-smoke'); - fs.mkdirSync(outputRoot, { recursive: true }); - const storageRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-cooperative-smoke-')); - const storage = new WebStorage(storageRoot), runner = new DockerWebRunner({ workerImage: image }); - const owner = `offline-cooperative-${crypto.randomUUID()}`; - const key = `sk-theoremos-smoke-${crypto.randomBytes(24).toString('hex')}`; - const observations = new Map(), trace: { type: string; at: string; detail?: string }[] = []; - let built = false, run: WebRun | undefined; - const jobs = new WebJobs({ readiness: () => runner.readiness(), command: (id, command) => runner.command(id, command), - run: (input, onMessage, signal) => runner.run(input, message => { - onMessage(message); observe(message); - }, signal) }, { concurrency: 1, queueLimit: 1 }, { storage }); - function observe(message: WorkerMessage) { - if (message.type === 'observation') observations.set(message.observation.sequence, message.observation); - trace.push({ type: message.type, at: new Date().toISOString(), - ...(message.type === 'progress' ? { detail: message.event } : {}) }); - } - const write = (name: string, value: unknown) => { - const text = JSON.stringify(value, null, 2) + '\n'; - assert.ok(!text.includes(key), 'Smoke artifacts must not contain the disposable API key.'); - fs.writeFileSync(path.join(outputRoot, name), text); - }; - const wait = async (label: string, predicate: () => boolean, timeout = 120_000) => { - console.log(`Cooperative smoke: ${label}`); - const deadline = Date.now() + timeout; - let lastLog = Date.now(); - while (!predicate()) { - if (run && terminal(run)) throw new Error(`Ended before ${label}: ${run.error || run.result?.status || run.status}`); - if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${label}; phase ${run?.phase}`); - if (Date.now() - lastLog > 20_000) { - console.log(`Cooperative smoke: waiting for ${label} (${run?.phase})`); lastLog = Date.now(); - } - await pause(200); - } - }; - const capture = async () => { - const result = await runner.command(run!.id, { type: 'capture' }); - assert.equal(result.status, 'captured'); assert.ok(result.observation); - observations.set(result.observation.sequence, result.observation); - return result.observation; - }; - const guidance = (observation: WebObservation, input: Omit) => - ({ ...input, observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } }); - try { - if (!values['skip-build']) { - console.log('Cooperative smoke: building the offline fixture derivative'); - await docker(['build', '--pull=false', '--build-arg', `BASE_IMAGE=${values['base-image']}`, - '--file', 'tests/fixtures/web-runtime.Dockerfile', '--tag', image, '.'], 120_000); - built = true; - } - const metadata = JSON.parse((await docker(['image', 'inspect', image])).stdout)[0]; - assert.equal(metadata.Config.Labels['org.theoremos.fixture'], 'web-runtime-no-provider'); - const imageId = metadata.Id; - const template = standardRuntimeTemplate; - const input: WebRunInput = { providerId: 'offline-fixture', apiKey: key, model: 'offline-fixture', effort: 'xhigh', - environment: 'standard', source: template.source, task: `WEB_COOPERATIVE_SMOKE\n${template.task}`, - workers: 3, coordination: 'cooperative', maxTurns: 12, maxRunSeconds: 300 }; - run = jobs.create(owner, input, { id: 'offline-fixture', name: 'Offline fixture', baseUrl: 'https://no-provider.invalid/v1' }); - await wait('Lead publishes the initial plan and Engineer starts goal_1', () => Boolean(run?.observation?.plan?.tasks.length === 2 && - run.observation.inspection.workers.some(worker => worker.id === 'solver' && worker.scheduling?.status === 'working') && - run.observation.inspection.workers.some(worker => worker.id === 'engineer' && worker.task === 'goal_1' && - worker.scheduling?.status === 'working'))); - assertWebContainerBoundary((await docker(['container', 'inspect', `theoremos-web-${run.id}`])).stdout, key); - const before = await capture(), first = before.inspection.tasks.find(task => task.id === 'goal_1')!; - assert.equal(first.proof.status, 'none'); - assert.equal(before.plan!.tasks.find(task => task.id === 'goal_2')!.status, 'paused'); - const direction = guidance(before, { id: guidanceId, recipient: { kind: 'task', id: first.id }, - taskRef: { id: first.id, version: first.version }, text: `${proveMarker}: use definitional equality and leave the other original target unchanged.` }); - const queuedGuidance = await jobs.command(owner, run.id, { type: 'guidance', guidance: direction }); - assert.ok(['queued', 'deferred', 'delivered'].includes(queuedGuidance.status)); - await wait('host delivers guidance and independently integrates the first proof', () => Boolean( - run?.observation?.guidance.find(item => item.id === guidanceId)?.status === 'delivered' && - run.observation.inspection.tasks.find(task => task.id === 'goal_1')?.proof.status === 'checked')); - const checked = await capture(); - const delivered = checked.guidance.find(item => item.id === guidanceId)!; - assert.deepEqual(delivered.deliveredTo, ['engineer']); - assert.equal(delivered.taskRef!.version, first.version); - assert.ok(checked.inspection.tasks.find(task => task.id === 'goal_1')!.proof.receiptIds!.length); - assert.equal(run.result, undefined, 'A single checked target cannot finish the original problem.'); - assert.ok(checked.sources.some(item => item.taskId === 'goal_1' && item.source.includes('by rfl') && item.source.includes('by sorry'))); - const proposal: WebPlanProposal = { ...checked.plan!, id: editId, - tasks: checked.plan!.tasks.map(task => task.id === 'goal_1' ? { ...task, revision: task.revision + 1 } : - { ...task, revision: task.revision + 1, status: 'active', dependsOn: ['goal_1'] }) }; - const preview = await jobs.command(owner, run.id, { type: 'edit-preview', proposal }); - assert.equal(preview.status, 'validated'); - assert.deepEqual(new Set(preview.affectedTaskIds), new Set(['goal_1', 'goal_2'])); - const afterPreview = await capture(); - assert.equal(afterPreview.plan!.baseVersion, checked.plan!.baseVersion); - assert.equal(afterPreview.inspection.tasks.find(task => task.id === 'goal_1')!.version, first.version); - assert.ok(!afterPreview.inspection.edits.some(edit => edit.id === editId)); - const queuedEdit = await jobs.command(owner, run.id, { type: 'edit', proposal }); - assert.ok(['queued', 'received', 'applied'].includes(queuedEdit.status)); - assert.equal(queuedEdit.commandDigest, preview.commandDigest); - await wait('host applies the revised plan and starts the second proof', () => Boolean( - run?.observation?.inspection.edits.find(edit => edit.id === editId)?.status === 'applied' && - run.observation.inspection.workers.some(worker => worker.id === 'engineer' && worker.task === 'goal_2' && - worker.scheduling?.status === 'working'))); - const revised = await capture(), second = revised.inspection.tasks.find(task => task.id === 'goal_2')!; - assert.notEqual(revised.inspection.tasks.find(task => task.id === 'goal_1')!.version, first.version); - const duplicate = await jobs.command(owner, run.id, { type: 'edit', proposal }); - assert.equal(duplicate.status, 'applied'); - const auditScript = `const fs=require('node:fs'),path=require('node:path'),cp=require('node:child_process'); - const active=JSON.parse(fs.readFileSync('/work/active-run.json','utf8')); - const state=JSON.parse(fs.readFileSync(active.output+'.runtime/state.json','utf8')); - const guidance=JSON.parse(fs.readFileSync(active.output+'.runtime/human-guidance.json','utf8')); - const proofNotes=(state.cooperation.proofReadyRecords||[]).filter(item=>item.snapshotCommit).map(item=>{ - const worker=state.workers.find(worker=>worker.id===item.workerId); - return {receipt:item,notes:JSON.parse(cp.execFileSync('git',['-C',worker.worktree,'show',item.snapshotCommit+':RESEARCH.md'],{encoding:'utf8'}))}; - });process.stdout.write(JSON.stringify({state,guidance,proofNotes}));`; - const audit = JSON.parse((await docker(['exec', `theoremos-web-${run.id}`, 'bun', '-e', auditScript])).stdout); - assert.ok(audit.state.cooperation.initialPlanPublication?.eventDigest); - assert.equal(audit.state.cooperation.edits.filter((item: { id: string }) => item.id === editId).length, 1); - assert.ok(audit.proofNotes.some((item: { notes: { fixture?: { guidanceReceived?: string } } }) => - item.notes.fixture?.guidanceReceived?.includes(proveMarker)), 'A frozen worker note must retain the guidance actually received through turn/steer.'); - write('host-audit.json', audit); - const release = guidance(revised, { id: 'web-cooperative-second-proof', recipient: { kind: 'task', id: second.id }, - taskRef: { id: second.id, version: second.version }, text: `${secondProofMarker}: prove the second goal using Nat.zero_add.` }); - assert.ok(['queued', 'deferred', 'delivered'].includes((await jobs.command(owner, run.id, { type: 'guidance', guidance: release })).status)); - await wait('final Lean/S3 accepts both original targets', () => terminal(run!), 180_000); - assert.equal(run.status, 'completed', run.error); - assert.equal(run.result!.status, 'evaluated_passed', JSON.stringify(run.result!.report)); - assertWebEnvironmentReport(run.result!.report, 'standard'); - assert.equal(run.result!.report.solver_ready_receipt_valid, true); - assert.equal(run.result!.report.completion_signal_valid, true); - const evaluator = run.result!.report.evaluator as { status: string; verification: { passed: boolean } }; - assert.equal(evaluator.status, 'passed'); assert.equal(evaluator.verification.passed, true); - // Canonical integration can remove empty lines between unchanged declaration headers. - assert.equal(run.result!.proof.replace(/\n\n+/gu, '\n'), - input.source.replace('by sorry', 'by rfl').replace('by sorry', 'by exact Nat.zero_add n').replace(/\n\n+/gu, '\n')); - const finished = run.observation!.inspection, edit = finished.edits.find(item => item.id === editId)!; - assert.equal(edit.status, 'applied'); assert.notEqual(edit.planVersion, proposal.baseVersion); - assert.equal(edit.recheck!.status, 'passed'); - assert.equal(edit.recheck!.tasks.length, 2); - for (const item of edit.recheck!.tasks) { - assert.equal(item.status, 'passed'); assert.equal(item.lastCheck!.passed, true); - assert.ok(item.lastCheck!.receiptIds.length); - assert.equal(item.taskDigest, finished.tasks.find(task => task.id === item.taskId)!.version); - } - assert.equal(finished.review, undefined); - assert.equal(run.observation!.acceptance, 'not-assessed'); - assert.equal(run.observation!.inspection.configuration.methodDigest, run.moduleConfiguration!.methodDigest); - assert.equal(run.observation!.guidance.find(item => item.id === release.id)!.status, 'delivered'); - const archive = await jobs.archive(owner, run.id), archived = storage.getArchive(owner, run.id, archive.id)!; - assert.ok(archived.observations.length && archived.sources.length && archived.checks.length); - for (const id of ['goal_1', 'goal_2']) assert.ok(archived.checks.some(check => check.taskId === id && check.record.passed === true)); - console.log('Cooperative smoke: confirming worker container removal'); - let removed = false; - for (let attempt = 0; attempt < 100; attempt++) { - try { await docker(['container', 'inspect', `theoremos-web-${run.id}`]); } - catch (error) { assert.match(String((error as { stderr?: string }).stderr), /No such (?:object|container)/iu); removed = true; break; } - await pause(100); - } - assert.equal(removed, true, 'Docker must confirm removal of this smoke container.'); - fs.rmSync(path.join(outputRoot, 'failure.json'), { force: true }); - write('archive.json', archived); write('commands.json', storage.listCommands(owner, run.id)); - write('report.json', { schema: 'theorem-os.web-cooperative-smoke.v1', checkedAt: new Date().toISOString(), passed: true, - image, imageId, baseImage: values['base-image'], webRunId: run.id, solverRunId: run.observation!.solverRunId, - modelInvoked: false, realHost: true, commandPipe: 'WebJobs → DockerWebRunner → worker-command → existing cooperative host', - workers: run.observation!.inspection.workers.map(worker => ({ id: worker.id, role: worker.role, turns: worker.turns })), - initialPlanPublished: true, guidanceDeliveredToExactTask: delivered, actualGuidanceRetainedInFrozenWorkerNotes: true, - previewReadOnly: true, previousCheckedTaskVersion: first.version, edit: edit, duplicateEditAppliedOnce: true, - result: run.result, archive: archive, containerRemoved: removed, - artifacts: ['observations.json', 'host-audit.json', 'archive.json', 'commands.json', 'trace.json'] }); - console.log('Cooperative Docker / command / host / Lean checks passed. Report: out/web-cooperative-smoke/report.json'); - } catch (error) { - write('failure.json', { checkedAt: new Date().toISOString(), error: error instanceof Error ? error.message : String(error), - ...(run ? { run } : {}) }); - throw error; - } finally { - write('observations.json', [...observations.values()].sort((a, b) => a.sequence - b.sequence)); write('trace.json', trace); - await jobs.close(); - if (run) await docker(['rm', '--force', '--volumes', `theoremos-web-${run.id}`]).catch(() => {}); - if (built && !values['keep-image']) await docker(['image', 'rm', image]).catch(() => {}); - fs.rmSync(storageRoot, { recursive: true, force: true }); - } -} - -if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - runWebCooperativeSmoke().catch(error => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }); -} diff --git a/scripts/test-web-first-research-sharing.ts b/scripts/test-web-first-research-sharing.ts index e8543cbb..4194ad8d 100644 --- a/scripts/test-web-first-research-sharing.ts +++ b/scripts/test-web-first-research-sharing.ts @@ -15,7 +15,8 @@ import type { WebRunner } from '../apps/web/runner'; import type { WebExplanation, WebSession } from '../apps/web/shared'; import { readingCommit, readingEvidence, readingRun } from '../tests/helpers/shareReadingFixture'; import { audit } from './web-a11y'; -import { freePort, postRun, startBrowser, waitForRun } from './web-scenario'; +import { freePort, startBrowser, waitForRun } from './web-scenario'; +import { seedCooperativeRun } from './web-cooperative-fixture'; import { openChatBudget, openChatModelSettings, openChatParticipation } from './web-ui-controls'; const root = path.resolve(import.meta.dirname, '..'); @@ -28,7 +29,7 @@ const credential = 'sk-disposable-first-reading'; const checks: object[] = [], failures: object[] = [], errors: string[] = [], external: string[] = []; const runtimeCalls = { run: 0, formalize: 0, check: 0, explain: 0 }; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable reader fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable reader fixture' }; }, async run(input, send) { runtimeCalls.run++; assert.equal(input.input.task, readingRun().task); @@ -166,9 +167,9 @@ try { await scenario('share-service-projection', 'zh', 1440, async (page, context) => { await page.goto(origin); await page.locator('#formalize-original').waitFor(); const fixture = readingRun(); - const created = await postRun({ page }, { providerId: 'fixture-a', apiKey: credential, model: 'fixture-model', + const created = await seedCooperativeRun(service, context, origin, { providerId: 'fixture-a', apiKey: credential, model: 'fixture-model', effort: 'max', environment: 'standard', source: fixture.source, task: fixture.task, - maxTurns: 3, maxRunSeconds: 120, workers: 1, coordination: 'independent' }); + maxTurns: 3, maxRunSeconds: 120, workers: 2, coordination: 'cooperative' }); const accepted = await waitForRun({ page }, created.id, run => run.status === 'completed'); const owner = (await context.cookies(origin)).find(cookie => cookie.name === 'theoremos_session')!.value; const now = new Date().toISOString(); diff --git a/scripts/test-web-formalize.ts b/scripts/test-web-formalize.ts index 7d8b0f44..b8704c6a 100644 --- a/scripts/test-web-formalize.ts +++ b/scripts/test-web-formalize.ts @@ -20,7 +20,7 @@ const output = path.join(root, 'out/web-formalize'); await fs.mkdir(output, { re const port = await freePort(), origin = `http://127.0.0.1:${port}`; const service = createWebService(readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin, THEOREMOS_WEB_STATIC_ROOT: path.join(root, 'out/web') }), { - async readiness() { return { ready: true, message: 'Fixture only' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Fixture only' }; }, async run() { throw new Error('This UI test must never call a model'); }, }); const original = ' For every natural number n, prove $n + 0 = n$.\n\nKeep this exact text. '; diff --git a/scripts/test-web-inline-annotations.ts b/scripts/test-web-inline-annotations.ts index 0c729ab2..70a45ad0 100644 --- a/scripts/test-web-inline-annotations.ts +++ b/scripts/test-web-inline-annotations.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Disposable HTTP/Chromium state with a controlled runner; no real models, Lean or mail. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -85,7 +86,7 @@ try { await Promise.all([owner, peer].map(page => page.goto(origin + '/theorems.html'))); const peerSession = await http<{ researcherId: string }>(peer, 'GET', '/api/research/session'); for (const [page, name] of [[owner, 'Owner'], [peer, 'Peer']] as const) await http(page, 'PUT', '/api/research/profile', { requestId: crypto.randomUUID(), expectedRevision: 0, displayName: name, visibility: 'public' }); - const { run } = await http<{ run: { id: string } }>(owner, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-inline-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); + const run = await seedCooperativeRun(service, owner.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-inline-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); await owner.waitForFunction(async id => (await (await fetch(`/api/runs/${id}`)).json()).run.observation, run.id); const routeUrl = `${origin}/problem.html?${new URLSearchParams({ run: run.id, tab: 'route', task: 'goal', taskVersion: 'goal-v1' })}`; await owner.goto(routeUrl); const inline = owner.locator('[data-research-inline-actions]'); await inline.locator('[data-inline-open]').click(); await inline.locator('[data-inline-approve-plan]').waitFor(); diff --git a/scripts/test-web-key-memory.ts b/scripts/test-web-key-memory.ts index 5a3c8d9a..121ee321 100644 --- a/scripts/test-web-key-memory.ts +++ b/scripts/test-web-key-memory.ts @@ -24,7 +24,7 @@ await fs.rm(output, { recursive: true, force: true }); await fs.mkdir(output, { recursive: true }); const credential = 'sk-local-key-memory-fixture-0123456789'; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Local key memory fixture; no model or Lean' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Local key memory fixture; no model or Lean' }; }, async run(input, send) { send({ type: 'result', result: { status: 'incomplete', proof: '', report: input.input.task.includes('reject') ? { failure: { kind: 'authentication', reason: 'math_model_authentication_failed' } } : { fixture: true } } }); diff --git a/scripts/test-web-library-personal-continuity.ts b/scripts/test-web-library-personal-continuity.ts index a03f3f04..94dbc409 100644 --- a/scripts/test-web-library-personal-continuity.ts +++ b/scripts/test-web-library-personal-continuity.ts @@ -24,7 +24,7 @@ const original = 'theorem preserved : 1 = 1 := by rfl\nnamespace Research\ntheor const commit = 'a'.repeat(40), environmentDigest = getLeanTaskEnvironment('standard').dependencyDigest; let workers = 0, compilerCalls = 0, prohibited = 0, pass = true; const inputs: Parameters[0][] = []; -const runner: WebRunner = { async readiness() { return { ready: true, message: 'Disposable continuity fixture' }; }, +const runner: WebRunner = { async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable continuity fixture' }; }, async run(input, send) { workers++; inputs.push(structuredClone(input)); const observation = structuredClone(loadWebSample()!.observations.at(-1)!); observation.webRunId = input.id; observation.sequence = 1; @@ -119,11 +119,13 @@ try { await page.waitForFunction(expected => (document.querySelector('#source') as HTMLTextAreaElement)?.value === expected, passed.source); assert.equal(workers, workerStart); assert.equal(compilerCalls, compiledBeforeReading); assert.equal(await page.locator('#api-key').inputValue(), ''); await page.reload(); await page.waitForFunction(expected => (document.querySelector('#source') as HTMLTextAreaElement)?.value === expected, passed.source); + await page.waitForFunction(() => document.querySelector('#environment')?.value === 'standard'); assert.equal(workers, workerStart); await page.screenshot({ path: path.join(output, `prepared-personal-${language}.png`), fullPage: true }); await page.evaluate(() => { const key = document.querySelector('#api-key')!; key.value = 'sk-disposable-personal-attempt'; key.dispatchEvent(new Event('input', { bubbles: true })); }); const launch = page.waitForResponse(response => response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/runs'); await page.locator('#run-form').evaluate(form => (form as HTMLFormElement).requestSubmit()); const launched = await launch; assert.ok(launched.ok(), await launched.text()); + assert.equal(launched.request().postDataJSON().environment, 'standard'); assert.deepEqual(launched.request().postDataJSON().researchSelection.libraries, [release && { assetId: release.assetId, version: release.version, digest: release.digest }]); for (let attempt = 0; attempt < 40 && workers === workerStart; attempt++) await new Promise(resolve => setTimeout(resolve, 25)); assert.equal(workers, workerStart + 1); assert.equal(inputs.at(-1)!.input.source, passed.source.trim()); diff --git a/scripts/test-web-message-stage-continuity.ts b/scripts/test-web-message-stage-continuity.ts index 7ffb4c8d..c6a30e8d 100644 --- a/scripts/test-web-message-stage-continuity.ts +++ b/scripts/test-web-message-stage-continuity.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Disposable HTTP sessions and a controlled recorded runner; no model, Lean, mail or production access. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -10,7 +11,6 @@ import { readWebConfig } from '../apps/web/config'; import { loadWebSample } from '../apps/web/sample'; import { mathDigest } from '../src/math/mathRuntimeIo'; import type { WebRunner } from '../apps/web/runner'; -import type { WebRun } from '../apps/web/shared'; import type { ResearchAnnotation, ResearchAnnotationPage, ResearchProjectDetail } from '../apps/web/researchProjectTypes'; import type { ResearchCollaborationInbox, ResearchIssue } from '../apps/web/researchCollaborationTypes'; import type { ResearchProblem, ResearchStageConclusion } from '../apps/web/researchProblemTypes'; @@ -63,7 +63,7 @@ try { await Promise.all([owner, peer].map(page => page.goto(origin + '/theorems.html'))); for (const [page, name] of [[owner, 'Stage author'], [peer, 'Stage peer']] as const) await http(page, 'PUT', '/api/research/profile', { requestId: crypto.randomUUID(), expectedRevision: 0, displayName: name, visibility: 'public' }); const peerSession = await http<{ researcherId: string }>(peer, 'GET', '/api/research/session'); - const { run } = await http<{ run: WebRun }>(owner, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-message-fixture', model: 'fixture', effort: 'low', environment: sample.run.environment, + const run = await seedCooperativeRun(service, owner.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-message-fixture', model: 'fixture', effort: 'low', environment: sample.run.environment, source: sample.run.source.trim(), task: 'Message and stage workflow', maxTurns: 2, maxRunSeconds: 60, workers: 2, coordination: 'cooperative' }); await owner.waitForFunction(async id => (await (await fetch(`/api/runs/${id}`)).json()).run.status === 'completed', run.id); const problemPath = `/api/research/workspace/problem/${run.id}`, initial = (await http<{ item: ResearchProblem }>(owner, 'GET', problemPath)).item; diff --git a/scripts/test-web-native-team.ts b/scripts/test-web-native-team.ts index 5dec2951..350e1558 100644 --- a/scripts/test-web-native-team.ts +++ b/scripts/test-web-native-team.ts @@ -7,10 +7,15 @@ import { once } from 'node:events'; import { createWebService } from '../apps/web/server'; import { readWebConfig } from '../apps/web/config'; import { webResearchArguments } from '../apps/web/researchMode'; +import { retiredResearchCoordinationCode } from '../apps/web/shared'; import type { WebRunner } from '../apps/web/runner'; -import type { WorkerInput } from '../apps/web/shared'; -import { freePort, ready, startBrowser } from './web-scenario'; -import { enterLean, fillConfig, showChat, withSettings } from './web-ui-controls'; +import type { WebRunInput, WorkerInput } from '../apps/web/shared'; +import { encodeTaskDraft, taskDraftStorageKey } from '../apps/web/client/draft'; +import { researchEnvironmentStorageKey, researchSelectionStorageKey, submissionStorageKey } from '../apps/web/client/ownedDrafts'; +import { SubmissionIdentity } from '../apps/web/client/submissionIdentity'; +import { buildTheoremKnowledge } from '../src/solver/theoremKnowledge'; +import { freePort, postRun, ready, startBrowser, waitForRun } from './web-scenario'; +import { closeSettings, enterLean, fillConfig, selectHistoryRun, showArtifacts, showChat, withSettings } from './web-ui-controls'; const port = await freePort(), origin = 'http://127.0.0.1:' + port; const output = process.env.THEOREMOS_TEST_OUTPUT ?? 'out/web-native-team'; @@ -24,6 +29,10 @@ const runner: WebRunner = { async readiness() { return { ready: true, nativeTeam, nativeTeamPreferences, nativeTeamExpertCards, message: 'Offline fixture' }; }, async run(request, send) { started.push(request); + if (request.input.task === 'Rate limit fixture') { + send({ type: 'error', message: 'Offline rate limit fixture', failure: { kind: 'rate_limit' } }); + return; + } send({ type: 'result', result: { status: 'incomplete', proof: '', report: { reason: 'offline_fixture' } } }); }, }; @@ -51,7 +60,11 @@ if (process.argv.includes('--serve')) { await page.locator('#task').fill('Prove original.'); await withSettings(page, async () => { await page.locator('#provider').selectOption('offline'); - await page.locator('#research-mode').selectOption('native-team'); + assert.equal(await page.locator('#current-research-mode').innerText(), 'Codex 原生团队'); + assert.equal(await page.locator('#research-mode').isVisible(), false); + assert.equal(await page.locator('#module-plan').isVisible(), false); + assert.equal(await page.locator('#plan-approval').isVisible(), true); + assert.equal(await page.locator('#plan-approval').isChecked(), false); const capacity = page.locator('#native-team-capacity'); assert.equal(await capacity.inputValue(), '3'); assert.deepEqual(await capacity.locator('option').allTextContents(), ['2', '3', '4', '5', '6', '7', '8']); @@ -93,9 +106,6 @@ if (process.argv.includes('--serve')) { await picker.locator('input[value=D013]').waitFor(); assert.equal(await picker.locator('input[value=engineer]').isChecked(), true); assert.equal(await picker.locator('input[value=D011]').isChecked(), true); - await page.locator('#research-mode').selectOption('skill'); - await page.waitForFunction(() => !JSON.parse(sessionStorage.getItem('theorem-os.web-draft.v1') ?? '{}').draft?.nativeTeamPreferredProfiles); - await page.locator('#research-mode').selectOption('native-team'); await page.locator('#model').fill('fixture'); await page.locator('#api-key').fill('offline-fixture-key'); }); await showChat(page); @@ -112,6 +122,7 @@ if (process.argv.includes('--serve')) { assert.equal(request.researchConfiguration?.personalExperts?.[0]?.name, saved.name); assert.match(request.researchConfiguration!.personalExperts![0]!.knowledge, /uniformizer/); assert.equal(request.input.coordination, 'independent'); assert.equal(request.input.workers, 1); + assert.equal(request.input.planApproval, undefined); assert.equal(request.input.modulePlan, undefined); assert.deepEqual(args, ['--research-mode', 'skill', '--skill-loading', 'native', '--skill-delegation', 'team', '--skill-max-agents', '8', '--skill-preferred-profiles', 'D011,engineer']); const { requestId: _replay, ...newSubmission } = response.request().postDataJSON(); @@ -134,5 +145,132 @@ if (process.argv.includes('--serve')) { await fs.writeFile(path.join(output, 'report.json'), JSON.stringify({ status: 'passed', capacity: run.nativeTeamCapacity, hostWorkers: run.workers, frozenCoordination: run.coordination, args, personalExpert: saved.name, personalExpertVersion: 'v1', oldExpertImageStatus: 503, overCapacityStatus: overCapacity, oldImageStatus: refused, modelRequests: 0 }, null, 2)); + + nativeTeam = true; + const input = { providerId: 'offline', model: 'fixture', apiKey: 'offline-fixture-key', environment: 'mathlib', effort: 'low', + source: 'theorem retained : True := by\n sorry', task: 'Keep this Lean draft', maxTurns: 6, maxRunSeconds: 120, + workers: 2, coordination: 'cooperative', autoExplain: true, explanationLanguage: 'zh' } satisfies WebRunInput; + async function submit() { + const pending = page.waitForResponse(r => new URL(r.url()).pathname === '/api/runs' && r.request().method() === 'POST'); + await page.locator('#submit-run').click(); + return pending; + } + async function restoreUncertainLegacySubmission() { + await page.goto(origin); await ready(page); + const storage = new Map(); + const identity = new SubmissionIdentity({ + getItem: key => storage.get(key) ?? null, + setItem: (key, value) => { storage.set(key, value); }, + removeItem: key => { storage.delete(key); }, + }); + const requestId = await identity.prepare(input); + const draft = encodeTaskDraft({ ...input, templateId: '', maxTurns: '6', maxRunSeconds: '120', workers: '2' }); + await page.evaluate(({ draft, identity, draftKey, identityKey, selectionKeys }) => { + for (const key of selectionKeys) sessionStorage.removeItem(key); + sessionStorage.setItem(draftKey, draft); sessionStorage.setItem(identityKey, identity); + }, { draft, identity: storage.get(submissionStorageKey)!, draftKey: taskDraftStorageKey, identityKey: submissionStorageKey, + selectionKeys: [researchSelectionStorageKey, researchEnvironmentStorageKey] }); + await page.reload(); await ready(page); await enterLean(page); + await fillConfig(page, 'api-key', input.apiKey); + return requestId; + } + + // A prior version submitted the draft but the reply was lost. An existing run keeps its original identity. + const previousId = await restoreUncertainLegacySubmission(); + const frozen = service.jobs.create(owner, { ...input, maxTotalTokens: 0 }, config.providers[0]!, undefined, previousId); + const replay = await submit(); + const { requestId: replayedId, apiKey: _fixtureKey, ...replayed } = replay.request().postDataJSON(); + const { apiKey: _key, ...expectedReplay } = input; + assert.deepEqual(replayed, expectedReplay); + assert.equal(replayedId, previousId); + assert.equal(replay.status(), 200, await replay.text()); + assert.equal((await replay.json()).run.id, frozen.id); + await page.locator(`.detail-heading[data-run="${frozen.id}"]`).waitFor({ state: 'attached' }); + + // With no existing run, only the explicit retirement response permits a new request ID. + const missingId = await restoreUncertainLegacySubmission(); + const rejected = await submit(); + assert.equal(rejected.status(), 400, await rejected.text()); + assert.equal(rejected.request().postDataJSON().requestId, missingId); + assert.equal((await rejected.json()).code, retiredResearchCoordinationCode); + await page.locator('#form-error:visible').getByText(/草稿已切换到当前研究方式/u).waitFor(); + assert.equal(await page.locator('#task').inputValue(), input.task); + assert.equal(await page.locator('#source').inputValue(), input.source); + await page.reload(); await ready(page); await enterLean(page); + await fillConfig(page, 'api-key', input.apiKey); + const retried = await submit(); + assert.equal(retried.status(), 201, await retried.text()); + const retriedRequest = retried.request().postDataJSON(); + assert.notEqual(retriedRequest.requestId, missingId); + assert.equal(retriedRequest.nativeTeamCapacity, 3); + assert.equal(retriedRequest.workers, 1); + assert.equal(retriedRequest.source, input.source); + assert.equal(retriedRequest.task, input.task); + + // Reusing a run creates a new Lean draft while retaining both explicit knowledge choices across reload. + const catalog = service.knowledge.importCatalog(owner, buildTheoremKnowledge([])); + for (const knowledgeDigest of [catalog.digest, null]) { + const historical = await postRun({ page }, { ...input, workers: 1, coordination: 'independent', knowledgeDigest }); + await waitForRun({ page }, historical.id, run => run.status === 'completed'); + await page.goto(`${origin}/?run=${historical.id}`); await ready(page); + await selectHistoryRun(page, historical.id); await showArtifacts(page); + await page.locator('[data-action="reuse-run"]').click(); + await page.locator('#run-settings[open]').waitFor(); + await closeSettings(page); + await page.reload(); await ready(page); await enterLean(page); + await fillConfig(page, 'api-key', input.apiKey); + const response = await submit(); + assert.equal(response.status(), 201, await response.text()); + assert.equal(response.request().postDataJSON().knowledgeDigest, knowledgeDigest); + assert.equal((await response.json()).run.knowledgeDigest, knowledgeDigest); + await page.locator('body[data-view="run"]').waitFor({ state: 'attached' }); + } + // Choose a knowledge directory in the native team settings, including both special values. + const knowledge = page.locator('#knowledge-catalog'); + for (const [option, digest] of [[catalog.digest, catalog.digest], ['', undefined], ['__none__', null]] as const) { + await showChat(page); + await fillConfig(page, 'source', input.source); + await page.locator('#task').fill(input.task); + await withSettings(page, async () => { + await page.locator('#provider').selectOption(input.providerId); + await page.locator('#model').fill(input.model); + await page.locator('#api-key').fill(input.apiKey); + await knowledge.selectOption(option); + }); + const response = await submit(); + assert.equal(response.status(), 201, await response.text()); + assert.equal(response.request().postDataJSON().knowledgeDigest, digest); + await page.locator('body[data-view="run"]').waitFor({ state: 'attached' }); + } + + for (const capacity of [3, 2]) { + const limited = await postRun({ page }, { ...input, task: 'Rate limit fixture', workers: 1, coordination: 'independent', + researchMode: 'skill', skillLoading: 'native', nativeTeamCapacity: capacity }); + const failed = await waitForRun({ page }, limited.id, run => run.status === 'error'); + assert.equal(failed.failure?.kind, 'rate_limit'); + await page.goto(`${origin}/?run=${limited.id}`); await ready(page); await selectHistoryRun(page, limited.id); + await page.locator('[data-action="recover"][data-recovery="retry"]:visible').first().waitFor(); + const shrink = page.locator('[data-action="recover"][data-recovery="workers"]:visible').first(); + if (capacity === 3) { + await shrink.click(); + await page.locator('#run-settings[open] #native-team-capacity:focus').waitFor(); + assert.equal(await page.locator('#native-team-capacity').inputValue(), '2'); + await closeSettings(page); + } else assert.equal(await shrink.count(), 0); + } + + await showChat(page); + const legacyDraft = encodeTaskDraft({ ...input, templateId: '', maxTurns: '6', maxRunSeconds: '120', workers: '2', + modulePlan: { scheduler: 'critical-path', context: 'essential', custom: [] } }); + await page.locator('#task-file').setInputFiles({ name: 'legacy-draft.json', mimeType: 'application/json', buffer: Buffer.from(legacyDraft) }); + await page.locator('#import-task-dialog[open]').waitFor(); + const previewFacts = await page.locator('#import-facts').innerText(); + assert.match(previewFacts, /Codex 原生团队/u); + assert.match(previewFacts, /团队人数上限(含 Lead)\s+3/u); + assert.doesNotMatch(previewFacts, /模块方案|任务协作/u); + await page.locator('#confirm-import').click(); + await page.locator('#run-settings[open]').waitFor(); + assert.equal(await page.locator('#native-team-capacity').inputValue(), '3'); + console.log('Native team browser checks passed, including submission replay, knowledge settings, rate limit recovery, and importing legacy drafts.'); } finally { await browser.close(); await service.close(); await fs.rm(config.dataRoot!, { recursive: true, force: true }); } } diff --git a/scripts/test-web-natural-first.ts b/scripts/test-web-natural-first.ts index 1b9b8869..b20f6b65 100644 --- a/scripts/test-web-natural-first.ts +++ b/scripts/test-web-natural-first.ts @@ -17,7 +17,7 @@ await fs.mkdir(output, { recursive: true }); const port = await freePort(), origin = `http://127.0.0.1:${port}`; const service = createWebService(readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin, THEOREMOS_WEB_STATIC_ROOT: path.join(root, 'out/web') }), { - async readiness() { return { ready: true, message: 'Browser fixture only' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Browser fixture only' }; }, async run() { throw new Error('This UI test must never call a model'); }, async formalize() { throw new Error('This UI test must never call a model'); }, }); diff --git a/scripts/test-web-plan-approval.ts b/scripts/test-web-plan-approval.ts index e9ef7a5d..62a5dcc6 100644 --- a/scripts/test-web-plan-approval.ts +++ b/scripts/test-web-plan-approval.ts @@ -15,10 +15,8 @@ import { closeSettings, openHistory, openSettings, openTab, refreshHistory, sele import { freePort, postRun, ready, settled, startBrowser } from './web-scenario'; /** - * 先审计划 against a local runner (no Docker, no model): the option needs task collaboration and two Agents and reaches - * the worker; a run whose plan waits shows the approval banner with its four actions; an approval of a plan that changed - * meanwhile is rejected with a readable reason, whether the saved checkpoint or the running solver rejects it; the - * approval of the current version releases the run; while the Lead revises from a note nothing can be approved. + * Native route approval against a local runner. The browser submits the opt-in, reads the frozen route, + * reconciles stale approvals, and releases the same run after approval of the current version. * Audited, and laid out at 1440 and 375 px in Chinese and at 1440 px in English. */ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); @@ -44,10 +42,12 @@ function observation(id: string): WebObservation { id: name, kind: 'goal' as const, objective: `证明 ${name}`, dependsOn: [], revision: 0, theoremName: name, proofPath: 'Submission.lean', type })) }; const snapshot = { schema: 'theoremos.run-observation.v1', runId: `solver-${id}`, stateDigest: digest('a'), resultDigest: null }; const inspection: WebInspection = { schema: 'deepscientist.math.inspection.v1', runId: snapshot.runId, snapshot, - evidence: 'recorded-not-replayed', phase: 'cooperative', + evidence: 'recorded-not-replayed', phase: 'running', problem: { id: 'plan-approval-fixture', statement: '证明两个自然数加零的等式', formalStatement: source, assumptions: [], targets: tasks.map(([name]) => ({ proofPath: 'Submission.lean', theoremName: name })) }, - configuration: { model: 'fixture', effort: 'low', workers: 2, coordination: 'cooperative', buildDigest: digest('b'), environmentDigest: digest('e') }, + configuration: { model: 'fixture', effort: 'low', workers: 1, coordination: 'independent', buildDigest: digest('b'), environmentDigest: digest('e'), + researchMode: 'skill', researchDelegation: { mode: 'team', maxAgents: 3 }, + researchSkill: { name: 'theoremos-research', digest: digest('f'), loading: 'native' } }, turns: 1, planVersion: plan.baseVersion, scheduling: { evidence: 'recorded-dispatch-state', observedWorkers: 2, working: 0, proofAssignments: 0, preparing: 0, stopping: 0, idle: 2, stopped: 0 }, knowledge: { status: 'disabled', evidence: 'recorded-not-replayed', attribution: 'model-reported-origin', retrievalCoverage: 'recorded', @@ -74,7 +74,7 @@ function revise(control: Control, version: string) { control.observation.inspection.planVersion = control.approval.planVersion = version; } const runner: WebRunner = { - async readiness() { return { ready: true, message: '本地计划批准验证环境' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: '本地计划批准验证环境' }; }, async run(input, send: (message: WorkerMessage) => void, signal) { started.push(input.input); await new Promise(resolve => { @@ -112,7 +112,8 @@ const runner: WebRunner = { const service = createWebService(readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin, THEOREMOS_WEB_STATIC_ROOT: path.join(root, 'out/web'), THEOREMOS_WEB_CONCURRENCY: '4' }), runner); const input: WebRunInput = { providerId: 'openai', apiKey: 'sk-plan-approval-fixture', model: 'fixture-plan-model', effort: 'low', - environment: 'standard', source, task: '证明两个加零的等式', maxTurns: 6, maxRunSeconds: 600, workers: 2, coordination: 'cooperative', planApproval: true }; + environment: 'mathlib', source, task: '证明两个加零的等式', maxTurns: 6, maxRunSeconds: 600, + workers: 1, coordination: 'independent', researchMode: 'skill', nativeTeamCapacity: 3, planApproval: true }; const mark = (check: string) => console.log(`PASS ${check}`); const banner = (page: Page) => page.locator('[data-run-approval]'); const shot = async (page: Page, name: string) => { await settled(page); await page.screenshot({ path: path.join(output, name) }); }; @@ -162,23 +163,16 @@ try { browser = await startBrowser(service.server, port); const { context, page } = await open(1440); - // The option is offered only where it means something: task collaboration with at least two Agents. await openSettings(page); const option = page.locator('#plan-approval'); - assert.equal(await option.isDisabled(), true, 'one Agent has no peers to hold'); - await page.locator('#workers').fill('2'); - assert.equal(await option.isDisabled(), false); + assert.equal(await option.isEnabled(), true); + assert.equal(await option.isChecked(), false); await option.check(); - await page.locator('input[name="coordination"][value="independent"]').check({ force: true }); - assert.equal(await option.isDisabled(), true, 'independent Agents share no plan'); - assert.equal(await option.isChecked(), true, 'the choice is kept for when it applies again'); - await page.locator('input[name="coordination"][value="cooperative"]').check({ force: true }); - assert.equal(await option.isDisabled(), false); await page.locator('.plan-approval-option').scrollIntoViewIfNeeded(); assert.deepEqual(await audit(page, { scope: '#run-settings' }), [], 'settings with the plan-approval option'); await shot(page, 'option-1440.png'); await closeSettings(page); - mark('先审计划 needs task collaboration and two Agents'); + mark('approval is an explicit opt-in on the Codex native team'); await page.locator('#task').fill(input.task); await page.evaluate(([key, value]) => { @@ -191,16 +185,24 @@ try { await page.locator('#submit-run:enabled').click(); const body = JSON.parse((await request).postData() ?? '{}'); assert.equal(body.planApproval, true, 'the option is submitted'); + assert.equal(body.nativeTeamCapacity, 3); + assert.equal(body.coordination, 'independent'); // The new run opens on its chat, whose card names the wait; the banner and its actions are in the run panel. await page.locator('body[data-view="run"] .detail-heading[data-run]').waitFor({ state: 'attached' }); await showArtifacts(page); - await banner(page).waitFor({ timeout: 15_000 }); + await banner(page).waitFor({ timeout: 15_000 }).catch(async error => { + const data = await page.evaluate(async () => (await (await fetch('/api/runs')).json()).runs?.map((run: { status: string; phase?: string; observation?: WebObservation; events: { event: string }[] }) => ({ + status: run.status, phase: run.phase, approval: run.observation?.inspection.planApproval, events: run.events.map(event => event.event), + }))); + console.error('Native approval observations at timeout:', data, 'document:', await page.locator('#run-detail').innerText(), 'page errors:', errors); + throw error; + }); assert.equal(started.at(-1)?.planApproval, true, 'the option reaches the worker'); const first = [...controls.keys()].at(-1)!, control = controls.get(first)!; mark('the option reaches the worker'); // The waiting plan: the banner says what is asked and why nothing runs, and the run reads as waiting everywhere. assert.equal(await page.locator('#run-approval-heading').innerText(), '研究计划等你批准'); - assert.match(await banner(page).innerText(), /Lead 把题目拆成了 2 项任务。批准后 Agent 才开始工作[\s\S]*等待确认不计入证明预算/u); + assert.match(await banner(page).innerText(), /请核对 Lead 的初始路线,批准后团队开始证明/u); assert.equal(await page.locator('.detail-statusline [data-status]').innerText(), '等你批准计划'); assert.match(await page.locator('#detail-panel').innerText(), /Lead 已经拟好研究计划,等你批准后 Agent 才开始工作/u); // The history sits folded under 证明任务 beside the chat. @@ -223,21 +225,16 @@ try { assert.equal(await page.locator('[data-run-approval] [data-action="approve-plan"]').isEnabled(), true); mark('returning to a pending plan keeps the same run ready to approve'); - // Its other actions lead to the plan, its editor and a note to the Lead; the banner stays above every tab. + // The banner links to the saved plan so the reader can review what they are about to approve. await page.locator('[data-run-approval] [data-action="show-plan"]').click(); await page.locator('#detail-tab-collaboration[aria-selected="true"]').waitFor(); await page.locator('[data-collab-task="add_zero"]:visible').first().waitFor(); assert.equal(await banner(page).count(), 1); - await page.locator('[data-run-approval] [data-action="edit-plan"]').click(); - await page.locator('.collab-plan-dialog[open]').waitFor(); - await page.locator('[data-plan-close]').click(); - await page.locator('.collab-plan-dialog[open]').waitFor({ state: 'detached' }); - await page.locator('[data-run-approval] [data-action="guide-lead"]').click(); - await page.waitForFunction(() => document.activeElement?.matches('[data-guidance-text]')); - assert.equal(await page.locator('[data-guidance-kind]').inputValue(), 'lead', 'the note is addressed to the Lead'); - assert.equal(approvals.length, 0, 'looking, editing and writing a note approve nothing'); + assert.equal(await page.locator('[data-run-approval] [data-action="edit-plan"]').count(), 0); + assert.equal(await page.locator('[data-run-approval] [data-action="guide-lead"]').count(), 0); + assert.equal(approvals.length, 0, 'reading the plan sends no approval'); await openTab(page, 'result'); - mark('查看计划, 修改计划 and 给 Lead 留言 open the plan, its editor and a note to the Lead'); + mark('viewing the saved native plan does not send approval'); // The plan changed after the page last read it: the saved checkpoint rejects the approval of the older version. revise(control, 'plan-v2'); @@ -255,7 +252,6 @@ try { await page.locator('[data-run-approval] [data-action="approve-plan"]').click(); await page.locator('[data-run-original-plan-approval]').waitFor(); assert.equal(await page.locator('[data-run-approval] [data-action="approve-plan"]').isDisabled(), true); - assert.equal(await page.locator('[data-run-approval] [data-action="edit-plan"]').isDisabled(), true); await page.locator('#toast:not([hidden])').getByText('批准已提交,运行确认后 Agent 就开始工作').waitFor(); for (let tries = 0; control.approval.status !== 'approved' && tries < 50; tries++) await page.waitForTimeout(100); await poll(page); @@ -311,7 +307,7 @@ try { const { context, page } = await open(1440, 'en'); await selectHistoryRun(page, second); await page.locator('#run-approval-heading').getByText('The research plan is waiting for your approval').waitFor(); - assert.match(await banner(page).innerText(), /The Lead split the problem into 2 tasks[\s\S]*Approve and start/u); + assert.match(await banner(page).innerText(), /Review the Lead’s initial route[\s\S]*Approve and start/u); assert.deepEqual(await audit(page, { scope: '[data-run-approval]' }), [], 'English approval banner'); assert.equal(await page.locator('#result-verdict-heading').innerText(), 'Proving has not started'); assert.equal(await page.locator('.result-goals .goal-row .badge').first().innerText(), 'Awaiting plan approval'); @@ -335,9 +331,14 @@ try { await page.locator('#detail-panel [data-action="notify"][aria-pressed="true"]').waitFor(); await page.locator('#toast:not([hidden])').getByText('研究结束或计划等你批准时会发送桌面通知').waitFor(); await page.waitForFunction(() => document.title.startsWith('(1) 等你批准计划')); + await page.clock.install(); await setHidden(page, true); Object.assign(later.approval, { status: 'pending', requestedAt: Date.now() }); later.emit(); - await page.waitForFunction(() => document.title.startsWith('(2) 等你批准计划'), undefined, { timeout: 25_000 }); + // A hidden tab stops live updates and polls every 30 seconds. + await page.clock.fastForward(31_000); + await page.waitForFunction(() => document.title.startsWith('(2) 等你批准计划')); + // The browser lock for notification delivery can run after the title has been rendered. + await page.waitForFunction(() => (window as unknown as { __notifications: unknown[] }).__notifications.length > 0); const shown = await notifications(page); assert.equal(shown.length, 1); assert.equal(shown[0].title, 'TheoremOS · 研究计划等你批准'); diff --git a/scripts/test-web-plan-ownership.ts b/scripts/test-web-plan-ownership.ts deleted file mode 100644 index 71d7b312..00000000 --- a/scripts/test-web-plan-ownership.ts +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env bun -// Real loopback HTTP and Chromium with in-memory accounts and a synthetic runner. No model, Lean or Docker calls. -import assert from 'node:assert/strict'; -import fs from 'node:fs/promises'; -import path from 'node:path'; -import type { BrowserContext, Page } from 'playwright'; -import { readWebConfig } from '../apps/web/config'; -import { createWebService } from '../apps/web/server'; -import type { WebRunner } from '../apps/web/runner'; -import type { WebRunInput } from '../apps/web/shared'; -import type { WebObservation } from '../apps/web/collaboration'; -import { closeDialog, refreshHistory, selectHistoryRun } from './web-ui-controls'; -import { freePort, ready, settled, startBrowser, webScenario, writeScenarioReport, - type ScenarioHarness, type ScenarioSuite } from './web-scenario'; - -const root = path.resolve(import.meta.dirname, '..'), output = path.join(root, 'out/web-plan-ownership'); -await fs.mkdir(output, { recursive: true }); -const now = () => new Date().toISOString(), digest = (text: string) => text.repeat(64); -const controls = new Map(); -const commands: { runId: string; type: string }[] = []; -const mail: { to: string; text: string }[] = []; -function observation(id: string): WebObservation { - const tasks = [{ id: 'base', kind: 'lemma' as const, objective: 'Synthetic local premise', dependsOn: [], revision: 0, - theoremName: 'base', proofPath: 'Submission.lean', type: 'True' }, - { id: 'original', kind: 'goal' as const, objective: 'Synthetic original target', dependsOn: ['base'], revision: 0, - theoremName: 'original_goal', proofPath: 'Submission.lean', type: 'True' }]; - const snapshot = { schema: 'theoremos.run-observation.v1', runId: `solver-${id}`, stateDigest: digest('a'), resultDigest: null }; - return { schema: 'theorem-os.web-observation.v1', webRunId: id, solverRunId: snapshot.runId, - observedAt: now(), sequence: 1, evidence: 'recorded-not-replayed', acceptance: 'not-assessed', snapshot, - plan: { schema: 'deepscientist.math.plan-edit.v1', baseVersion: 'plan-v1', tasks }, - inspection: { schema: 'deepscientist.math.inspection.v1', runId: snapshot.runId, snapshot, - evidence: 'recorded-not-replayed', phase: 'cooperative', - problem: { id: 'ownership-fixture', statement: 'Synthetic True fixture', formalStatement: 'True', assumptions: [], - targets: [{ proofPath: 'Submission.lean', theoremName: 'original_goal' }] }, - configuration: { model: 'fixture', effort: 'low', workers: 2, coordination: 'cooperative', buildDigest: digest('b'), environmentDigest: digest('e') }, - turns: 1, planVersion: 'plan-v1', scheduling: { evidence: 'recorded-dispatch-state', observedWorkers: 2, - working: 0, proofAssignments: 0, preparing: 0, stopping: 0, idle: 2, stopped: 0 }, - knowledge: { status: 'disabled', evidence: 'recorded-not-replayed', attribution: 'model-reported-origin', - retrievalCoverage: 'recorded', droppedRetrievals: 0, retrievals: [], originalUses: [], uses: [] }, tokenBudget: {}, continuation: {}, - mathematics: { snapshot: { schema: 'theorem-os.obligation.v1', evidence: 'recorded-not-replayed', - acceptance: 'not-assessed', digest: digest('c'), obligations: [], goals: [], blockers: [], routes: [], advisory: [] }, - recentChanges: [], retainedChangeLimit: 64 }, - progress: { checkedProofTasks: 0, conditionalProofTasks: 0, completedResearchTasks: 0, openProofTasks: ['base', 'original'] }, - groups: [], tasks: tasks.map(task => ({ id: task.id, kind: task.kind, objective: task.objective, group: 'main', - status: 'pending', control: 'active', version: `${task.id}-v1`, theorem: task.theoremName, type: task.type, - premises: [], plannedDependencies: task.dependsOn, attempts: 0, proof: { status: 'none' }, parkedBy: [], parkedRoutes: {} })), - workers: [], statementReviews: [], edits: [] }, sources: [], checks: [], guidance: [], coverage: { sources: 'recorded', checks: 'recorded' } }; -} -const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Local plan ownership fixture' }; }, - async run(input, send, signal) { - await new Promise(resolve => { - controls.set(input.id, { finish: resolve }); - signal.addEventListener('abort', () => resolve(), { once: true }); - send({ type: 'observation', observation: observation(input.id) }); - }); - }, - async command(runId, command) { - commands.push({ runId, type: command.type }); - if (command.type === 'capture') return { id: 'capture', status: 'captured', observation: observation(runId) }; - if (command.type !== 'edit' && command.type !== 'edit-preview') throw new Error(`Unexpected fixture command: ${command.type}`); - return { id: command.proposal.id, status: command.type === 'edit-preview' ? 'validated' : 'unknown' }; - }, -}; -const port = await freePort(), origin = `http://127.0.0.1:${port}`; -const service = createWebService(readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin, - THEOREMOS_WEB_STATIC_ROOT: path.join(root, 'out/web'), THEOREMOS_WEB_CONCURRENCY: '8', - THEOREMOS_WEB_AUTH: 'email', THEOREMOS_WEB_SMTP_URL: 'log:', THEOREMOS_WEB_ALLOWLIST: 'alice@example.org,bob@example.org' }), runner, -{ sample: null, mailer: async item => { mail.push(item); }, captchaAnswer: () => '12345' }); -const browser = await startBrowser(service.server, port); -const suite: ScenarioSuite = { origin, output, checks: [], failedScenario: '' }; -const accountCookies = new Map>>(); -type Login = Awaited>; -type Harness = ScenarioHarness & { alice: Login; runIds: string[] }; -async function login(context: BrowserContext, email: string) { - const cookies = accountCookies.get(email); - if (cookies) await context.addCookies(cookies); - const request = context.request; - let session = await (await request.get(origin + '/api/session')).json(); - const headers = () => ({ 'X-CSRF-Token': session.csrfToken, Origin: origin }); - if (!cookies) { - const captcha = await (await request.post(origin + '/api/auth/captcha', { headers: headers(), data: {} })).json(); - const sent = await request.post(origin + '/api/auth/code', { headers: headers(), data: { email, captchaId: captcha.id, captcha: '12345' } }); - assert.equal(sent.status(), 200); - const code = mail.findLast(item => item.to === email)!.text.match(/\b\d{6}\b/)![0]; - const verified = await request.post(origin + '/api/auth/verify', { headers: headers(), data: { email, code } }); - assert.equal(verified.status(), 200); session = await verified.json(); - accountCookies.set(email, await context.cookies()); - } - return { async create(task: string) { - const input: WebRunInput = { providerId: 'openai', apiKey: 'sk-local-plan-ownership', model: 'fixture', effort: 'low', - environment: 'standard', source: 'theorem original_goal : True := by sorry\n', task, - maxTurns: 2, maxRunSeconds: 60, workers: 2, coordination: 'cooperative' }; - const response = await request.post(origin + '/api/runs', { headers: headers(), data: input }); - assert.equal(response.status(), 201); - return (await response.json()).run.id as string; - } }; -} -async function reconnect(page: Page, email: string) { - const session = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session' && response.status() === 200); - const listed = page.waitForResponse(response => new URL(response.url()).pathname === '/api/runs' && response.request().method() === 'GET'); - await page.evaluate(() => window.dispatchEvent(new Event('offline'))); - await page.evaluate(() => window.dispatchEvent(new Event('online'))); - assert.equal((await (await session).json()).account.email, email); - await listed; await settled(page); -} -async function openPlan(page: Page, id: string) { - await refreshHistory(page); await selectHistoryRun(page, id, 'collaboration'); - await page.locator('[data-collab-plan]:enabled').click(); - await page.locator('.collab-plan-dialog[open]').waitFor(); - await page.locator('[data-plan-task]').selectOption('base'); -} -try { - // Separate authenticated sessions model cookies being replaced by another tab without expiring the previous owner. - for (const email of ['alice@example.org', 'bob@example.org']) { - const context = await browser.newContext(); - try { await login(context, email); } finally { await context.close(); } - } - for (const width of [1440, 390]) for (const outcome of ['unknown', 'error', 'missing-retry'] as const) { - const name = `${width}px: switching owner closes a private plan and revokes its late ${outcome} response`; - await webScenario(browser, suite, name, async h => { - const { page, context } = h, id = await h.alice.create('Synthetic Alice run'); h.runIds.push(id); - await openPlan(page, id); - const privateText = `Alice private full plan ${width} ${outcome}`; - await page.locator('[data-plan-objective]').fill(privateText); - const aliceJson = await page.locator('#collab-plan-json').inputValue(); - await reconnect(page, 'alice@example.org'); - assert.equal(await page.locator('.collab-plan-dialog[open]').count(), 1, 'same-owner reconnect preserves an open editor'); - assert.equal(await page.locator('#collab-plan-json').inputValue(), aliceJson); - await page.locator('[data-plan-preview]').click(); await page.locator('[data-plan-apply]:enabled').waitFor(); - const editPath = `/api/runs/${id}/edits`, commandId = JSON.parse(aliceJson).id as string; - if (outcome === 'missing-retry') { - await page.route(`**${editPath}`, route => route.abort(), { times: 1 }); - await page.locator('[data-plan-apply]').click(); - await page.locator('[data-plan-retry]:enabled').waitFor(); - } - // Delay body handling after api() already checked Alice's HTTP owner header. - await page.evaluate(({ pathname, outcome }) => { - const json = Response.prototype.json; - Response.prototype.json = async function () { - const value = await json.call(this); - if (new URL(this.url).pathname === pathname && (value.receipt?.status === 'unknown' || this.status === 404)) { - await new Promise(resolve => { (window as any).__releasePrivatePlan = resolve; }); - if (outcome === 'error') throw new Error('Alice private late response failed'); - } - return value; - }; - }, { pathname: outcome === 'missing-retry' ? `/api/runs/${id}/commands/${commandId}` : editPath, outcome }); - await page.locator(outcome === 'missing-retry' ? '[data-plan-retry]' : '[data-plan-apply]').click(); - await page.waitForFunction(() => Boolean((window as any).__releasePrivatePlan)); - const bob = await login(context, 'bob@example.org'); - await reconnect(page, 'bob@example.org'); - assert.equal(await page.locator('.collab-plan-dialog[open]').count(), 0, 'an owner change must close the old owner plan editor'); - assert.ok(!(await page.locator('body').innerText()).includes(privateText), 'the new owner cannot see the private plan'); - const bobId = await bob.create('Synthetic Bob run'); h.runIds.push(bobId); await openPlan(page, bobId); - await page.locator('[data-plan-objective]').fill('Bob current editable proposal'); - const bobJson = await page.locator('#collab-plan-json').inputValue(); - const afterSwitch = h.requests.length; - await page.evaluate(() => (window as any).__releasePrivatePlan()); await settled(page); - assert.equal(await page.locator('#collab-plan-json').inputValue(), bobJson); - assert.equal(await page.locator('[data-plan-receipt] > :not([data-decision-summary])').count(), 0, 'Alice receipt/error cannot enter Bob editor beside his own plan summary'); - assert.deepEqual(h.requests.slice(afterSwitch).filter(request => request.pathname.startsWith(`/api/runs/${id}/commands/`) - || request.method === 'POST' && request.pathname === editPath), [], - 'a revoked command cannot read or retry its receipt under the new owner'); - await page.locator('[data-plan-preview]').click(); await page.locator('[data-plan-apply]:enabled').waitFor(); - await closeDialog(page, '.collab-plan-dialog', () => page.locator('[data-plan-close]').click()); - await login(context, 'alice@example.org'); await reconnect(page, 'alice@example.org'); await openPlan(page, id); - assert.ok(!(await page.locator('#collab-plan-json').inputValue()).includes(privateText), 'discarded plan drafts cannot revive after a later login'); - await page.screenshot({ path: path.join(output, `owner-switch-${width}-${outcome}.png`) }); - }, { - context: { viewport: { width, height: 1000 }, reducedMotion: 'reduce' }, - harness: (page, context) => ({ page, context, requests: [], alice: undefined as unknown as Login, runIds: [] }), - routes: { local: 'All browser requests must stay on the local synthetic fixture' }, - open: async h => { h.alice = await login(h.context, 'alice@example.org'); await h.page.goto(origin); await ready(h.page); }, - timeout: { label: 'Plan ownership', seconds: 45 }, - verify: (h, elapsedMs) => ({ name, elapsedMs: elapsedMs(), requests: h.requests, runIds: h.runIds }), - cleanup: async h => { - await h.page.evaluate(() => (window as any).__releasePrivatePlan?.()).catch(() => {}); - for (const id of h.runIds) controls.get(id)?.finish(); - }, - }); - } - await writeScenarioReport(path.join(output, 'report.json'), suite, 'passed', undefined, 'local-real-http-plan-ownership', - { checks: suite.checks, commands, screenshots: [1440, 390].flatMap(width => ['unknown', 'error', 'missing-retry'] - .map(outcome => `owner-switch-${width}-${outcome}.png`)) }); -} catch (error) { - await writeScenarioReport(path.join(output, 'report.json'), suite, 'failed', error, 'local-real-http-plan-ownership', - { checks: suite.checks }, { failureRequests: true }); throw error; -} finally { - for (const control of controls.values()) control.finish(); - await browser.close(); await service.close(); -} diff --git a/scripts/test-web-plan-recovery.ts b/scripts/test-web-plan-recovery.ts deleted file mode 100644 index 289dc646..00000000 --- a/scripts/test-web-plan-recovery.ts +++ /dev/null @@ -1,456 +0,0 @@ -#!/usr/bin/env bun -import assert from 'node:assert/strict'; -import fs from 'node:fs/promises'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import type { Page, Route } from 'playwright'; -import { readWebConfig } from '../apps/web/config'; -import { createWebService } from '../apps/web/server'; -import type { WebRunner } from '../apps/web/runner'; -import type { WebRunInput } from '../apps/web/shared'; -import type { WebCommand, WebObservation, WebPlanProposal } from '../apps/web/collaboration'; -import { closeDialog, fitViewport, refreshHistory, selectHistoryRun } from './web-ui-controls'; -import { deferred, freePort, postRun, settled, startBrowser, webScenario, writeScenarioReport, - type ScenarioHarness, type ScenarioSuite } from './web-scenario'; - -const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const output = path.join(root, 'out/web-plan-recovery'); -await fs.mkdir(output, { recursive: true }); -const now = () => new Date().toISOString(), digest = (character: string) => character.repeat(64); -type Control = { observation: WebObservation; mode: 'unknown' | 'queued' | 'applied'; emit(): void; finish(): void }; -type Call = { method: string; pathname: string; body: string | null }; -type Harness = ScenarioHarness & { runIds: string[]; calls: Call[]; effect?: (route: Route) => Promise }; -const controls = new Map(); -const commands: Array<{ runId: string; command: WebCommand }> = []; - -function observation(id: string): WebObservation { - const plan: WebObservation['plan'] = { schema: 'deepscientist.math.plan-edit.v1', baseVersion: 'plan-v1', tasks: [ - { id: 'base', kind: 'lemma', objective: 'Prove the reusable premise', dependsOn: [], revision: 0, - theoremName: 'base', proofPath: 'Submission.lean', type: 'True' }, - { id: 'original', kind: 'goal', objective: 'Prove the original theorem', dependsOn: ['base'], revision: 0, - theoremName: 'original_goal', proofPath: 'Submission.lean', type: 'True' }, - ] }; - const snapshot = { schema: 'theoremos.run-observation.v1', runId: `solver-${id}`, stateDigest: digest('a'), resultDigest: null }; - return { schema: 'theorem-os.web-observation.v1', webRunId: id, solverRunId: snapshot.runId, - observedAt: now(), sequence: 1, evidence: 'recorded-not-replayed', acceptance: 'not-assessed', snapshot, plan, - inspection: { schema: 'deepscientist.math.inspection.v1', runId: snapshot.runId, snapshot, - evidence: 'recorded-not-replayed', phase: 'cooperative', - problem: { id: 'plan-recovery-fixture', statement: 'Prove True', formalStatement: 'True', assumptions: [], - targets: [{ proofPath: 'Submission.lean', theoremName: 'original_goal' }] }, - configuration: { model: 'fixture', effort: 'low', workers: 2, coordination: 'cooperative', - buildDigest: digest('b'), environmentDigest: digest('e') }, turns: 1, planVersion: plan.baseVersion, - scheduling: { evidence: 'recorded-dispatch-state', observedWorkers: 2, working: 1, proofAssignments: 1, - preparing: 0, stopping: 0, idle: 1, stopped: 0 }, - knowledge: { status: 'disabled', evidence: 'recorded-not-replayed', attribution: 'model-reported-origin', - retrievalCoverage: 'recorded', droppedRetrievals: 0, retrievals: [], originalUses: [], uses: [] }, - tokenBudget: {}, continuation: {}, mathematics: { snapshot: { schema: 'theorem-os.obligation.v1', - evidence: 'recorded-not-replayed', acceptance: 'not-assessed', digest: digest('c'), - obligations: [], goals: [], blockers: [], routes: [], advisory: [] }, recentChanges: [], retainedChangeLimit: 64 }, - progress: { checkedProofTasks: 0, conditionalProofTasks: 0, completedResearchTasks: 0, openProofTasks: ['base', 'original'] }, - groups: [], tasks: plan.tasks.map(task => ({ id: task.id, kind: task.kind, objective: task.objective, - group: 'main', status: 'pending', control: 'active', version: `${task.id}-v1`, theorem: task.theoremName, - type: task.type, premises: [], plannedDependencies: task.dependsOn, attempts: 0, - proof: { status: 'none' }, parkedBy: [], parkedRoutes: {} })), - workers: [{ id: 'lead', role: 'lead', phase: 'waiting', turns: 1, dispatchWait: { status: 'unknown' } }, - { id: 'prover-1', role: 'prover', phase: 'proving', task: 'base', turns: 1, dispatchWait: { status: 'unknown' } }], - statementReviews: [], edits: [] }, sources: [], checks: [], guidance: [], coverage: { sources: 'recorded', checks: 'recorded' } }; -} - -function hostReceipt(runId: string, proposal: WebPlanProposal, status: 'applied' | 'rejected') { - const control = controls.get(runId)!; - if (status === 'applied') { - control.observation.plan = { ...structuredClone(proposal), baseVersion: 'plan-v2' }; - control.observation.inspection.planVersion = 'plan-v2'; - } - control.observation.inspection.edits.push({ id: proposal.id, status, baseVersion: proposal.baseVersion, - planVersion: status === 'applied' ? 'plan-v2' : undefined, affectedTasks: ['base'], - ...(status === 'applied' ? { recheck: { status: 'pending', tasks: [{ taskId: 'base', taskDigest: 'base-v1', status: 'pending' }] } } : {}), - reason: status === 'rejected' ? 'fixture_host_rejected' : undefined }); - control.emit(); -} -const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Local plan recovery HTTP fixture' }; }, - async run(input, send, signal) { - await new Promise(resolve => { - const control: Control = { observation: observation(input.id), mode: 'unknown', finish: resolve, - emit() { this.observation = { ...this.observation, sequence: this.observation.sequence + 1, observedAt: now() }; - send({ type: 'observation', observation: structuredClone(this.observation) }); } }; - controls.set(input.id, control); signal.addEventListener('abort', () => resolve(), { once: true }); control.emit(); - }); - }, - async command(runId, command) { - commands.push({ runId, command: structuredClone(command) }); - const control = controls.get(runId)!; - if (command.type === 'capture') return { id: 'capture', status: 'captured', observation: control.observation }; - if (command.type === 'guidance-withdraw') return { id: command.id, status: 'rejected', reason: 'fixture_guidance_withdraw_not_simulated' }; - if (command.type === 'guidance') throw new Error('Plan recovery must not send guidance'); - if (command.type === 'plan-approval') throw new Error('Plan recovery must not approve a plan'); - if (command.proposal.baseVersion !== control.observation.plan!.baseVersion) throw new Error('math_edit_version_conflict'); - if (command.type === 'edit-preview') return { id: command.proposal.id, status: 'validated', affectedTaskIds: ['base'], - changes: [{ taskId: 'base', fields: ['objective'] }] }; - if (control.mode !== 'applied') return { id: command.proposal.id, status: control.mode, - ...(control.mode === 'unknown' ? { reason: 'fixture_delivery_uncertain' } : {}) }; - hostReceipt(runId, command.proposal, 'applied'); - return { id: command.proposal.id, status: 'queued', baseVersion: command.proposal.baseVersion, observation: control.observation }; - }, -}; -const port = await freePort(), origin = `http://127.0.0.1:${port}`; -const service = createWebService(readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin, - THEOREMOS_WEB_STATIC_ROOT: path.join(root, 'out/web'), THEOREMOS_WEB_CONCURRENCY: '4' }), runner); -const browser = await startBrowser(service.server, port); -const suite: ScenarioSuite = { origin, output, checks: [], failedScenario: '' }; -const input: WebRunInput = { providerId: 'openai', apiKey: 'sk-local-plan-recovery-fixture', model: 'fixture', effort: 'low', - environment: 'standard', source: 'theorem original_goal : True := by sorry\n', task: 'Inspect plan recovery', - maxTurns: 2, maxRunSeconds: 60, workers: 2, coordination: 'cooperative' }; -const receipt = '[data-plan-receipt]', refresh = '[data-plan-receipt-refresh]', retry = '[data-plan-retry]'; -const json = (page: Page) => page.locator('#collab-plan-json').inputValue(); -const proposal = async (page: Page) => JSON.parse(await json(page)) as WebPlanProposal; -const edits = (h: Harness, id: string) => h.calls.filter(call => call.method === 'POST' && call.pathname === `/api/runs/${id}/edits`); -const reads = (h: Harness, id: string) => h.calls.filter(call => call.method === 'GET' && call.pathname.startsWith(`/api/runs/${id}/commands/`)); -const delivered = (id: string) => commands.filter(item => item.runId === id && item.command.type === 'edit'); -async function select(h: Harness, id: string) { - await selectHistoryRun(h.page, id, 'collaboration'); await h.page.locator('.collab-surface').waitFor(); - await h.page.locator('[data-collab-task="base"]:visible').first().waitFor(); -} -async function create(h: Harness) { - const run = await postRun(h, input); h.runIds.push(run.id); - await refreshHistory(h.page); await select(h, run.id); return run; -} -async function openPlan(page: Page) { - await page.locator('[data-collab-plan]:enabled').click(); - await page.locator('.collab-plan-dialog[open]').waitFor(); await page.locator('[data-plan-task]').selectOption('base'); -} -const closePlan = (page: Page) => closeDialog(page, '.collab-plan-dialog', () => page.locator('[data-plan-close]').click()); -async function preview(page: Page) { - await page.locator('[data-plan-preview]').click(); await page.locator('[data-plan-apply]:enabled').waitFor(); -} -async function poll(page: Page) { - const response = page.waitForResponse(response => new URL(response.url()).pathname === '/api/runs' && response.request().method() === 'GET'); - await page.evaluate(() => document.dispatchEvent(new Event('visibilitychange'))); await response; await settled(page); -} -async function observed(page: Page, sequence: number) { - await page.waitForFunction(sequence => document.querySelector('[data-collab-observation]')?.textContent?.includes(`观察 #${sequence} ·`), sequence); -} -async function applied(page: Page, id: string) { - await page.locator(receipt).getByText(new RegExp(`回执 ${id} · 已应用`)).waitFor(); -} -function scenario(name: string, run: (h: Harness) => Promise, width = 1440) { - return webScenario(browser, suite, name, run, { - context: { viewport: { width, height: width > 850 ? 1000 : 812 }, reducedMotion: 'reduce' }, - harness: (page, context) => { - const h: Harness = { page, context, requests: [], runIds: [], calls: [] }; - h.intercept = async route => { - const pathname = new URL(route.request().url()).pathname; - h.calls.push({ method: route.request().method(), pathname, - body: /\/edits(?:\/preview)?$/.test(pathname) ? route.request().postData() : null }); - return await h.effect?.(route) ?? false; - }; return h; - }, routes: { local: 'Plan recovery browser checks must stay local' }, open: true, - timeout: { label: 'Plan recovery', seconds: 45 }, - verify: (h, elapsedMs) => ({ name, elapsedMs: elapsedMs(), calls: h.calls, runIds: h.runIds }), - cleanup: h => { for (const id of h.runIds) controls.get(id)?.finish(); }, - }); -} - -try { - for (const width of [1440, 390]) for (const originalState of ['applied', 'pending'] as const) - await scenario(`${width}px: correcting invalid JSON creates a fresh draft after an ${originalState} submission`, async h => { - const { page } = h, run = await create(h), control = controls.get(run.id)!; - control.mode = originalState === 'applied' ? 'applied' : 'unknown'; - await openPlan(page); await page.locator('[data-plan-objective]').fill('Original submitted JSON proposal'); await preview(page); - const original = await proposal(page); await page.locator('[data-plan-apply]').click(); - await page.locator('[data-plan-objective]:enabled').waitFor(); - if (originalState === 'applied') await applied(page, original.id); - else await page.locator(`${refresh}:enabled`).waitFor(); - await page.locator('[data-plan-advanced] summary').click(); - const editor = page.locator('#collab-plan-json'); - for (const incomplete of ['{', '[]', '{}', 'null']) { - await editor.fill(incomplete); - assert.equal(await page.locator('[data-plan-preview]').isDisabled(), true, 'incomplete JSON cannot be previewed'); - } - const corrected = { ...structuredClone(original), baseVersion: control.observation.plan!.baseVersion }; - corrected.tasks.find(task => task.id === 'base')!.objective = 'Corrected newer JSON proposal'; - await editor.fill(JSON.stringify(corrected, null, 2)); await editor.press('Tab'); - const newer = await proposal(page), newerText = await json(page); - assert.equal(newer.tasks.find(task => task.id === 'base')!.objective, corrected.tasks[0]!.objective); - if (originalState === 'pending') { - assert.deepEqual(JSON.parse((await page.locator(`${receipt} pre`).textContent())!), original, 'the exact original pending command remains recoverable'); - hostReceipt(run.id, original, 'rejected'); - await page.locator(receipt).getByText(new RegExp(`回执 ${original.id} · 已拒绝`)).waitFor(); - assert.equal(await json(page), newerText, 'the original late receipt cannot change the corrected draft'); - assert.equal(await page.locator(refresh).isHidden(), true); - } - await page.locator('[data-plan-preview]').click(); await page.locator('[data-plan-objective]:enabled').waitFor(); - assert.equal(await page.locator('[data-plan-apply]').isEnabled(), true, 'the corrected draft preview must remain usable instead of showing the original command receipt'); - assert.notEqual(newer.id, original.id, 'correcting temporary invalid JSON must retire the already submitted command ID'); - await page.locator(receipt).getByText(new RegExp(`回执 ${newer.id} · 已校验`)).waitFor(); - control.mode = 'applied'; await page.locator('[data-plan-apply]').click(); await applied(page, newer.id); - const sent = edits(h, run.id).map(call => JSON.parse(call.body!) as WebPlanProposal); - assert.deepEqual(sent.map(item => item.id), [original.id, newer.id], 'a corrected draft is a separate command, never a replay of the original'); - assert.equal(sent[1]!.tasks.find(task => task.id === 'base')!.objective, 'Corrected newer JSON proposal'); - assert.equal(delivered(run.id).length, 2); - }, width); - - for (const status of ['applied', 'rejected'] as const) await scenario(`live ${status} receipt resolves an unknown command while preserving draft and focus`, async h => { - const { page } = h, run = await create(h); await openPlan(page); - await page.locator('[data-plan-objective]').fill(`Original proposal for ${status}`); await preview(page); - const original = await proposal(page); await page.locator('[data-plan-apply]').click(); - await page.locator(`${refresh}:enabled`).waitFor(); await page.locator(receipt).getByText(/回执 .* · 结果尚未确认/).waitFor(); - assert.equal(reads(h, run.id).length, 1, 'unknown POST must automatically read the original receipt'); - await page.locator(refresh).click(); await page.locator(`${refresh}:enabled`).waitFor(); - assert.equal(reads(h, run.id).length, 2, 'manual refresh must read again'); - assert.equal(await page.locator(retry).isHidden(), true, 'an existing unknown receipt must not offer a missing-command retry'); - await page.locator('[data-plan-objective]').fill(`New local draft after ${status}`); - const newerText = await json(page), newer = await proposal(page); assert.notEqual(newer.id, original.id); - assert.deepEqual(JSON.parse((await page.locator(`${receipt} pre`).textContent())!), original, 'pending original remains reviewable after editing'); - assert.equal(await page.locator('[data-plan-apply]').isDisabled(), true); - const control = controls.get(run.id)!; - control.observation.inspection.edits.push({ id: `${original.id}-unrelated`, status: 'applied', baseVersion: original.baseVersion }); - control.emit(); await observed(page, control.observation.sequence); - assert.equal(await page.locator(refresh).isVisible(), true, 'a different edit ID cannot confirm the pending command'); - assert.deepEqual(JSON.parse((await page.locator(`${receipt} pre`).textContent())!), original); - const focus = page.locator('[data-plan-objective]'); - await focus.focus(); await focus.evaluate((node: HTMLTextAreaElement) => node.setSelectionRange(3, 9)); - const beforeReads = reads(h, run.id).length; - hostReceipt(run.id, original, status); - await page.locator(receipt).getByText(new RegExp(`回执 ${original.id} · ${status === 'applied' ? '已应用' : '已拒绝'}`)).waitFor(); - await page.locator('[data-plan-objective]:enabled').waitFor(); - assert.equal(await json(page), newerText, 'host receipt must preserve the newer full draft'); - assert.deepEqual(await focus.evaluate((node: HTMLTextAreaElement) => ({ focused: document.activeElement === node, - start: node.selectionStart, end: node.selectionEnd })), { focused: true, start: 3, end: 9 }, 'live receipts cannot interrupt editing'); - assert.equal(await page.locator(refresh).isHidden(), true); - assert.equal(reads(h, run.id).length, beforeReads, 'observed outcomes need no manual or automatic receipt GET'); - assert.equal(edits(h, run.id).length, 1); assert.equal(delivered(run.id).length, 1); - assert.ok(reads(h, run.id).every(call => call.pathname.endsWith(`/${original.id}`))); - if (status === 'applied') { - await page.locator('[data-plan-rebase]').click(); await page.locator('[data-plan-apply]:enabled').waitFor(); - const rebased = await proposal(page), previewedText = await json(page); - assert.notEqual(rebased.id, original.id); - await focus.focus(); await focus.evaluate((node: HTMLTextAreaElement) => node.setSelectionRange(2, 7)); - const priorEdit = control.observation.inspection.edits.find(edit => edit.id === original.id)!; - priorEdit.recheck = { status: 'passed', tasks: [{ taskId: 'base', taskDigest: 'base-v1', status: 'passed' }] }; - control.emit(); await observed(page, control.observation.sequence); - await page.locator(receipt).getByText(new RegExp(`回执 ${rebased.id} · 已校验`)).waitFor(); - assert.equal(await page.locator('[data-plan-apply]').isEnabled(), true, 'an earlier command recheck cannot replace the new draft preview'); - assert.equal(await json(page), previewedText); - assert.deepEqual(await focus.evaluate((node: HTMLTextAreaElement) => ({ focused: document.activeElement === node, - start: node.selectionStart, end: node.selectionEnd })), { focused: true, start: 2, end: 7 }); - } - }); - - for (const operation of ['post-unknown', 'post-queued', 'receipt-unknown', 'receipt-error'] as const) - await scenario(`live applied and recheck progress survive a late ${operation} response`, async h => { - const { page } = h, run = await create(h), control = controls.get(run.id)!; - control.mode = operation === 'post-queued' ? 'queued' : 'unknown'; await openPlan(page); - await page.locator('[data-plan-objective]').fill(`Original command awaiting ${operation}`); await preview(page); - const original = await proposal(page), holdPost = operation.startsWith('post-'); - if (!holdPost) { - await page.locator('[data-plan-apply]').click(); await page.locator(`${refresh}:enabled`).waitFor(); - await page.locator(receipt).getByText(new RegExp(`回执 ${original.id} · 结果尚未确认`)).waitFor(); - await page.locator('[data-plan-objective]').fill(`Newer draft while ${operation} is delayed`); - } - const newerText = await json(page), held = deferred(), release = deferred(), completed = deferred(); - const target = holdPost ? `/api/runs/${run.id}/edits` : `/api/runs/${run.id}/commands/${original.id}`; - const matches = (request: { url(): string; method(): string }) => - new URL(request.url()).pathname === target && request.method() === (holdPost ? 'POST' : 'GET'); - h.effect = async route => { - if (!matches(route.request())) return false; - const response = await route.fetch(); assert.equal(response.status(), 200); held.resolve(); - await release.promise; - if (operation === 'receipt-error') await route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: 'fixture_late_read_failure' }) }); - else await route.fulfill({ response }); - completed.resolve(); return true; - }; - try { - await page.locator(holdPost ? '[data-plan-apply]' : refresh).click(); await held.promise; - const beforeReads = reads(h, run.id).length; - const canceled = !holdPost ? page.waitForEvent('requestfailed', matches) : undefined; - hostReceipt(run.id, original, 'applied'); await applied(page, original.id); - if (canceled) { - const request = await canceled; - assert.match(request.failure()?.errorText ?? '', /ERR_ABORTED/, 'a live receipt cancels the obsolete pending read'); - await page.locator('[data-plan-objective]:enabled').waitFor(); - } - await page.locator('[data-plan-recheck]').getByText('待重新检查', { exact: true }).waitFor(); - await page.locator('[data-plan-recheck] summary').click(); - const edit = control.observation.inspection.edits.find(edit => edit.id === original.id)!; - edit.recheck = { status: 'passed', tasks: [{ taskId: 'base', taskDigest: 'base-v1', status: 'passed', - lastCheck: { commit: 'fixture-checked-commit', sourceDigest: digest('d'), environmentDigest: digest('e'), - passed: true, conditional: false, receiptIds: ['fixture-recheck-receipt'] } }] }; - control.emit(); - await page.locator('[data-plan-recheck]').getByText('重新检查通过', { exact: true }).waitFor(); - assert.equal(await page.locator('[data-plan-recheck] details').evaluate((node: HTMLDetailsElement) => node.open), true, 'live recheck updates preserve the open evidence details'); - const finishedRecheck = await page.locator('[data-plan-recheck]').innerText(); - assert.match(finishedRecheck, /fixture-recheck-receipt/); - const response = holdPost ? page.waitForResponse(response => matches(response.request())) : undefined; - release.resolve(); await completed.promise; await response; await settled(page); - await page.locator('[data-plan-objective]:enabled').waitFor(); - await applied(page, original.id); - assert.equal(await page.locator('[data-plan-recheck]').innerText(), finishedRecheck, 'late responses cannot rewind recheck evidence'); - assert.equal(await page.locator(refresh).isHidden(), true, 'live confirmation must remain confirmed'); - assert.equal(await page.locator(retry).isHidden(), true); - assert.equal(await json(page), newerText, 'late response must not alter the full local draft'); - assert.doesNotMatch(await page.locator(receipt).innerText(), /fixture_late_read_failure|fixture_delivery_uncertain|结果尚未确认/); - assert.equal(reads(h, run.id).length, beforeReads, 'confirmed observations avoid another receipt recovery read'); - assert.equal(edits(h, run.id).length, 1); assert.equal(delivered(run.id).length, 1); - } finally { release.resolve(); } - }); - - await scenario('a background run receipt reconciles on reopening without changing another run draft', async h => { - const { page } = h, runA = await create(h), runB = await create(h); await select(h, runA.id); await openPlan(page); - await page.locator('[data-plan-objective]').fill('Run A original uncertain proposal'); await preview(page); - const originalA = await proposal(page); await page.locator('[data-plan-apply]').click(); - await page.locator(`${refresh}:enabled`).waitFor(); await page.locator(receipt).getByText(/回执 .* · 结果尚未确认/).waitFor(); - await page.locator('[data-plan-objective]').fill('Run A newer local draft'); const textA = await json(page); - await closePlan(page); await select(h, runB.id); await openPlan(page); - await page.locator('[data-plan-objective]').fill('Run B draft must stay isolated from A'); const textB = await json(page); - const beforeReads = reads(h, runA.id).length; - const updated = page.waitForResponse(async response => { - if (new URL(response.url()).pathname !== '/api/runs' || response.status() !== 200) return false; - const body = await response.json(); - return body.runs?.some((run: { id: string; observation?: WebObservation }) => run.id === runA.id && - run.observation?.inspection.edits.some(edit => edit.id === originalA.id && edit.status === 'applied')); - }); - hostReceipt(runA.id, originalA, 'applied'); await updated; await settled(page); - assert.equal(await json(page), textB); - assert.equal(await page.locator(`${receipt} > :not([data-decision-summary])`).count(), 0, 'only B’s own plan summary may appear; A’s receipt must stay with A'); - await closePlan(page); await select(h, runA.id); await openPlan(page); await applied(page, originalA.id); - assert.equal(await json(page), textA); assert.equal(await page.locator(refresh).isHidden(), true); - assert.equal(reads(h, runA.id).length, beforeReads, 'reopening uses the latest saved observation'); - await closePlan(page); await select(h, runB.id); await openPlan(page); assert.equal(await json(page), textB); - assert.equal(edits(h, runA.id).length, 1); assert.equal(delivered(runA.id).length, 1); - }); - - await scenario('a lost accepted POST response confirms through SSE without recovery reads', async h => { - const { page } = h, run = await create(h); controls.get(run.id)!.mode = 'applied'; await openPlan(page); - await page.locator('[data-plan-objective]').fill('Persist before dropping the browser response'); await preview(page); - const original = await proposal(page), received = deferred(), release = deferred(); - h.effect = async route => { - if (route.request().method() !== 'POST' || new URL(route.request().url()).pathname !== `/api/runs/${run.id}/edits`) return false; - const response = await route.fetch(); assert.equal(response.status(), 200); received.resolve(); - await release.promise; await route.abort(); return true; - }; - try { - await page.locator('[data-plan-apply]').click(); await received.promise; assert.equal(delivered(run.id).length, 1); - await applied(page, original.id); - } - finally { release.resolve(); } - await page.locator(receipt).getByText(new RegExp(`回执 ${original.id} · 已应用`)).waitFor(); - await page.locator('[data-plan-objective]:enabled').waitFor(); - assert.equal(edits(h, run.id).length, 1, 'lost responses must never resend an edit automatically'); - assert.equal(reads(h, run.id).length, 0, 'a matching live receipt avoids reading again after the lost response'); - assert.equal(delivered(run.id).length, 1); - assert.equal(await page.locator(refresh).isHidden(), true); - }); - - await scenario('missing edit retries its exact original snapshot after GET and retains a newer draft', async h => { - const { page } = h, run = await create(h); await openPlan(page); - await page.locator('[data-plan-objective]').fill('Original snapshot before a request abort'); await preview(page); - const original = await proposal(page); let aborted = false; - h.effect = async route => { - if (aborted || route.request().method() !== 'POST' || new URL(route.request().url()).pathname !== `/api/runs/${run.id}/edits`) return false; - aborted = true; await route.abort(); return true; - }; - await page.locator('[data-plan-apply]').click(); await page.locator(`${retry}:enabled`).waitFor(); - assert.equal(delivered(run.id).length, 0, 'aborted POST must not reach the runner'); - assert.equal(reads(h, run.id).length, 1); - await page.locator('[data-plan-objective]').fill('Newer draft must not be sent by the retry control'); - await page.locator('[data-plan-type]').fill('True ∧ True'); - const newerText = await json(page); assert.notEqual((await proposal(page)).id, original.id); - assert.deepEqual(JSON.parse((await page.locator(`${receipt} pre`).textContent())!), original); - controls.get(run.id)!.mode = 'applied'; const before = h.calls.length; - await page.locator(retry).click(); await applied(page, original.id); - await page.locator('[data-plan-objective]:enabled').waitFor(); - const recovery = h.calls.slice(before).filter(call => call.pathname.includes('/commands/') || call.pathname.endsWith('/edits')); - assert.deepEqual(recovery.map(call => call.method), ['GET', 'POST'], 'explicit retry must check again before sending'); - const posts = edits(h, run.id); assert.equal(posts.length, 2); assert.equal(posts[1]!.body, posts[0]!.body, 'retry must send the exact original serialized body'); - assert.deepEqual(JSON.parse(posts[1]!.body!), original); - assert.equal(delivered(run.id).length, 1); assert.equal(await json(page), newerText); - }); - - for (const operation of ['preview', 'rebase', 'readLatest', 'apply'] as const) await scenario(`late run A ${operation} response cannot change run B`, async h => { - const { page } = h, runA = await create(h), runB = await create(h); - const readsPlan = operation === 'readLatest' || operation === 'rebase'; - controls.get(runA.id)!.mode = 'applied'; await select(h, runA.id); await openPlan(page); - await page.locator('[data-plan-objective]').fill(`Run A ${operation} proposal`); - if (operation === 'apply') await preview(page); - const originalA = await json(page), idA = (await proposal(page)).id; - const received = deferred(), release = deferred(), completed = deferred(); - const target = `/api/runs/${runA.id}/${readsPlan ? 'observation' : operation === 'preview' ? 'edits/preview' : 'edits'}`; - h.effect = async route => { - if (new URL(route.request().url()).pathname !== target || route.request().method() !== (readsPlan ? 'GET' : 'POST')) return false; - const response = await route.fetch(); assert.equal(response.status(), 200); received.resolve(); - await release.promise; await route.fulfill({ response }); completed.resolve(); return true; - }; - try { - await page.locator(operation === 'rebase' ? '[data-plan-rebase]' : operation === 'readLatest' ? '[data-plan-current]' : operation === 'preview' ? '[data-plan-preview]' : '[data-plan-apply]').click(); - await received.promise; assert.equal(await page.locator('[data-plan-objective]').isDisabled(), true); - if (readsPlan) { - const control = controls.get(runA.id)!; control.observation.plan!.baseVersion = 'run-A-newer-plan'; - control.observation.inspection.planVersion = 'run-A-newer-plan'; control.emit(); await poll(page); - await page.locator('[data-plan-versions]').getByText('run-A-newer-plan', { exact: true }).waitFor(); - } - await closePlan(page); await select(h, runB.id); await openPlan(page); - assert.equal(await page.locator('[data-plan-objective]').isDisabled(), false, 'another run must remain editable while A is pending'); - await page.locator('[data-plan-objective]').fill(`Run B local draft during ${operation}`); - const beforeB = await json(page); release.resolve(); await completed.promise; await settled(page); - assert.equal(await json(page), beforeB, 'late A response must not replace B full JSON'); - assert.equal(await page.locator('[data-plan-objective]').isDisabled(), false); - assert.equal(await page.locator(`${receipt} > :not([data-decision-summary])`).count(), 0, 'A receipt must not appear beside B’s own plan summary'); - assert.equal(await page.locator('[data-plan-comparison]').textContent(), '', 'A comparison must not appear in B'); - await page.locator('[data-plan-type]').fill('True ∧ True'); const editedB = await json(page); - await closePlan(page); await select(h, runA.id); await openPlan(page); - await page.locator('[data-plan-objective]:enabled').waitFor(); - if (operation === 'rebase') { - const rebased = await proposal(page), original = JSON.parse(originalA) as WebPlanProposal; - assert.equal(rebased.baseVersion, 'run-A-newer-plan', 'a late rebase must use the newest observation already saved for A'); - assert.notEqual(rebased.id, original.id); - assert.deepEqual({ ...rebased, id: original.id, baseVersion: original.baseVersion }, original, 'rebasing must retain A full local proposal'); - await page.locator(receipt).getByText(new RegExp(`回执 ${rebased.id} · 已校验`)).waitFor(); - assert.equal(await page.locator('[data-plan-apply]').isEnabled(), true, 'the rebased preview must be usable on return'); - } else assert.equal(await json(page), originalA, 'A must retain its own draft after completion'); - if (readsPlan) { - await page.locator('[data-plan-comparison]').getByText('当前服务器计划 · 本地草稿保留', { exact: true }).waitFor(); - await page.locator('[data-plan-versions]').getByText('run-A-newer-plan', { exact: true }).last().waitFor(); - const comparison = JSON.parse((await page.locator('[data-plan-comparison] pre').textContent())!); - assert.equal(comparison.baseVersion, 'run-A-newer-plan', 'a late read cannot rewind A saved server plan'); - } else { - await page.locator(receipt).getByText(new RegExp(`回执 ${idA} · ${operation === 'apply' ? '已应用' : '已校验'}`)).waitFor(); - if (operation === 'preview') assert.equal(await page.locator('[data-plan-apply]').isDisabled(), false); - } - await closePlan(page); await select(h, runB.id); await openPlan(page); assert.equal(await json(page), editedB); - } finally { release.resolve(); } - }); - - for (const width of [375, 320]) await scenario(`pending receipt and retry controls fit ${width}px`, async h => { - const { page } = h, run = await create(h); await openPlan(page); - await page.locator('[data-plan-objective]').fill('Review the original pending snapshot on a narrow screen'); await preview(page); - const original = await proposal(page); - h.effect = async route => { - if (route.request().method() !== 'POST' || new URL(route.request().url()).pathname !== `/api/runs/${run.id}/edits`) return false; - await route.abort(); return true; - }; - await page.locator('[data-plan-apply]').click(); await page.locator(`${retry}:enabled`).waitFor(); - await page.locator('[data-plan-objective]').fill('A newer local draft remains editable on mobile'); - await page.locator(receipt).getByText('待核对的原提交', { exact: true }).click(); - assert.deepEqual(JSON.parse((await page.locator(`${receipt} pre`).textContent())!), original); - await page.locator(receipt).scrollIntoViewIfNeeded(); - await fitViewport(page, '.collab-plan-dialog', 'pending editor must not widen the mobile document', true); - await fitViewport(page, '.collab-dialog-footer', 'pending footer must fit the mobile document', true); - for (const selector of [refresh, retry, '[data-plan-current]', '[data-plan-rebase]', '[data-plan-preview]', '[data-plan-apply]', '[data-plan-close]']) - await fitViewport(page, selector, `${selector} must remain reachable on mobile`, true); - assert.equal(await page.locator('.collab-plan-dialog').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true); - await page.screenshot({ path: path.join(output, `pending-${width}.png`) }); - assert.equal(edits(h, run.id).length, 1); assert.equal(delivered(run.id).length, 0); - }, width); - - await writeScenarioReport(path.join(output, 'report.json'), suite, 'passed', undefined, 'local-real-http-plan-recovery', - { checks: suite.checks, commands: commands.map(item => ({ runId: item.runId, type: item.command.type })), - screenshots: ['pending-375.png', 'pending-320.png'] }, { credential: input.apiKey }); - console.log('Plan recovery browser checks passed'); -} catch (error) { - await writeScenarioReport(path.join(output, 'report.json'), suite, 'failed', error, 'local-real-http-plan-recovery', - { checks: suite.checks }, { credential: input.apiKey, failureRequests: true }); throw error; -} finally { - for (const control of controls.values()) control.finish(); await browser.close(); await service.close(); -} diff --git a/scripts/test-web-problem-drafts.ts b/scripts/test-web-problem-drafts.ts index 916c34dc..a7a8fd2b 100644 --- a/scripts/test-web-problem-drafts.ts +++ b/scripts/test-web-problem-drafts.ts @@ -21,7 +21,7 @@ const writes: string[] = [], checks: string[] = [], contexts: BrowserContext[] = let prohibited = 0, phase = 'login', active: Page | undefined, failure: unknown; let release: unknown; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable problem draft fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable problem draft fixture' }; }, async run() { prohibited++; throw new Error('Drafts must not run research'); }, async formalize() { prohibited++; throw new Error('Keyboard submission is intercepted before any model call'); }, }; @@ -168,12 +168,16 @@ try { await page.locator('#source').fill(leanSource); await page.locator('#task').fill('保留这一份未完成证明与预算。'); await page.locator('#composer-settings').click(); await page.locator('#model').fill('lean-draft-model'); await page.locator('[data-settings-section="settings-execution"]').click(); - await page.locator('#max-turns').fill('7'); await page.locator('#max-seconds').fill('600'); await page.locator('#workers').fill('3'); + await page.locator('#max-turns').fill('7'); await page.locator('#max-seconds').fill('600'); + await page.locator('#research-mode').selectOption('native-team'); + await page.locator('#native-team-capacity').selectOption('5'); await closeSettings(page); const lean = await save(page, 'Lean 待完成版本'); assert.equal(lean.version.value.mode, 'lean'); await chooseVersion(other, lean); await other.locator('body[data-entry=lean]').waitFor({ state: 'attached' }); assert.equal(await other.locator('#source').inputValue(), leanSource); assert.equal(await other.locator('#task').inputValue(), '保留这一份未完成证明与预算。'); assert.equal(await other.locator('#model').inputValue(), 'lean-draft-model'); assert.equal(await other.locator('#max-turns').inputValue(), '7'); - assert.equal(await other.locator('#max-seconds').inputValue(), '600'); assert.equal(await other.locator('#workers').inputValue(), '3'); + assert.equal(await other.locator('#max-seconds').inputValue(), '600'); + assert.equal(await other.locator('#research-mode').inputValue(), 'native-team'); + assert.equal(await other.locator('#native-team-capacity').inputValue(), '5'); assert.equal(await other.locator('#api-key').inputValue(), ''); await other.goto(`${origin}/?accountDraft=${lean.draft.id}&draftVersion=${lean.version.id}`); await openChatModelSettings(other); await enterLean(other); diff --git a/scripts/test-web-problem-lifecycle.ts b/scripts/test-web-problem-lifecycle.ts index 72a180dd..4c9716de 100644 --- a/scripts/test-web-problem-lifecycle.ts +++ b/scripts/test-web-problem-lifecycle.ts @@ -10,7 +10,7 @@ import type { WebRunner } from '../apps/web/runner'; import type { ResearchAccountDraftResult, ResearchAccountDraft } from '../apps/web/researchPersonalTypes'; import type { ProblemDraftValue } from '../apps/web/problemDraftTypes'; import { freePort, startBrowser } from './web-scenario'; -import { enterLean, closeSettings, openAdvancedChatSettings, openChatModelSettings } from './web-ui-controls'; +import { enterLean, closeSettings, openAdvancedChatSettings, openChatModelSettings, openChatParticipation } from './web-ui-controls'; import { webFormalizationEvidence, webFormalizationStatement } from '../tests/helpers/webFormalizationFixture'; const root=path.resolve(import.meta.dirname,'..'),output=process.env.THEOREMOS_TEST_OUTPUT ?? path.join(root,'out/product-continuity/research-lifecycle/entry'); @@ -19,7 +19,7 @@ const temporary=await fs.mkdtemp(path.join(os.tmpdir(),'theoremos-lifecycle-')); const port=await freePort(),origin=`http://127.0.0.1:${port}`; const mail:{to:string;text:string}[]=[],external:string[]=[],errors:string[]=[],checks:object[]=[],contexts:BrowserContext[]=[]; let formalizations=0,runs=0,phase='initial',failure:unknown,active:Page|undefined; -const runner:WebRunner={async readiness(){return {ready:true,message:'Disposable lifecycle fixture'};},async formalize(input,send){formalizations++;send({type:'result',status:'approved',evidence:webFormalizationEvidence(input)});},async run(_input,send){runs++;send({type:'error',message:'Recorded lifecycle fixture; no proof execution.'});}}; +const runner:WebRunner={async readiness(){return {ready:true,nativeTeam:true,message:'Disposable lifecycle fixture'};},async formalize(input,send){formalizations++;send({type:'result',status:'approved',evidence:webFormalizationEvidence(input)});},async run(_input,send){runs++;send({type:'error',message:'Recorded lifecycle fixture; no proof execution.'});}}; const emails=['lifecycle-zh@example.org','lifecycle-en@example.org']; const service=createWebService(readWebConfig({THEOREMOS_WEB_PORT:String(port),THEOREMOS_WEB_PUBLIC_URL:origin,THEOREMOS_WEB_STATIC_ROOT:path.join(root,'out/web'),THEOREMOS_WEB_DATA_ROOT:temporary,THEOREMOS_WEB_AUTH:'email',THEOREMOS_WEB_SMTP_URL:'log:',THEOREMOS_WEB_ALLOWLIST:emails.join(','),THEOREMOS_WEB_PROVIDERS:JSON.stringify([{id:'fixture',name:'Local fixture',baseUrl:'https://fixture.invalid/v1'}])}),runner,{sample:null,mailer:async message=>{mail.push(message);},captchaAnswer:()=> '24680'}); const browser=await startBrowser(service.server,port); @@ -64,6 +64,8 @@ try{ await showArchived.check();const history=panel(page).locator(`[data-problem-draft="${first.draft.id}"]`);await history.waitFor();if(await history.getAttribute('open')!=='')await history.locator(':scope > summary').click();const row=history.locator(`[data-problem-draft-version="${first.version.id}"]`);assert.match(await row.innerText(),/已丢弃|Discarded/); await row.locator('[data-restore-problem-draft]').click();await page.waitForFunction(text=>(document.querySelector('#formalize-original') as HTMLTextAreaElement)?.value===text,webFormalizationStatement); phase=`submit-exact-version-${language}`; + await openChatParticipation(page); await page.locator('input[name="chat-participation"][value="guided"]').check(); + await page.locator('#formalize-settings > summary').click(); await page.locator('#formalize-settings > summary').click();await page.locator('#formalize-key').fill('sk-disposable-lifecycle');await page.locator('#formalize-settings > summary').click(); let loseFormalizationReply=true; const unknownPattern='**/api/formalizations'; @@ -87,7 +89,7 @@ try{ const leanSource='theorem lifecycle_target (n : Nat) : n + 0 = n := by\n sorry\n'; await page.locator('#source').fill(leanSource);await page.locator('#task').fill('Initial Lean instructions'); await page.locator('#composer-settings').click();await page.locator('#model').fill('fixture-lean');await page.locator('#api-key').fill('sk-disposable-lifecycle'); - await page.locator('[data-settings-section="settings-execution"]').click();await page.locator('#max-turns').fill('4');await page.locator('#max-seconds').fill('120');await page.locator('#workers').fill('1');await closeSettings(page); + await page.locator('[data-settings-section="settings-execution"]').click();await page.locator('#max-turns').fill('4');await page.locator('#max-seconds').fill('120');await closeSettings(page); const lean=await save(page,'Lean original');assert.equal(lean.version.value.mode,'lean'); const parallel=await page.evaluate(async saved=>{const session=await(await fetch('/api/session')).json();const value=saved.version.value as Extract; const reply=await fetch('/api/research/personal/drafts',{method:'POST',headers:{'content-type':'application/json','x-csrf-token':session.csrfToken},body:JSON.stringify({requestId:crypto.randomUUID(),expectedRevision:saved.version.revision,scope:{kind:'problem',draftKey:saved.draft.scope.draftKey},value:{...value,draft:{...value.draft,task:'Parallel device instructions'}},summary:'Parallel Lean original',deviceId:'another-device',deviceName:'Another device',clientUpdatedAt:new Date().toISOString()})});if(!reply.ok)throw new Error(await reply.text());return(await reply.json()).item;},lean); diff --git a/scripts/test-web-proof-thinking.ts b/scripts/test-web-proof-thinking.ts index f7ea6021..73e4b8bc 100644 --- a/scripts/test-web-proof-thinking.ts +++ b/scripts/test-web-proof-thinking.ts @@ -961,8 +961,21 @@ try { await composer.fill(''); await settled(page); await openWithoutComposerFocus(conversation.id); await thinking.waitFor(); await expectDraftPosition(quotedDraftPosition, 'independent positions after cleaning the other draft', false); - await page.reload({ timeout: 0 }); - await contains(copy.expanded.split('\n')[1]!); await goalPlan.waitFor(); await settled(page); + const composerFont = '**/assets/fonts/Geist-latin.woff2'; + let releaseFont: (() => void) | undefined; + if (scenario === 'zh-390') { + // Force the layout change that can occur when a long draft is restored before its font loads. + const fontHeld = new Promise(resolve => { releaseFont = resolve; }); + await page.route(composerFont, async route => { await fontHeld; await route.fallback(); }); + } + try { + await page.reload({ timeout: 0, waitUntil: 'domcontentloaded' }); + await contains(copy.expanded.split('\n')[1]!); await goalPlan.waitFor(); await settled(page); + } finally { + releaseFont?.(); + } + await page.evaluate(() => document.fonts.ready.then(() => undefined)); + if (releaseFont) await page.unroute(composerFont); assert.equal(await composer.inputValue(), workDraft, 'Refreshing restores the editable quoted draft'); await expectQuoteCount(2); await expectDraftPosition(quotedDraftPosition, 'refresh restores the quoted draft editing position', false); diff --git a/scripts/test-web-research-completion.ts b/scripts/test-web-research-completion.ts index ac490113..71860bdc 100644 --- a/scripts/test-web-research-completion.ts +++ b/scripts/test-web-research-completion.ts @@ -17,7 +17,7 @@ const root = path.resolve(import.meta.dirname, '..'), output = process.env.THEOR const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-research-completion-')), port = await freePort(), origin = `http://127.0.0.1:${port}`; await fs.mkdir(output, { recursive: true }); let workers = 0, prohibited = 0; -const runner: WebRunner = { async readiness() { return { ready: true, message: 'Disposable fixture: /private/path sk-do-not-expose' }; }, +const runner: WebRunner = { async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable fixture: /private/path sk-do-not-expose' }; }, async run(input, send) { workers++; const run = readingRun(input.id); run.observation!.inspection.configuration.environmentDigest = readingEnvironment; for (const check of run.observation!.checks) check.record = { passed: true }; send({ type: 'observation', observation: run.observation! }); send({ type: 'result', result: run.result! }); }, diff --git a/scripts/test-web-research-decisions-lifecycle.ts b/scripts/test-web-research-decisions-lifecycle.ts index a65f03c9..c528ec8f 100644 --- a/scripts/test-web-research-decisions-lifecycle.ts +++ b/scripts/test-web-research-decisions-lifecycle.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Disposable HTTP/Chromium state and a controlled runner. No models, Lean or mail. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -87,7 +88,7 @@ try { await http(page, 'PUT', '/api/research/profile', { requestId: crypto.randomUUID(), expectedRevision: 0, displayName: 'Solo Researcher', visibility: 'public' }); await http(peer, 'PUT', '/api/research/profile', { requestId: crypto.randomUUID(), expectedRevision: 0, displayName: 'Private Teammate', visibility: 'private' }); const peerId = service.research.projects.identity(peerOwner); - const { run } = await http<{ run: { id: string } }>(page, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-audit-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); + const run = await seedCooperativeRun(service, page.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-audit-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); await waitForRun({page},run.id,item=>Boolean(item.observation)); phase = `personal-guidance-unknown-${language}-${width}`; diff --git a/scripts/test-web-research-library-trials.ts b/scripts/test-web-research-library-trials.ts index ddd79c8a..6cc3998c 100644 --- a/scripts/test-web-research-library-trials.ts +++ b/scripts/test-web-research-library-trials.ts @@ -29,7 +29,7 @@ const workerInputs: Parameters[0][] = []; let compiler: (value: Parameters[0]) => Promise = async value => ({ output: '', exitCode: 0, timedOut: false, checkedTarget: value.candidateTarget?.name }); const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable trial fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable trial fixture' }; }, async run(value, send) { workerCalls++; workerInputs.push(structuredClone(value)); const observed = structuredClone(loadWebSample()!.observations.at(-1)!); diff --git a/scripts/test-web-review-regressions.ts b/scripts/test-web-review-regressions.ts index 2a868f6b..bb209d37 100644 --- a/scripts/test-web-review-regressions.ts +++ b/scripts/test-web-review-regressions.ts @@ -39,7 +39,7 @@ async function harness(concurrency: number, queueLimit = 8, formalizationFixture const workerStarts: string[] = []; const compiles = new Map void }>(); const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Local review fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Local review fixture' }; }, async run(value, send, signal) { workerStarts.push(value.id); await new Promise((resolve, reject) => { diff --git a/scripts/test-web-round10-collaboration.ts b/scripts/test-web-round10-collaboration.ts deleted file mode 100644 index d3320120..00000000 --- a/scripts/test-web-round10-collaboration.ts +++ /dev/null @@ -1,178 +0,0 @@ -#!/usr/bin/env bun -// Real project grants and Chromium; disposable state and controlled previews, without mathematical acceptance. -import assert from 'node:assert/strict'; -import fs from 'node:fs/promises'; -import os from 'node:os'; -import path from 'node:path'; -import type { Page } from 'playwright'; -import { readWebConfig } from '../apps/web/config'; -import { createWebService } from '../apps/web/server'; -import type { WebRunner } from '../apps/web/runner'; -import type { WebObservation } from '../apps/web/collaboration'; -import type { ResearchProjectDetail } from '../apps/web/researchProjectTypes'; -import { freePort, startBrowser, preferFullCollaboration, settled } from './web-scenario'; -import { mathDigest } from '../src/math/mathRuntimeIo'; - -const root = path.resolve(import.meta.dirname, '..'); -const output = process.env.THEOREMOS_TEST_OUTPUT ?? path.join(root, 'out/frontend-round10/collaboration'); -await fs.access(path.join(root, 'out/web/research.js')); await fs.mkdir(output, { recursive: true }); -const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-round10-collaboration-')); -const source = 'theorem plan_access_fixture : True := by sorry\n'; -const now = () => new Date().toISOString(), hash = (value: string) => mathDigest(value); -type Control = { finish(): void }; -const controls = new Map(), commands: string[] = [], writes: string[] = []; -const checks: object[] = [], errors: string[] = [], external: string[] = [], mail: unknown[] = []; -let phase = 'setup'; -function observation(id: string): WebObservation { - const tasks = [{ id: 'lemma', kind: 'lemma' as const, objective: '证明辅助事实', dependsOn: [], revision: 0, theoremName: 'supporting_fact', proofPath: 'Main.lean', type: 'True' }, - { id: 'goal', kind: 'goal' as const, objective: '从辅助事实推出原题', dependsOn: ['lemma'], revision: 0, theoremName: 'plan_access_fixture', proofPath: 'Main.lean', type: 'True' }]; - const snapshot = { schema: 'theoremos.run-observation.v1', runId: 'fixture-' + id, stateDigest: hash('initial'), resultDigest: null }; - return { schema: 'theorem-os.web-observation.v1', webRunId: id, solverRunId: snapshot.runId, observedAt: now(), sequence: 1, - evidence: 'recorded-not-replayed', acceptance: 'not-assessed', snapshot, - inspection: { schema: 'deepscientist.math.inspection.v1', runId: snapshot.runId, snapshot, evidence: 'recorded-not-replayed', phase: 'cooperative', - problem: { id: 'round10-plan-access-fixture', statement: 'Prove True', formalStatement: 'True', assumptions: [], targets: [{ theoremName: 'plan_access_fixture', proofPath: 'Main.lean' }] }, - configuration: { model: 'fixture', effort: 'low', workers: 2, coordination: 'cooperative', buildDigest: hash('build'), environmentDigest: hash('environment') }, turns: 1, planVersion: 'plan-v1', - scheduling: { evidence: 'recorded-dispatch-state', observedWorkers: 0, working: 0, proofAssignments: 0, preparing: 0, stopping: 0, idle: 0, stopped: 0 }, - knowledge: { status: 'disabled', evidence: 'recorded-not-replayed', attribution: 'model-reported-origin', retrievalCoverage: 'recorded', droppedRetrievals: 0, retrievals: [], originalUses: [], uses: [] }, - tokenBudget: {}, continuation: {}, mathematics: { snapshot: { schema: 'theorem-os.obligation.v1', evidence: 'recorded-not-replayed', acceptance: 'not-assessed', digest: hash('mathematics'), obligations: [], goals: [], blockers: [], routes: [], advisory: [] }, recentChanges: [], retainedChangeLimit: 64 }, - progress: { checkedProofTasks: 0, conditionalProofTasks: 0, completedResearchTasks: 0, openProofTasks: ['lemma', 'goal'] }, groups: [], - tasks: tasks.map(task => ({ id: task.id, kind: task.kind, objective: task.objective, group: 'main', status: 'pending', control: 'active', version: task.id + '-v1', theorem: task.theoremName, type: task.type, - premises: [], plannedDependencies: task.dependsOn, attempts: 0, proof: { status: 'none' }, parkedBy: [], parkedRoutes: {} })), - workers: [], statementReviews: [], edits: [] }, - plan: { schema: 'deepscientist.math.plan-edit.v1', baseVersion: 'plan-v1', tasks }, sources: [], checks: [], guidance: [], coverage: { sources: 'partial', checks: 'partial' } }; -} -const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable plan-access regression' }; }, - async check() { throw new Error('This regression cannot check or accept mathematical proofs'); }, - async run(input, send, signal) { - await new Promise(resolve => { - controls.set(input.id, { finish: resolve }); signal.addEventListener('abort', () => resolve(), { once: true }); - send({ type: 'observation', observation: observation(input.id) }); - }); - }, - async command(_runId, command) { - commands.push(command.type); - assert.equal(command.type, 'edit-preview', 'The regression must never apply a plan'); - if (command.type !== 'edit-preview') throw new Error('Unexpected command'); - return { id: command.proposal.id, status: 'validated', affectedTaskIds: ['lemma'], changes: [{ taskId: 'lemma', fields: ['objective'] }] }; - }, -}; -const port = await freePort(), origin = 'http://127.0.0.1:' + port; -const service = createWebService(readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin, - THEOREMOS_WEB_STATIC_ROOT: path.join(root, 'out/web'), THEOREMOS_WEB_DATA_ROOT: dataRoot, THEOREMOS_WEB_CONCURRENCY: '4' }), runner, -{ sample: null, mailer: async message => { mail.push(message); throw new Error('This regression cannot send mail'); } }); -const browser = await startBrowser(service.server, port); -const context = await browser.newContext({ locale: 'zh-CN', viewport: { width: 1440, height: 1000 }, reducedMotion: 'reduce' }); -const ownerContext = await browser.newContext({ locale: 'zh-CN', viewport: { width: 1440, height: 1000 }, reducedMotion: 'reduce' }); -for (const actor of [context, ownerContext]) { - await preferFullCollaboration(actor); - actor.on('page', page => { page.setDefaultTimeout(12000); page.on('pageerror', error => errors.push(error.message)); }); - await actor.route(/^https?:\/\//u, async route => { - if (new URL(route.request().url()).origin !== origin) { external.push(route.request().url()); await route.abort(); } else await route.continue(); - }); -} -const page = await context.newPage(), owner = await ownerContext.newPage(); -page.on('request', request => { - if (request.method() === 'POST' && /\/edits(?:\/preview)?$/u.test(new URL(request.url()).pathname)) writes.push(new URL(request.url()).pathname); -}); -async function http(actor: Page, method: string, pathname: string, input?: unknown): Promise { - return actor.evaluate(async ({ method, pathname, input }) => { - const session = await (await fetch('/api/session')).json(); - const response = await fetch(pathname, { method, headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': session.csrfToken }, - ...(input === undefined ? {} : { body: JSON.stringify(input) }) }); - const body = await response.json(); if (!response.ok) throw new Error('Fixture HTTP ' + response.status + ': ' + body.error); return body; - }, { method, pathname, input }) as Promise; -} -const reply = (method: string, pathname: string) => page.waitForResponse(response => response.request().method() === method && new URL(response.url()).pathname === pathname); -async function remainsBlocked(json: string, reason: string) { - await page.locator('[data-plan-availability]').getByText(reason, { exact: true }).waitFor(); - for (const name of ['preview', 'rebase', 'apply', 'retry']) assert.equal(await page.locator(`[data-plan-${name}]`).isDisabled(), true); - const before = writes.length; - for (const name of ['preview', 'rebase', 'apply']) await page.locator(`[data-plan-${name}]`).evaluate(node => node.dispatchEvent(new MouseEvent('click', { bubbles: true }))); - await settled(page); - assert.equal(writes.length, before, 'Unavailable controls and their handlers must send no plan POST'); - assert.equal(await page.locator('#collab-plan-json').inputValue(), json); - assert.equal(await page.locator('.collab-plan-dialog').evaluate((node: HTMLDialogElement) => node.open), true); -} -try { - await Promise.all([page.goto(origin + '/theorems.html'), owner.goto(origin + '/theorems.html')]); - await Promise.all([page.locator('main[aria-busy="false"]').waitFor(), owner.locator('main[aria-busy="false"]').waitFor()]); - let project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', '/api/research/theorems', { requestId: crypto.randomUUID(), title: '计划弹窗授权与连接恢复', description: '一次性本地回执,不进行数学验收', visibility: 'members' })).item; - const projectPath = '/api/research/theorems/' + project.id; - project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/versions', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statement: 'Prove True', source, environment: 'standard', confirmation: { confirmed: true } })).item; - const version = project.currentStatementVersionId!; - const peerId = (await http<{ researcherId: string }>(page, 'GET', '/api/research/session')).researcherId; assert.ok(peerId); - const ownerId = (await http<{ researcherId: string }>(owner, 'GET', '/api/research/session')).researcherId; assert.notEqual(peerId, ownerId); - project = (await http<{ item: ResearchProjectDetail }>(owner, 'PUT', projectPath + '/members/' + peerId, { requestId: crypto.randomUUID(), expectedRevision: project.revision, role: 'collaborator' })).item; - for (const width of [1440, 390]) { - phase = 'grant-change-' + width; - const run = (await http<{ run: { id: string } }>(owner, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-plan-access', model: 'fixture', effort: 'low', environment: 'standard', source, - task: '检查计划弹窗操作权限与恢复', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' })).run; - for (let attempt = 0; attempt < 100 && !controls.has(run.id); attempt++) await new Promise(resolve => setTimeout(resolve, 20)); - assert.ok(controls.has(run.id)); - const grants = async (edit: boolean) => { - project = (await http<{ item: ResearchProjectDetail }>(owner, 'GET', projectPath)).item; - return (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/runs', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: version, runId: run.id, - exposure: 'members', grants: { guidance: true, edit, approve: false, proof: false } })).item; - }; - const projected = (edit: boolean) => page.waitForResponse(async response => { - if (response.request().method() !== 'GET' || new URL(response.url()).pathname !== projectPath || response.status() !== 200) return false; - const body = await response.json(); return body.item.runs.find((item: { runId: string }) => item.runId === run.id)?.permissions.edit === edit; - }, { timeout: 20000 }); - await grants(true); - await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 }); - await page.goto(origin + '/theorems.html?id=' + project.id + '&version=' + version + '&run=' + run.id); - await page.locator('[data-collab-plan]:enabled').click(); await page.locator('.collab-plan-dialog[open]').waitFor(); - await page.locator('[data-plan-task]').selectOption('lemma'); - await page.locator('[data-plan-objective]').fill('保留完整本地草稿:说明辅助结论如何接到原题 ' + width); - const json = await page.locator('#collab-plan-json').inputValue(), editPath = projectPath + '/runs/' + run.id + '/edits'; - const preview = async () => { - const response = reply('POST', editPath + '/preview'); await page.locator('[data-plan-preview]').click(); assert.equal((await response).status(), 200); - await page.locator('[data-plan-apply]:enabled').waitFor(); - }; - await preview(); - const denied = projected(false); await grants(false); await denied; - const deniedReason = '当前没有此运行的计划编辑权限。草稿已保留。'; - await remainsBlocked(json, deniedReason); - assert.equal(await page.locator('[data-collab-plan]').isDisabled(), true); - const peerView = (await http<{ item: ResearchProjectDetail }>(page, 'GET', projectPath)).item; - assert.equal(peerView.permissions.edit, true); - assert.equal(peerView.runs.find(item => item.runId === run.id)!.permissions.read, true); - await page.locator('[data-plan-availability]').scrollIntoViewIfNeeded(); - await page.locator('.collab-plan-dialog').screenshot({ path: path.join(output, 'revoked-edit-preserved-' + width + '.png') }); - const restored = projected(true); await grants(true); await restored; - await page.waitForFunction(() => (document.querySelector('[data-plan-preview]') as HTMLButtonElement)?.disabled === false); - assert.equal(await page.locator('[data-plan-apply]').isDisabled(), true, 'A preview from before revocation must not be reused'); - assert.equal(await page.locator('#collab-plan-json').inputValue(), json); await preview(); - - phase = 'disconnection-and-recovery-' + width; - const observationPath = projectPath + '/runs/' + run.id + '/observation', observationUrl = origin + observationPath; - await page.route(observationUrl, route => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: '本地连接故障回归' }) })); - await remainsBlocked(json, '连接中断,暂时无法预览或提交计划。草稿已保留。'); - await page.locator('[data-plan-availability]').scrollIntoViewIfNeeded(); - await page.locator('.collab-plan-dialog').screenshot({ path: path.join(output, 'disconnected-preserved-' + width + '.png') }); - await page.unroute(observationUrl); const reconnected = reply('GET', observationPath); assert.equal((await reconnected).status(), 200); - await page.waitForFunction(() => (document.querySelector('[data-plan-preview]') as HTMLButtonElement)?.disabled === false); - assert.equal(await page.locator('[data-plan-apply]').isDisabled(), true); await preview(); - - phase = 'ended-run-preserves-draft-' + width; - await http(owner, 'POST', '/api/runs/' + run.id + '/cancel'); - await remainsBlocked(json, '运行已结束,无法再修改计划。草稿已保留。'); - await page.locator('[data-plan-availability]').scrollIntoViewIfNeeded(); - await page.locator('.collab-plan-dialog').screenshot({ path: path.join(output, 'ended-run-preserved-' + width + '.png') }); - await page.locator('[data-plan-close]').click(); - checks.push({ width, initialPreview: 200, revokedControlsDisabled: true, revokedPosts: 0, completeDraftRetained: true, - restoredPreview: 200, disconnectedControlsDisabled: true, disconnectedPosts: 0, reconnectedPreview: 200, endedControlsDisabled: true, endedPosts: 0 }); - } - assert.deepEqual(errors, []); assert.deepEqual(external, []); assert.deepEqual(mail, []); - assert.equal(writes.length, 6); assert.deepEqual(commands, Array(6).fill('edit-preview')); - await fs.writeFile(path.join(output, 'report.json'), JSON.stringify({ status: 'passed', checks, errors, external, planPosts: writes, controlledCommands: commands, - realModels: 0, realLean: 0, externalMail: 0, productionTouched: false, mathematicalAcceptance: 'not-assessed' }, null, 2) + '\n'); - console.log(JSON.stringify({ status: 'passed', scenarios: checks.length, output })); -} catch (error) { - await page.screenshot({ path: path.join(output, 'failure.png'), fullPage: true }).catch(() => {}); - await fs.writeFile(path.join(output, 'failure.json'), JSON.stringify({ phase, error: String(error), checks, writes, commands, errors, external }, null, 2) + '\n'); throw error; -} finally { - for (const control of controls.values()) control.finish(); - await context.close(); await ownerContext.close(); await browser.close(); await service.close(); await fs.rm(dataRoot, { recursive: true, force: true }); -} diff --git a/scripts/test-web-round10-workbench.ts b/scripts/test-web-round10-workbench.ts index a1da159f..5410f13e 100644 --- a/scripts/test-web-round10-workbench.ts +++ b/scripts/test-web-round10-workbench.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Real loopback HTTP and disposable records; the runner and discussion provider are controlled fixtures. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -99,13 +100,12 @@ async function http(page: Page, method: string, pathname: string, input?: unknow }, { method, pathname, input }); } async function task(page: Page, ctx: BrowserContext): Promise { - const run = (await http(page, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'local', apiKey: credential, model: 'fixture', effort: 'low', - environment: 'standard', source: 'theorem workbench_goal : True := by sorry\n', task: 'Round10 workbench recovery', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' })).run; + const run = await seedCooperativeRun(service, ctx, origin, { providerId: 'local', apiKey: credential, model: 'fixture', effort: 'low', + environment: 'standard', source: 'theorem workbench_goal : True := by sorry\n', task: 'Round10 workbench recovery', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); await page.waitForFunction(async id => !!(await (await fetch(`/api/runs/${id}`)).json()).run.observation, run.id); const conversation = (await http(page, 'POST', '/api/conversations', { runId: run.id })).conversation; const owner = (await ctx.cookies(origin)).find(cookie => cookie.name === 'theoremos_session')!.value; await page.goto(`${origin}/?chat=${conversation.id}`); await page.locator(`[data-conversation="${conversation.id}"]`).waitFor(); - await page.locator('[data-chat-guidance-mode-open]').waitFor(); return { runId: run.id, id: conversation.id, pathname: `/api/conversations/${conversation.id}`, owner }; } async function settings(page: Page) { @@ -137,54 +137,7 @@ const mark = (details: object) => { checks.push({ phase, ...details }); console. try { browser = await startBrowser(service.server, port); for (const [width, locale] of [[1440, 'zh'], [390, 'en']] as const) { - phase = `guidance/${locale}/${width}`; const { ctx, page } = await open(width, locale); - let c: Task | undefined; - try { - c = await task(page, ctx); const original = 'Unsent guidance: prove the helper before the main target.'; - await page.locator('[data-chat-guidance-mode-open]').click(); await page.locator('[data-chat-guidance-target]').selectOption('goal'); - await page.locator('#formalize-original').fill(original); - assert.deepEqual((await draft(page, c)).guidanceDraft, - { text: original, active: true, runId: c.runId, taskRef: { id: 'goal', version: 'goal-v1' } }); - await page.locator('#topbar-draft').click(); await page.waitForURL(origin + '/'); - await page.goBack(); await page.locator(`[data-conversation="${c.id}"]`).waitFor(); - await page.locator('[data-chat-guidance-mode-open][aria-pressed="true"]').waitFor(); - assert.equal(await page.locator('[data-chat-guidance-target]').inputValue(), 'goal'); - assert.equal(await page.locator('#formalize-original').inputValue(), original); - await page.reload(); await page.locator('[data-chat-guidance-mode-open][aria-pressed="true"]').waitFor(); - assert.equal(await page.locator('[data-chat-guidance-target]').inputValue(), 'goal'); - assert.deepEqual((await draft(page, c)).guidanceDraft?.taskRef, { id: 'goal', version: 'goal-v1' }); - const control = controls.get(c.runId)!; control.observation.inspection.tasks[0]!.version = 'goal-v2'; control.emit(); - await page.reload(); await page.locator('[data-chat-guidance-mode-open][aria-pressed="true"]').waitFor(); - const confirm = page.locator('[data-chat-guidance-mode] button:not([data-chat-guidance-cancel])'); await confirm.waitFor(); - assert.equal(await page.locator('#formalize-start').isDisabled(), true); - assert.deepEqual((await draft(page, c)).guidanceDraft?.taskRef, { id: 'goal', version: 'goal-v1' }, 'refresh never silently rebinds the observed task'); - await page.screenshot({ path: path.join(output, `guidance-stale-${locale}-${width}.png`) }); - await confirm.click(); assert.equal(await page.locator('#formalize-start').isEnabled(), true); - assert.deepEqual((await draft(page, c)).guidanceDraft?.taskRef, { id: 'goal', version: 'goal-v2' }); - const commandBefore = commands.length, providerBefore = providerCalls.length; - if (width > 850) await page.locator('#formalize-original').press('Enter'); else await page.locator('#formalize-start').click(); - await page.locator('[data-chat-guidance-receipt][data-guidance-status="delivered"]').waitFor(); - assert.equal(commands.length, commandBefore + 1); assert.equal(providerCalls.length, providerBefore); - assert.deepEqual((commands.at(-1) as any).input.taskRef, { id: 'goal', version: 'goal-v2' }); - const leadGuidance = 'Guidance to the lead survives refresh.'; - await page.locator('[data-chat-guidance-mode-open]').click(); await page.locator('#formalize-original').fill(leadGuidance); - await page.reload(); await page.locator('[data-chat-guidance-mode-open][aria-pressed="true"]').waitFor(); - assert.equal(await page.locator('[data-chat-guidance-target]').inputValue(), ''); - await page.locator('[data-chat-guidance-cancel]').click(); await page.reload(); - await page.locator('[data-chat-discussion-mode][aria-pressed="true"]').waitFor(); - assert.equal(await page.locator('[data-chat-guidance-target]').count(), 0); - assert.equal(await page.locator('#formalize-original').inputValue(), ''); - assert.deepEqual((await draft(page, c)).guidanceDraft, { text: leadGuidance, active: false, runId: c.runId }); - await page.locator('[data-chat-guidance-mode-open]').click(); - assert.equal(await page.locator('#formalize-original').inputValue(), leadGuidance); - await privacy(page); mark({ restoredAfterBackAndRefresh: true, restoredTaskVersion: 'goal-v1', explicitConfirmedVersion: 'goal-v2', - guidanceCommands: 1, discussionCalls: 0, leadModeRestored: true, explicitDiscussionPersists: true }); - } finally { if (c) controls.get(c.runId)?.finish(); await ctx.close(); } - } - - // The workspace lists the plan next to the conversation; a task there addresses guidance to itself in the composer. - for (const [width, locale] of [[1440, 'zh'], [390, 'en']] as const) { - phase = `workspace-guidance/${locale}/${width}`; const { ctx, page } = await open(width, locale); + phase = `workspace-task-status/${locale}/${width}`; const { ctx, page } = await open(width, locale); let c: Task | undefined; try { c = await task(page, ctx); const live = page.locator('#chat-live-panel'); @@ -198,9 +151,7 @@ try { assert.equal(await row.getAttribute('data-tone'), 'pending'); assert.equal(await live.locator('[data-live-done]').innerText(), locale === 'zh' ? '已完成 0/1' : '0 of 1 done'); assert.equal(await live.locator('[data-live-failed]').count(), 0); - // Guidance while the proof runs has one entry, the composer's 指导 Agent; the status line no longer repeats it. assert.equal(await page.locator('#research-chat-thread [data-research-guidance]').count(), 0); - assert.equal(await page.locator('[data-chat-guidance-mode-open]').count(), 1); await row.locator('.live-task-head').click(); const control = controls.get(c.runId)!; const recordedTask = control.observation.inspection.tasks[0]!; @@ -212,19 +163,7 @@ try { await page.waitForFunction(() => document.querySelector('[data-live-task="goal"]')?.getAttribute('data-tone') === 'active'); assert.equal(await row.locator('.live-task-head').getAttribute('aria-expanded'), 'false', 'A retry preserves the reader’s explicit collapse'); await row.locator('.live-task-head').click(); - await row.locator('[data-live-guide="goal"]').click(); - await page.locator('[data-chat-guidance-mode-open][aria-pressed="true"]').waitFor(); - assert.equal(await page.locator('[data-chat-guidance-target]').inputValue(), 'goal'); - assert.equal(await page.locator('#formalize-original').isVisible(), true, 'Guiding a task leaves the reader at the composer'); - assert.deepEqual((await draft(page, c)).guidanceDraft, - { text: '', active: true, runId: c.runId, taskRef: { id: 'goal', version: 'goal-v1' } }); - const text = 'Workspace guidance: settle the helper first.'; - const commandBefore = commands.length, providerBefore = providerCalls.length; - await page.locator('#formalize-original').fill(text); await page.locator('#formalize-start:enabled').click(); - await page.locator('[data-chat-guidance-receipt][data-guidance-status="delivered"]').waitFor(); - assert.equal(commands.length, commandBefore + 1); assert.equal(providerCalls.length, providerBefore, 'Guidance goes to the running research, not to a discussion model'); - assert.equal((commands.at(-1) as any).input.text, text); assert.deepEqual((commands.at(-1) as any).input.taskRef, { id: 'goal', version: 'goal-v1' }); - await privacy(page); mark({ guidedTask: 'goal', delivered: true }); + await privacy(page); mark({ task: 'goal', expansionRetained: true, collapseRetained: true }); } finally { if (c) controls.get(c.runId)?.finish(); await ctx.close(); } } diff --git a/scripts/test-web-round5-collaboration.ts b/scripts/test-web-round5-collaboration.ts index 144848c6..88e40688 100644 --- a/scripts/test-web-round5-collaboration.ts +++ b/scripts/test-web-round5-collaboration.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Statement draft preservation and historical human-claim release. Local disposable accounts and observations only. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -12,7 +13,7 @@ import type { WebRunner } from '../apps/web/runner'; import type { WebRunInput, WorkerMessage } from '../apps/web/shared'; import type { WebObservation, WebInspection } from '../apps/web/collaboration'; import type { ResearchProjectDetail } from '../apps/web/researchProjectTypes'; -import { freePort, postRun, preferFullCollaboration, startBrowser } from './web-scenario'; +import { freePort, preferFullCollaboration, startBrowser } from './web-scenario'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const output = process.env.THEOREMOS_TEST_OUTPUT ?? path.join(root, 'out/frontend-round5/collaboration'); @@ -154,7 +155,7 @@ try { checks.push({ name: 'An unchanged submitted draft still clears after a successful save', payload: unchangedReply.request().postDataJSON(), status: unchangedReply.status() }); phase = 'release-the-existing-claim-after-task-version-changes'; - const run = await postRun({ page }, runInput); assert.ok(controls.has(run.id)); + const run = await seedCooperativeRun(service, page.context(), origin, runInput); assert.ok(controls.has(run.id)); project = (await http<{ item: ResearchProjectDetail }>(page, 'GET', projectPath)).item; project = (await http<{ item: ResearchProjectDetail }>(page, 'POST', `${projectPath}/runs`, { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: version, runId: run.id, diff --git a/scripts/test-web-round5-workbench.ts b/scripts/test-web-round5-workbench.ts index ded2cbc1..64f35a24 100644 --- a/scripts/test-web-round5-workbench.ts +++ b/scripts/test-web-round5-workbench.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Real local HTTP and Chromium, with delayed responses and controlled observations; no model, Lean or mail. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import fs from 'node:fs/promises'; @@ -11,7 +12,7 @@ import { readWebConfig } from '../apps/web/config'; import type { WebRunner } from '../apps/web/runner'; import type { WebObservation, WebInspection } from '../apps/web/collaboration'; import type { WorkerMessage } from '../apps/web/shared'; -import { freePort, startBrowser, postRun, settled } from './web-scenario'; +import { freePort, startBrowser, settled } from './web-scenario'; import { openTab, refresh } from './web-ui-controls'; const root = path.resolve(import.meta.dirname, '..'); @@ -78,7 +79,7 @@ try { let control: Control | undefined; try { await page.goto(origin); await page.locator('#formalize-original').waitFor(); - const run = await postRun({ page }, { providerId: 'openai', apiKey: 'sk-disposable-round5-fixture', model: 'fixture', effort: 'low', environment: 'standard', + const run = await seedCooperativeRun(service, page.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-round5-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Observe plan state synchronization', maxTurns: 2, maxRunSeconds: 300, workers: 2, coordination: 'cooperative', planApproval: true }); await page.goto(origin + '/?run=' + run.id); await page.waitForURL(url => url.searchParams.has('chat')); diff --git a/scripts/test-web-round6-collaboration.ts b/scripts/test-web-round6-collaboration.ts index 948b701a..e56d49e6 100644 --- a/scripts/test-web-round6-collaboration.ts +++ b/scripts/test-web-round6-collaboration.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Real Chromium collaboration regression using disposable loopback data and controlled checks only. +import { seedCooperativeRun } from './web-cooperative-fixture'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -12,7 +13,7 @@ import type { WebRunner } from '../apps/web/runner'; import type { WebRunInput, WorkerMessage } from '../apps/web/shared'; import type { WebObservation, WebInspection } from '../apps/web/collaboration'; import type { ResearchCandidateReview, ResearchFeedback, ResearchProjectDetail } from '../apps/web/researchProjectTypes'; -import { freePort, postRun, preferFullCollaboration, startBrowser } from './web-scenario'; +import { freePort, preferFullCollaboration, startBrowser } from './web-scenario'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); @@ -182,7 +183,7 @@ try { savedVersion: v2, cardNavigation: true, timelineNavigation: true, projectWideDiscussion: true, draftRetained: true }); phase = 'submit-candidate-through-ui'; - const run = await postRun({ page: owner }, runInput); assert.ok(controls.has(run.id)); + const run = await seedCooperativeRun(service, owner.context(), origin, runInput); assert.ok(controls.has(run.id)); project = (await http<{ item: ResearchProjectDetail }>(owner, 'GET', route)).item; project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', route + '/runs', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: v1, runId: run.id, @@ -199,7 +200,7 @@ try { const candidateReply = await candidateResponse; assert.equal(candidateReply.status(), 201); const candidate: ResearchFeedback = (await candidateReply.json()).item; assert.equal(candidate.proofCheck?.status, 'checked'); assert.equal(candidate.decision.status, 'pending'); - assert.equal(checkerCalls, 1); assert.equal(guidanceCalls, 1); + assert.equal(checkerCalls, 1); assert.equal(guidanceCalls, 0); const visitorId = (await http<{ researcherId: string }>(visitor, 'GET', '/api/research/session')).researcherId; project = (await http<{ item: ResearchProjectDetail }>(owner, 'GET', route)).item; project = (await http<{ item: ResearchProjectDetail }>(owner, 'PUT', route + '/members/' + visitorId, @@ -240,7 +241,7 @@ try { await review.getByRole('button', { name: '提交基准', exact: true }).click(); await review.locator('[data-candidate-baseline]').waitFor(); assert.equal(await review.locator('[data-candidate-baseline]').textContent(), source); - assert.equal(checkerCalls, 1); assert.equal(guidanceCalls, 1); + assert.equal(checkerCalls, 1); assert.equal(guidanceCalls, 0); checks.push({ name: 'Reload after task/source advances preserves the historical baseline and check, without rerunning either', currentTaskVersion: 'goal-v2', frozenTaskVersion: originalReview.target.taskRef?.version }); phase = 'review-request-error-can-retry'; diff --git a/scripts/test-web-round8-approval.ts b/scripts/test-web-round8-approval.ts index 2bd47218..9d5743f6 100644 --- a/scripts/test-web-round8-approval.ts +++ b/scripts/test-web-round8-approval.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun // Real HTTP + Chromium, with disposable data and deterministic approval receipts. No mathematical acceptance. +import { webAgentTeamPreset } from '../apps/web/researchMode'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -25,9 +26,9 @@ let phase = 'setup'; function observation(id: string): WebObservation { const tasks = [{ id: 'goal', kind: 'goal' as const, objective: '核对原题再开始证明', dependsOn: [], revision: 0, theoremName: 'approval_fixture', proofPath: 'Main.lean', type: 'True' }]; const snapshot = { schema: 'theoremos.run-observation.v1', runId: 'fixture-' + id, stateDigest: mathDigest('initial'), resultDigest: null }; - const inspection: WebInspection = { schema: 'deepscientist.math.inspection.v1', runId: snapshot.runId, snapshot, evidence: 'recorded-not-replayed', phase: 'cooperative', + const inspection: WebInspection = { schema: 'deepscientist.math.inspection.v1', runId: snapshot.runId, snapshot, evidence: 'recorded-not-replayed', phase: 'research', problem: { id: 'round8-approval-fixture', statement: 'Prove True', formalStatement: 'True', assumptions: [], targets: [{ theoremName: 'approval_fixture', proofPath: 'Main.lean' }] }, - configuration: { model: 'fixture', effort: 'low', workers: 2, coordination: 'cooperative', buildDigest: mathDigest('build'), environmentDigest: mathDigest('environment') }, turns: 1, planVersion: 'plan-v1', + configuration: { model: 'fixture', effort: 'low', workers: 1, coordination: 'independent', buildDigest: mathDigest('build'), environmentDigest: mathDigest('environment') }, turns: 1, planVersion: 'plan-v1', scheduling: { evidence: 'recorded-dispatch-state', observedWorkers: 0, working: 0, proofAssignments: 0, preparing: 0, stopping: 0, idle: 0, stopped: 0 }, knowledge: { status: 'disabled', evidence: 'recorded-not-replayed', attribution: 'model-reported-origin', retrievalCoverage: 'recorded', droppedRetrievals: 0, retrievals: [], originalUses: [], uses: [] }, tokenBudget: {}, continuation: {}, mathematics: { snapshot: { schema: 'theorem-os.obligation.v1', evidence: 'recorded-not-replayed', acceptance: 'not-assessed', digest: mathDigest('mathematics'), obligations: [], goals: [], blockers: [], routes: [], advisory: [] }, recentChanges: [], retainedChangeLimit: 64 }, @@ -39,7 +40,7 @@ function observation(id: string): WebObservation { plan: { schema: 'deepscientist.math.plan-edit.v1', baseVersion: 'plan-v1', tasks }, sources: [], checks: [], guidance: [], coverage: { sources: 'partial', checks: 'partial' } }; } const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable project plan approval regression' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable project plan approval regression' }; }, async check() { throw new Error('Approval regressions must not check or accept proofs'); }, async run(input, send, signal) { await new Promise(resolve => { @@ -48,6 +49,9 @@ const runner: WebRunner = { this.observation.inspection.snapshot.stateDigest = this.observation.snapshot.stateDigest; send({ type: 'observation', observation: structuredClone(this.observation) }); } }; + Object.assign(control.observation.inspection.configuration, { researchMode: 'skill', + researchSkill: { name: 'theoremos-research', digest: mathDigest('fixture skill'), loading: 'native' }, + researchDelegation: { mode: 'team', maxAgents: input.input.nativeTeamCapacity } }); controls.set(input.id, control); signal.addEventListener('abort', () => resolve(), { once: true }); control.emit(); }); }, @@ -107,8 +111,9 @@ try { const version = project.currentStatementVersionId!, posts: any[] = []; page.on('request', request => { if (request.method() === 'POST' && new URL(request.url()).pathname === feedbackPath) posts.push(request.postDataJSON()); }); const create = async (task: string) => { - const run = (await http<{ run: { id: string } }>('POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-local-approval-fixture', model: 'fixture', effort: 'low', - environment: 'standard', source, task, maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative', planApproval: true })).run; + const { run } = await http<{ run: { id: string } }>('POST', '/api/runs', { providerId: 'openai', apiKey: 'sk-local-approval-fixture', + model: 'fixture', effort: 'low', environment: 'standard', source, task, maxTurns: 2, maxRunSeconds: 600, + ...webAgentTeamPreset(), planApproval: true }); for (let attempt = 0; attempt < 100 && !controls.has(run.id); attempt++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(controls.has(run.id)); project = (await http<{ item: ResearchProjectDetail }>('GET', projectPath)).item; await http('POST', projectPath + '/runs', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: version, runId: run.id, diff --git a/scripts/test-web-round8-budget.ts b/scripts/test-web-round8-budget.ts index bad1442d..2f1e2cd2 100644 --- a/scripts/test-web-round8-budget.ts +++ b/scripts/test-web-round8-budget.ts @@ -23,7 +23,7 @@ const credential = 'sk-disposable-round8-budget-fixture'; const checks: object[] = [], errors: string[] = [], external: string[] = []; const starts: Array<{ id: string; maxTotalTokens?: number }> = []; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable budget regression fixture' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable budget regression fixture' }; }, async run(input, send) { starts.push({ id: input.id, ...(input.input.maxTotalTokens !== undefined ? { maxTotalTokens: input.input.maxTotalTokens } : {}) }); send({ type: 'result', result: { status: 'incomplete', proof: '', report: { localBudgetFixture: true } } }); diff --git a/scripts/test-web-round8-keys.ts b/scripts/test-web-round8-keys.ts index 81da3605..b052b0f7 100644 --- a/scripts/test-web-round8-keys.ts +++ b/scripts/test-web-round8-keys.ts @@ -22,7 +22,7 @@ const runnerEndings: string[] = []; let formalizationCalls = 0, phase = 'setup', failure: unknown, active: Page | undefined; const releaseGates: (() => void)[] = []; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable key ordering regression; no model or Lean' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable key ordering regression; no model or Lean' }; }, async formalize() { formalizationCalls++; throw new Error('Key management must not formalize'); }, async run(input, send) { runnerEndings.push(input.input.apiKey.slice(-4)); diff --git a/scripts/test-web-round9-availability.ts b/scripts/test-web-round9-availability.ts index 034d88f3..2b0cf7a4 100644 --- a/scripts/test-web-round9-availability.ts +++ b/scripts/test-web-round9-availability.ts @@ -20,23 +20,25 @@ const original = '保留这份原题:对任意自然数 n,证明 n + 0 = n const texts = { zh: { runtime: '当前服务暂不支持自然语言解题,可切换到 Lean 输入。', + 'old-worker': '当前运行镜像未安装原生团队后端。', provider: '当前服务未配置自然语言解题的模型,请联系管理员;也可切换到 Lean 输入。', offline: '运行环境暂未就绪,原题会保留;恢复后可继续发送。', }, en: { runtime: 'This service does not currently support solving natural-language problems. You can switch to Lean input.', + 'old-worker': 'The worker image does not include the native team backend.', provider: 'No model service is configured for natural-language problems. Contact the administrator, or switch to Lean input.', offline: 'The runtime is not ready. Your problem is kept; you can send it when the runtime recovers.', }, }; let phase = 'setup', failure: unknown, runnerCalls = 0; try { - for (const kind of ['runtime', 'provider', 'offline'] as const) { + for (const kind of ['runtime', 'old-worker', 'provider', 'offline'] as const) { const data = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-round9-availability-')); const port = await freePort(), origin = `http://127.0.0.1:${port}`; let runtimeReady = kind !== 'offline'; const runner: WebRunner = { - async readiness() { return { ready: runtimeReady, message: runtimeReady ? 'Ready' : 'Fixture runtime unavailable' }; }, + async readiness() { return { ready: runtimeReady, nativeTeam: runtimeReady && kind !== 'old-worker', message: runtimeReady ? 'Ready' : 'Fixture runtime unavailable' }; }, async run() { runnerCalls++; throw new Error('Availability checks must not start a run'); }, ...(kind === 'runtime' ? {} : { async formalize() { runnerCalls++; throw new Error('Availability checks must not formalize'); } }), }; @@ -68,7 +70,9 @@ try { try { const response = page.waitForResponse(response => new URL(response.url()).pathname === '/api/formalizations'); await page.goto(origin); const capabilities = (await (await response).json()).generation; - assert.equal(capabilities.available, false); assert.equal(capabilities.reason, kind === 'provider' ? 'provider' : 'runtime'); + assert.equal(capabilities.available, kind === 'old-worker'); + assert.equal(capabilities.solveAvailable, false); + assert.equal(capabilities.reason, kind === 'old-worker' ? undefined : kind === 'provider' ? 'provider' : 'runtime'); await page.locator('#formalize-original').fill(original); await clickWorkbenchAction(page, '#open-settings'); if (kind !== 'provider') await page.locator('#formalize-key').fill('sk-disposable-availability'); @@ -86,7 +90,7 @@ try { await page.locator('#open-natural-language').click(); await page.locator('#formalize-original').waitFor(); assert.equal(await page.locator('#formalize-original').inputValue(), original, 'The original survives checking the Lean alternative'); - } else { + } else if (kind === 'offline') { runtimeReady = true; // A visibility refresh respects the workbench's list refresh interval. await page.clock.fastForward(6_001); @@ -98,9 +102,11 @@ try { assert.equal(await page.locator('#formalize-original').inputValue(), original); runtimeReady = false; } + assert.equal(await page.locator('#formalize-original').inputValue(), original); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)); checks.push({ name: phase, status: 'passed', capabilityReason: capabilities.reason, actionableBlocker: true, - draftPreserved: true, ...(kind === 'offline' ? { recoveredWithoutReload: true } : { leanFallbackAvailable: true }) }); + draftPreserved: true, ...(kind === 'offline' ? { recoveredWithoutReload: true } + : kind !== 'old-worker' ? { leanFallbackAvailable: true } : {}) }); console.log(`PASS ${phase}`); } finally { await context.close(); } } diff --git a/scripts/test-web-round9-collaboration.ts b/scripts/test-web-round9-collaboration.ts deleted file mode 100644 index 1a69be06..00000000 --- a/scripts/test-web-round9-collaboration.ts +++ /dev/null @@ -1,139 +0,0 @@ -#!/usr/bin/env bun -// Real HTTP and Chromium with disposable state; controlled guidance receipts never imply proof acceptance. -import assert from 'node:assert/strict'; -import fs from 'node:fs/promises'; -import os from 'node:os'; -import path from 'node:path'; -import { readWebConfig } from '../apps/web/config'; -import { createWebService } from '../apps/web/server'; -import type { WebRunner } from '../apps/web/runner'; -import type { WebObservation } from '../apps/web/collaboration'; -import type { ResearchProjectDetail } from '../apps/web/researchProjectTypes'; -import { freePort, preferFullCollaboration, settled, startBrowser } from './web-scenario'; -import { mathDigest } from '../src/math/mathRuntimeIo'; - -const root = path.resolve(import.meta.dirname, '..'); -const output = process.env.THEOREMOS_TEST_OUTPUT ?? path.join(root, 'out/frontend-round9/collaboration'); -await fs.access(path.join(root, 'out/web/research.js')); await fs.mkdir(output, { recursive: true }); -const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-round9-collaboration-')); -const source = 'theorem guidance_fixture : True := by sorry\n', now = () => new Date().toISOString(); -type Control = { observation: WebObservation; emit(): void; finish(): void }; -const controls = new Map(), commands: { runId: string; taskId?: string; taskVersion?: string }[] = []; -const checks: object[] = [], errors: string[] = [], external: string[] = [], mail: unknown[] = []; -let phase = 'setup'; -function observation(id: string): WebObservation { - const snapshot = { schema: 'theoremos.run-observation.v1', runId: 'fixture-' + id, stateDigest: mathDigest('initial'), resultDigest: null }; - const task = { id: 'goal', kind: 'goal' as const, objective: '当前任务:使用新增假设证明结论', group: 'main', status: 'pending', control: 'active', - version: 'goal-v2', theorem: 'guidance_fixture', type: 'True', premises: [], plannedDependencies: [], attempts: 0, proof: { status: 'none' }, parkedBy: [], parkedRoutes: {} }; - return { schema: 'theorem-os.web-observation.v1', webRunId: id, solverRunId: snapshot.runId, observedAt: now(), sequence: 1, evidence: 'recorded-not-replayed', acceptance: 'not-assessed', snapshot, - inspection: { schema: 'deepscientist.math.inspection.v1', runId: snapshot.runId, snapshot, evidence: 'recorded-not-replayed', phase: 'cooperative', - problem: { id: 'round9-guidance-fixture', statement: 'Prove True', formalStatement: 'True', assumptions: [], targets: [{ theoremName: 'guidance_fixture', proofPath: 'Main.lean' }] }, - configuration: { model: 'fixture', effort: 'low', workers: 2, coordination: 'cooperative', buildDigest: mathDigest('build'), environmentDigest: mathDigest('environment') }, turns: 1, planVersion: 'plan-v2', - scheduling: { evidence: 'recorded-dispatch-state', observedWorkers: 0, working: 0, proofAssignments: 0, preparing: 0, stopping: 0, idle: 0, stopped: 0 }, - knowledge: { status: 'disabled', evidence: 'recorded-not-replayed', attribution: 'model-reported-origin', retrievalCoverage: 'recorded', droppedRetrievals: 0, retrievals: [], originalUses: [], uses: [] }, - tokenBudget: {}, continuation: {}, mathematics: { snapshot: { schema: 'theorem-os.obligation.v1', evidence: 'recorded-not-replayed', acceptance: 'not-assessed', digest: mathDigest('mathematics'), obligations: [], goals: [], blockers: [], routes: [], advisory: [] }, recentChanges: [], retainedChangeLimit: 64 }, - progress: { checkedProofTasks: 0, conditionalProofTasks: 0, completedResearchTasks: 0, openProofTasks: ['goal'] }, groups: [], tasks: [task], workers: [], statementReviews: [], edits: [] }, - plan: { schema: 'deepscientist.math.plan-edit.v1', baseVersion: 'plan-v2', tasks: [{ id: 'goal', kind: 'goal', objective: task.objective, dependsOn: [], revision: 1, theoremName: 'guidance_fixture', proofPath: 'Main.lean', type: 'True' }] }, - history: [{ ...structuredClone(task), version: 'goal-v1', objective: '历史任务:核对第一步的假设' }], sources: [], checks: [], guidance: [], coverage: { sources: 'partial', checks: 'partial' } }; -} -const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable historical guidance regression' }; }, - async check() { throw new Error('Guidance regressions must not check mathematical proofs'); }, - async run(input, send, signal) { - await new Promise(resolve => { - const control: Control = { observation: observation(input.id), finish: resolve, emit() { - this.observation.sequence++; this.observation.observedAt = now(); this.observation.snapshot.stateDigest = mathDigest('state-' + this.observation.sequence); - this.observation.inspection.snapshot.stateDigest = this.observation.snapshot.stateDigest; - send({ type: 'observation', observation: structuredClone(this.observation) }); - } }; - controls.set(input.id, control); signal.addEventListener('abort', () => resolve(), { once: true }); control.emit(); - }); - }, - async command(runId, command) { - const control = controls.get(runId)!; - if (command.type === 'capture') return { id: 'capture', status: 'captured', observation: structuredClone(control.observation) }; - if (command.type !== 'guidance') throw new Error('Unexpected command: ' + command.type); - commands.push({ runId, taskId: command.guidance.taskRef?.id, taskVersion: command.guidance.taskRef?.version }); - const guidance = { ...command.guidance, status: 'delivered' as const, deliveredTo: ['fixture-lead'], createdAt: now(), updatedAt: now() }; - control.observation.guidance.push(guidance); control.emit(); - return { id: guidance.id, status: 'delivered', guidance, observation: structuredClone(control.observation) }; - }, -}; -const port = await freePort(), origin = 'http://127.0.0.1:' + port; -const service = createWebService(readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin, - THEOREMOS_WEB_STATIC_ROOT: path.join(root, 'out/web'), THEOREMOS_WEB_DATA_ROOT: dataRoot, THEOREMOS_WEB_CONCURRENCY: '4' }), runner, -{ sample: null, mailer: async message => { mail.push(message); throw new Error('Guidance regressions cannot send mail'); } }); -const browser = await startBrowser(service.server, port), context = await browser.newContext({ locale: 'zh-CN', viewport: { width: 1440, height: 1000 }, reducedMotion: 'reduce' }); -await preferFullCollaboration(context); -context.on('page', page => { page.setDefaultTimeout(12000); page.on('pageerror', error => errors.push(error.message)); }); -await context.route(/^https?:\/\//u, async route => { - if (new URL(route.request().url()).origin !== origin) { external.push(route.request().url()); await route.abort(); } else await route.continue(); -}); -const page = await context.newPage(); -async function http(method: string, pathname: string, input?: unknown): Promise { - return page.evaluate(async ({ method, pathname, input }) => { - const session = await (await fetch('/api/session')).json(); - const response = await fetch(pathname, { method, headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': session.csrfToken }, - ...(input === undefined ? {} : { body: JSON.stringify(input) }) }); - const body = await response.json(); if (!response.ok) throw new Error('Fixture HTTP ' + response.status + ': ' + body.error); - return body; - }, { method, pathname, input }) as Promise; -} -const reply = (method: string, pathname: string) => page.waitForResponse(response => response.request().method() === method && new URL(response.url()).pathname === pathname); -try { - await page.goto(origin + '/theorems.html'); - let project = (await http<{ item: ResearchProjectDetail }>('POST', '/api/research/theorems', { requestId: crypto.randomUUID(), title: '历史任务指导版本回归', description: '本地控制回执,不代表数学验收', visibility: 'private' })).item; - const projectPath = '/api/research/theorems/' + project.id; - project = (await http<{ item: ResearchProjectDetail }>('POST', projectPath + '/versions', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statement: 'Prove True', source, environment: 'standard', confirmation: { confirmed: true } })).item; - const version = project.currentStatementVersionId!; - const run = (await http<{ run: { id: string } }>('POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-local-guidance-fixture', model: 'fixture', effort: 'low', - environment: 'standard', source, task: '历史任务指导入口', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' })).run; - for (let attempt = 0; attempt < 100 && !controls.has(run.id); attempt++) await new Promise(resolve => setTimeout(resolve, 20)); - assert.ok(controls.has(run.id)); project = (await http<{ item: ResearchProjectDetail }>('GET', projectPath)).item; - await http('POST', projectPath + '/runs', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: version, runId: run.id, - exposure: 'members', grants: { guidance: true, edit: true, approve: true, proof: true } }); - const url = origin + '/theorems.html?id=' + project.id + '&version=' + version + '&run=' + run.id; - const inspector = page.locator('[data-collab-inspector]'), guide = page.locator('[data-collab-guide-task]'); - for (const width of [1440, 390]) { - phase = 'historical-guidance-' + width; - await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 }); - await page.goto(url + '&task=goal&taskVersion=goal-v1'); await inspector.getByText('goal-v1', { exact: true }).first().waitFor(); - assert.equal(await guide.isDisabled(), true); - const read = reply('GET', projectPath + '/runs/' + run.id + '/observation'); - await page.locator('[data-collab-refresh]:enabled').click(); await (await read).finished(); await settled(page); - assert.match(await inspector.innerText(), /历史/u); assert.equal(await guide.isDisabled(), true, 'Refreshing must keep historical guidance disabled'); - const before = commands.length; - await guide.evaluate(node => node.dispatchEvent(new MouseEvent('click', { bubbles: true }))); await settled(page); - assert.equal(await page.locator('[data-guidance-kind]').inputValue(), 'lead', 'The click handler must not retarget the historical inspector to the current task'); - assert.equal(commands.length, before); - await page.locator('.collab-inspector').screenshot({ path: path.join(output, 'historical-guidance-disabled-' + width + '.png') }); - - await inspector.locator('[data-task-current]').click(); await inspector.getByText('goal-v2', { exact: true }).first().waitFor(); assert.equal(await guide.isEnabled(), true); - await guide.click(); await page.locator('[data-guidance-text]').fill('已核对当前版本后,请补充从假设到结论的推导 ' + width); - const posted = reply('POST', projectPath + '/runs/' + run.id + '/guidance'); - await page.getByRole('button', { name: '发送指导', exact: true }).click(); const response = await posted; assert.equal(response.status(), 200); - assert.deepEqual(response.request().postDataJSON().taskRef, { id: 'goal', version: 'goal-v2' }); - await page.locator('[data-guidance-notice]').getByText(/已送达/u).waitFor(); - assert.equal(commands.length, before + 1); - assert.equal(await page.locator('[data-guidance-text]').inputValue(), ''); - const fit = await page.evaluate(() => ({ viewport: innerWidth, content: document.documentElement.scrollWidth })); assert.ok(fit.content <= fit.viewport + 1, JSON.stringify(fit)); - await page.locator('.collab-guidance').screenshot({ path: path.join(output, 'explicit-current-guidance-delivered-' + width + '.png') }); - - await page.goto(url + '&task=goal&taskVersion=unavailable-version'); - await inspector.getByText('unavailable-version', { exact: true }).first().waitFor(); - const missingRead = reply('GET', projectPath + '/runs/' + run.id + '/observation'); - await page.locator('[data-collab-refresh]:enabled').click(); await (await missingRead).finished(); await settled(page); - assert.equal(await guide.isDisabled(), true, 'A missing historical version must not guide the current task either'); - checks.push({ width, historicalVersion: 'goal-v1', disabledAfterRefresh: true, handlerGuarded: true, missingVersionDisabled: true, - explicitCurrentVersion: 'goal-v2', guidanceStatus: 200, deliveryVisible: true, draftClearedAfterDelivery: true, ...fit }); - } - assert.deepEqual(errors, []); assert.deepEqual(external, []); assert.deepEqual(mail, []); - await fs.writeFile(path.join(output, 'report.json'), JSON.stringify({ status: 'passed', checks, errors, external, realModels: 0, realLean: 0, externalMail: 0, - productionTouched: false, controlledGuidanceCommands: commands, mathematicalAcceptance: 'not-assessed' }, null, 2) + '\n'); - console.log(JSON.stringify({ status: 'passed', checks: checks.length, output })); -} catch (error) { - await page.screenshot({ path: path.join(output, 'failure.png'), fullPage: true }).catch(() => {}); - await fs.writeFile(path.join(output, 'failure.json'), JSON.stringify({ phase, error: String(error), checks, errors, external }, null, 2) + '\n'); throw error; -} finally { - for (const control of controls.values()) control.finish(); await context.close(); await browser.close(); await service.close(); await fs.rm(dataRoot, { recursive: true, force: true }); -} diff --git a/scripts/test-web-saved-key.ts b/scripts/test-web-saved-key.ts index 5b979408..5e4f2adb 100644 --- a/scripts/test-web-saved-key.ts +++ b/scripts/test-web-saved-key.ts @@ -25,7 +25,7 @@ const replacement = 'sk-replacement-browser-check-never-publish-R7m2'; const keys: string[] = []; let formalizationCalls = 0; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Local saved key fixture; no model or Lean' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Local saved key fixture; no model or Lean' }; }, async formalize() { formalizationCalls++; throw new Error('Saving an account key must not start formalization.'); }, async run(input, send) { keys.push(input.input.apiKey); send({ type: 'result', result: { status: 'incomplete', proof: '', report: { fixture: true } } }); }, }; diff --git a/scripts/test-web-solve-process.ts b/scripts/test-web-solve-process.ts index 329074c3..141ac9eb 100644 --- a/scripts/test-web-solve-process.ts +++ b/scripts/test-web-solve-process.ts @@ -1,5 +1,5 @@ #!/usr/bin/env bun -import { clickWorkbenchAction, openAdvancedChatSettings, openChatParticipation, openChatResultDetails } from './web-ui-controls'; +import { clickWorkbenchAction, openAdvancedChatSettings, openChatResultDetails } from './web-ui-controls'; // The solving process: the checklist under the task's status, and the live workspace beside it on a wide screen. // Local fixtures only: a formalization and a run are replayed through a runner. No model, no Lean. import assert from 'node:assert/strict'; @@ -32,7 +32,7 @@ let runInput: WorkerInput | undefined; // The proof stays live until the reader has looked at it; the test releases the end of the run itself. let releaseRun: (() => void) | undefined; const runner: WebRunner = { - async readiness() { return { ready: true, message: '本地解题过程验证环境' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: '本地解题过程验证环境' }; }, formalize(input, send, signal) { return new Promise(resolve => { pending = { input: structuredClone(input), send, resolve }; signal.addEventListener('abort', () => resolve(), { once: true }); }); @@ -78,8 +78,6 @@ async function eventually(check: () => boolean, _description: string) { while (!check()) { assert.ok(Date.now() < until, _description); await sleep(40); } } async function credentials(page: Page) { - await openChatParticipation(page); - await page.locator('input[name="chat-participation"][value="automatic"]').check(); if (!await page.locator('#formalize-key').isVisible()) await clickWorkbenchAction(page, '#open-settings'); await page.locator('#formalize-key').fill('sk-disposable-browser-fixture'); await openAdvancedChatSettings(page); @@ -142,6 +140,8 @@ try { formalization.send({ type: 'result', status: 'approved', evidence: webFormalizationEvidence(formalization.input) }); formalization.resolve(); await eventually(() => Boolean(runInput), 'The confirmed statement starts one proof'); await eventually(() => runInput!.input.source.length > 0, 'The proof receives the statement'); + assert.equal(runInput!.input.nativeTeamCapacity, 3, 'Automatic research uses the native team by default'); + assert.equal(runInput!.input.planApproval, undefined); // A wide screen's check rows open the workspace beside the chat; a phone's open their record in place. await page.waitForFunction(wide => document.querySelectorAll(wide ? '[data-solve-check]' : '.solve-row[data-solve-row]').length > 0, width === 1440, { timeout: 15_000 }); @@ -177,6 +177,7 @@ try { await page.locator('[data-research-artifact="live"]').click(); await page.waitForFunction(() => document.body.dataset.chatArtifact === 'live'); assert.equal(await live(page).isVisible(), true); + await live(page).locator('[data-live-tab="file"]').click(); await live(page).locator('.live-code .lean-line').first().waitFor(); assert.match(await live(page).locator('.live-file-head').innerText(), /Submission\.lean/u); // The check list stays folded to one line under the code until the reader opens it. diff --git a/scripts/web-cooperative-fixture.ts b/scripts/web-cooperative-fixture.ts new file mode 100644 index 00000000..88d8da7b --- /dev/null +++ b/scripts/web-cooperative-fixture.ts @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict'; +import type { BrowserContext } from 'playwright'; +import type { createWebService } from '../apps/web/server'; +import { accountLogin, type WebRunInput, type WebSession } from '../apps/web/shared'; + +/** Install a legacy cooperative test fixture before exercising its current readers and commands. */ +export async function seedCooperativeRun(service: ReturnType, context: BrowserContext, + origin: string, input: WebRunInput) { + const sessionResponse = await context.request.get(origin + '/api/session'); + assert.equal(sessionResponse.status(), 200); + const session: WebSession = await sessionResponse.json(); + const provider = session.providers.find(item => item.id === input.providerId); + assert.ok(provider); + const account = session.account && accountLogin(session.account); + const owner = service.auth + ? service.auth.listAccounts().find(item => accountLogin(item) === account)?.id + : (await context.cookies(origin)).find(item => item.name === 'theoremos_session')?.value; + assert.ok(owner); + return service.jobs.create(service.auth ? 'account:' + owner : owner, { ...input, source: input.source.trim() }, provider); +} diff --git a/scripts/web-i18n.ts b/scripts/web-i18n.ts index dc45b968..afa93b2a 100644 --- a/scripts/web-i18n.ts +++ b/scripts/web-i18n.ts @@ -170,7 +170,7 @@ export function serverKeys() { */ export function errorKeys() { const keys = new Map(); - const files = ['apps/web/conversations.ts', 'apps/web/formalizations.ts', 'apps/web/server.ts', 'apps/web/paperDrafts.ts', 'apps/web/jobs.ts', 'apps/web/storage.ts', 'apps/web/auth.ts', 'apps/web/explain.ts', 'apps/web/quota.ts', 'apps/web/admission.ts', 'apps/web/providerCheck.ts', + const files = ['apps/web/shared.ts', 'apps/web/conversations.ts', 'apps/web/formalizations.ts', 'apps/web/server.ts', 'apps/web/paperDrafts.ts', 'apps/web/jobs.ts', 'apps/web/storage.ts', 'apps/web/auth.ts', 'apps/web/explain.ts', 'apps/web/quota.ts', 'apps/web/admission.ts', 'apps/web/providerCheck.ts', 'apps/web/runner.ts', 'apps/web/worker.ts', 'apps/web/moduleRegistry.ts', 'apps/web/knowledgeService.ts', 'apps/web/researchProjects.ts', 'apps/web/researchAssets.ts', 'apps/web/researchApi.ts', 'apps/web/researchMathematics.ts', 'apps/web/researchCandidateScope.ts', 'apps/web/researchAssetPrefill.ts', 'apps/web/researchLibraryTrials.ts', 'apps/web/researchProblems.ts', 'apps/web/researchMathExamples.ts', 'apps/web/researchBudgets.ts', 'apps/web/researchPersonal.ts', 'apps/web/researchJourney.ts', 'apps/web/researchProjectStart.ts', 'apps/web/sharedProofs.ts', 'apps/web/researchCollections.ts', 'apps/web/researchCollaborationApi.ts', 'apps/web/researchMode.ts', 'apps/web/nativeTeamProfiles.ts']; @@ -188,7 +188,9 @@ export function errorKeys() { // Besides error constructors, `.error =` and `error:`: the worker's `{ type: 'error', message }` and the explain // service's table of provider statuses. const visit = (node: ts.Node) => { - if (ts.isNewExpression(node) && /Error$/u.test(node.expression.getText(source))) node.arguments?.forEach(collect); + if (relative === 'apps/web/shared.ts' && ts.isVariableDeclaration(node) && + /^retired.*Message$/u.test(node.name.getText(source)) && node.initializer) collect(node.initializer); + else if (ts.isNewExpression(node) && /Error$/u.test(node.expression.getText(source))) node.arguments?.forEach(collect); else if (['apps/web/researchAssets.ts', 'apps/web/researchApi.ts', 'apps/web/researchMathematics.ts', 'apps/web/researchAssetPrefill.ts', 'apps/web/researchLibraryTrials.ts', 'apps/web/researchPersonal.ts', 'apps/web/researchJourney.ts', 'apps/web/sharedProofs.ts'].includes(relative) && ts.isCallExpression(node) && node.expression.getText(source) === 'fail' && node.arguments[1]) collect(node.arguments[1]); else if (relative === 'apps/web/researchLibraryTrials.ts' && ts.isPropertyAssignment(node) && ['incompatibility', 'error'].includes(node.name.getText(source))) collect(node.initializer); else if (relative === 'apps/web/researchLibraryTrials.ts' && ts.isVariableDeclaration(node) && node.name.getText(source) === 'reason' && node.initializer) collect(node.initializer); diff --git a/skills/theoremos-research/SKILL.md b/skills/theoremos-research/SKILL.md index c95a93a6..258502d3 100644 --- a/skills/theoremos-research/SKILL.md +++ b/skills/theoremos-research/SKILL.md @@ -9,15 +9,15 @@ Work toward the frozen original statement. Choose the mathematical approach, res The current host assignment fixes your role, owned paths and available tools. Use native editing, shell and search within its permissions; delegation also requires an exposed, permitted tool. Choose a tool when its answer would change the next step. A direct proof can go straight to the supplied Lean check. For an experiment, look up the relevant command in this run's `.scratch/theoremos-help.md`, which also gives the delivery interface. -When the host selects native AgentControl, use the exposed native collaboration tools for spawn, followup, message, wait, listing and interruption. `theoremos_team` then handles mathematical tasks, source handoffs and checked-result adoption. Historical `theoremos_team` transport examples below apply only when those operations are advertised. Follow the run's current transport and target identities. +Use the native collaboration tools for spawn, followup, messaging, waiting, listing and interruption. Use `theoremos_team` for mathematical evidence, source handoffs and adoption. If the host requires route approval, Lead calls `publish_plan` with a goal for each original target, then returns so the owner can review it. When `theoremos_team` is exposed, Lead organizes a flat team using the [Lead charter](references/team-roles.md#lead--organize-and-connect-the-work), which the host injects into Lead's stable instructions at startup and continuation. Assign concrete gaps with usable outputs and keep one owner per active obligation, including Lead's own work. While a member owns a gap, Lead advances its consumer or another gap and integrates findings. Follow [parallel-work.md](references/parallel-work.md) for the current operation contracts. Choose expertise for the specific missing concept, assumption or formal interface. Use the [assignment format](references/parallel-work.md#identity-and-assignments) to select a member profile or tag work by route when useful. The host loads profile material for reading on demand. Give the member its gap, known inputs, intended consumer and first useful result. Say what work remains with you. The member chooses its proof approach. -Members send the first usable finding, probe result or blocker through native messages (historical host-tools may use `progress`), with the exact claim or question, assumptions and available evidence. Do not wait for every subgoal before reporting. Private reasoning is not a team update. These are research milestones, without fixed polling intervals, message counts or task quotas. +Members send the first usable finding, probe result or blocker through `send_message`, with the exact claim or question, assumptions and available evidence. Do not wait for every subgoal before reporting. Private reasoning is not a team update. These are research milestones, without fixed polling intervals, message counts or task quotas. -Use native `followup_task` for further instructions and `interrupt_agent` to stop a turn; drafts and history persist. Historical host-tools may use `amend` for an objective change. Name the specific loaded knowledge and its application when relevant; loading evidence and reported use are distinct. Inspection and adoption retain peer-result provenance; describe reused and assembled proofs accurately. Read [parallel-work.md](references/parallel-work.md) for the operation contracts. +Use native `followup_task` for further instructions and `interrupt_agent` to stop a turn; drafts and history persist. Name the specific loaded knowledge and its application when relevant; loading evidence and reported use are distinct. Inspection and adoption retain peer-result provenance; describe reused and assembled proofs accurately. Read [parallel-work.md](references/parallel-work.md) for the operation contracts. Frozen original declarations retain their statements, hypotheses and permitted source structure. Add independent helpers inside the exact editable Lean paths supplied by the host; the same filename in different members' worktrees denotes separate copies. Lead describes mathematical work while the host supplies file and delivery rules. Keep scratch experiments under the documented scratch paths; transfer useful helpers through the current owned-file delivery interface. Helpers may be checked while unrelated original goals remain open, but cannot depend on those holes or new axioms. @@ -29,7 +29,6 @@ Use these references when the work calls for them: - [Lean work](references/lean.md): when finding, testing or delivering formal declarations. - [Continuation](references/continuation.md): when starting from saved work or preparing durable research artifacts. - [Portfolio exploration](references/portfolio.md) describes bounded route scouting and falsification before proof work. -- [Cooperation](references/cooperation.md): when the host uses its cooperative task-graph workflow; read the shared rules and relevant assignment, review or feedback section. - [HuggingMath](references/huggingmath.md): when asked to export a completed result or transfer it into private Hub drafts. - [Parallel work](references/parallel-work.md): when `theoremos_team` is exposed or an independent investigation can usefully run alongside the current task. - [Domain experts](references/domain-experts.md): when a question calls for specialized mathematical knowledge. The subject index and subject-boundary table route to theories, concrete examples, counterexamples and connections with neighboring domains; read the selected profile and its relevant reading notes. diff --git a/skills/theoremos-research/references/parallel-work.md b/skills/theoremos-research/references/parallel-work.md index f76b29f2..8505d27f 100644 --- a/skills/theoremos-research/references/parallel-work.md +++ b/skills/theoremos-research/references/parallel-work.md @@ -8,57 +8,57 @@ Give an investigator the original statement and enough definitions and environme When the host exposes `theoremos_team`, Lead chooses the decomposition, assignments, route changes and adoption decisions. Children have isolated writable worktrees, the same pinned Skill and their own native threads. A later assignment continues that child's thread and saved sources. Runs have no time, turn or token budget by default; explicitly configured host limits apply to all agents together. The host enforces source ownership, process isolation, persistence and independent proof checks. -### Choose the run's transport +### Collaboration and math tools -In a native AgentControl run, use the exposed native `spawn_agent`, `followup_task`, `send_message`, `list_agents`, `wait_agent` and `interrupt_agent` tools for collaboration. Native tools own canonical agent paths, sender identity, messaging and turn control. Use absolute paths such as `/root` for Lead and `/root/NAME` for peers, or native thread IDs. Workspace member IDs in mathematical host operations are shown separately in team observations. +Use the exposed native `spawn_agent`, `followup_task`, `send_message`, `list_agents`, `wait_agent` and `interrupt_agent` tools for collaboration. Native tools own canonical agent paths, sender identity, messaging and turn control. Use absolute paths such as `/root` for Lead and `/root/NAME` for peers, or native thread IDs. Workspace member IDs in mathematical host operations are shown separately in team observations. -The native `theoremos_team` interface contains only seven mathematical operations. Lead sees `finish`, `history`, `inspect`, `inspect-research` and `adopt`; members see `yield`, `history`, `inspect`, `inspect-research` and `submit`. Use the tool's `operation` field. These operations read fixed evidence or release writing for source checking and integration. +Both Lead and members can use `history`, `inspect`, `inspect-research` and `route_summary`. Lead can use `finish`, `adopt` and `retire_route`. Members can use `yield` and `submit`. -Native followup supplies further instructions to a busy member, resumes a yielded task with its draft, and assigns work to a member whose last task has finished. The host records these instructions and refreshes selected profile knowledge. Use `send_message` for findings, route updates and questions, and `interrupt_agent` to stop a turn while retaining membership and saved work. Members can message peers but only Lead dispatches or interrupts members. A child's final answer is automatically delivered to its parent and remains advisory; save and `submit` for independent mathematical checking. Mailbox acceptance is not a read receipt, and an unloaded member is not proof completion. +When the owner requires approval, Lead starts by calling `publish_plan` with `goals: [{theoremName, objective}]` covering every original target and optional `investigations`. Return after publishing. Continue proof work after the host confirms approval. If the owner requests a revision, publish the revised plan. + +If the host exposes the published mathematics library, both Lead and members can search it and read exact declaration sources. Send Lead the declaration name and intended application when installation is needed. Lead requests installation so the host can prepare a new frozen continuation. -Historical `host-tools` runs retain the advertised host collaboration operations for compatibility. Their operation names and optional note formats are documented below. They do not impose an opening decision, publication acknowledgment or coordination checkpoint. +Native followup supplies further instructions to a busy member, resumes a yielded task with its draft, and assigns work to a member whose last task has finished. The host records these instructions and refreshes selected profile knowledge. Use `send_message` for findings, route updates and questions, and `interrupt_agent` to stop a turn while retaining membership and saved work. Members can message peers but only Lead dispatches or interrupts members. A child's final answer is automatically delivered to its parent and remains advisory; save and `submit` for independent mathematical checking. Mailbox acceptance is not a read receipt, and an unloaded member is not proof completion. ### Start and reassess -Use the [Lead charter](team-roles.md#lead--organize-and-connect-the-work) to identify useful complementary work from the statement and necessary definitions, before deriving the complete solution. Assign a concrete gap with an intended consumer and first usable output; the complete proof route or exact helper type need not be known. Identify what Lead retains so ownership includes Lead's own work. Use native `spawn_agent` in native mode; in historical host-tools mode use `theoremos_team` with `operation: "spawn"`, a new `agentId` and a self-contained `message`. A catalogue survey is not a prerequisite. +Use the [Lead charter](team-roles.md#lead--organize-and-connect-the-work) to identify useful complementary work from the statement and necessary definitions, before deriving the complete solution. Assign a concrete gap with an intended consumer and first usable output; the complete proof route or exact helper type need not be known. Identify what Lead retains so ownership includes Lead's own work. Use `spawn_agent` with a self-contained assignment. A catalogue survey is not a prerequisite. When no useful assignment is ready, inspect the relevant definitions, run a focused probe or check an already clear direct proof. Reconsider ownership when a finding, failed check, blocker or new gap creates a useful question. An accepted dispatch records delegation; whether the work is complementary depends on its question and intended consumer. Lead chooses the route, timing and team size within host capacity. -While a member owns a gap, work on its consumer or a different gap and assess findings when they affect the next decision. If the next step needs its result, request the first useful finding or use native `wait_agent`, or historical `wait`, rather than reproduce the assigned work. An empty team does not call for waiting. Source handoffs require confirmed writer shutdown in either transport. +While a member owns a gap, work on its consumer or a different gap and assess findings when they affect the next decision. If the next step needs its result, request the first useful finding or use `wait_agent` to avoid reproducing the assigned work. An empty team does not call for waiting. Source handoffs require confirmed writer shutdown before integration. When the host reports a finite remaining run allowance or hard turn deadline, plan investigations, save sources and RESEARCH.md, and return for checking or handoff before cutoff. An explicitly configured hard native-turn limit can interrupt an unfinished provider request even when the overall run has time left. Save useful partial work at natural milestones; use a member's `yield` when a dependency calls for a resumable handoff. Organize a flat team around complementary gaps in the current proof effort, with one owner per active obligation. Direct discussion between members can clarify interfaces or challenge assumptions without passing every message through Lead. Different tactics or coordinate systems for the same target still overlap. Explore a specific unresolved route question and report the smallest discriminating finding first; a second complete proof is justified when full independent reconstruction is itself the required evidence. When one member owns the original target in full, Lead handles integration and targeted support or review. Lead remains responsible for assignments, shared route changes and formal adoption, while each member chooses its mathematical approach. -For historical `message`, `agentId` names the recipient and the host supplies the sender from the current session. A member reports to Lead with `{"operation":"message","agentId":"lead","message":"..."}`; use the other member's ID for a peer. Native `send_message` uses canonical paths or native IDs. Self-addressed messages are rejected with corrective feedback. - ### Identity and assignments The durable identities are Lead and mathematical researchers who can write Lean. Lead may research and prove as well as coordinate. A member's `agentId`, workspace and thread persist; its expertise and work focus come from the current assignment and can change. Match [domain knowledge](domain-experts.md) to the actual missing concept, hypothesis or mathematical tool, and [work responsibility](team-roles.md) to the result needed. A broad subject label is not enough reason to load a profile; a Lean interface failure may need a Library Scout or Debugger rather than more domain reading. Read the selected domain section and relevant linked passage. The expert chooses its reasoning and proof approach. Profiles can be combined or reused when each supplies useful knowledge, without adding workers merely to cover roles. Make the dispatch message self-contained: give the selected profiles, concrete gap or proposed declaration, necessary definitions and known inputs, intended consumer and first usable result. A single helper, useful probe or blocking question can be the first result; do not require all assigned lemmas before communication. Distinguish checked inputs from conjectures and cite delivery or research artifact IDs when available. The host supplies allowed source paths and delivery operations; do not copy Lead's own declaration-submission file protocol into member assignments or invent extra writable files. Profiles go in the message; there is no separate `role` tool parameter. Private scratch paths alone do not transfer their contents. -Choose native `fork_turns` for the assignment. Use `"none"` with a self-contained question when prior conversation is unnecessary, especially for independent reconstruction or review. Use `"all"` when continuing reasoning that needs inherited history; it can contain tentative answers, obsolete tool results and Lead's route. Full-history forks inherit the parent's model and reasoning effort, with native provenance but no access to another member's mutable files. The child still receives the host's current assignment, source permissions and its own workspace. Historical host-tools children start without Lead's conversation. For an independent review, choose a member who did not produce the work and provide the fixed claim and required evidence without prescribing the verdict. Record prior exposure rather than claiming independence after an answer-bearing fork. +Choose native `fork_turns` for the assignment. Use `"none"` with a self-contained question when prior conversation is unnecessary, especially for independent reconstruction or review. Use `"all"` when continuing reasoning that needs inherited history; it can contain tentative answers, obsolete tool results and Lead's route. Full-history forks inherit the parent's model and reasoning effort, with native provenance but no access to another member's mutable files. The child still receives the host's current assignment, source permissions and its own workspace. For an independent review, choose a member who did not produce the work and provide the fixed claim and required evidence without prescribing the verdict. Record prior exposure rather than claiming independence after an answer-bearing fork. -Native `spawn_agent` and `followup_task` use the same message format. Put an optional `Route: ROUTE_ID` line first, an optional `Profiles: prover, D006` line next, then the assignment. The `Profiles:` line lists only catalogue IDs or slugs. Put custom expertise in the body. Historical host-tools use the `routeId` argument and put `Profiles:` first in `message` if present. The host loads selected profile sections and provides local reading locators from the pinned Skill. A native followup keeps the current selection unless it supplies a new one. +Native `spawn_agent` and `followup_task` use the same message format. Put an optional `Route: ROUTE_ID` line first, an optional `Profiles: prover, D006` line next, then the assignment. The `Profiles:` line lists only catalogue IDs or slugs. Put custom expertise in the body. The host loads selected profile sections and provides local reading locators from the pinned Skill. A native followup keeps the current selection unless it supplies a new one. The task retains `profileEvidence`: the pinned Skill digest and source file, anchor, line range, digests and loading mode. An `available-on-demand` entry identifies readable material; it does not claim its text reached the model. When a passage informs a finding, name its anchor and concrete application in the message or RESEARCH.md. A loading record or reported use does not prove expert contribution or a fresh external-source read. -Lead uses native `followup_task` for further instructions, including a changed objective or specialty. The saved task retains the draft, instruction history and loaded profile identities; earlier findings remain evidence from their original context. Historical host-tools use `amend(agentId, taskId, message, reason, workKind?)` for an objective change, preserving their revision history and optional research, proof, independent-reconstruction, review or assembly work kind. A discussion message in either transport is advisory. +Lead uses native `followup_task` for further instructions, including a changed objective or specialty. The saved task retains the draft, instruction history and loaded profile identities; earlier findings remain evidence from their original context. Discussion messages carry advisory findings. `inspect` records exposure to a checked peer delivery. Adoption records reuse and its producer, task and commit; that information persists across assignments and is attached to later proof deliveries. Members use independent Git object stores and cannot browse mutable peer workspaces. These records describe explicit transfers, not complete mathematical independence: messages, prior work and the seeded sources also inform reasoning. Do not describe a proof assembled from peer results as an independent reconstruction. Preserve the original authors of reused results even when your delivery also contains their declarations. On a new assignment, read its current instructions, source/delivery baseline, previous task result and addressed updates. Inspect relevant definitions and exact types before extending an inherited derivation. As soon as a concrete claim or application can be checked, save a focused Lean probe and use its result to choose the next step. Current files and host feedback take priority over remembered claims. Retain useful drafts and rejected declarations for correction. If the objective or interface is flawed, send Lead the precise issue, assumptions and supporting example or check. Lead can stop obsolete native work with `interrupt_agent` and supply further instructions with `followup_task`; the next writer still waits for confirmed shutdown in that workspace. -Communicate a useful reduction, blocking question or contradictory finding as soon as it affects another member's work. Include enough argument, exact declaration/type, assumptions and evidence references for the recipient to assess it. Native messages retain sender identity and saved mailbox records; acceptance is not a read acknowledgment. Historical host messages can include `relatedTaskId` and `researchRevision`; their saved dispatch revision does not assert the recipient read later updates. A local Lean check is advisory; use `submit` for transferable formal evidence. +Communicate a useful reduction, blocking question or contradictory finding as soon as it affects another member's work. Include enough argument, exact declaration/type, assumptions and evidence references for the recipient to assess it. Native messages retain sender identity and saved mailbox records; acceptance is not a read acknowledgment. A local Lean check is advisory; use `submit` for transferable formal evidence. ### Keep findings moving -Apply the [Lead charter](team-roles.md#lead--organize-and-connect-the-work) when sharing ownership, receiving findings or deciding adoption. Assess native messages and available results, or the durable inbox in historical host-tools mode, when they affect the work. When the first usable result is ready, handle its submission, checking and adoption before requesting optional extensions. Use the current transport's instruction mechanism when responsibility changes. +Apply the [Lead charter](team-roles.md#lead--organize-and-connect-the-work) when sharing ownership, receiving findings or deciding adoption. Assess messages and available results when they affect the work. When the first usable result is ready, handle its submission, checking and adoption before requesting optional extensions. Use `followup_task` when responsibility changes. A member reports the first usable finding, local probe result or blocker when it can affect another member's work, including on a whole-target assignment. Send the exact claim, assumptions, argument or diagnostic and remaining uncertainty, and save reproducible notes. Once independent Lean declarations answer the assignment, save source and RESEARCH.md, call `submit` and return for host checking before expanding into a peer's gap. Remaining holes in unrelated original targets do not prevent a helper delivery. If a host command fails, send its command, diagnostic and any documented fallback result; distinguish infrastructure failure from a failed mathematical argument. Lead can arrange the next assignment once the result has entered the checking and handoff path. -Native members use `send_message` for findings, probe results, blockers and route changes. Choose a useful question or probe and report its result when it matters to someone else, with its assumptions and evidence. Historical host-tools additionally support optional structured `progress` records. Private transcript commentary is not a shared message, and reported progress does not grant proof acceptance. +Native members use `send_message` for findings, probe results, blockers and route changes. Choose a useful question or probe and report its result when it matters to someone else, with its assumptions and evidence. Private transcript commentary is not a shared message, and reported progress does not grant proof acceptance. For example, send the consumer the exact candidate type, the hypotheses that work, the application that fails, and the goal Lean leaves open. Keep those facts and the next experiment in RESEARCH.md. After `send_message`, retain its `submission_id` in the notes so Lead can match the message to the saved artifact. @@ -74,7 +74,7 @@ Use these milestones to keep collaboration connected; no fixed message count, po ### Handoff and limits -When a peer dependency or Lead decision blocks the current task, save the draft and RESEARCH.md, call `yield(reason)` and return. The acknowledgment requests writer shutdown; the task becomes `paused` only after shutdown is confirmed. Lead may adopt a needed checked result and continue the task with native `followup_task`, or historical `resume(agentId, taskId)`, retaining its source baseline and thread. A normal return still finishes the investigation; use `yield` when the existing task should remain open. Do not wait indefinitely with an active writer, or call `yield` after requesting a formal submission. +When a peer dependency or Lead decision blocks the current task, save the draft and RESEARCH.md, call `yield(reason)` and return. The acknowledgment requests writer shutdown; the task becomes `paused` only after shutdown is confirmed. Lead may adopt a needed checked result and continue the task with `followup_task`, retaining its source baseline and thread. A normal return still finishes the investigation; use `yield` when the existing task should remain open. Do not wait indefinitely with an active writer, or call `yield` after requesting a formal submission. Save before `submit` or `yield`. Both also request an automatic handoff at the next unpaid request boundary. The current paid response and its tool calls settle first; the host then confirms writer shutdown. Submission enters declaration checking; yielding retains the task for resume. No further model request is needed to poll this handoff. @@ -82,48 +82,16 @@ Lead saves all original proofs and returns for independent checking. For an earl Do not invent task budgets or a Lead reserve. Native team tools expose no local allowance controls. Report observed usage as usage, without turning it into a stopping rule. -Historical host-tools expose budget controls only when the host explicitly configures a finite token or turn allowance. Lead may give `spawn`/`assign` an optional `budget:{tokens?,turns?}` and use `budget` to replace a task allowance or `leadReserve:{tokens?,turns?}`. Consumption is cumulative across yields and resumes. Supplied allowance/reserve objects replace their previous values; an empty object releases local limits. When all host token and turn limits are removed, older caps and reserves remain in history but are not enforced. A budget change does not resume a paused task. Token limits govern later request admission from observed receipts; an admitted request can finish beyond the allowance, and unavailable usage remains explicit. - Save reproducible arguments and exact code in RESEARCH.md and owned source files. In the final summary, identify what was established or remains open, the declarations or evidence to inspect, the precise blocker if any, and a useful next step. Do not report a rejected delivery as checked or a finished investigation as an accepted proof. No fixed report template or role acknowledgment is required. ### Shared research and saved findings -In native mode, share route updates through `send_message` and save reproducible findings in RESEARCH.md. Lead chooses what each member needs for its assignment. Historical host-tools also retain optional `publish(summary)`: it versions a shared advisory summary and notifies members. Neither message storage nor a published summary grants proof acceptance. Members send corrections or disagreements to the relevant peers and Lead. +Share route updates through `send_message` and save reproducible findings in RESEARCH.md. Lead chooses what each member needs for its assignment. Route updates remain advisory. Members send corrections or disagreements to the relevant peers and Lead. -Contexts and historical `poll`/`wait` use a bounded overview: current/next/recent tasks and recent references, task-text previews and omission counts. Member `activity` distinguishes preparing, running, stopping, checking, integrating, paused and idle; these are execution observations, not mathematical progress. Use `history` to page complete task instructions, summaries and errors, including legacy notes when present. A task's `historyOffset` is its offset within that member's history. Without `agentId`, history follows the host's stable global task sequence. Follow `nextOffset` until null; the default limit is 4 and maximum 8, with a byte limit stopping at whole-task boundaries. Declaration arrays are omitted; use `inspect` for checked proof interfaces. - -Historical context inbox events can be previews. `textTruncated` means the body remains unread; `previewThrough` is not a receive cursor. Use `poll(after: through)` to obtain complete messages. Historical `poll`/`wait` return at most 8 complete events and can return fewer to stay within their byte allowance; continue from their returned cursor. Older omitted task and reference records remain in the archive and are discoverable through task history and evidence IDs. +The team overview lists active assignments, recent tasks and references. Member `activity` distinguishes preparing, running, stopping, checking, integrating, paused and idle; these are execution observations, not mathematical progress. Use `history` to page complete task instructions, summaries and errors, including legacy notes when present. A task's `historyOffset` is its offset within that member's history. Without `agentId`, history follows the host's stable global task sequence. Follow `nextOffset` until null; the default limit is 4 and maximum 8, with a byte limit stopping at whole-task boundaries. Declaration arrays are omitted; use `inspect` for checked proof interfaces. After an executed task's writer has stopped, the host saves a stable `sourceCommit` and `researchArtifactId`. The artifact contains its summary and task status, plus RESEARCH.md when present; absent notes are reported explicitly. These references remain discoverable in task results and the team's `researchArtifacts` index when the producer takes another assignment. Use `inspect-research` with the artifact ID to read the saved findings at that fixed commit, following pagination until complete. This is the path for a source survey, counterexample argument, failed route or useful calculation without a formal Lean delivery. Refer to its hypotheses and evidence when using it; a stored artifact is advisory even if its note reports a successful local check. Inspect checked proof declarations separately with `inspect`. -### Historical host-tools compatibility - -These additional operations apply only when advertised by the historical transport. Publication is advisory. - -| Operation | Caller | Arguments and result | -| --- | --- | --- | -| `spawn` | Lead | `agentId`, `message`: create a child and queue its first assignment; returns a task ID. Optional `budget:{tokens?,turns?}` is available only with a finite host allowance. | -| `assign` | Lead | `agentId`, `message`: queue follow-up work for an existing child. Optional `budget:{tokens?,turns?}` is available only with a finite host allowance. | -| `amend` | Lead | `agentId`, `taskId`, `message`, `reason`, optional `workKind`: revise a queued, running or paused objective without replacing the task or draft. `spawn`/`assign` also accept optional `workKind`. | -| `progress` | Child | `objectiveRevision`, `kind` (`finding`, `probe`, `blocker`, `route`), `summary`, optional `nextStep`, `evidenceRefs`, `knowledgeUses`: save advisory progress against the current objective revision and notify Lead. | -| `finish` | Lead | `summary`: after saving, request writer shutdown and independent checking of all original targets. | -| `budget` | Lead, finite host allowance only | Optional `leadReserve:{tokens?,turns?}` and/or the complete `agentId`, `taskId`, `budget:{tokens?,turns?}` group: replace the reserve or that task's cumulative allowance without resuming it. | -| `yield` | Child | `reason`: save and return for confirmed writer shutdown, pausing the current task while retaining its identity and drafts. | -| `resume` | Lead | `agentId`, `taskId`: queue a paused task again with the same identity and cumulative allowance. | -| `history` | Any member | Optional `agentId`, `offset`, `limit` (default 4, maximum 8): page complete task text, source/evidence references and the full current advisory research summary. | -| `cancel` | Lead | `agentId`, `taskId`, optional `reason` and `replacement`: cancel a queued task or request a running task's shutdown; an optional replacement message queues a new task for the same member. | -| `publish` | Lead | `summary`: update the versioned advisory team research summary and notify members. | -| `message` | Any member | `agentId` is the recipient, `message`, optional `relatedTaskId` and `researchRevision`: durably save an advisory message and return `from`/`to`; native notification is queued separately. Self-addressed messages are rejected. | -| `poll` | Any member | Optional `after` cursor: receive addressed events, the advisory research summary, worker/task results, research artifact references, delivery IDs and adoption status immediately. | -| `wait` | Any member | `after`, optional `timeoutMs` from 1 to 30000: wait for addressed events, then return the same snapshot as `poll`. | -| `inspect` | Any member | `deliveryId`: read a checked delivery's declarations, provenance, commit, imports and evidence. For a truncated source change, call `inspect` again with the same delivery ID, its `changeIndex` and `nextOffset` as `offset`. Each page returns up to `limit` Unicode code points (default and maximum 16,000). Reading a page does not adopt it. | -| `inspect-research` | Any member | `artifactId`, optional `offset` and `limit` in Unicode code points: read a page of saved research notes at their fixed commit; follow `nextOffset` until complete. | -| `submit` | Child | `summary`, `declarations`: nominate exact declarations for checking after returning. Optional `helpersOnly: true` shares standalone helpers and keeps the assignment open. | -| `adopt` | Lead | `deliveryId`, optional `targetId` (default `lead`): queue checked integration into Lead or an idle child; returns before integration completes. | -| `stop` | Lead | `agentId`: prevent further assignments and request interruption of an active child; shutdown finishes asynchronously. | - -`spawn` and `assign` queue work without waiting for its completion. Receive results through `poll` or `wait`, passing the cursor returned by either receive operation as `after` on the next one. Each result can arrive while other children continue. Messages and completion summaries are advisory. Use `inspect` if you need the exact interface or evidence for an adoption decision. A saved result is available even after its producer receives another assignment. - ### Source checking and adoption Adopt by delivery ID when the checked interface fits. For a source review, `inspect` can page through a long frozen declaration using the same `deliveryId` and `changeIndex` with each `nextOffset`. @@ -132,9 +100,9 @@ For a new auxiliary `def` or `abbrev`, add `"kind":"definition"` to that declara An acknowledged submission keeps the assignment revision at nomination. Interrupting a member stops its work; submitted declarations still go to the checker after confirmed writer shutdown. A busy followup may report a pending submission: let the check settle before assigning new work. For a rejected Lean check, give the repairing member the producer's `history` locator from the failure notice. The full task entry contains the failing declaration, the checked versions and Lean's diagnostic. -When the assigned proof is still open, save the sources and call `submit` with `helpersOnly: true`, `summary` and only the standalone declarations you want to share. Include the current `objectiveRevision` after an amendment in host-tools mode. The host also checks any same-file helper dependencies and rejects any helper that depends on an unfinished original goal. Return after the call so the host can verify the saved sources independently. The host publishes checked signatures and brings the helpers into peer worktrees before their next turns. Lead can resume the producer's same assignment with its unfinished proof and notes. +When the assigned proof is still open, save the sources and call `submit` with `helpersOnly: true`, `summary` and only the standalone declarations you want to share. The host also checks any same-file helper dependencies and rejects any helper that depends on an unfinished original goal. Return after the call so the host can verify the saved sources independently. The host publishes checked signatures and brings the helpers into peer worktrees before their next turns. Lead can resume the producer's same assignment with its unfinished proof and notes. -In either transport, a child submitting Lean work supplies 1–32 declarations, each with `file`, fully qualified `name` and complete closed `type`; optional `description` and explicit `premises` preserve its interface. Native submit omits `objectiveRevision`: the host binds the current member and task. Historical host-tools require the current `objectiveRevision` after an amendment. For a completed assignment, list every changed declaration in the delivery. Frozen original declarations keep their names, statements, hypotheses and permitted source structure. New independent helper declarations are allowed inside editable owned Lean files; keeping original proof edits within their permitted bodies does not forbid these additions. Helpers cannot depend on unfinished original proofs or new axioms. Scratch experiments remain under the documented scratch paths; put transferable helper declarations in an editable owned file before nomination. Save sources and research notes, call `submit`, then return. Its `pending-writer-stop` response records the request; it does not assert that checking passed. The host confirms shutdown, freezes actual source bytes and checks the submitted declarations before publishing a delivery ID. Read failures from the task/event feedback and correct them through a later assignment. A deterministic source-policy failure preserves the invalid draft and clears that rejected nomination so the same member can repair it; invalid source bytes do not create a checked commit or research artifact. If the host identifies a file outside ownership, repair it in your own worktree and nominate only permitted source paths. Historical pending infrastructure checks retain their separate retry path. +A child submitting Lean work supplies 1–32 declarations, each with `file`, fully qualified `name` and complete closed `type`; optional `description` and explicit `premises` preserve its interface. Native submit omits `objectiveRevision`: the host binds the current member and task. For a completed assignment, list every changed declaration in the delivery. Frozen original declarations keep their names, statements, hypotheses and permitted source structure. New independent helper declarations are allowed inside editable owned Lean files; keeping original proof edits within their permitted bodies does not forbid these additions. Helpers cannot depend on unfinished original proofs or new axioms. Scratch experiments remain under the documented scratch paths; put transferable helper declarations in an editable owned file before nomination. Save sources and research notes, call `submit`, then return. Its `pending-writer-stop` response records the request; it does not assert that checking passed. The host confirms shutdown, freezes actual source bytes and checks the submitted declarations before publishing a delivery ID. Read failures from the task/event feedback and correct them through a later assignment. A deterministic source-policy failure preserves the invalid draft and clears that rejected nomination so the same member can repair it; invalid source bytes do not create a checked commit or research artifact. If the host identifies a file outside ownership, repair it in your own worktree and nominate only permitted source paths. The host can retry an infrastructure failure against the pending nomination. Draft sources from a deferred or rejected delivery remain part of the next submission. List their changed declarations as well as the new corrections; only a successful delivery advances this source baseline. A stopped child may receive a checked peer adoption while retaining its own unfinished draft. The host preserves that draft and its delivery baseline, rechecks the integration and reports conflicts. Later submissions still list all of the child's own unpublished changes; adopted peer declarations are already tracked by the host and need not be manually resubmitted as new work. @@ -144,8 +112,4 @@ Keep organizing useful work while children are active. On host recovery, an inte A checked local delivery or completed adoption does not establish the original problem. The host independently checks every frozen original target before whole-problem acceptance. -## Other delegation modes - -When only `theoremos_investigate` is exposed, use its bounded `questions` array for read-only investigations. That call waits for all results; investigators do not retain proof-writing assignments. The primary researcher integrates any useful findings within its own source permissions. - -Without a supported team interface, use read-only investigations or separately isolated candidate workspaces within the actual host capability. Do not grant broader permissions, edit run state or treat a completion message as proof acceptance. An unavailable child tool is not a reason to fabricate a parallel workflow. Historical host-tools and read-only investigation modes keep built-in spawn/fork disabled; native AgentControl mode uses its explicitly exposed native collaboration tools. +Without a team in the current session, continue the proof in your assigned workspace using the available tools. diff --git a/src/math/mathBuildManifest.ts b/src/math/mathBuildManifest.ts index 3bf1b947..8dec5e94 100644 --- a/src/math/mathBuildManifest.ts +++ b/src/math/mathBuildManifest.ts @@ -11,7 +11,7 @@ const sourceSchema = z.object({ root: z.string(), commit: z.string().regex(/^[a-f0-9]{40,64}$/u), submodules: z.array(z.object({ path: z.string(), commit: z.string() }).strict()), inputs: z.array(fileSchema), }).strict(); -export const MATH_RUNTIME_BUNDLES = ['math-solver.js', 'search-lean.js', 'check-lean.js', 'proof-search.js'] as const; +export const MATH_RUNTIME_BUNDLES = ['math-solver.js', 'search-lean.js', 'check-lean.js'] as const; const schema = z.object({ schema: z.literal('deepscientist.math.build-manifest.v1'), buildId: z.string().uuid(), startedAt: z.string().datetime(), finishedAt: z.string().datetime(), source: sourceSchema, diff --git a/src/math/mathRuntimeIo.ts b/src/math/mathRuntimeIo.ts index fc536e42..14ddc917 100644 --- a/src/math/mathRuntimeIo.ts +++ b/src/math/mathRuntimeIo.ts @@ -37,14 +37,20 @@ function checkpointJson(item: unknown, previous: unknown): unknown { if (previous !== undefined && item === previous) return previous; if (Array.isArray(item)) { const prior = Array.isArray(previous) ? previous : undefined; - let unchanged = prior?.length === item.length; - const values = item.map((entry, index) => { - const current = checkpointJson(entry, prior?.[index]); - if (current !== prior?.[index]) unchanged = false; - return current; - }); - // For a sparse array, a removed value is not visited by map. - return unchanged && prior!.every((_, index) => index in values) ? prior : values; + if (!prior) return item.map(entry => checkpointJson(entry, undefined)); + // Keep the matching prefix detached without copying it until a slot changes. + let values: unknown[] | undefined; + for (let index = 0; index < item.length; index++) { + const present = index in item; + const saved = prior[index]; + const current = present ? checkpointJson(item[index], saved) : undefined; + if (!values && current !== saved) values = prior.slice(0, index); + if (values && present) values[index] = current; + } + if (!values && item.length === prior.length) return prior; + values ??= prior.slice(0, item.length); + values.length = item.length; + return values; } if (item && typeof item === 'object') { const prototype = Object.getPrototypeOf(item); diff --git a/src/runtime/agentSession.ts b/src/runtime/agentSession.ts index bef38941..3b1f342e 100644 --- a/src/runtime/agentSession.ts +++ b/src/runtime/agentSession.ts @@ -4,7 +4,6 @@ import type { MathAgentSkill } from './agentSkills'; import type { MathAgentFailureDiagnostic } from './failureDiagnostic'; export type { MathAgentFailureDiagnostic } from './failureDiagnostic'; import type { ModelRequestGate } from './modelRequest'; -import type { NativeDelegationOptions, NativeResearchAgent } from './nativeDelegation'; import type { MathAgentTools } from './agentTeamTools'; export type { MathAgentTools, MathAgentToolDefinition, MathAgentToolContext } from './agentTeamTools'; import type { HarnessProcessIdentity } from './harnessProcess'; @@ -32,13 +31,13 @@ export type MathAgentOptions = { effort: string; instructions: string; skills?: readonly MathAgentSkill[]; - delegation?: NativeDelegationOptions; - onNativeAgent?: (agent: NativeResearchAgent) => void; tools?: MathAgentTools; /** Host backend for Codex's built-in collaboration tools, with isolated native children. */ nativeAgentControl?: NativeAgentControlOptions; /** Tie the complete native writer tree to this host with a dedicated PID namespace. */ isolateProcess?: boolean; + /** Native planning can read the proof workspace and write only to its scratch directory. */ + readOnlyWorkspace?: boolean; environment?: NodeJS.ProcessEnv; proofProjectRoot?: string; /** Host-owned environment probe, run in the same isolated namespace before native/model startup. */ diff --git a/src/runtime/agentSessionPlan.ts b/src/runtime/agentSessionPlan.ts index 9590a02e..8c2817c6 100644 --- a/src/runtime/agentSessionPlan.ts +++ b/src/runtime/agentSessionPlan.ts @@ -1,8 +1,7 @@ import type { MathAgentHarnessId, MathAgentOptions, MathAgentSessionPlan } from './agentSession'; import type { CliConfiguration } from './cliConfiguration'; -import { validateNativeDelegation } from './nativeDelegation'; -type Request = Pick; +type Request = Pick; /** Resolve actual workflow requirements before a native process or provider request. * A read-only host-root mount is not the sealed, credential-free role sandbox. @@ -13,11 +12,6 @@ export function planMathAgentSession(harness: MathAgentHarnessId, request: Reque if (request.readIsolation && request.skills?.length) throw new Error(`math_${prefix}_skill_read_isolation_unsupported`); if (request.readIsolation && harness === 'cli' && !cli?.sealedRole) throw new Error('math_cli_sealed_role_configuration_required'); - if (request.delegation) { - if (harness !== 'codex') throw new Error(`math_${prefix}_delegation_unsupported`); - validateNativeDelegation(request.delegation); - if (request.readIsolation) throw new Error('math_native_delegation_read_isolation_unsupported'); - } const loading = new Set(request.skills?.map(skill => skill.loading)); if (harness !== 'codex' && loading.has('native')) throw new Error(harness === 'claude-code' ? 'math_claude_native_skill_loading_unsupported' : `math_${prefix}_requires_file_skill`); diff --git a/src/runtime/agentTeamTools.ts b/src/runtime/agentTeamTools.ts index 37bb190a..bb330b71 100644 --- a/src/runtime/agentTeamTools.ts +++ b/src/runtime/agentTeamTools.ts @@ -29,11 +29,10 @@ export class MathAgentToolDispatcher { private controller?: AbortController; private stopped = false; - constructor(private readonly tools: MathAgentTools, private readonly active: (threadId: string, turnId: string) => boolean, - reserved: readonly string[] = []) { + constructor(private readonly tools: MathAgentTools, private readonly active: (threadId: string, turnId: string) => boolean) { this.definitions = tools.definitions.map(definition => { if (!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(definition.name) || this.names.has(definition.name) || - reserved.includes(definition.name) || !definition.description || !definition.inputSchema || + !definition.description || !definition.inputSchema || typeof definition.inputSchema !== 'object' || Array.isArray(definition.inputSchema)) throw new Error('math_agent_tool_definition_invalid'); this.names.add(definition.name); diff --git a/src/runtime/cliSession.ts b/src/runtime/cliSession.ts index 59d00416..097c5a1e 100644 --- a/src/runtime/cliSession.ts +++ b/src/runtime/cliSession.ts @@ -31,7 +31,6 @@ const observe = (callback: (() => void) | undefined) => { try { callback?.(); } /** One configured headless command per turn. It never treats output as mathematical acceptance. */ export async function createCliMathSession(options: MathAgentOptions): Promise { - if (options.delegation) throw new Error('math_cli_delegation_unsupported'); if (options.outputSchema && !options.completedOutput) throw new Error('math_cli_output_schema_unsupported'); if (options.skills?.some(skill => skill.loading !== 'file')) throw new Error('math_cli_requires_file_skill'); if (options.signal?.aborted) throw new Error('math_model_request_stopped'); diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index d4d8676f..4278a0c2 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -16,8 +16,6 @@ import { startFormalizationRelay } from './formalizationRelay'; import { mathDigest, readMathText } from '../math/mathRuntimeIo'; import { scheduleMathTimeout } from '../math/mathTimers'; import { assertMathAgentSkillsCurrent, assertMathAgentSkillsDiscovered } from './codexSkills'; -import { INVESTIGATION_TOOL, INVESTIGATOR_PERMISSION_PROFILE, NativeInvestigations, - nativeInvestigationTool, validateNativeDelegation } from './nativeDelegation'; import { planMathAgentSession } from './agentSessionPlan'; import { MathAgentToolDispatcher } from './agentTeamTools'; import { confirmHarnessProcessStopped, prepareHarnessProcess, readHarnessProcessIdentity, type HarnessProcessIdentity } from './harnessProcess'; @@ -68,13 +66,6 @@ export function mathWorkerPermissionConfig(workspace: string, hiddenRoots: reado }; } -function investigatorPermissionConfig(workspace: string, hiddenRoots: readonly string[] = []): Json { - const hidden = ['/run', '/tmp', ...hiddenRoots].filter(root => workspace !== root && !workspace.startsWith(`${root}/`)); - return { [`permissions.${INVESTIGATOR_PERMISSION_PROFILE}.filesystem`]: { - '/': 'read', [workspace]: 'read', ...Object.fromEntries(hidden.map(root => [root, 'none'])), - }, [`permissions.${INVESTIGATOR_PERMISSION_PROFILE}.network.enabled`]: false }; -} - const object = (value: unknown): Json => { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('math_codex_invalid_message'); return value as Json; @@ -295,11 +286,12 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise if (skills.length && options.readIsolation) throw new Error('math_codex_skill_read_isolation_unsupported'); if (options.tools && options.readIsolation) throw new Error('math_codex_tools_read_isolation_unsupported'); if (options.isolateProcess && options.readIsolation) throw new Error('math_codex_process_isolation_role_conflict'); - if (options.nativeAgentControl && (options.readIsolation || options.delegation)) + if (options.readOnlyWorkspace && !options.isolateProcess) throw new Error('math_codex_read_only_workspace_requires_process_isolation'); + if (options.nativeAgentControl && options.readIsolation) throw new Error('math_native_agent_control_role_conflict'); const tools = options.tools ? new MathAgentToolDispatcher(options.tools, (calledThread, calledTurn) => calledThread === threadId && activeTurn === calledTurn && - !turnSettled && !turnStopping && !closing, options.delegation ? [INVESTIGATION_TOOL] : []) : undefined; + !turnSettled && !turnStopping && !closing) : undefined; const configFile = path.join(options.profile, 'config.toml'); const frozenConfig = fs.existsSync(configFile) ? fs.readFileSync(configFile, 'utf8') : undefined; const profileConfig = frozenConfig === undefined ? {} : parseToml(frozenConfig); @@ -314,9 +306,6 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise const webNativeTeam = providerId === 'web_provider' && Boolean(options.nativeAgentControl); const useResponsesRelay = (providerId === SUB2API_PROVIDER.id || webNativeTeam) && !options.readIsolation && Boolean(options.requestGate); - if (options.delegation && (!skills.length || !useResponsesRelay)) - throw new Error('math_native_delegation_requires_skill_and_metered_relay'); - if (options.delegation) validateNativeDelegation(options.delegation); const executionPlan = planMathAgentSession('codex', options.nativeAgentControl?.initialInput ? { ...options, skills: skills.map(skill => ({ ...skill, loading: 'file' as const })) } : options); const activeRequests = new Set(); @@ -336,7 +325,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise }); let checkCompletedOutput: (() => void) | undefined; let completedOutputWatch: { id: string; file: string; changed(): void } | undefined; - let checkTurnCheckpoint: (() => boolean) | undefined; + let checkTurnCheckpoint: ((atRequestBoundary?: boolean) => boolean) | undefined; const requestGate: ModelRequestGate = identity => { // A tool can submit and immediately request more model work before fs/changed arrives. // Inspect that file synchronously before admitting another paid request. @@ -506,21 +495,15 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise } as const : {}) }, }; let closing: Promise | undefined; - let investigations: NativeInvestigations | undefined; let boundTurn: Promise = Promise.resolve(undefined); let bindTurn: ((turnId?: string) => void) | undefined; const closeSession = () => closing ??= (async () => { options.signal?.removeEventListener('abort', aborted); compacting?.reject(new Error('math_codex_compaction_closed')); turnStopping = true; cancelNotifications(); publicItems.clear(); - bindTurn?.(); investigations?.stop(); tools?.stop(); nativeControl?.stop(); + bindTurn?.(); tools?.stop(); nativeControl?.stop(); try { await rpc.close(); } finally { try { await responsesRelay?.close(); } finally { try { await bridge?.close(); } finally { await isolated?.close(); } } - if (investigations) { - await investigations.settled(); - const receipt = await rpc.confirmStopped(); - investigations.confirmStopped(receipt.status === 'stopped'); - } await tools?.settled(); await nativeControl?.settled(); } @@ -555,7 +538,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise notices.clear(); releaseFence(); }; const flushNotifications = (atRequest = false): NotificationFence | undefined => { - if (!notices.size || activeRequests.size || investigations?.busy || tools?.busy || notificationFence || !activeTurn || turnSettled || turnStopping || turnCheckpointReached || closing) return; + if (!notices.size || activeRequests.size || tools?.busy || notificationFence || !activeTurn || turnSettled || turnStopping || turnCheckpointReached || closing) return; if (![...notices].some(notice => !notice.waitForRequest || atRequest)) return; const turnId = activeTurn, turn = requestTurn; let release!: () => void; @@ -707,23 +690,20 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise cancelNotifications(); publicItems.clear(); transportFailure = error; lastError = error.message; lastFailureDiagnostic = undefined; completion?.reject(error); compacting?.reject(error); - investigations?.stop(); tools?.stop(); nativeControl?.stop(); bindTurn?.(); + tools?.stop(); nativeControl?.stop(); bindTurn?.(); if (!closing) { void closeSession().catch(() => {}); } }; rpc.onRequest = async (method, params) => { if (method === NATIVE_AGENT_CONTROL_REQUEST && nativeControl) return nativeControl.call(params); - if (method !== 'item/tool/call' || !investigations && !tools) return; + if (method !== 'item/tool/call' || !tools) return; const turnId = await boundTurn; if (!turnId || params.turnId !== turnId) return { contentItems: [{ type: 'inputText', text: 'math_agent_tool_turn_mismatch' }], success: false }; - if (investigations && params.tool === INVESTIGATION_TOOL) return investigations.call(params); - if (tools) { - const result = await tools.call(params); - flushNotifications(); - return result; - } + const result = await tools.call(params); + flushNotifications(); + return result; }; rpc.onNotification = (method, params) => { if (method === 'fs/changed') { @@ -734,7 +714,6 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise completedOutputWatch.changed(); return; } - investigations?.observe(method, params); if (threadId !== undefined && params.threadId !== undefined && params.threadId !== threadId) return; if (compacting && method === 'turn/started') { const { id } = object(params.turn); @@ -742,6 +721,13 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise } if (method === 'item/started' || method === 'item/completed') { const item = object(params.item); + // Direct providers have no request relay. The completed host-tool item + // confirms the read-only planner received the result before we stop it. + const args = item.arguments; + if (options.readOnlyWorkspace && !usesRequestReceipts && method === 'item/completed' && + params.turnId === activeTurn && item.type === 'dynamicToolCall' && item.tool === 'theoremos_team' && + item.success === true && args && typeof args === 'object' && 'operation' in args && args.operation === 'publish_plan') + checkTurnCheckpoint?.(false); if (compacting?.turnId && method === 'item/completed' && params.turnId === compacting.turnId && item.type === 'contextCompaction') compacting.installed = true; if (isTurnOutputItem(item)) recordTurnOutput(params.turnId); @@ -810,7 +796,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise try { options.signal?.throwIfAborted(); const processIdentity = await rpc.processIdentity; - await rpc.initialize(Boolean(options.delegation || options.tools || nativeControl)); + await rpc.initialize(Boolean(options.tools || nativeControl)); await nativeControl?.initialize(); const inherited = profileConfig.mcp_servers; const disabled = Object.fromEntries(Object.keys(inherited ?? {}).map(name => [name, { enabled: false }])); @@ -857,7 +843,6 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise model_reasoning_effort: options.effort, // The formalization sandbox is the OS boundary for isolated roles; every other shell runs the worker profile. ...(!isolated ? { ...mathWorkerPermissionConfig(options.workspace, options.hiddenRoots), - ...(options.delegation ? investigatorPermissionConfig(options.workspace, options.hiddenRoots) : {}), ...shellCredentialPolicy, ...shellTemporaryPolicy } : {}), ...providerSettings, }, @@ -873,9 +858,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise const threadSettings = { ...settings, ...(options.threadId ? { threadId: options.threadId, ...(metadataOnlyResume ? { excludeTurns: true } : {}) } : {}), - ...(!options.threadId && (options.delegation || tools?.definitions.length) ? { dynamicTools: [ - ...(options.delegation ? [nativeInvestigationTool(options.delegation.maxAgents)] : []), ...(tools?.definitions ?? []), - ] } : {}), + ...(!options.threadId && tools?.definitions.length ? { dynamicTools: tools.definitions } : {}), }; const result = await rpc.request(bootstrap ? 'theoremos/agentControl/start' : options.threadId ? 'thread/resume' : 'thread/start', bootstrap ? { version: 1, bootstrap, [options.threadId ? 'resume' : 'thread']: threadSettings } : threadSettings); @@ -899,17 +882,6 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise // Ordinary new threads must still confirm the requested named sandbox profile. if (!bootstrap && !isolated && !options.threadId && object(result.activePermissionProfile ?? {}).id !== MATH_WORKER_PERMISSION_PROFILE) throw new Error('math_codex_sandbox_profile_mismatch'); - if (options.delegation) { - if (object(result.activePermissionProfile ?? {}).id !== MATH_WORKER_PERMISSION_PROFILE) - throw new Error('math_codex_sandbox_profile_mismatch'); - investigations = new NativeInvestigations({ parentThreadId: threadId, maxAgents: options.delegation.maxAgents, - workspace: options.workspace, model: options.model, effort: options.effort, settings, - request: (method, params) => rpc.request(method, params), - active: turnId => activeTurn === turnId && !turnSettled && !turnStopping && !closing, - changed: agent => { try { options.onNativeAgent?.(agent); } catch { /* Observation cannot grant permissions. */ } }, - activity: (event, itemType) => activity(event, itemType, true, activeTurn), - fail: error => { completion?.reject(error); void closeSession().catch(() => {}); } }); - } if (skills.some(skill => skill.loading === 'native')) { const discovered = await rpc.request('skills/list', { cwds: [options.workspace], forceReload: true }); assertMathAgentSkillsDiscovered(discovered, options.workspace, skills); @@ -964,7 +936,6 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise 'Completed tool results remain valid. Explicitly backgrounded commands may still be running. ' + 'Continue from the saved work and the current host observations below.\n\n' + message; priorBoundaryCheckpoint = false; externallyInterrupted = false; - investigations?.beginTurn(); tools?.beginTurn(); assertMathAgentSkillsCurrent(skills); if (temporaryDirectory) prepareWorkerTemporaryDirectory(options.workspace); @@ -1063,16 +1034,15 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise if (activeTurn === turnId && !turnSettled && !closing) requestInterruption(); }); }; - checkTurnCheckpoint = () => { + checkTurnCheckpoint = (atRequestBoundary = true) => { if (checkpoint || turnSettled || turnStopping || closing || !(turnCheckpointReached || options.requestGate?.checkpoint?.())) return false; - // A settled response may still have tools to run. The next request is - // the unpaid boundary proving those tools finished; prefer a valid - // output they just saved before requesting a checkpoint. + // For relayed turns the unpaid request boundary confirms tools had a + // chance to finish and save a valid output. checkCompletedOutput?.(); if (submitted || turnSettled || turnStopping || closing) return false; checkpoint = true; - boundaryCheckpoint = true; + boundaryCheckpoint = atRequestBoundary; stopAfterRequests(); return true; }; @@ -1159,11 +1129,6 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise // Native watches are debounced and can be a noop on unsupported // hosts. Completion remains a deterministic final discovery boundary. if (finished.status !== 'failed') checkOutput?.(false, true); - if (investigations?.busy) { - await closeSession(); - if (finished.status === 'completed' && !submitted) - throw new Error('math_codex_transport_closed:investigations_unsettled'); - } options.signal?.throwIfAborted(); if (typeof finished.status !== 'string') throw new Error('math_codex_turn_status_missing'); if (finished.status === 'completed' && !submitted && !turnHasOutput && @@ -1210,15 +1175,13 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise interrupt: async () => { externallyInterrupted = true; turnStopping = true; tools?.cancel(); cancelNotifications(); publicItems.clear(); - // Native turn/interrupt does not reap investigator background commands. - if (investigations?.busy) { await closeSession(); return; } if (activeTurn && !turnSettled && !closing) await rpc.request('turn/interrupt', { threadId, turnId: activeTurn }); }, notify, close: closeSession, stopForFreeze: async () => { // An interrupt RPC acknowledgement does not settle the active turn. - if (completion || activeTurn || compacting || investigations?.busy || tools?.busy || nativeControl?.busy) + if (completion || activeTurn || compacting || tools?.busy || nativeControl?.busy) return { status: 'unconfirmed', reason: 'turn-not-settled' }; try { await closeSession(); diff --git a/src/runtime/harnessProcess.ts b/src/runtime/harnessProcess.ts index 3e8d45b5..aae3dcb4 100644 --- a/src/runtime/harnessProcess.ts +++ b/src/runtime/harnessProcess.ts @@ -72,7 +72,8 @@ export function confirmHarnessProcessStopped(identity: HarnessProcessIdentity): } /** Native tool permissions do not constrain arbitrary shell children. Both CLI harnesses use this OS contract. */ -export function prepareHarnessProcess(options: Pick, +export function prepareHarnessProcess(options: Pick, executable: string, arguments_: readonly string[], infoDescriptor?: number) { if (process.platform !== 'linux' || !fs.existsSync('/usr/bin/bwrap')) throw new Error('math_harness_process_isolation_unavailable'); @@ -88,7 +89,8 @@ export function prepareHarnessProcess(options: Pick }; } diff --git a/src/runtime/nativeDelegation.ts b/src/runtime/nativeDelegation.ts deleted file mode 100644 index a4f4e3ec..00000000 --- a/src/runtime/nativeDelegation.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { limitMathOutput } from '../math/mathProcess'; - -type Json = Record; -export type NativeDelegationOptions = { mode: 'read-only'; maxAgents: number }; -export type NativeResearchAgent = { - threadId: string; parentThreadId: string; startedAt: number; updatedAt: number; - status: 'running' | 'completed' | 'errored' | 'interrupted' | 'stopped' | 'unknown'; - usage?: Record; message?: string; stoppedAt?: number; - permissionProfile?: 'math-investigator'; - dispatch?: 'host-mediated-native-threads'; - callId?: string; parentTurnId?: string; turnId?: string; question?: string; -}; - -export const INVESTIGATOR_PERMISSION_PROFILE = 'math-investigator'; -export const INVESTIGATION_TOOL = 'theoremos_investigate'; - -export function validateNativeDelegation(options: NativeDelegationOptions): void { - if (options.mode !== 'read-only' || !Number.isSafeInteger(options.maxAgents) || - options.maxAgents < 2 || options.maxAgents > 4) throw new Error('math_native_delegation_configuration_invalid'); -} - -export function nativeInvestigationTool(maxAgents: number): Json { - return { type: 'function', name: INVESTIGATION_TOOL, - description: 'Investigate bounded independent questions in parallel read-only native threads. ' + - 'The host mediates dispatch and shared accounting. Results are advisory; only the primary researcher edits or submits sources. ' + - 'This call waits for all results. It cannot accept proofs or change the fixed problem.', - inputSchema: { type: 'object', properties: { questions: { type: 'array', minItems: 1, maxItems: maxAgents - 1, - items: { type: 'string', minLength: 1, maxLength: 16_000 } } }, required: ['questions'], additionalProperties: false } }; -} - -const object = (value: unknown): Json => value && typeof value === 'object' && !Array.isArray(value) ? value as Json : {}; -const text = (value: unknown): string | undefined => { - const item = object(value); - if (item.type === 'agentMessage' && typeof item.text === 'string' && - (item.phase == null || item.phase === 'final_answer')) return item.text; -}; -type Investigation = { observation: NativeResearchAgent; turnId?: string; message?: string; - early: Map; finish?: (turn: Json) => void }; - -/** A single bounded native tool, not a task scheduler. Built-in spawn/fork remains disabled: - * it inherits writer permissions. Independent thread/start verifies its named read-only policy - * before any turn. All threads use the parent's owned app-server and metered provider relay. */ -export class NativeInvestigations { - private agents = new Map(); - private calls = new Map }>(); - private reserved = 0; - private stopped = false; - private pending = new Set>(); - constructor(private input: { parentThreadId: string; maxAgents: number; workspace: string; model: string; effort: string; - settings: Json; request: (method: string, params: Json) => Promise; - active: (parentTurnId: string) => boolean; changed: (agent: NativeResearchAgent) => void; - fail: (error: Error) => void; - activity: (event: 'item_started' | 'item_completed' | 'reasoning' | 'message' | 'command_output', itemType?: string) => void }) {} - - get busy(): boolean { return this.reserved > 0; } - - beginTurn(): void { - if (this.stopped || this.busy) throw new Error('math_native_investigations_unsettled'); - this.calls.clear(); - } - - private publish(agent: Investigation) { - agent.observation.updatedAt = Date.now(); - this.input.changed({ ...agent.observation }); - } - - call(params: Json): Promise { - const { callId, turnId, threadId } = params; - if (params.tool !== INVESTIGATION_TOOL || params.namespace != null || threadId !== this.input.parentThreadId || - typeof turnId !== 'string' || typeof callId !== 'string' || !callId || !this.input.active(turnId) || this.stopped) - return Promise.resolve(this.failure('math_native_investigation_not_active')); - const args = object(params.arguments), questions = args.questions; - if (Object.keys(args).length !== 1 || !Array.isArray(questions) || !questions.length || - questions.length >= this.input.maxAgents || questions.some(question => typeof question !== 'string' || - !question.trim() || question.length > 16_000)) - return Promise.resolve(this.failure('math_native_investigation_arguments_invalid')); - const serialized = JSON.stringify(questions), key = JSON.stringify([turnId, callId]), prior = this.calls.get(key); - if (prior) return prior.arguments === serialized ? prior.result : Promise.resolve(this.failure('math_native_investigation_call_mismatch')); - if (this.reserved + questions.length >= this.input.maxAgents) - return Promise.resolve(this.failure('math_native_investigation_capacity_exceeded')); - this.reserved += questions.length; - const result = Promise.all((questions as string[]).map(question => this.investigate(question, callId, turnId))) - .then(results => ({ contentItems: [{ type: 'inputText', text: JSON.stringify({ - dispatch: 'host-mediated-native-threads', advisory: true, results }) }], success: true })) - .finally(() => { this.reserved -= questions.length; this.pending.delete(result); }); - this.calls.set(key, { arguments: serialized, result }); this.pending.add(result); - return result; - } - - private failure(reason: string): Json { return { contentItems: [{ type: 'inputText', text: reason }], success: false }; } - - private async investigate(question: string, callId: string, parentTurnId: string): Promise { - let agent: Investigation | undefined; - try { - const started = await this.input.request('thread/start', { ...this.input.settings, - permissions: INVESTIGATOR_PERMISSION_PROFILE, - developerInstructions: this.input.settings.developerInstructions + '\n\n' + - 'You are a read-only investigator. Answer only the supplied bounded question. ' + - 'Read the fixed original problem and relevant local sources as needed. Do not edit files, launch background work, ' + - 'delegate, submit proofs or treat other agents\' findings as checked evidence. Return your findings and precise source references.' }); - const threadId = object(started.thread).id; - if (typeof threadId !== 'string' || !threadId || threadId === this.input.parentThreadId) - throw new Error('math_native_investigator_thread_invalid'); - agent = { observation: { threadId, parentThreadId: this.input.parentThreadId, callId, parentTurnId, question, - startedAt: Date.now(), updatedAt: Date.now(), status: 'running', dispatch: 'host-mediated-native-threads' }, early: new Map() }; - this.agents.set(threadId, agent); - if (object(started.activePermissionProfile).id !== INVESTIGATOR_PERMISSION_PROFILE || started.approvalPolicy !== 'never' || - started.model !== this.input.model || started.reasoningEffort !== this.input.effort) - throw new Error('math_native_investigator_binding_mismatch'); - agent.observation.permissionProfile = INVESTIGATOR_PERMISSION_PROFILE; - this.publish(agent); - if (this.stopped || !this.input.active(parentTurnId)) throw new Error('math_native_investigation_not_active'); - const done = new Promise(resolve => { agent!.finish = resolve; }); - const result = await this.input.request('turn/start', { threadId, cwd: this.input.workspace, - clientUserMessageId: randomUUID(), model: this.input.model, effort: this.input.effort, - approvalPolicy: 'never', permissions: INVESTIGATOR_PERMISSION_PROFILE, - input: [{ type: 'text', text: question, text_elements: [] }] }); - const turnId = object(result.turn).id; - if (typeof turnId !== 'string' || !turnId) throw new Error('math_native_investigator_turn_missing'); - agent.turnId = turnId; agent.observation.turnId = turnId; - const early = agent.early.get(turnId); agent.early.clear(); - if (early) agent.finish?.(early); - this.publish(agent); - const completed = await done; - const final = Array.isArray(completed.items) ? completed.items.findLast(item => text(item) !== undefined) : undefined; - const message = text(final) ?? agent.message; - agent.observation.status = completed.status === 'completed' ? 'completed' : completed.status === 'interrupted' ? 'interrupted' : 'errored'; - if (message !== undefined) agent.observation.message = limitMathOutput(message, 32_000, 'head'); - if (!this.stopped) { - // Unsubscribe and turn/interrupt do not reap native background commands. - // Archiving unloads the owned investigation before its capacity is released. - await this.input.request('thread/archive', { threadId }); - agent.observation.stoppedAt = Date.now(); - } - this.publish(agent); - return { threadId, status: agent.observation.status, ...(message === undefined ? {} : { findings: agent.observation.message }) }; - } catch { - if (agent) { agent.observation.status = this.stopped ? 'interrupted' : 'errored'; this.publish(agent); } - if (!this.stopped) this.input.fail(new Error('math_native_investigation_failed')); - return { ...(agent ? { threadId: agent.observation.threadId } : {}), status: 'errored', reason: 'math_native_investigation_failed' }; - } - } - - observe(method: string, params: Json): void { - if (typeof params.threadId !== 'string') return; - const agent = this.agents.get(params.threadId); - if (!agent) return; - if (method === 'thread/tokenUsage/updated') { - agent.observation.usage = object(object(params.tokenUsage).total); this.publish(agent); - } else if (method === 'turn/completed') { - const turn = object(params.turn); - if (typeof turn.id !== 'string' || !['completed', 'failed', 'interrupted'].includes(String(turn.status))) return; - if (agent.turnId === turn.id) agent.finish?.(turn); - else if (!agent.turnId && agent.early.size < 32) agent.early.set(turn.id, turn); - } else if (method === 'item/started' || method === 'item/completed') { - const item = object(params.item), message = text(item); - if (message !== undefined && method === 'item/completed') agent.message = message; - this.input.activity(method === 'item/started' ? 'item_started' : 'item_completed', - typeof item.type === 'string' ? item.type : undefined); - } else if (method === 'item/agentMessage/delta') this.input.activity('message'); - else if (method === 'item/commandExecution/outputDelta') this.input.activity('command_output'); - else if (method.startsWith('item/reasoning/')) this.input.activity('reasoning'); - } - - /** The app-server process owns the entire tree. Only its confirmed stop can mark - * unfinished observations stopped; lost transports are recorded as unknown. */ - stop(): void { - this.stopped = true; - for (const agent of this.agents.values()) agent.finish?.({ id: agent.turnId, status: 'interrupted' }); - } - async settled(): Promise { await Promise.allSettled([...this.pending]); } - confirmStopped(confirmed: boolean): void { - for (const agent of this.agents.values()) { - if (!confirmed && agent.observation.stoppedAt === undefined) agent.observation.status = 'unknown'; - if (confirmed) agent.observation.stoppedAt = Date.now(); - this.publish(agent); - } - } -} diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index 03c39195..2e77893c 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -5,6 +5,7 @@ import { z } from 'zod'; import type { MathAgentSession, MathAgentTools } from '../runtime/agentSession'; import { confirmHarnessProcessStopped } from '../runtime/harnessProcess'; import { NativeAgentControlInputError } from '../runtime/nativeAgentControl'; +import { planApprovalStatus, publishNativeApprovalPlan } from './planApproval'; import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; import { bindLeanPackages } from '../math/leanDiagnostics'; import type { SolverRunState } from './archive'; @@ -24,20 +25,19 @@ import { ResearchUsage } from './researchUsage'; import { aggregateUsage, buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; import { agentTeamStateSchema, type AgentTeamState, type AgentTeamWorker, type AgentTeamTask } from './agentTeamState'; +import { AgentTeamOperations } from './agentTeamOperations'; import { checkAgentTeamProofDelivery, integrateAgentTeamProofDelivery, readAgentTeamProofDelivery, ReusedTeamCheckFailure, type TeamFailureCache } from './agentTeamProof'; import { ownedSourceDigest } from './cooperativeProof'; -import { agentTeamWorkerSection } from './agentTeamContext'; import { saveAgentTeamResearchArtifact, inspectAgentTeamResearchArtifact } from './agentTeamResearch'; -import { agentTeamChildAdmission, projectAgentTeamBudget } from './agentTeamBudget'; -import { agentTeamOverview, agentTeamRouteSummary, agentTeamTaskHistory } from './agentTeamViews'; +import { agentTeamRouteSummary, agentTeamTaskHistory } from './agentTeamViews'; import { agentTeamProfileSelection, resolveNewMemberProfiles, resolveAgentTeamProfiles } from './agentTeamProfiles'; import { writeWorkerProject } from './workerProject'; import { agentTeamRequestSchema as request, agentTeamToolDefinition as teamTool, - agentTeamMemberOperations as memberOperations, agentTeamArgumentFeedback, agentTeamMessageRouteFeedback, - agentTeamOperationAllowed, legacyHelperSubmissionSchema } from './agentTeamTool'; + agentTeamArgumentFeedback, agentTeamOperationAllowed, legacyHelperSubmissionSchema } from './agentTeamTool'; import type { ModelRequestGate } from '../runtime/modelRequest'; import { LeanEnvironmentHealthCheckError } from '../runtime/leanHealthCheck'; +import { writeLibraryAccess } from './libraryAccess'; import { prepareAgentTeamWorkspace } from './agentTeamWorkspace'; import { AgentTeamNativeControl, nativeSpawnHistory, nativeTeamAssignmentMessage, type NativeTeamAcceptedChild, type NativeTeamSpawn } from './agentTeamNative'; import { IncrementalHelperRejection, landVerifiedHelpers } from './incrementalHelpers'; @@ -45,7 +45,7 @@ import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './so import { portfolioRouteIdSchema, type RetiredRoute, type routeRetirementSchema } from './routeControl'; type LiveWorker = { session?: MathAgentSession; task: Promise; abort: AbortController; routeAbort: AbortController; - cancelledTaskId?: string; admittedTurnId?: string; runSettled?: boolean }; + admittedTurnId?: string; runSettled?: boolean }; const CHECKPOINT_CLOSE_GRACE_MS = 10_000; /** Native AgentControl carries an attributed message rather than a separate route field. */ @@ -88,16 +88,17 @@ export class AgentResearchTeam { readonly archive: AgentTeamState; readonly directory: string; private live = new Map(); - private nativeControl?: AgentTeamNativeControl; + private readonly nativeControl: AgentTeamNativeControl; + private readonly operations: AgentTeamOperations; private readonly nativeIdle = new Map(); private readonly failedNominations: TeamFailureCache = new Map(); private readonly nativeStarts = new Map; resolve: (value: NativeTeamAcceptedChild) => void; reject: (error: unknown) => void; accepted: boolean }>(); - private access = new Map(); + private readonly workspaces = new Map }>(); private leadSession?: MathAgentSession; - private waiters = new Set<() => void>(); private stopping = false; private serial: Promise = Promise.resolve(); + private taskSequence = 0; leadAdoptionCheckpoint = false; leadCompletionCheckpoint = false; @@ -110,20 +111,20 @@ export class AgentResearchTeam { save: () => void; emit: (event: string, details?: Record) => void; exclusiveCheck: (operation: () => Promise) => Promise; }) { + if (input.state.agentTeam?.transport !== 'native-agent-control') throw new Error('math_historical_team_requires_pinned_revision'); + this.archive = input.state.agentTeam; this.directory = path.join(path.dirname(input.state.worktree), 'agent-team'); fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 }); fs.mkdirSync(path.join(path.dirname(input.state.worktree), 'team-workspaces'), { recursive: true, mode: 0o700 }); - this.archive = input.state.agentTeam ??= { schema: 'theorem-os.agent-team.v1', workers: [], events: [], - deliveries: [], adoptions: [], operations: [] }; - for (const route of input.state.portfolioExploration?.gate?.retiredRoutes ?? []) { - if (!this.archive.retiredRoutes?.some(item => item.routeId === route.routeId)) - (this.archive.retiredRoutes ??= []).push(route); - } agentTeamStateSchema.parse(this.archive); - let sequence = Math.max(0, ...this.archive.workers.flatMap(worker => worker.tasks.map(task => task.sequence ?? 0))); - for (const worker of this.archive.workers) for (const task of worker.tasks) task.sequence ??= ++sequence; + this.operations = new AgentTeamOperations(this.archive.operations); + for (const worker of this.archive.workers) for (const task of worker.tasks) + this.taskSequence = Math.max(this.taskSequence, task.sequence ?? 0); + for (const worker of this.archive.workers) for (const task of worker.tasks) + task.sequence ??= ++this.taskSequence; this.archive.hostLimits = { maxTurns: Number.isFinite(input.maxTurns) ? input.maxTurns : null, maxTotalTokens: input.maxTotalTokens }; - if (this.nativeAgentControlEnabled) this.nativeControl = new AgentTeamNativeControl(this.archive, { + this.refreshUsage(); + this.nativeControl = new AgentTeamNativeControl(this.archive, { spawn: (request, signal) => this.spawnNative(request, signal), followup: (worker, request, signal) => this.followupNative(worker, request, signal), interrupt: worker => this.interruptNative(worker), @@ -135,43 +136,30 @@ export class AgentResearchTeam { throw new Error('math_team_native_turn_not_dispatched:' + turnId); live.admittedTurnId = turnId; worker.native!.turnId = turnId; worker.native!.status = 'running'; - this.changed(); + this.input.save(); }, - }, () => this.changed()); + }, () => this.input.save(), this.operations); } - get usageRecords() { return this.archive.workers; } get hiddenRoots() { return [this.directory, path.join(path.dirname(this.input.state.worktree), 'team-workspaces')]; } get hasActiveWorkers() { return this.live.size > 0; } - get nativeAgentControlEnabled() { return this.archive.transport === 'native-agent-control'; } - nativeAgentControlOptions(actor = 'lead') { return this.nativeControl?.options(actor); } - fallbackLeadTransport(error: unknown) { - const { state, signal } = this.input; - if (!this.nativeAgentControlEnabled || signal.aborted || this.leadSession || state.threadId || state.writerProcess || - state.usageAccounting?.startedTurns || state.requestUsageAccounting?.startedRequests || this.archive.workers.length) - return; - if (!(error instanceof Error)) return; - if (error.cause instanceof Error && /auth|api[_ -]?key|credential|abort/iu.test(error.cause.message)) return; - const match = /^(math_codex_rpc_failed|math_codex_rpc_timeout)(?::(?:(-?\d+|invalid_code):)?(initialize|thread\/start|theoremos\/agentControl\/(?:capabilities|snapshot)))?$/u.exec(error.message); - const transport = /^(math_codex_transport_closed)(?::[\w:=.-]+)?$/u.exec(error.message); - const backend = /^(math_native_agent_control_(?:backend_required|closed)|math_codex_thread_missing)$/u.exec(error.message); - const reason = (match ?? transport ?? backend)?.[1]; - if (!reason || match?.[2] === '401' || match?.[2] === '403') return; - this.archive.transport = 'host-tools'; - delete this.archive.nativeControl; - this.nativeControl = undefined; - return { from: 'native-agent-control', to: 'host-tools', reason, error: error.message }; + 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'; } + + private assertNativePlanApproved() { + if (!this.mayStartProofWork) + throw new NativeAgentControlInputError('math_team_plan_approval_required: Publish a route with theoremos_team publish_plan and wait for approval before dispatch.'); } - private get budgetControlsEnabled() { return this.input.maxTotalTokens > 0 || Number.isFinite(this.input.maxTurns); } setLeadSession(session?: MathAgentSession) { this.leadSession = session; if (session?.nativeConfiguration && this.archive.nativeControl) { this.archive.nativeControl.rootRuntimeConfiguration = session.nativeConfiguration; - this.changed(); + this.input.save(); } } - leadWriterStopped() { this.nativeControl?.writerStopped('lead'); } + leadWriterStopped() { this.nativeControl.writerStopped('lead'); } beginLeadTurn() { this.leadAdoptionCheckpoint = false; @@ -185,6 +173,7 @@ export class AgentResearchTeam { gate.checkpoint = () => { if (base.checkpoint?.()) return true; if ((this.input.state.requestUsageAccounting?.pendingRequests ?? 0) > 0) return false; + if (!this.mayStartProofWork && planApprovalStatus(this.input.state) === 'pending') return true; if (this.archive.completionRequested) { if (!this.leadCompletionCheckpoint) { this.leadCompletionCheckpoint = true; @@ -205,13 +194,11 @@ export class AgentResearchTeam { return gate; } - private changed() { + refreshUsage() { const { state } = this.input; - const records = [state, ...this.usageRecords, ...(state.portfolioExploration?.scouts ?? [])]; + const records = [state, ...this.archive.workers]; state.tokenBudget = buildTokenBudget(this.input.maxTotalTokens, records, state.tokenBudget?.enforcement); state.teamUsage = aggregateUsage(records); - this.input.save(); - for (const wake of this.waiters) wake(); } private event(from: string | null, to: string, kind: AgentTeamState['events'][number]['kind'], message: string, @@ -220,52 +207,31 @@ export class AgentResearchTeam { objectiveRevision?: number; progressId?: string } = {}) { const item = { sequence: (this.archive.events.at(-1)?.sequence ?? 0) + 1, from: from ?? 'host', to, kind, at: Date.now(), text: message.slice(0, 16000), ...extra }; - this.archive.events.push(item); this.changed(); + this.archive.events.push(item); this.input.save(); this.input.emit('team_event', { ...item }); // Saved events, including completion and checked deliveries, all use the // native advisory queue. Amendments supply their effective context separately. - if (from !== to && kind !== 'amended') { - if (this.nativeControl) { - if (kind !== 'completed' && kind !== 'interrupted') - void this.nativeControl.advisory(from, to, 'Mathematical host update (advisory):\n' + canonicalMathJson(item)).catch(() => {}); - } else void this.notify(to, item); - } + if (from !== to && kind !== 'completed' && kind !== 'interrupted') + void this.nativeControl.advisory(from, to, 'Mathematical host update (advisory):\n' + canonicalMathJson(item)).catch(() => {}); return item; } - private async notify(actor: string, event: AgentTeamState['events'][number]): Promise { - const session = actor === 'lead' ? this.leadSession : this.live.get(actor)?.session; - if (!session?.notify) return false; - try { - await session.notify((event.kind === 'amended' ? 'Lead assignment amendment (effective objective):\n' : - 'Team update (advisory):\n') + canonicalMathJson(event), - event.kind === 'amended' ? undefined : { mode: 'advisory' }); - return true; - } - catch { return false; } - } - tools(actor = 'lead'): MathAgentTools { - const transport = this.archive.transport ?? 'host-tools'; - const definition = teamTool(actor, this.budgetControlsEnabled, transport); + const definition = teamTool(actor, this.reviewPlan); return { definitions: [definition], call: async (name, args, context) => { context.signal.throwIfAborted(); if (name !== definition.name) throw new Error('math_team_tool_unknown'); const parsed = args && typeof args === 'object' && 'operation' in args && args.operation === 'submit_helpers' ? legacyHelperSubmissionSchema.safeParse(args) : request.safeParse(args); - if (!parsed.success) return agentTeamArgumentFeedback(actor, this.budgetControlsEnabled, args, parsed.error, transport); + if (!parsed.success) return agentTeamArgumentFeedback(actor, args, parsed.error, this.reviewPlan); const received = parsed.data; const operation = received.operation === 'submit_helpers' ? { ...received, operation: 'submit' as const, helpersOnly: true } : received; - if (this.nativeAgentControlEnabled && !agentTeamOperationAllowed(actor, this.budgetControlsEnabled, transport, operation.operation)) + if (!agentTeamOperationAllowed(actor, operation.operation, this.reviewPlan)) return { ok: false, error: 'math_team_native_operation_required', hint: 'Use an advertised mathematical host operation. Native collaboration tools manage this run\'s agent transport.' }; - if (['poll', 'wait'].includes(operation.operation)) { - return this.receive(actor, 'after' in operation ? operation.after ?? 0 : 0, - operation.operation === 'wait' ? operation.timeoutMs ?? 30000 : 0, context.signal); - } if (operation.operation === 'history') { if (operation.agentId) this.worker(operation.agentId); return agentTeamTaskHistory(this.archive, operation); @@ -273,10 +239,10 @@ export class AgentResearchTeam { if (operation.operation === 'route_summary') return agentTeamRouteSummary(this.archive, operation); const key = canonicalMathJson([actor, context.threadId, context.turnId, context.callId]); const digest = mathDigest(canonicalMathJson(received)); - // Serializing mutations also prevents concurrent spawn/adoption calls from racing capacity or source checks. + // Serialize host operations that mutate shared evidence. const apply = this.serial.then(async () => { context.signal.throwIfAborted(); - const prior = this.archive.operations.find(item => item.key === key); + const prior = this.operations.get(key); if (prior) { if (prior.digest !== digest) throw new Error('math_team_call_changed'); if (operation.operation === 'inspect' && operation.changeIndex !== undefined && @@ -289,7 +255,7 @@ export class AgentResearchTeam { // Successful pages can be replayed from the content-addressed delivery; avoid storing its whole source twice. const fixedPage = operation.operation === 'inspect' && operation.changeIndex !== undefined && result !== null && typeof result === 'object' && 'ok' in result && result.ok === true; - this.archive.operations.push({ key, digest, result: fixedPage ? 'read-fixed-delivery-page' : result }); this.changed(); + this.operations.append({ key, digest, result: fixedPage ? 'read-fixed-delivery-page' : result }); this.input.save(); return result; }); this.serial = apply.catch(() => {}); @@ -351,7 +317,7 @@ export class AgentResearchTeam { } // Save the entire route decision before signalling workers. Reuse of an // affected member still goes through its stopped-writer barrier. - this.changed(); + this.input.save(); for (const entry of interrupted) { const reason = new Error('math_team_route_retired:' + input.routeId); entry.routeAbort.abort(reason); @@ -395,7 +361,7 @@ export class AgentResearchTeam { } } this.live.get(worker.id)?.abort.abort(signal.reason); - this.changed(); + this.input.save(); }; signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort(); @@ -407,6 +373,7 @@ export class AgentResearchTeam { private async spawnNative(request: NativeTeamSpawn, signal: AbortSignal): Promise { this.assertNativeDispatchOpen(signal); + this.assertNativePlanApproved(); const { model, effort } = this.input.state; const config = request.bootstrap.config as Record; if (config.model !== model || config.reasoningEffort !== effort) @@ -418,7 +385,7 @@ export class AgentResearchTeam { const leaf = request.agentPath.slice('/root/'.length); const id = /^[A-Za-z0-9_-]{1,64}$/u.test(leaf) && leaf !== 'lead' ? leaf : 'native-' + mathDigest(request.agentPath).slice(0, 24); if (this.archive.workers.some(worker => worker.id === id)) throw new Error('math_team_agent_exists'); - const task = this.newTask(message, undefined, { routeId }); + const task = this.newTask(message, undefined, routeId); const seedCommit = git(this.input.state.worktree, ['rev-parse', 'HEAD']); const spawnHistory = nativeSpawnHistory(request.bootstrap); const worker: AgentTeamWorker = { id, role: 'researcher', @@ -434,12 +401,13 @@ export class AgentResearchTeam { spawnHistory === 'parent-history' && item.kind === 'inspected' && !adopted.has(item.deliveryId)) .map(item => ({ ...item, kind: item.kind === 'adopted' ? 'adopted' : 'possible-via-parent' })); this.archive.workers.push(worker); this.nativeStart(worker); - this.enqueue(worker, task); + worker.tasks.push(task); this.input.save(); this.launch(worker); return this.waitNativeStart(worker, signal, true); } private async followupNative(worker: AgentTeamWorker, initialInput: Record, signal: AbortSignal): Promise { this.assertNativeDispatchOpen(signal); + this.assertNativePlanApproved(); const { message, routeId } = nativeTaskRoute(nativeTeamAssignmentMessage(initialInput.input as Record)); this.assertRouteAvailable(routeId); if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); @@ -466,7 +434,7 @@ export class AgentResearchTeam { if (result.accepted !== true || typeof result.submissionId !== 'string') throw new Error('math_team_native_input_not_accepted'); if (task.cancelRequested) throw new Error('math_team_task_not_running'); this.updateNativeFollowup(task, message, profiles?.evidence ?? task.profileEvidence); - const accepted = this.nativeControl!.accepted(worker, active.session, worker.native!.turnId!); + const accepted = this.nativeControl.accepted(worker, active.session, worker.native!.turnId!); return { ...accepted, submissionId: result.submissionId }; } if (active) await active.task; @@ -475,7 +443,7 @@ export class AgentResearchTeam { if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); if ((worker.status as string) === 'stopped') throw new Error('math_team_agent_stopped'); this.assertRouteAvailable(routeId); - const saved = worker.tasks.toReversed().find(task => ['paused', 'interrupted', 'queued'].includes(task.status) && + const saved = worker.tasks.findLast(task => ['paused', 'interrupted', 'queued'].includes(task.status) && !task.cancelRequested && !task.deliveryId && (routeId === undefined || routeId === task.routeId)); // There is one captured input per native writer. Do not replace it while // a different queued task still needs it. @@ -485,9 +453,9 @@ export class AgentResearchTeam { this.assertRouteAvailable(saved.routeId); this.updateNativeFollowup(saved, message, profiles?.evidence); saved.pauseRequested = undefined; saved.status = 'queued'; saved.error = undefined; - } else worker.tasks.push(this.newTask(message, profiles?.evidence, { routeId })); + } else worker.tasks.push(this.newTask(message, profiles?.evidence, routeId)); worker.native!.initialInput = initialInput; - this.changed(); + this.input.save(); this.nativeStart(worker); this.launch(worker); return this.waitNativeStart(worker, signal); @@ -515,10 +483,10 @@ export class AgentResearchTeam { const session = this.nativeIdle.get(worker.id); if (!session) return; await stopProofWriter({ session, record: worker, workerId: worker.id, - close: async () => { await session.close(); this.nativeIdle.delete(worker.id); }, save: () => this.changed(), + close: async () => { await session.close(); this.nativeIdle.delete(worker.id); }, save: () => this.input.save(), deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }) }); - this.nativeControl?.writerStopped(worker.id); - worker.writerProcess = undefined; this.changed(); + this.nativeControl.writerStopped(worker.id); + worker.writerProcess = undefined; this.input.save(); } private async loadNative(worker: AgentTeamWorker) { @@ -527,8 +495,10 @@ export class AgentResearchTeam { if (this.live.has(worker.id) || worker.writerStopUnconfirmed || worker.pendingDelivery || ['checking', 'integrating', 'stopping'].includes(worker.activity ?? '')) throw new Error('math_team_native_member_busy'); if (!worker.threadId) throw new Error('math_team_native_child_not_bound'); - if (!this.access.has(worker.id)) await this.prepare(worker); - const { state } = this.input, access = this.access.get(worker.id)!; + const access = this.workspaces.get(worker.id)?.access ?? await this.prepare(worker); + if (this.live.has(worker.id)) throw new Error('math_team_native_member_busy'); + if ((worker.status as string) === 'stopped') throw new Error('math_team_agent_stopped'); + const { state } = this.input; const task = worker.tasks.at(-1)!; const sourceCommit = git(worker.worktree, ['rev-parse', 'HEAD']); const context = buildSkillResearchContext(state.problem, { ...state, ...worker, check: undefined }, { ...access, @@ -547,242 +517,38 @@ export class AgentResearchTeam { isolatedWorkspaceParent: path.dirname(worker.worktree), isolateProcess: true, instructions: context.instructions, signal: this.input.signal, onUsage: () => { throw new Error('math_team_native_idle_usage'); } }).catch(error => { - recordUnconfirmedWriterStartup(worker, error, () => this.changed()); + recordUnconfirmedWriterStartup(worker, error, () => this.input.save()); throw error; }); this.nativeIdle.set(worker.id, session); if (worker.native && session.nativeConfiguration) worker.native.runtimeConfiguration = session.nativeConfiguration; - worker.writerProcess = session.processIdentity; this.changed(); + worker.writerProcess = session.processIdentity; this.input.save(); if ((worker.status as string) === 'stopped') await this.closeNativeIdle(worker); } - private snapshot(actor: string, after: number) { - const visible = this.archive.events.filter(item => item.sequence > after && item.to === actor); - const events: AgentTeamState['events'] = []; - let bytes = 0; - for (const event of visible) { - const size = Buffer.byteLength(canonicalMathJson(event)); - if (events.length && (events.length >= 8 || bytes + size > 128 * 1024)) break; - events.push(event); bytes += size; - } - return { ok: true, cursor: visible.length > events.length ? events.at(-1)!.sequence : this.archive.events.at(-1)?.sequence ?? 0, - events, - ...agentTeamOverview(this.input.state, { focusAgentId: actor, budget: this.budget() }), - }; - } - - private budget(task?: AgentTeamTask) { - return projectAgentTeamBudget(this.budgetInput(task)); - } - - private budgetInput(task?: AgentTeamTask) { - const worker = task && this.archive.workers.find(worker => worker.tasks.includes(task)); - return { tokenBudget: this.input.state.tokenBudget!, maxTurns: this.input.maxTurns, turns: this.input.state.turns, - leadReserve: this.archive.leadReserve, - task: task ? { id: task.id, budget: task.budget, turns: task.turns } : undefined, - taskUsage: this.input.state.taskUsage, - taskUsageUnavailable: Boolean(task && worker && (worker.requestUsageAccounting?.receipts?.some(receipt => - receipt.taskId === task.id && receipt.status === 'missing') || !worker.requestUsageAccounting && worker.usageAccounting?.incomplete)) }; - } - - private async receive(actor: string, after: number, timeoutMs: number, signal: AbortSignal) { - if (!this.archive.events.some(item => item.sequence > after && item.to === actor) && timeoutMs && !this.stopping) { - await new Promise((resolve, reject) => { - let timer: ReturnType; - const cleanup = () => { clearTimeout(timer); this.waiters.delete(wake); signal.removeEventListener('abort', abort); }; - const wake = () => { if (this.stopping || this.archive.events.some(item => item.sequence > after && item.to === actor)) { cleanup(); resolve(); } }; - const abort = () => { cleanup(); reject(signal.reason ?? new Error('math_team_wait_cancelled')); }; - timer = setTimeout(() => { cleanup(); resolve(); }, timeoutMs); - this.waiters.add(wake); signal.addEventListener('abort', abort, { once: true }); - if (signal.aborted) abort(); else wake(); - }); - } - return this.snapshot(actor, after); - } - private async perform(actor: string, operation: z.infer): Promise { if (this.stopping || this.input.signal.aborted) throw new Error('math_team_stopped'); - if (actor !== 'lead' && !memberOperations.has(operation.operation)) - throw new Error('math_team_lead_operation_required'); - // Unlimited runs must not acquire model-invented task caps. - if (!this.budgetControlsEnabled && (operation.operation === 'budget' || - (operation.operation === 'spawn' || operation.operation === 'assign') && Object.keys(operation.budget ?? {}).length > 0)) - throw new Error('math_team_budget_not_configured'); + if (!this.mayStartProofWork && ['adopt', 'finish', 'retire_route'].includes(operation.operation)) + this.assertNativePlanApproved(); switch (operation.operation) { - case 'coordinate': { - // Compatibility for pinned historical host-tool clients; a note has no scheduling effect. - const coordination = this.archive.coordination = { decision: operation.decision, reason: operation.reason, - nextStep: operation.nextStep, revision: (this.archive.coordination?.revision ?? 0) + 1, at: Date.now(), - startedRequests: this.input.state.requestUsageAccounting?.startedRequests ?? 0, - eventSequence: this.archive.events.at(-1)?.sequence ?? 0 }; - this.changed(); - return { ok: true, coordination, advisory: true }; - } - case 'spawn': { - this.assertRouteAvailable(operation.routeId); - if (operation.agentId === 'lead' || this.archive.workers.some(item => item.id === operation.agentId)) - throw new Error('math_team_agent_exists'); - if (this.occupiedAgentSlots() >= this.input.maxAgents - 1) - throw new Error('math_team_capacity_exceeded'); - const task = this.newTask(operation.message, undefined, operation); - const worktree = path.join(path.dirname(this.input.state.worktree), 'team-workspaces', operation.agentId); - const seedCommit = git(this.input.state.worktree, ['rev-parse', 'HEAD']); - const worker: AgentTeamWorker = { id: operation.agentId, role: 'researcher', worktree, seedCommit, - status: 'preparing', phase: 'prepared', turns: 0, tasks: [], cursor: 0 }; - this.archive.workers.push(worker); this.changed(); - worker.exposures = structuredClone((this.archive.leadExposures ?? []).filter(item => item.kind === 'adopted')); - return this.enqueue(worker, task); - } - case 'assign': { - this.assertRouteAvailable(operation.routeId); - const worker = this.worker(operation.agentId); - if (worker.status === 'stopped') throw new Error('math_team_agent_stopped'); - return this.enqueue(worker, this.newTask(operation.message, this.memberProfiles(operation.message, worker).evidence, operation)); - } - case 'amend': { - const worker = this.worker(operation.agentId), task = worker.tasks.find(task => task.id === operation.taskId); - if (!task) throw new Error('math_team_task_unknown'); - if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); - if (!['queued', 'running', 'paused'].includes(task.status) || task.cancelRequested) - throw new Error('math_team_task_not_amendable'); - if (task.declarations || worker.pendingDelivery?.taskId === task.id) throw new Error('math_team_submission_pending'); - const profiles = this.memberProfiles(operation.message, worker); - (task.objectiveHistory ??= []).push({ revision: task.objectiveRevision ?? 1, message: task.message, - workKind: task.workKind, at: Date.now(), reason: operation.reason, profileEvidence: task.profileEvidence }); - task.message = operation.message; task.objectiveRevision = (task.objectiveRevision ?? 1) + 1; - task.workKind = operation.workKind ?? task.workKind; task.profileEvidence = profiles.evidence; - const assignment = { - instruction: 'This replaces the objective of the named task. Retain its draft and assess earlier progress against this revision. Other tasks are unchanged.', - taskId: task.id, objectiveRevision: task.objectiveRevision, objective: task.message, - workKind: task.workKind, reason: operation.reason, profileEvidence: profiles.evidence }; - const event = this.event('lead', worker.id, 'amended', 'Lead amended this task: ' + operation.reason, - { taskId: task.id, objectiveRevision: task.objectiveRevision }); - // The entire profile section can exceed the ordinary event preview; notify with - // the full assignment while durable history retains its source identities. - if (task.status === 'running') void this.notify(worker.id, { ...event, text: canonicalMathJson(assignment) + '\n' + profiles.section.text }); - return { ok: true, agentId: worker.id, taskId: task.id, objectiveRevision: task.objectiveRevision, - workKind: task.workKind, profileEvidence: profiles.evidence, notification: task.status === 'running' ? 'queued' : 'saved-inbox' }; - } - case 'progress': { - if (actor === 'lead') throw new Error('math_team_child_operation_required'); - const worker = this.worker(actor), task = worker.tasks.find(task => task.status === 'running'); - if (!task || task.cancelRequested || !this.live.has(actor)) throw new Error('math_team_task_not_running'); - if (operation.objectiveRevision !== (task.objectiveRevision ?? 1)) throw new Error('math_team_objective_revision_changed'); - const knowledgeUses = operation.knowledgeUses?.map(use => { - const source = task.profileEvidence?.sources.find(source => source.file + '#' + source.anchor === use.anchor); - if (!source) throw new Error('math_team_knowledge_anchor_not_loaded:' + use.anchor); - return { ...use, digest: source.digest }; - }); - const progress = { id: crypto.randomUUID(), at: Date.now(), objectiveRevision: task.objectiveRevision ?? 1, - kind: operation.kind, summary: operation.summary, nextStep: operation.nextStep, - evidenceRefs: operation.evidenceRefs, knowledgeUses }; - (task.progress ??= []).push(progress); - this.event(actor, 'lead', 'progress', canonicalMathJson(progress), - { taskId: task.id, sourceTaskId: task.id, objectiveRevision: progress.objectiveRevision, progressId: progress.id, - dispatchResearchRevision: worker.dispatchResearchRevision }); - return { ok: true, taskId: task.id, objectiveRevision: progress.objectiveRevision, progressId: progress.id, - advisory: true, delivery: 'saved-inbox' }; - } + case 'publish_plan': + if (!this.reviewPlan) throw new Error('math_plan_approval_not_required'); + return publishNativeApprovalPlan(this.input.state, operation, this.input.save, this.input.emit); case 'finish': { - this.archive.completionRequested = { at: Date.now(), summary: operation.summary }; this.changed(); + this.archive.completionRequested = { at: Date.now(), summary: operation.summary }; this.input.save(); return { ok: true, status: 'pending-writer-stop', originalProblemAcceptance: 'not-assessed', instruction: 'Sources and notes should already be saved. Return now. The host also checkpoints before the next model request, confirms writer shutdown, freezes sources and independently checks all original targets.' }; } - case 'budget': { - const targeted = operation.agentId !== undefined || operation.taskId !== undefined || operation.budget !== undefined; - if (!operation.leadReserve && !targeted || targeted && (!operation.agentId || !operation.taskId || !operation.budget)) - throw new Error('math_team_budget_arguments_invalid'); - const worker = targeted ? this.worker(operation.agentId!) : undefined; - const task = worker?.tasks.find(task => task.id === operation.taskId); - if (targeted && !task) throw new Error('math_team_task_unknown'); - if (task && !['queued', 'running', 'paused'].includes(task.status)) throw new Error('math_team_task_budget_finished'); - if (operation.leadReserve) this.archive.leadReserve = operation.leadReserve; - if (task) task.budget = operation.budget; - this.event('lead', 'lead', 'budget-updated', 'Lead adjusted task allowance or integration reserve.', { taskId: task?.id }); - return { ok: true, budget: this.budget(task) }; - } case 'yield': { if (actor === 'lead') throw new Error('math_team_child_operation_required'); const worker = this.worker(actor), task = worker.tasks.find(task => task.status === 'running'); if (!task || task.cancelRequested || !this.live.has(actor)) throw new Error('math_team_task_not_running'); if (task.declarations) throw new Error('math_team_submission_pending'); task.pauseRequested ??= { at: Date.now(), kind: 'handoff', reason: operation.reason }; - this.changed(); + this.input.save(); return { ok: true, taskId: task.id, status: 'pending-writer-stop', instruction: 'Save your draft and notes, then return. Lead can adopt needed results and resume this same task after writer shutdown.' }; } - case 'resume': { - const worker = this.worker(operation.agentId), task = worker.tasks.find(task => task.id === operation.taskId); - if (!task) throw new Error('math_team_task_unknown'); - this.assertRouteAvailable(task.routeId); - if (worker.status === 'stopped') throw new Error('math_team_agent_stopped'); - if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); - if (task.status !== 'paused') throw new Error('math_team_task_not_paused'); - const admission = agentTeamChildAdmission(this.budgetInput(task), 'turn'); - if (admission.allowed === false) return { ok: false, error: admission.reason, budget: this.budget(task) }; - task.pauseRequested = undefined; task.status = 'queued'; task.error = undefined; - this.event('lead', worker.id, 'resumed', 'Lead resumed the same saved task.', { taskId: task.id }); - this.launch(worker); - return { ok: true, agentId: worker.id, taskId: task.id, status: 'queued' }; - } - case 'publish': { - const researchState = { revision: (this.archive.researchState?.revision ?? 0) + 1, - summary: operation.summary, publishedAt: Date.now(), assignmentRevision: this.archive.workers.reduce((sum, worker) => sum + worker.tasks.reduce((total, task) => total + (task.objectiveRevision ?? 1), 0), 0) }; - this.archive.researchState = researchState; - for (const recipient of ['lead', ...this.archive.workers.filter(worker => worker.status !== 'stopped').map(worker => worker.id)]) { - this.event('lead', recipient, 'research-updated', operation.summary, { researchRevision: researchState.revision }); - } - return { ok: true, researchState: { ...researchState, advisory: true } }; - } - case 'cancel': { - const worker = this.worker(operation.agentId); - if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); - const task = worker.tasks.find(item => item.id === operation.taskId); - if (!task) throw new Error('math_team_task_unknown'); - if (task.cancelRequested) return { ok: true, agentId: worker.id, taskId: task.id, - status: task.status === 'running' ? 'stopping' : task.status, - replacementTaskId: task.cancelRequested.replacementTaskId }; - if (!['queued', 'running', 'paused'].includes(task.status)) throw new Error('math_team_task_not_cancellable'); - const active = this.live.get(worker.id); - if (task.status === 'running' && !active) throw new Error('math_team_task_not_running'); - const replacement: AgentTeamTask | undefined = operation.replacement - ? this.newTask(operation.replacement, this.memberProfiles(operation.replacement, worker).evidence, { routeId: task.routeId }) : undefined; - if (replacement && worker.native) worker.native.initialInput = { author: '/root', - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: replacement.message } }, startOptions: {} }; - task.cancelRequested = { at: Date.now(), reason: operation.reason, replacementTaskId: replacement?.id }; - if (replacement) worker.tasks.push(replacement); - if (task.status !== 'running') { - task.status = 'cancelled'; task.finishedAt = Date.now(); - this.event('lead', 'lead', 'cancelled', operation.reason ?? 'Queued task cancelled.', { taskId: task.id }); - this.changed(); this.launch(worker); - } else { - this.changed(); - active!.cancelledTaskId = task.id; - worker.activity = 'stopping'; - active!.abort.abort(new Error('math_team_task_cancelled')); - void active!.session?.interrupt().catch(() => {}); - } - return { ok: true, agentId: worker.id, taskId: task.id, - status: task.status === 'cancelled' ? 'cancelled' : 'stopping', replacementTaskId: replacement?.id }; - } - case 'message': { - const feedback = agentTeamMessageRouteFeedback(actor, operation.agentId); - if (feedback) return feedback; - if (operation.agentId !== 'lead') this.worker(operation.agentId); - if (operation.relatedTaskId && !this.archive.workers.some(worker => worker.tasks.some(task => task.id === operation.relatedTaskId))) - throw new Error('math_team_task_unknown'); - if (operation.researchRevision && operation.researchRevision > (this.archive.researchState?.revision ?? 0)) - throw new Error('math_team_research_revision_unknown'); - const sender = actor === 'lead' ? undefined : this.worker(actor); - const sourceTaskId = sender?.tasks.find(task => task.status === 'running')?.id; - const event = this.event(actor, operation.agentId, 'message', operation.message, - { taskId: sourceTaskId, sourceTaskId, relatedTaskId: operation.relatedTaskId, - dispatchResearchRevision: sender?.dispatchResearchRevision, researchRevision: operation.researchRevision }); - const targetSession = operation.agentId === 'lead' ? this.leadSession : this.live.get(operation.agentId)?.session; - // Native delivery is asynchronous; this mutation returns the durable inbox result. - return { ok: true, from: actor, to: operation.agentId, sequence: event.sequence, - delivery: 'saved-inbox', notification: targetSession?.notify ? 'queued' : 'unavailable' }; - } case 'inspect-research': { const reference = this.archive.researchArtifacts?.find(item => item.id === operation.artifactId); if (!reference) throw new Error('math_team_research_unknown'); @@ -829,10 +595,6 @@ export class AgentResearchTeam { const worker = this.worker(actor), task = worker.tasks.find(item => item.status === 'running'); if (!task || task.cancelRequested || task.pauseRequested || !this.live.has(actor)) throw new Error('math_team_task_not_running'); if (task.declarations || task.helperSubmission) throw new Error('math_team_submission_pending'); - if (!this.nativeAgentControlEnabled && operation.objectiveRevision !== undefined && operation.objectiveRevision !== (task.objectiveRevision ?? 1)) - throw new Error('math_team_objective_revision_changed'); - if (!this.nativeAgentControlEnabled && operation.objectiveRevision === undefined && task.objectiveHistory?.length) - throw new Error('math_team_objective_revision_required'); const outside = operation.declarations.filter(declaration => !this.input.state.problem.ownedFiles.includes(declaration.file)); if (outside.length) return { ok: false, error: 'math_agent_team_proof_declaration_outside_ownership', rejectedFiles: [...new Set(outside.map(declaration => declaration.file))], @@ -843,12 +605,12 @@ export class AgentResearchTeam { task.helperSubmission = operation.declarations; task.summary = operation.summary; task.pauseRequested = { at: Date.now(), kind: 'handoff', reason: 'Standalone helper handoff. The assignment remains open.' }; - this.changed(); + this.input.save(); return { ok: true, status: 'pending-writer-stop', taskId: task.id, instruction: 'Save source and notes, then return. The host verifies standalone helpers and the assignment can resume afterward.' }; } task.nomination = { objectiveRevision: task.objectiveRevision ?? 1, objectiveDigest: mathDigest(task.message), workKind: task.workKind }; - task.declarations = operation.declarations; task.summary = operation.summary; this.changed(); + task.declarations = operation.declarations; task.summary = operation.summary; this.input.save(); return { ok: true, status: 'pending-writer-stop', taskId: task.id, instruction: 'Save source and notes, then return. The host checks declarations after confirming writer shutdown.' }; } @@ -867,7 +629,7 @@ export class AgentResearchTeam { if (target.pendingDelivery) throw new Error('math_team_target_delivery_pending'); } const adoption = { id: crypto.randomUUID(), deliveryId: operation.deliveryId, targetId, status: 'queued' as const }; - this.archive.adoptions.push(adoption); this.changed(); + this.archive.adoptions.push(adoption); this.input.save(); if (targetId !== 'lead') this.launch(this.worker(targetId)); return { ok: true, adoption, ...(targetId === 'lead' ? { instruction: 'Sources and notes should already be saved. Return now; the host also releases your writer before the next model request, checks and integrates this delivery, then continues your saved thread.' } : {}) }; @@ -876,16 +638,6 @@ export class AgentResearchTeam { const { operation: _operation, ...retirement } = operation; return this.retireRoute(retirement); } - case 'stop': { - const worker = this.worker(operation.agentId), active = this.live.get(worker.id); - worker.status = 'stopped'; this.changed(); - for (const task of worker.tasks.filter(item => ['queued', 'paused'].includes(item.status))) task.status = 'interrupted'; - worker.activity = active ? 'stopping' : 'idle'; - // Never join a child while holding the tool mutation queue: its final tool callback may be queued here. - if (active) { active.abort.abort(); void active.session?.interrupt().catch(() => {}); } - this.changed(); - return { ok: true, agentId: worker.id, status: active ? 'stopping' : worker.status }; - } default: throw new Error('math_team_operation_invalid'); } } @@ -895,17 +647,17 @@ export class AgentResearchTeam { return delegation?.mode === 'team' ? delegation.personalExperts?.cards : undefined; } private memberProfiles(message: string, worker?: AgentTeamWorker) { - const skill = (worker && this.access.get(worker.id)?.researchSkill) ?? this.input.leadAccess.researchSkill!; + const skill = (worker && this.workspaces.get(worker.id)?.access?.researchSkill) ?? this.input.leadAccess.researchSkill!; return resolveNewMemberProfiles(skill, message, this.expertCards); } private newTask(message: string, profileEvidence = this.memberProfiles(message).evidence, - { budget, workKind, routeId }: Pick = {}): AgentTeamTask { + routeId?: string): AgentTeamTask { this.assertRouteAvailable(routeId); - return { id: crypto.randomUUID(), message, status: 'queued', createdAt: Date.now(), turns: 0, budget, - objectiveRevision: 1, workKind, routeId, + return { id: crypto.randomUUID(), message, status: 'queued', createdAt: Date.now(), turns: 0, + objectiveRevision: 1, routeId, profileEvidence, - sequence: Math.max(0, ...this.archive.workers.flatMap(worker => worker.tasks.map(task => task.sequence ?? 0))) + 1 }; + sequence: ++this.taskSequence }; } private recordExposure(actor: string, reference: AgentTeamState['deliveries'][number], commit: string, @@ -915,23 +667,35 @@ 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.changed(); + this.input.save(); } } - private enqueue(worker: AgentTeamWorker, task: AgentTeamTask) { - worker.tasks.push(task); this.changed(); this.launch(worker); - return { ok: true, agentId: worker.id, taskId: task.id, status: 'queued', - worktree: worker.worktree, seedCommit: worker.seedCommit, - selectedProfiles: task.profileEvidence!.selected, - profileEvidence: task.profileEvidence, objectiveRevision: task.objectiveRevision, workKind: task.workKind, routeId: task.routeId }; + private prepareWorkspace(worker: AgentTeamWorker) { + const existing = this.workspaces.get(worker.id); + if (existing) return existing; + prepareAgentTeamWorkspace({ sourceWorktree: this.input.state.worktree, worktree: worker.worktree, + seedCommit: worker.seedCommit, migrationDirectory: path.join(this.directory, 'workspace-migrations') }); + const workspace: { access?: WorkerAccess; preparation?: Promise } = {}; + this.workspaces.set(worker.id, workspace); + return workspace; + } + + private prepare(worker: AgentTeamWorker): Promise { + const workspace = this.prepareWorkspace(worker); + return workspace.preparation ??= this.prepareAccess(worker).then(access => { + workspace.access = access; + return access; + }, error => { + workspace.preparation = undefined; + throw error; + }); } - private async prepare(worker: AgentTeamWorker) { + private async prepareAccess(worker: AgentTeamWorker): Promise { const { state, leadAccess } = this.input; - prepareAgentTeamWorkspace({ sourceWorktree: state.worktree, worktree: worker.worktree, - seedCommit: worker.seedCommit, migrationDirectory: path.join(this.directory, 'workspace-migrations') }); - if (this.input.prepareWorker) this.access.set(worker.id, await this.input.prepareWorker(worker.id, worker.worktree)); + let access: WorkerAccess; + if (this.input.prepareWorker) access = await this.input.prepareWorker(worker.id, worker.worktree); else { const project = path.join(worker.worktree, state.problem.projectRelative); fs.mkdirSync(path.join(project, '.lake'), { recursive: true }); @@ -939,10 +703,11 @@ export class AgentResearchTeam { const packages = path.join(state.worktree, state.problem.projectRelative, '.lake/packages'); if (fs.existsSync(packages)) bindLeanPackages(project, packages); const skill = prepareResearchSkill(this.input.root, worker.worktree, state.researchSkill!, state.problem); - this.access.set(worker.id, { ...leadAccess, researchSkill: skill, retrievalRoot: project }); + access = { ...leadAccess, researchSkill: skill, retrievalRoot: project }; } + if (access.libraryCatalog) writeLibraryAccess(state.problem, worker.worktree, access.libraryCatalog, false); writeWorkerProject(worker.worktree, state.problem.projectRelative); - this.sourceFeedback(worker); + return access; } /** Invalid drafts stay editable; only stopped-writer source checks can admit them as evidence. */ @@ -975,7 +740,7 @@ export class AgentResearchTeam { if (worker.status !== 'stopped') worker.status = worker.tasks.some(task => task.status === 'paused') ? 'paused' : 'idle'; worker.activity = worker.status === 'paused' ? 'paused' : 'idle'; worker.phase = 'prepared'; worker.error = undefined; - this.changed(); + this.input.save(); } private launch(worker: AgentTeamWorker) { @@ -984,23 +749,28 @@ export class AgentResearchTeam { const entry: LiveWorker = { abort, routeAbort: new AbortController(), task: undefined as unknown as Promise }; this.live.set(worker.id, entry); entry.task = Promise.resolve().then(async () => { - if (!this.access.has(worker.id)) await this.prepare(worker); + const access = await this.prepare(worker); await this.flushHelperSubmissions(worker); if (worker.pendingDelivery) await this.finishDelivery(worker); await this.flushAdoptions(worker.id); while (!this.stopping && !abort.signal.aborted && worker.status !== 'stopped') { // A native followup chooses and supplies input for one particular task. // A parked draft on another route does not block that dispatch. - if (!worker.native && worker.tasks.some(task => task.status === 'paused')) break; const task = worker.tasks.find(item => item.status === 'queued'); if (!task) break; - const admission = agentTeamChildAdmission(this.budgetInput(task), 'turn'); - if (admission.allowed === false) { - this.pauseForBudget(worker, task, admission.reason); break; + const { state, maxTurns } = this.input; + if (!modelDispatchAllowed(state.tokenBudget!)) { + this.pauseForBudget(worker, task, state.tokenBudget!.status === 'usage-unavailable' ? + 'math_model_usage_unavailable' : 'math_total_token_limit'); + break; + } + if (state.turns >= maxTurns) { + this.pauseForBudget(worker, task, 'math_team_total_turn_limit'); + break; } if (this.input.remainingMs() <= 0) break; await this.flushAdoptions(worker.id); - await this.runTask(worker, task, entry); + await this.runTask(worker, task, entry, access); } }).catch(error => { if (!this.stopping && !abort.signal.aborted) { @@ -1019,20 +789,20 @@ export class AgentResearchTeam { firstTask.finishedAt ??= Date.now(); } pending?.reject(new Error(worker.error ?? 'math_team_native_start_failed')); - this.live.delete(worker.id); this.changed(); + this.live.delete(worker.id); this.input.save(); // Per-task interruption consumes this controller. Reuse the member only after runTask has // confirmed shutdown and saved its draft; a global stop or quarantine must never relaunch it. - if ((entry.routeAbort.signal.aborted || entry.cancelledTaskId && worker.tasks.find(task => task.id === entry.cancelledTaskId)?.researchArtifactId) && + if (entry.routeAbort.signal.aborted && worker.tasks.some(task => task.status === 'queued') && modelDispatchAllowed(this.input.state.tokenBudget!) && this.input.remainingMs() > 0 && this.input.state.turns < this.input.maxTurns) this.launch(worker); }); } private async runTask(worker: AgentTeamWorker, task: AgentTeamTask, - entry: Pick) { + entry: Pick, access: WorkerAccess) { entry.admittedTurnId = undefined; entry.runSettled = false; await this.closeNativeIdle(worker); - const { state } = this.input, access = this.access.get(worker.id)!; + const { state } = this.input; const signal = AbortSignal.any([this.input.signal, entry.abort.signal]); if (signal.aborted || task.status !== 'queued' || task.cancelRequested) return; this.assertRouteAvailable(task.routeId); @@ -1046,13 +816,13 @@ export class AgentResearchTeam { task.status = 'running'; task.startedAt ??= Date.now(); task.lastStartedAt = Date.now(); task.finishedAt = undefined; task.summary = undefined; task.error = undefined; task.declarations = undefined; task.nomination = undefined; worker.status = 'running'; worker.activity = 'running'; worker.phase = 'running'; worker.error = undefined; - worker.dispatchResearchRevision = this.archive.researchState?.revision; task.objectiveRevision ??= 1; task.profileEvidence = resolveAgentTeamProfiles(access.researchSkill!, task.message, this.expertCards).evidence; initializeUsageAccounting(worker); - this.changed(); - const usage = new ResearchUsage({ state, research: worker, maxTotalTokens: this.input.maxTotalTokens, - signal, remainingMs: this.input.remainingMs, changed: () => this.changed(), + this.refreshUsage(); + this.input.save(); + const usage = new ResearchUsage({ state, research: worker, + signal, remainingMs: this.input.remainingMs, changed: () => { this.refreshUsage(); this.input.save(); }, emit: (event, details) => this.input.emit(event, { ...details, workerId: worker.id }) }); const sessionId = crypto.randomUUID(); const callbacks = usage.bindSession(sessionId, () => entry.session?.lastInputTokens); @@ -1086,14 +856,12 @@ export class AgentResearchTeam { }, }); const requestGate: NonNullable = identity => { - const admission = agentTeamChildAdmission(this.budgetInput(task), 'request'); - if (admission.allowed === false) { + const admission = callbacks.requestGate!(identity); + if (admission.allowed === false && (admission.reason === 'math_model_usage_unavailable' || admission.reason === 'math_total_token_limit')) { task.pauseRequested ??= { at: Date.now(), kind: 'budget', reason: admission.reason }; - this.changed(); - return { allowed: false, reason: admission.reason === 'math_model_usage_unavailable' || - admission.reason === 'math_total_token_limit' ? admission.reason : 'math_model_request_stopped' }; + this.input.save(); } - return callbacks.requestGate!(identity); + return admission; }; requestGate.beforeRequest = callbacks.requestGate?.beforeRequest; requestGate.checkpoint = () => { @@ -1110,7 +878,6 @@ export class AgentResearchTeam { }; const teamRole = { id: worker.id, role: 'worker' as const }; const teamAssignment = { taskId: task.id, message: task.message, sourceCommit }; - const { inboxThrough } = agentTeamWorkerSection(state, teamRole, teamAssignment); const turnTiming = teamTurnTiming(this.input.maxTurnMs); const context = buildSkillResearchContext(state.problem, { ...state, ...worker, check: undefined }, { ...access, root: this.input.root, tools: this.input.modules.M4.tools, worktree: worker.worktree, taskText: this.input.taskText, @@ -1118,11 +885,12 @@ export class AgentResearchTeam { sourceFeedback, executionLimits: { ...turnTiming, remainingRunMs: this.input.remainingMs } }); writeOwnedDeclarationIndex(state.problem, worker.worktree); + const tools = this.tools(worker.id); const nativeOptions = this.nativeAgentControlOptions(worker.id); if (nativeOptions?.bootstrap) nativeOptions.bootstrap.hostOverrides = { ...(nativeOptions.bootstrap.hostOverrides as Record | undefined), cwd: worker.worktree, developerInstructions: context.instructions, - dynamicTools: this.tools(worker.id).definitions.map(definition => ({ type: 'function', ...definition })), + dynamicTools: tools.definitions.map(definition => ({ type: 'function', ...definition })), workspaceRelocation: { from: (nativeOptions.bootstrap.config as Record).cwd, to: worker.worktree }, }; let completed = false, started = false, reserved = false, writerStopped = false; @@ -1130,7 +898,8 @@ export class AgentResearchTeam { try { if (!modelDispatchAllowed(state.tokenBudget!) || this.input.remainingMs() <= 0 || state.turns >= this.input.maxTurns) throw new Error('math_team_dispatch_stopped'); - state.turns++; worker.turns++; reserved = true; this.changed(); + state.turns++; worker.turns++; reserved = true; + this.refreshUsage(); this.input.save(); entry.session = await this.input.modules.M1.open({ executable: this.input.executable, profile: this.input.profile, workspace: worker.worktree, proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative), leanHealthCheck: { executable: process.execPath, arguments: [path.join(this.input.root, 'out/main/check-lean.js'), @@ -1138,8 +907,8 @@ export class AgentResearchTeam { model: state.model, effort: state.effort, threadId: worker.threadId, environment: { ...access.environment, ...access.harnessEnvironment, DEEPSCIENTIST_MATH_WORKER_ID: worker.id, DEEPSCIENTIST_MATH_WORKER_WORKTREE: worker.worktree }, - skills: [access.researchSkill!], tools: this.tools(worker.id), - ...(nativeOptions ? { nativeAgentControl: nativeOptions } : {}), + skills: [access.researchSkill!], tools, + nativeAgentControl: nativeOptions, hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), this.directory, state.worktree, git(state.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir'])], isolatedWorkspaceParent: path.dirname(worker.worktree), isolateProcess: true, @@ -1149,30 +918,31 @@ export class AgentResearchTeam { worker.lastActivity = { ...activity, at: Date.now() }; if (activity.event === 'item_completed' && activity.itemType === 'contextCompaction') milestone.compacted(); if (activity.event === 'lean_environment_ready') this.input.emit('lean_environment_ready', { workerId: worker.id, health: activity.health }); - this.changed(); + this.input.save(); }, ...callbacks, requestGate }); usage.sessionOpened(entry.session); if (worker.native && entry.session.nativeConfiguration) worker.native.runtimeConfiguration = entry.session.nativeConfiguration; if (entry.session.processIdentity) worker.writerProcess = entry.session.processIdentity; - worker.threadId = entry.session.threadId || worker.threadId; this.changed(); + worker.threadId = entry.session.threadId || worker.threadId; this.input.save(); signal.throwIfAborted(); if (!modelDispatchAllowed(state.tokenBudget!) || this.input.remainingMs() <= 0) throw new Error('math_team_dispatch_stopped'); - usage.begin(undefined, task.id); task.turns = (task.turns ?? 0) + 1; started = true; this.changed(); + task.turns = (task.turns ?? 0) + 1; + usage.begin(task.id); started = true; const status = await entry.session.run(context.message, task.id, worker.worktree, activeTurnId => { turnId = activeTurnId; milestone.start(); - worker.threadId = entry.session!.threadId; worker.cursor = inboxThrough; usage.turnStarted(turnId); this.changed(); - if (this.nativeControl) { - if (worker.threadId !== worker.native!.threadId) throw new Error('math_team_native_start_identity_changed'); - const accepted = this.nativeControl.accepted(worker, entry.session!, turnId); - const pending = this.nativeStarts.get(worker.id); - if (pending) { pending.accepted = true; pending.resolve(accepted); } - } + worker.threadId = entry.session!.threadId; + worker.cursor = context.inboxThrough ?? worker.cursor; + usage.turnStarted(turnId); this.input.save(); + if (worker.threadId !== worker.native!.threadId) throw new Error('math_team_native_start_identity_changed'); + const accepted = this.nativeControl.accepted(worker, entry.session!, turnId); + const pending = this.nativeStarts.get(worker.id); + if (pending) { pending.accepted = true; pending.resolve(accepted); } }); if ((status === 'checkpoint' || milestoneCheckpoint) && !task.declarations) { task.pauseRequested ??= milestoneCheckpoint ? { at: Date.now(), kind: 'handoff', reason: 'math_soft_slice_checkpoint' } : { at: Date.now(), kind: 'budget', reason: 'math_team_turn_checkpoint' }; - this.changed(); + this.input.save(); } completed = ['completed', 'submitted'].includes(status) || status === 'checkpoint' && task.declarations !== undefined; outcome = completed ? 'completed' : status === 'failed' ? 'failed' : 'interrupted'; @@ -1181,7 +951,7 @@ export class AgentResearchTeam { } catch (error) { outcome = signal.aborted || error instanceof Error && error.message === 'math_team_dispatch_stopped' ? 'interrupted' : 'failed'; task.error = error instanceof Error ? error.message : 'math_team_worker_failed'; - if (recordUnconfirmedWriterStartup(worker, error, () => this.changed())) throw error; + if (recordUnconfirmedWriterStartup(worker, error, () => this.input.save())) throw error; if (error instanceof LeanEnvironmentHealthCheckError) this.input.emit('lean_environment_unavailable', { workerId: worker.id, health: error.health }); } finally { @@ -1191,18 +961,21 @@ export class AgentResearchTeam { try { if (entry.session) { const current = entry.session; - worker.activity = 'stopping'; this.changed(); + worker.activity = 'stopping'; this.input.save(); if (signal.aborted && !closingSession) await current.interrupt().catch(() => {}); await stopProofWriter({ session: current, record: worker, workerId: worker.id, close: async () => { await closeSession(current); entry.session = undefined; usage.sessionClosed(sessionId); }, - save: () => this.changed(), deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }) }); - this.nativeControl?.writerStopped(worker.id); + save: () => this.input.save(), deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }) }); + this.nativeControl.writerStopped(worker.id); worker.writerProcess = undefined; } writerStopped = !worker.writerStopUnconfirmed; } finally { if (started) usage.finish(completed); - else if (reserved) { state.turns--; worker.turns--; } + else if (reserved) { + state.turns--; worker.turns--; + this.refreshUsage(); + } if (writerStopped) { if ((milestoneCheckpoint || milestone.requested && completed) && !task.declarations) task.pauseRequested ??= { at: Date.now(), kind: 'handoff', reason: milestoneCheckpoint @@ -1222,7 +995,7 @@ export class AgentResearchTeam { // finished task with an unsaved draft for a fully archived result. this.saveResearch(worker, task); } - this.changed(); + this.input.save(); } } access.assertHarnessCurrent?.(); @@ -1250,7 +1023,7 @@ export class AgentResearchTeam { summary: teamTaskResearchSummary(task), status: task.status }); if (!this.archive.researchArtifacts?.some(item => item.id === reference.id)) (this.archive.researchArtifacts ??= []).push(reference); task.researchArtifactId = reference.id; - this.changed(); + this.input.save(); } private pauseForBudget(worker: AgentTeamWorker, task: AgentTeamTask, reason: string) { @@ -1275,8 +1048,9 @@ export class AgentResearchTeam { const task = worker.tasks.find(item => item.helperSubmission); if (!task || this.input.signal.aborted) return; if (task.cancelRequested || worker.status === 'stopped') { - task.helperSubmission = undefined; this.changed(); return; + task.helperSubmission = undefined; this.input.save(); return; } + const access = this.workspaces.get(worker.id)?.access ?? await this.prepare(worker); const nominations = task.helperSubmission!; const local = this.live.get(worker.id)?.routeAbort.signal; const signal = local ? AbortSignal.any([this.input.signal, local]) : this.input.signal; @@ -1284,7 +1058,7 @@ export class AgentResearchTeam { signal.throwIfAborted(); if (worker.writerStopUnconfirmed || this.live.get(worker.id)?.session || this.nativeIdle.has(worker.id)) throw new Error('math_writer_stop_unconfirmed:' + worker.id); - this.access.get(worker.id)?.assertHarnessCurrent?.(); + access.assertHarnessCurrent?.(); }; const { state } = this.input; try { @@ -1327,7 +1101,7 @@ export class AgentResearchTeam { path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json'), declarationCount: delivery.declarations.length, summary: task.summary?.slice(0, 200) }); task.helperSubmission = undefined; - this.changed(); + this.input.save(); const signatures = result.helpers.slice(0, 8).map(({ file, qualifiedName, type }) => ({ file, qualifiedName, type: type.slice(0, 240) })); const notice = 'Verified ' + result.helpers.length + ' standalone helpers at ' + delivery.commit + '.\n' + canonicalMathJson(signatures) + '\nUse inspect for the full signature list. The host applies these sources before your next turn. ' + @@ -1353,11 +1127,12 @@ export class AgentResearchTeam { const pending = worker.pendingDelivery; if (!pending) return; if (worker.writerStopUnconfirmed || this.live.get(worker.id)?.session) throw new Error('math_writer_stop_unconfirmed:' + worker.id); + const access = this.workspaces.get(worker.id)?.access ?? await this.prepare(worker); const task = worker.tasks.find(item => item.id === pending.taskId)!; // Native turn interruption preserves a nomination. Retirement withdraws it. const local = this.live.get(worker.id)?.routeAbort.signal; const signal = local ? AbortSignal.any([this.input.signal, local]) : this.input.signal; - worker.activity = 'checking'; worker.phase = 'checking'; this.changed(); + 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 => { @@ -1367,11 +1142,11 @@ export class AgentResearchTeam { 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'); - pending.commit = commit; pending.sourceDigest = digest; this.changed(); + pending.commit = commit; pending.sourceDigest = digest; this.input.save(); const delivery = await this.input.exclusiveCheck(() => checkAgentTeamProofDelivery({ state: this.input.state, - failureCache: this.nativeAgentControlEnabled ? this.failedNominations : undefined, + failureCache: this.failedNominations, agentId: worker.id, worktree: worker.worktree, seedCommit: pending.seedCommit, declarations: pending.declarations, inferredHelperTypes, - env: this.access.get(worker.id)!.environment, signal, timeoutMs: this.input.proofTimeoutMs, + env: access.environment, signal, timeoutMs: this.input.proofTimeoutMs, // Older checkpoints do not record when a nomination was made relative to a followup. provenance: { ...(task.nomination ?? (!task.objectiveHistory?.length && (task.objectiveRevision ?? 1) === 1 ? { objectiveRevision: 1, workKind: task.workKind } : {})), taskId: task.id, @@ -1396,7 +1171,7 @@ export class AgentResearchTeam { if (task.cancelRequested && signal.aborted) { worker.phase = 'prepared'; worker.activity = 'idle'; - this.changed(); + this.input.save(); return; } // Keep infrastructure failures pending; deterministic proof feedback is correctable by another explicit assignment. @@ -1409,7 +1184,7 @@ export class AgentResearchTeam { } else throw error; } worker.activity = worker.tasks.some(task => task.status === 'paused') ? 'paused' : 'idle'; - worker.phase = 'prepared'; this.changed(); + worker.phase = 'prepared'; this.input.save(); } /** Called only after the receiving writer has stopped; no running writer is overwritten. */ @@ -1422,21 +1197,27 @@ export class AgentResearchTeam { const worktree = target?.worktree ?? state.worktree; const helpers = 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; + 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) this.archive.adoptions.push({ id: crypto.randomUUID(), - deliveryId: delivery.id, targetId, status: 'queued' }); - this.changed(); + 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(); } - for (const adoption of this.archive.adoptions.filter(item => item.targetId === targetId && ['queued', 'integrating'].includes(item.status))) { + for (const adoption of queued) { 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.changed(); + this.input.save(); try { const result = await this.input.exclusiveCheck(() => integrateAgentTeamProofDelivery({ state, delivery, worktree, - expectedCommit: adoption.expectedCommit!, env: (target ? this.access.get(targetId) : this.input.leadAccess)!.environment, + expectedCommit: adoption.expectedCommit!, env: access.environment, signal: this.input.signal, timeoutMs: this.input.proofTimeoutMs, evidenceDirectory: path.join(this.directory, 'proofs'), assertWriterStopped: () => { if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed)) @@ -1465,25 +1246,28 @@ export class AgentResearchTeam { if (!correctableProofFailure(error) && !/^math_task_integration_(?:conflict|missing_context|missing_declaration)$/u.test(adoption.error) && adoption.error !== 'math_agent_team_proof_source_changed') { // Leave the same expectedCommit queued for crash-safe retry; infrastructure failures are not proof feedback. - this.changed(); throw error; + this.input.save(); throw error; } adoption.status = 'failed'; this.event(null, 'lead', 'failed', adoption.error, { deliveryId: adoption.deliveryId }); } if (target) target.activity = target.tasks.some(task => task.status === 'paused') ? 'paused' : 'idle'; - this.changed(); + this.input.save(); } } async restore() { assertAgentTeamProcessesStopped(this.input.state); - this.nativeControl?.writerStopped('lead', 'recovery-process-check'); + // Reconcile lost usage receipts before saving any recovered writer or launching tasks. + for (const worker of this.archive.workers) initializeUsageAccounting(worker); + this.refreshUsage(); + this.nativeControl.writerStopped('lead', 'recovery-process-check'); this.input.state.writerProcess = undefined; for (const worker of this.archive.workers) { - initializeUsageAccounting(worker); worker.writerProcess = undefined; - if (worker.native) this.nativeControl?.writerStopped(worker.id, 'recovery-process-check'); - await this.prepare(worker); + if (worker.native) this.nativeControl.writerStopped(worker.id, 'recovery-process-check'); + // Isolate legacy Git worktrees before Lead can access the shared repository. + this.prepareWorkspace(worker); const queued = worker.tasks.filter(task => task.status === 'queued'); if (worker.native && queued.length > 1) { // Older checkpoints could accept another queue entry after a blocked @@ -1494,6 +1278,8 @@ export class AgentResearchTeam { } } for (const task of worker.tasks.filter(item => item.status === 'running')) { + // Restore the pinned project metadata before freezing a stopped writer's draft. + await this.prepare(worker); task.status = task.cancelRequested ? 'cancelled' : task.pauseRequested ? 'paused' : 'interrupted'; if (task.status === 'paused') task.pausedAt = Date.now(); else task.finishedAt = Date.now(); // Submit is already a durable nomination. A crash can precede the turn's @@ -1516,7 +1302,7 @@ export class AgentResearchTeam { // Historical checkpoints could settle a completion or interruption without // registering its nomination. Recover only the last writer at its fixed HEAD. if (!worker.pendingDelivery && worker.pendingSourceBase) { - const task = worker.tasks.toReversed().find(task => task.seedCommit !== undefined); + const task = worker.tasks.findLast(task => task.seedCommit !== undefined); if (task && ['completed', 'interrupted'].includes(task.status) && task.declarations?.length && !task.deliveryId && !task.cancelRequested && task.pauseRequested?.kind !== 'handoff' && task.seedCommit === worker.pendingSourceBase && task.sourceCommit && task.sourceCommit === git(worker.worktree, ['rev-parse', 'HEAD']) && @@ -1524,7 +1310,7 @@ export class AgentResearchTeam { .map(file => path.join(this.input.state.problem.projectRelative, file))])) { worker.pendingDelivery = { taskId: task.id, seedCommit: task.seedCommit ?? worker.pendingSourceBase, declarations: this.deliveryDeclarations(worker, task) }; - this.changed(); + this.input.save(); } } await this.flushHelperSubmissions(worker); @@ -1535,18 +1321,17 @@ export class AgentResearchTeam { await this.flushAdoptions(worker.id); if (worker.tasks.some(task => task.status === 'queued')) this.launch(worker); } - this.changed(); + this.input.save(); } async close() { this.stopping = true; this.leadSession = undefined; - for (const wake of this.waiters) wake(); for (const entry of this.live.values()) { entry.abort.abort(); void entry.session?.interrupt().catch(() => {}); } await this.serial; await Promise.allSettled([...this.live.values()].map(entry => entry.task)); await Promise.allSettled([...this.nativeIdle.keys()].map(id => this.closeNativeIdle(this.worker(id)))); - this.changed(); + this.input.save(); const unconfirmed = this.archive.workers.find(worker => worker.writerStopUnconfirmed); if (unconfirmed) throw new Error('math_writer_stop_unconfirmed:' + unconfirmed.id); } diff --git a/src/solver/agentTeamBudget.ts b/src/solver/agentTeamBudget.ts index 77897969..63c20766 100644 --- a/src/solver/agentTeamBudget.ts +++ b/src/solver/agentTeamBudget.ts @@ -1,4 +1,4 @@ -import { modelDispatchAllowed, reportedTotalTokens, type TokenBudget } from './usageBudget'; +import { reportedTotalTokens, type TokenBudget } from './usageBudget'; /** Limits are cumulative across every turn of the same task, including yields and resumes. */ export type AgentTeamAllowance = Readonly<{ tokens?: number; turns?: number }>; @@ -14,12 +14,6 @@ export type AgentTeamBudgetInput = Readonly<{ taskUsageUnavailable?: boolean; }>; -export type AgentTeamBudgetStopReason = 'math_total_token_limit' | 'math_model_usage_unavailable' | - 'math_team_total_turn_limit' | 'math_team_lead_token_reserve' | 'math_team_lead_turn_reserve' | - 'math_team_task_token_limit' | 'math_team_task_turn_limit'; -export type AgentTeamChildAdmission = Readonly<{ allowed: true }> | - Readonly<{ allowed: false; reason: AgentTeamBudgetStopReason }>; - const remaining = (limit: number | undefined, used: number) => limit === undefined || limit === Infinity ? null : Math.max(0, limit - used); @@ -68,33 +62,3 @@ export function projectAgentTeamBudget(input: AgentTeamBudgetInput) { } } : {}), }; } - -/** - * Call with "turn" before reserving a new child turn and with "request" before each - * upstream request. The current turn has already consumed its turn allowance at request - * admission; reaching that turn cap must not prevent the turn's own requests from running. - * This helper applies only to children. Lead uses the ordinary global allowance. - */ -export function agentTeamChildAdmission(input: AgentTeamBudgetInput, - stage: 'turn' | 'request' = 'turn'): AgentTeamChildAdmission { - if (!modelDispatchAllowed(input.tokenBudget)) return { allowed: false, - reason: input.tokenBudget.status === 'usage-unavailable' ? 'math_model_usage_unavailable' : 'math_total_token_limit' }; - const projection = projectAgentTeamBudget(input); - const task = projection.task; - if (stage === 'turn' && projection.remaining.turns !== null && projection.remaining.turns <= 0) - return { allowed: false, reason: 'math_team_total_turn_limit' }; - if (task?.budget.tokens !== undefined && - task?.usageUnavailable) - return { allowed: false, reason: 'math_model_usage_unavailable' }; - if (task && task.remaining.tokens !== null && task.remaining.tokens <= 0) - return { allowed: false, reason: 'math_team_task_token_limit' }; - if (projection.childRemaining.tokens !== null && projection.childRemaining.tokens <= 0) - return { allowed: false, reason: 'math_team_lead_token_reserve' }; - if (stage === 'turn') { - if (task && task.remaining.turns !== null && task.remaining.turns <= 0) - return { allowed: false, reason: 'math_team_task_turn_limit' }; - if (projection.childRemaining.turns !== null && projection.childRemaining.turns <= 0) - return { allowed: false, reason: 'math_team_lead_turn_reserve' }; - } - return { allowed: true }; -} diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index a6b75bf0..225a96d7 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -6,53 +6,7 @@ export type AgentTeamRole = Readonly<{ id: string; role: 'lead' | 'worker' }>; export type AgentTeamAssignment = Readonly<{ taskId: string; message: string; sourceCommit: string }>; /** Stable authority and identity; professional profiles live in the pinned skill and current assignment. */ -export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, - transport: 'host-tools' | 'native-agent-control' = 'host-tools'): string { - if (transport === 'native-agent-control') return nativeAgentTeamInstructions(role, maxAgents); - const shared = 'Read the pinned references/parallel-work.md for the theoremos_team interface and collaboration methods. ' + - 'Select domain knowledge for the specific missing concept from references/domain-experts.md and work responsibilities from references/team-roles.md. ' + - 'To select a member profile, start the assignment with an optional Profiles: line of comma-separated IDs or slugs. ' + - 'The host includes selected profiles and locators for collected reading from the pinned Skill; read relevant material on demand and clarify unresolved expertise. ' + - 'Profiles guide the work without changing tools, source permissions or proof acceptance. ' + - 'The published team research summary and fixed-commit research artifacts are advisory; use inspect-research to read an artifact. ' + - 'Team observations contain bounded previews; use history for full task text and the latest research summary, and poll for complete inbox messages. ' + - 'Run without task budgets or a Lead reserve by default; only allocate an explicitly configured finite token or turn allowance. ' + - 'When the host reports finite time limits, leave time for saving source and RESEARCH.md and returning before cutoff. ' + - 'Built-in spawn/fork is disabled. '; - if (role.role === 'lead') return 'You are the Lead of an Agent-organized research team; your agentId is lead. ' + - `At most ${maxAgents} agents including you may be available. ` + - 'Use the injected Lead profile from the pinned Skill for delegation, task ownership and integration decisions. ' + - 'Team updates enter your ongoing native conversation after the current response and tools. Poll the durable inbox for complete addressed messages. ' + - 'Use cancel to withdraw or replace an individual assignment. Tag route-specific work with routeId and use retire_route with the obstruction and evidence refs to stop the entire branch. ' + - 'Use amend to change a current task objective or responsibility while retaining its task ID, draft and history; message alone does not amend it. ' + - 'Mark workKind when the distinction matters: independent-reconstruction, assembly, review, research or proof. ' + - 'Inspection and adoption record source exposure; preserve original authorship and describe assembly or exposed review accurately. ' + - 'Use resume to continue a paused task without replacing its identity. ' + - 'Spawn and assign return immediately; poll/wait receives individual arrivals while other agents continue. ' + - 'If portfolio scouting produced no report, split concrete unanswered questions from the frozen statement and spawn useful independent work as soon as capacity is free. ' + - 'Adopt a checked delivery when its interface fits. Use inspect for exact declarations and evidence when needed. ' + - 'Save sources and notes before requesting adoption into your worktree, then return. ' + - 'A pending adoption also makes the host hand off automatically before the next model request; ' + - 'after confirmed writer shutdown it rechecks and integrates the delivery, then continues your saved thread. ' + - 'Save all original proofs and return for independent host checking. Use finish to request early handoff. ' + shared + '\n'; - return `You are a mathematical researcher and Lean proof writer; your agentId is ${JSON.stringify(role.id)}, and your coordinator is lead. ` + - 'Carry out the current Lead assignment; the frozen original problem supplies its background and constraints. ' + - 'Use the selected professional knowledge and choose your methods independently within that assignment. A requested specialization is a task focus and can change on a later assignment. ' + - 'Your own worktree, notes and native thread persist across assignments. Read relevant source definitions, exact types and current host feedback before relying on older conversation. ' + - 'Lead and peers do not automatically see your files or conversation. Use message for self-contained findings, questions and disagreements, and poll/wait for addressed updates. ' + - 'For message, agentId is the recipient: use agentId:"lead" to report to Lead, or the peer ID to contact a peer. The host binds your sender identity; self-addressed messages are rejected. ' + - 'Message Lead at the first usable result, local probe or blocker, including the exact claim, assumptions and available evidence; a whole-target assignment does not require waiting for the complete proof to report. ' + - 'Use progress for a useful finding, probe result, blocker or route change. Give the exact result and next step; optional knowledgeUses names a supplied source anchor actually used and its concrete application. These reports remain advisory. ' + - 'For a formal delivery, save exact declarations, call submit and return for host checking. Set helpersOnly:true to share standalone helpers while keeping the assignment open. ' + - 'For a host tool failure, message Lead with the command and diagnostic; use a documented fallback when available and distinguish that result from host checking. ' + - 'Use inspect to read peer deliveries and inspect-research for their saved findings; ask Lead to adopt useful declarations into your worktree. ' + - 'When the same task needs a dependency or Lead decision, save your draft and notes, call yield with the reason, then return to release writing; Lead can resume it later. ' + - 'Submit and yield also checkpoint automatically before the next model request, after the current response and tools settle. Save before calling them. ' + - 'An amended task carries a new objective revision. Follow it, assess previous findings against it, and retain the draft. ' + - 'Only Lead can spawn, assign, amend, cancel, budget, resume, publish, adopt, finish, stop members or retire routes. Write only in your own workspace. ' + shared + '\n'; -} - -function nativeAgentTeamInstructions(role: AgentTeamRole, maxAgents: number): string { +export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number): string { const shared = 'This run uses native AgentControl collaboration with isolated writer workspaces. ' + 'Call collaboration tools directly in their exposed namespace, not through functions.exec. A child\'s final answer is automatically delivered to its parent. ' + 'Native tools target canonical agent paths or native thread IDs. Mathematical host operations use the workspace member IDs in the team observation. ' + @@ -64,7 +18,7 @@ function nativeAgentTeamInstructions(role: AgentTeamRole, maxAgents: number): st 'This team run explicitly authorizes you to spawn and coordinate useful child agents through the native collaboration tools. ' + `At most ${maxAgents} agents including you may be available. ` + 'As soon as you identify a proof step you can advance, work on it in your Lean files. Keep writing the consuming argument or another unassigned gap while members work. ' + - 'If portfolio scouting produced no report, use native spawn_agent for concrete independent gaps found in the frozen statement. ' + + 'Use native spawn_agent for concrete independent gaps found in the frozen statement. ' + 'Omit model and reasoning_effort when calling spawn_agent so members inherit the frozen run configuration. ' + 'If several goals share a mathematical foundation, assign and check its small Lean interfaces before dispatching the consuming goals. ' + 'For a native spawn or followup, put an optional Route: ROUTE_ID line first, then an optional Profiles: line of comma-separated IDs or slugs, then the assignment. Use theoremos_team retire_route with the obstruction and evidence refs to stop a refuted route. ' + @@ -108,9 +62,7 @@ export function agentTeamWorkerSection(state: Readonly, role: Ag const inbox = agentTeamInboxPreview(state.agentTeam!, role.id, worker.cursor); const inboxThrough = inbox.through; return { inboxThrough, section: { id: 'agent-team-assignment', kind: 'assignment', - text: (state.agentTeam?.transport === 'native-agent-control' - ? 'Current native task instructions (latest accepted followup; earlier instructions remain in native history; frozen problem and source constraints still apply):\n' - : 'Current team assignment (replaces earlier assignments; messages are advisory updates):\n') + JSON.stringify({ + text: 'Current native task instructions (latest accepted followup; earlier instructions remain in native history; frozen problem and source constraints still apply):\n' + JSON.stringify({ agentId: role.id, coordinator: 'lead', taskId: current.id, objective: assignment.message, objectiveRevision: current.objectiveRevision ?? 1, workKind: current.workKind, ...(current.routeId ? { routeId: current.routeId } : {}), diff --git a/src/solver/agentTeamNative.ts b/src/solver/agentTeamNative.ts index a06ff56d..95208d94 100644 --- a/src/solver/agentTeamNative.ts +++ b/src/solver/agentTeamNative.ts @@ -2,6 +2,7 @@ import crypto from 'node:crypto'; import type { NativeAgentControlConnection, NativeAgentControlOptions, NativeAgentControlRequest } from '../runtime/nativeAgentControl'; import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; import type { AgentTeamState, AgentTeamWorker } from './agentTeamState'; +import { AgentTeamOperations } from './agentTeamOperations'; type Json = Record; export type NativeTeamAcceptedChild = { agent: Json; configSnapshot: Json; submissionId: string }; @@ -60,7 +61,7 @@ export class AgentTeamNativeControl { private readonly updates = new Map>(); constructor(private readonly archive: AgentTeamState, private readonly lifecycle: AgentTeamNativeLifecycle, - private readonly save: () => void) { + private readonly save: () => void, private readonly operations = new AgentTeamOperations(archive.operations)) { // Queue ownership transferred to a lost runtime is uncertain, never a read receipt. for (const mail of archive.nativeControl?.mailbox ?? []) if (mail.status === 'accepted') mail.status = 'uncertain'; } @@ -305,45 +306,48 @@ export class AgentTeamNativeControl { return this.perform(actor, request, signal).then(result => ({ result })); const key = 'native:' + request.operationId; const digest = mathDigest(canonicalMathJson([request.sessionId, expected, request.operation, payload])); - const receipt = this.archive.operations.find(item => item.key === key); + const receipt = this.operations.get(key); if (receipt) return receipt.digest !== digest ? Promise.reject(new Error('math_team_call_changed')) : Promise.resolve(object(receipt.result)); const pending = this.pending.get(key); if (pending) return pending.digest === digest ? pending.promise : Promise.reject(new Error('math_team_call_changed')); - const apply = this.perform(actor, request, signal).then(result => { + const operation = request.operation === 'spawn' + ? this.spawn(actor, request, digest, signal) + : this.perform(actor, request, signal); + const apply = operation.then(result => { const response = { result }; - this.archive.operations.push({ key, digest, result: response }); this.save(); return response; + this.operations.append({ key, digest, result: response }); this.save(); return response; }).finally(() => this.pending.delete(key)); this.pending.set(key, { promise: apply, digest }); return apply; } + private async spawn(actor: string, request: NativeAgentControlRequest, requestDigest: string, signal: AbortSignal) { + if (actor !== 'lead') throw new Error('math_team_lead_operation_required'); + signal.throwIfAborted(); + const { payload, threadId: caller } = request; + const source = nativeSource(payload.source), agentPath = text(source.agent_path); + if (!/^\/root\/[^/]+$/u.test(agentPath) || source.parent_thread_id !== caller) + throw new Error('math_team_native_flat_team_required'); + const existing = this.archive.workers.find(worker => worker.native?.agentPath === agentPath); + if (existing) { + const native = existing.native!; + if (native.spawnOperationId !== request.operationId) throw new Error('math_team_agent_exists'); + if (native.spawnRequestDigest !== requestDigest) throw new Error('math_team_call_changed'); + if (native.agent && native.configSnapshot && native.submissionId) + return { agent: native.agent, configSnapshot: native.configSnapshot, submissionId: native.submissionId }; + throw new Error('math_team_native_spawn_unconfirmed'); + } + const threadId = crypto.randomUUID(), input = object(payload.input), bootstrap = { ...object(payload.bootstrap), threadId }; + const initialInput = { author: this.identity(caller).path, input, startOptions: object(payload.startOptions ?? {}) }; + return this.lifecycle.spawn({ sessionId: request.sessionId, threadId, agentPath, parentThreadId: caller, + operationId: request.operationId, requestDigest, bootstrap, initialInput, message: nativeTeamAssignmentMessage(input) }, signal); + } + private async perform(actor: string, request: NativeAgentControlRequest, signal: AbortSignal): Promise { const payload = request.payload, state = this.archive.nativeControl!, caller = request.threadId; const leadOnly = () => { if (actor !== 'lead') throw new Error('math_team_lead_operation_required'); }; switch (request.operation) { case 'resolve': return { threadId: this.target(payload.target) }; - case 'spawn': { - leadOnly(); signal.throwIfAborted(); - const source = nativeSource(payload.source), agentPath = text(source.agent_path); - if (!/^\/root\/[^/]+$/u.test(agentPath) || source.parent_thread_id !== caller) - throw new Error('math_team_native_flat_team_required'); - const existing = this.archive.workers.find(worker => worker.native?.agentPath === agentPath); - const requestDigest = mathDigest(canonicalMathJson([request.sessionId, caller, request.operation, payload])); - if (existing) { - const native = existing.native!; - if (native.spawnOperationId === request.operationId) { - if (native.spawnRequestDigest !== requestDigest) throw new Error('math_team_call_changed'); - if (native.agent && native.configSnapshot && native.submissionId) - return { agent: native.agent, configSnapshot: native.configSnapshot, submissionId: native.submissionId }; - throw new Error('math_team_native_spawn_unconfirmed'); - } - throw new Error('math_team_agent_exists'); - } - const threadId = crypto.randomUUID(), input = object(payload.input), bootstrap = { ...object(payload.bootstrap), threadId }; - const initialInput = { author: this.identity(caller).path, input, startOptions: object(payload.startOptions ?? {}) }; - return this.lifecycle.spawn({ sessionId: state.sessionId, threadId, agentPath, parentThreadId: caller, - operationId: request.operationId, requestDigest, bootstrap, initialInput, message: nativeTeamAssignmentMessage(input) }, signal); - } case 'send': { const target = this.target(payload.target), input = object(payload.input); if (input.kind !== 'message') throw new Error('math_team_native_message_required'); @@ -379,8 +383,11 @@ export class AgentTeamNativeControl { } case 'list': { const prefix = payload.pathPrefix == null ? undefined : text(payload.pathPrefix); - return { agents: [...this.connections.keys()].filter(id => !prefix || this.identity(id).path === prefix || - this.identity(id).path.startsWith(prefix + '/')).flatMap(id => { + return { agents: [...this.connections.keys()].filter(id => { + if (!prefix) return true; + const agentPath = this.identity(id).path; + return agentPath === prefix || agentPath.startsWith(prefix + '/'); + }).flatMap(id => { const snapshot = this.snapshot(id); return snapshot.kind === 'loaded' ? [snapshot.agent] : []; }) }; } diff --git a/src/solver/agentTeamOperations.ts b/src/solver/agentTeamOperations.ts new file mode 100644 index 00000000..8cd88ae7 --- /dev/null +++ b/src/solver/agentTeamOperations.ts @@ -0,0 +1,22 @@ +import type { AgentTeamState } from './agentTeamState'; + +type OperationReceipt = AgentTeamState['operations'][number]; + +/** One index for both callers. The append-only array remains the checkpoint format. */ +export class AgentTeamOperations { + private readonly byKey = new Map(); + + constructor(private readonly receipts: OperationReceipt[]) { + for (const receipt of receipts) { + // Match the old find() behavior for checkpoints with repeated keys. + if (!this.byKey.has(receipt.key)) this.byKey.set(receipt.key, receipt); + } + } + + get(key: string): OperationReceipt | undefined { return this.byKey.get(key); } + + append(receipt: OperationReceipt): void { + this.receipts.push(receipt); + if (!this.byKey.has(receipt.key)) this.byKey.set(receipt.key, receipt); + } +} diff --git a/src/solver/agentTeamProof.ts b/src/solver/agentTeamProof.ts index 6f730c10..abaabdae 100644 --- a/src/solver/agentTeamProof.ts +++ b/src/solver/agentTeamProof.ts @@ -8,7 +8,7 @@ import { bindLeanPackages } from '../math/leanDiagnostics'; import { formalVerificationToolIdentity } from '../math/verifier'; import { hasDeterministicLeanFailure, proofReuseEnvironment } from './proofReuse'; import { applyTaskChanges, ownedSourceDigest, taskChanges, type DeclarationChange } from './cooperativeProof'; -import { checkDeclarationArtifacts, DeclarationArtifactCheckError, DeclarationSubmissionError, declarationSubmissionSchema, validateDeclarationArtifact, +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'; @@ -51,13 +51,10 @@ const provenanceSchema = z.object({ objectiveRevision: z.number().int().positive spawnHistory: teamSpawnHistory.optional(), exposures: z.array(z.object({ deliveryId: hash, agentId: z.string().min(1), taskId: z.string().min(1), commit: commitHash, kind: teamExposureKind, at: z.string().min(1) }).strict()).optional() }).strict(); -// The host can combine prior checked peer inputs with a member's <=32-declaration submission. -// Individual declarations keep the public validation; only the internal collection is larger. -const teamDeclarations = z.array(declarationSubmissionSchema.shape.declarations.element).min(1); const deliverySchema = z.object({ schema: z.literal('theorem-os.agent-team-proof-delivery.v1'), id: hash, ...identitySchema, agentId: z.string().trim().min(1).max(1000), sourceWorktree: z.string().min(1), seedCommit: commitHash, commit: commitHash, sourceDigest: hash, - declarations: teamDeclarations, artifacts: z.array(z.unknown()).min(1), + declarations: teamDeclarationListSchema, artifacts: z.array(z.unknown()).min(1), changes: z.array(z.object({ file: z.string(), name: z.string(), before: z.string().optional(), after: z.string(), beforeName: z.string().optional(), afterName: z.string().optional(), tail: z.string().optional() }).strict()), imports: z.array(z.object({ file: z.string(), module: z.string() }).strict()), @@ -188,19 +185,39 @@ function importEvidenceCommit(input: IntegrationInput, commit: string): void { importAgentTeamCommit(archive, input.worktree, commit); } +/** Reuse committed bytes only within one delivery inspection. */ +function readDeliverySources(worktree: string, projectRelative: string) { + const sources = new Map(); + return (revision: string, file: string) => { + const key = revision + '\0' + file; + let source = sources.get(key); + if (source === undefined) { + source = committedSource(worktree, revision, `${projectRelative}/${file}`); + sources.set(key, source); + } + return source; + }; +} + /** Every changed declaration must be named and independently checked; metadata never widens source ownership. */ -function deliveryPatch(state: DeclarationArtifactIdentity, worktree: string, seedCommit: string, commit: string, - declarations: DeclarationSubmission['declarations']) { - const { problem } = state; +function deliveryPatch(problem: DeclarationArtifactIdentity['problem'], worktree: string, seedCommit: string, commit: string, + declarations: DeclarationSubmission['declarations'], readSource = readDeliverySources(worktree, problem.projectRelative)) { if (declarations.some(declaration => !problem.ownedFiles.includes(declaration.file))) return fail('declaration_outside_ownership'); git(worktree, ['merge-base', '--is-ancestor', seedCommit, commit]); if (problem.ownedFiles.some(file => !file.endsWith('.lean') && - committedSource(worktree, seedCommit, `${problem.projectRelative}/${file}`) !== - committedSource(worktree, commit, `${problem.projectRelative}/${file}`))) return fail('undeclared_source_change'); - const changes = taskChanges(problem, worktree, commit, undefined, { seedCommit }); + readSource(seedCommit, file) !== readSource(commit, file))) return fail('undeclared_source_change'); + const changes = taskChanges(problem, worktree, commit, undefined, { seedCommit }, readSource); + const changeKey = (file: string, name: string) => `${file}\0${name}`; + const firstChanges = new Map(); + // A declaration can have both a body change and a later reorder entry. + for (const change of changes) { + const key = changeKey(change.file, change.name); + if (!firstChanges.has(key)) firstChanges.set(key, change); + } + const keysByFile = new Map>(); const declared = new Set(declarations.map(declaration => { - const source = committedSource(worktree, commit, `${problem.projectRelative}/${declaration.file}`); + const source = readSource(commit, declaration.file); let location: ReturnType; try { location = locateKnowledgeDeclaration(source, declaration.name); } catch (error) { @@ -208,23 +225,28 @@ function deliveryPatch(state: DeclarationArtifactIdentity, worktree: string, see return fail('declaration_missing'); throw error; } - const name = leanDeclarationKeys(source).get(location.startOffset); + let keys = keysByFile.get(declaration.file); + if (!keys) { + keys = leanDeclarationKeys(source); + keysByFile.set(declaration.file, keys); + } + const name = keys.get(location.startOffset); if (!name) return fail('declaration_missing'); - const change = changes.find(item => item.file === declaration.file && item.name === name); + const key = changeKey(declaration.file, name), change = firstChanges.get(key); if (declaration.kind === 'definition' && (!change || change.before !== undefined)) throw new DeclarationSubmissionError('math_agent_team_definition_must_be_new:' + declaration.name); if (change?.before && change.before !== change.after) { - const prior = committedSource(worktree, seedCommit, `${problem.projectRelative}/${declaration.file}`); + const prior = readSource(seedCommit, declaration.file); if (locateKnowledgeDeclaration(prior, declaration.name).kind === 'definition') throw new DeclarationSubmissionError('math_agent_team_cannot_replace_definition:' + declaration.name); } - return `${declaration.file}\0${name}`; + return key; })); - if (declared.size !== declarations.length || changes.some(change => !declared.has(`${change.file}\0${change.name}`))) + if (declared.size !== declarations.length || changes.some(change => !declared.has(changeKey(change.file, change.name)))) return fail('undeclared_source_change'); const imports = problem.ownedFiles.filter(file => file.endsWith('.lean')).flatMap(file => { - const before = solverProofImports(problem, committedSource(worktree, seedCommit, `${problem.projectRelative}/${file}`)); - const after = solverProofImports(problem, committedSource(worktree, commit, `${problem.projectRelative}/${file}`)); + const before = solverProofImports(problem, readSource(seedCommit, file)); + const after = solverProofImports(problem, readSource(commit, file)); if (before.some(module => !after.includes(module))) return fail('import_removed'); return after.filter(module => !before.includes(module)).map(module => ({ file, module })); }); @@ -232,32 +254,23 @@ function deliveryPatch(state: DeclarationArtifactIdentity, worktree: string, see } function frozenSource(input: CheckInput, worktree: string, commit: string): () => void { - const identity = canonicalMathJson(identityOf(input.state)); + const { state } = input, { problem } = state; + const identity = canonicalMathJson(identityOf(state)); return () => { - input.signal.throwIfAborted(); input.assertWriterStopped(); assertSolverSources(input.state.problem, worktree); - if (canonicalMathJson(identityOf(input.state)) !== identity) return fail('run_identity_changed'); + input.signal.throwIfAborted(); input.assertWriterStopped(); assertSolverSources(problem, worktree); + if (canonicalMathJson(identityOf(state)) !== identity) return fail('run_identity_changed'); if (git(worktree, ['rev-parse', 'HEAD']) !== commit || git(worktree, ['status', '--porcelain', '--', - ...input.state.problem.ownedFiles.map(file => path.join(input.state.problem.projectRelative, file))])) + ...problem.ownedFiles.map(file => path.join(problem.projectRelative, file))])) return fail('source_changed'); }; } -/** Delta/duplicate checks cover the whole delivery; each batch still receives fresh ordinary declaration checks. */ -async function checkTeamDeclarationArtifacts(input: Parameters[0]) { - const artifacts: DeclarationArtifact[] = []; - for (let offset = 0; offset < input.declarations.length; offset += 32) { - artifacts.push(...await checkDeclarationArtifacts({ ...input, allowAuxiliaryDefinitions: true, - declarations: input.declarations.slice(offset, offset + 32) })); - } - return artifacts; -} - /** Called only after the child writer has stopped. No mutable child files become proof evidence. */ export async function checkAgentTeamProofDelivery(input: CheckInput & { agentId: string; worktree: string; seedCommit: string; declarations: DeclarationSubmission['declarations']; provenance?: AgentTeamProofProvenance; failureCache?: TeamFailureCache; inferredHelperTypes?: string[]; }): Promise { - const declarations = teamDeclarations.parse(input.declarations); + const declarations = teamDeclarationListSchema.parse(input.declarations); const agentId = deliverySchema.shape.agentId.parse(input.agentId); commitHash.parse(input.seedCommit); assertMathCanonicalPath(input.worktree); input.signal.throwIfAborted(); input.assertWriterStopped(); @@ -265,7 +278,7 @@ export async function checkAgentTeamProofDelivery(input: CheckInput & { if (input.worktree === problem.workspace) return fail('worktree_not_isolated'); const commit = commitSolverSources(problem, input.worktree), stable = frozenSource(input, input.worktree, commit); stable(); - const patch = deliveryPatch(input.state, input.worktree, input.seedCommit, commit, declarations); + const patch = deliveryPatch(problem, input.worktree, input.seedCommit, commit, declarations); const project = path.join(input.worktree, problem.projectRelative); const environmentKey = () => { const env = proofReuseEnvironment(project, input.env); @@ -282,7 +295,7 @@ export async function checkAgentTeamProofDelivery(input: CheckInput & { const previous = key && input.failureCache?.get(key); if (previous) throw new ReusedTeamCheckFailure({ commit: previous.commit, agentId: previous.agentId }, previous.error); const artifacts = await checkTeamDeclarationArtifacts({ ...input, commit, declarations, - inferredExpectedTypes: new Set(input.inferredHelperTypes), assertWriterStopped: stable }).catch(error => { + inferredExpectedTypes: new Set(input.inferredHelperTypes), assertFrozenSource: stable }).catch(error => { if (key && input.failureCache && error instanceof DeclarationArtifactCheckError && hasDeterministicLeanFailure(error.verification)) { stable(); if (canonicalMathJson(environmentKey() ?? null) === canonicalMathJson(environment)) { @@ -343,7 +356,7 @@ async function resumeAdoption(input: IntegrationInput, delivery: AgentTeamProofD const checkoutStable = frozenSource(input, checkout, adoption.commit); await checkTeamDeclarationArtifacts({ ...input, worktree: checkout, commit: adoption.commit, declarations: delivery.declarations, inferredExpectedTypes: new Set(delivery.inferredHelperTypes), - assertWriterStopped: () => { stable(); checkoutStable(); } }); + assertFrozenSource: () => { stable(); checkoutStable(); } }); stable(); checkoutStable(); } }); @@ -366,8 +379,9 @@ export async function integrateAgentTeamProofDelivery(input: IntegrationInput): if (pending) importEvidenceCommit(input, pending.commit); return withSolverWorktree(input.worktree, delivery.commit, async frozen => { assertSolverSources(problem, frozen); - if (ownedSourceDigest(problem, frozen, delivery.commit) !== delivery.sourceDigest) return fail('delivery_source_changed'); - const patch = deliveryPatch(input.state, frozen, delivery.seedCommit, delivery.commit, delivery.declarations); + const readSource = readDeliverySources(frozen, problem.projectRelative); + if (ownedSourceDigest(problem, frozen, delivery.commit, readSource) !== delivery.sourceDigest) return fail('delivery_source_changed'); + const patch = deliveryPatch(problem, frozen, delivery.seedCommit, delivery.commit, delivery.declarations, readSource); if (canonicalMathJson(patch) !== canonicalMathJson({ changes: delivery.changes, imports: delivery.imports })) return fail('delivery_patch_changed'); if (pending) return resumeAdoption(input, delivery, pending); @@ -376,10 +390,10 @@ export async function integrateAgentTeamProofDelivery(input: IntegrationInput): if (fs.existsSync(packages)) bindLeanPackages(path.join(checkout, problem.projectRelative), packages); applyTaskChanges(problem, checkout, patch.changes, patch.imports); const commit = commitSolverSources(problem, checkout), checkoutStable = frozenSource(input, checkout, commit); - const assertStopped = () => { stable(); checkoutStable(); }; + const assertAdoptionSources = () => { stable(); checkoutStable(); }; const artifacts = await checkTeamDeclarationArtifacts({ ...input, worktree: checkout, commit, - declarations: delivery.declarations, inferredExpectedTypes: new Set(delivery.inferredHelperTypes), assertWriterStopped: assertStopped }); - assertStopped(); + declarations: delivery.declarations, inferredExpectedTypes: new Set(delivery.inferredHelperTypes), assertFrozenSource: assertAdoptionSources }); + assertAdoptionSources(); const record: AgentTeamProofAdoption = { schema: 'theorem-os.agent-team-proof-adoption.v1', id: '', ...identityOf(input.state), deliveryId: delivery.id, beforeCommit: input.expectedCommit, commit, sourceDigest: ownedSourceDigest(problem, checkout, commit), artifacts }; @@ -388,7 +402,7 @@ export async function integrateAgentTeamProofDelivery(input: IntegrationInput): persist(input, 'adoption-intents', { schema: 'theorem-os.agent-team-proof-adoption-intent.v1', id: intentId(input, delivery), ...identityOf(input.state), worktree: input.worktree, adoption }, input.worktree); // This is checked adoption evidence, not whole-problem acceptance. Journals stay with the primary. - assertStopped(); + assertAdoptionSources(); git(input.worktree, ['merge', '--ff-only', '--no-edit', commit]); return finishAdoption(input, adoption); }); diff --git a/src/solver/agentTeamTool.ts b/src/solver/agentTeamTool.ts index 2cd4c999..93400852 100644 --- a/src/solver/agentTeamTool.ts +++ b/src/solver/agentTeamTool.ts @@ -1,15 +1,10 @@ import { z } from 'zod'; import type { MathAgentToolDefinition } from '../runtime/agentSession'; -import { agentTeamAllowanceSchema, agentTeamReserveSchema, agentTeamWorkKindSchema, agentTeamKnowledgeUseSchema } from './agentTeamState'; import { declarationSubmissionSchema } from './declarationArtifacts'; import { portfolioRouteIdSchema, routeRetirementSchema } from './routeControl'; +import { nativePlanApprovalSchema } from './planApproval'; type Json = Record; -export type AgentTeamTransport = 'host-tools' | 'native-agent-control'; -// Codex 0.171 drops the entire parameters object above this branch count. -const MAX_CODEX_ONEOF_BRANCHES = 16; -const nativeOperations = new Set(['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'yield', 'submit', 'retire_route', 'route_summary']); - const text = z.string().trim().min(1).max(16000); const id = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/u); const submission = z.object({ @@ -21,28 +16,11 @@ export const legacyHelperSubmissionSchema = submission.omit({ helpersOnly: true .extend({ operation: z.literal('submit_helpers') }); export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ - z.object({ operation: z.literal('spawn'), agentId: id, message: text, routeId: portfolioRouteIdSchema.optional(), workKind: agentTeamWorkKindSchema.optional(), budget: agentTeamAllowanceSchema.optional() }).strict(), - z.object({ operation: z.literal('assign'), agentId: id, message: text, routeId: portfolioRouteIdSchema.optional(), workKind: agentTeamWorkKindSchema.optional(), budget: agentTeamAllowanceSchema.optional() }).strict(), - z.object({ operation: z.literal('amend'), agentId: id, taskId: z.string().min(1), message: text, reason: text, - workKind: agentTeamWorkKindSchema.optional() }).strict(), + nativePlanApprovalSchema, z.object({ operation: z.literal('finish'), summary: text }).strict(), - z.object({ operation: z.literal('progress'), objectiveRevision: z.number().int().positive(), kind: z.enum(['finding', 'probe', 'blocker', 'route']), summary: text, - nextStep: text.optional(), evidenceRefs: z.array(z.string().min(1).max(2000)).max(16).optional(), - knowledgeUses: z.array(agentTeamKnowledgeUseSchema).max(16).optional() }).strict(), - z.object({ operation: z.literal('coordinate'), decision: z.enum(['defer', 'continue']), reason: text, nextStep: text }).strict(), - z.object({ operation: z.literal('budget'), leadReserve: agentTeamReserveSchema.optional(), agentId: id.optional(), - taskId: z.string().min(1).optional(), budget: agentTeamAllowanceSchema.optional() }).strict(), z.object({ operation: z.literal('yield'), reason: text }).strict(), - z.object({ operation: z.literal('resume'), agentId: id, taskId: z.string().min(1) }).strict(), z.object({ operation: z.literal('history'), agentId: id.optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(8).optional() }).strict(), - z.object({ operation: z.literal('publish'), summary: text }).strict(), - z.object({ operation: z.literal('cancel'), agentId: id, taskId: z.string().min(1), reason: text.optional(), replacement: text.optional() }).strict(), - z.object({ operation: z.literal('message'), agentId: id, message: text, - relatedTaskId: z.string().min(1).optional(), researchRevision: z.number().int().positive().optional() }).strict(), - z.object({ operation: z.literal('poll'), after: z.number().int().nonnegative().optional() }).strict(), - z.object({ operation: z.literal('wait'), after: z.number().int().nonnegative(), - timeoutMs: z.number().int().min(1).max(30000).optional() }).strict(), z.object({ operation: z.literal('inspect'), deliveryId: z.string().regex(/^[a-f0-9]{64}$/u), changeIndex: z.number().int().nonnegative().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(16000).optional() }).strict(), @@ -50,30 +28,24 @@ export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(16000).optional() }).strict(), submission, z.object({ operation: z.literal('adopt'), deliveryId: z.string().regex(/^[a-f0-9]{64}$/u), targetId: id.optional() }).strict(), - z.object({ operation: z.literal('stop'), agentId: id }).strict(), routeRetirementSchema.extend({ operation: z.literal('retire_route') }), z.object({ operation: z.literal('route_summary'), routeId: portfolioRouteIdSchema.optional(), includeRetired: z.boolean().optional() }).strict(), ]); -export const agentTeamMemberOperations = new Set(['message', 'poll', 'wait', 'inspect', 'inspect-research', 'history', 'yield', 'submit', 'progress', 'route_summary']); - -export function agentTeamMessageRouteFeedback(actor: string, recipient: string) { - if (recipient !== actor) return; - return { ok: false, error: 'math_team_message_self_addressed', from: actor, to: recipient, - hint: `The host fixes the sender as "${actor}". agentId names the recipient, not the sender. ` + - (actor === 'lead' ? 'Use the intended team member ID.' : - 'Use agentId: "lead" to report to Lead, or another team member ID for peer discussion.') }; -} +const deliveryOperations = new Set(['yield', 'submit']); +const leadOperations = new Set(['publish_plan', 'finish', 'adopt', 'retire_route']); -function optionsFor(actor: string, budgetControlsEnabled: boolean, transport: AgentTeamTransport = 'host-tools') { - return agentTeamRequestSchema.options.filter(option => (transport !== 'native-agent-control' || nativeOperations.has(option.shape.operation.value)) && (actor === 'lead' - ? !['submit', 'yield', 'progress'].includes(option.shape.operation.value) && (budgetControlsEnabled || option.shape.operation.value !== 'budget') - : agentTeamMemberOperations.has(option.shape.operation.value))); +function operationsFor(actor: string, approval: boolean) { + return agentTeamRequestSchema.options.filter(option => { + const operation = option.shape.operation.value; + if (operation === 'publish_plan' && !approval) return false; + return actor === 'lead' ? !deliveryOperations.has(operation) : !leadOperations.has(operation); + }); } -export function agentTeamOperationAllowed(actor: string, budgetControlsEnabled: boolean, transport: AgentTeamTransport, operation: string) { - return optionsFor(actor, budgetControlsEnabled, transport).some(option => option.shape.operation.value === operation); +export function agentTeamOperationAllowed(actor: string, operation: string, approval = false) { + return operationsFor(actor, approval).some(option => option.shape.operation.value === operation); } /** Only the concrete schema kinds used by this interface; refinements still run on the host. */ @@ -109,19 +81,12 @@ function fieldSchema(value: z.ZodTypeAny): Json { throw new Error('math_team_tool_schema_kind_unsupported'); } -function operationContracts(actor: string, budgetControlsEnabled: boolean, transport: AgentTeamTransport = 'host-tools') { - // Historical host callers can still send coordinate explicitly. - const advertised = optionsFor(actor, budgetControlsEnabled, transport).filter(option => option.shape.operation.value !== 'coordinate'); - return advertised.map(option => { +function operationContracts(actor: string, approval: boolean) { + return operationsFor(actor, approval).map(option => { const schema = fieldSchema(option); - if (!budgetControlsEnabled) { - delete schema.properties.budget; - delete schema.properties.leadReserve; - } - if (transport === 'native-agent-control') { - delete schema.properties.objectiveRevision; - schema.required = schema.required.filter((key: string) => key !== 'objectiveRevision'); - } + // Old native threads can still submit the previously accepted optional field. + // The advertised interface binds the current task itself. + delete schema.properties.objectiveRevision; return { operation: option.shape.operation.value, schema }; }); } @@ -130,15 +95,13 @@ function contractText(operation: string, schema: Json): string { const required = (schema.required as string[]).filter(key => key !== 'operation'); const optional = Object.keys(schema.properties).filter(key => key !== 'operation' && !required.includes(key)); return `${operation}: required ${required.length ? required.join(', ') : 'none'}; optional ${optional.length ? optional.join(', ') : 'none'}; other fields forbidden.` + - (operation === 'message' ? ' agentId is the recipient; sender is host-bound. Self-addressed messages are rejected.' : - operation === 'inspect' ? ' For more source, pass a changeIndex from the overview and its nextOffset. offset and limit require changeIndex and count Unicode code points.' : ''); + (operation === 'inspect' ? ' For more source, pass a changeIndex from the overview and its nextOffset. offset and limit require changeIndex and count Unicode code points.' : ''); } /** The same contracts drive advertised fields and corrective feedback. */ -export function agentTeamArgumentFeedback(actor: string, budgetControlsEnabled: boolean, args: unknown, error: z.ZodError, - transport: AgentTeamTransport = 'host-tools') { +export function agentTeamArgumentFeedback(actor: string, args: unknown, error: z.ZodError, approval = false) { const operation = args && typeof args === 'object' && 'operation' in args ? (args as Json).operation : undefined; - const contracts = operationContracts(actor, budgetControlsEnabled, transport); + const contracts = operationContracts(actor, approval); const contract = contracts.find(item => item.operation === operation); return { ok: false, error: 'math_team_arguments_invalid', detail: error.message, ...(contract ? { contract: contract.schema, hint: contractText(contract.operation, contract.schema) } : { @@ -147,38 +110,24 @@ export function agentTeamArgumentFeedback(actor: string, budgetControlsEnabled: } /** Advertise required/allowed fields per operation, retaining the native single-entry interface. */ -export function agentTeamToolDefinition(actor: string, budgetControlsEnabled: boolean, - transport: AgentTeamTransport = 'host-tools'): MathAgentToolDefinition { - const lead = actor === 'lead', native = transport === 'native-agent-control', contracts = operationContracts(actor, budgetControlsEnabled, transport); - // Finite host Lead allowances also require a flat wire schema. All operations - // retain their separate advertised contracts and strict host validation. - const flat = (lead && budgetControlsEnabled && !native) || contracts.length > MAX_CODEX_ONEOF_BRANCHES; +export function agentTeamToolDefinition(actor: string, approval = false): MathAgentToolDefinition { + const lead = actor === 'lead', contracts = operationContracts(actor, approval); const properties: Json = {}; for (const { schema } of contracts) Object.assign(properties, schema.properties); properties.operation = { type: 'string', enum: contracts.map(item => item.operation) }; - const purpose = native ? lead + const purpose = lead ? 'Mathematical host interface for the Lead. Native collaboration tools manage agent identities, spawning, followups, messages and interruption. Adopt rechecks a delivery in the saved consumer draft before merging. Inspect shows details on demand. Return with saved original proofs for independent checking. Finish requests early handoff. ' - : 'Mathematical host interface for a proof-writing member. Native collaboration tools deliver messages. Submit exact saved declarations, then return for stopped-writer checking. Yield preserves this task and draft for native followup after dependencies are integrated. ' - : lead - ? 'Lead collaboration interface. Spawn and assign queue proof writers and return immediately. Amend changes the effective objective or workKind of a queued, running or paused task, retaining its identity, draft and revision history. Publish updates the shared advisory research summary. Inspect shows delivery details on demand. Return after requesting adoption into your workspace. Save original proofs and return for independent checking. Finish requests early handoff. Stop interrupts a member. ' - : 'Proof-writing member interface. Progress records a useful finding, local probe, blocker or route change against the supplied current objectiveRevision and notifies Lead. Optional knowledgeUses names a supplied source anchor (file#heading) actually used and its concrete application; a report remains advisory. Message Lead or peers to discuss results. Submit exact declarations once they answer the assignment; include objectiveRevision after an amendment, then return for host checking. The host also checkpoints before the next model request after submit/yield. Other original goals may remain open. Yield preserves the task and draft for later resume. '; + : 'Mathematical host interface for a proof-writing member. Native collaboration tools deliver messages. Submit exact saved declarations, then return for stopped-writer checking. Yield preserves this task and draft for native followup after dependencies are integrated. '; return { name: 'theoremos_team', description: purpose + - (native ? 'History pages complete business task text; inspect and inspect-research read fixed evidence. agentId/targetId refer to the workspace member IDs shown in team observations; native collaboration targets use canonical paths or thread IDs. ' : - 'Poll/wait receives the durable inbox, saved research and delivery references. History pages complete task text; inspect and inspect-research read fixed evidence. ' + - `For message, the host fixes the sender as "${actor}"; agentId names the recipient. Self-addressed messages are rejected. `) + - (native ? 'Configured limits apply to the shared run; this interface does not allocate task budgets. ' : - lead && budgetControlsEnabled ? 'Budget controls allocate the configured finite run allowance. ' : - lead ? 'This run has no token or turn budget; do not set task allowances or a Lead reserve. ' : '') + - 'Only the host publishes checked proof evidence; original proof acceptance remains independent. ' + - (native ? 'Inspection and adoption retain peer-result provenance. ' : - 'WorkKind describes the deliverable: research, proof, independent-reconstruction, review or assembly. Inspection/adoption exposure is recorded and carried with later deliveries; this records reuse, not a guarantee of mathematical independence. ') + + 'History pages complete business task text; inspect and inspect-research read fixed evidence. agentId/targetId refer to the workspace member IDs shown in team observations; native collaboration targets use canonical paths or thread IDs. ' + + 'Configured limits apply to the shared run. ' + + (lead && approval ? 'While approval is required, first call publish_plan with goals [{theoremName,objective}] for all original targets and optional investigations, then return. Follow the host approval status before starting proof work. ' : '') + + 'Only the host publishes checked proof evidence; original proof acceptance remains independent. Inspection and adoption retain peer-result provenance. ' + (lead ? 'Use retire_route to record a refutation and cancel all unfinished work tagged with that route. ' + - (native ? 'For native spawn_agent or followup_task, put an optional Route: ROUTE_ID line first, then an optional Profiles: line of comma-separated IDs or slugs, then the assignment. ' : - 'For spawn/assign, use routeId to tag the route and select assignment profiles from the pinned Skill for the gap. ') : + 'For native spawn_agent or followup_task, put an optional Route: ROUTE_ID line first, then an optional Profiles: line of comma-separated IDs or slugs, then the assignment. ' : 'Set helpersOnly:true on submit to share standalone helpers and keep the assignment open. The host makes checked helpers available to peers before their next turn. ' + - (native ? '' : 'To report to Lead use agentId: "lead"; for peer discussion use the peer ID. ') + 'Submit omits agentId because the caller and task are already bound; each declaration supplies file, name and complete closed type. For a new auxiliary def or abbrev, also set kind to "definition"; submit theorems about it as separate declarations. ') + + 'Submit omits agentId because the caller and task are already bound; each declaration supplies file, name and complete closed type. For a new auxiliary def or abbrev, also set kind to "definition"; submit theorems about it as separate declarations. ') + 'Use route_summary for a compact view of route assignments, checked helpers and recent deliveries. ' + 'Supply only the fields for the selected operation:\n' + contracts.map(item => contractText(item.operation, item.schema)).join('\n'), - inputSchema: { type: 'object', properties, required: ['operation'], additionalProperties: false, - ...(flat ? {} : { oneOf: contracts.map(item => item.schema) }) } }; + inputSchema: { type: 'object', properties, required: ['operation'], additionalProperties: false, oneOf: contracts.map(item => item.schema) } }; } diff --git a/src/solver/agentTeamViews.ts b/src/solver/agentTeamViews.ts index 06e200aa..6c6be00c 100644 --- a/src/solver/agentTeamViews.ts +++ b/src/solver/agentTeamViews.ts @@ -57,13 +57,12 @@ function taskProjection(task: AgentTeamTask, historyOffset: number, full = false return { ...result, ...(textTruncated.length ? { textTruncated } : {}) }; } -function activity(team: Readonly, worker: AgentTeamWorker): Activity { +function activity(worker: AgentTeamWorker, current: AgentTeamTask | undefined, integrating: boolean): Activity { if (worker.writerStopUnconfirmed) return 'stopping'; if (worker.activity) return worker.activity; - const current = worker.tasks.find(task => task.status === 'running'); if (current?.cancelRequested || current?.pauseRequested) return 'stopping'; if (worker.pendingDelivery || worker.phase === 'checking') return 'checking'; - if (team.adoptions.some(item => item.targetId === worker.id && ['queued', 'integrating'].includes(item.status))) return 'integrating'; + if (integrating) return 'integrating'; if (worker.status === 'preparing') return 'preparing'; if (worker.status === 'running') return 'running'; if (worker.status === 'paused' || worker.tasks.at(-1)?.status === 'paused') return 'paused'; @@ -86,20 +85,30 @@ function taskBudget(state: Readonly, worker: AgentTeamWorker, ta usageUnavailable: projection.usageUnavailable, turnUsageKnown: turns !== null }; } -function visibleTasks(state: Readonly, worker: AgentTeamWorker, assignmentTaskId?: string) { - const selected = new Set(worker.tasks.filter(task => task.status === 'running').map(task => task.id)); - const next = worker.tasks.find(task => task.status === 'queued'); - if (next) selected.add(next.id); - for (const task of worker.tasks.toReversed().filter(task => !['running', 'queued'].includes(task.status)).slice(0, 2)) - if (selected.size < TASKS) selected.add(task.id); - for (const task of worker.tasks.toReversed()) { - if (selected.size >= TASKS) break; - selected.add(task.id); +function workerTaskView(state: Readonly, worker: AgentTeamWorker, assignmentTaskId?: string) { + const selected = new Set(); + let current: AgentTeamTask | undefined, queuedTaskCount = 0; + for (const [index, task] of worker.tasks.entries()) { + if (task.status === 'running') { + current ??= task; + selected.add(index); + } else if (task.status === 'queued' && queuedTaskCount++ === 0) selected.add(index); } - return worker.tasks.flatMap((task, index) => selected.has(task.id) - ? [{ ...taskProjection(task, index), + let recent = 0; + for (let index = worker.tasks.length - 1; index >= 0 && selected.size < TASKS && recent < 2; index--) { + const { status } = worker.tasks[index]!; + if (status === 'running' || status === 'queued') continue; + selected.add(index); + recent++; + } + for (let index = worker.tasks.length - 1; index >= 0 && selected.size < TASKS; index--) selected.add(index); + const tasks = [...selected].sort((left, right) => left - right).slice(-TASKS).map(index => { + const task = worker.tasks[index]!; + return { ...taskProjection(task, index), ...(task.id === assignmentTaskId ? { objective: undefined, profileEvidence: undefined } : {}), - budget: taskBudget(state, worker, task) }] : []).slice(-TASKS); + budget: taskBudget(state, worker, task) }; + }); + return { current, tasks, queuedTaskCount }; } function contextBudget(state: Readonly, focusAgentId?: string) { @@ -121,29 +130,31 @@ export function agentTeamOverview(state: Readonly, options: { focusAgentId?: string; assignmentTaskId?: string; budget?: unknown; workerLimit?: number } = {}) { const team = state.agentTeam; const workers = team?.workers ?? []; - const selected = [...workers].sort((left, right) => { - const rank = (worker: AgentTeamWorker) => worker.id === options.focusAgentId ? 0 : - worker.status === 'running' || worker.status === 'preparing' || worker.pendingDelivery || - team!.adoptions.some(item => item.targetId === worker.id && ['queued', 'integrating'].includes(item.status)) ? 1 : - worker.status === 'stopped' ? 3 : 2; - return rank(left) - rank(right) || workers.indexOf(right) - workers.indexOf(left); - }).slice(0, options.workerLimit ?? WORKERS); - const visible = new Set(selected.map(worker => worker.id)); const research = team?.researchState; const researchPreview = research && preview(research.summary, RESEARCH_TEXT); const refs = team?.researchArtifacts ?? [], deliveries = team?.deliveries ?? [], adoptions = team?.adoptions ?? []; const retiredRoutes = team?.retiredRoutes ?? []; - const selectedAdoptions = new Set(adoptions.filter(item => ['queued', 'integrating'].includes(item.status)).slice(0, 4).map(item => item.id)); - for (const item of adoptions.toReversed()) { - if (selectedAdoptions.size >= REFERENCES) break; - selectedAdoptions.add(item.id); + const integrating = new Set(); + const selectedAdoptions = new Set(); + for (const [index, item] of adoptions.entries()) { + if (item.status !== 'queued' && item.status !== 'integrating') continue; + integrating.add(item.targetId); + if (selectedAdoptions.size < 4) selectedAdoptions.add(index); } - return { - workers: workers.filter(worker => visible.has(worker.id)).map(worker => { - const tasks = visibleTasks(state, worker, worker.id === options.focusAgentId ? options.assignmentTaskId : undefined), error = worker.error && preview(worker.error, TASK_TEXT); + for (let index = adoptions.length - 1; index >= 0 && selectedAdoptions.size < REFERENCES; index--) selectedAdoptions.add(index); + const rank = (worker: AgentTeamWorker) => worker.id === options.focusAgentId ? 0 : + worker.status === 'running' || worker.status === 'preparing' || worker.pendingDelivery || integrating.has(worker.id) ? 1 : + worker.status === 'stopped' ? 3 : 2; + const visibleWorkers = workers.map((worker, index) => ({ worker, index, rank: rank(worker) })) + .sort((left, right) => left.rank - right.rank || right.index - left.index) + .slice(0, options.workerLimit ?? WORKERS).sort((left, right) => left.index - right.index) + .map(({ worker }) => { + const { current, tasks, queuedTaskCount } = workerTaskView(state, worker, + worker.id === options.focusAgentId ? options.assignmentTaskId : undefined); + const error = worker.error && preview(worker.error, TASK_TEXT); const stopReason = worker.writerStopUnconfirmed && preview(worker.writerStopUnconfirmed.reason, TASK_TEXT); const usage = buildTokenBudget(0, [worker]), requests = worker.requestUsageAccounting; - return { id: worker.id, status: worker.status, activity: activity(team!, worker), turns: worker.turns, + return { id: worker.id, status: worker.status, activity: activity(worker, current, integrating.has(worker.id)), turns: worker.turns, ...(worker.native ? { nativeIdentity: { threadId: worker.native.threadId, agentPath: worker.native.agentPath, spawnHistory: worker.native.spawnHistory ?? 'unknown' } } : {}), error: error && error.text, ...(error && error.truncated ? { errorTruncated: true } : {}), @@ -159,10 +170,13 @@ export function agentTeamOverview(state: Readonly, deliveryExposures: worker.exposures?.slice(-REFERENCES) ?? [], deliveryExposureCount: worker.exposures?.length ?? 0, tasks, taskCount: worker.tasks.length, tasksOmitted: worker.tasks.length - tasks.length, - queuedTaskCount: worker.tasks.filter(task => task.status === 'queued').length, + queuedTaskCount, writerStopUnconfirmed: worker.writerStopUnconfirmed && { at: worker.writerStopUnconfirmed.at, reason: stopReason!.text, ...(stopReason!.truncated ? { reasonTruncated: true } : {}) } }; - }), + }); + const taskCount = workers.reduce((sum, worker) => sum + worker.tasks.length, 0); + return { + workers: visibleWorkers, ...(research && { researchState: { revision: research.revision, publishedAt: research.publishedAt, summary: researchPreview!.text, advisory: true, ...(researchPreview!.truncated ? { summaryTruncated: true } : {}) } }), ...(retiredRoutes.length > 0 && { retiredRouteCount: retiredRoutes.length, @@ -175,15 +189,17 @@ export function agentTeamOverview(state: Readonly, landedHelperCount: team.landedHelpers.length } : {}), researchArtifacts: refs.slice(-REFERENCES).map(({ id, agentId, taskId, commit }) => ({ id, agentId, taskId, commit })), deliveries: deliveries.slice(-REFERENCES).map(({ id, agentId, taskId, kind }) => ({ id, agentId, taskId, ...(kind ? { kind } : {}) })), - adoptions: adoptions.filter(item => selectedAdoptions.has(item.id)).map(item => ({ id: item.id, deliveryId: item.deliveryId, targetId: item.targetId, - status: item.status, expectedCommit: item.expectedCommit, commit: item.commit, - error: item.error && preview(item.error, TASK_TEXT).text, - ...(item.error && preview(item.error, TASK_TEXT).truncated ? { errorTruncated: true } : {}) })), + adoptions: [...selectedAdoptions].sort((left, right) => left - right).map(index => { + const item = adoptions[index]!, error = item.error && preview(item.error, TASK_TEXT); + return { id: item.id, deliveryId: item.deliveryId, targetId: item.targetId, + status: item.status, expectedCommit: item.expectedCommit, commit: item.commit, + error: error && error.text, ...(error && error.truncated ? { errorTruncated: true } : {}) }; + }), budget: options.budget ?? contextBudget(state, options.focusAgentId), - totals: { workers: workers.length, tasks: workers.reduce((sum, worker) => sum + worker.tasks.length, 0), + totals: { workers: workers.length, tasks: taskCount, researchArtifacts: refs.length, deliveries: deliveries.length, adoptions: adoptions.length }, - omissions: { workers: workers.length - selected.length, - tasks: workers.reduce((sum, worker) => sum + worker.tasks.length, 0) - selected.reduce((sum, worker) => sum + visibleTasks(state, worker).length, 0), + omissions: { workers: workers.length - visibleWorkers.length, + tasks: taskCount - visibleWorkers.reduce((sum, worker) => sum + worker.tasks.length, 0), researchArtifacts: Math.max(0, refs.length - REFERENCES), deliveries: Math.max(0, deliveries.length - REFERENCES), adoptions: Math.max(0, adoptions.length - REFERENCES) }, retrieval: { @@ -202,10 +218,11 @@ function oneLine(value: string, limit: number) { } /** Bound each section by its serialized UTF-8 bytes, including JSON escapes. */ -function routeSummaryRows(rows: readonly T[], bytes: number) { +function routeSummaryRows(rows: readonly T[], bytes: number, project: (item: T) => Row) { let used = 2; // Array brackets. - const selected: T[] = []; - for (const row of rows) { + const selected: Row[] = []; + for (const item of rows) { + const row = project(item); const size = Buffer.byteLength(JSON.stringify(row)) + Number(selected.length > 0); if (used + size > bytes) break; selected.push(row); @@ -237,30 +254,33 @@ export function agentTeamRouteSummary(team: Readonly, } group[status]++; } - return [{ taskId: oneLine(task.id, 64), workerId, routeId: key, status, workKind: task.workKind ?? null, - objective: oneLine(task.message, 100), sequence: task.sequence ?? 0 }]; - }).sort((a, b) => routeTaskRank[a.status] - routeTaskRank[b.status] || b.sequence - a.sequence); + return [{ task, workerId, status }]; + }).sort((a, b) => routeTaskRank[a.status] - routeTaskRank[b.status] || (b.task.sequence ?? 0) - (a.task.sequence ?? 0)); const routes = routeSummaryRows([...activeRoutes.values()].sort((a, b) => - (b.running + b.queued + b.paused) - (a.running + a.queued + a.paused)), 800); - const tasks = routeSummaryRows(taskRows.map(({ sequence: _sequence, ...row }) => row), 2200); + (b.running + b.queued + b.paused) - (a.running + a.queued + a.paused)), 800, route => route); + const tasks = routeSummaryRows(taskRows, 2200, ({ task, workerId, status }) => ({ + taskId: oneLine(task.id, 64), workerId, routeId: task.routeId ?? null, status, workKind: task.workKind ?? null, + objective: oneLine(task.message, 100), + })); const retirementRows = includeRetired ? [...retired.values()].toReversed() - .filter(route => routeId === undefined || route.routeId === routeId) - .map(route => ({ routeId: route.routeId, source: route.source, reason: oneLine(route.reason, 120), - evidenceRefCount: route.evidenceRefs?.length ?? 0 })) : []; - const retiredRoutes = routeSummaryRows(retirementRows, 950); + .filter(route => routeId === undefined || route.routeId === routeId) : []; + const retiredRoutes = routeSummaryRows(retirementRows, 950, route => ({ + routeId: route.routeId, source: route.source, reason: oneLine(route.reason, 120), + evidenceRefCount: route.evidenceRefs?.length ?? 0, + })); const helpers = team.landedHelpers ?? []; - const landedHelpers = routeSummaryRows(helpers.slice(-8).reverse().map(helper => ({ + const landedHelpers = routeSummaryRows(helpers.slice(-8).reverse(), 1200, helper => ({ file: oneLine(helper.file, 96), qualifiedName: oneLine(helper.qualifiedName, 120), signature: oneLine(helper.type, 120), landedAt: helper.landedAt ?? null, - })), 1200); + })); const deliveries = routeId === undefined && includeRetired ? team.deliveries : team.deliveries.filter(delivery => byTask.has(delivery.taskId)); - const recentDeliveries = routeSummaryRows(deliveries.slice(-8).reverse().map(delivery => { + const recentDeliveries = routeSummaryRows(deliveries.slice(-8).reverse(), 1250, delivery => { const task = byTask.get(delivery.taskId); return { id: oneLine(delivery.id, 64), producer: delivery.agentId, kind: delivery.kind ?? 'proof', declarationCount: delivery.declarationCount ?? (task?.deliveryId === delivery.id && task.declarations ? task.declarations.length : null), summary: oneLine(delivery.summary ?? task?.summary ?? 'Independently checked delivery.', 100) }; - }), 1250); + }); const research = team.researchState; return { ok: true, routeId: routeId ?? null, canonicalCommit: team.canonicalCommit, @@ -274,28 +294,35 @@ export function agentTeamRouteSummary(team: Readonly, /** Task order is append-only once the host has filled the optional legacy sequence values. */ export function agentTeamTaskHistory(team: Readonly, input: { agentId?: string; offset?: number; limit?: number } = {}) { - const offset = input.offset ?? 0, limit = input.limit ?? 4; + const { agentId, offset = 0, limit = 4 } = input; if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 8) throw new Error('math_team_history_arguments_invalid'); - if (input.agentId && !team.workers.some(worker => worker.id === input.agentId)) - throw new Error('math_team_agent_unknown:' + input.agentId); - const all = team.workers.flatMap(worker => input.agentId && worker.id !== input.agentId ? [] : - worker.tasks.map((task, index) => ({ agentId: worker.id, task, index }))); - if (!input.agentId) all.sort((left, right) => (left.task.sequence ?? Number.MAX_SAFE_INTEGER) - - (right.task.sequence ?? Number.MAX_SAFE_INTEGER)); + let total: number; + let entries: { agentId: string; task: AgentTeamTask; index: number }[]; + if (agentId) { + const worker = team.workers.find(item => item.id === agentId); + if (!worker) throw new Error('math_team_agent_unknown:' + agentId); + total = worker.tasks.length; + entries = worker.tasks.slice(offset, offset + limit).map((task, index) => ({ agentId, task, index: offset + index })); + } else { + const all = team.workers.flatMap(worker => worker.tasks.map((task, index) => ({ agentId: worker.id, task, index }))); + all.sort((left, right) => (left.task.sequence ?? Number.MAX_SAFE_INTEGER) - (right.task.sequence ?? Number.MAX_SAFE_INTEGER)); + total = all.length; + entries = all.slice(offset, offset + limit); + } // Include the next whole task or leave it for the next page; a byte limit never skips a row. // One legal task is always returned even when its full text exceeds the ordinary page budget. - const page: typeof all = []; + const tasks = []; let bytes = Buffer.byteLength(JSON.stringify(team.researchState ?? null)); - for (const entry of all.slice(offset, offset + limit)) { - const size = Buffer.byteLength(JSON.stringify(taskProjection(entry.task, entry.index, true))); - if (page.length && bytes + size > HISTORY_BYTES) break; - page.push(entry); bytes += size; + for (const entry of entries) { + const projection = taskProjection(entry.task, entry.index, true); + const size = Buffer.byteLength(JSON.stringify(projection)); + if (tasks.length && bytes + size > HISTORY_BYTES) break; + tasks.push({ agentId: entry.agentId, ...projection }); + bytes += size; } - return { ok: true, agentId: input.agentId, offset, total: all.length, - coordination: team.coordination, - tasks: page.map(item => ({ agentId: item.agentId, ...taskProjection(item.task, item.index, true) })), - nextOffset: offset + page.length < all.length ? offset + page.length : null, + return { ok: true, agentId, offset, total, coordination: team.coordination, tasks, + nextOffset: offset + tasks.length < total ? offset + tasks.length : null, ...(team.researchState && { researchState: { ...team.researchState, advisory: true } }), declarations: 'Task text is complete. Declaration arrays are omitted; inspect a checked deliveryId for exact declarations and evidence.', pagination: 'Pages stop at a complete task boundary. Follow nextOffset; a single large task can exceed the ordinary 256 KiB page budget.', @@ -309,20 +336,30 @@ function eventPreview(event: AgentTeamState['events'][number]) { /** A truncated preview never acknowledges the unreturned message body. */ export function agentTeamInboxPreview(team: Readonly, actor: string, after: number) { - const unread = team.events.filter(item => item.to === actor && item.sequence > after); - const events = unread.slice(0, EVENTS).map(eventPreview); - let through = after, truncated = false; - for (const event of events) { + const events: ReturnType[] = []; + let through = after, truncated = false, more = false; + for (const item of team.events) { + if (item.to !== actor || item.sequence <= after) continue; + if (events.length === EVENTS) { + more = true; + break; + } + const event = eventPreview(item); + events.push(event); truncated ||= Boolean(event.textTruncated); if (!truncated) through = event.sequence; } return { after, through, previewThrough: events.at(-1)?.sequence ?? after, events, - more: unread.length > events.length || truncated, - continuation: team.transport === 'native-agent-control' - ? 'Read addressed native messages for complete updates; use history and inspect-research for saved task results. Previews do not acknowledge their bodies.' - : 'Poll after through for complete unread messages. textTruncated previews do not acknowledge their bodies; previewThrough is not a receive cursor.' }; + more: more || truncated, + continuation: 'Read addressed native messages for complete updates; use history and inspect-research for saved task results. Previews do not acknowledge their bodies.' }; } export function agentTeamRecentEvents(team: Readonly | undefined, actor: string) { - return team?.events.filter(event => event.to === actor).slice(-EVENTS).map(eventPreview) ?? []; + const events = team?.events ?? []; + const recent: ReturnType[] = []; + for (let index = events.length - 1; index >= 0 && recent.length < EVENTS; index--) { + const event = events[index]!; + if (event.to === actor) recent.push(eventPreview(event)); + } + return recent.reverse(); } diff --git a/src/solver/archive.ts b/src/solver/archive.ts index daae7ffa..5a1dcff8 100644 --- a/src/solver/archive.ts +++ b/src/solver/archive.ts @@ -6,7 +6,7 @@ import type { ProofCheck } from './modules/evidence'; import type { SolverFailure } from './feedback'; import type { ResearchCandidate } from './modules/execution'; import type { ResearchRole } from './modules/organization'; -import type { CooperationState } from './cooperation'; +import type { CooperationState } from './cooperationShared'; import type { MathAgentActivity } from '../runtime/agentSession'; import type { ResearchHarnessIdentity } from '../runtime/researchHarness'; import { safeFailureDiagnostic, type MathAgentFailureDiagnostic } from '../runtime/failureDiagnostic'; @@ -93,7 +93,7 @@ export type SolverRunState = { portfolioExploration?: PortfolioExploration; teamUsage?: Record; writerProcess?: import('../runtime/harnessProcess').HarnessProcessIdentity; - nativeAgents?: import('../runtime/nativeDelegation').NativeResearchAgent[]; + nativeAgents?: z.infer[]; /** A stopped writer's check/consumption resumes before any new model dispatch. */ pendingDeclarationCheck?: { commit: string; requestDigest: string; phase?: 'completed' }; /** Stopped research sources must finish freezing even if the host exits before journaling their checks. */ @@ -217,6 +217,14 @@ const check = z.object({ commit: z.string().min(1), sourceDigest: z.string().min targetCommit: z.string().optional(), results: z.array(record) }).passthrough() }).passthrough(); const advisoryCheckpoint = z.object({ noProgressStreak: safeCount, contentDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(), inputDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional() }); +// Historical investigator observations are archive data. +const archivedNativeAgentSchema = z.object({ threadId: z.string().min(1), parentThreadId: z.string().min(1), + startedAt: safeCount, updatedAt: safeCount, status: z.enum(['running', 'completed', 'errored', 'interrupted', 'stopped', 'unknown']), + usage: record.optional(), message: z.string().optional(), stoppedAt: safeCount.optional(), + dispatch: z.literal('host-mediated-native-threads').optional(), callId: z.string().optional(), + parentTurnId: z.string().optional(), turnId: z.string().optional(), question: z.string().optional(), + permissionProfile: z.literal('math-investigator').optional() }); + const research = z.object({ worktree: z.string().min(1), phase, turns: count, threadId: z.string().optional(), dispatchCounts: z.object({ planning: count.optional(), research: count.optional(), proof: count.optional(), review: count.optional() }).optional(), solveStartedAt: count.optional(), solveFinishedAt: count.optional(), solveWaitingMs: count.optional(), @@ -380,12 +388,7 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver. usageAccounting: usageAccounting.optional(), requestUsageAccounting: requestUsageAccountingSchema.optional(), })).max(3), }).optional(), - nativeAgents: z.array(z.object({ threadId: z.string().min(1), parentThreadId: z.string().min(1), - startedAt: safeCount, updatedAt: safeCount, status: z.enum(['running', 'completed', 'errored', 'interrupted', 'stopped', 'unknown']), - usage: record.optional(), message: z.string().optional(), stoppedAt: safeCount.optional(), - dispatch: z.literal('host-mediated-native-threads').optional(), callId: z.string().optional(), - parentTurnId: z.string().optional(), turnId: z.string().optional(), question: z.string().optional(), - permissionProfile: z.literal('math-investigator').optional() })).optional(), + nativeAgents: z.array(archivedNativeAgentSchema).optional(), pendingDeclarationCheck: z.object({ commit: z.string().regex(/^[a-f0-9]{40,64}$/u), requestDigest: z.string().regex(/^[a-f0-9]{64}$/u), phase: z.literal('completed').optional() }).strict().optional(), pendingResearchFreeze: z.object({ commit: z.string().regex(/^[a-f0-9]{40,64}$/u), diff --git a/src/solver/componentTemplate.ts b/src/solver/componentTemplate.ts index c2c84d9b..e5f5ed87 100644 --- a/src/solver/componentTemplate.ts +++ b/src/solver/componentTemplate.ts @@ -41,7 +41,7 @@ import { modules } from '../../src/components/${name}'; process.env.CODEX_HOME ||= path.join(os.homedir(), '.config/deepscientist/math-sol-codex'); const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); -runSolver(process.argv.slice(2), root, modules).then( +runSolver(process.argv.slice(2), root, modules, undefined, 'historical-component').then( code => { process.exitCode = code; }, error => { console.error(error instanceof Error ? error.message : 'Component run failed.'); process.exitCode = 1; }, ); diff --git a/src/solver/contextCompiler.ts b/src/solver/contextCompiler.ts index be8e7ab5..4fd85341 100644 --- a/src/solver/contextCompiler.ts +++ b/src/solver/contextCompiler.ts @@ -2,7 +2,7 @@ import path from 'node:path'; import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; import { inspectLeanDeclarations, inspectLeanDeclarationRegions } from '../math/leanSource'; import { maskLeanCommentsAndStrings } from '../math/leanSyntax'; -import type { CooperationState } from './cooperation'; +import type { CooperationState } from './cooperationShared'; import { deliveryFinding, researchFindingRequestsDecision, type DeliveryRecord } from './deliveries'; import { originalDeclarationRegions, type SolverProblem } from './problem'; import { assignmentDeliveryFile, hasTaskAcceptance, leadPlanDeliveryFile, taskGroup, taskReferenceDependencies, taskVersion, type CooperativeAction, type TaskRecord } from './tasks'; @@ -14,8 +14,6 @@ import { goalProgressTaskContext } from './goalProgress'; import { leadPlanPublicationFeedback, LEAD_PLAN_REPAIR_INSTRUCTION } from './cooperationShared'; import { contextCheckpointRejectionFeedback } from './contextCheckpoint'; import { researchDecisionMatches, type ResearchDecision } from './researchDecisions'; -import type { SolverRunState } from './archive'; -import { portfolioPhase2Guidance } from './portfolioExploration'; export const DEFAULT_TASK_CONTEXT_BYTES = 512 * 1024; export const DEFAULT_OPTIONAL_TASK_CONTEXT_BYTES = 64 * 1024; @@ -92,18 +90,6 @@ export function landedHelperSection(cooperation?: CooperationState) { 'Read the exact Lean type at the recorded commit before use.', helpers.slice(-4)); } -export function portfolioContextSections(state: Pick): ContextSection[] { - const sections: ContextSection[] = []; - const guidance = portfolioPhase2Guidance(state.portfolioExploration); - if (guidance) sections.push({ id: 'portfolio-gate', kind: 'routes', text: guidance }); - const retired = state.cooperation?.retiredRoutes?.filter(route => route.source === 'lead'); - if (retired?.length) sections.push(section('retired-routes', 'routes', - 'Recent route retirements. Read COOPERATION.json retiredRoutes for the full list. Use a distinct route ID and explain any new evidence before revisiting the inference.', - retired.slice(-8).map(({ routeId, reason, evidenceRefs }) => ({ routeId, - reason: reason.slice(0, 300), evidenceRefs: evidenceRefs?.slice(0, 2) })))); - return sections; -} - /** * Preserve source-level variables, scopes, instances and fixed definitions; never copy an existing proof body. * A source above COMPACT_CONTEXT_SOURCE_BYTES also omits definition and instance bodies, which stay in the frozen file. diff --git a/src/solver/continuationSeed.ts b/src/solver/continuationSeed.ts index c9e9c7cb..2fcfd686 100644 --- a/src/solver/continuationSeed.ts +++ b/src/solver/continuationSeed.ts @@ -1,206 +1,16 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { z } from 'zod'; -import { readMathBuildManifest } from '../math/mathBuildManifest'; -import { bindLeanPackages } from '../math/leanDiagnostics'; -import { MATH_PROOF_ENVIRONMENT_ENV, MATH_PROOF_ENVIRONMENT_SANDBOX_ENV, prepareMathProofEnvironment } from '../math/mathProofEnvironment'; -import { DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT } from '../math/mathProofEnvironmentCache'; -import { assertMathCanonicalPath, repositoryRelativePath } from '../math/paths'; -import { canonicalMathJson, mathDigest, readMathFile, readMathJson, withMathRuntimeLease, writeMathJsonDurable, type MathLease } from '../math/mathRuntimeIo'; -import { resolveMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnvironment'; -import { resolveMathematicsLakePackagesCache } from '../math/verifier'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from './archive'; -import { continuationActivity } from './continuationHistory'; -import { checkTaskProofs, createTaskSourceProjector, isAttributedTaskProof, ownedSourceDigest, projectedGoalInputs, type TaskProof, type TaskProofRequest } from './cooperativeProof'; -import { rejectionCode, taskSourceRejections } from './cooperationShared'; -import { freezeContinuationInput, MAX_CONTINUATION_ATTACHMENT_BYTES, readContinuationSnapshot, type ContinuationManifest } from './continuationInput'; -import { readRunInspection } from './inspection'; -import type { DeliveryRecord } from './deliveries'; -import { researchRecordSchema, researchSourceDigest, restoreResearch } from './researchRecords'; -import { researchSourceTasks, scopedResearchSources, type ResearchSourceTask } from './researchSources'; -import { researchSourceKinds, researchSourceUseSchema } from './researchReferences'; -import { installRetainedProofSearchText, MAX_PROOF_SEARCH_CHECKPOINT_BYTES, proofSearchCheckpointReferenceSchema, - proofSearchRecordForAssignment, proofSearchRecordSchema, readRetainedProofSearchText, relocateRetainedProofSearchRecord, - type ProofSearchRecord } from './proofSearchRecords'; -import { mathematicalGapSchema } from './mathematicalGaps'; -import { checkOutcomeSchema, nextCheckRecordSchema, nextCheckScopeSchema } from './nextCheckContract'; -import { currentNextCheck } from './nextChecks'; -import { goalProgressStateSchema, resetGoalProgressClock } from './goalProgress'; -import { assessTaskResponsibility, researchWorkerCanNode, researchWorkerCanTask } from './modules/organization'; -import { CAPACITY_EXPLORATION_FOCUSES, currentCapacityExploration, plannedTaskRecords, type CapacityExploration } from './capacityExploration'; -import { assertSolverSources, committedSource, commitSolverSources, git, readSolverProblem, withSolverWorktree, type SolverProblem } from './problem'; -import { assignmentDeliveryFile, assumableLemma, isAdvisoryTask, isDefinitionTask, isFeasibilityReview, isFinalCandidateReview, parseCooperationPlan, taskGroup, taskVersion, type CooperativeTask, type TaskAssignment, type TaskRecord } from './tasks'; -import { proofReadyRecord, proofReadyRecordSchema } from './proofReady'; -import { automaticTaskConnection, createTaskConnectionCheck } from './taskConnections'; -import { setTaskStatus } from './taskLifecycle'; -import { taskDependencyRecords } from './modules/search'; -import { hasDeterministicLeanFailure } from './proofReuse'; -import { VerificationCheckpointError, withVerificationCheckpoints } from './verificationCheckpoint'; -import { captureDeliveryArtifacts } from './deliveryArtifacts'; -import { rememberFreshConditionalCheck } from './freshContinuationChecks'; -import { resumableFeasibilityReviewInput, researchCheckpointInputDigest, researchCheckpointLocalInputDigest, researchCheckpointOutputDigest, - UNCHANGED_RESEARCH_CHECKPOINT, type ResearchCheckpoint } from './researchCheckpoints'; -import { recordRouteBlockers, validateBlockerProposals } from './routeControl'; - -const hash = z.string().regex(/^[a-f0-9]{64}$/u), oid = z.string().regex(/^[a-f0-9]{40,64}$/u); -const id = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/u); -const seedBatchFallbacks = new Set([...taskSourceRejections, 'math_task_batch_projection_mismatch', - 'math_task_missing_declaration', 'math_task_condition_version_invalid']); -const maxSeedBatchSize = 32; -// This project permits undefined at the type level. Materialize validated required -// fields so Zod's optional-property inference does not weaken the runtime contract. -const capacityMarker = z.object({ schema: z.literal('theorem-os.capacity-exploration.v1'), - targetTaskId: id, targetTaskDigest: hash, inputDigest: hash, focus: z.enum(CAPACITY_EXPLORATION_FOCUSES), - workerId: id, taskDigest: hash, environmentDigest: hash, problemReceiptDigest: hash }).strict() - .transform((value): CapacityExploration => ({ schema: value.schema, targetTaskId: value.targetTaskId, - targetTaskDigest: value.targetTaskDigest, inputDigest: value.inputDigest, focus: value.focus, - workerId: value.workerId, taskDigest: value.taskDigest, environmentDigest: value.environmentDigest, - problemReceiptDigest: value.problemReceiptDigest })); -const capacityInput = z.object({ inputDigest: hash, focus: z.enum(CAPACITY_EXPLORATION_FOCUSES), - targetTaskId: id, taskId: id }).strict().transform(value => ({ inputDigest: value.inputDigest, - focus: value.focus, targetTaskId: value.targetTaskId, taskId: value.taskId })); -const capacityRecord = z.object({ - task: z.object({ id, kind: z.literal('research'), objective: z.string().min(1), dependsOn: z.array(id), - revision: z.number().int().nonnegative() }).passthrough(), - capacityExploration: capacityMarker, - status: z.enum(['pending', 'running', 'blocked', 'conditional', 'delivered', 'integrated', 'completed']), - finding: z.string().optional(), archived: z.literal(true).optional(), -}).strict().refine(value => taskVersion(value.task as CooperativeTask) === value.capacityExploration.taskDigest, - 'Capacity exploration task identity changed'); -const capacitySource = z.object({ records: z.array(capacityRecord), - inputs: z.array(capacityInput).optional(), - notes: z.array(z.object({ taskId: id, taskDigest: hash, deliveryId: z.string().min(1), commit: oid, - notes: z.string() }).strict()), -}).strict(); -type CapacityRecord = z.infer; -const handoffTask = z.object({ id, kind: z.enum(['research', 'sketch', 'lemma', 'goal']), - objective: z.string().min(1), dependsOn: z.array(id), revision: z.number().int().nonnegative(), - proofPath: z.string().optional(), theoremName: z.string().optional(), type: z.string().optional(), - groupId: id.optional(), sharing: z.enum(['group', 'problem']).optional(), status: z.enum(['active', 'paused', 'stopped']).optional(), - ownerId: id.optional(), preferredOwnerId: id.optional(), researchSource: z.enum(researchSourceKinds).optional(), - consumerGoalIds: z.array(id).optional(), - premises: z.array(z.string()).optional(), conditional: z.boolean().optional(), - statementReview: z.boolean().optional(), informalStatement: z.string().optional(), - informalProof: z.string().optional(), citations: z.array(z.string()).optional(), - reviewScope: z.enum(['final-candidate', 'feasibility']).optional(), declaration: z.literal('definition').optional(), - family: z.object({ lo: z.number().int().nonnegative(), hi: z.number().int().nonnegative(), - chunk: z.number().int().positive(), predicate: z.string() }).strict().transform(value => ({ lo: value.lo, hi: value.hi, - chunk: value.chunk, predicate: value.predicate })).optional(), familyMember: id.optional(), -}).strict().transform((value): CooperativeTask => ({ ...value, id: value.id, kind: value.kind, - objective: value.objective, dependsOn: value.dependsOn, revision: value.revision })); -const continuableResearch = (task: CooperativeTask) => isAdvisoryTask(task) && !task.reviewScope && !isFinalCandidateReview(task); -const nextCheckSource = z.object({ records: z.array(nextCheckRecordSchema), - tasks: z.array(z.object({ task: handoffTask, nextCheckId: hash, - status: z.enum(['pending', 'running', 'blocked', 'conditional', 'delivered', 'integrated', 'completed']), - finding: z.string().optional() }).strict()), -}).strict().refine(value => value.tasks.every(node => value.records.some(record => record.id === node.nextCheckId && - record.taskId === node.task.id && record.taskDigest === taskVersion(node.task))), 'Scoped check task identity changed'); -const legacyCompletedResearchRecord = z.object({ task: handoffTask.refine(continuableResearch, 'Completion requires ordinary advisory research'), - inputDigest: hash, finding: z.string().optional(), archived: z.literal(true).optional() }).strict(); -const immutableCompletedResearchRecord = z.object({ task: handoffTask.refine(continuableResearch, 'Completion requires ordinary advisory research'), - record: researchRecordSchema, finding: z.string().optional(), archived: z.literal(true).optional() }).strict(); -const unboundCompletedResearchRecord = z.object({ task: handoffTask.refine(continuableResearch, 'Completion requires ordinary advisory research'), - finding: z.string().optional(), archived: z.literal(true) }).strict(); -const completedResearchRecord = z.union([immutableCompletedResearchRecord, legacyCompletedResearchRecord, unboundCompletedResearchRecord]); -type CompletedResearchRecord = z.infer; -const handoffReference = z.object({ taskId: id, taskDigest: hash }).strict() - .transform(value => ({ taskId: value.taskId, taskDigest: value.taskDigest })); -const frozenCandidate = z.object({ taskId: id, taskDigest: hash, workerId: id, - readyId: z.string().min(1), submissionId: z.string().min(1), assignmentKey: z.string().min(1), - seedCommit: oid, snapshotCommit: oid, sourceDigest: hash, environmentDigest: hash, problemReceiptDigest: hash, - dependencies: z.array(handoffReference), sources: z.record(z.string()), seedSources: z.record(z.string()), -}).strict(); -const researchDelivery = z.object({ id: z.string().min(1), producer: id, taskId: id, taskDigest: hash, - groupId: id.optional(), kind: z.enum(['research', 'progress']), status: z.enum(['advisory', 'conditional', 'superseded']), - statement: z.string(), premises: z.array(z.string()), dependencies: z.array(handoffReference), - remainingObligations: z.array(z.string()), summary: z.string(), evidenceRefs: z.array(z.string()), - createdAt: z.number().int().nonnegative(), commit: oid.optional(), sourceDigest: z.string().optional(), - finding: z.string().optional(), findingDigest: hash.optional(), - leadDecisionRequested: z.literal(true).optional(), - researchRecord: researchRecordSchema.optional(), mathematicalGap: mathematicalGapSchema.optional(), - checkOutcome: checkOutcomeSchema.optional(), checkOutcomeScope: nextCheckScopeSchema.optional(), - sourceUses: z.array(researchSourceUseSchema).max(32).optional(), - searchCheckpoint: proofSearchCheckpointReferenceSchema.optional(), - mathematicalGapScope: z.object({ problemReceiptDigest: hash, environmentDigest: hash, - source: handoffTask, consumer: handoffTask, dependencies: z.array(handoffReference) }).strict() - .transform(value => ({ ...value, problemReceiptDigest: value.problemReceiptDigest, - environmentDigest: value.environmentDigest, source: value.source, consumer: value.consumer, - dependencies: value.dependencies })).optional(), - lemmaRequests: z.array(handoffTask.refine(task => task.kind === 'lemma' && Boolean(task.type?.trim()) && - Boolean(task.proofPath) && Boolean(task.theoremName), 'Handoff requires an exact typed lemma')).optional(), -}).strict().transform((value): DeliveryRecord => ({ ...value, id: value.id, producer: value.producer, - taskId: value.taskId, taskDigest: value.taskDigest, kind: value.kind, status: value.status, - statement: value.statement, premises: value.premises, dependencies: value.dependencies, - remainingObligations: value.remainingObligations, summary: value.summary, evidenceRefs: value.evidenceRefs, - createdAt: value.createdAt, lemmaRequests: value.lemmaRequests })); -const researchProofInput = z.object({ passed: z.boolean(), taskDigest: hash, - conditions: z.array(handoffReference).optional() }).strict() - .transform(value => ({ ...value, passed: value.passed, taskDigest: value.taskDigest })); -const researchTaskInput = z.object({ task: handoffTask, - status: z.enum(['pending', 'running', 'blocked', 'conditional', 'delivered', 'integrated', 'completed']), - finding: z.string().optional(), proof: researchProofInput.optional(), integratedCheck: researchProofInput.optional(), - visibleDependencies: z.array(id), sourceDependencies: z.array(id), sourceHelpers: z.array(z.string()), -}).strict().transform((value): ResearchSourceTask => ({ ...value, task: value.task, status: value.status, - visibleDependencies: value.visibleDependencies, sourceDependencies: value.sourceDependencies, sourceHelpers: value.sourceHelpers })); -const researchContext = z.object({ environmentDigest: hash, problemReceiptDigest: hash, - tasks: z.array(researchTaskInput), deliveries: z.array(researchDelivery) }).strict(); -const savedTaskDraft = z.object({ taskId: id, taskDigest: hash, workerId: id, - assignmentId: z.string().optional(), seedCommit: oid, canonicalCommit: oid.optional(), commit: oid, - outputDigest: hash, task: handoffTask.optional(), suspended: z.boolean().optional(), archived: z.literal(true).optional(), - sources: z.record(z.string()), notes: z.string().nullable(), handoffNotesDigest: hash.optional(), - feasibilityInputDigest: hash.optional(), - source: z.object({ runId: z.string(), stateFile: z.string(), environmentDigest: hash, - problemReceiptDigest: hash, sourcePolicyDigest: hash }).strict(), -}).strict(); -type SavedTaskDraft = z.infer; -const savedResearchCheckpoint = z.object({ taskId: id, workerId: id, - checkpoint: z.object({ taskDigest: hash, inputDigest: hash, outputDigest: hash, - count: z.number().int().positive(), localInputDigest: hash.optional(), candidateOutputDigest: hash.optional(), - unchangedEvidenceCount: z.number().int().positive().optional(), - candidateStatus: z.enum(['structured-candidate', 'unclassified-draft']).optional(), paused: z.boolean().optional(), - advisoryCheckpoint: z.object({ scope: hash, noProgressStreak: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), - contentDigest: hash.optional(), inputDigest: hash.optional() }).strict().transform(value => ({ ...value, - scope: value.scope, noProgressStreak: value.noProgressStreak })).optional(), - }).strict().transform((value): ResearchCheckpoint => ({ ...value, taskDigest: value.taskDigest, - inputDigest: value.inputDigest, outputDigest: value.outputDigest, count: value.count })), - source: savedTaskDraft.shape.source, -}).strict(); -type SavedResearchCheckpoint = z.infer; -const sourceSchema = z.object({ - schema: z.literal('theorem-os.continuation-seed-source.v1'), capturedAt: z.number().int().nonnegative(), - taskDigest: hash, problemReceiptDigest: hash, sourcePolicyDigest: hash, - destination: z.object({ runId: z.string(), stateFile: z.string(), buildDigest: hash, - methodDigest: z.string().optional(), environmentDigest: hash }).strict(), - source: z.object({ runId: z.string(), stateFile: z.string(), stateDigest: hash, buildDigest: z.string(), - methodDigest: z.string().optional(), canonicalCommit: oid, planVersion: z.string().optional() }).strict(), - plan: z.unknown(), initialPlanning: z.literal(true).optional(), candidateIds: z.array(id), canonicalSources: z.record(z.string()), - conditionalCandidates: z.array(z.object({ taskId: id, taskDigest: hash, commit: z.string(), seedCommit: z.string(), - conditions: z.array(handoffReference).nonempty(), dependencies: z.array(handoffReference), - sources: z.record(z.string()).optional(), seedSources: z.record(z.string()).optional(), captureError: z.string().optional() }).strict()).optional(), - frozenCandidates: z.array(frozenCandidate).optional(), - verificationCheckpoints: z.array(z.object({ key: hash, - timeoutMs: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), - attempts: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), - at: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), - targetCommit: z.string(), receiptIds: z.array(z.string()) }).strict()).max(32).optional(), - taskDrafts: z.array(savedTaskDraft).optional(), - researchCheckpoints: z.array(savedResearchCheckpoint).optional(), - workers: z.array(z.object({ id, role: z.string(), headBefore: oid, headAfter: oid, - sources: z.record(z.string()), notes: z.string().nullable(), assignment: z.unknown().optional() }).strict()), - history: z.unknown(), - capacityExplorations: capacitySource.optional(), - nextChecks: nextCheckSource.optional(), - proofSearch: z.object({ - records: z.record(proofSearchRecordSchema), - checkpoints: z.record(hash, z.string().max(MAX_PROOF_SEARCH_CHECKPOINT_BYTES)), - }).strict().optional(), - goalProgress: goalProgressStateSchema.optional(), - completedResearch: z.array(completedResearchRecord).optional(), - researchContext: researchContext.optional(), - ownershipExtension: z.object({ sourceReceiptDigest: hash, sourcePolicyDigest: hash, - addedFiles: z.array(z.string()) }).strict().optional(), -}).strict(); -type SeedSource = z.infer; +import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; +import type { SolverRunState } from './archive'; +import type { TaskProof } from './cooperativeProof'; +import { committedSource, git, type SolverProblem } from './problem'; +import { researchCheckpointOutputDigest, type ResearchCheckpoint } from './researchCheckpoints'; +import { isAdvisoryTask, isFinalCandidateReview, taskVersion, type CooperativeTask, type TaskRecord } from './tasks'; + +export type ContinuationSeedOptions = { + sourceRun: string; run: string; root: string; buildManifest: string; signal: AbortSignal; timeoutMs?: number; + onProgress?: (event: string, details: Record) => void; + lease?: import('../math/mathRuntimeIo').MathLease; preparedEnvironment?: NodeJS.ProcessEnv; deferChecks?: boolean; + onSeeded?: (state: SolverRunState, freshChecks: TaskProof[]) => void; +}; export type ContinuationSeedReport = { schema: 'theorem-os.continuation-seed.v1'; sourceRunId: string; runId: string; sourceStateFile: string; @@ -214,14 +24,14 @@ const sourcePolicy = (problem: SolverProblem) => ({ workspace: problem.workspace baseCommit: problem.baseCommit, receiptDigest: problem.receiptDigest, contract: problem.contract, targets: problem.targets, ownedFiles: problem.ownedFiles, trustedFiles: problem.trustedFiles, declarations: problem.declarations, sourceStructure: problem.sourceStructure, sourceImports: problem.sourceImports, frozenFiles: problem.frozenFiles }); -const policyDigest = (problem: SolverProblem) => mathDigest(canonicalMathJson(sourcePolicy(problem))); +export const continuationSourcePolicyDigest = (problem: SolverProblem) => mathDigest(canonicalMathJson(sourcePolicy(problem))); /** * Owned files that a re-bootstrapped destination adds to the source problem, e.g. certificate or theory slots. * Undefined unless both are the same mathematical problem: equal contract, targets and trusted files, and every * source-owned file keeps its frozen declarations, context, imports and library bytes. Added files start at the destination baseline. */ -function ownershipExtension(source: SolverProblem, destination: SolverProblem): string[] | undefined { +export function continuationOwnershipExtension(source: SolverProblem, destination: SolverProblem): string[] | undefined { const frozen = (problem: SolverProblem, file: string) => canonicalMathJson([problem.declarations[file] ?? null, problem.sourceStructure[file] ?? null, problem.sourceImports?.[file] ?? null, problem.frozenFiles?.[file] ?? null]); if (source.kind !== destination.kind || source.projectRelative !== destination.projectRelative || @@ -232,328 +42,37 @@ function ownershipExtension(source: SolverProblem, destination: SolverProblem): const added = destination.ownedFiles.filter(file => !source.ownedFiles.includes(file)); return added.length ? added : undefined; } -const commonDirectory = (worktree: string) => git(worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir']); - -function textFile(file: string) { - assertMathCanonicalPath(file); - return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(readMathFile(file, 16_000_000).bytes); -} - -function assertPrepared(state: SolverRunState, stateFile: string, seeded: boolean) { - const directory = path.dirname(stateFile); - if (state.phase !== 'prepared' || state.turns !== 0 || state.solveStartedAt !== undefined || - state.solveFinishedAt !== undefined || state.threadId || state.previousThreadIds?.length || state.check || - state.candidate || state.winningWorker || state.lastActivity || state.lastFailure || state.lastContextManifest || - state.usage || state.usageBeforeThread || state.usageAccounting || state.requestUsageAccounting || - state.failures?.length || Object.values(state.dispatchCounts ?? {}).some(value => value !== 0) || - state.coordination !== 'cooperative' || !state.workers?.length || state.workerCount !== state.workers.length || - state.worktree !== path.join(directory, 'worktree') || state.workers[0].id !== 'solver' || - state.workers[0].role !== 'lead' || state.workers.some((worker, index) => - worker.worktree !== path.join(directory, index ? `worktree-${index + 1}` : 'worktree') || - worker.phase !== 'prepared' || worker.turns !== 0 || worker.threadId || worker.previousThreadIds?.length || - worker.sessionTaskId || worker.sessionTaskVersion || worker.sessionAssignmentId || worker.sessionRole || worker.sessionGroupId || - worker.sessionStatementReview || worker.lastActivity || worker.lastFailure || worker.lastContextManifest || worker.check || worker.candidate || - worker.usage || worker.usageBeforeThread || worker.usageAccounting || worker.requestUsageAccounting || worker.failures?.length || - Object.values(worker.dispatchCounts ?? {}).some(value => value !== 0)) || - (!seeded && (state.cooperation !== undefined || state.continuationDigest !== undefined))) - throw new Error('math_continuation_seed_requires_fresh_prepared_run'); - assertMathCanonicalPath(directory); - const stat = fs.statSync(directory); - if ((stat.mode & 0o077) || (process.getuid && stat.uid !== process.getuid())) - throw new Error('math_state_directory_not_private'); - for (const worker of state.workers) assertMathCanonicalPath(worker.worktree); - if (!repositoryRelativePath(state.problem.projectRelative) || - state.problem.ownedFiles.some(file => !repositoryRelativePath(file))) throw new Error('math_continuation_seed_invalid_source_path'); - const current = readSolverProblem(state.problem.workspace, state.problem.activeProblemPath); - if (policyDigest(current) !== policyDigest(state.problem)) throw new Error('math_continuation_seed_source_policy_changed'); -} - -function validatePlan(state: SolverRunState, value: unknown) { - const plan = parseCooperationPlan(state.problem, value); - for (const task of plan.tasks) if (task.ownerId && !state.workers!.some(worker => worker.id === task.ownerId && - researchWorkerCanTask(worker, task))) - throw new Error('math_plan_task_owner_unavailable'); - for (const group of plan.groups) if (group.engineerId && - !state.workers!.some(worker => worker.id === group.engineerId && worker.role === 'engineer')) - throw new Error('math_plan_group_engineer_unavailable'); - return plan; -} - -// An interrupted first plan has no accepted graph to replay. Keep that absence -// explicit so normal cooperation asks the Lead for its first accepted plan. -const emptyInitialPlan = z.object({ tasks: z.array(z.never()).length(0), groups: z.array(z.never()).length(0) }).strict() - .transform(value => ({ tasks: value.tasks, groups: value.groups })); -function validateSeedPlan(state: SolverRunState, source: SeedSource): ReturnType { - if (!source.initialPlanning) return validatePlan(state, source.plan); - if (source.candidateIds.length || source.conditionalCandidates?.length || source.frozenCandidates?.length || source.capacityExplorations || - source.completedResearch || source.researchContext || source.nextChecks || source.proofSearch || source.taskDrafts?.length) - throw new Error('math_continuation_seed_initial_plan_invalid'); - return emptyInitialPlan.parse(source.plan); -} - -function initialPlanningOnly(state: SolverRunState) { - const cooperation = state.cooperation!; - const noStartedTurns = state.turns === 0 && state.workers!.every(worker => worker.turns === 0 && !worker.threadId && - !worker.previousThreadIds?.length && !worker.usageAccounting?.startedTurns) && - !state.threadId && !state.previousThreadIds?.length && !state.usageAccounting?.startedTurns; - const onlyPlanning = (record: Pick) => - record.dispatchCounts?.planning === record.turns && Object.entries(record.dispatchCounts) - .every(([kind, turns]) => kind === 'planning' || turns === 0); - const lead = state.workers![0]; - const startedLead = state.turns > 0 && onlyPlanning(state) && lead.id === 'solver' && lead.role === 'lead' && - lead.turns === state.turns && onlyPlanning(lead) && lead.sessionRole === 'lead' && - !lead.sessionTaskId && !lead.sessionTaskVersion && !lead.sessionAssignmentId && !lead.sessionGroupId && - !lead.sessionStatementReview && !lead.check?.passed && (!lead.candidate || lead.candidate.status === 'failed') && - state.workers!.slice(1).every(worker => worker.turns === 0 && !worker.threadId && - !worker.previousThreadIds?.length && !worker.usageAccounting?.startedTurns && !worker.requestUsageAccounting?.startedRequests && - Object.values(worker.dispatchCounts ?? {}).every(turns => turns === 0) && !worker.check && !worker.candidate && - !worker.sessionTaskId && !worker.sessionAssignmentId && !worker.sessionTaskVersion && !worker.sessionGroupId) && - cooperation.planVersion === mathDigest(canonicalMathJson({ tasks: [], groups: cooperation.groups?.map(route => route.group) })); - // preserveLeadDraft records this bookkeeping when the first plan is rejected. It - // carries no task or proof authority and must not make an absent graph look accepted. - const savedInitialDraftsOnly = startedLead && (cooperation.deliveries ?? []).every(delivery => - delivery.producer === lead.id && delivery.kind === 'progress' && delivery.status === 'advisory' && - delivery.commit === cooperation.canonicalCommit && delivery.summary.startsWith('Saved Lead draft pending integration:') && - delivery.statement === state.problem.contract.formalStatement && - canonicalMathJson(delivery.premises) === canonicalMathJson(state.problem.contract.assumptions) && - !delivery.taskId && !delivery.taskDigest && !delivery.groupId && !delivery.dependencies?.length && - !delivery.remainingObligations?.length && !delivery.evidence && !delivery.evidenceRefs?.length && - !delivery.artifacts && !delivery.actualReferences && !delivery.researchRecord && !delivery.lemmaRequests?.length); - return (noStartedTurns || startedLead) && !state.check && !state.candidate && !state.winningWorker && !state.continuationDigest && - cooperation.canonicalCommit === state.problem.baseCommit && !cooperation.tasks.length && - !cooperation.groups?.length && !cooperation.proofRoutes?.length && !cooperation.history?.length && - (!cooperation.deliveries?.length || savedInitialDraftsOnly) && !cooperation.initialPlanPublication && !cooperation.planPublication && - !cooperation.initialPlanFallback && !cooperation.planEdited && !cooperation.edits?.length && - !cooperation.planApproval && !cooperation.statementReviews?.length && !cooperation.proofReadyRecords?.length && - !cooperation.proofImports?.length && !cooperation.deliveryReceipts?.length && - !cooperation.capacityExplorationInputs?.length; -} - -function capturedCapacityRecords(state: SolverRunState): CapacityRecord[] { - const records = new Map(); - const add = (node: Partial>, archived = false) => { - if (!node.capacityExploration) return; - const record = capacityRecord.parse({ task: node.task, capacityExploration: node.capacityExploration, - status: node.status ?? 'blocked', ...(node.finding === undefined ? {} : { finding: node.finding }), - ...(archived ? { archived: true } : {}) }); - records.set(canonicalMathJson([record.task.id, record.capacityExploration]), record); - }; - for (const item of state.cooperation?.history ?? []) add(item, true); - for (const node of state.cooperation?.tasks ?? []) add(node); - return [...records.values()]; -} - -function capturedCompletedResearch(state: SolverRunState, - previous: readonly CompletedResearchRecord[] = []): CompletedResearchRecord[] { - const key = (record: CompletedResearchRecord) => 'record' in record ? `record:${record.record.id}` : - canonicalMathJson(['legacy', taskVersion(record.task), 'inputDigest' in record ? record.inputDigest : null, record.finding ?? null]); - const records = new Map(previous.map(record => [key(record), { ...record, archived: true }])); - for (const node of state.cooperation!.history ?? []) if (continuableResearch(node.task) && node.researchCompletion) { - const record = immutableCompletedResearchRecord.parse({ task: node.task, finding: node.finding, - record: node.researchCompletion, archived: true }); - records.set(key(record), record); - } - for (const node of plannedTaskRecords(state.cooperation!.tasks)) { - if (!continuableResearch(node.task) || node.status !== 'completed') continue; - // A completion's inputs are fixed when it is published, never reconstructed - // from newer canonical sources or guessed from equal finding text. - const record = node.researchCompletion ? immutableCompletedResearchRecord.parse({ task: node.task, finding: node.finding, - record: node.researchCompletion }) : unboundCompletedResearchRecord.parse({ task: node.task, finding: node.finding, archived: true }); - records.set(key(record), record); - } - return [...records.values()]; -} - -function currentCompletedResearch(source: SeedSource, state: SolverRunState, tasks: readonly CooperativeTask[], - checkedTasks?: readonly TaskRecord[], deliveries?: readonly DeliveryRecord[]) { - const context = source.researchContext; - if (!context) return new Map>(); - const view = { problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, - retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest, - tasks: context.tasks, deliveries: context.deliveries }; - const sourceDigest = (task: CooperativeTask) => researchSourceDigest(scopedResearchSources(state.problem, task, - source.canonicalSources, context.tasks)); - const current = new Map>(); - for (const record of source.completedResearch ?? []) { - const task = tasks.find(task => task.id === record.task.id); - if (record.archived || !('record' in record) || !task || - restoreResearch(record.record, task, { ...view, sourceDigest: sourceDigest(task) }, record.finding).status !== 'completed') continue; - current.set(task.id, record); - } - if (checkedTasks) { - // Rechecks may invalidate a previously passing dependency. Remove affected - // completions and their dependent findings until the advisory view is stable. - let changed: boolean; - do { - changed = false; - const checkedView = { ...view, deliveries: deliveries ?? context.deliveries, - tasks: checkedTasks.map(node => continuableResearch(node.task) && !node.capacityExploration ? - { ...node, status: current.has(node.task.id) ? 'completed' as const : 'pending' as const, - finding: current.get(node.task.id)?.finding } : node) }; - for (const [id, record] of current) if (restoreResearch(record.record, - tasks.find(task => task.id === id)!, { ...checkedView, - sourceDigest: sourceDigest(tasks.find(task => task.id === id)!) }, record.finding).status !== 'completed') { - current.delete(id); changed = true; - } - } while (changed); - } - return current; -} - -function completedResearchHistory(source: SeedSource, - current: ReturnType = new Map()) { - return (source.completedResearch ?? []).filter(record => current.get(record.task.id) !== record) - .map(record => ({ task: record.task, status: 'completed', finding: record.finding, - ...('record' in record ? { researchCompletion: record.record } : {}) })); -} - -function capacityOrigin(records: readonly CapacityRecord[]) { - return records.map(({ task, capacityExploration, finding }) => ({ task, capacityExploration, - ...(finding === undefined ? {} : { finding }) })).sort((left, right) => - canonicalMathJson(left).localeCompare(canonicalMathJson(right))); -} - -function archivedCapacity(record: CapacityRecord) { - return { task: record.task as CooperativeTask, capacityExploration: record.capacityExploration, - status: record.status, producer: record.capacityExploration.workerId, - ...(record.finding === undefined ? {} : { finding: record.finding }) }; -} - -function advisoryResearchDelivery(delivery: DeliveryRecord): DeliveryRecord { - // Publication provenance is useful; old proof evidence, references, artifacts, - // assignment keys and acceptance statuses are never replayed into the new host. - return researchDelivery.parse({ id: delivery.id, producer: delivery.producer, taskId: delivery.taskId, - taskDigest: delivery.taskDigest, groupId: delivery.groupId, kind: delivery.kind, - status: delivery.status === 'superseded' ? 'superseded' : - delivery.kind === 'progress' && delivery.status === 'conditional' ? 'conditional' : 'advisory', statement: delivery.statement, - premises: delivery.premises, dependencies: delivery.dependencies, remainingObligations: delivery.remainingObligations, - summary: delivery.summary, evidenceRefs: delivery.evidenceRefs, createdAt: delivery.createdAt, - commit: delivery.commit, sourceDigest: delivery.sourceDigest, finding: delivery.finding, - findingDigest: delivery.findingDigest, leadDecisionRequested: delivery.leadDecisionRequested, researchRecord: delivery.researchRecord, - mathematicalGap: delivery.mathematicalGap, mathematicalGapScope: delivery.mathematicalGapScope, - checkOutcome: delivery.checkOutcome, checkOutcomeScope: delivery.checkOutcomeScope, - sourceUses: delivery.sourceUses, searchCheckpoint: delivery.searchCheckpoint, - lemmaRequests: delivery.lemmaRequests }); -} - -function capturedResearchContext(state: SolverRunState): z.infer { - return researchContext.parse({ environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, - tasks: researchSourceTasks(state.cooperation!.tasks).map(node => ({ ...node, - proof: node.proof?.taskDigest ? node.proof : undefined, - integratedCheck: node.integratedCheck?.taskDigest ? node.integratedCheck : undefined })), - deliveries: (state.cooperation!.deliveries ?? []).filter(delivery => - (delivery.kind === 'research' || delivery.kind === 'progress' && delivery.mathematicalGap) && - delivery.taskId && delivery.taskDigest).map(advisoryResearchDelivery) }); -} - -function restoredResearchDeliveries(source: SeedSource, state: SolverRunState): DeliveryRecord[] { - const nodes = new Map(state.cooperation!.tasks.map(node => [node.task.id, node.task])); - const deliveries = new Map((source.researchContext?.deliveries ?? []).map(delivery => { - const task = nodes.get(delivery.taskId!); - const current = source.researchContext!.environmentDigest === state.environmentDigest && - source.researchContext!.problemReceiptDigest === state.problem.receiptDigest && task && - taskVersion(task) === delivery.taskDigest && delivery.dependencies.every(input => - nodes.has(input.taskId) && taskVersion(nodes.get(input.taskId)!) === input.taskDigest); - return [delivery.id, { ...delivery, status: current ? delivery.status : 'superseded' as const }]; - })); - return [...deliveries.values()]; -} - -function captureProofSearch(archived: SolverRunState, runDirectory: string): SeedSource['proofSearch'] { - const cooperation = archived.cooperation!, identity = { problemReceiptDigest: archived.problem.receiptDigest, - environmentDigest: archived.environmentDigest }; - const records: [string, ProofSearchRecord][] = [], checkpoints: Record = {}; - const capture = (record: ProofSearchRecord) => { - const digest = record.checkpoint.digest; - if (Object.hasOwn(checkpoints, digest)) return true; - try { - checkpoints[digest] = readRetainedProofSearchText(runDirectory, record); - return true; - } catch { return false; } - }; - for (const check of cooperation.nextChecks ?? []) { - if (check.status !== 'pending' || check.check.execution?.kind !== 'proof-search' || - !currentNextCheck(check, cooperation, identity)) continue; - if (check.proofSearchSeed) capture(check.proofSearchSeed); - const scope = { ...identity, ...check.scope.target }; - const selected = proofSearchRecordForAssignment(cooperation.proofSearchRecords, scope, check); - if (selected?.history === check.id && capture(selected)) records.push([check.taskId, selected]); - if (!check.proofSearchSeed && check.scope.executionBasisDigest) { - const owner = proofSearchRecordForAssignment(cooperation.proofSearchRecords, scope); - if (owner?.basisDigest === check.scope.executionBasisDigest && capture(owner)) records.push([scope.taskId, owner]); - } - } - if (Object.keys(checkpoints).length) return { records: Object.fromEntries(records), checkpoints }; -} - -function restoreProofSearch(source: SeedSource, state: SolverRunState, runDirectory: string) { - const artifacts = new Map(); - const identity = { problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest }; - const restore = (record: ProofSearchRecord) => { - if (record.problemReceiptDigest !== identity.problemReceiptDigest || record.environmentDigest !== identity.environmentDigest) return; - let text = source.proofSearch?.checkpoints[record.checkpoint.digest]; - // Older frozen continuations contain the pinned record but predate embedded checkpoint bytes. - if (text === undefined && !source.proofSearch) { - try { text = readRetainedProofSearchText(path.dirname(source.source.stateFile), record); } - catch { return; } - } - if (text === undefined) return; - const relocated = relocateRetainedProofSearchRecord(runDirectory, record); - artifacts.set(record.checkpoint.digest, { record: relocated, text }); - return relocated; - }; - const records = Object.fromEntries(Object.entries(source.proofSearch?.records ?? {}).flatMap(([taskId, record]) => { - const restored = restore(record); - return restored ? [[taskId, restored] as const] : []; - })); - const checks = source.nextChecks?.records.map(check => { - if (check.status !== 'pending' || !check.scope.executionBasisDigest) return check; - const seed = check.proofSearchSeed && restore(check.proofSearchSeed); - if (seed) return { ...check, proofSearchSeed: seed }; - if (records[check.taskId] || !check.proofSearchSeed && - records[check.scope.target.taskId]?.basisDigest === check.scope.executionBasisDigest) return check; - if (check.scope.problemReceiptDigest === identity.problemReceiptDigest && check.scope.environmentDigest === identity.environmentDigest) - return { ...check, status: 'stale' as const }; - return check; - }); - return { records, checks, artifacts }; -} - -const draftOutputDigest = researchCheckpointOutputDigest; +const continuableResearch = (task: CooperativeTask) => isAdvisoryTask(task) && !task.reviewScope && !isFinalCandidateReview(task); const ordinaryCheckpointTask = (node: TaskRecord) => continuableResearch(node.task) && !node.capacityExploration && !node.nextCheckId; const pausedResearchCheckpoint = (node: TaskRecord, checkpoint?: ResearchCheckpoint) => ordinaryCheckpointTask(node) && checkpoint?.paused && checkpoint.taskDigest === taskVersion(node.task) && node.status === 'blocked' && node.feedback?.startsWith('math_research_checkpoint_unchanged'); -function capturedTaskDrafts(state: SolverRunState, stateFile: string, previous: readonly SavedTaskDraft[] = []) { - const key = (draft: SavedTaskDraft) => canonicalMathJson([draft.source, draft.taskId, draft.taskDigest, - draft.workerId, draft.seedCommit, draft.canonicalCommit ?? null, draft.commit]); - const drafts = new Map(previous.map(draft => [key(draft), { ...draft, archived: true }])); + +/** Read archived task snapshots as advisory material for a new continuation. */ +export function captureContinuationTaskDrafts(state: SolverRunState, stateFile: string) { + const cooperation = state.cooperation; + if (!cooperation) return []; const origin = { runId: state.runId, stateFile, environmentDigest: state.environmentDigest, - problemReceiptDigest: state.problem.receiptDigest, sourcePolicyDigest: policyDigest(state.problem) }; - for (const [taskId, snapshot] of Object.entries(state.cooperation!.researchDrafts ?? {})) { - const node = state.cooperation!.tasks.find(node => node.task.id === taskId); + problemReceiptDigest: state.problem.receiptDigest, sourcePolicyDigest: continuationSourcePolicyDigest(state.problem) }; + return Object.entries(cooperation.researchDrafts ?? {}).map(([taskId, snapshot]) => { + const node = cooperation.tasks.find(node => node.task.id === taskId); const task = node?.task && taskVersion(node.task) === snapshot.taskDigest ? node.task : - state.cooperation!.history?.find(record => record.task.id === taskId && taskVersion(record.task) === snapshot.taskDigest)?.task; + cooperation.history?.find(record => record.task.id === taskId && taskVersion(record.task) === snapshot.taskDigest)?.task; const assignment = node?.assignment; - const checkpoint = state.cooperation!.researchCheckpoints?.[taskId]; + const checkpoint = cooperation.researchCheckpoints?.[taskId]; const current = node && taskVersion(node.task) === snapshot.taskDigest && (['pending', 'running'].includes(node.status) || pausedResearchCheckpoint(node, checkpoint) && checkpoint!.outputDigest === snapshot.outputDigest) && assignment?.taskDigest === snapshot.taskDigest && assignment.workerId === snapshot.workerId && assignment.assignmentId === snapshot.assignmentId && assignment.seedCommit === snapshot.seedCommit && assignment.canonicalCommit === snapshot.canonicalCommit && - snapshot.outputDigest === draftOutputDigest(state.problem, state.worktree, snapshot.commit) && + snapshot.outputDigest === researchCheckpointOutputDigest(state.problem, state.worktree, snapshot.commit) && snapshot.artifacts.problemReceiptDigest === state.problem.receiptDigest && snapshot.artifacts.taskId === taskId && snapshot.artifacts.taskDigest === snapshot.taskDigest && snapshot.artifacts.seedCommit === snapshot.seedCommit && snapshot.artifacts.commit === snapshot.commit; - const prior = previous.find(draft => !draft.archived && draft.taskId === taskId && draft.taskDigest === snapshot.taskDigest && - draft.workerId === snapshot.workerId && draft.seedCommit === snapshot.seedCommit && - draft.canonicalCommit === snapshot.canonicalCommit && draft.commit === snapshot.commit && - draft.outputDigest === snapshot.outputDigest && draft.source.environmentDigest === origin.environmentDigest && - draft.source.problemReceiptDigest === origin.problemReceiptDigest && draft.source.sourcePolicyDigest === origin.sourcePolicyDigest); - const draft = savedTaskDraft.parse({ taskId, taskDigest: snapshot.taskDigest, workerId: snapshot.workerId, - assignmentId: prior?.assignmentId ?? snapshot.assignmentId, seedCommit: snapshot.seedCommit, + return { taskId, taskDigest: snapshot.taskDigest, workerId: snapshot.workerId, + assignmentId: snapshot.assignmentId, seedCommit: snapshot.seedCommit, canonicalCommit: snapshot.canonicalCommit, commit: snapshot.commit, outputDigest: snapshot.outputDigest, handoffNotesDigest: snapshot.handoffNotesDigest, feasibilityInputDigest: snapshot.feasibilityInputDigest, task, suspended: snapshot.suspended, ...(current ? {} : { archived: true }), @@ -561,970 +80,6 @@ function capturedTaskDrafts(state: SolverRunState, stateFile: string, previous: committedSource(state.worktree, snapshot.commit, `${state.problem.projectRelative}/${file}`)])), notes: git(state.worktree, ['ls-tree', '--format=%(objectname)', snapshot.commit, '--', 'RESEARCH.md']) ? committedSource(state.worktree, snapshot.commit, 'RESEARCH.md') : null, - source: prior?.source ?? origin }); - drafts.set(key(draft), draft); - } - return [...drafts.values()]; -} - -function capturedResearchCheckpoints(state: SolverRunState, stateFile: string, drafts: readonly SavedTaskDraft[]) { - const checkpoints: SavedResearchCheckpoint[] = []; - for (const [taskId, checkpoint] of Object.entries(state.cooperation!.researchCheckpoints ?? {})) { - const node = state.cooperation!.tasks.find(node => node.task.id === taskId); - const draft = drafts.find(draft => !draft.archived && draft.taskId === taskId && - draft.taskDigest === checkpoint.taskDigest && draft.outputDigest === checkpoint.outputDigest && - draft.workerId === node?.assignment?.workerId); - if (!node || !ordinaryCheckpointTask(node) || taskVersion(node.task) !== checkpoint.taskDigest || !draft || - !(['pending', 'running'].includes(node.status) || pausedResearchCheckpoint(node, checkpoint))) continue; - const { blockerId: _oldBlocker, ...scheduling } = checkpoint; - checkpoints.push(savedResearchCheckpoint.parse({ taskId, workerId: draft.workerId, checkpoint: scheduling, - source: { runId: state.runId, stateFile, environmentDigest: state.environmentDigest, - problemReceiptDigest: state.problem.receiptDigest, sourcePolicyDigest: policyDigest(state.problem) } })); - } - return checkpoints; -} - -/** Saved bytes and the effective current inputs must agree before restoring a scheduling pause. */ -function currentResearchCheckpoints(source: SeedSource, state: SolverRunState) { - const checkpoints = new Map(); - if (source.ownershipExtension || !state.cooperation) return checkpoints; - const cooperation = state.cooperation; - for (const saved of source.researchCheckpoints ?? []) { - const node = cooperation.tasks.find(node => node.task.id === saved.taskId); - const draft = cooperation.researchDrafts?.[saved.taskId], checkpoint = saved.checkpoint; - if (!node || !ordinaryCheckpointTask(node) || !['pending', 'blocked'].includes(node.status) || - taskVersion(node.task) !== checkpoint.taskDigest || node.assignment?.workerId !== saved.workerId || - !draft || draft.taskDigest !== checkpoint.taskDigest || draft.workerId !== saved.workerId || - draft.assignmentId !== node.assignment.assignmentId || draft.outputDigest !== checkpoint.outputDigest || - saved.source.environmentDigest !== state.environmentDigest || - saved.source.problemReceiptDigest !== state.problem.receiptDigest || - saved.source.sourcePolicyDigest !== policyDigest(state.problem)) continue; - const input = { task: node.task, workerId: saved.workerId, tasks: cooperation.tasks, deliveries: cooperation.deliveries ?? [], - environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest }; - const sameInput = checkpoint.localInputDigest - ? checkpoint.localInputDigest === researchCheckpointLocalInputDigest(input) - : checkpoint.inputDigest === researchCheckpointInputDigest({ ...input, problem: state.problem, - worktree: state.worktree, canonicalCommit: cooperation.canonicalCommit! }); - if (sameInput) checkpoints.set(saved.taskId, saved); - } - return checkpoints; -} - -function taskDraftAssignment(draft: SavedTaskDraft, task: CooperativeTask, - tasks: readonly TaskRecord[], state: SolverRunState): TaskAssignment { - const assignment: TaskAssignment = { taskId: draft.taskId, taskDigest: draft.taskDigest, workerId: draft.workerId, - seedCommit: draft.seedCommit, canonicalCommit: draft.canonicalCommit, - feasibilityInputDigest: draft.feasibilityInputDigest, - assignmentId: mathDigest(canonicalMathJson({ runId: state.runId, draft: { source: draft.source, - taskId: draft.taskId, taskDigest: draft.taskDigest, workerId: draft.workerId, - assignmentId: draft.assignmentId, seedCommit: draft.seedCommit, commit: draft.commit } })), - groupId: taskGroup(task), dependencies: taskDependencyRecords(task, tasks) - .map(node => ({ taskId: node.task.id, taskDigest: taskVersion(node.task) })) }; - if (automaticTaskConnection(task, tasks, state.cooperation!.groups)) - assignment.connectionCheck = createTaskConnectionCheck(task, assignment, tasks, - { environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest }, - input => committedSource(state.worktree, draft.seedCommit, `${state.problem.projectRelative}/${input.proofPath}`)); - return assignment; -} - -function restorableTaskDraft(draft: SavedTaskDraft, node: TaskRecord, state: SolverRunState) { - const worker = state.workers!.find(worker => worker.id === draft.workerId); - const eligible = !draft.archived && (node.status === 'pending' || - pausedResearchCheckpoint(node, state.cooperation!.researchCheckpoints?.[node.task.id])) && !node.alternativeRoutes?.length && - draft.taskId === node.task.id && draft.taskDigest === taskVersion(node.task) && - draft.source.environmentDigest === state.environmentDigest && draft.source.problemReceiptDigest === state.problem.receiptDigest && - draft.source.sourcePolicyDigest === policyDigest(state.problem) && worker && - assessTaskResponsibility({ ...node, assignment: undefined }, worker, - { tasks: state.cooperation!.tasks, groups: state.cooperation!.groups }).kind === 'matches'; - if (!eligible) return false; - return !isFeasibilityReview(node.task) || Boolean(resumableFeasibilityReviewInput({ task: node.task, workerId: draft.workerId, - tasks: state.cooperation!.tasks, deliveries: state.cooperation!.deliveries ?? [], - problem: state.problem, worktree: state.worktree, canonicalCommit: state.cooperation!.canonicalCommit!, - environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, - retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest }, draft)); -} - -function frozenTaskAssignment(candidate: z.infer, task: CooperativeTask, - identity: { runId: string; sourceRunId: string; canonicalCommit: string }): TaskAssignment { - return { taskId: candidate.taskId, taskDigest: candidate.taskDigest, workerId: candidate.workerId, - seedCommit: candidate.seedCommit, canonicalCommit: identity.canonicalCommit, - assignmentId: mathDigest(canonicalMathJson({ runId: identity.runId, sourceRunId: identity.sourceRunId, - readyId: candidate.readyId, snapshotCommit: candidate.snapshotCommit })), - groupId: taskGroup(task), dependencies: candidate.dependencies }; -} - -function captureSource(sourceStateFile: string, stateFile: string, state: SolverRunState, sourceLease?: MathLease): SeedSource { - const stateDigest = mathDigest(readMathFile(sourceStateFile).bytes); - const archived = readSolverRunState(sourceStateFile); - if (stateDigest !== mathDigest(readMathFile(sourceStateFile).bytes)) throw new Error('math_continuation_seed_source_changed'); - const sameProblem = archived.problem.receiptDigest === state.problem.receiptDigest && - policyDigest(archived.problem) === policyDigest(state.problem); - const added = sameProblem ? undefined : ownershipExtension(archived.problem, state.problem); - if (archived.runId === state.runId || archived.taskDigest !== state.taskDigest || (!sameProblem && !added)) - throw new Error('math_continuation_seed_identity_changed'); - if (!archived.cooperation?.canonicalCommit || !archived.workers?.length) - throw new Error('math_continuation_seed_source_incomplete'); - const planned = plannedTaskRecords(archived.cooperation.tasks); - // A smaller destination team cannot staff every historical owner. Ownership is - // scheduling metadata outside taskVersion, so release only those assignments. - const staffed = (task: CooperativeTask) => !task.ownerId || state.workers!.some(worker => - worker.id === task.ownerId && researchWorkerCanTask(worker, task)); - const initialPlanning = initialPlanningOnly(archived); - const plan: ReturnType = initialPlanning ? emptyInitialPlan.parse({ tasks: [], groups: [] }) : validatePlan(state, { tasks: planned.map(({ task }) => { - if (staffed(task)) return task; - const { ownerId: _released, ...unowned } = task; - return unowned; - }), - groups: archived.cooperation.groups?.map(record => record.group), proofRoutes: archived.cooperation.proofRoutes }); - if (plan.tasks.some((task, index) => taskVersion(task) !== taskVersion(planned[index].task))) - throw new Error('math_continuation_seed_task_identity_changed'); - // An extended destination is a new bootstrap workspace, so source commits are read from their own repository. - const sourceDirectory = path.dirname(sourceStateFile); - if (archived.worktree !== path.join(sourceDirectory, 'worktree')) throw new Error('math_continuation_seed_repository_changed'); - const common = commonDirectory(archived.worktree); - if (!added && common !== commonDirectory(state.worktree)) throw new Error('math_continuation_seed_repository_changed'); - for (const [file, expected] of Object.entries(state.problem.trustedFiles)) - if (mathDigest(committedSource(archived.worktree, archived.cooperation.canonicalCommit, - `${state.problem.projectRelative}/${file}`)) !== expected) throw new Error('math_continuation_seed_source_policy_changed'); - const historicalSources = (commit: string) => Object.fromEntries(state.problem.ownedFiles.map(file => [file, - added?.includes(file) ? committedSource(state.worktree, state.problem.baseCommit, `${state.problem.projectRelative}/${file}`) - : committedSource(archived.worktree, commit, `${state.problem.projectRelative}/${file}`)])); - const canonicalSources = historicalSources(archived.cooperation.canonicalCommit); - const snapshot = archived.continuationDigest ? readContinuationSnapshot(path.join(sourceDirectory, 'continuation.json'), - archived.continuationDigest, { taskDigest: archived.taskDigest, problemReceiptDigest: archived.problem.receiptDigest }) : undefined; - const frozenCandidates: z.infer[] = []; - const frozenRecords = (archived.cooperation.proofReadyRecords ?? []).filter(record => record.status === 'frozen'); - if (frozenRecords.length) { - if (!sourceLease) throw new Error('math_continuation_seed_frozen_source_lease_required'); - sourceLease.assertHeld(); - if ([archived, ...archived.workers].some(worker => worker.writerStopUnconfirmed)) - throw new Error('math_continuation_seed_frozen_writer_unconfirmed'); - for (const ready of frozenRecords) { - if (!proofReadyRecordSchema.safeParse(ready).success) throw new Error('math_continuation_seed_frozen_identity_changed'); - const node = planned.find(node => node.task.id === ready.taskId); - let assignment = node?.assignment; - // Timeout recovery can release scheduling assignments while retaining a frozen proof. - // Only its pinned prior continuation can reconstruct the exact imported assignment. - const attachment = snapshot?.manifest.attachments.find(item => item.id === `frozen-${ready.taskId}` && item.kind === 'proof-source'); - if (node && !assignment && attachment?.provenance.runId) { - const bytes = readMathFile(path.join(sourceDirectory, attachment.contentPath), attachment.bytes).bytes; - if (bytes.length !== attachment.bytes || mathDigest(bytes) !== attachment.sha256) - throw new Error('math_continuation_content_changed'); - const candidate = frozenCandidate.parse(JSON.parse(bytes.toString('utf8'))); - assignment = frozenTaskAssignment(candidate, node.task, { runId: archived.runId, - sourceRunId: attachment.provenance.runId, canonicalCommit: archived.cooperation.canonicalCommit }); - const expected = proofReadyRecord({ assignment, workerId: candidate.workerId, - submissionId: mathDigest(canonicalMathJson({ sourceRunId: attachment.provenance.runId, - readyId: candidate.readyId, runId: archived.runId })), - problemReceiptDigest: candidate.problemReceiptDigest, environmentDigest: candidate.environmentDigest, - now: ready.requestedAt }); - if (attachment.provenance.commit !== candidate.snapshotCommit || candidate.snapshotCommit !== ready.snapshotCommit || - candidate.sourceDigest !== ready.sourceDigest || candidate.environmentDigest !== ready.environmentDigest || - candidate.problemReceiptDigest !== ready.problemReceiptDigest || expected.id !== ready.id || - expected.submissionId !== ready.submissionId) - throw new Error('math_continuation_seed_frozen_identity_changed'); - } - const worker = archived.workers.find(worker => worker.id === ready.workerId); - if (!node || !assignment || !worker || ready.taskDigest !== taskVersion(node.task) || - assignment.taskId !== ready.taskId || assignment.taskDigest !== ready.taskDigest || - assignment.workerId !== ready.workerId || ready.assignmentKey !== assignmentDeliveryFile(assignment) || - ready.seedCommit !== assignment.seedCommit || ready.problemReceiptDigest !== archived.problem.receiptDigest || - ready.environmentDigest !== archived.environmentDigest || - ready.sourceDigest !== ownedSourceDigest(archived.problem, archived.worktree, ready.snapshotCommit!)) - throw new Error('math_continuation_seed_frozen_identity_changed'); - // Changed scopes and conditional inputs remain advisory drafts. This path only restores an - // exact ordinary task with the same proof environment, source policy and available worker. - const destinationTask = plan.tasks.find(task => task.id === node.task.id); - const destinationWorker = state.workers!.find(worker => worker.id === ready.workerId); - if (added || !sameProblem || state.environmentDigest !== ready.environmentDigest || - !destinationTask || !destinationWorker || taskVersion(destinationTask) !== ready.taskDigest || - !['goal', 'lemma'].includes(node.task.kind) || isDefinitionTask(node.task) || node.task.conditional || - assignment.connectionCheck || assignment.routeId || node.alternativeRoutes?.length || - (node.task.status ?? 'active') !== 'active' || !['pending', 'running'].includes(node.status) || - assessTaskResponsibility({ task: destinationTask, status: 'pending', attempts: 0 }, destinationWorker, - { tasks: plan.tasks.map(task => ({ task, status: 'pending' as const, attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) }).kind !== 'matches') continue; - const dependencies = assignment.dependencies ?? []; - if (dependencies.some(reference => !plan.tasks.some(task => task.id === reference.taskId && taskVersion(task) === reference.taskDigest))) - throw new Error('math_continuation_seed_frozen_identity_changed'); - if (frozenCandidates.some(candidate => candidate.taskId === ready.taskId || candidate.workerId === ready.workerId)) - throw new Error('math_continuation_seed_frozen_candidate_conflict'); - frozenCandidates.push({ taskId: ready.taskId, taskDigest: ready.taskDigest, workerId: ready.workerId, - readyId: ready.id, submissionId: ready.submissionId, assignmentKey: ready.assignmentKey, - seedCommit: ready.seedCommit, snapshotCommit: ready.snapshotCommit!, sourceDigest: ready.sourceDigest!, - environmentDigest: ready.environmentDigest, problemReceiptDigest: ready.problemReceiptDigest, - dependencies, sources: historicalSources(ready.snapshotCommit!), seedSources: historicalSources(ready.seedCommit) }); - } - sourceLease.assertHeld(); - } - const workers = archived.workers.map((worker, index) => { - if (!id.safeParse(worker.id).success || worker.worktree !== path.join(sourceDirectory, index ? `worktree-${index + 1}` : 'worktree')) - throw new Error('math_continuation_seed_worker_path_changed'); - assertMathCanonicalPath(worker.worktree); - if (commonDirectory(worker.worktree) !== common) throw new Error('math_continuation_seed_repository_changed'); - const headBefore = git(worker.worktree, ['rev-parse', 'HEAD']); - const sources = Object.fromEntries(archived.problem.ownedFiles.map(file => [file, - textFile(path.join(worker.worktree, state.problem.projectRelative, file))])); - const notesFile = path.join(worker.worktree, 'RESEARCH.md'); - const notes = fs.lstatSync(notesFile, { throwIfNoEntry: false }) ? textFile(notesFile) : null; - const activeTask = archived.cooperation!.tasks.find(node => node.task.id === worker.sessionTaskId && node.assignment?.workerId === worker.id) ?? - archived.cooperation!.tasks.find(node => node.status === 'running' && node.assignment?.workerId === worker.id); - return { id: worker.id, role: worker.role, headBefore, headAfter: git(worker.worktree, ['rev-parse', 'HEAD']), sources, notes, - assignment: activeTask?.assignment }; + source: origin }; }); - const proofHistory = (proof: TaskProof | undefined) => proof && ({ commit: proof.commit, taskDigest: proof.taskDigest, - seedCommit: proof.seedCommit, passed: proof.passed, conditions: proof.conditions, - receiptIds: proof.verification.results.map(result => result.receiptId).filter(Boolean) }); - const capacities = capturedCapacityRecords(archived); - let previousCapacity: z.infer | undefined; - let previousResearch: CompletedResearchRecord[] | undefined; - let previousDrafts: SavedTaskDraft[] | undefined; - if (snapshot) { - const attachment = snapshot.manifest.attachments.find(item => item.id === 'seed-capacity-explorations'); - if (attachment) { - const bytes = readMathFile(path.join(sourceDirectory, attachment.contentPath), attachment.bytes).bytes; - if (bytes.length !== attachment.bytes || mathDigest(bytes) !== attachment.sha256) - throw new Error('math_continuation_content_changed'); - previousCapacity = capacitySource.parse(JSON.parse(bytes.toString('utf8'))); - const captured = new Set(capacities.map(record => canonicalMathJson([record.task.id, record.capacityExploration]))); - for (const record of previousCapacity.records) - if (!captured.has(canonicalMathJson([record.task.id, record.capacityExploration]))) capacities.push({ ...record, archived: true }); - } - const research = snapshot.manifest.attachments.find(item => item.id === 'seed-completed-research'); - if (research) { - const bytes = readMathFile(path.join(sourceDirectory, research.contentPath), research.bytes).bytes; - if (bytes.length !== research.bytes || mathDigest(bytes) !== research.sha256) - throw new Error('math_continuation_content_changed'); - previousResearch = z.array(completedResearchRecord).parse(JSON.parse(bytes.toString('utf8'))); - } - const drafts = snapshot.manifest.attachments.filter(item => /^seed-task-drafts(?:-[1-9][0-9]*)?$/u.test(item.id)); - if (drafts.length) previousDrafts = drafts.flatMap(attachment => { - const bytes = readMathFile(path.join(sourceDirectory, attachment.contentPath), attachment.bytes).bytes; - if (bytes.length !== attachment.bytes || mathDigest(bytes) !== attachment.sha256) - throw new Error('math_continuation_content_changed'); - return z.array(savedTaskDraft).parse(JSON.parse(bytes.toString('utf8'))); - }); - } - const taskDrafts = capturedTaskDrafts(archived, sourceStateFile, previousDrafts); - const researchCheckpoints = capturedResearchCheckpoints(archived, sourceStateFile, taskDrafts); - const capacityVersions = new Set(capacities.map(record => - canonicalMathJson([record.task.id, record.capacityExploration.taskDigest]))); - const notes = new Map['notes'][number]>(); - for (const note of previousCapacity?.notes ?? []) if (capacityVersions.has(canonicalMathJson([note.taskId, note.taskDigest]))) - notes.set(canonicalMathJson([note.taskId, note.taskDigest, note.commit]), note); - for (const delivery of archived.cooperation.deliveries ?? []) { - if (delivery.kind !== 'research' || !delivery.commit || !delivery.taskId || !delivery.taskDigest || - !capacityVersions.has(canonicalMathJson([delivery.taskId, delivery.taskDigest]))) continue; - const key = canonicalMathJson([delivery.taskId, delivery.taskDigest, delivery.commit]); - if (!notes.has(key)) notes.set(key, { taskId: delivery.taskId, taskDigest: delivery.taskDigest, - deliveryId: delivery.id, commit: delivery.commit, - notes: committedSource(archived.worktree, delivery.commit, 'RESEARCH.md') }); - } - const completedResearch = capturedCompletedResearch(archived, previousResearch); - const context = capturedResearchContext(archived); - const proofSearch = sameProblem && archived.environmentDigest === state.environmentDigest - ? captureProofSearch(archived, sourceDirectory) : undefined; - const conditionalCandidates = planned.filter(node => !isAdvisoryTask(node.task) && - !(node.proof?.passed && !node.proof.conditions?.length) && - !(node.integratedCheck?.passed && !node.integratedCheck.conditions?.length) && - (node.proof?.passed && node.proof.conditions?.length || node.integratedCheck?.passed && node.integratedCheck.conditions?.length)) - .map(node => { - const proof = node.proof?.passed && node.proof.conditions?.length ? node.proof : node.integratedCheck!; - const evidence = { taskId: node.task.id, taskDigest: proof.taskDigest, commit: proof.commit, - seedCommit: proof.seedCommit, conditions: proof.conditions!, dependencies: node.assignment?.dependencies ?? [] }; - try { - if (!oid.safeParse(proof.commit).success || !oid.safeParse(proof.seedCommit).success) - throw new Error('math_continuation_seed_conditional_commit_invalid'); - return { ...evidence, sources: historicalSources(proof.commit), seedSources: historicalSources(proof.seedCommit) }; - } catch (error) { - return { ...evidence, captureError: error instanceof Error ? error.message : 'math_task_source_unavailable' }; - } - }); - const value = { schema: 'theorem-os.continuation-seed-source.v1', capturedAt: Date.now(), taskDigest: state.taskDigest, - problemReceiptDigest: state.problem.receiptDigest, sourcePolicyDigest: policyDigest(state.problem), - destination: { runId: state.runId, stateFile, buildDigest: state.buildDigest, - methodDigest: state.methodDigest, environmentDigest: state.environmentDigest }, - source: { runId: archived.runId, stateFile: sourceStateFile, stateDigest, - buildDigest: archived.buildDigest, methodDigest: archived.methodDigest, canonicalCommit: archived.cooperation.canonicalCommit, - planVersion: archived.cooperation.planVersion }, - plan, ...(initialPlanning ? { initialPlanning: true } : {}), canonicalSources, workers, conditionalCandidates, - ...(frozenCandidates.length ? { frozenCandidates } : {}), - ...(sameProblem && archived.environmentDigest === state.environmentDigest && archived.verificationCheckpoints?.length - ? { verificationCheckpoints: archived.verificationCheckpoints } : {}), - ...(taskDrafts.length ? { taskDrafts } : {}), - ...(researchCheckpoints.length ? { researchCheckpoints } : {}), - candidateIds: planned.filter(node => !isAdvisoryTask(node.task) && - ((node.proof?.passed && !node.proof.conditions?.length) || - (node.integratedCheck?.passed && !node.integratedCheck.conditions?.length) || - // A prior continuation may have rejected correct canonical sources in a - // broken projection. Reconsider that attempted contract, never its status. - (node.integratedCheck?.taskDigest === taskVersion(node.task) && !node.integratedCheck.conditions?.length && - hasDeterministicLeanFailure(node.integratedCheck.verification)))).map(node => node.task.id), - ...(capacities.length || archived.cooperation.capacityExplorationInputs !== undefined ? { capacityExplorations: { - records: capacities, inputs: archived.cooperation.capacityExplorationInputs, notes: [...notes.values()] } } : {}), - ...(archived.cooperation.nextChecks?.length ? { nextChecks: { records: archived.cooperation.nextChecks, - tasks: archived.cooperation.tasks.filter(node => node.nextCheckId).map(node => ({ task: node.task, - nextCheckId: node.nextCheckId!, status: node.status, ...(node.finding ? { finding: node.finding } : {}) })) } } : {}), - ...(proofSearch ? { proofSearch } : {}), - ...(!added && archived.cooperation.goalProgress ? { goalProgress: archived.cooperation.goalProgress } : {}), - ...(completedResearch.length ? { completedResearch } : {}), - ...(completedResearch.length || context.deliveries.length ? { researchContext: context } : {}), - ...(added ? { ownershipExtension: { sourceReceiptDigest: archived.problem.receiptDigest, - sourcePolicyDigest: policyDigest(archived.problem), addedFiles: added } } : {}), - history: { evidence: 'recorded-not-replayed', sourcePhase: archived.phase, - ...(initialPlanning ? { activity: continuationActivity(archived, archived.workers) } : {}), - tasks: archived.cooperation.tasks.map(node => ({ taskId: node.task.id, taskDigest: taskVersion(node.task), status: node.status, - attempts: node.attempts, assignment: node.assignment, finding: node.finding, - proof: proofHistory(node.proof), integratedCheck: proofHistory(node.integratedCheck) })), - deliveries: archived.cooperation.deliveries?.map(delivery => initialPlanning ? delivery : ({ id: delivery.id, kind: delivery.kind, status: delivery.status, - taskId: delivery.taskId, taskDigest: delivery.taskDigest, commit: delivery.commit, producer: delivery.producer, - summary: delivery.summary, evidenceRefs: delivery.evidenceRefs })), - history: archived.cooperation.history?.map(record => ({ task: record.task, producer: record.producer, finding: record.finding, - researchCompletion: record.researchCompletion, - proof: proofHistory(record.proof), integratedCheck: record.integratedCheck && { - commit: record.integratedCheck.commit, passed: record.integratedCheck.passed } })) }, - }; - return sourceSchema.parse(value); -} - -/** Capture advisory source bytes and history without initializing a run or checking a proof. */ -export { captureSource as captureSolverContinuationSource }; -// The single-researcher importer shares source contracts and draft capture, not the task scheduler. -export { policyDigest as continuationSourcePolicyDigest, ownershipExtension as continuationOwnershipExtension, - capturedTaskDrafts as captureContinuationTaskDrafts }; -export { seedSingleSolverContinuation } from './singleContinuationSeed'; - -function taskDraftDocuments(drafts: readonly SavedTaskDraft[]) { - const chunks: string[] = []; - let entries: string[] = [], bytes = 2; - for (const draft of drafts) { - const text = canonicalMathJson(draft), size = Buffer.byteLength(text); - if (size + 2 > MAX_CONTINUATION_ATTACHMENT_BYTES) throw new Error('math_continuation_snapshot_invalid'); - if (entries.length && bytes + 1 + size > MAX_CONTINUATION_ATTACHMENT_BYTES) { - chunks.push(`[${entries.join(',')}]`); entries = []; bytes = 2; - } - bytes += size + (entries.length ? 1 : 0); entries.push(text); - } - if (entries.length || !chunks.length) chunks.push(`[${entries.join(',')}]`); - return chunks.map((text, index) => ({ id: index ? `seed-task-drafts-${index + 1}` : 'seed-task-drafts', - kind: 'proof-source' as const, text, commit: null })); -} - -function freezeSource(source: SeedSource, directory: string) { - const documents: { id: string; kind: ContinuationManifest['attachments'][number]['kind']; text: string; commit?: null }[] = [ - { id: 'seed-recovery-guide', kind: 'research-notes' as const, text: - (source.initialPlanning - ? 'The source published no accepted initial plan. Canonical owned sources, worker drafts and notes were preserved; prior planning turns and usage remain recorded in seed-history. The Lead still owes the first plan covering every original target.\n' - : 'The canonical owned sources and exact task graph were explicitly initialized in this new run. ') + - 'Historical proof flags, threads and assignments do not authorize work or acceptance. Only freshly checked helpers are integrated; conditional proofs retain their typed obligations.\n' + - 'Per-task saved drafts, including suspended tasks, are preserved in seed-task-drafts with exact sources, missing-versus-empty notes and their original run/commit identities. Compatible drafts resume through the normal task draft restoration; changed task or environment snapshots remain advisory. Inspect draft-WORKER_ID for the current worker workspace as well. Match captured task ids and digests before recovering useful code. Preserve current canonical proofs; recovered drafts still require ordinary typed host checks.\n' + - 'Ordinary research/sketch no-progress counts and pauses are retained in seed-research-checkpoints only while the task, environment, effective inputs and saved task output still match. A pause is scheduling state and never proof acceptance, research completion or mathematical refutation.\n' + - 'The original run may still be progressing. Its canonical sources are pinned to the recorded commit; worker files are individually stable captured bytes, not a globally atomic observation. Repeated initialization uses this same frozen capture.\n' + - (source.ownershipExtension ? `This run re-bootstraps the same problem with added owned files ${JSON.stringify(source.ownershipExtension.addedFiles)}; ` + - 'they start at their baseline and worker drafts hold only the former owned files. Research findings bound to the former problem receipt are history and their tasks reopen.\n' : '') }, - { id: 'seed-canonical', kind: 'proof-source' as const, text: canonicalMathJson({ sources: source.canonicalSources }) }, - { id: 'seed-task-graph', kind: 'diagnostics' as const, text: canonicalMathJson(source.plan) }, - { id: 'seed-history', kind: 'diagnostics' as const, text: canonicalMathJson({ source: source.source, history: source.history, - ...(source.verificationCheckpoints ? { verificationCheckpoints: source.verificationCheckpoints } : {}), - capturedAt: source.capturedAt, capture: 'canonical-commit-and-individually-stable-advisory-worker-files' }) }, - ...source.workers.map(worker => ({ id: `draft-${worker.id}`, kind: 'proof-source' as const, text: canonicalMathJson(worker) })), - ...(source.conditionalCandidates ?? []).map(candidate => ({ id: `conditional-${candidate.taskId}`, kind: 'proof-source' as const, - text: canonicalMathJson(candidate) })), - ...(source.frozenCandidates ?? []).map(candidate => ({ id: `frozen-${candidate.taskId}`, kind: 'proof-source' as const, - text: canonicalMathJson(candidate), commit: candidate.snapshotCommit })), - ...(source.capacityExplorations ? [{ id: 'seed-capacity-explorations', kind: 'research-notes' as const, - text: canonicalMathJson(source.capacityExplorations), commit: null }] : []), - ...(source.completedResearch ? [{ id: 'seed-completed-research', kind: 'research-notes' as const, - text: canonicalMathJson(source.completedResearch), commit: null }] : []), - ...(source.researchContext ? [{ id: 'seed-research-context', kind: 'research-notes' as const, - text: canonicalMathJson(source.researchContext), commit: null }] : []), - ...(source.taskDrafts ? taskDraftDocuments(source.taskDrafts) : []), - ...(source.researchCheckpoints ? [{ id: 'seed-research-checkpoints', kind: 'diagnostics' as const, - text: canonicalMathJson(source.researchCheckpoints), commit: null }] : []), - ]; - const manifest: ContinuationManifest = { schema: 'theorem-os.continuation-snapshot.v1', taskDigest: source.taskDigest, - problemReceiptDigest: source.problemReceiptDigest, attachments: documents.map(document => { - const sha256 = mathDigest(document.text); - return { id: document.id, kind: document.kind, path: `${document.id}.json`, bytes: Buffer.byteLength(document.text), sha256, - provenance: { evidence: 'recorded-not-replayed', runId: source.source.runId, - ...(document.commit === null ? {} : { commit: document.commit ?? source.source.canonicalCommit }), - source: source.source.stateFile }, contentPath: `continuation/${sha256}.txt` }; - }) }; - return freezeContinuationInput({ manifest, digest: mathDigest(canonicalMathJson(manifest)), - contents: new Map(documents.map(document => [mathDigest(document.text), document.text])) }, directory); -} - -/** Explicit initialization of a new, idle run. Historical acceptance is never execution authority. */ -export async function seedSolverContinuation(options: { - sourceRun: string; run: string; root: string; buildManifest: string; signal: AbortSignal; timeoutMs?: number; - onProgress?: (event: string, details: Record) => void; - lease?: MathLease; preparedEnvironment?: NodeJS.ProcessEnv; deferChecks?: boolean; - onSeeded?: (state: SolverRunState, freshChecks: TaskProof[]) => void; -}): Promise { - const target = readRunInspection(options.run), sourceStateFile = path.basename(path.resolve(options.sourceRun)) === 'state.json' - ? path.resolve(options.sourceRun) : `${path.resolve(options.sourceRun)}.runtime/state.json`; - const stateFile = target.stateFile, directory = path.dirname(stateFile); - assertMathCanonicalPath(sourceStateFile); - if (sourceStateFile === stateFile) throw new Error('math_continuation_seed_identity_changed'); - const seedWithLease = async (lease: MathLease): Promise => { - const state = readRunInspection(options.run).state; - const sourceFile = path.join(directory, 'continuation-seed-source.json'), reportFile = path.join(directory, 'continuation-seed.json'); - const seeded = Boolean(fs.lstatSync(sourceFile, { throwIfNoEntry: false })); - assertPrepared(state, stateFile, seeded); - const buildFile = fs.realpathSync(options.buildManifest); - readMathBuildManifest(buildFile, options.root, path.join(options.root, 'out', 'main')); - if (mathDigest(readMathFile(buildFile).bytes) !== state.buildDigest) throw new Error('math_continuation_seed_build_changed'); - let source: SeedSource; - if (seeded) { - assertMathCanonicalPath(sourceFile); - if ((fs.lstatSync(sourceFile).mode & 0o777) !== 0o400) throw new Error('math_continuation_seed_source_not_frozen'); - source = sourceSchema.parse(readMathJson(sourceFile)); - } else { - const archived = readSolverRunState(sourceStateFile); - source = archived.cooperation?.proofReadyRecords?.some(record => record.status === 'frozen') - ? await withMathRuntimeLease({ lockPath: path.join(path.dirname(sourceStateFile), 'run.lock'), - flockExecutable: '/usr/bin/flock', signal: lease.signal }, async sourceLease => - captureSource(sourceStateFile, stateFile, state, sourceLease)) - : captureSource(sourceStateFile, stateFile, state); - } - if (source.taskDigest !== state.taskDigest || source.problemReceiptDigest !== state.problem.receiptDigest || - source.sourcePolicyDigest !== policyDigest(state.problem) || source.source.stateFile !== sourceStateFile || - source.destination.runId !== state.runId || source.destination.stateFile !== stateFile || - source.destination.buildDigest !== state.buildDigest || source.destination.methodDigest !== state.methodDigest || - source.destination.environmentDigest !== state.environmentDigest || - canonicalMathJson(Object.keys(source.canonicalSources).sort()) !== canonicalMathJson([...state.problem.ownedFiles].sort())) - throw new Error('math_continuation_seed_identity_changed'); - const plan = validateSeedPlan(state, source); - const conditional = source.conditionalCandidates ?? []; - const candidateIds = [...source.candidateIds, ...conditional.map(candidate => candidate.taskId)]; - if (new Set(candidateIds).size !== candidateIds.length || candidateIds.some(candidate => - !plan.tasks.some(task => task.id === candidate && !isAdvisoryTask(task))) || conditional.some(candidate => - !candidate.captureError && (canonicalMathJson(Object.keys(candidate.sources ?? {}).sort()) !== - canonicalMathJson([...state.problem.ownedFiles].sort()) || - canonicalMathJson(Object.keys(candidate.seedSources ?? {}).sort()) !== - canonicalMathJson([...state.problem.ownedFiles].sort())))) throw new Error('math_continuation_seed_candidates_invalid'); - const planVersion = source.initialPlanning ? undefined : mathDigest(canonicalMathJson(plan)); - const frozenAssignment = (candidate: z.infer, canonicalCommit: string) => - frozenTaskAssignment(candidate, plan.tasks.find(task => task.id === candidate.taskId)!, - { runId: state.runId, sourceRunId: source.source.runId, canonicalCommit }); - const pendingResearch = new Map>(); - const restoredResearch = state.cooperation ? currentCompletedResearch(source, state, plan.tasks, - state.cooperation.tasks, restoredResearchDeliveries(source, state)) : pendingResearch; - const restoredCheckpoints = currentResearchCheckpoints(source, state); - const matchesCheckpoint = (taskId: string, checkpoint: ResearchCheckpoint) => { - const saved = restoredCheckpoints.get(taskId); - const { blockerId: _localBlocker, ...scheduling } = checkpoint; - return saved && canonicalMathJson(scheduling) === canonicalMathJson(saved.checkpoint); - }; - const matchesResearch = (node: TaskRecord, records: typeof pendingResearch) => { - const record = records.get(node.task.id); - const checkpoint = state.cooperation?.researchCheckpoints?.[node.task.id]; - const paused = checkpoint?.paused && matchesCheckpoint(node.task.id, checkpoint) && - node.feedback === UNCHANGED_RESEARCH_CHECKPOINT; - return node.status === (record ? 'completed' : paused ? 'blocked' : 'pending') && node.finding === record?.finding && - canonicalMathJson(node.researchCompletion ?? null) === canonicalMathJson(record?.record ?? null); - }; - const priorCooperation = state.cooperation; - lease.assertHeld(); - const proofSearch = restoreProofSearch(source, state, directory); - if (seeded && priorCooperation && (priorCooperation.planVersion !== planVersion || - canonicalMathJson(plannedTaskRecords(priorCooperation.tasks).map(node => node.task)) !== canonicalMathJson(plan.tasks) || - canonicalMathJson(capacityOrigin(capturedCapacityRecords(state))) !== - canonicalMathJson(capacityOrigin(source.capacityExplorations?.records ?? [])) || - canonicalMathJson(priorCooperation.capacityExplorationInputs ?? []) !== - canonicalMathJson(source.capacityExplorations?.inputs ?? []) || - canonicalMathJson(priorCooperation.nextChecks ?? []) !== canonicalMathJson(proofSearch.checks ?? []) && - canonicalMathJson(priorCooperation.nextChecks ?? []) !== canonicalMathJson(source.nextChecks?.records ?? []) || - canonicalMathJson(priorCooperation.proofSearchRecords ?? {}) !== canonicalMathJson(proofSearch.records) || - source.researchContext && canonicalMathJson(priorCooperation.deliveries ?? []) !== - canonicalMathJson(restoredResearchDeliveries(source, state)) || - (source.completedResearch || source.researchCheckpoints) && ![pendingResearch, restoredResearch].some(records => - priorCooperation.tasks.filter(node => isAdvisoryTask(node.task) && !node.capacityExploration && !node.nextCheckId) - .every(node => matchesResearch(node, records))) || - source.researchCheckpoints && Object.entries(priorCooperation.researchCheckpoints ?? []) - .some(([taskId, checkpoint]) => !matchesCheckpoint(taskId, checkpoint)) || - priorCooperation.tasks.some(node => node.assignment && !conditional.some(candidate => - candidate.taskId === node.task.id && node.status === 'conditional' && - node.assignment!.taskDigest === candidate.taskDigest && node.assignment!.workerId === 'continuation') && - !(source.frozenCandidates ?? []).some(candidate => candidate.taskId === node.task.id && node.status === 'pending' && - canonicalMathJson(node.assignment) === canonicalMathJson(frozenAssignment(candidate, priorCooperation.canonicalCommit!))) && - !(source.taskDrafts ?? []).some(draft => !source.ownershipExtension && restorableTaskDraft(draft, node, state) && - canonicalMathJson(node.assignment) === canonicalMathJson(taskDraftAssignment(draft, node.task, - priorCooperation.tasks, state)))))) - throw new Error('math_continuation_seed_destination_changed'); - if (seeded && state.cooperation) { - const previous = fs.existsSync(reportFile) ? readMathJson(reportFile) as Partial : undefined; - const head = git(state.worktree, ['rev-parse', 'HEAD']); - if (![state.problem.baseCommit, state.cooperation.canonicalCommit].includes(head) || - (previous?.sourcesInstalled && (head !== state.cooperation.canonicalCommit || - git(state.worktree, ['status', '--porcelain', '--untracked-files=no'])))) - throw new Error('math_continuation_seed_destination_changed'); - } - if (!seeded && (git(state.worktree, ['rev-parse', 'HEAD']) !== state.problem.baseCommit || - git(state.worktree, ['status', '--porcelain', '--untracked-files=no']) || fs.existsSync(path.join(state.worktree, 'RESEARCH.md')))) - throw new Error('math_continuation_seed_destination_changed'); - // Restoring frozen deliveries also resets their worker checkouts. Preserve - // new destination work before publishing state or rechecking any sources. - for (const candidate of source.frozenCandidates ?? []) { - const worker = state.workers!.find(worker => worker.id === candidate.workerId); - if (!worker || worker.worktree === state.worktree) continue; - const restoredSources = git(worker.worktree, ['ls-tree', '-r', '--name-only', '-z', candidate.snapshotCommit, '--', - ...state.problem.ownedFiles.map(file => path.join(state.problem.projectRelative, file)), 'RESEARCH.md']).split('\0').filter(Boolean); - if (![state.problem.baseCommit, candidate.snapshotCommit].includes(git(worker.worktree, ['rev-parse', 'HEAD'])) || - git(worker.worktree, ['status', '--porcelain', '--untracked-files=no']) || - restoredSources.length && git(worker.worktree, ['ls-files', '--others', '-z', '--', ...restoredSources])) - throw new Error('math_continuation_seed_destination_changed'); - } - lease.assertHeld(); - if (!seeded) writeMathJsonDurable(sourceFile, source, 0o400); - const deferChecks = options.deferChecks && candidateIds.length > 0; - if (deferChecks && !state.pendingContinuationSource) { - state.pendingContinuationSource = sourceStateFile; - writeSolverRunState(stateFile, state); - } - const report: ContinuationSeedReport = { schema: 'theorem-os.continuation-seed.v1', sourceRunId: source.source.runId, - runId: state.runId, sourceStateFile, stateFile, sourceDigest: mathDigest(canonicalMathJson(source)), stage: 'frozen', - candidates: candidateIds, checked: [], failed: [], evidence: 'advisory-sources-require-recheck' }; - const saveReport = () => { lease.assertHeld(); writeMathJsonDurable(reportFile, report); }; - const emit = (event: string, details: Record = {}) => options.onProgress?.(event, details); - let proofEnvironment: Awaited> | undefined; - try { - const snapshot = freezeSource(source, directory); - report.snapshotDigest = snapshot.digest; - if (state.continuationDigest && state.continuationDigest !== snapshot.digest) - throw new Error('math_continuation_seed_destination_changed'); - readContinuationSnapshot(snapshot.file, snapshot.digest, { taskDigest: state.taskDigest, problemReceiptDigest: state.problem.receiptDigest }); - saveReport(); - for (const { record, text } of proofSearch.artifacts.values()) - installRetainedProofSearchText(directory, record, text); - const canonical = await withSolverWorktree(state.worktree, state.problem.baseCommit, async checkout => { - for (const [file, text] of Object.entries(source.canonicalSources)) { - const target = path.join(checkout, state.problem.projectRelative, file); assertMathCanonicalPath(target); - fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, text); - } - assertSolverSources(state.problem, checkout); - const commit = commitSolverSources(state.problem, checkout); - git(state.worktree, ['update-ref', `refs/math/${state.runId}/continuation/source`, commit]); - return commit; - }); - lease.signal.throwIfAborted(); - report.canonicalCommit = canonical; report.stage = 'installing'; saveReport(); - const capacities = source.capacityExplorations?.records ?? []; - const tasks: TaskRecord[] = plan.tasks.map(task => ({ task, attempts: 0, - status: 'pending', - ...(plan.proofRoutes?.length ? { alternativeRoutes: plan.proofRoutes.filter(route => route.targetTaskId === task.id) } : {}) })); - for (const record of capacities.filter(item => !item.archived)) tasks.push({ task: record.task as CooperativeTask, - capacityExploration: record.capacityExploration, attempts: 0, - status: record.status === 'completed' ? 'completed' : 'pending', - ...(record.finding === undefined ? {} : { finding: record.finding }) }); - for (const node of source.nextChecks?.tasks ?? []) { - const stale = proofSearch.checks?.some(check => check.id === node.nextCheckId && check.status === 'stale'); - tasks.push({ task: stale ? { ...node.task, status: 'stopped' } : node.task, nextCheckId: node.nextCheckId, - attempts: 0, status: node.status === 'completed' ? 'completed' : node.status === 'blocked' || stale ? 'blocked' : 'pending', - ...(node.finding ? { finding: node.finding } : {}) }); - } - // A timeout only grants more time to the identical tree/items/environment key; - // it never restores proof acceptance. Retries retain this run's later timeout progress. - if (!state.continuationDigest && source.verificationCheckpoints) state.verificationCheckpoints = source.verificationCheckpoints.map(record => ({ - key: record.key, timeoutMs: record.timeoutMs, attempts: record.attempts, at: record.at, - targetCommit: record.targetCommit, receiptIds: [...record.receiptIds], - })); - state.continuationDigest = snapshot.digest; - const cooperation: NonNullable = state.cooperation = { tasks, groups: plan.groups.map(group => ({ group, turns: 0 })), proofRoutes: plan.proofRoutes, - canonicalCommit: canonical, leadSeedCommit: canonical, planVersion, planEdited: !source.initialPlanning, - ...(source.capacityExplorations?.inputs === undefined ? {} : { - capacityExplorationInputs: source.capacityExplorations.inputs.map(entry => ({ ...entry })) }), - ...(proofSearch.checks ? { nextChecks: proofSearch.checks } : {}), - ...(Object.keys(proofSearch.records).length ? { proofSearchRecords: proofSearch.records } : {}), - ...(source.goalProgress ? { goalProgress: structuredClone(source.goalProgress) } : {}), - deliveries: [], history: [...capacities.filter(record => record.archived).map(archivedCapacity), - ...completedResearchHistory(source)], edits: [], cursors: {} }; - state.cooperation.deliveries = restoredResearchDeliveries(source, state); - resetGoalProgressClock(state.cooperation.goalProgress); - // Publish pending obligations before installing sources; interruption cannot manufacture acceptance. - writeSolverRunState(stateFile, state); - git(state.worktree, ['reset', '--hard', canonical]); - assertSolverSources(state.problem, state.worktree); - report.sourcesInstalled = true; saveReport(); - emit('continuation_seed_installed', { sourceRunId: source.source.runId, runId: state.runId, tasks: tasks.length, - candidates: candidateIds.length, snapshotDigest: snapshot.digest }); - if (deferChecks) { - report.stage = 'awaiting-checks'; saveReport(); - options.onSeeded?.(state, []); - return report; - } - const environmentFile = path.join(directory, 'environment-solver.json'); - assertMathCanonicalPath(environmentFile); - if ((fs.lstatSync(environmentFile).mode & 0o777) !== 0o400) throw new Error('math_continuation_seed_environment_not_frozen'); - const staticEnv = { ...(options.preparedEnvironment ?? - resolveMathematicsRuntimeEnvironment({ DEEPSCIENTIST_MATH_ENV_FILE: environmentFile })) }; - // Startup-only already disposed its lease. Keep the frozen static identity and - // authorized cache settings, but never resolve or reuse that temporary descriptor. - if (!options.preparedEnvironment) { - delete staticEnv[MATH_PROOF_ENVIRONMENT_ENV]; - delete staticEnv[MATH_PROOF_ENVIRONMENT_SANDBOX_ENV]; - } - const project = path.join(state.worktree, state.problem.projectRelative); - const packages = resolveMathematicsLakePackagesCache(project, staticEnv); - if (!packages) { - const manifestFile = path.join(project, 'lake-manifest.json'); - const manifest = fs.existsSync(manifestFile) ? readMathJson(manifestFile) as { packages?: unknown } : undefined; - if (Array.isArray(manifest?.packages) && manifest.packages.length) throw new Error('math_lake_packages_unavailable'); - } else { - bindLeanPackages(project, packages); - const overrides = path.join(project, '.lake', 'package-overrides.json'); - assertMathCanonicalPath(overrides); - fs.rmSync(overrides, { force: true }); - } - const timeoutMs = options.timeoutMs ?? 180_000; - if (packages && !options.preparedEnvironment) proofEnvironment = await prepareMathProofEnvironment(project, packages, { env: staticEnv, signal: lease.signal, - deadlineAt: Number.isFinite(timeoutMs) ? Date.now() + timeoutMs : undefined, - cacheRoot: DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT, - onProgress: phase => emit('continuation_seed_proof_environment', { phase }) }); - const env = proofEnvironment ? { ...staticEnv, [MATH_PROOF_ENVIRONMENT_ENV]: proofEnvironment.environmentValue } : staticEnv; - report.stage = 'checking'; saveReport(); - const recheck: NonNullable = cooperation.recheck = { - canonicalCommit: canonical, total: candidateIds.length, completed: 0 }; - writeSolverRunState(stateFile, state); - const freshChecks: TaskProof[] = []; - // These receipts belong only to this immutable canonical/environment/task - // snapshot. Persisted status alone never authorizes a retained original. - const freshGoals = new Map(); - const projectors = new Map>(); - const projector = (commit: string) => { - let project = projectors.get(commit); - if (!project) { - project = createTaskSourceProjector(state.problem, state.worktree, commit); - projectors.set(commit, project); - } - return project; - }; - type CandidateSource = { sourceCommit: string; assignment: NonNullable; - conditions: CooperativeTask[]; savedConditional?: (typeof conditional)[number] }; - const candidateSources = new Map>(); - const materializeCandidate = async (node: TaskRecord): Promise => { - const taskId = node.task.id, savedConditional = conditional.find(candidate => candidate.taskId === taskId); - let sourceCommit = canonical, assignment = { taskId, taskDigest: taskVersion(node.task), - workerId: 'continuation', seedCommit: canonical } as NonNullable; - let conditions: CooperativeTask[] = []; - if (savedConditional) { - if (savedConditional.captureError) throw new Error(savedConditional.captureError); - if (savedConditional.taskDigest !== taskVersion(node.task) || !savedConditional.sources || - !savedConditional.seedSources) throw new Error('math_task_condition_version_invalid'); - const byId = new Map(tasks.map(item => [item.task.id, item.task])); - const references = (items: readonly { taskId: string; taskDigest: string }[]) => items.map(reference => { - const task = byId.get(reference.taskId); - if (!task || taskVersion(task) !== reference.taskDigest) throw new Error('math_task_condition_version_invalid'); - return task; - }); - conditions = references(savedConditional.conditions); - const dependencies = references(savedConditional.dependencies); - if (!conditions.every(task => assumableLemma(task) && - dependencies.some(dependency => dependency.id === task.id)) || new Set(conditions.map(task => task.id)).size !== conditions.length) - throw new Error('math_task_condition_version_invalid'); - const frozen = await withSolverWorktree(state.worktree, state.problem.baseCommit, async checkout => { - const write = (sources: Record) => { - for (const [file, text] of Object.entries(sources)) { - const target = path.join(checkout, state.problem.projectRelative, file); - assertMathCanonicalPath(target); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, text); - } - return commitSolverSources(state.problem, checkout); - }; - const seedCommit = write(savedConditional.seedSources!); - const proofCommit = write(savedConditional.sources!); - return { seedCommit, proofCommit }; - }); - assignment = { ...assignment, seedCommit: frozen.seedCommit, dependencies: savedConditional.dependencies }; - if (!node.task.conditional) assignment.connectionCheck = createTaskConnectionCheck(node.task, assignment, - tasks.map(item => conditions.some(condition => condition.id === item.task.id) ? { ...item, status: 'pending' } : item), - { environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest }, - task => savedConditional.seedSources![task.proofPath!] ?? ''); - sourceCommit = frozen.proofCommit; - git(state.worktree, ['update-ref', `refs/math/${state.runId}/continuation/conditional/${taskId}`, sourceCommit]); - } - return { sourceCommit, assignment, conditions, savedConditional }; - }; - const candidateSource = (node: TaskRecord) => { - let candidate = candidateSources.get(node.task.id); - if (!candidate) { - candidate = materializeCandidate(node); - candidateSources.set(node.task.id, candidate); - } - return candidate; - }; - const sourceDependencies = new Map(); - for (const taskId of candidateIds) { - lease.signal.throwIfAborted(); lease.assertHeld(); - const node = tasks.find(item => item.task.id === taskId)!; - const inputs = taskDependencyRecords(node.task, tasks).map(item => item.task.id); - try { - // Conditional declarations may exist only in their frozen delivery. - // Discover their original inputs from that same source identity. - const { sourceCommit, conditions } = await candidateSource(node); - inputs.push(...projectedGoalInputs(projector(sourceCommit), node.task, tasks, conditions).map(item => item.task.id)); - } catch { /* Candidate preparation publishes its exact projection error below. */ } - sourceDependencies.set(taskId, [...new Set(inputs)]); - } - type Candidate = { node: TaskRecord; sourceCommit: string; request: TaskProofRequest; - availableGoals: string[]; savedConditional?: (typeof conditional)[number] }; - const prepareCandidate = async (node: TaskRecord, restoreContext = false): Promise => { - const taskId = node.task.id; - const { sourceCommit, assignment, conditions, savedConditional } = await candidateSource(node); - const availableGoals = tasks.filter(item => item.task.id !== taskId && item.task.kind === 'goal' && - freshGoals.get(item.task.id) === taskVersion(item.task)).map(item => item.task.id); - const retainedGoals = availableGoals.filter(id => restoreContext || - sourceDependencies.get(taskId)!.includes(id)).map(id => tasks.find(item => item.task.id === id)!.task.theoremName!); - return { node, savedConditional, sourceCommit, availableGoals, request: { task: node.task, retainedGoals, assignment, - ...(conditions.length ? { conditions } : {}) } }; - }; - const blockCandidate = (node: TaskRecord, error: unknown) => { - lease.signal.throwIfAborted(); lease.assertHeld(); - setTaskStatus(node, 'blocked', 'reconstructed'); node.integratedCheck = undefined; node.proof = undefined; node.assignment = undefined; - node.feedback = error instanceof Error ? error.message : 'math_continuation_seed_helper_check_failed'; - }; - const completeCandidate = (node: TaskRecord) => { - lease.signal.throwIfAborted(); lease.assertHeld(); - const taskId = node.task.id; - const first = !report.checked.includes(taskId); - if (first) report.checked.push(taskId); - report.failed = report.failed.filter(id => id !== taskId); - if (node.status === 'blocked') report.failed.push(taskId); - if (node.status === 'integrated') report.evidence = 'fresh-helper-receipts'; - if (first) recheck.completed++; - recheck.taskId = undefined; - cooperation.deliveries = restoredResearchDeliveries(source, state); - writeSolverRunState(stateFile, state); saveReport(); - emit('continuation_seed_checked', { taskId, passed: node.status === 'integrated' || node.status === 'conditional' }); - }; - const retryable = new Map(); - const publishCandidate = (candidate: Candidate, proof: TaskProof) => { - const { node, savedConditional, sourceCommit, request: { assignment } } = candidate; - try { - lease.signal.throwIfAborted(); lease.assertHeld(); - const fresh = proof.passed && isAttributedTaskProof(proof) && - proof.taskDigest === taskVersion(node.task) && proof.commit === sourceCommit && proof.seedCommit === assignment.seedCommit && - canonicalMathJson(proof.conditions ?? []) === canonicalMathJson(savedConditional?.conditions ?? []) && - proof.verification.status === 'kernel_verified' && proof.verification.results.length > 0 && - proof.verification.results.every(result => result.status === 'kernel_verified' && typeof result.receiptId === 'string' && result.receiptId); - for (const commit of [proof.commit, proof.verification.targetCommit]) if (commit) { - if (!oid.safeParse(commit).success) throw new Error('math_continuation_seed_invalid_receipt_commit'); - git(state.worktree, ['update-ref', `refs/math/${state.runId}/evidence/${commit}`, commit]); - } - if (savedConditional) { - node.proof = proof; - node.assignment = fresh ? assignment : undefined; - setTaskStatus(node, fresh ? 'conditional' : 'blocked', 'reconstructed'); - if (fresh && options.preparedEnvironment) rememberFreshConditionalCheck(proof, { ...candidate.request, - environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, environment: env }); - } else { - node.integratedCheck = proof; - setTaskStatus(node, fresh ? 'integrated' : 'blocked', 'reconstructed'); - if (fresh) { - if (node.task.kind === 'goal') freshGoals.set(node.task.id, taskVersion(node.task)); - } else if (hasDeterministicLeanFailure(proof.verification)) retryable.set(node.task.id, candidate); - } - if (fresh) freshChecks.push(proof); - node.feedback = fresh ? undefined : 'math_continuation_seed_helper_not_verified'; - } catch (error) { - blockCandidate(node, error); - } - completeCandidate(node); - }; - const checkBatch = async (batch: Candidate[]): Promise => { - lease.signal.throwIfAborted(); lease.assertHeld(); - let proofs: TaskProof[]; - try { - proofs = await withVerificationCheckpoints({ environmentDigest: state.environmentDigest, - problemReceiptDigest: state.problem.receiptDigest, checkpoints: state.verificationCheckpoints ??= [], - save: () => { lease.assertOwned(); writeSolverRunState(stateFile, state); }, emit }, - () => checkTaskProofs(state.problem, state.worktree, batch[0].sourceCommit, batch.map(candidate => candidate.request), - env, lease.signal, timeoutMs, state.environmentDigest)); - } catch (error) { - lease.signal.throwIfAborted(); lease.assertHeld(); - if (error instanceof VerificationCheckpointError) throw error; - if (batch.length > 1 && error instanceof Error && seedBatchFallbacks.has(rejectionCode(error))) { - for (const candidate of batch) await checkBatch([candidate]); - } else for (const { node } of batch) { blockCandidate(node, error); completeCandidate(node); } - return; - } - if (batch.length > 1 && proofs.some(proof => !proof.passed && hasDeterministicLeanFailure(proof.verification))) { - emit('continuation_seed_batch_fallback', { taskIds: batch.map(item => item.node.task.id), reason: 'lean-compilation-failed' }); - for (const candidate of batch) await checkBatch([candidate]); - return; - } - for (const [index, candidate] of batch.entries()) publishCandidate(candidate, proofs[index]); - }; - const checkWave = async (ids: string[], restoreContext = false) => { - const groups = new Map(); - const batches: (Candidate[] | { node: TaskRecord; error: unknown })[] = []; - for (const taskId of ids) { - lease.signal.throwIfAborted(); lease.assertHeld(); - const node = tasks.find(node => node.task.id === taskId)!; - try { - const candidate = await prepareCandidate(node, restoreContext), { sourceCommit, request } = candidate; - const projection = projector(sourceCommit)(request.task, request.retainedGoals, request.conditions); - const key = mathDigest(canonicalMathJson({ sourceCommit, sources: [...projection], retainedGoals: request.retainedGoals, - conditions: request.conditions?.map(task => ({ taskId: task.id, taskDigest: taskVersion(task) })) ?? [], - premises: request.task.premises ?? [], environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest })); - let group = groups.get(key); - if (!group || group.length === maxSeedBatchSize) { group = []; groups.set(key, group); batches.push(group); } - group.push(candidate); - } catch (error) { - lease.signal.throwIfAborted(); lease.assertHeld(); batches.push({ node, error }); - } - } - for (const batch of batches) { - lease.signal.throwIfAborted(); lease.assertHeld(); - const nodes = Array.isArray(batch) ? batch.map(candidate => candidate.node) : [batch.node]; - recheck.taskId = nodes[0].task.id; writeSolverRunState(stateFile, state); - for (const node of nodes) emit('continuation_seed_check', { taskId: node.task.id, batchSize: nodes.length, restoreContext }); - if (Array.isArray(batch)) await checkBatch(batch); - else { blockCandidate(batch.node, batch.error); completeCandidate(batch.node); } - } - }; - const pending = new Set(candidateIds); - while (pending.size) { - const wave = [...pending].filter(id => sourceDependencies.get(id)!.every(input => !pending.has(input))); - if (!wave.length) { - for (const id of pending) { - const node = tasks.find(item => item.task.id === id)!; - blockCandidate(node, new Error(`math_continuation_seed_dependency_cycle\n${id}: ${sourceDependencies.get(id)!.join(', ')}`)); - completeCandidate(node); - } - break; - } - await checkWave(wave); - wave.forEach(id => pending.delete(id)); - } - // One recovery attempt is allowed only when independently checked originals - // have added actual context since this candidate's first request. - for (const [id, candidate] of [...retryable]) { - if (candidate.savedConditional || ![...freshGoals.keys()].some(goal => goal !== id && !candidate.availableGoals.includes(goal))) continue; - emit('continuation_seed_context_retry', { taskId: id, canonicalCommit: canonical }); - await checkWave([id], true); - } - // Rechecking typed inputs may retire a former investigation. Keep its frozen - // provenance and tombstone without importing an old assignment or acceptance. - for (const record of capacities.filter(item => !item.archived)) { - const index = tasks.findIndex(node => node.task.id === record.task.id), node = tasks[index]; - const owner = state.workers!.find(worker => worker.id === record.capacityExploration.workerId); - if (node && owner && researchWorkerCanNode(owner, node) && currentCapacityExploration(node, tasks, - { environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest })) continue; - if (index >= 0) tasks.splice(index, 1); - state.cooperation.history!.push(archivedCapacity(record)); - } - state.cooperation.deliveries = restoredResearchDeliveries(source, state); - const completedResearch = currentCompletedResearch(source, state, plan.tasks, tasks, state.cooperation.deliveries); - // Host next checks restore their lifecycle and finding with their own records. - for (const node of tasks.filter(node => isAdvisoryTask(node.task) && !node.capacityExploration && !node.nextCheckId)) { - const completion = completedResearch.get(node.task.id); - setTaskStatus(node, completion ? 'completed' : 'pending', 'reconstructed'); - node.finding = completion?.finding; node.researchCompletion = completion?.record; - } - state.cooperation.history = [...state.cooperation.history!.filter(record => 'capacityExploration' in record), - ...completedResearchHistory(source, completedResearch)]; - // Frozen unfinished deliveries are executable source inputs, never inherited acceptance. Leave - // them pending for normal WorkerProofLifecycle deadlines rather than checking during cold seeding. - for (const candidate of source.frozenCandidates ?? []) { - lease.signal.throwIfAborted(); lease.assertHeld(); - const node = tasks.find(node => node.task.id === candidate.taskId); - const worker = state.workers!.find(worker => worker.id === candidate.workerId); - if (!node || !worker || node.status === 'integrated' || node.status === 'conditional') continue; - const names = [...state.problem.ownedFiles].sort(); - if (source.ownershipExtension || candidate.taskDigest !== taskVersion(node.task) || - candidate.problemReceiptDigest !== state.problem.receiptDigest || candidate.environmentDigest !== state.environmentDigest || - candidate.dependencies.some(reference => !tasks.some(node => node.task.id === reference.taskId && taskVersion(node.task) === reference.taskDigest)) || - canonicalMathJson(Object.keys(candidate.sources).sort()) !== canonicalMathJson(names) || - canonicalMathJson(Object.keys(candidate.seedSources).sort()) !== canonicalMathJson(names) || - candidate.sourceDigest !== ownedSourceDigest(state.problem, state.worktree, candidate.snapshotCommit) || - assessTaskResponsibility({ ...node, assignment: undefined }, worker, { tasks, groups: state.cooperation.groups }).kind !== 'matches') - throw new Error('math_continuation_seed_frozen_identity_changed'); - for (const [commit, sources] of [[candidate.seedCommit, candidate.seedSources], - [candidate.snapshotCommit, candidate.sources]] as const) { - for (const file of state.problem.ownedFiles) if (committedSource(state.worktree, commit, - `${state.problem.projectRelative}/${file}`) !== sources[file]) throw new Error('math_continuation_seed_frozen_source_changed'); - await withSolverWorktree(state.worktree, commit, async checkout => { assertSolverSources(state.problem, checkout); }); - git(state.worktree, ['update-ref', `refs/math/${state.runId}/continuation/frozen/${candidate.taskId}/${commit}`, commit]); - } - const assignment = frozenAssignment(candidate, canonical); - const ready = proofReadyRecord({ assignment, workerId: worker.id, - submissionId: mathDigest(canonicalMathJson({ sourceRunId: source.source.runId, readyId: candidate.readyId, runId: state.runId })), - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, now: source.capturedAt }); - Object.assign(ready, { status: 'frozen', frozenAt: source.capturedAt, - snapshotCommit: candidate.snapshotCommit, sourceDigest: candidate.sourceDigest }); - git(worker.worktree, ['reset', '--hard', candidate.snapshotCommit]); - assertSolverSources(state.problem, worker.worktree); - node.assignment = assignment; node.proof = undefined; node.integratedCheck = undefined; - setTaskStatus(node, 'pending', 'reconstructed'); - (state.cooperation.proofReadyRecords ??= []).push(ready); - emit('continuation_seed_frozen_pending', { taskId: candidate.taskId, workerId: worker.id, readyId: ready.id, - sourceRunId: source.source.runId, sourceReadyId: candidate.readyId, snapshotCommit: candidate.snapshotCommit, - sourceDigest: candidate.sourceDigest, acceptance: 'not-assessed' }); - } - // A worker's current workspace may belong to a different task. Install the - // saved task snapshots, not its workspace, for ordinary on-dispatch recovery. - for (const draft of source.taskDrafts ?? []) { - const node = tasks.find(node => node.task.id === draft.taskId); - if (source.ownershipExtension || !node || node.assignment || !restorableTaskDraft(draft, node, state)) continue; - lease.signal.throwIfAborted(); lease.assertHeld(); - const assignment = taskDraftAssignment(draft, node.task, tasks, state); - const artifacts = await withSolverWorktree(state.worktree, draft.commit, async checkout => { - assertSolverSources(state.problem, checkout); - if (canonicalMathJson(Object.keys(draft.sources).sort()) !== canonicalMathJson([...state.problem.ownedFiles].sort()) || - state.problem.ownedFiles.some(file => committedSource(checkout, draft.commit, - `${state.problem.projectRelative}/${file}`) !== draft.sources[file]) || - (git(checkout, ['ls-tree', '--format=%(objectname)', draft.commit, '--', 'RESEARCH.md']) - ? committedSource(checkout, draft.commit, 'RESEARCH.md') : null) !== draft.notes || - draftOutputDigest(state.problem, checkout, draft.commit) !== draft.outputDigest) - throw new Error('math_continuation_seed_draft_source_changed'); - // Compare the retained canonical basis during normal restoration. A newer - // canonical keeps precedence; its saved notes and source evidence survive. - ownedSourceDigest(state.problem, checkout, draft.canonicalCommit ?? draft.seedCommit); - return captureDeliveryArtifacts({ problem: state.problem, worktree: checkout, commit: draft.commit, assignment }); - }); - for (const commit of new Set([draft.seedCommit, draft.canonicalCommit ?? draft.seedCommit, draft.commit])) - git(state.worktree, ['update-ref', `refs/math/${state.runId}/continuation/drafts/${draft.taskId}/${commit}`, commit]); - node.assignment = assignment; - (state.cooperation.researchDrafts ??= {})[draft.taskId] = { taskDigest: draft.taskDigest, workerId: draft.workerId, - assignmentId: assignment.assignmentId, seedCommit: draft.seedCommit, canonicalCommit: draft.canonicalCommit, - commit: draft.commit, outputDigest: draft.outputDigest, artifacts, suspended: true, - handoffNotesDigest: draft.handoffNotesDigest, feasibilityInputDigest: draft.feasibilityInputDigest }; - emit('continuation_seed_task_draft_pending', { taskId: draft.taskId, workerId: draft.workerId, - sourceRunId: draft.source.runId, snapshotCommit: draft.commit, acceptance: 'not-assessed' }); - } - for (const [taskId, saved] of currentResearchCheckpoints(source, state)) { - const node = tasks.find(node => node.task.id === taskId)!, checkpoint = { ...saved.checkpoint }; - (state.cooperation.researchCheckpoints ??= {})[taskId] = checkpoint; - if (checkpoint.paused) { - const scope = `assigned-local-inference/checkpoint:${mathDigest(canonicalMathJson({ - inputDigest: checkpoint.inputDigest, outputDigest: checkpoint.outputDigest }))}`; - const [blocker] = recordRouteBlockers(state.cooperation.blockers ??= [], - validateBlockerProposals([{ mechanism: 'unchanged-research-checkpoint', scope }], node.task, tasks), - node.task, tasks, state.environmentDigest, state.problem.receiptDigest, source.capturedAt); - blocker.status = 'parked'; blocker.count = 2; checkpoint.blockerId = blocker.id; - setTaskStatus(node, 'blocked', 'reconstructed'); node.feedback = UNCHANGED_RESEARCH_CHECKPOINT; - } - emit('continuation_seed_research_checkpoint_restored', { taskId, workerId: saved.workerId, - sourceRunId: saved.source.runId, count: checkpoint.count, paused: Boolean(checkpoint.paused), - acceptance: 'not-assessed' }); - } - writeSolverRunState(stateFile, state); - report.stage = 'complete'; saveReport(); - if (state.pendingContinuationSource) { - delete state.pendingContinuationSource; - writeSolverRunState(stateFile, state); - } - options.onSeeded?.(state, freshChecks); - return report; - } catch (error) { - report.stage = 'interrupted'; report.error = error instanceof Error ? error.message : 'math_continuation_seed_failed'; - // Already published helper checks are fresh; every unchecked obligation remains pending. - lease.assertOwned(); writeMathJsonDurable(reportFile, report); - throw error; - } finally { - await proofEnvironment?.dispose(); - } - }; - return options.lease ? seedWithLease(options.lease) : - withMathRuntimeLease({ lockPath: path.join(directory, 'run.lock'), flockExecutable: '/usr/bin/flock', signal: options.signal }, seedWithLease); } diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts deleted file mode 100644 index 61022438..00000000 --- a/src/solver/cooperation.ts +++ /dev/null @@ -1,1840 +0,0 @@ -import { isAdvisoryTask as advisory } from './tasks'; -import fs from 'node:fs'; -import path from 'node:path'; -import crypto from 'node:crypto'; -import { VerificationCheckpointError } from './verificationCheckpoint'; -import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; -import { inspectLeanDeclarationRegions, inspectLeanSource, inspectScopedLeanDeclarations } from '../math/leanSource'; -import { committedSource, commitSolverSources, git, originalDeclarationRegions, solverSourceConstraints } from './problem'; -import { solverProofFeedback, solverSourceFeedback } from './feedback'; -import { assessTaskResponsibility, assignSharedResearchTask, independentFeasibilityWorker, researchWorkerCanNode, type ResearchWorker } from './modules/organization'; -import type { DispatchWaitObservation } from './archive'; -import { CAPACITY_EXPLORATION_FOCUSES, capacityExplorationInput, createCapacityExploration, - currentCapacityExploration, TIMED_EXPLORATION_FOCUSES, TIMED_EXPLORATION_IDLE_MS, TIMED_EXPLORATION_MIN_REMAINING_MS, - TIMED_EXPLORATION_UNANSWERED_WAKES, timedExplorationTargets } from './capacityExploration'; -import { hasFreshSolverCheck, proofReceiptsMatch, type ProofCheck } from './modules/evidence'; -import { originalGoalTaskFocus, readyResearchTasks, researchCanAdvance, routeAllowsTask, taskCanStart, taskDependenciesReady, selectedTaskRoute, runningTaskDependencies } from './modules/search'; -import { deliveryDetails, hasPlanResponse, reviewVerdict, readMathResponse as block } from './deliveries'; -import { checkTaskProof, ownedSourceDigest, taskChanges } from './cooperativeProof'; -import { assertStatementSnapshot, isStatementAction, resetStatementReview } from './statementReview'; -import { captureProofReferences } from './proofReferences'; -import { captureDeliveryArtifacts, type DeliveryArtifactManifest } from './deliveryArtifacts'; -import { attributeTaskReferences } from './taskReferenceAttribution'; -import { taskConsumerProjection } from './taskConsumers'; -import { parallelQuestions } from './taskQuestions'; -import { contextCheckpointRejection } from './contextCheckpoint'; -import { assignmentDeliveryReceipts } from './deliveryReceipts'; -import { leadResearchInputs } from './contextCompiler'; -import { deliverHumanGuidance, readHumanGuidance } from './humanGuidance'; -import { mathematicalGaps, mathematicalGapVisible } from './mathematicalGaps'; -import { currentNextCheck, visibleNextChecks } from './nextChecks'; -import { goalProgressForTask } from './goalProgress'; -import { automaticTaskConnection, createTaskConnectionCheck, taskConnectionNeedsRefresh } from './taskConnections'; -import { TACTIC_BATTERY_TIMEOUT_MS } from './tacticBattery'; -import { LIBRARY_APPLICATION_TIMEOUT_MS } from './libraryApplication'; -import { knowledgeReferenceCoverage } from './knowledgeUsage'; -import { taskTypePreflightEnvironmentIdentity, typeDiagnosticExcerpt, type TaskTypePreflight } from './taskTypePreflight'; -import { assignmentDeliveryFile, isActiveFinalCandidateReview, isDefinitionTask, isFeasibilityReview, isFinalCandidateReview, taskGroup, type CooperativeTask, type CooperativeAction, type RouteRecord, type TaskAssignment, type TaskRecord } from './tasks'; -import { consumeLeadWakes, dropLeadWakes, LEAD_MAX_BACKOFF, leadWakePending, settleLeadWakes } from './leadWakes'; -import { idlePeerEpisode, idlePeersAwaitingLead, IDLE_PEER_WAKE_MS, leadInbox, leadInboxBasis, NO_WORK_STAGES, type LeadInboxBasis } from './leadInbox'; -import { restoreResidue } from './stateInvariants'; -import { digest, directDeliveryRejections, isTaskSourceRepairFeedback, LEAD_PLAN_REPAIR_INSTRUCTION, - rejectionCode, CooperationState, TaskVersions, DispatchBudget, RETRY_DISPATCH, DispatchResult, bounded } from './cooperationShared'; -import { CooperationInputs } from './cooperationInputs'; -import { ResearchAdmissionError } from './researchAdmission'; -export { parseCooperationPlan } from './tasks'; -export { taskGroup, taskVersion, taskReferenceDependencies, assignmentDeliveryFile } from './tasks'; -export type { CooperativeTask, RouteGroup, RouteRecord, TaskAssignment, TaskRecord, CooperativeAction } from './tasks'; -export { readCooperationPlan } from './cooperationShared'; -export type { ReviewRecord, HumanEditRecord, InitialPlanPublication, CooperationState } from './cooperationShared'; - -const PREEMPTION_MISMATCH_COOLDOWN_MS = 10 * 60_000; -const ordinaryAdvisoryTask = (task: CooperativeTask) => advisory(task) && !isFeasibilityReview(task) && !isFinalCandidateReview(task); - -/** Lead plans; workers claim distinct ready obligations; only checked source enters the canonical proof. */ -export class CooperativeResearch extends CooperationInputs { - private humanGuidanceCheckpoint(stopped = false): Promise { - if (this.guidancePulse) return this.guidancePulse; - const pending = deliverHumanGuidance({ - stateFile: path.join(path.dirname(this.lead.worktree), 'state.json'), state: this.input.state, stopped, - recipients: () => [...this.active].flatMap(([workerId, active]) => { - const worker = this.input.workers.find(item => item.id === workerId); - if (!worker || active.cancelled || isStatementAction(active.action)) return []; - const action = active.action; - return [{ workerId, role: worker.role, - ...(action.kind === 'task' ? { taskRef: { id: action.task.id, version: action.assignment.taskDigest } } : {}), - ...(action.kind === 'lead' && action.planVersion ? { planVersion: action.planVersion } : {}), - current: () => !this.stopping && !this.input.signal.aborted && this.active.get(workerId) === active && - !active.cancelled && this.current(action), notify: message => active.notify(message, { requireTurn: true }) }]; - }), - onRecord: record => { - this.input.emit('human_guidance_' + record.status, { id: record.id, recipient: record.recipient, - taskRef: record.taskRef, deliveredTo: record.deliveredTo, reason: record.reason }); - // An idle Lead needs a decision turn before its normal checkpoint can deliver this note. - if (record.status === 'deferred' && record.recipient.kind === 'lead' && !record.taskRef && - (!record.recipient.id || record.recipient.id === this.lead.id)) this.wake(); - }, - }).catch(error => { - if (error instanceof Error && error.message === 'math_runtime_lease_busy') return; - this.input.emit('human_guidance_unavailable', { reason: error instanceof Error ? error.message : 'math_guidance_unavailable' }); - }).finally(() => { if (this.guidancePulse === pending) this.guidancePulse = undefined; }); - this.guidancePulse = pending; - return pending; - } - /** - * Optional advisory supply for otherwise idle expanded teams, without a Lead graph mutation. A small team gets - * the same supply only through a narrow gate (timedExplorationDue), on its crux consumer. - */ - private async requestCapacityExploration(worker: ResearchWorker, budget: DispatchBudget, previousReady: readonly TaskRecord[]) { - const expanded = this.input.workers.length > 4 && budget.remainingMs === Infinity; - const timed = this.input.workers.length <= 4; - if (!this.input.continuousResearch || !expanded && !timed || - !['prover', 'researcher', 'engineer'].includes(worker.role) || budget.maxTurns !== Infinity) return false; - return this.input.exclusiveCheck(async () => { - if (this.stopping || this.failure || this.input.signal.aborted || this.input.modelDispatchAllowed?.() === false || - !this.liveWorkers.has(this.lead.id) || !this.allocationPeers.some(peer => peer.id === worker.id) || - this.active.has(worker.id) || this.reservedTurns.has(worker.id) || this.deliveryChecks.has(worker.id) || - [...this.proofPublications.values()].some(publication => publication.workerId === worker.id) || - [...this.preparingTaskTypes.values()].some(pending => pending.workerId === worker.id) || - this.pendingFixedStatementReviews() || this.archive.review && ['pending', 'running'].includes(this.archive.review.status)) return false; - const ready = readyResearchTasks(this.archive.tasks, this.archive.groups) - .filter(node => !this.preparingTaskTypes.has(node) && !this.synchronizationBlocked(node.task) && - (!node.capacityExploration || currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity))); - // A peer may have published real work while this request waited for the archive transaction. - const newlyReady = assignSharedResearchTask(ready, worker, this.allocationPeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers); - if (newlyReady) return !previousReady.includes(newlyReady); - if (timed && !this.timedExplorationDue(worker, budget)) return false; - const focus = originalGoalTaskFocus(this.plannedTasks(), this.archive.groups, this.input.state.environmentDigest); - const targets = [...focus.frontier].map(id => this.node(id)).filter(node => node && - ['lemma', 'goal'].includes(node.task.kind) && !['integrated', 'completed', 'delivered'].includes(node.status) && - !this.synchronizationBlocked(node.task) && routeAllowsTask(node.task, this.archive.tasks, this.archive.groups)); - // Expanded teams spread each method across the frontier; the timed gate stays on the crux first. - const plan = timed ? timedExplorationTargets(targets).flatMap(target => - TIMED_EXPLORATION_FOCUSES.map(method => ({ method, target }))) - : CAPACITY_EXPLORATION_FOCUSES.flatMap(method => targets.map(target => ({ method, target }))); - for (const { method, target } of plan) { - const inputDigest = capacityExplorationInput(target.task, this.archive.tasks, this.explorationIdentity); - if (this.archive.capacityExplorationInputs?.some(input => input.targetTaskId === target.task.id && - input.inputDigest === inputDigest && input.focus === method)) continue; - const node = createCapacityExploration(target, worker, this.archive.tasks, this.explorationIdentity, method); - if (this.archive.tasks.some(existing => existing.task.id === node.task.id) || - !currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity) || - !routeAllowsTask(node.task, [...this.archive.tasks, node], this.archive.groups)) continue; - // Marker and tombstone become durable together. No Lead files or CAS base are rewritten. - (this.archive.capacityExplorationInputs ??= []).push({ inputDigest, focus: method, - targetTaskId: target.task.id, taskId: node.task.id }); - this.archive.tasks.push(node); - this.input.emit('capacity_exploration_requested', { workerId: worker.id, taskId: node.task.id, - targetTaskId: target.task.id, inputDigest, focus: method, evidenceStatus: 'advisory', - ...(timed ? { gate: 'timed-idle' } : {}) }); - this.changed(); return true; - } - return false; - }); - } - private explorationTimer?: { at: number; timer: NodeJS.Timeout }; - /** - * The narrow gate for a team of at most four. This peer has waited at least - * TIMED_EXPLORATION_IDLE_MS with nothing it can start; the Lead was woken for this peer at least twice during the - * same idle episode without a deciding turn; and enough solving time remains. - * The host-owned advisory overlay can run alongside a still-planning Lead without changing its accepted graph. - * Only the wait itself matures with time, so a peer that is otherwise eligible is re-dispatched when it does. - */ - private timedExplorationDue(worker: ResearchWorker, budget: DispatchBudget): boolean { - const scheduling = this.input.state.workers?.find(record => record.id === worker.id)?.scheduling; - const wait = scheduling?.wait; - const episode = scheduling && idlePeerEpisode(this.archive.idlePeerWake, worker.id, scheduling.since); - if (budget.remainingMs < TIMED_EXPLORATION_MIN_REMAINING_MS || - scheduling?.status !== 'idle' || !wait || wait.endedAt !== undefined || !NO_WORK_STAGES.has(wait.stage) || - !episode || episode.count < TIMED_EXPLORATION_UNANSWERED_WAKES) return false; - const dueAt = scheduling.since + TIMED_EXPLORATION_IDLE_MS, now = Date.now(); - if (dueAt <= now) return true; - // One timer serves every waiting peer: the earliest one re-dispatches all, and later peers re-arm it. - if (dueAt - now <= budget.remainingMs - TIMED_EXPLORATION_MIN_REMAINING_MS && !(this.explorationTimer && this.explorationTimer.at <= dueAt)) { - clearTimeout(this.explorationTimer?.timer); - const timer = setTimeout(() => { this.explorationTimer = undefined; if (!this.stopping) this.wake(); }, dueAt - now); - timer.unref(); this.explorationTimer = { at: dueAt, timer }; - } - return false; - } - private pendingProofHandoffs = new Map(); - private preemptionCooldowns = new Map(); - - recordProofHandoff(worker: ResearchWorker, taskId: string, targetTaskId: string) { - this.pendingProofHandoffs.set(worker.id, { taskId, targetTaskId }); - } - - /** Preview the normal dispatch after releasing this assignment and its route slot. */ - proofHandoffTarget(worker: ResearchWorker, action: CooperativeAction): { taskId: string; taskDigest: string; capacity: boolean } | undefined { - if (action.kind !== 'task' || action.assignment.workerId !== worker.id || !advisory(action.task) || - this.finalReviewCommit() || - Date.now() < (this.preemptionCooldowns.get(worker.id) ?? 0) || - !this.current(action) || this.stopping || this.failure || this.input.signal.aborted || - !this.liveWorkers.has(this.lead.id) || !this.liveWorkers.has(worker.id) || this.planApprovalPending() || - this.input.modelDispatchAllowed?.() === false || this.goalProgressBudget && - (this.input.state.turns >= this.goalProgressBudget.maxTurns || Date.now() >= this.goalProgressBudget.deadline)) return; - const outgoing = this.node(action.task.id); - if (outgoing?.status !== 'running' || !['prover', 'researcher', 'engineer'].includes(worker.role)) return; - const groups = this.archive.groups?.map(route => route.group.id === taskGroup(outgoing.task) - ? { ...route, busy: Math.max(0, (route.busy ?? 0) - 1) } : route); - const tasks: TaskRecord[] = this.archive.tasks.map(node => node === outgoing ? { ...node, status: 'pending' } : node); - if (this.peerReview(worker, { outgoing, tasks, groups })) return; - const { ready } = this.peerTaskCandidates(tasks, groups); - const peers = this.allocationPeers, stopped = this.stoppedWorkers; - const selected = this.assignPeerTask(ready, worker, tasks, groups, peers, stopped); - if (!selected || !ready.includes(selected) || selected.task.kind !== 'goal' && - !(selected.task.kind === 'lemma' && selected.task.type?.trim()) || - !taskDependenciesReady(selected.task, tasks) || - !originalGoalTaskFocus(tasks, groups, this.input.state.environmentDigest).preferred.proofPath.has(selected.task.id)) return; - const currentReady = this.peerTaskCandidates(this.archive.tasks, this.archive.groups).ready; - if (currentReady.includes(selected) && peers.some(peer => peer.id !== worker.id && - !this.active.has(peer.id) && !this.reservedTurns.has(peer.id) && !this.deliveryChecks.has(peer.id) && - !this.archive.tasks.some(node => node.status === 'running' && node.assignment?.workerId === peer.id) && - ![...this.preparingTaskTypes.values()].some(item => item.workerId === peer.id) && - ![...this.proofPublications.values()].some(item => item.workerId === peer.id) && !this.peerReview(peer) && - this.assignPeerTask(currentReady, peer, this.archive.tasks, this.archive.groups, peers, stopped) === selected)) return; - return { taskId: selected.task.id, taskDigest: digest(selected.task), capacity: Boolean(outgoing.capacityExploration) }; - } - private leadPauseInputs = new WeakMap(); - private pendingLeadInboxBases = new WeakMap(); - private idlePeerTimer?: NodeJS.Timeout; - /** - * Busy peers never return the Lead's turn, so a peer left without startable work would wait for them. One wake per - * continuous idle episode, independent of when the Lead last became idle or accepted a plan. Each peer keeps - * its own bounded retry schedule until it gets work or waits on a live dependency. Nothing running is the ordinary - * idle-Lead path, not this one. - */ - private wakeForIdlePeers() { - clearTimeout(this.idlePeerTimer); this.idlePeerTimer = undefined; - if (this.stopping || !this.active.size && !this.proofPublications.size || this.active.has(this.lead.id) || !this.archive.tasks.length) return; - const workers = this.input.state.workers ?? [], previous = this.archive.idlePeerWake; - const episodes: NonNullable['episodes']> = {}; - const retries = new Map(); - for (const worker of workers) { - const scheduling = worker.scheduling; - if (worker.id === this.lead.id || scheduling?.status !== 'idle' || !scheduling.wait || - scheduling.wait.endedAt !== undefined || !NO_WORK_STAGES.has(scheduling.wait.stage)) continue; - const episode = idlePeerEpisode(previous, worker.id, scheduling.since); - if (!episode) continue; - episodes[worker.id] = episode; - retries.set(worker.id, { since: episode.since, - notBefore: episode.at + IDLE_PEER_WAKE_MS * 2 ** Math.min(episode.count, LEAD_MAX_BACKOFF) }); - } - const { due, dueAt } = idlePeersAwaitingLead(workers, this.lead.id, Date.now(), retries); - if (due.length) { - const at = Date.now(); - for (const id of due) episodes[id] = { since: workers.find(worker => worker.id === id)!.scheduling!.since, - at, count: (episodes[id]?.count ?? 0) + 1 }; - this.archive.idlePeerWake = { at, workerIds: due, count: Math.max(...due.map(id => episodes[id].count)), episodes }; - this.wakeLead('peers-idle'); - this.input.emit('lead_woken_for_idle_peers', { workerIds: due, idleWakeMs: IDLE_PEER_WAKE_MS }); - this.input.save(); - } else if (dueAt !== undefined) { - this.idlePeerTimer = setTimeout(() => { this.idlePeerTimer = undefined; if (!this.stopping) this.wake(); }, - Math.max(0, dueAt - Date.now())); - this.idlePeerTimer.unref(); - } - } - private leadResponsibilityDigest(): string { - const focus = originalGoalTaskFocus(this.archive.tasks, this.archive.groups, this.input.state.environmentDigest); - return mathDigest(canonicalMathJson({ schema: 'theorem-os.lead-responsibility.v1', ...this.explorationIdentity, - frontier: this.archive.tasks.filter(node => focus.frontier.has(node.task.id)).map(node => - [node.task.id, capacityExplorationInput(node.task, this.archive.tasks, this.explorationIdentity)]) - .sort(([a], [b]) => a.localeCompare(b)) })); - } - protected refreshFeasibilityAssignments() { - let changed = false; - for (const node of this.archive.tasks) { - const assignment = node.assignment; - if (!assignment || !isFeasibilityReview(node.task) || !['pending', 'running'].includes(node.status)) continue; - const worker = this.input.workers.find(worker => worker.id === assignment.workerId); - if (worker && independentFeasibilityWorker(node, worker, this.archive.tasks, this.archive.groups)) continue; - this.moveTask(node, 'pending', 'reassigned'); node.assignment = undefined; - node.feedback = 'math_feasibility_review_independence_lost: Reassign this advisory review to a peer who does not own or produce the inspected inputs.'; - const draft = this.archive.researchDrafts?.[node.task.id]; - if (draft && draft.assignmentId === assignment.assignmentId && draft.workerId === assignment.workerId) draft.suspended = true; - const active = this.active.get(assignment.workerId); - if (active?.action.kind === 'task' && active.action.assignment === assignment && !active.cancelled) { - active.cancelled = true; void active.interrupt().catch(() => {}); - } - if (node.task.ownerId) this.wakeLead('feasibility-review-reassigned'); - this.input.emit('feasibility_review_reassigned', { taskId: node.task.id, workerId: assignment.workerId, - assignmentId: assignment.assignmentId, reason: 'reviewer-no-longer-independent', draftCommit: draft?.commit }); - changed = true; - } - return changed; - } - /** A live publication never authorizes a superseded dispatch or changed decisions. */ - hasLeadPublication(action: CooperativeAction) { - return this.current(action) && this.leadPublication(action) !== undefined; - } - start() { - this.timer = setInterval(() => { void this.humanGuidanceCheckpoint(); void this.inputs().catch(error => { - this.input.emit('cooperation_poll_failed', { reason: error instanceof Error ? error.message : 'unknown' }); - if (error instanceof VerificationCheckpointError || error instanceof Error && error.message === 'math_verifier_unavailable') { this.failure = error; this.changed(); } - }); }, 200); - this.timer.unref(); - this.refreshPlanApproval(); - } - async stop() { - this.stopping = true; - this.refreshGoalProgress(); - if (this.planApprovalPending()) this.input.emit('plan_approval_unanswered', { planVersion: this.archive.planVersion }); - clearTimeout(this.idlePeerTimer); this.idlePeerTimer = undefined; - clearTimeout(this.explorationTimer?.timer); this.explorationTimer = undefined; - for (const worker of this.input.workers) this.clearDispatchWait(worker, 'stopped'); - this.wake(); - clearInterval(this.timer); - await this.guidancePulse; - await this.humanGuidanceCheckpoint(true); - let pending: ReadonlyMap> | undefined; - try { pending = await this.pendingPulse; } catch (error) { if (!this.input.signal.aborted) throw error; } - const drained = new Set>(); - let failure: unknown; - for (;;) { - const work = [...new Set>([...(pending?.values() ?? []), ...(this.pendingPulse ? [this.pendingPulse] : []), - ...this.deliveryChecks.values(), ...[...this.proofPublications.values()].map(publication => publication.pending), - ...this.proofDeliveryChecks, ...this.planSynchronizations, - ...this.leadDeliveries, ...[...this.preparingTaskTypes.values()].map(pending => pending.settled), - ...(this.preparingStatements ? [this.preparingStatements] : []), this.integrationQueue])] - .filter(item => !drained.has(item)); - if (!work.length) break; - work.forEach(item => drained.add(item)); - const checks = await Promise.allSettled(work); - const failed = checks.find(result => result.status === 'rejected'); - if (failed?.status === 'rejected') failure ??= failed.reason; - await Promise.resolve(); - } - if (failure && !this.input.signal.aborted) throw failure; - await Promise.allSettled([...this.notifications]); - this.syncPlanNotes(); - if (!this.input.signal.aborted) this.archive.canonicalCommit = this.seed(this.lead, this.archive.canonicalCommit!); - this.input.save(); - } - async pulse(workerId?: string): Promise { - await this.humanGuidanceCheckpoint(); - if (workerId) await this.deliveryChecks.get(workerId); - const pending = await this.inputs(); - const checks = await Promise.allSettled(workerId ? [pending.get(workerId)] : [...pending.values()]); - const failed = checks.find(result => result.status === 'rejected'); - if (failed?.status === 'rejected') throw failed.reason; - } - async restore() { - if (this.refreshFeasibilityAssignments()) this.changed(); - for (const node of this.archive.tasks) if (['pending', 'running'].includes(node.status)) this.restoreTaskSourceRepair(node); - for (const failed of this.archive.failedTaskInputs ?? []) { - let repair = failed.repair; - const node = this.node(repair?.taskId ?? failed.taskId); - if (!repair && node && this.firstTaskRepair(node, failed.id) && ['pending', 'running'].includes(node.status) && - failed.taskDigest === digest(node.task) && node.assignment?.taskDigest === failed.taskDigest) { - repair = failed.repair = { taskId: node.task.id, taskDigest: failed.taskDigest, - workerId: node.assignment.workerId, pending: true }; - this.input.emit('task_repair_requested', { taskId: node.task.id, workerId: repair.workerId, - taskDigest: repair.taskDigest, reason: 'failed-check-restored' }); - } - if (!repair || repair.pending || !node || !['pending', 'running'].includes(node.status) || - repair.taskDigest !== digest(node.task) || repair.workerId !== node.assignment?.workerId || repair.startedAttempt !== node.attempts) continue; - repair.pending = true; delete repair.startedAttempt; - this.input.emit('task_repair_interrupted', { taskId: node.task.id, workerId: repair.workerId, failureId: failed.id, reason: 'process-restored' }); - } - this.syncPlanNotes(); - for (const review of this.archive.statementReviews ?? []) if (review.status !== 'superseded') { - try { assertStatementSnapshot(review); } - catch { this.supersedeStatementReview(review); continue; } - resetStatementReview(review); - } - // A resumed review must inspect the fixed version again. - if (this.archive.review) { this.archive.review.status = 'pending'; this.archive.review.workerId = undefined; } - const publication = this.archive.planPublication ?? this.archive.initialPlanPublication; - // A finalized dispatch can still leave inherited notes behind the accepted graph. - if (!publication && - fs.existsSync(path.join(this.lead.worktree, 'RESEARCH.md'))) { - try { - const rejection = this.archive.planRejection; - if (!rejection?.stalled || rejection.proposalDigest !== this.proposedPlanDigest() || - rejection.inputDigest !== this.planningInputDigest('rejection')) { - const plan = this.readLeadPlan(); - const initial = !this.archive.tasks.length; - // Host-synced notes describe the accepted graph, not a new answer to findings that - // arrived since it was accepted. Changed drafts and explicit decisions still validate. - const inherited = !initial && !plan.fromPatch && !plan.retireRoutes?.length && plan.researchDecisions === undefined && - !plan.goalProgressDecision && !plan.goalPathDecisions && !plan.nextCheckDecisions && - canonicalMathJson({ tasks: plan.tasks, groups: plan.groups, proofRoutes: plan.proofRoutes ?? [] }) === - canonicalMathJson({ tasks: this.plannedTasks().map(node => node.task), - groups: this.archive.groups?.map(route => route.group) ?? [], proofRoutes: this.archive.proofRoutes ?? [] }); - if (!inherited) await this.acceptPlan(plan); - if (initial) dropLeadWakes(this.archive.leadWakes!); - } - } catch (error) { this.rejectPlan(error, 'restore'); } - } - if (!solverSourceFeedback(this.input.state.problem, this.lead.worktree)) { - await this.restoreLeadSources(); - const integrated = this.archive.tasks.filter(node => node.status === 'integrated'); - this.markPendingValidation(integrated, new Set(integrated.map(node => node.task.id))); - if (integrated.length || this.archive.edits?.some(edit => edit.pendingSync)) await this.schedulePlanSynchronization(); - await this.input.exclusiveCheck(() => this.recheckConditional()); - } else { - for (const node of this.archive.tasks.filter(node => node.status === 'integrated')) { - this.moveTask(node, 'blocked', 'invalidated'); node.feedback = 'math_canonical_source_invalid'; - } - this.wakeLead('canonical-source-invalid'); - } - for (const node of this.archive.tasks) if (node.status === 'running') { - this.restoreConnectionHandoff(node); - this.moveTask(node, 'pending', 'interrupted'); - } - for (const node of this.archive.tasks.filter(node => node.status === 'delivered')) await this.integrate(node); - await this.integrateReady(); - const statements = this.prepareStatementContexts(); if (statements) await statements; - this.syncStatementReviews(); - if (publication) { - // Preserve the draft in restoreLeadSources, then seed future decisions from the accepted graph. - this.archive.planEdited = true; this.syncPlanNotes(); - } - this.changed(); - const residue = restoreResidue(this.archive); - if (residue.length) this.input.emit('restore_residue', { violations: residue }); - } - private dispatchBudgetExhausted(budget: DispatchBudget, modelAllowed: boolean) { - return this.input.state.turns >= budget.maxTurns || budget.remainingMs <= 0 || !modelAllowed; - } - private async exhaustedDispatch(budget: DispatchBudget, modelAllowed: boolean, running = false): Promise { - const refund = modelAllowed && budget.remainingMs > 0 && this.waitForTurn(budget.maxTurns); - if (refund) { await refund; return RETRY_DISPATCH; } - if (running) return this.waitForDispatch(); - } - protected canAssemble(commit: string) { - if (commit !== this.archive.canonicalCommit || this.candidateSynchronizationBlocked()) return false; - const goals = this.archive.tasks.filter(node => node.task.kind === 'goal'); - return this.reviewed() || goals.length > 0 && goals.every(node => node.status === 'integrated'); - } - async next(worker: ResearchWorker, budget: DispatchBudget): Promise { - this.goalProgressBudget = { maxTurns: budget.maxTurns, deadline: Date.now() + budget.remainingMs }; - if (this.refreshGoalProgress()) this.changed(); - for (;;) { - if (this.stopping) return; - this.input.signal.throwIfAborted(); - if (this.failure) throw this.failure; - if (this.refreshCapacityExplorations()) this.changed(); - if (this.refreshFeasibilityAssignments()) this.changed(); - this.refreshResearchCheckpoints(); - if (this.refreshFailedTaskInputs()) this.changed(); - if (this.refreshInvalidTaskTypes()) this.changed(); - if (this.refreshGoalPathStall()) this.changed(); - if (!this.liveWorkers.has(this.lead.id)) { - this.recordDispatchWait(worker, { stage: 'lead-unavailable', candidates: [], candidateCount: 0, omittedCandidates: 0 }); - return; - } - if (!this.liveWorkers.has(worker.id)) return; - const modelAllowed = this.input.modelDispatchAllowed?.() !== false; - const result = await (worker.id === this.lead.id - ? this.nextLead(worker, budget, modelAllowed) : this.nextPeer(worker, budget, modelAllowed)); - if (result === RETRY_DISPATCH) continue; - const handoff = this.pendingProofHandoffs.get(worker.id); - this.pendingProofHandoffs.delete(worker.id); - // Dispatch may retry while work is being prepared. Only a real assignment can repeat the preemption loop. - if (handoff && result && (result.kind !== 'task' || advisory(result.task))) { - const cooldownUntil = Date.now() + PREEMPTION_MISMATCH_COOLDOWN_MS; - this.preemptionCooldowns.set(worker.id, cooldownUntil); - this.input.emit('cooperative_preemption_mismatch', { workerId: worker.id, ...handoff, - assignedKind: result.kind === 'task' ? result.task.kind : result.kind, - assignedTaskId: result.kind === 'task' ? result.task.id : undefined, cooldownUntil }); - } - return result; - } - } - private async nextLead(worker: ResearchWorker, budget: DispatchBudget, modelAllowed: boolean): Promise { - if (this.synchronizationPending()) { - this.recordDispatchWait(worker, { stage: 'synchronizing', candidates: [], candidateCount: 0, omittedCandidates: 0 }); - return this.waitForDispatch(); - } - if (this.planApprovalPending()) { - // Nothing runs until a person approves; only their own note to the Lead earns a revision turn. - if (this.dispatchBudgetExhausted(budget, modelAllowed)) return this.exhaustedDispatch(budget, modelAllowed, this.active.size > 0 || this.proofPublications.size > 0); - const guidance = this.pendingLeadGuidance(); - if (!guidance.length) return this.waitForDispatch(); - const record = this.archive.planApproval ??= {}; - record.guidanceIds = [...new Set([...record.guidanceIds ?? [], ...guidance])].slice(-512); record.revisionAt = Date.now(); - this.input.emit('plan_approval_revision', { guidanceIds: guidance, planVersion: this.archive.planVersion }); - return this.leadDecision(worker, this.archive.canonicalCommit!, this.planningInputDigest()); - } - if (this.pendingFixedStatementReviews()) { - if (!this.livePeers.length || budget.remainingMs <= 0 || - this.input.state.turns >= budget.maxTurns && !this.reservedTurns.size || !modelAllowed && !this.active.size) return; - return this.waitForDispatch(); - } - const head = this.archive.canonicalCommit!; - if (this.canAssemble(head) && this.lastAssembly !== head) { - // Candidate selection stops the workers. Let integration publish its receipts first. - if (this.integrationQueueDepth) return this.waitForDispatch(); - this.syncPlanNotes(); - const seed = this.seed(worker, head); this.archive.canonicalCommit = seed; - this.cancelStaleTaskTypes(); - this.lastAssembly = seed; return { kind: 'assemble', seedCommit: seed }; - } - const running = this.preparingTaskTypes.size > 0 || this.active.size > 0 || this.proofPublications.size > 0 || this.archive.tasks.some(node => ['running', 'delivered'].includes(node.status) || - (node.status === 'conditional' && taskDependenciesReady(node.task, this.archive.tasks))) || this.archive.review?.status === 'running' || - this.archive.statementReviews?.some(review => ['translating', 'reviewing'].includes(review.status) || - (modelAllowed && this.input.state.turns < budget.maxTurns && budget.remainingMs > 0 && - ['pending', 'translated'].includes(review.status) && this.livePeers.length > 0 && - this.statementReviewAllowed(this.node(review.taskId).task, true))); - if (this.dispatchBudgetExhausted(budget, modelAllowed)) return this.exhaustedDispatch(budget, modelAllowed, running); - if (!running && !this.livePeers.length) return; - if (this.archive.review && ['pending', 'running'].includes(this.archive.review.status) && - (!this.fixedReviewScope || this.finalReviewCommit())) return this.waitForDispatch(); - if (this.pendingLeadGuidance().length) return this.leadDecision(worker, head, this.planningInputDigest()); - this.wakeForIdlePeers(); - const wakes = this.archive.leadWakes!, through = wakes.requested; - const pendingProgress = this.archive.goalProgress?.pending; - const owedProgress = pendingProgress && (pendingProgress.retryAt ?? 0) <= Date.now(); - // Conditions recomputed from durable state; only one-shot events are saved wake-ups. - const required = this.leadDecisionObligations(); - const owedFeedback = required.feedback || required.research || required.nextCheck; - let wake = leadWakePending(wakes) || owedFeedback; - // Idle peers are not in the planning digests, so their unconsumed wake must not be deduplicated away. - const owedIdle = (wakes.recent ?? []).some(item => item.reason === 'peers-idle' && item.seq > wakes.consumed && item.seq <= through); - const rejection = this.archive.planRejection; - if (rejection?.stalled && !owedProgress) { - if (rejection.inputDigest === this.planningInputDigest('rejection') && rejection.proposalDigest === this.proposedPlanDigest()) { - dropLeadWakes(wakes, through); - if (!running && !this.canAdvance()) { - if (this.input.continuousResearch) return this.idleFrontier(this.activeGoalFrontier(), rejection.inputDigest); - this.input.emit('plan_stalled', { ...rejection }); return; - } - return this.waitForDispatch(); - } - wake = true; - } - if (this.archive.lastLeadPauseInputDigest && - this.archive.lastLeadPauseInputDigest !== this.leadPauseInputDigest()) wake = true; - // An original goal whose whole frontier cannot run is owed one Lead turn, even when that Lead's own decision - // (a pause, say) produced it and other workers are busy elsewhere. It wakes after the existing reconsideration - // paths so their events still name the frontier they reopen, and after work already running on the stalled - // goal's own route settles, since that result is part of what the turn must answer. - const goalPathStall = this.unansweredGoalPathStall(); - const owedStall = goalPathStall && !this.goalPathStallWorkRunning() ? goalPathStall : undefined; - if (!wake && this.archive.tasks.length) { - const support = originalGoalTaskFocus(this.archive.tasks, this.archive.groups).support; - const supportingWork = this.archive.tasks.some(node => support.has(node.task.id) && - (this.preparingTaskTypes.has(node) || ['running', 'delivered'].includes(node.status) || - node.status === 'conditional' && taskDependenciesReady(node.task, this.archive.tasks))) || - this.archive.statementReviews?.some(review => support.has(review.taskId) && - ['pending', 'translating', 'translated', 'reviewing'].includes(review.status)); - // Independent work must not defer reconsidering a stalled original argument; it is an ordinary plan turn. - if (!supportingWork && !this.hasAssignableTask(support) && !this.canAdvance(support)) { - const frontier = this.activeGoalFrontier(), inputDigest = this.planningInputDigest(); - if (frontier.some(item => item.status === 'blocked' && item.attempts > 0) && inputDigest !== this.archive.lastLeadInputDigest) { - wake = true; - this.input.emit('blocked_tasks_reconsidered', { taskIds: frontier.map(item => item.taskId), - goalIds: [...new Set(frontier.flatMap(item => item.goalIds))], inputDigest }); - } - } - } - if (!running && !wake && this.archive.tasks.length && (!this.archive.review || this.archive.review.status === 'changes_requested') && - !this.canAdvance()) { - // Parking prevents repeating an inference, not reconsidering its unfinished original goal. - const frontier = this.activeGoalFrontier(); - const inputDigest = this.planningInputDigest(); - if (!frontier.length || inputDigest === this.archive.lastLeadInputDigest) { - if (!owedStall && !owedProgress) return this.idleFrontier(frontier, inputDigest); - // A mechanical resume of unattempted inputs comes before asking the Lead about the stall. - if (!this.preparingTaskTypes.size && this.resumeUnattemptedFrontier(frontier)) return RETRY_DISPATCH; - } else { - wake = true; - this.input.emit('blocked_tasks_reconsidered', { taskIds: frontier.map(item => item.taskId), - goalIds: [...new Set(frontier.flatMap(item => item.goalIds))], inputDigest }); - } - } - if (owedStall || owedProgress) wake = true; - if (wake || (!running && (!this.livePeers.length || !this.hasAssignableTask()))) { - const inputDigest = this.planningInputDigest(); - // The previous decision (or pause) already answers these inputs; drop the wake-ups without a turn. - if (inputDigest === this.archive.lastLeadInputDigest && !owedFeedback && !owedStall && !owedIdle && !owedProgress) { - dropLeadWakes(wakes, through); - // An older pause can still differ after this input was answered. Retrying immediately - // would observe that same pause forever and starve peer completions and stop signals. - return !running && !this.hasAssignableTask() - ? this.idleFrontier(this.activeGoalFrontier(), inputDigest) : this.waitForDispatch(); - } - if (this.archive.tasks.length && this.archive.lastLeadPauseInputDigest === this.leadPauseInputDigest() && - !owedFeedback && !owedStall && !owedIdle && !owedProgress) { - dropLeadWakes(wakes, through); - return !running && !this.hasAssignableTask() - ? this.idleFrontier(this.activeGoalFrontier(), inputDigest) : this.waitForDispatch(); - } - consumeLeadWakes(wakes, through); - const action = this.leadDecision(worker, head, inputDigest); - if (goalPathStall) this.input.emit('goal_path_stall_dispatched', { digest: goalPathStall }); - return action; - } - return this.waitForDispatch(); - } - /** Unanswered current inputs survive a notes-only pause; a live publication can already have answered them. */ - protected leadDecisionObligations(action?: Extract) { - const shown = action ? this.presentedResearchInputs.get(action)?.shown ?? [] : undefined; - const merging = action ? this.pendingSourceResearchDecisions.get(action) ?? [] : []; - const researchInputs = leadResearchInputs(this.archive.deliveries ?? [], - new Map(this.archive.tasks.map(node => [node.task.id, node])), this.archive.researchDecisions).filter(record => - (!shown || shown.some(item => item.id === record.id && item.taskDigest === record.taskDigest && - item.findingDigest === record.findingDigest)) && !merging.some(item => item.deliveryId === record.id && - item.taskDigest === record.taskDigest && item.findingDigest === record.findingDigest)); - const pending = this.archive.goalProgress?.pending; - const progressReview = pending?.id && (!action || this.presentedGoalProgress.get(action) === pending.id) ? pending : undefined; - const outcomes = action ? this.presentedNextCheckOutcomes.get(action) ?? [] : undefined; - const nextCheckOutcomes = (this.archive.nextChecks ?? []).filter(record => record.status === 'awaiting-decision' && - currentNextCheck(record, this.archive, this.explorationIdentity) && (!outcomes || outcomes.some(item => - item.checkId === record.id && item.outcomeDeliveryId === record.outcome?.deliveryId))); - const feedback = Boolean(this.archive.error || this.archive.planPublicationRejection && - this.archive.planPublicationRejection.baseVersion === this.archive.planVersion); - const research = researchInputs.length > 0, progress = Boolean(progressReview), nextCheck = nextCheckOutcomes.length > 0; - return { research, progress, nextCheck, feedback, any: research || progress || nextCheck || feedback, - researchInputs, progressReview, nextCheckOutcomes }; - } - /** A read or incomplete draft cannot satisfy this dispatch's still-owed decisions. */ - leadCheckpointHandoff(action: Extract) { - if (!this.current(action) || this.leadPublication(action) || - this.archive.tasks.length && !this.leadDecisionObligations(action).any) return; - const draft = this.inspectLeadCheckpointDraft(action); - if (draft && !draft.reason) return; - return { reason: draft?.reason }; - } - /** Re-read this dispatch's still-owed decisions when its checkpoint reminder is delivered. */ - leadCheckpointInstruction(action: Extract): string { - const obligations = this.leadDecisionObligations(action); - if (!obligations.any) return 'If the new deliveries, failures or idle peers call for a change, ' + - 'save or publish the math-plan revision as your instructions describe and return. If the accepted graph already ' + - 'gives each live peer its useful work, return without a revision. '; - const required: string[] = []; - if (obligations.research) required.push('Answer each still-unanswered presented delivery in researchDecisions: ' + - JSON.stringify(obligations.researchInputs.map(record => record.id)) + '.'); - if (obligations.progressReview) required.push('Include progressReview with id ' + JSON.stringify(obligations.progressReview.id) + - ', a reason and nextChecks covering every reviewed goal: ' + JSON.stringify(obligations.progressReview.goalIds) + '.'); - if (obligations.nextCheck) required.push('Include nextCheckDecisions for each still-unanswered presented outcome: ' + - JSON.stringify(obligations.nextCheckOutcomes.map(record => ({ checkId: record.id, - outcomeDeliveryId: record.outcome?.deliveryId }))) + '.'); - if (obligations.feedback) required.push('Repair the current host plan validation feedback; an unchanged saved draft does not answer it. ' + - LEAD_PLAN_REPAIR_INSTRUCTION); - const target = this.openLeadPublicationTarget(action); - const revision = Boolean(this.archive.tasks.length && action.planVersion); - const response = { - ...(revision ? { baseVersion: action.planVersion, upsert: [] } - : { tasks: [''] }), - ...(obligations.research ? { researchDecisions: obligations.researchInputs.map(record => ({ - deliveryId: record.id, outcome: '', reason: '', - })) } : {}), - ...(obligations.progressReview ? { progressReview: { id: obligations.progressReview.id, - reason: '', nextChecks: [{ - action: '', - objective: '', expectedEvidence: '', - targetTaskId: '', - }] } } : {}), - ...(obligations.nextCheck ? { nextCheckDecisions: obligations.nextCheckOutcomes.map(record => ({ - checkId: record.id, outcomeDeliveryId: record.outcome?.deliveryId, - action: '', reason: '', - })) } : {}), - }; - const destination = target - ? 'Save the decision as .scratch/plan.json and run plan-apply --publish from the Lead tool help. ' - : 'Use plan-apply to save the current decision in RESEARCH.md before returning. '; - const schema = revision - ? 'Use upsert:[] when the task graph stays unchanged, and include the required decisions in the same object. ' - : 'Include a complete tasks array and the required decisions in the same object. '; - return destination + required.join(' ') + ' ' + schema + 'Current response template (replace every angle-bracket placeholder with your own decision; ' + - 'the template itself is not a valid submission):\n' + JSON.stringify(response) + '\n' + - (obligations.research ? 'For research adoption add taskIds naming newly added or substantively changed tasks; ' + - 'for source add sourcePaths naming changed owned Lean files. ' : '') + - (obligations.progress ? 'Choose enough progress nextChecks to cover every reviewed goal. ' : '') + - (obligations.nextCheckOutcomes.some(record => record.outcome?.conclusion === 'refuted') - ? 'Continuing after a refutation requires counterEvidenceDeliveryId from a supporting host check of the same target and consumer with retained evidence. Otherwise revise the argument, dependencies or route, assign a new independent feasibility check, or stop. ' - : '') + - 'Keep still-unanswered ids and pending decisions in RESEARCH.md when saving an unfinished draft; ' + - 'notes alone do not answer these requirements. '; - } - private leadDecision(worker: ResearchWorker, head: string, inputDigest: string): CooperativeAction { - this.syncPlanNotes(); - const planVersion = this.archive.planVersion ??= this.planVersion(); - const action: CooperativeAction = { kind: 'lead', seedCommit: this.seed(worker, head), planVersion, - planningInputDigest: inputDigest, responsibilityDigest: this.leadResponsibilityDigest(), - ...(!this.archive.tasks.length && !this.archive.initialPlanPublication ? { initialPlanNonce: crypto.randomUUID() } : {}), - ...(this.archive.tasks.length ? { planNonce: crypto.randomUUID() } : {}) }; - this.leadEvidence.set(action, this.planningEvidenceDigest()); - const research = leadResearchInputs(this.archive.deliveries ?? [], - new Map(this.archive.tasks.map(node => [node.task.id, node])), this.archive.researchDecisions); - this.presentedResearchInputs.set(action, { shown: research.slice(-8), total: research.length }); - this.leadPauseInputs.set(action, this.leadPauseInputDigest(action.seedCommit)); - const presented = this.presentedGoalPathStall(); - if (presented) this.presentedGoalPathStalls.set(action, presented); - this.presentGoalProgressReview(action); - return action; - } - /** A delivered note still needs its scoped decision after an interrupted revision or a restart. */ - private pendingLeadGuidance(): string[] { - let records: ReturnType; - try { records = readHumanGuidance(path.join(path.dirname(this.lead.worktree), 'state.json'), this.input.state.runId); } - catch { return []; } - return records.filter(record => record.recipient.kind === 'lead' && (!record.recipient.id || record.recipient.id === this.lead.id) && - !record.taskRef && !record.decision && (['queued', 'deferred'].includes(record.status) || - record.status === 'delivered' && record.deliveredTo?.includes(this.lead.id) && - record.deliveredScope?.planVersion === this.archive.planVersion)).map(record => record.id); - } - /** Work on a stalled goal's own route that settles without the Lead: a run, delivery, ready recheck, type or statement check. */ - private goalPathStallWorkRunning() { - const route = this.goalPathStallTasks; - return this.archive.tasks.some(node => route.has(node.task.id) && - (this.preparingTaskTypes.has(node) || ['running', 'delivered'].includes(node.status) || - node.status === 'conditional' && taskDependenciesReady(node.task, this.archive.tasks))) || - Boolean(this.archive.statementReviews?.some(review => route.has(review.taskId) && ['translating', 'reviewing'].includes(review.status))); - } - private taskDispatchBlock(node: TaskRecord): 'preparing-type' | 'synchronizing' | 'capacity-expired' | 'awaiting-lead' | undefined { - if (this.preparingTaskTypes.has(node)) return 'preparing-type'; - if (this.transferringResearch.has(node) || this.synchronizationBlocked(node.task)) return 'synchronizing'; - if (node.capacityExploration && !currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity)) - return 'capacity-expired'; - const checkpoint = node.connectionCheckpoint; - if (!checkpoint || !this.liveWorkers.has(this.lead.id) || this.workerCoolingDown(this.lead.id)) return; - if (checkpoint.leadDeliveryId) { - const delivery = this.archive.deliveries?.find(record => record.id === checkpoint.leadDeliveryId); - if (!delivery || !leadResearchInputs([delivery], new Map(this.archive.tasks.map(task => [task.task.id, task])), - this.archive.researchDecisions).length) return; - // Match the planner's existing fallback when it cannot repair a rejected plan. - const rejection = this.archive.planRejection; - if (rejection?.stalled && rejection.inputDigest === this.planningInputDigest('rejection') && - rejection.proposalDigest === this.proposedPlanDigest()) return; - return 'awaiting-lead'; - } - // Older checkpoints recorded only the Lead turn's wake sequence. - if (checkpoint.leadWake !== undefined && this.archive.leadWakes!.settled < checkpoint.leadWake) return 'awaiting-lead'; - } - private transferringResearch = new Set(); - private transferableResearch(node: TaskRecord, worker: ResearchWorker): boolean { - const assignment = node.assignment; - if (this.stopping || this.failure || this.input.signal.aborted || this.planApprovalPending() || - this.input.modelDispatchAllowed?.() === false || !this.liveWorkers.has(this.lead.id) || - !this.allocationPeers.some(peer => peer.id === worker.id) || this.active.has(worker.id) || - this.archive.tasks.some(peer => peer.status === 'running' && peer.assignment?.workerId === worker.id) || - [...this.proofPublications.values()].some(publication => publication.workerId === worker.id) || - !this.archive.tasks.includes(node) || node.status !== 'pending' || !advisory(node.task) || - node.task.ownerId || isFeasibilityReview(node.task) || node.capacityExploration || node.nextCheckId || - node.alternativeRoutes?.length || !assignment || assignment.workerId === worker.id || - !this.liveWorkers.has(assignment.workerId) || assignment.taskId !== node.task.id || assignment.taskDigest !== digest(node.task) || - this.preparingTaskTypes.has(node) || this.synchronizationBlocked(node.task) || - !taskCanStart(node.task, this.archive.tasks, this.archive.groups) || - !routeAllowsTask(node.task, this.archive.tasks, this.archive.groups) || - assessTaskResponsibility({ ...node, assignment: undefined }, worker, this.responsibility).kind !== 'matches') return false; - // A pending status alone does not establish that the old writer stopped: - // delivery settlement can still own an active action or publication. - if ([...this.active.values()].some(active => active.action.kind === 'task' && active.action.assignment === assignment) || - [...this.proofPublications.values()].some(publication => publication.action.assignment === assignment)) return false; - return this.archive.tasks.some(peer => peer !== node && peer.status === 'running' && - peer.assignment?.workerId === assignment.workerId && peer.assignment.taskDigest === digest(peer.task)); - } - private recordTaskWait(worker: ResearchWorker, ranked: readonly TaskRecord[], ready: readonly TaskRecord[]) { - const owned = this.archive.tasks.filter(node => !['integrated', 'completed'].includes(node.status) && - researchWorkerCanNode(worker, node) && (!node.task.ownerId || node.task.ownerId === worker.id)); - if (!ranked.length && owned.length && owned.every(node => (node.task.status ?? 'active') !== 'active' || - this.archive.groups?.some(route => route.group.id === taskGroup(node.task) && route.group.status !== 'active'))) { - this.recordDispatchWait(worker, { stage: 'route-paused', candidateCount: 0, omittedCandidates: 0, candidates: [] }); - return; - } - const dependencies = this.archive.tasks.filter(node => - ['pending', 'blocked'].includes(node.status) && assessTaskResponsibility(node, worker, this.responsibility).kind === 'matches' && - routeAllowsTask(node.task, this.archive.tasks, this.archive.groups) && !this.synchronizationBlocked(node.task) && - !taskCanStart(node.task, this.archive.tasks, this.archive.groups)); - if (dependencies.length) { - const active = new Set([...this.active.values()].flatMap(work => work.action.kind === 'task' && - !work.cancelled && this.current(work.action) ? [work.action.task.id] : [])); - for (const node of this.preparingTaskTypes.keys()) active.add(node.task.id); - for (const publication of this.proofPublications.values()) - if (this.current(publication.action)) active.add(publication.action.task.id); - const running = dependencies.map(node => runningTaskDependencies(node, this.archive.tasks, active)); - const live = running.every(ids => ids && ids.length) ? [...new Set(running.flatMap(ids => ids!))] - .map(id => this.node(id)) : undefined; - const candidates = live ?? dependencies; - this.recordDispatchWait(worker, { stage: live ? 'dependency-running' : 'dependency-blocked', candidateCount: candidates.length, - omittedCandidates: Math.max(0, candidates.length - 16), candidates: candidates.slice(0, 16).map(node => ({ - taskId: node.task.id, taskDigest: digest(node.task), reason: 'dependency' })) }); - return; - } - const candidates: DispatchWaitObservation['candidates'] = ranked.slice(0, 16).map(node => { - const hostBlock = this.taskDispatchBlock(node); - const assessment = assessTaskResponsibility(node, worker, this.responsibility); - return { taskId: node.task.id, taskDigest: digest(node.task), - reason: hostBlock ?? (assessment.kind === 'blocked' ? assessment.reason : 'policy-no-selection') }; - }); - this.recordDispatchWait(worker, { stage: !ranked.length ? 'm3-no-ready' : !ready.length ? 'host-filtered' : 'm5-no-selection', - candidateCount: ranked.length, omittedCandidates: ranked.length - candidates.length, candidates }); - } - private peerTaskCandidates(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]) { - const finalReview = this.finalReviewCommit(); - const ranked = this.input.modules.M3.ready(tasks, groups).filter(node => !isFinalCandidateReview(node.task)); - const ready = ranked.filter(node => (!finalReview || !ordinaryAdvisoryTask(node.task)) && - this.nextCheckDispatchable(node) && !this.taskDispatchBlock(node)); - return { ranked, ready }; - } - private finalReviewCommit(): string | undefined { - const review = this.archive.review; - // The persisted record can outlive a changed candidate. The fixed scope binds it to the current source. - return review && review.status !== 'changes_requested' && this.fixedStatementReviewTasks() ? review.commit : undefined; - } - protected override wake() { - super.wake(); - const commit = this.finalReviewCommit(); - if (!commit || this.stopping || this.failure || this.input.signal.aborted) return; - for (const active of this.active.values()) { - const action = active.action; - if (active.requestAdvisoryCheckpoint && !active.cancelled && action.kind === 'task' && - ordinaryAdvisoryTask(action.task) && this.current(action)) active.requestAdvisoryCheckpoint(commit); - } - } - private assignPeerTask(ready: readonly TaskRecord[], worker: ResearchWorker, tasks: readonly TaskRecord[], - groups?: readonly RouteRecord[], peers = this.allocationPeers, stopped = this.stoppedWorkers) { - return this.input.modules.M5.assign(ready, worker, peers, groups, tasks, stopped); - } - private peerReview(worker: ResearchWorker, - release?: { outgoing: TaskRecord; tasks: readonly TaskRecord[]; groups?: readonly RouteRecord[] }) { - const statement = this.archive.statementReviews?.find(item => - ['pending', 'translated'].includes(item.status) && - this.statementReviewAllowed(this.node(item.taskId).task, true, release?.tasks, release?.groups) && - ![...this.active.values()].some(active => isStatementAction(active.action) && active.action.reviewId === item.id)); - if (statement && this.reviewer(release?.outgoing)?.id === worker.id) return { statement }; - const review = this.archive.review; - if (review?.status === 'pending' && (!this.fixedReviewScope || this.fixedStatementReviewTasks()) && - !this.candidateSynchronizationBlocked() && - this.reviewer(release?.outgoing, review.producerIds)?.id === worker.id) return { review }; - } - private async nextPeer(worker: ResearchWorker, budget: DispatchBudget, modelAllowed: boolean): Promise { - if (budget.remainingMs <= 0 || !modelAllowed || this.input.state.turns >= budget.maxTurns) { - this.recordDispatchWait(worker, { stage: 'budget-gated', - gate: budget.remainingMs <= 0 ? 'time-limit' : !modelAllowed ? 'model-disabled' : 'turn-limit', - candidates: [], candidateCount: 0, omittedCandidates: 0 }); - return budget.remainingMs <= 0 || !modelAllowed ? undefined : this.exhaustedDispatch(budget, modelAllowed); - } - if (this.planApprovalPending()) { - this.recordDispatchWait(worker, { stage: 'plan-approval', candidates: [], candidateCount: 0, omittedCandidates: 0 }); - return this.waitForDispatch(); - } - const { statement, review } = this.peerReview(worker) ?? {}; - if (statement) { - this.clearDispatchWait(worker, 'selected'); - const kind = statement.status === 'pending' ? 'backtranslate' : 'statement-review'; - fs.rmSync(path.join(statement.workspace, 'RESEARCH.md'), { force: true }); - statement.status = kind === 'backtranslate' ? 'translating' : 'reviewing'; statement.workerId = worker.id; - statement.assignmentId = crypto.randomUUID(); - this.input.emit('statement_review_assigned', { workerId: worker.id, taskId: statement.taskId, reviewId: statement.id, kind, role: 'reviewer' }); - this.changed(); return { kind, reviewId: statement.id, taskId: statement.taskId, taskDigest: statement.taskDigest, - snapshotDigest: statement.snapshotDigest, seedCommit: statement.commit, workspace: statement.workspace, - assignmentId: statement.assignmentId }; - } - if (review) { - this.clearDispatchWait(worker, 'selected'); - this.seed(worker, review.commit); - const notes = path.join(worker.worktree, 'RESEARCH.md'); - if (fs.existsSync(notes)) fs.writeFileSync(notes, fs.readFileSync(notes, 'utf8').replace(/```(?:math|math-review)\s*\n[\s\S]*?\n```/gu, '')); - review.workerId = worker.id; review.status = 'running'; review.assignmentId = crypto.randomUUID(); - review.independent = !review.producerIds?.includes(worker.id); - this.input.emit('review_assigned', { workerId: worker.id, commit: review.commit, role: 'reviewer', independent: review.independent }); - this.changed(); return { kind: 'review', seedCommit: review.commit, sourceDigest: review.sourceDigest, - assignmentId: review.assignmentId, ...(review.independent ? {} : { independent: false }) }; - } - this.refreshConnectionCheckpoints(); - const { ranked, ready } = this.peerTaskCandidates(this.archive.tasks, this.archive.groups); - const node = this.assignPeerTask(ready, worker, this.archive.tasks, this.archive.groups); - if (!node) { - const movable = ready.find(candidate => this.transferableResearch(candidate, worker)); - // Respect custom M5 decisions as well: only offer a transfer the configured - // allocator would select after this one saved-worker pin is replaced. - const proposal = movable && { ...movable, assignment: undefined }; - if (movable && proposal && this.input.modules.M5.assign([proposal], worker, this.allocationPeers, - this.archive.groups, this.archive.tasks.map(candidate => candidate === movable ? proposal : candidate), this.stoppedWorkers) === proposal) { - const observedRevision = this.dispatchRevision; - this.transferringResearch.add(movable); - try { - if (await this.transferResearchDraft(worker, movable, () => this.transferableResearch(movable, worker))) return RETRY_DISPATCH; - if (observedRevision !== this.dispatchRevision) return RETRY_DISPATCH; - } finally { - this.transferringResearch.delete(movable); - this.wake(); - } - } - if (this.finalReviewCommit()) { - this.recordDispatchWait(worker, { stage: 'final-review', candidateCount: 0, omittedCandidates: 0, candidates: [] }); - return this.waitForDispatch(); - } - this.recordTaskWait(worker, ranked, ready); - const observedRevision = this.dispatchRevision; - if (await this.requestCapacityExploration(worker, budget, ready)) return RETRY_DISPATCH; - return this.liveWorkers.has(worker.id) ? this.waitForDispatch(observedRevision) : undefined; - } - if (!ready.includes(node) || !this.archive.tasks.includes(node) || node.status !== 'pending' || - !taskCanStart(node.task, this.archive.tasks, this.archive.groups) || - !routeAllowsTask(node.task, this.archive.tasks, this.archive.groups) || - assessTaskResponsibility(node, worker, this.responsibility).kind !== 'matches') throw new Error('math_task_assignment_invalid'); - this.clearDispatchWait(worker, 'selected'); - const selectedRoute = selectedTaskRoute(node, this.archive.tasks); - // A stopped worker's pin is ignored for selection but survives until a peer actually takes its task. - const stoppedAssignment = node.assignment?.workerId !== worker.id ? node.assignment : undefined; - if (!stoppedAssignment && node.assignment && node.alternativeRoutes?.length && node.assignment.routeId !== selectedRoute?.id) - node.assignment = undefined; - const resumedAssignment = node.assignment; - let resuming = resumedAssignment?.workerId === worker.id; - const connectionIdentity = { environmentDigest: this.input.state.environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest }; - const readSource = (worktree: string, commit: string) => (dependency: CooperativeTask) => - committedSource(worktree, commit, `${this.input.state.problem.projectRelative}/${dependency.proofPath}`); - const refreshDependencies = resuming && taskConnectionNeedsRefresh(node.task, resumedAssignment!, this.archive.tasks, - connectionIdentity, readSource(worker.worktree, resumedAssignment!.seedCommit), - readSource(this.lead.worktree, this.archive.canonicalCommit!)); - const restoreWorkspace = resuming && - (this.archive.researchDrafts?.[node.task.id]?.suspended || this.researchWorkspaceChanged(worker, node)); - if (refreshDependencies) { - // Wait for the previous reader/writer before changing its seed or the checkout. - if (this.active.get(worker.id)?.action.kind === 'task' || - [...this.proofPublications.values()].some(publication => publication.action.assignment === resumedAssignment)) - return this.waitForDispatch(); - if (!restoreWorkspace) { - const commit = commitSolverSources(this.input.state.problem, worker.worktree); - this.preserveResearchDraft(worker, { kind: 'task', task: node.task, assignment: resumedAssignment! }, commit, - captureDeliveryArtifacts({ problem: this.input.state.problem, worktree: worker.worktree, commit, assignment: resumedAssignment! })); - } - } - if (restoreWorkspace || refreshDependencies) { - const previousAssignment = node.assignment; - const restored = await this.restoreResearchDraft(worker, node, refreshDependencies); - if (this.synchronizationBlocked(node.task) || !this.archive.tasks.includes(node) || node.status !== 'pending' || - this.finalReviewCommit() && ordinaryAdvisoryTask(node.task) || - !restored && node.assignment !== previousAssignment || - assessTaskResponsibility(node, worker, this.responsibility).kind !== 'matches' || - !taskCanStart(node.task, this.archive.tasks, this.archive.groups) || !routeAllowsTask(node.task, this.archive.tasks, this.archive.groups)) return RETRY_DISPATCH; - if (!restored) { - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), ''); - node.assignment = undefined; resuming = false; - if (this.archive.researchCheckpoints) delete this.archive.researchCheckpoints[node.task.id]; - node.feedback = 'math_research_draft_unavailable: No matching saved draft is available; continue from the current canonical sources and save findings for this assignment.'; - this.input.emit('research_draft_unavailable', { taskId: node.task.id, workerId: worker.id }); - } - if (refreshDependencies) node.connectionCheckpoint = undefined; - } - this.suspendResearchDrafts(worker, node.task.id); - const seed = this.archive.canonicalCommit!; - // Another reviewer's notes or notes for changed inputs cannot seed a fresh independent verdict. - // Their pinned draft remains available as archived advisory evidence. - if (!resuming && isFeasibilityReview(node.task)) fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), ''); - const scopedSeed = resuming ? node.assignment!.seedCommit : this.seed(worker, seed, node.task); - const dispatchAssignment: TaskAssignment = resuming ? node.assignment! : { taskId: node.task.id, taskDigest: digest(node.task), workerId: worker.id, - seedCommit: scopedSeed, assignmentId: crypto.randomUUID(), canonicalCommit: seed, groupId: taskGroup(node.task), - routeId: selectedRoute?.id, - ...(isFeasibilityReview(node.task) ? { feasibilityInputDigest: this.feasibilityInputDigest(node.task, worker.id) } : {}), - dependencies: this.dependencies(node.task).map(item => ({ taskId: item.task.id, taskDigest: digest(item.task) })) }; - const claimAssignment = () => { - node.assignment = dispatchAssignment; - if (stoppedAssignment) this.input.emit('task_assignment_released', { taskId: node.task.id, - workerId: stoppedAssignment.workerId, takenBy: worker.id, reason: 'worker-stopped' }); - return dispatchAssignment; - }; - const canonicalGoal = !resuming && node.task.kind === 'goal' && this.canonicalTaskCandidate(node, worker, scopedSeed); - if (node.task.kind === 'lemma' || node.task.kind === 'goal' && (canonicalGoal || this.input.access.get(worker.id)?.installedLibrary)) { - const task = node.task, taskDigest = digest(task), environment = this.input.state.environmentDigest; - const dependencies = this.typePreflightDependencies(task), head = git(worker.worktree, ['rev-parse', 'HEAD']); - const project = path.join(worker.worktree, this.input.state.problem.projectRelative), started = Date.now(); - const routeDigest = canonicalMathJson(selectedRoute ?? null); - const assignment = node.assignment, workerAccess = this.input.access.get(worker.id), leadAccess = this.input.access.get(this.lead.id); - const problemReceipt = this.input.state.problem.receiptDigest; - const controller = new AbortController(), signal = AbortSignal.any([this.input.signal, controller.signal]); - const preparationGroups = () => { - const reserved = this.preparingTaskTypes.get(node)?.workerId === worker.id || - [...this.proofPublications.values()].some(publication => publication.action.assignment === dispatchAssignment); - // Preflight and publication share one slot. Ignore that slot when rechecking admission. - return reserved ? this.archive.groups?.map(route => route.group.id === taskGroup(task) - ? { ...route, busy: Math.max(0, (route.busy ?? 0) - 1) } : route) : this.archive.groups; - }; - const stillSelected = () => this.input.modules.M5.assign([node], worker, this.allocationPeers, - preparationGroups(), this.archive.tasks, this.stoppedWorkers) === node; - const current = () => !signal.aborted && !this.stopping && !this.failure && this.liveWorkers.has(this.lead.id) && - this.archive.canonicalCommit === seed && this.archive.tasks.includes(node) && digest(node.task) === taskDigest && - this.typePreflightDependencies(task) === dependencies && this.input.access.get(worker.id) === workerAccess && - this.input.access.get(this.lead.id) === leadAccess && this.input.state.problem.receiptDigest === problemReceipt && - this.input.state.environmentDigest === environment && node.status === 'pending' && node.assignment === assignment && - !this.synchronizationBlocked(node.task) && taskCanStart(node.task, this.archive.tasks, this.archive.groups) && - routeAllowsTask(node.task, this.archive.tasks, preparationGroups()) && this.liveWorkers.has(worker.id) && - assessTaskResponsibility(node, worker, this.responsibility).kind === 'matches' && - canonicalMathJson(selectedTaskRoute(node, this.archive.tasks) ?? null) === routeDigest && - this.input.modelDispatchAllowed?.() !== false && - !this.dispatchBudgetExhausted(budget, true) && Date.now() - started < budget.remainingMs; - // Cancellation keeps the worker occupied until the Lean check has cleaned up. - let finishPreparation!: () => void; - const settled = new Promise(resolve => { finishPreparation = resolve; }); - this.preparingTaskTypes.set(node, { workerId: worker.id, groupId: taskGroup(task), controller, current, settled }); - this.changed(); - try { - const checker = this.input.modules.M2.checkTask ?? checkTaskProof; - const retainedGoals = () => this.retainedTaskGoals(task, this.archive.tasks, worker.worktree, head); - const publishable = () => current() && taskDependenciesReady(task, this.archive.tasks) && - git(worker.worktree, ['rev-parse', 'HEAD']) === head && stillSelected(); - const claim = () => { - // Publication owns cleanup from here; changing the assignment must not cancel its own preparation. - this.preparingTaskTypes.delete(node); - claimAssignment(); - }; - const probeCanonical = async (publishable: () => boolean): Promise => { - // A failed probe is not a model delivery. Keep it outside failure memory and archive acceptance. - const probeStarted = Date.now(); - let proof, checkError: string | undefined; - try { - proof = await checker(this.input.state.problem, worker.worktree, scopedSeed, task, dispatchAssignment, - retainedGoals(), leadAccess!.environment, signal, task.kind === 'goal' - ? Math.min(this.input.timeoutMs ?? 180_000, Math.max(1, budget.remainingMs - (Date.now() - started))) : this.input.timeoutMs, - [], environment, ...(checker === checkTaskProof ? [this.taskProofCache] : [])); - } catch (error) { - if (!current()) return true; - if (task.kind !== 'goal') throw error; - checkError = bounded(error instanceof Error ? error.message : String(error), 2000); - } - if (!publishable()) return true; - const receiptIds = proof?.verification.results.map(result => result.receiptId) ?? []; - const feedback = proof ? !proof.passed ? bounded(solverProofFeedback(proof), 2000) : undefined : checkError; - const status = proof?.verification.status ?? 'unavailable'; - this.input.emit('task_canonical_probe', { taskId: task.id, taskDigest, workerId: worker.id, seedCommit: scopedSeed, - passed: proof?.passed ?? false, status, durationMs: Date.now() - probeStarted, - receiptIds, ...(feedback ? { feedback } : {}) }); - if (proof?.passed) { - await this.publishTaskProof(worker, { kind: 'task', task, assignment: dispatchAssignment }, scopedSeed, - `Existing canonical ${task.kind === 'goal' ? 'original goal' : 'helper'} checked against this exact task before starting a model.`, {}, false, - { proof, current: publishable, claim }); - return true; - } - dispatchAssignment.canonicalProbe = { evidence: 'advisory-canonical-check', proofAcceptance: 'not-accepted', - sourceCommit: scopedSeed, environmentDigest: environment, verificationStatus: status, receiptIds, feedback: feedback! }; - return false; - }; - if (canonicalGoal && leadAccess && workerAccess && await probeCanonical(publishable)) return RETRY_DISPATCH; - const applyLibrary = this.input.modules.M2.applyLibrary, library = workerAccess?.installedLibrary; - const libraryKey = canonicalMathJson([taskDigest, scopedSeed, environment, library?.digest ?? null]); - if (applyLibrary && library && leadAccess && workerAccess && !resuming && !isDefinitionTask(task) && - !task.conditional && !automaticTaskConnection(task, this.archive.tasks, this.archive.groups) && - taskDependenciesReady(task, this.archive.tasks) && !this.libraryApplicationAttempts.has(libraryKey)) { - this.libraryApplicationAttempts.add(libraryKey); - const applicationStarted = Date.now(); - const application = await applyLibrary({ problem: this.input.state.problem, task, library, taskText: this.input.taskText, environmentDigest: environment, - worktree: worker.worktree, seedCommit: scopedSeed }); - if (!current()) { this.libraryApplicationAttempts.delete(libraryKey); return RETRY_DISPATCH; } - let proof, checkError: string | undefined; - if (application.commit && application.status === 'candidate') { - try { - proof = await checker(this.input.state.problem, worker.worktree, application.commit, task, dispatchAssignment, - retainedGoals(), leadAccess.environment, signal, - Math.min(this.input.timeoutMs ?? Infinity, LIBRARY_APPLICATION_TIMEOUT_MS, budget.remainingMs - (Date.now() - started)), - [], environment, ...(checker === checkTaskProof ? [this.taskProofCache] : [])); - } catch (error) { - if (!current()) return RETRY_DISPATCH; - checkError = bounded(error instanceof Error ? error.message : String(error), 1000); - } - } - if (!publishable()) return RETRY_DISPATCH; - const references = proof && knowledgeReferenceCoverage(task, proof); - this.input.emit('task_library_application', { taskId: task.id, taskDigest, workerId: worker.id, seedCommit: scopedSeed, - libraryDigest: library.digest, candidates: application.candidates, status: application.status, reason: application.reason, - durationMs: Date.now() - applicationStarted, ...(checkError ? { checkError } : {}), - ...(application.commit ? { commit: application.commit } : {}), - ...(references ? { referenceCoverage: references.coverage, usedDeclarations: application.candidates.filter(candidate => - references.references?.some(reference => reference.name === candidate.name && reference.file === candidate.file)) } : {}), - ...(proof ? { passed: proof.passed, verificationStatus: proof.verification.status, - receiptIds: proof.verification.results.map(result => result.receiptId), - ...(!proof.passed ? { diagnostic: bounded(solverProofFeedback(proof), 2000) } : {}) } : {}) }); - if (proof?.passed) { - await this.publishTaskProof(worker, { kind: 'task', task, assignment: dispatchAssignment }, application.commit!, - 'Host applied an installed library theorem to this exact task before starting a model.', {}, false, - { proof, current: publishable, claim }); - return RETRY_DISPATCH; - } - if (proof || checkError) node.feedback = [node.feedback ?? '', - 'Host library application attempt (advisory): the selected installed theorems did not close this task. ' + - 'Continue the original proof; the application event and check receipts retain the attempted-candidate diagnostics.'] - .filter(Boolean).join('\n\n'); - } - if (task.kind === 'lemma') { - const checked: { result: TaskTypePreflight; current: () => boolean } = workerAccess ? await this.taskTypePreflight.check({ problem: this.input.state.problem, task, - projectRoot: project, - // A family type never names its own members, which do not exist in source until they are proved. - dependencies: this.dependencies(task).map(item => item.task).filter(input => input.familyMember !== task.id), environmentDigest: environment, - env: workerAccess.environment, installedLibrary: workerAccess.installedLibrary, signal, - timeoutMs: this.input.timeoutMs ?? Infinity }) : { - result: { status: 'unavailable', inputDigest: mathDigest(canonicalMathJson([taskDigest, environment, 'worker-environment-unavailable'])), - taskDigest, reason: 'worker-environment-unavailable', evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' }, - current: () => !this.input.signal.aborted, - }; - if (!current() || !checked.current() || git(worker.worktree, ['rev-parse', 'HEAD']) !== head || - !stillSelected()) - return RETRY_DISPATCH; - node.typePreflight = checked.result; - this.input.emit('task_type_preflight', { taskId: node.task.id, workerId: worker.id, ...checked.result }); - if (checked.result.status === 'invalid') { - this.invalidTaskTypes.set(node, { canonical: seed, environment, taskDigest, dependencies, project, workerId: worker.id, - environmentIdentity: taskTypePreflightEnvironmentIdentity(project, workerAccess!.environment) }); - this.moveTask(node, 'blocked', 'rejected'); - const excerpt = typeDiagnosticExcerpt(task.type!, checked.result.reason); - node.feedback = 'math_task_type_invalid\n' + bounded(checked.result.reason, 2000) + (excerpt ? `\n${excerpt}` : '') + - (checked.result.artifact ? `\nAdvisory type diagnostics in ${worker.id}'s worktree: ${checked.result.artifact.path} (${checked.result.artifact.digest})` : '') + - '\nRevise the closed helper type or its context before proving it. This is not proof acceptance or a mathematical refutation.'; - this.wakeLead('task-type-invalid'); this.changed(); return RETRY_DISPATCH; - } - const publishable = () => current() && checked.current() && taskDependenciesReady(task, this.archive.tasks) && - git(worker.worktree, ['rev-parse', 'HEAD']) === head && stillSelected(); - const assembleFamily = this.input.modules.M2.assembleFamily; - const familyKey = canonicalMathJson([taskDigest, dependencies, environment]); - if (assembleFamily && task.family && !resuming && leadAccess && workerAccess && checked.result.status === 'elaborated' && - checked.result.context && !this.familyAssemblyAttempts.has(familyKey)) { - // One host assembly per exact family contract in this process; a failure falls through to a model. - this.familyAssemblyAttempts.add(familyKey); - const assemblyStarted = Date.now(); - const assembly = await assembleFamily({ problem: this.input.state.problem, task, worktree: worker.worktree, - seedCommit: scopedSeed, context: checked.result.context }); - if (!current()) { this.familyAssemblyAttempts.delete(familyKey); return RETRY_DISPATCH; } - // Unproved members (and other fixed lemma inputs) are bound exactly as in the ordinary conditional check. - const conditions = this.assignmentConditions(task, dispatchAssignment); - let proof, checkError: string | undefined; - if (assembly.commit) { - try { - proof = await checker(this.input.state.problem, worker.worktree, assembly.commit, task, dispatchAssignment, - retainedGoals(), leadAccess.environment, signal, this.input.timeoutMs, conditions, environment, - ...(checker === checkTaskProof ? [this.taskProofCache] : [])); - } catch (error) { - if (!current()) return RETRY_DISPATCH; - checkError = bounded(error instanceof Error ? error.message : String(error), 600); - } - } - this.input.emit('task_family_assembly', { taskId: task.id, taskDigest, workerId: worker.id, seedCommit: scopedSeed, - status: assembly.status, reason: assembly.reason, durationMs: Date.now() - assemblyStarted, - assumedInputs: conditions.map(input => input.id), ...(checkError ? { checkError } : {}), - ...(assembly.commit ? { commit: assembly.commit } : {}), ...(proof ? { passed: proof.passed, - verificationStatus: proof.verification.status, receiptIds: proof.verification.results.map(result => result.receiptId) } : {}) }); - // A conditional family starts before its members are checked, so this omits the dependency-readiness gate. - const assembled = () => current() && checked.current() && git(worker.worktree, ['rev-parse', 'HEAD']) === head && stillSelected(); - if (proof?.passed) { - if (!assembled()) return RETRY_DISPATCH; - await this.publishTaskProof(worker, { kind: 'task', task, assignment: dispatchAssignment }, assembly.commit!, - 'Host assembled this family lemma from its member lemmas before starting a model.' + (conditions.length - ? ` Its check binds its ${conditions.length} lemma input(s) as explicit hypotheses; the host rechecks it unconditionally once they integrate.` : ''), - {}, false, { proof, current: assembled, claim }); - return RETRY_DISPATCH; - } - if (!assembled()) return RETRY_DISPATCH; - } - const canonicalCandidate = !resuming && leadAccess && workerAccess && this.canonicalTaskCandidate(node, worker, scopedSeed); - if (canonicalCandidate && await probeCanonical(publishable)) return RETRY_DISPATCH; - const closeTask = this.input.modules.M2.closeTask; - const batteryKey = canonicalMathJson([taskDigest, dependencies, environment, checked.result.inputDigest]); - if (closeTask && !resuming && !canonicalCandidate && leadAccess && workerAccess && checked.result.status === 'elaborated' && - checked.result.context && !isDefinitionTask(task) && this.tacticBatteryCandidate(node) && !this.tacticBatteryAttempts.has(batteryKey)) { - // One host attempt per exact helper contract in this process; a failure is not model feedback. - this.tacticBatteryAttempts.add(batteryKey); - const batteryStarted = Date.now(); - const battery = await closeTask({ problem: this.input.state.problem, task, worktree: worker.worktree, seedCommit: scopedSeed, - context: checked.result.context, env: workerAccess.environment, signal, - timeoutMs: Math.min(this.input.timeoutMs ?? Infinity, TACTIC_BATTERY_TIMEOUT_MS) }); - // A superseded preparation has not tried this contract; leave it to the next eligible dispatch. - if (!current()) { this.tacticBatteryAttempts.delete(batteryKey); return RETRY_DISPATCH; } - let proof, checkError: string | undefined; - if (battery.status === 'closed' && battery.commit) { - try { - proof = await checker(this.input.state.problem, worker.worktree, battery.commit, task, dispatchAssignment, - retainedGoals(), leadAccess.environment, signal, this.input.timeoutMs, [], environment, - ...(checker === checkTaskProof ? [this.taskProofCache] : [])); - } catch (error) { - // Host automation never blocks the ordinary model assignment. - if (!current()) return RETRY_DISPATCH; - checkError = bounded(error instanceof Error ? error.message : String(error), 600); - } - } - this.input.emit('task_tactic_battery', { taskId: task.id, taskDigest, workerId: worker.id, seedCommit: scopedSeed, - status: battery.status, reason: battery.reason, durationMs: Date.now() - batteryStarted, ...(checkError ? { checkError } : {}), - ...(battery.cacheHit ? { cacheHit: true, cacheKey: battery.cacheKey, originDiagnosticDigest: battery.originDiagnosticDigest } : {}), - ...(battery.commit ? { commit: battery.commit } : {}), ...(battery.artifact ? { artifact: battery.artifact } : {}), - ...(battery.vacuous ? { vacuous: true } : {}), ...(proof ? { passed: proof.passed, verificationStatus: proof.verification.status, - receiptIds: proof.verification.results.map(result => result.receiptId) } : {}) }); - if (proof?.passed) { - if (!publishable()) return RETRY_DISPATCH; - const advisorySummary = 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.' : undefined; - await this.publishTaskProof(worker, { kind: 'task', task, assignment: dispatchAssignment }, battery.commit!, - 'Host tactic battery closed this exact helper type before starting a model.' + - (advisorySummary ? ' ' + advisorySummary : ''), {}, false, - { proof, current: publishable, claim, ...(advisorySummary ? { advisorySummary } : {}) }); - return RETRY_DISPATCH; - } - if (!publishable()) return RETRY_DISPATCH; - } - } - } finally { - this.preparingTaskTypes.delete(node); finishPreparation(); this.changed(); - } - } - let assignment = claimAssignment(); - if (!assignment.connectionCheck && (resuming && resumedAssignment?.connectionCheck && assignment !== resumedAssignment || - automaticTaskConnection(node.task, this.archive.tasks, this.archive.groups))) { - const candidate = resuming && assignment === resumedAssignment ? { ...assignment, assignmentId: crypto.randomUUID() } : assignment; - const check = createTaskConnectionCheck(node.task, candidate, this.archive.tasks, - connectionIdentity, readSource(worker.worktree, candidate.seedCommit)); - // Upgrading an idle historical assignment keeps its saved draft but supersedes late publications. - if (check.assumedInputs?.length) { - assignment = candidate; - assignment.connectionCheck = check; - node.assignment = assignment; - this.input.emit('task_connection_check_assigned', { taskId: node.task.id, workerId: worker.id, connectionCheck: check }); - } - } - if (!advisory(node.task) && - fs.existsSync(path.join(worker.worktree, this.input.state.problem.projectRelative, '.lake/source-constraints.json'))) { - const problem = this.input.state.problem; - // Local diagnostics should reject the same unrelated goal edits as task delivery, - // before the worker spends time compiling a candidate it cannot submit. - const declarations = Object.fromEntries(Object.entries(problem.declarations).map(([file, originals]) => { - // Library modules are byte-frozen as a whole; their declarations need no per-task bodies. - if (problem.frozenFiles && Object.hasOwn(problem.frozenFiles, file)) return [file, originals]; - const source = committedSource(worker.worktree, assignment.seedCommit, `${problem.projectRelative}/${file}`); - const matching = originalDeclarationRegions(source); - return [file, originals.map(original => { - if (original.body || file === node.task.proofPath && - original.name.split('.').at(-1) === node.task.theoremName?.split('.').at(-1)) return original; - const region = matching(original)[0]!; - return { ...original, body: mathDigest(source.slice(region.bodyOffset, region.endOffset).trim()) }; - })]; - })); - writeMathJsonDurable(path.join(worker.worktree, problem.projectRelative, '.lake/source-constraints.json'), - solverSourceConstraints(problem, declarations), 0o400); - } - this.moveTask(node, 'running', 'dispatched'); - const route = this.archive.groups?.find(record => record.group.id === taskGroup(node.task)); - this.input.emit('task_assigned', { taskId: node.task.id, workerId: worker.id, kind: node.task.kind, - taskDigest: assignment.taskDigest, assignmentKey: assignmentDeliveryFile(assignment), - planVersion: this.archive.planVersion, groupId: taskGroup(node.task), groupTurns: route?.turns, - seedCommit: assignment.seedCommit }); - this.changed(); return { kind: 'task', assignment, task: node.task }; - } - /** Host proof attempts start only from a fresh, unconditional typed helper whose dependencies are checked. */ - private tacticBatteryCandidate(node: TaskRecord): boolean { - const task = node.task; - return !task.conditional && Boolean(task.type?.trim()) && taskDependenciesReady(task, this.archive.tasks) && - !automaticTaskConnection(task, this.archive.tasks, this.archive.groups); - } - /** Declaration scanning only selects complete candidates; the checker still establishes proof and exact type. */ - private canonicalTaskCandidate(node: TaskRecord, worker: ResearchWorker, seed: string): boolean { - const task = node.task; - let kind: 'theorem' | 'definition' | 'instance'; - if (task.kind === 'goal') { - if (task.conditional || !taskDependenciesReady(task, this.archive.tasks) || - automaticTaskConnection(task, this.archive.tasks, this.archive.groups) || - !this.input.state.problem.targets.some(target => target.proofPath === task.proofPath && target.theoremName === task.theoremName)) return false; - const original = committedSource(worker.worktree, this.input.state.problem.baseCommit, - `${this.input.state.problem.projectRelative}/${task.proofPath}`); - const declaration = inspectScopedLeanDeclarations(original).find(item => item.qualifiedName === task.theoremName); - if (!declaration) return false; - kind = declaration.kind; - } else { - if (task.kind !== 'lemma' || !this.tacticBatteryCandidate(node)) return false; - kind = isDefinitionTask(task) ? 'definition' : 'theorem'; - } - const source = committedSource(worker.worktree, seed, `${this.input.state.problem.projectRelative}/${task.proofPath}`); - // The current task projector also requires a unique leaf name within this file. - const declarations = inspectScopedLeanDeclarations(source).filter(item => - item.name.split('.').at(-1) === task.theoremName!.split('.').at(-1)); - if (declarations.length !== 1 || declarations[0].kind !== kind || - declarations[0].qualifiedName !== task.theoremName) return false; - const region = inspectLeanDeclarationRegions(source).find(item => item.startOffset === declarations[0].startOffset)!; - const inspected = inspectLeanSource(source.slice(region.bodyOffset, region.endOffset)); - return inspected.sorryCount === 0 && inspected.admitCount === 0; - } - private typePreflightDependencies(task: CooperativeTask) { - return canonicalMathJson(this.dependencies(task).map(item => [item.task.id, digest(item.task)])); - } - private refreshInvalidTaskTypes() { - let changed = false; - for (const node of this.archive.tasks) { - if (node.status !== 'blocked' || node.typePreflight?.status !== 'invalid') continue; - const prior = this.invalidTaskTypes.get(node); - const access = prior && this.input.access.get(prior.workerId); - if (prior && access && prior.canonical === this.archive.canonicalCommit && prior.environment === this.input.state.environmentDigest && - prior.taskDigest === digest(node.task) && prior.dependencies === this.typePreflightDependencies(node.task) && - prior.environmentIdentity === taskTypePreflightEnvironmentIdentity(prior.project, access.environment)) continue; - this.moveTask(node, 'pending', 'reopened'); node.typePreflight = undefined; - if (node.feedback?.startsWith('math_task_type_invalid\n')) node.feedback = undefined; - this.invalidTaskTypes.delete(node); changed = true; - } - return changed; - } - private canAdvance(taskIds?: ReadonlySet) { - return researchCanAdvance(this.archive.tasks, this.archive.groups, this.liveWorkers, node => - !this.preparingTaskTypes.has(node) && !this.synchronizationBlocked(node.task) && - this.livePeers.some(worker => assessTaskResponsibility(node, worker, this.responsibility).kind === 'matches' && - this.input.modules.M5.assign([node], worker, this.livePeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) === node), taskIds, - this.stoppedWorkers); - } - private hasAssignableTask(taskIds?: ReadonlySet) { - return this.input.modules.M3.ready(this.archive.tasks, this.archive.groups).some(node => !this.preparingTaskTypes.has(node) && !this.synchronizationBlocked(node.task) && - (!taskIds || taskIds.has(node.task.id)) && this.archive.tasks.includes(node) && - this.livePeers.some(worker => assessTaskResponsibility(node, worker, this.responsibility).kind === 'matches' && - this.input.modules.M5.assign([node], worker, this.livePeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) === node)); - } - candidateReady(check: ProofCheck): boolean { - if (check.commit !== this.archive.canonicalCommit || this.candidateSynchronizationBlocked()) return false; - const reviewRequired = this.input.state.planApproval || this.archive.review || this.archive.tasks.some(({ task }) => - task.statementReview || isActiveFinalCandidateReview(task)); - if (!reviewRequired || this.reviewed(check)) return true; - this.requireReview(check); - return false; - } - reviewed(check?: ProofCheck) { - const required = this.fixedStatementReviewTasks(); - if (this.fixedReviewScope && !required) return false; - return !this.candidateSynchronizationBlocked() && this.archive.review?.status === 'accepted' && this.archive.review.commit === this.archive.canonicalCommit && - (!check || (check.commit === this.archive.review.commit && check.sourceDigest === this.archive.review.sourceDigest)) && - this.archive.tasks.filter(node => node.task.statementReview && (!required || required.has(node.task.id))).every(node => this.archive.statementReviews?.some(review => - review.taskId === node.task.id && review.taskDigest === digest(node.task) && review.status === 'accepted')); - } - requireReview(check: ProofCheck) { - if (this.archive.review?.commit !== check.commit || this.archive.review.sourceDigest !== check.sourceDigest) { - this.archive.review = { commit: check.commit, sourceDigest: check.sourceDigest, status: 'pending' }; - this.input.emit('review_requested', { commit: check.commit }); - } - const configured = this.archive.tasks.filter(node => node.task.statementReview), used = new Set(); - const referencedDeclarations = new Set(); - const problem = this.input.state.problem; - let complete = hasFreshSolverCheck(check) && proofReceiptsMatch(check.verification, check.commit, - problem.targets.map(target => ({ proofPath: target.proofPath, theoremName: target.theoremName, - expectedSourceDeclarationHash: target.declarationHash, statementHash: problem.contract.statementHash, - leanStatementHash: problem.contract.leanStatementHash, claim: 'statement' }))); - if (complete) for (const target of problem.targets) { - const receipt = check.verification.results.find(result => result.proofPath === target.proofPath && result.theoremName === target.theoremName); - const references = receipt?.declarationReferences && captureProofReferences(problem, this.lead.worktree, check.commit, - { name: target.theoremName, file: target.proofPath }, receipt.declarationReferences, this.input.state.environmentDigest); - if (!references) { complete = false; break; } - for (const reference of attributeTaskReferences(references, this.archive.tasks)) used.add(reference.taskId); - for (const reference of [...references.statement, ...references.proof]) - referencedDeclarations.add(reference.file + '\0' + reference.name); - } - const producers = new Set(this.archive.tasks.flatMap(node => node.status === 'integrated' && node.assignment && - (node.task.kind === 'goal' || used.has(node.task.id) || !complete && node.task.kind === 'lemma') - ? [node.assignment.workerId] : [])); - for (const helper of this.archive.landedHelpers ?? []) if (helper.producer && - (!complete || referencedDeclarations.has(helper.file + '\0' + helper.qualifiedName))) producers.add(helper.producer); - this.archive.review.producerIds = [...producers].sort(); - const required = new Map(configured.filter(node => !complete || node.task.kind === 'goal' || used.has(node.task.id)) - .map(node => [node.task.id, digest(node.task)])); - this.fixedReviewScope = { review: this.archive.review, commit: check.commit, sourceDigest: check.sourceDigest, - environmentDigest: this.input.state.environmentDigest, tasksDigest: this.statementTaskIdentity(), required }; - for (const active of this.active.values()) if (isStatementAction(active.action) && !this.current(active.action) && !active.cancelled) { - const reviewId = active.action.reviewId; - const statement = this.archive.statementReviews?.find(item => item.id === reviewId); - if (statement) resetStatementReview(statement); - active.cancelled = true; void active.interrupt().catch(() => {}); - } - this.input.emit('final_statement_review_scope', { commit: check.commit, sourceDigest: check.sourceDigest, - referenceCoverage: complete ? 'complete' : 'unknown', requiredTaskIds: [...required.keys()], - unusedTaskIds: configured.filter(node => !required.has(node.task.id)).map(node => node.task.id) }); - this.changed(); - } - contextState(action?: CooperativeAction, worker?: ResearchWorker, versions: TaskVersions = this.taskVersions()): CooperationState { - const record = worker && this.input.state.workers?.find(item => item.id === worker.id); - const checkpointWorkerId = worker?.id ?? (action?.kind === 'task' ? action.assignment.workerId : action?.kind === 'lead' ? this.lead.id : undefined); - const checkpointResearch = this.input.state.workers?.find(peer => peer.id === checkpointWorkerId) ?? - (checkpointWorkerId === this.lead.id ? this.input.state : undefined); - const ordinaryWorker = !action && worker && worker.id !== this.lead.id; - const task = action?.kind === 'task' ? action.task : ordinaryWorker ? - this.archive.tasks.find(node => node.status === 'running' && node.assignment?.workerId === worker.id)?.task ?? - this.archive.tasks.find(node => node.task.id === record?.sessionTaskId)?.task : undefined; - const tasks = task ? this.visible(task) : ordinaryWorker ? - this.archive.tasks.filter(node => node.task.sharing !== 'group' && ['integrated', 'completed'].includes(node.status)) : this.archive.tasks; - const gapViewer = task ?? (ordinaryWorker ? { id: 'idle', groupId: '__idle__' } as CooperativeTask : undefined); - const visibleIds = new Set(tasks.map(node => node.task.id)); - const visible = (id: string, version: string) => visibleIds.has(id) && versions.get(id)?.version === version; - const deliveries = this.archive.deliveries?.filter(item => this.deliveryVisible(item, task, versions, gapViewer) && - (task || tasks === this.archive.tasks || !item.taskId || versions.get(item.taskId)?.task.sharing !== 'group')) ?? []; - const hiddenFindings = new Set((this.archive.deliveries ?? []).filter(item => - !mathematicalGapVisible(item, this.archive, gapViewer)).flatMap(item => item.findingDigest ? [item.findingDigest] : [])); - const scopedFinding = (node: T): T => node.finding && hiddenFindings.has(mathDigest(node.finding)) ? - { ...node, finding: undefined } : node; - const proofRoutes = (this.archive.proofRoutes ?? this.archive.tasks.flatMap(node => node.alternativeRoutes ?? [])) - .filter(route => visibleIds.has(route.targetTaskId) && - [route.closingTaskId, ...route.prerequisiteTaskIds].every(id => visibleIds.has(id))); - const scopedTasks = tasks.map(node => scopedFinding(node.alternativeRoutes?.length ? { ...node, - alternativeRoutes: proofRoutes.filter(route => route.targetTaskId === node.task.id) } : node)); - // The Lead's own context is built before its turn starts; that turn then becomes the next inbox basis. - const leadInboxView = action?.kind === 'lead' && !this.active.has(this.lead.id) ? leadInbox(this.archive.leadInboxBasis, { - tasks: this.archive.tasks, planVersion: this.archive.planVersion, deliveries: this.archive.deliveries, leadId: this.lead.id, - workers: this.input.state.workers, roles: new Map(this.input.workers.map(peer => [peer.id, peer.role])) }) : undefined; - // Keep the earliest snapshot for this dispatch: repeating a change is harmless, skipping one is not. - if (action?.kind === 'lead' && !this.active.has(this.lead.id) && !this.pendingLeadInboxBases.has(action)) - this.pendingLeadInboxBases.set(action, leadInboxBasis(this.archive.tasks, this.archive.planVersion)); - if (action?.kind === 'lead' && !this.active.has(this.lead.id) && !this.presentedNextCheckOutcomes.has(action)) - this.presentedNextCheckOutcomes.set(action, (this.archive.nextChecks ?? []).flatMap(record => - record.status === 'awaiting-decision' && record.outcome ? [{ checkId: record.id, outcomeDeliveryId: record.outcome.deliveryId }] : [])); - const searchRecord = action?.kind === 'task' ? this.proofSearchAssignment(action).record : undefined; - const guidance = checkpointWorkerId ? readHumanGuidance(path.join(path.dirname(this.lead.worktree), 'state.json'), this.input.state.runId) - .filter(item => { - if (item.status !== 'delivered' || !item.deliveredTo?.includes(checkpointWorkerId)) return false; - const target = item.deliveredScope?.taskRef ?? item.taskRef; - return target ? task?.id === target.id && digest(task) === target.version : !task && - (!item.deliveredScope?.planVersion || item.deliveredScope.planVersion === - (action?.kind === 'lead' ? action.planVersion ?? this.archive.planVersion : this.archive.planVersion)); - }) : undefined; - return { ...this.archive, tasks: scopedTasks, leadInbox: leadInboxView, humanGuidance: guidance, - leadDecisionInstruction: action?.kind === 'lead' ? this.leadCheckpointInstruction(action) : undefined, - researchDecisions: action?.kind === 'lead' || worker?.id === this.lead.id ? this.archive.researchDecisions : undefined, - ...(action?.kind === 'lead' && this.presentedResearchInputs.has(action) ? { - leadResearchInputIds: this.presentedResearchInputs.get(action)!.shown.map(record => record.id), - leadResearchInputCount: this.presentedResearchInputs.get(action)!.total, - } : {}), - proofSearchRecords: searchRecord ? { [searchRecord.taskId]: searchRecord } : undefined, - goalProgress: action?.kind === 'lead' || worker?.id === this.lead.id ? this.archive.goalProgress : - action?.kind === 'task' ? goalProgressForTask(this.archive.goalProgress, action.task) : undefined, - goalPathReview: action?.kind === 'lead' || worker?.id === this.lead.id ? this.goalPathReview() : undefined, - planPublicationRejection: (action?.kind === 'lead' || worker?.id === this.lead.id) && - this.archive.planPublicationRejection?.baseVersion === this.archive.planVersion ? this.archive.planPublicationRejection : undefined, - contextCheckpointRejection: checkpointResearch ? contextCheckpointRejection(checkpointResearch) : undefined, - deliveryReceipts: worker && action?.kind === 'task' - ? assignmentDeliveryReceipts(this.archive.deliveryReceipts, action.assignment, this.input.state.environmentDigest, worker.id) - : this.archive.deliveryReceipts?.filter(receipt => receipt.workerId === worker?.id && - receipt.environmentDigest === this.input.state.environmentDigest && visible(receipt.taskId, receipt.taskDigest)), - proofReadyRecords: this.archive.proofReadyRecords?.filter(receipt => - (action?.kind === 'lead' || worker?.id === this.lead.id || worker && receipt.workerId === worker.id && - (action?.kind !== 'task' || receipt.assignmentKey === assignmentDeliveryFile(action.assignment))) && - receipt.problemReceiptDigest === this.input.state.problem.receiptDigest && - receipt.environmentDigest === this.input.state.environmentDigest), - parallelQuestions: parallelQuestions(this.archive.tasks, task).filter(question => !ordinaryWorker || task || - versions.get(question.taskId)?.task.sharing !== 'group'), - consumerInterfaces: task ? taskConsumerProjection(task, this.archive.tasks, this.archive.proofRoutes) : undefined, - landedHelpers: this.archive.landedHelpers, - mathematicalGaps: mathematicalGaps(this.archive, { problemReceiptDigest: this.input.state.problem.receiptDigest, - environmentDigest: this.input.state.environmentDigest }, gapViewer), - nextChecks: visibleNextChecks(this.archive, gapViewer), - failedTaskInputs: this.archive.failedTaskInputs?.filter(record => tasks === this.archive.tasks || visible(record.taskId, record.taskDigest)), - progressSnapshot: tasks === this.archive.tasks ? this.archive.progressSnapshot : undefined, - progressReceipts: tasks === this.archive.tasks ? this.archive.progressReceipts : undefined, - blockers: this.archive.blockers?.filter(blocker => tasks === this.archive.tasks || - (visibleIds.has(blocker.taskId) && task && blocker.groupId === taskGroup(task))), - proofRoutes, - unchangedResearch: this.archive.unchangedResearch && Object.fromEntries(Object.entries(this.archive.unchangedResearch) - .filter(([id, record]) => visible(id, record.taskDigest))), - researchCheckpoints: this.archive.researchCheckpoints && Object.fromEntries(Object.entries(this.archive.researchCheckpoints) - .filter(([id, record]) => visible(id, record.taskDigest))), - researchDrafts: this.archive.researchDrafts && Object.fromEntries(Object.entries(this.archive.researchDrafts) - .filter(([id, record]) => visible(id, record.taskDigest))), - // Public progress can steer another route before its proof is complete; it remains advisory. - deliveries, - history: (tasks === this.archive.tasks ? this.archive.history : this.archive.history?.filter(item => - visible(item.task.id, digest(item.task))))?.map(scopedFinding), - statementReviews: this.archive.statementReviews?.filter(item => item.status !== 'superseded' && visible(item.taskId, item.taskDigest)) }; - } - private async deliverLead(worker: ResearchWorker, action: Extract, commit: string, - recovering: boolean, recoveryKind: 'checkpoint' | 'request-failure' | 'scheduling-checkpoint'): Promise<{ checkWhole: boolean; savedPlan?: boolean }> { - const staged = await this.input.exclusiveCheck(async () => { - if (!this.current(action)) { - this.input.emit('lead_decision_superseded', { commit }); this.syncPlanNotes(); this.wakeLead('lead-turn-superseded'); this.changed(); - return { finished: true as const, checkWhole: false }; - } - const sourceChanged = ownedSourceDigest(this.input.state.problem, worker.worktree, action.seedCommit) !== - ownedSourceDigest(this.input.state.problem, worker.worktree, commit); - let accepted = false; - const publishedPlan = this.leadPublication(action); - const previousPlanVersion = this.planVersion(); - const obligations = this.leadDecisionObligations(action); - const requiredDecision = obligations.any; - try { - const schedulingDraft = recovering && recoveryKind === 'scheduling-checkpoint' && !action.initialPlanNonce && - !publishedPlan && this.archive.tasks.length > 0; - const savedNotes = publishedPlan || schedulingDraft ? this.leadNotes().text : ''; - let unchangedCheckpoint = false, changedNotes = false; - if (schedulingDraft && savedNotes !== undefined) { - try { - const seedNotes = this.leadNotes(action.seedCommit).text; - unchangedCheckpoint = seedNotes !== undefined && - this.proposedPlanDigest(seedNotes) === this.proposedPlanDigest(savedNotes); - changedNotes = seedNotes?.trim() !== savedNotes.trim(); - } catch { /* Without a readable dispatch baseline, validate the saved response normally. */ } - } - const hasPlan = hasPlanResponse(savedNotes ?? ''); - let hasFinalPlan = hasPlan; - if (publishedPlan && hasPlan && savedNotes !== undefined) { - const seedNotes = this.leadNotes(action.seedCommit); - const baseline = seedNotes.text === undefined ? seedNotes.digest : this.proposedPlanDigest(seedNotes.text); - hasFinalPlan = baseline !== this.proposedPlanDigest(savedNotes); - } - if (schedulingDraft && (savedNotes === undefined || changedNotes && savedNotes.trim() && !hasPlan)) { - // A scheduled yield can save fresh mathematical notes before Lead has a decision to submit. - this.pin(commit); - if (requiredDecision) this.wakeLead('lead-checkpoint-unchanged'); - this.input.emit('lead_checkpoint_saved', { commit, seedCommit: action.seedCommit, - reason: savedNotes === undefined ? 'oversized-notes-draft' : 'notes-only-draft' }); - } else if (unchangedCheckpoint && !requiredDecision) { - // Inherited control notes are a draft, not a fresh response to this dispatch. - // Continue below so saved Lean source changes still take the ordinary merge path. - this.pin(commit); this.wakeLead('lead-checkpoint-unchanged'); - this.input.emit('lead_checkpoint_saved', { commit, seedCommit: action.seedCommit, - reason: 'unchanged-control-response' }); - } else if (publishedPlan && !hasFinalPlan) { - // A published immutable event remains useful when the continued writer only saves notes. - accepted = true; - } else { - await this.acceptPlan(undefined, undefined, undefined, action); - accepted = true; - } - } catch (error) { - this.rejectPlan(error, recovering ? recoveryKind : undefined); - if (recovering) { - // Keep partial notes resumable, and share a draft only when its owned Lean source changed. - const reason = error instanceof Error ? error.message : 'math_plan_incomplete'; - this.preserveLeadDraft(commit, action.seedCommit, reason, { requestDecision: false, shareSource: sourceChanged }); - } - if (!this.archive.tasks.length && !(recovering && recoveryKind === 'request-failure')) { - try { await this.startInitialTasks(); } - catch (fallbackError) { this.input.emit('initial_plan_fallback_failed', { - reason: fallbackError instanceof Error ? fallbackError.message : 'math_initial_plan_failed' }); } - } - } - // Clearing generic host feedback does not recover an unchanged failed request. - // Explicit research, progress and check decisions can advance an unchanged graph. - const decisionProgress = Boolean(publishedPlan) || accepted && - (previousPlanVersion !== this.planVersion() || obligations.research || obligations.progress || obligations.nextCheck); - const savedPlan = recovering && recoveryKind === 'request-failure' && decisionProgress; - if (publishedPlan && accepted && !recovering) publishedPlan.finalized = true; - if (accepted && (!recovering || decisionProgress)) this.rememberLeadDecision(action); - if (recovering && recoveryKind !== 'request-failure' && action.kind === 'lead' && - !action.initialPlanNonce && !decisionProgress && !this.leadDecisionObligations(action).any) { - this.archive.lastLeadPauseInputDigest = this.leadPauseInputs.get(action); - } - // The decision or pause above is durable now; a restart must not re-ask this turn's wake-ups. - settleLeadWakes(this.archive.leadWakes!); - // A failed request that saved nothing has not considered the stall; a decision, rejection or pause has. - if (!recovering || recoveryKind !== 'request-failure' || decisionProgress) this.answerGoalPathStall(action, !recovering); - this.changed(); - return { finished: false as const, sourceChanged, savedPlan, planVersion: this.archive.planVersion }; - }); - if (staged.finished) return { checkWhole: false }; - const saved = staged.savedPlan ? { savedPlan: true } : {}; - if (!staged.sourceChanged) return { checkWhole: false, ...saved }; - try { - for (;;) { - const snapshot = await this.input.exclusiveCheck(async () => { - if (this.archive.planVersion !== staged.planVersion) { - this.preserveLeadDraft(commit, action.seedCommit, 'math_lead_decision_superseded', { requestDecision: false }); this.changed(); return; - } - return { canonical: this.archive.canonicalCommit!, environmentDigest: this.input.state.environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest }; - }); - if (!snapshot) return { checkWhole: false, ...saved }; - const merged = await this.mergeLeadSources(commit, action.seedCommit, snapshot.canonical); - const published = await this.input.exclusiveCheck(async () => { - this.input.signal.throwIfAborted(); - if (this.archive.planVersion !== staged.planVersion) { - this.preserveLeadDraft(commit, action.seedCommit, 'math_lead_decision_superseded', { requestDecision: false }); this.changed(); return 'superseded'; - } - if (this.archive.canonicalCommit !== snapshot.canonical || this.input.state.environmentDigest !== snapshot.environmentDigest || - this.input.state.problem.receiptDigest !== snapshot.problemReceiptDigest) return 'retry'; - this.archive.canonicalCommit = merged; - this.settleSourceResearchDecisions(action, snapshot.canonical, merged); - const integrated = new Set(this.archive.tasks.filter(node => node.status === 'integrated').map(node => node.task.id)); - this.markPendingValidation(this.archive.tasks.filter(node => integrated.has(node.task.id) || node.task.statementReview), integrated); - this.changed(); return 'published'; - }); - if (published === 'retry') continue; - if (published === 'superseded') return { checkWhole: false, ...saved }; - await this.schedulePlanSynchronization(); - return await this.input.exclusiveCheck(async () => { - if (this.archive.planVersion !== staged.planVersion || this.candidateSynchronizationBlocked()) return { checkWhole: false, ...saved }; - const problem = this.input.state.problem; - const unchangedDraft = git(worker.worktree, ['rev-parse', 'HEAD']) === commit && problem.ownedFiles.every(file => { - const local = path.join(worker.worktree, problem.projectRelative, file); - return fs.existsSync(local) && fs.readFileSync(local, 'utf8') === committedSource(worker.worktree, commit, `${problem.projectRelative}/${file}`); - }); - if (unchangedDraft) this.archive.canonicalCommit = this.seed(worker, this.archive.canonicalCommit!); - this.changed(); return { checkWhole: unchangedDraft, ...saved }; - }); - } - } catch (error) { - this.input.signal.throwIfAborted(); - if (error instanceof VerificationCheckpointError || error instanceof Error && error.message === 'math_verifier_unavailable') throw error; - await this.input.exclusiveCheck(async () => { - this.preserveLeadDraft(commit, action.seedCommit, error instanceof Error ? error.message : 'math_lead_integration_failed', - { requestDecision: this.archive.planVersion === staged.planVersion }); - this.changed(); - }); - return { checkWhole: false, ...saved }; - } - } - /** A completed assistant final may report advisory decisions independently of its file delivery. */ - async deliverCompletedGuidance(worker: ResearchWorker, action: CooperativeAction, decisions: unknown) { - await this.retainGuidanceDecisions(worker, action, decisions); - } - async deliver(worker: ResearchWorker, action: CooperativeAction, commit: string, recovering = false, - recoveryKind: 'checkpoint' | 'request-failure' | 'scheduling-checkpoint' | 'proof-handoff' | 'final-review-handoff' = 'checkpoint'): Promise<{ check?: ProofCheck; checkWhole: boolean; savedPlan?: boolean }> { - if (isStatementAction(action)) return this.deliverStatement(worker, action); - // Optional handling decisions are metadata; malformed/forged ones cannot change mathematical delivery acceptance. - let response: any; - try { response = block(worker.worktree, action.kind === 'lead' ? 'math-plan' : action.kind === 'review' ? 'math-review' : 'math-result', {}, 'summary'); } - catch { /* Saved proof work and ordinary Markdown still follow their existing delivery protocols. */ } - await this.retainGuidanceDecisions(worker, action, response?.guidanceDecisions); - if (action.kind === 'review') { - const review = this.archive.review; - if (!review || !this.current(action) || review.workerId !== worker.id) { - this.record(worker, undefined, 'review', 'superseded', 'The reviewed version is no longer current.', { commit: action.seedCommit }); - return { checkWhole: false }; - } - if (recovering) { this.interrupted(worker, action); return { checkWhole: false }; } - let evidenceRefs: readonly string[] = []; - try { - if (ownedSourceDigest(this.input.state.problem, worker.worktree, commit) !== action.sourceDigest) - throw new Error('math_review_source_changed'); - const result = block(worker.worktree, 'math-review', { commit: action.seedCommit }); - if (result.commit !== action.seedCommit) throw new Error('math_review_delivery_invalid'); - const status = reviewVerdict(result.verdict, 'math_review_delivery_invalid'); - const details = deliveryDetails(result); - review.status = status; review.summary = details.summary; - evidenceRefs = details.evidenceRefs; - this.input.emit('review_completed', { commit: review.commit, verdict: review.status, workerId: worker.id, independent: review.independent }); - } catch (error) { - review.status = 'changes_requested'; review.summary = error instanceof Error ? error.message : 'math_review_failed'; - } - review.workerId = undefined; - if (review.status === 'accepted') this.lastAssembly = undefined; - else { this.archive.error = review.summary; this.wakeLead('review-changes-requested'); } - this.record(worker, undefined, 'review', review.status, review.summary ?? '', { commit: review.commit, sourceDigest: review.sourceDigest, evidenceRefs }); - return { checkWhole: false }; - } - if (action.kind === 'assemble') { - this.changed(); - return { checkWhole: true }; - } - if (action.kind !== 'task') { - const pending = this.deliverLead(worker, action, commit, recovering, - recoveryKind === 'proof-handoff' || recoveryKind === 'final-review-handoff' ? 'checkpoint' : recoveryKind); - this.leadDeliveries.add(pending); - this.refreshPlanApproval(); - try { return await pending; } finally { this.leadDeliveries.delete(pending); this.wake(); } - } - const node = this.node(action.task.id); - if (!this.current(action)) { - this.record(worker, action.task, advisory(action.task) ? 'research' : 'proof', 'superseded', 'Delivery belongs to a superseded assignment.', - { taskDigest: action.assignment.taskDigest, premises: action.task.premises ?? [], dependencies: action.assignment.dependencies ?? [], commit }); - this.input.emit('task_delivery_superseded', { taskId: action.task.id, workerId: worker.id, commit }); - return { checkWhole: false }; - } - let unchangedNotesBlob: string | undefined; - let artifacts: DeliveryArtifactManifest | undefined; - try { - artifacts = captureDeliveryArtifacts({ problem: this.input.state.problem, worktree: worker.worktree, commit, assignment: action.assignment }); - if (advisory(node.task)) { - if (recovering) { - this.preserveResearchDraft(worker, action, commit, artifacts); - if (recoveryKind !== 'request-failure') - await this.researchCheckpoint(worker, action, commit, - recoveryKind !== 'proof-handoff' && recoveryKind !== 'final-review-handoff'); - else this.interrupted(worker, action); - return { checkWhole: false }; - } - taskChanges(this.input.state.problem, worker.worktree, commit, node.task, action.assignment); - const notesBlob = (version: string) => git(worker.worktree, ['ls-tree', '--format=%(objectname)', version, '--', 'RESEARCH.md']); - const inherited = notesBlob(action.assignment.seedCommit), submitted = notesBlob(commit); - if (!submitted || inherited === submitted) { - unchangedNotesBlob = submitted; - throw new Error(submitted ? 'math_research_delivery_unchanged: Replace inherited RESEARCH.md with findings for the current task.' - : 'math_research_delivery_unchanged: Write RESEARCH.md with findings for the current task.'); - } - await this.publishResearchFinding(worker, action, commit, - { kind: 'notes', text: committedSource(worker.worktree, commit, 'RESEARCH.md') }, { artifacts }); - } else { - // The same assignment resumes; the next real turn of this draft is still checked. - if (recovering && recoveryKind === 'request-failure' && this.untouchedTaskSeed(worker, action, commit)) { - this.interrupted(worker, action); return { checkWhole: false }; - } - const proof = await this.publishTaskProof(worker, action, commit, - 'Fixed declaration checked; unresolved lemma assumptions remain obligations.', { artifacts }, recovering); - return { check: proof, checkWhole: false }; - } - } catch (error) { - this.input.signal.throwIfAborted(); - if (!(error instanceof Error) || error.name === 'AbortError' || - ['delivered', 'conditional', 'integrated'].includes(node.status) || - !(error instanceof SyntaxError) && !directDeliveryRejections.has(rejectionCode(error))) throw error; - if (!this.current(action)) return { checkWhole: false }; - const feedback = error instanceof Error ? error.message : 'math_task_delivery_failed'; - if (advisory(node.task)) { - // A turn that never wrote RESEARCH.md is rejected with an empty submission instead of stopping the worker. - const submission = git(worker.worktree, ['ls-tree', '--name-only', commit, '--', 'RESEARCH.md']) - ? committedSource(worker.worktree, commit, 'RESEARCH.md') : ''; - this.rejectWorkerDelivery(worker, action, submission, error); - this.input.save(); - } - if (artifacts?.artifacts.length) this.record(worker, node.task, 'progress', 'advisory', - 'Recoverable supporting code retained after an incomplete or rejected delivery; it still requires typed host checking.', - { commit, artifacts, remainingObligations: [node.task.id] }); - if (error instanceof ResearchAdmissionError) { - // A malformed report is corrected by the same writer, not a mathematical route failure. - if (!artifacts) throw error; - this.preserveResearchDraft(worker, action, commit, artifacts); - this.interrupted(worker, action); - return { checkWhole: false }; - } - if (recovering && recoveryKind === 'request-failure' && feedback.startsWith('math_task_repeated_failed_input\n') && - this.restoreInterruptedRepair(worker, action, commit)) { - return { checkWhole: false }; - } - if (recovering && feedback.startsWith('math_task_missing_declaration\n')) { - if (this.continueTaskCheckpoint(worker, node, commit)) { - node.feedback = feedback; this.interrupted(worker, action); - } else this.rejected(action, feedback, commit); - return { checkWhole: false }; - } - if (/^math_task_(?:missing_declaration|repeated_failed_input)\n/u.test(feedback) || isTaskSourceRepairFeedback(feedback)) - this.rejected(action, feedback, commit, recovering); - else if (recovering) { node.feedback = feedback; this.interrupted(worker, action); } - else if (unchangedNotesBlob !== undefined) { - this.reportBlockers(node.task, [{ mechanism: 'unchanged-research-delivery', scope: 'assigned-local-inference' }]); - const previous = this.archive.unchangedResearch?.[node.task.id]; - const count = previous?.taskDigest === action.assignment.taskDigest && previous.notesBlob === unchangedNotesBlob ? previous.count + 1 : 1; - (this.archive.unchangedResearch ??= {})[node.task.id] = { taskDigest: action.assignment.taskDigest, notesBlob: unchangedNotesBlob, count }; - this.input.emit('research_delivery_unchanged', { taskId: node.task.id, taskDigest: action.assignment.taskDigest, count, needsDecision: count >= 2 }); - if (count >= 2) this.rejected(action, feedback, commit); - else { node.feedback = feedback; this.interrupted(worker, action); } - } else this.rejected(action, feedback, commit); - } - return { checkWhole: false }; - } - private releaseTaskReservation(worker: ResearchWorker, action: Extract, unstarted = false) { - const node = this.node(action.task.id); - // Validity may have expired before admission. Cleanup still owns this exact reservation, - // but a delayed callback must never revoke a different worker, contract or successor. - if (node?.status !== 'running' || node.assignment !== action.assignment || action.assignment.workerId !== worker.id || - digest(node.task) !== action.assignment.taskDigest) return; - if (!this.current(action) || unstarted && !node.attempts) node.assignment = undefined; - this.moveTask(node, 'pending', 'interrupted'); - } - interrupted(worker: ResearchWorker, action: CooperativeAction) { - if (isStatementAction(action)) { - const review = this.archive.statementReviews?.find(item => item.id === action.reviewId); - if (review && this.current(action) && review.workerId === worker.id) resetStatementReview(review); - } else if (action.kind === 'task') { - this.releaseTaskReservation(worker, action); - } - else if (action.kind === 'review') { - const review = this.archive.review; - if (review && this.current(action) && review.workerId === worker.id) { review.status = 'pending'; review.workerId = undefined; } - } - else this.wakeLead('lead-turn-interrupted'); - this.changed(); - } - rejected(action: CooperativeAction, feedback: string, commit?: string, incomplete = false) { - if (['task', 'lead', 'review'].includes(action.kind) && !this.current(action)) return; - let localRepair = false; - let reviewWorker: ResearchWorker | undefined; - if (isStatementAction(action)) { - const review = this.archive.statementReviews?.find(item => item.id === action.reviewId); - if (!review || !this.current(action)) return; - review.status = 'changes_requested'; review.summary = feedback; - const worker = this.input.workers.find(item => item.id === review.workerId); - review.workerId = undefined; - this.archive.error = feedback; this.wakeLead('statement-review-rejected'); - if (worker) this.record(worker, this.node(review.taskId).task, 'failure', 'failed', feedback, - { sourceDigest: review.snapshotDigest, commit: review.commit }); - else this.changed(); - return; - } else if (action.kind === 'task') { - const node = this.node(action.task.id); this.moveTask(node, 'blocked', 'rejected'); node.feedback = feedback; - if (incomplete) this.restoreTaskSourceRepair(node); - else this.settleTaskSourceRepair(node); - if (isTaskSourceRepairFeedback(feedback)) localRepair = this.retryTaskSourceLocally(node); - else if (/^math_task_(?:missing_declaration|repeated_failed_input)\n/u.test(feedback)) { - const worker = this.input.workers.find(worker => worker.id === action.assignment.workerId); - if (worker && commit && feedback.startsWith('math_task_missing_declaration\n')) - this.rememberTaskFailure(this.failedTaskInput(action.task, action.assignment, worker.worktree, commit), feedback); - localRepair = this.retryTaskLocally(node, commit); - if (!localRepair) this.settleTaskRepair(node); - } - } else if (action.kind === 'review') { - reviewWorker = this.input.workers.find(item => item.id === this.archive.review!.workerId); - this.archive.review!.status = 'changes_requested'; this.archive.review!.summary = feedback; - this.archive.review!.workerId = undefined; - } else this.archive.error = feedback; - const worker = action.kind === 'task' ? this.input.workers.find(item => item.id === action.assignment.workerId) : - action.kind === 'review' ? reviewWorker : this.lead; - if (!localRepair) this.wakeLead(action.kind === 'task' ? 'task-delivery-rejected' : - action.kind === 'review' ? 'review-changes-requested' : 'lead-turn-rejected'); - if (worker) this.record(worker, action.kind === 'task' ? action.task : undefined, 'failure', 'failed', feedback, { commit }); - else this.changed(); - } - assemblyFailed(check: ProofCheck) { this.archive.error = solverProofFeedback(check); this.wakeLead('assembly-failed'); this.changed(); } - /** A reserved turn may still be refunded; the caller rechecks synchronously after waking. */ - waitForTurn(maxTurns: number): Promise | undefined { - return this.input.state.turns >= maxTurns && this.reservedTurns.size ? this.wait() : undefined; - } - reserveTurn(worker: ResearchWorker) { this.reservedTurns.add(worker.id); this.refreshPlanApproval(); } - settleTurn(worker: ResearchWorker) { if (this.reservedTurns.delete(worker.id)) { this.refreshPlanApproval(); this.wake(); } } - release(worker: ResearchWorker, action: CooperativeAction) { - if (action.kind === 'task') { - this.releaseTaskReservation(worker, action, true); - this.changed(); - } else this.interrupted(worker, action); - } - private reviewer(releasing?: TaskRecord, producerIds?: readonly string[]): ResearchWorker | undefined { - const preparing = new Set([...this.preparingTaskTypes.values()].map(item => item.workerId)); - for (const publication of this.proofPublications.values()) preparing.add(publication.workerId); - const peers = this.livePeers; - const independent = peers.filter(worker => !producerIds?.includes(worker.id)); - // Wait for an independent peer to finish its current work. A team without one can still review in a fresh session. - const available = (independent.length ? independent : peers).filter(worker => (!this.active.has(worker.id) || releasing?.assignment?.workerId === worker.id) && - !this.workerCoolingDown(worker.id) && - !preparing.has(worker.id) && - !(this.archive.review?.status === 'running' && this.archive.review.workerId === worker.id) && - !this.archive.tasks.some(node => node !== releasing && node.status === 'running' && node.assignment?.workerId === worker.id) && - !this.archive.statementReviews?.some(review => review.workerId === worker.id && ['translating', 'reviewing'].includes(review.status))); - const selected = this.input.modules.M5.reviewer(available, this.lead.id); - if (selected && (!available.includes(selected) || selected.role === 'lead')) throw new Error('math_review_assignment_invalid'); - return selected; - } - /** Assignments reserve concurrency immediately; charge only when a model turn actually starts. */ - started(worker: ResearchWorker, action: CooperativeAction): boolean { - if (this.failure || this.stopping || !this.liveWorkers.has(worker.id) || !this.liveWorkers.has(this.lead.id)) return false; - if (this.refreshFeasibilityAssignments()) this.changed(); - if (!this.current(action)) return false; - if (action.kind === 'task' && ordinaryAdvisoryTask(action.task) && this.finalReviewCommit()) return false; - if (action.kind === 'review' && this.fixedReviewScope && !this.fixedStatementReviewTasks()) return false; - if (action.kind === 'task' && action.assignment.workerId !== worker.id) throw new Error('math_task_assignment_invalid'); - if (action.kind === 'review' && this.archive.review?.workerId !== worker.id) throw new Error('math_review_assignment_invalid'); - const inboxBasis = action.kind === 'lead' ? this.pendingLeadInboxBases.get(action) : undefined; - if (inboxBasis) { this.archive.leadInboxBasis = inboxBasis; this.pendingLeadInboxBases.delete(action); } - if (isStatementAction(action) && this.archive.statementReviews?.find(item => item.id === action.reviewId)?.workerId !== worker.id) - throw new Error('math_statement_review_assignment_invalid'); - if (action.kind === 'task' && - assessTaskResponsibility(this.node(action.task.id), worker, this.responsibility).kind !== 'matches') return false; - const task = action.kind === 'task' ? action.task : isStatementAction(action) ? this.node(action.taskId).task : undefined; - if (task && this.synchronizationBlocked(task) || (action.kind === 'review' || action.kind === 'assemble') && - this.candidateSynchronizationBlocked()) return false; - const route = task && this.archive.groups?.find(record => record.group.id === taskGroup(task)); - const fixedStatement = isStatementAction(action) && this.fixedStatementReviewTasks()?.get(action.taskId) === action.taskDigest; - if (route && !fixedStatement && (route.group.status !== 'active' || route.turns >= (route.group.maxTurns ?? Infinity))) return false; - if (route && !fixedStatement) route.turns++; - if (action.kind === 'task') { - const node = this.node(action.task.id); - const sourceRepair = this.currentTaskSourceRepair(node); - if (sourceRepair?.pending) { sourceRepair.pending = false; sourceRepair.startedAttempt = node.attempts + 1; } - for (const record of this.archive.failedTaskInputs ?? []) if (this.pendingTaskRepair(node, record)) { - record.repair!.pending = false; record.repair!.startedAttempt = node.attempts + 1; - } - node.attempts++; - } - this.changed(); return true; - } - stopped(worker: ResearchWorker, error?: string) { - this.clearDispatchWait(worker, 'stopped'); - this.liveWorkers.delete(worker.id); - if (this.archive.review?.status === 'running' && this.archive.review.workerId === worker.id) { - this.archive.review.status = 'pending'; this.archive.review.workerId = undefined; - } - for (const review of this.archive.statementReviews ?? []) - if (review.workerId === worker.id && ['translating', 'reviewing'].includes(review.status)) resetStatementReview(review); - for (const node of this.archive.tasks.filter(node => node.status === 'running' && node.assignment?.workerId === worker.id)) { - this.moveTask(node, 'pending', 'interrupted'); node.feedback = error; - if (error) this.wakeLead('worker-stopped'); - } - this.changed(); - } -} diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts deleted file mode 100644 index c7782b8f..00000000 --- a/src/solver/cooperationCore.ts +++ /dev/null @@ -1,1146 +0,0 @@ -import { parseCooperationPlan } from './tasks'; -import fs from 'node:fs'; -import path from 'node:path'; -import crypto from 'node:crypto'; -import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; -import type { LeanStatementContext } from '../math/leanStatementContext'; -import { commitSolverSources, committedSource, git, solverSourceConstraints } from './problem'; -import type { DispatchWaitObservation, SolverRunState } from './archive'; -import { independentFeasibilityWorker, type ResearchWorker } from './modules/organization'; -import type { WorkerAccess } from './research'; -import type { SolverModules } from './modules'; -import { originalGoalTaskFocus, originalGoalFrontierSnapshot, plannedTaskDependencyIds, taskDependencyRecords } from './modules/search'; -import { type DeliveryRecord } from './deliveries'; -import { assignmentDeliveryReceipts, rejectedDeliveryReceipt, deliveryReceiptFeedback, type DeliveryReceipt } from './deliveryReceipts'; -import { proofReadyRecord, type ProofReadyRecord } from './proofReady'; -import type { ProofCheck } from './modules/evidence'; -import { createTaskSourceProjector, isAttributedTaskProof, ownedSourceDigest, TaskProofCache, type TaskProof } from './cooperativeProof'; -import { researchSourceTasks, scopedResearchSources } from './researchSources'; -import { isStatementAction, statementReviewSummary, type StatementReview } from './statementReview'; -import { type ProofReferences } from './proofReferences'; -import { attributeTaskReferences } from './taskReferenceAttribution'; -import { buildProofContinuation } from './progress'; -import { leadResearchInputs } from './contextCompiler'; -import type { ResearchDecision } from './researchDecisions'; -import { recordRouteBlockers, refreshRouteBlockers, validateBlockerProposals } from './routeControl'; -import { parseProofRoutes } from './proofRoutes'; -import { retireCooperativeRoutes, retiredCooperativeRoute } from './cooperationRoutes'; -import { createProofRoutePriorityIndex } from './routePriority'; -import { captureObligationSnapshot, diffObligationProgress } from './obligationProgress'; -import { reviewGoalPaths } from './goalPathReview'; -import { reviewProjectionDependencies } from './projectionDependencyReview'; -import type { GoalPathDecisions } from './goalPathDecisions'; -import type { PlanPatchBase } from './planPatch'; -import type { PlanToolContext } from './planTool'; -import { bindMathematicalGap, mathematicalGapVisible } from './mathematicalGaps'; -import { currentNextCheck, proposedNextChecks } from './nextChecks'; -import { proposedDefinitionContractChecks } from './definitionContractChecks'; -import { taskConnectionCheckCurrent } from './taskConnections'; -import { TaskTypePreflightCache } from './taskTypePreflight'; -import { currentCapacityExploration, plannedTaskRecords } from './capacityExploration'; -import { assignmentDeliveryFile, isFeasibilityReview, markTaskAcceptance, markTaskReferences, taskGroup, taskReferenceDependencies, type CooperativeTask, type TaskRecord, type CooperativeAction } from './tasks'; -import { digest, ReviewRecord, HumanEditRecord, CooperationState, TaskVersions, RETRY_DISPATCH, bounded, leadPlanPublicationTarget } from './cooperationShared'; -import { emptyLeadWakes, leadWakePending, reopenLeadWakes, requestLeadWake, type LeadWakeReason } from './leadWakes'; -import { MAX_INVALID_TASK_TRANSITIONS, setTaskStatus, type TaskStatus, type TaskTransitionCause } from './taskLifecycle'; -import { planApprovalStatus } from './planApproval'; -import { projectProofSearchRecord, proofSearchCheckForAssignment, proofSearchRecordForAssignment } from './proofSearchRecords'; -import { answerGoalProgress, GOAL_PROGRESS_REVIEW_MS, goalProgressTaskContext, observeGoalProgress, resetGoalProgressClock, - type GoalProgressDecision } from './goalProgress'; - -/** Shared cooperation state, scheduling primitives and the per-worker context projection. */ -/** Lead turns that may leave a presented stall unanswered before it is recorded as ignored. */ -export const MAX_UNANSWERED_GOAL_PATH_TURNS = 2; - -export abstract class CooperationCore { - protected readonly lead: ResearchWorker; - protected readonly archive: CooperationState; - protected presentedResearchInputs = new WeakMap(); - protected pendingSourceResearchDecisions = new WeakMap(); - protected presentedNextCheckOutcomes = new WeakMap(); - protected lastAssembly?: string; - private assemblyYieldedLeads = new WeakSet(); - private waiters = new Set<() => void>(); - protected dispatchRevision = 0; - protected reservedTurns = new Set(); - protected liveWorkers: Set; - protected checkedDeliveries = new WeakSet(); - protected readonly taskProofCache = new TaskProofCache(); - protected readonly rejectedIntegrationBatches = new Set(); - protected readonly taskTypePreflight = new TaskTypePreflightCache(); - protected preparingTaskTypes = new Map boolean; settled: Promise; - }>(); - /** Exact helper contracts already tried by the host tactic battery in this process. */ - protected readonly tacticBatteryAttempts = new Set(); - protected readonly libraryApplicationAttempts = new Set(); - /** Exact family contracts whose host assembly was already checked in this process. */ - protected readonly familyAssemblyAttempts = new Set(); - protected invalidTaskTypes = new Map(); - protected readonly preparedSources = new Map }>(); - protected checkedStatementReferences = new WeakSet(); - protected fixedReviewScope?: { review: ReviewRecord; commit: string; sourceDigest: string; environmentDigest: string; - tasksDigest: string; required: ReadonlyMap }; - protected statementContexts = new Map(); - protected preparingStatements?: Promise; - protected preparingStatementTasks = new Set(); - protected planSynchronization?: Promise; - protected planSynchronizations = new Set>(); - protected leadDeliveries = new Set>(); - protected active = new Map Promise; notify: (message: string, options?: { requireTurn?: boolean; mode?: 'advisory' }) => Promise; - requestReady?: () => Promise; requestAdvisoryCheckpoint?: (commit: string) => void; cancelled?: boolean }>(); - private freshProofReady = new WeakMap(); - protected notifications = new Set>(); - private deliveryReceiptNotifications = new WeakMap(); - protected pendingPulse?: Promise>>; - protected deliveryChecks = new Map>(); - protected proofPublications = new Map; pending: Promise; - }>(); - protected proofDeliveryChecks = new Set>(); - protected integrationQueue = Promise.resolve(); - protected integrationQueueDepth = 0; - protected leadEvidence = new WeakMap(); - private goalProgressTimer?: NodeJS.Timeout; - protected goalProgressBudget?: { maxTurns: number; deadline: number }; - protected presentedGoalProgress = new WeakMap(); - protected goalProgressDecisions = new WeakMap(); - /** The goal-path stall a Lead dispatch was shown: its digest, goals and the stalled inputs its review listed. */ - protected presentedGoalPathStalls = new WeakMap(); - /** goalPath answers accepted from a Lead dispatch's publications, in order. */ - protected goalPathDecisions = new WeakMap(); - /** Tasks on the routes of the currently stalled goals, recomputed with the stall itself. */ - protected goalPathStallTasks: ReadonlySet = new Set(); - protected checkingTaskInputs = new Map>(); - protected leanSourceDigests = new Map(); - protected timer?: NodeJS.Timeout; - protected stopping = false; - protected failure?: Error; - private pinned = new Set(); - // Implemented by later layers; listed here because this layer calls them. - protected abstract statementReviewAllowed(task: CooperativeTask, dispatch?: boolean): boolean; - protected abstract syncEditChecks(nodes: ReadonlyMap, versions: TaskVersions): void; - protected abstract refreshFeasibilityAssignments(): boolean; - protected abstract planningInputDigest(): string; - protected abstract refreshFailedTaskInputs(): boolean; - protected abstract refreshResearchCheckpoints(): void; - protected abstract suspendResearchDrafts(worker: ResearchWorker, taskId?: string): void; - protected abstract planVersion(): string; - protected abstract planPatchBase(): PlanPatchBase | undefined; - protected abstract canAssemble(commit: string): boolean; - protected abstract synchronizationPending(): boolean; - abstract contextState(action?: CooperativeAction, worker?: ResearchWorker, versions?: TaskVersions): CooperationState; - constructor(protected readonly input: { state: SolverRunState; workers: readonly ResearchWorker[]; - access: ReadonlyMap; signal: AbortSignal; timeoutMs?: number; taskText?: string; - /** Exact continuation checks verified in this process; conditional receipts keep their frozen inputs. */ - freshContinuationChecks?: readonly TaskProof[]; - continuousResearch?: boolean; - modelDispatchAllowed?: () => boolean; - goalProgressReviewMs?: number; - /** Only idle human approval time is excluded; initial planning and owner-requested revisions still execute. */ - onPlanApprovalWaiting?: (waiting: boolean) => void; - save: () => void; emit: (event: string, details?: Record) => void; - modules: SolverModules; exclusiveCheck: (check: () => Promise) => Promise }) { - this.lead = input.workers[0]; - this.archive = input.state.cooperation ??= { tasks: [] }; - resetGoalProgressClock(this.archive.goalProgress); - const legacyLeadWakes = !this.archive.leadWakes; - if (this.archive.leadWakes) reopenLeadWakes(this.archive.leadWakes); - else this.archive.leadWakes = emptyLeadWakes(); - this.archive.proofRoutes = parseProofRoutes(this.archive.proofRoutes, this.archive.tasks.map(node => node.task)); - const gateRetirements = input.state.portfolioExploration?.gate?.retiredRoutes ?? []; - let retirementChanged = false; - if (gateRetirements.length) { - const retired = new Map(gateRetirements.map(route => [route.routeId, route])); - for (const route of this.archive.retiredRoutes ?? []) retired.set(route.routeId, route); - retirementChanged = retired.size !== (this.archive.retiredRoutes?.length ?? 0); - this.archive.retiredRoutes = [...retired.values()]; - } - if (this.archive.retiredRoutes?.length) { - const retirement = retireCooperativeRoutes({ - tasks: this.archive.tasks.map(node => node.task), - groups: this.archive.groups?.map(route => route.group) ?? [], - proofRoutes: this.archive.proofRoutes, - }, this.archive); - if (retirement) { - this.archive.retiredRouteTasks = retirement.retiredRouteTasks; - retirementChanged ||= (this.archive.proofRoutes?.length ?? 0) !== (retirement.plan.proofRoutes?.length ?? 0); - this.archive.proofRoutes = retirement.plan.proofRoutes; - for (const route of this.archive.groups ?? []) { - if (route.group.status !== 'stopped' && this.archive.retiredRoutes.some(record => record.routeId === route.group.id)) { - route.group = { ...route.group, status: 'stopped' }; - retirementChanged = true; - } - } - if (this.stopRetiredRouteTasks() || retirementChanged) - this.archive.planVersion = this.planVersion(); - } - } - this.syncProofRoutes(); - if (!this.archive.canonicalCommit) { - this.archive.canonicalCommit = git(this.lead.worktree, ['rev-parse', 'HEAD']); - this.archive.leadSeedCommit ??= this.archive.canonicalCommit; - } - // Continuation seeding and this cooperation instance share the proof objects. - // Register unconditional acceptance only for exact objects on integrated tasks; - // conditional receipts go through the ordinary check identity path on restore. This - // keeps the restore path able to reuse a fresh receipt without trusting a - // deserialized or otherwise unrelated proof value. - for (const proof of input.freshContinuationChecks ?? []) { - const node = this.archive.tasks.find(node => node.status === 'integrated' && node.integratedCheck === proof); - if (!node || !proof.passed || proof.conditions?.length || proof.taskDigest !== digest(node.task) || - proof.commit !== this.archive.canonicalCommit || !isAttributedTaskProof(proof) || - proof.references && proof.references.environmentDigest !== input.state.environmentDigest) continue; - if (proof.references) { - proof.references.tasks = attributeTaskReferences(proof.references, this.archive.tasks); - markTaskReferences(proof); - } - this.checkedDeliveries.add(proof); markTaskAcceptance(proof); - } - this.liveWorkers = new Set(input.workers.map(worker => worker.id)); - if (!this.archive.tasks.length) { - // Without a graph every peer is idle; the first plan is always owed. - if (!leadWakePending(this.archive.leadWakes)) this.wakeLead('initial-plan'); - } else if (legacyLeadWakes) { - // Older states saved no wake-ups: infer the unanswered decision once from its durable inputs. - const researchInputs = leadResearchInputs(this.archive.deliveries ?? [], - new Map(this.archive.tasks.map(node => [node.task.id, node])), this.archive.researchDecisions).length > 0; - if (this.archive.error || (researchInputs || this.archive.tasks.some(node => node.status === 'blocked')) && - this.archive.lastLeadInputDigest !== this.planningInputDigest()) this.wakeLead('restored-legacy-state'); - } - } - /** Ask the Lead for a decision; the request is saved with the state change that caused it. */ - protected wakeLead(reason: LeadWakeReason) { requestLeadWake(this.archive.leadWakes!, reason); } - /** One timer for the next goal review. Busy worker labels and offline time never arm it. */ - protected refreshGoalProgress(snapshot = this.archive.progressSnapshot) { - clearTimeout(this.goalProgressTimer); this.goalProgressTimer = undefined; - const now = Date.now(), budget = this.goalProgressBudget; - const enabled = !this.stopping && !this.failure && !this.input.signal.aborted && !this.planApprovalPending() && - this.input.modelDispatchAllowed?.() !== false && (!budget || now < budget.deadline && this.input.state.turns < budget.maxTurns); - const active = new Set(); - if (enabled) { - for (const [workerId, work] of this.active) if (work.action.kind === 'task' && !work.cancelled && - this.liveWorkers.has(workerId) && this.current(work.action) && - this.input.state.workers?.find(worker => worker.id === workerId)?.recovery?.phase !== 'cooling-down') - active.add(work.action.task.id); - for (const node of this.preparingTaskTypes.keys()) active.add(node.task.id); - for (const node of this.archive.tasks) if (node.assignment && this.deliveryChecks.has(node.assignment.workerId)) active.add(node.task.id); - for (const publication of this.proofPublications.values()) if (this.current(publication.action)) active.add(publication.action.task.id); - } - const observation = observeGoalProgress(this.archive.goalProgress, { - problemReceiptDigest: this.input.state.problem.receiptDigest, targets: this.input.state.problem.targets, - tasks: this.archive.tasks, snapshot: snapshot ?? captureObligationSnapshot(this.archive.tasks, { - groups: this.archive.groups, environmentDigest: this.input.state.environmentDigest, proofRoutes: this.archive.proofRoutes }), - nextChecks: this.archive.nextChecks?.filter(record => currentNextCheck(record, this.archive, this.explorationIdentity)), - proofRoutes: this.archive.proofRoutes, groups: this.archive.groups, activeTaskIds: active, now, intervalMs: this.input.goalProgressReviewMs }); - this.archive.goalProgress = observation.state; - if (observation.resumed.length) this.input.emit('goal_progress_resumed', { goalIds: observation.resumed, acceptance: 'not-assessed' }); - if (observation.requested) { - this.wakeLead('goal-progress-review'); - this.input.emit('goal_progress_review_requested', { ...observation.state.pending, acceptance: 'not-assessed' }); - } - const retryAt = observation.state.pending?.retryAt; - const retryDelay = retryAt !== undefined && retryAt > now ? retryAt - now : undefined; - const delay = observation.nextDelayMs === undefined ? retryDelay : Math.min(observation.nextDelayMs, retryDelay ?? Infinity); - if (enabled && delay !== undefined) { - this.goalProgressTimer = setTimeout(() => { this.goalProgressTimer = undefined; this.changed(); }, - Math.min(delay, Math.max(1, (budget?.deadline ?? Infinity) - now))); - this.goalProgressTimer.unref(); - } - return observation.requested; - } - protected presentGoalProgressReview(action: CooperativeAction) { - const pending = this.archive.goalProgress?.pending; - if (!pending) return; - this.presentedGoalProgress.set(action, pending.id); - pending.retryAt = Date.now() + (this.input.goalProgressReviewMs ?? GOAL_PROGRESS_REVIEW_MS); - this.input.emit('goal_progress_review_dispatched', { id: pending.id, goalIds: pending.goalIds }); - this.refreshGoalProgress(); - } - protected answerGoalProgressReview(action: CooperativeAction) { - const decision = this.goalProgressDecisions.get(action), state = this.archive.goalProgress; - if (!decision || !state || this.presentedGoalProgress.get(action) !== decision.id || !answerGoalProgress(state, decision)) return; - this.input.emit('goal_progress_review_answered', { ...decision, acceptance: 'not-assessed' }); - for (const [workerId, active] of this.active) if (active.action.kind === 'task' && !active.cancelled && this.current(active.action)) { - const task = active.action.task, message = goalProgressTaskContext(state, task); - if (!message || !decision.nextChecks.some(check => check.targetTaskId === task.id)) continue; - const pending = active.notify(message).catch(() => { - this.input.emit('notification_deferred', { workerId, reviewId: decision.id }); - }); - this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); - } - this.refreshGoalProgress(); - } - /** - * Record whether some original goal has no frontier input that can run. The condition is recomputed from durable - * state, so it is not a saved wake-up: a new stall stays owed to the Lead until a turn answers it (answerGoalPathStall) - * or it is recorded as ignored, and an identical stall is not asked again. Busy workers elsewhere do not answer it. An applied human edit is itself the - * planning decision for a stall it creates, unless a goal of that stall was already owed a Lead turn before it. - */ - protected refreshGoalPathStall(edit?: HumanEditRecord) { - const review = reviewGoalPaths(this.archive.tasks, { groups: this.archive.groups, proofRoutes: this.archive.proofRoutes, - environmentDigest: this.input.state.environmentDigest, candidates: false }); - this.goalPathStallTasks = new Set(review.stalledPathTaskIds); - const previous = this.archive.goalPathStall; - const owed = previous?.active && previous.answeredAt === undefined ? previous.goalIds : []; - const decided = edit?.status === 'applied' && !review.stalledGoalIds.some(goalId => owed.includes(goalId)); - if (!review.stallDigest) { - if (!previous?.active) return false; - previous.active = false; return true; - } - if (previous?.digest === review.stallDigest) { - if (previous.active) return false; - previous.active = true; - if (decided) previous.answeredAt ??= Date.now(); - return true; - } - this.archive.goalPathStall = { digest: review.stallDigest, active: true, at: Date.now(), - goalIds: review.stalledGoalIds, taskIds: review.stalledTaskIds.slice(0, 16), ...(decided ? { answeredAt: Date.now() } : {}) }; - this.input.emit('goal_path_stalled', { digest: review.stallDigest, goalIds: review.stalledGoalIds, taskIds: review.stalledTaskIds, - ...(decided ? { answeredByEdit: edit!.id } : {}) }); - return true; - } - protected unansweredGoalPathStall() { - const stall = this.archive.goalPathStall; - return stall?.active && stall.answeredAt === undefined ? stall.digest : undefined; - } - /** The review a Lead is shown, with candidate ids: the basis for its goalPath answer. */ - protected goalPathReview(candidates = true) { - const options = { groups: this.archive.groups, proofRoutes: this.archive.proofRoutes, - environmentDigest: this.input.state.environmentDigest }; - const review = reviewGoalPaths(this.archive.tasks, { ...options, candidates: false }); - if (!candidates || !review.stalledTaskIds.length) return review; - const projectionConnections = reviewProjectionDependencies({ problem: this.input.state.problem, - worktree: this.lead.worktree, canonicalCommit: this.archive.canonicalCommit, - environmentDigest: this.input.state.environmentDigest, tasks: this.archive.tasks, - consumerTaskIds: review.stalledTaskIds, - retainedGoals: task => this.dependencies(task).filter(node => node.task.kind === 'goal' && node.status === 'integrated') - .map(node => node.task.theoremName!) }); - return reviewGoalPaths(this.archive.tasks, { ...options, projectionConnections }); - } - /** What a Lead dispatch is shown of the current stall: the stalled inputs listed in its bounded review. */ - protected presentedGoalPathStall() { - const stall = this.archive.goalPathStall; - if (!stall?.active) return; - const review = this.goalPathReview(false); - return { digest: stall.digest, goalIds: stall.goalIds, - taskIds: [...new Set(review.goals.filter(goal => goal.stalled).flatMap(goal => goal.frontier.map(item => item.taskId)))] }; - } - /** - * A Lead turn that was shown the stalled goals answers the stall its decision leaves on them when that stall differs - * from the one it was shown (a re-pause, a revision, a reopened route), or when its goalPath adopted or declined every - * presented input. A settled turn that did neither leaves it owed; after MAX_UNANSWERED_GOAL_PATH_TURNS such turns it - * is recorded as ignored and no longer wakes the Lead. An unfinished (checkpointed) turn answers it by having seen it, - * as before: its saved pause, not the stall, decides when the Lead continues. A goal that newly stalls stays owed. - */ - protected answerGoalPathStall(action: CooperativeAction, settled = true) { - this.refreshGoalPathStall(); - const stall = this.archive.goalPathStall, presented = this.presentedGoalPathStalls.get(action); - if (!stall?.active || !presented || stall.answeredAt !== undefined || !stall.goalIds.every(goalId => presented.goalIds.includes(goalId))) - return; - const decisions = this.goalPathDecisions.get(action), now = Date.now(); - if (decisions?.declined.length) stall.declined = [...(stall.declined ?? []).filter(item => - !decisions.declined.some(entry => entry.taskId === item.taskId)), - ...decisions.declined.map(item => ({ ...item, at: now }))].slice(-16); - const covered = new Set([...decisions?.adopted.map(item => item.taskId) ?? [], ...stall.declined?.map(item => item.taskId) ?? []]); - if (!settled || stall.digest !== presented.digest || presented.taskIds.every(taskId => covered.has(taskId))) { - stall.answeredAt = now; return; - } - stall.unanswered = (stall.unanswered ?? 0) + 1; - const missing = presented.taskIds.filter(taskId => !covered.has(taskId)); - if (stall.unanswered < MAX_UNANSWERED_GOAL_PATH_TURNS) { - this.input.emit('goal_path_stall_unanswered', { digest: stall.digest, taskIds: missing, unanswered: stall.unanswered }); - return; - } - stall.answeredAt = stall.ignoredAt = now; - this.input.emit('goal_path_stall_ignored', { digest: stall.digest, goalIds: stall.goalIds, taskIds: missing, unanswered: stall.unanswered }); - } - /** Keep a Lead dispatch's accepted goalPath answers until its turn settles. */ - protected recordGoalPathDecisions(action: CooperativeAction, decisions: GoalPathDecisions) { - const previous = this.goalPathDecisions.get(action); - this.goalPathDecisions.set(action, { adopted: [...previous?.adopted ?? [], ...decisions.adopted], - declined: [...(previous?.declined ?? []).filter(item => !decisions.declined.some(entry => entry.taskId === item.taskId)), - ...decisions.declined] }); - if (decisions.adopted.length || decisions.declined.length) - this.input.emit('goal_path_decided', { adopted: decisions.adopted.map(item => item.id), - declined: decisions.declined.map(item => item.taskId) }); - } - /** The only live task status write. Staged validation copies are checked but never recorded. */ - protected moveTask(node: TaskRecord, to: TaskStatus, cause: TaskTransitionCause) { - const from = node.status; - if (setTaskStatus(node, to, cause) || !this.archive.tasks.includes(node)) return; - const record = { taskId: node.task.id, from, to, cause, at: Date.now() }; - this.archive.invalidTaskTransitions = [...this.archive.invalidTaskTransitions ?? [], record].slice(-MAX_INVALID_TASK_TRANSITIONS); - this.input.emit('task_transition_invalid', record); - } - protected get livePeers() { return this.input.workers.filter(worker => worker.id !== this.lead.id && this.liveWorkers.has(worker.id)); } - /** A stopped worker never returns in this process; a restart restores every plan reservation. */ - protected get stoppedWorkers(): ReadonlySet { - return new Set(this.input.workers.filter(worker => !this.liveWorkers.has(worker.id)).map(worker => worker.id)); - } - protected get responsibility() { - return { tasks: this.archive.tasks, groups: this.archive.groups, stopped: this.stoppedWorkers }; - } - protected workerCoolingDown(workerId: string) { - return this.input.state.workers?.some(worker => worker.id === workerId && worker.recovery?.phase === 'cooling-down') === true; - } - protected get allocationPeers() { - const occupied = new Set([...this.active].filter(([, active]) => active.action.kind !== 'task').map(([id]) => id)); - if (this.archive.review?.status === 'running' && this.archive.review.workerId) occupied.add(this.archive.review.workerId); - for (const review of this.archive.statementReviews ?? []) if (review.workerId && ['translating', 'reviewing'].includes(review.status)) - occupied.add(review.workerId); - return this.livePeers.filter(worker => !occupied.has(worker.id) && !this.workerCoolingDown(worker.id)); - } - protected get explorationIdentity() { - return { environmentDigest: this.input.state.environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest }; - } - /** The CAS plan belongs to Lead; host advisory capacity is a separate execution overlay. */ - protected plannedTasks() { return plannedTaskRecords(this.archive.tasks); } - /** Turn one scoped mathematical question into ordinary feasibility work and retain its complete lifecycle. */ - protected refreshNextChecks() { - const identity = { problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest }; - const now = Date.now(); - for (const proposed of [...proposedNextChecks(this.archive, identity, now, path.dirname(this.lead.worktree)), - ...proposedDefinitionContractChecks(this.archive, identity, now)]) { - const previous = this.archive.nextChecks?.find(record => record.id === proposed.record.id); - if (previous) { - if (previous.status !== 'stale' || previous.outcome) continue; - const nodeIndex = this.archive.tasks.findIndex(item => item.nextCheckId === previous.id); - if (previous.origin === 'definition-contract') { - // An unfinished definition check can resume when the same question becomes relevant again. - if (!currentNextCheck({ ...previous, status: 'pending' }, this.archive, identity)) continue; - previous.status = 'pending'; - const node = this.archive.tasks[nodeIndex]; - if (node) { node.task = { ...node.task, status: 'active' }; this.moveTask(node, 'pending', 'reopened'); } - else this.archive.tasks.push(proposed.node); - } else { - // A republished gap needs a current delivery and a fresh assignment. - const { record, node } = proposed; - if (record.gapDeliveryId === previous.gapDeliveryId || !currentNextCheck(record, this.archive, identity)) continue; - Object.assign(previous, { status: 'pending', gapDeliveryId: record.gapDeliveryId, scope: record.scope, - check: record.check, proofSearchSeed: record.proofSearchSeed }); - if (nodeIndex < 0) this.archive.tasks.push(node); - else this.archive.tasks[nodeIndex] = { ...node, attempts: this.archive.tasks[nodeIndex].attempts }; - } - this.input.emit('next_check_resumed', { checkId: previous.id, taskId: previous.taskId }); - continue; - } - // A model task cannot take ownership of the host's deterministic check id. - if (this.archive.tasks.some(node => node.task.id === proposed.node.task.id)) continue; - (this.archive.nextChecks ??= []).push(proposed.record); this.archive.tasks.push(proposed.node); - this.input.emit('next_check_scheduled', { checkId: proposed.record.id, taskId: proposed.node.task.id, - target: proposed.record.scope.target, consumer: proposed.record.scope.consumer, - ...(proposed.record.origin ? { origin: proposed.record.origin } : {}) }); - } - for (const record of this.archive.nextChecks ?? []) { - const node = this.archive.tasks.find(item => item.nextCheckId === record.id); - if (record.status !== 'stale' && !currentNextCheck(record, this.archive, identity)) { - record.status = 'stale'; - if (node) { node.task = { ...node.task, status: 'stopped' }; this.moveTask(node, 'blocked', 'expired'); } - this.input.emit('next_check_expired', { checkId: record.id, taskId: record.taskId }); - } - if (record.status === 'pending') { - const outcome = this.archive.deliveries?.find(delivery => delivery.checkOutcome?.checkId === record.id && - delivery.kind === 'research' && delivery.status !== 'superseded' && delivery.taskId === record.taskId && - delivery.taskDigest === record.taskDigest && canonicalMathJson(delivery.checkOutcomeScope) === canonicalMathJson(record.scope)); - if (outcome?.checkOutcome) { - record.outcome = { ...outcome.checkOutcome, deliveryId: outcome.id, ...(outcome.commit ? { commit: outcome.commit } : {}) }; - record.status = 'awaiting-decision'; - if (node && node.status !== 'completed') this.moveTask(node, 'completed', 'research-completed'); - this.wakeLead('research-finding'); - this.input.emit('next_check_outcome', { checkId: record.id, outcomeDeliveryId: outcome.id, conclusion: outcome.checkOutcome.conclusion }); - } - } - // Older continuation seeds could leave a settled check's task in the work queue. - if (node && (record.status === 'awaiting-decision' || record.status === 'decided') && - (node.status === 'pending' || node.status === 'running')) - this.moveTask(node, 'completed', 'research-completed'); - if (record.status !== 'pending' && node?.assignment) { - const active = this.active.get(node.assignment.workerId); - if (active?.action.kind === 'task' && active.action.assignment === node.assignment && !active.cancelled) { - active.cancelled = true; void active.interrupt().catch(() => {}); - } - } - } - } - protected includeNextCheckTasks(plan: ReturnType) { - const hostNodes = this.archive.tasks.filter(node => node.nextCheckId); - const hostIds = new Set(hostNodes.map(node => node.task.id)); - for (const task of plan.tasks) { - const host = hostNodes.find(node => node.task.id === task.id); - if (host && digest(task) !== digest(host.task)) throw new Error('math_plan_host_next_check_changed'); - if (!host && task.dependsOn.some(id => hostIds.has(id))) - throw new Error('math_plan_host_next_check_dependency: adopt a separate typed lemma; advisory checks are not proof inputs.'); - } - plan.tasks = plan.tasks.filter(task => !hostIds.has(task.id)); - const proposed = this.nextCheckPlanView(plan); - for (const node of hostNodes) { - const record = this.archive.nextChecks?.find(item => item.id === node.nextCheckId); - if (record && currentNextCheck(record, proposed, this.explorationIdentity) && plan.groups.some(group => group.id === taskGroup(node.task))) - plan.tasks.push(node.task); - } - } - protected nextCheckPlanView(plan: ReturnType) { - const previousGroups = new Map(this.archive.groups?.map(record => [record.group.id, record])); - return { ...this.archive, tasks: this.capacityPlanView(plan), proofRoutes: plan.proofRoutes, - groups: plan.groups.map(group => ({ group, turns: previousGroups.get(group.id)?.turns ?? 0 })) }; - } - protected refreshCapacityExplorations() { - let changed = false; - for (const node of this.archive.tasks) { - if (!node.capacityExploration || (node.task.status ?? 'active') !== 'active' || - currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity)) continue; - node.task = { ...node.task, status: 'stopped' }; - this.moveTask(node, 'blocked', 'expired'); node.feedback = 'math_capacity_exploration_expired: Its frozen target or mathematical inputs are no longer current.'; - for (const record of this.archive.deliveries ?? []) if (record.taskId === node.task.id) record.status = 'superseded'; - const active = node.assignment && this.active.get(node.assignment.workerId); - if (active?.action.kind === 'task' && active.action.assignment === node.assignment && !active.cancelled) { - active.cancelled = true; void active.interrupt().catch(() => {}); - } - this.input.emit('capacity_exploration_expired', { taskId: node.task.id, - targetTaskId: node.capacityExploration.targetTaskId, inputDigest: node.capacityExploration.inputDigest }); - changed = true; - } - return changed; - } - protected capacityPlanView(plan: ReturnType): TaskRecord[] { - const existing = new Map(this.archive.tasks.map(node => [node.task.id, node])); - return plan.tasks.map(task => { - const previous = existing.get(task.id); - return { ...(previous && digest(previous.task) === digest(task) ? previous : { status: 'pending' as const, attempts: 0 }), - task, alternativeRoutes: plan.proofRoutes?.filter(route => route.targetTaskId === task.id) }; - }); - } - protected includeCapacityExplorations(plan: ReturnType) { - const existing = new Map(this.archive.tasks.map(node => [node.task.id, node])); - const hostIds = new Set(this.archive.tasks.filter(node => node.capacityExploration).map(node => node.task.id)); - for (const task of plan.tasks) { - const previous = existing.get(task.id); - if (previous?.capacityExploration) { - if (digest(task) !== digest(previous.task) || task.ownerId !== previous.capacityExploration.workerId) - throw new Error('math_plan_host_exploration_changed: create a separate typed task for an adopted interface.'); - } else if (task.dependsOn.some(id => hostIds.has(id))) - throw new Error('math_plan_host_exploration_dependency: use the actual typed inputs, not advisory exploration IDs.'); - } - const proposed = this.capacityPlanView(plan); - plan.tasks = plan.tasks.filter(task => { - const previous = existing.get(task.id); - return !previous?.capacityExploration || digest(previous.task) !== digest(task) || - currentCapacityExploration({ ...previous, task }, proposed, this.explorationIdentity); - }); - const ids = new Set(plan.tasks.map(task => task.id)); - for (const node of this.archive.tasks) if (node.capacityExploration && !ids.has(node.task.id) && - plan.groups.some(group => group.id === taskGroup(node.task)) && - currentCapacityExploration(node, proposed, this.explorationIdentity)) { - plan.tasks.push(node.task); ids.add(node.task.id); - } - return plan; - } - protected syncProofRoutes() { - for (const node of this.archive.tasks) node.alternativeRoutes = this.archive.proofRoutes?.filter(route => route.targetTaskId === node.task.id); - } - protected supersedeStatementReview(review: StatementReview) { - review.status = 'superseded'; - for (const record of this.archive.deliveries ?? []) if (record.statementReviewId === review.id) record.status = 'superseded'; - } - protected stopRetiredRouteTasks() { - if (!this.archive.retiredRoutes?.length) return false; - let changed = false; - for (const node of this.archive.tasks) { - if (node.status === 'integrated') continue; - const route = retiredCooperativeRoute(node.task, this.archive); - if (!route) { - if (!node.assignment?.routeId || !this.archive.retiredRoutes.some(item => item.routeId === node.assignment?.routeId)) continue; - if (node.status === 'running') this.moveTask(node, 'pending', 'interrupted'); - node.assignment = undefined; - changed = true; - continue; - } - const feedback = `math_route_retired: ${route.routeId}: ${route.reason}`; - if (node.status === 'blocked' && node.task.status === 'stopped' && node.feedback === feedback && !node.assignment) continue; - node.task = { ...node.task, status: 'stopped' }; - this.moveTask(node, 'blocked', 'route-retired'); - node.assignment = undefined; - node.pendingValidation = undefined; - node.feedback = feedback; - changed = true; - } - for (const review of this.archive.statementReviews ?? []) { - if (review.status === 'superseded') continue; - const node = this.node(review.taskId); - if (node && node.status !== 'integrated' && retiredCooperativeRoute(node.task, this.archive)) { - this.supersedeStatementReview(review); - changed = true; - } - } - return changed; - } - protected actionRouteRetired(action: Extract) { - return Boolean(retiredCooperativeRoute(action.task, this.archive) || - this.archive.retiredRoutes?.some(route => route.routeId === action.assignment.routeId)); - } - protected recordDispatchWait(worker: ResearchWorker, - observation: Omit) { - const record = this.input.state.workers?.find(item => item.id === worker.id); - if (!record) return; - const basis = { ...observation, planVersion: this.archive.planVersion ?? this.planVersion() }; - const previous = record.scheduling?.wait; - if (previous) { - const { observedAt: _at, endedAt, ...prior } = previous; - if (endedAt === undefined && canonicalMathJson(prior) === canonicalMathJson(basis)) return; - this.clearDispatchWait(worker, 'changed'); - } - const wait: DispatchWaitObservation = { ...basis, observedAt: Date.now() }; - record.scheduling ??= { status: 'idle', since: wait.observedAt }; - record.scheduling.wait = wait; - this.input.emit('dispatch_wait', { workerId: worker.id, ...wait }); - this.changed(); - } - protected clearDispatchWait(worker: ResearchWorker, reason: 'changed' | 'selected' | 'stopped') { - const scheduling = this.input.state.workers?.find(item => item.id === worker.id)?.scheduling; - if (!scheduling?.wait) return; - const wait = scheduling.wait; - if (reason !== 'stopped') delete scheduling.wait; - if (wait.endedAt !== undefined) return; - wait.endedAt = Date.now(); - this.input.emit('dispatch_wait_ended', { workerId: worker.id, observedAt: wait.observedAt, - endedAt: wait.endedAt, planVersion: wait.planVersion, stage: wait.stage, reason }); - } - protected changed(edit?: HumanEditRecord) { - this.refreshNextChecks(); - this.refreshCapacityExplorations(); - this.refreshFeasibilityAssignments(); - this.refreshResearchCheckpoints(); - this.stopRetiredRouteTasks(); - for (const blocker of refreshRouteBlockers(this.archive.blockers ?? [], this.archive.tasks, - this.input.state.environmentDigest, this.input.state.problem.receiptDigest)) { - this.wakeLead('route-reopened'); - this.input.emit('route_reopened', { blockerId: blocker.id, taskId: blocker.taskId, reason: blocker.reopenedReason }); - } - this.refreshFailedTaskInputs(); - this.refreshGoalPathStall(edit); - const snapshot = captureObligationSnapshot(this.archive.tasks, { groups: this.archive.groups, - environmentDigest: this.input.state.environmentDigest, proofRoutes: this.archive.proofRoutes, blockers: this.archive.blockers }); - const progress = diffObligationProgress(this.archive.progressSnapshot, snapshot); - this.archive.progressSnapshot = snapshot; - if (progress) { - this.archive.progressReceipts = [...(this.archive.progressReceipts ?? []), progress].slice(-64); - this.input.emit('obligation_progress', { receipt: progress }); - } - this.refreshGoalProgress(snapshot); - const nodes = new Map(this.archive.tasks.map(node => [node.task.id, node])); - const versions = this.taskVersions(); - const busy = new Map>(); - const occupy = (groupId: string, workerId?: string) => { - const owners = busy.get(groupId) ?? new Set(); owners.add(workerId); busy.set(groupId, owners); - }; - for (const node of this.archive.tasks) if (node.status === 'running') occupy(taskGroup(node.task), node.assignment?.workerId); - for (const [id, active] of this.active) if (active.action.kind === 'task' && - !this.actionRouteRetired(active.action)) occupy(taskGroup(active.action.task), id); - for (const publication of this.proofPublications.values()) if (!this.actionRouteRetired(publication.action)) - occupy(taskGroup(publication.action.task), publication.workerId); - for (const preparation of this.preparingTaskTypes.values()) occupy(preparation.groupId, preparation.workerId); - for (const review of this.archive.statementReviews ?? []) { - const node = nodes.get(review.taskId); - if (node && ['translating', 'reviewing'].includes(review.status)) occupy(taskGroup(node.task), review.workerId); - } - for (const route of this.archive.groups ?? []) route.busy = busy.get(route.group.id)?.size ?? 0; - this.archive.planVersion ??= this.planVersion(); - if (edit?.status === 'applied') edit.planVersion = this.archive.planVersion; - this.refreshPlanApproval(); - this.syncEditChecks(nodes, versions); - // A new inbox can supersede an assessment-only Lead without publishing a plan. - // Reclaim its running turn as well as rejecting stale decisions. - const lead = this.active.get(this.lead.id); - if (lead?.action.kind === 'lead' && !lead.cancelled && !this.current(lead.action)) { - lead.cancelled = true; void lead.interrupt().catch(() => {}); - } - const agents = this.input.workers.map(peer => { - const active = this.active.get(peer.id); - const publication = [...this.proofPublications.values()].find(item => item.workerId === peer.id); - const work = active?.action ?? publication?.action; - const preparation = [...this.preparingTaskTypes].find(([, item]) => item.workerId === peer.id)?.[0]; - const status = !this.liveWorkers.has(peer.id) ? 'stopped' as const - : active && (active.cancelled || !this.current(active.action)) ? 'stopping' as const - : work ? 'working' as const : preparation ? 'preparing' as const : 'idle' as const; - const action = work?.kind ?? (preparation ? 'task' : undefined); - const taskId = work?.kind === 'task' ? work.task.id : preparation?.task.id; - const record = this.input.state.workers?.find(worker => worker.id === peer.id); - if (record) { - if ((work || preparation) && record.scheduling?.wait?.stage !== 'integration-queue') this.clearDispatchWait(peer, 'selected'); - const previous = record.scheduling; - const same = previous?.status === status && previous.action === action && previous.taskId === taskId; - record.scheduling = { status, action, taskId, since: same ? previous.since : Date.now(), wait: previous?.wait }; - } - return { id: peer.id, role: work && (work.kind === 'review' || isStatementAction(work) || - work.kind === 'task' && isFeasibilityReview(work.task)) ? 'reviewer' : peer.role, - status, - work: work && { kind: work.kind, taskId: work.kind === 'task' ? work.task.id : undefined, - version: work.kind === 'task' ? work.assignment.taskDigest : work.seedCommit } }; - }); - this.input.save(); - for (const worker of this.input.workers) { - const action = this.active.get(worker.id)?.action; - const scoped = this.contextState(action, worker, versions); - const searchAssignment = action?.kind === 'task' ? this.proofSearchAssignment(action) : undefined; - const search = searchAssignment ? projectProofSearchRecord({ - ...searchAssignment, - projectRoot: path.join(worker.worktree, this.input.state.problem.projectRelative), - runDirectory: path.dirname(this.lead.worktree), - }) : undefined; - const visible = new Set(scoped.tasks.map(node => node.task.id)); - const requiredCheckDeliveries = new Set((scoped.nextChecks ?? []).filter(record => - record.status === 'pending' || record.status === 'awaiting-decision').flatMap(record => - [...(record.gapDeliveryId ? [record.gapDeliveryId] : []), ...(record.outcome ? [record.outcome.deliveryId] : [])])); - const recentDeliveries = new Set((scoped.deliveries ?? []).slice(-16).map(record => record.id)); - const deliveries = (scoped.deliveries ?? []).filter(record => recentDeliveries.has(record.id) || requiredCheckDeliveries.has(record.id)); - writeMathJsonDurable(path.join(worker.worktree, 'COOPERATION.json'), { - planVersion: this.archive.planVersion, - ...(worker.id === this.lead.id ? { planTool: { - problem: { targets: this.input.state.problem.targets, ownedFiles: this.input.state.problem.ownedFiles, - frozenFiles: this.input.state.problem.frozenFiles, declarations: this.input.state.problem.declarations }, - base: this.planPatchBase(), goalPath: scoped.goalPathReview, publication: this.openLeadPublicationTarget(action), - } satisfies PlanToolContext } : {}), - ...(scoped.landedHelpers?.length ? { landedHelpers: scoped.landedHelpers } : {}), - ...(scoped.retiredRoutes?.length ? { retiredRoutes: scoped.retiredRoutes } : {}), - edits: (this.archive.edits ?? []).slice(-16), - agents, - dispatchWaits: (this.input.state.workers ?? []).flatMap(peer => { - const wait = peer.scheduling?.wait; - if (!wait) return []; - const candidates = wait.candidates.filter(item => visible.has(item.taskId)); - return [{ workerId: peer.id, ...wait, candidates, - omittedCandidates: wait.omittedCandidates + wait.candidates.length - candidates.length }]; - }), - ...(worker.id === this.lead.id && scoped.error ? { error: scoped.error, planRejection: scoped.planRejection } : {}), - ...(scoped.planPublicationRejection ? { planPublicationRejection: scoped.planPublicationRejection } : {}), - ...(scoped.contextCheckpointRejection ? { contextCheckpointRejection: scoped.contextCheckpointRejection } : {}), - capacityExplorations: scoped.tasks.filter(node => node.capacityExploration).map(node => ({ - taskId: node.task.id, status: node.status, ...node.capacityExploration })), - parallelQuestions: scoped.parallelQuestions ?? [], - tasks: scoped.tasks, - failedTaskInputs: scoped.failedTaskInputs ?? [], - peers: this.archive.tasks.map(node => ({ id: node.task.id, taskDigest: digest(node.task), - objectiveDigest: mathDigest(node.task.objective), groupId: taskGroup(node.task), kind: node.task.kind, - status: node.status, owner: node.assignment?.workerId ?? node.task.ownerId, dependsOn: node.task.dependsOn, - ...(visible.has(node.task.id) ? { objective: node.task.objective, feedback: node.feedback, - canonicalProbe: node.assignment?.canonicalProbe, - actualReferences: (node.integratedCheck ?? node.proof)?.references } : {}) })), - deliveries: deliveries.map(({ evidence: _evidence, researchRecord: _researchRecord, ...record }) => record), - ...(scoped.humanGuidance?.length ? { humanGuidance: scoped.humanGuidance } : {}), - deliveryReceipts: scoped.deliveryReceipts ?? [], - proofReadyRecords: scoped.proofReadyRecords ?? [], - proofSearchRecords: search ? { [search.taskId]: search } : {}, - mathematicalGaps: scoped.mathematicalGaps ?? [], - nextChecks: scoped.nextChecks ?? [], - ...(action?.kind === 'task' ? { researchDelivery: { assignment: action.assignment, - problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest, - projectRelative: this.input.state.problem.projectRelative, - ownedFiles: this.input.state.problem.ownedFiles.filter(file => file.endsWith('.lean') && - !Object.hasOwn(this.input.state.problem.frozenFiles ?? {}, file)) } } : {}), - blockers: scoped.blockers ?? [], - proofRoutes: scoped.proofRoutes ?? [], - routePriority: createProofRoutePriorityIndex(scoped.tasks, { groups: scoped.groups, - environmentDigest: this.input.state.environmentDigest, proofRoutes: scoped.proofRoutes }), - frontierFocus: originalGoalFrontierSnapshot(originalGoalTaskFocus(scoped.tasks, scoped.groups, this.input.state.environmentDigest)), - mathematicalChanges: scoped.progressReceipts?.slice(-16) ?? [], - ...(scoped.goalProgress ? { goalProgress: scoped.goalProgress } : {}), - continuation: buildProofContinuation(scoped.tasks, { groups: scoped.groups, environmentDigest: this.input.state.environmentDigest, - proofRoutes: scoped.proofRoutes }), - statements: (scoped.statementReviews ?? []).map(statementReviewSummary), - }); - } - this.wake(); - } - /** An independent scoped check may continue its explicit target's advisory search, never an arbitrary task. */ - protected proofSearchAssignment(action: Extract) { - const identity = { problemReceiptDigest: this.input.state.problem.receiptDigest, - environmentDigest: this.input.state.environmentDigest }; - const checks = (this.archive.nextChecks ?? []).filter(record => currentNextCheck(record, this.archive, identity)); - const check = proofSearchCheckForAssignment(action.assignment, checks, identity); - const { taskId, taskDigest } = check?.scope.target ?? action.assignment; - const scope = { ...identity, taskId, taskDigest }; - return { scope, record: proofSearchRecordForAssignment(this.archive.proofSearchRecords, scope, check), - history: check?.id, requiredBasisDigest: check?.scope.executionBasisDigest }; - } - /** With --plan-approval, the first accepted plan holds every worker until a human approves its exact version. */ - protected planApprovalPending() { - return planApprovalStatus(this.input.state) === 'pending'; - } - protected refreshPlanApproval() { - const pending = this.planApprovalPending(); - if (pending && this.archive.planApproval?.requestedAt === undefined) { - this.archive.planApproval = { ...this.archive.planApproval, requestedAt: Date.now(), requestedVersion: this.archive.planVersion }; - this.input.emit('plan_approval_requested', { planVersion: this.archive.planVersion }); - } - const waiting = pending && !this.stopping && !this.failure && !this.input.signal.aborted && - this.liveWorkers.has(this.lead.id) && !this.active.size && !this.reservedTurns.size && - !this.preparingTaskTypes.size && !this.preparingStatements && !this.planSynchronizations.size && - !this.leadDeliveries.size && !this.deliveryChecks.size && !this.proofPublications.size && - !this.proofDeliveryChecks.size && !this.checkingTaskInputs.size && !this.integrationQueueDepth; - // A planning checkpoint may close every model session. Keep the CLI alive to receive approval - // while its execution timer is paused, using the existing input poller. - if (waiting) this.timer?.ref(); else this.timer?.unref(); - this.input.onPlanApprovalWaiting?.(waiting); - } - protected cancelStaleTaskTypes() { - for (const pending of this.preparingTaskTypes.values()) - if (!pending.controller.signal.aborted && !pending.current()) pending.controller.abort(); - } - protected wake() { - this.dispatchRevision++; - this.cancelStaleTaskTypes(); - this.refreshPlanApproval(); - const lead = this.active.get(this.lead.id), canonical = this.archive.canonicalCommit; - if (lead?.action.kind === 'lead' && !lead.cancelled && canonical && !this.stopping && !this.failure && - !this.input.signal.aborted && !this.planApprovalPending() && !this.synchronizationPending() && - this.lastAssembly !== canonical && this.canAssemble(canonical)) { - // Synchronization can settle with only a wake. Yield this dispatch permanently before - // stopping its writer, so late plans and source drafts cannot replace the candidate. - this.assemblyYieldedLeads.add(lead.action); - lead.cancelled = true; - this.input.emit('lead_yielded_for_assembly', { workerId: this.lead.id, seedCommit: lead.action.seedCommit, commit: canonical }); - void lead.interrupt().catch(() => {}); - } - for (const wake of this.waiters) wake(); - this.waiters.clear(); - } - modelBudgetChanged() { this.refreshGoalProgress(); this.input.save(); this.wake(); } - workerAvailabilityChanged() { this.wake(); } - protected rejectWorkerDelivery(worker: ResearchWorker, action: Extract, - submission: string, error: Error): DeliveryReceipt { - const receipt = rejectedDeliveryReceipt({ assignment: action.assignment, workerId: worker.id, - environmentDigest: this.input.state.environmentDigest, submission, error, now: Date.now(), - receipts: this.archive.deliveryReceipts }); - const receipts = this.archive.deliveryReceipts ??= []; - const previous = assignmentDeliveryReceipts(receipts, action.assignment, this.input.state.environmentDigest, worker.id) - .find(item => item.id === receipt.id); - if (previous) return previous; - receipts.push(receipt); - const node = this.node(action.task.id); - if (this.current(action) && node) node.feedback = deliveryReceiptFeedback(receipt); - return receipt; - } - protected async notifyDeliveryReceipts(worker: ResearchWorker, action: Extract) { - const active = this.active?.get(worker.id); - if (!active || active.action !== action) return; - const current = () => this.active.get(worker.id) === active && !active.cancelled && - !this.stopping && !this.input.signal.aborted && this.current(action); - if (!current()) return; - const notified = this.deliveryReceiptNotifications ??= new WeakMap(); - for (const receipt of assignmentDeliveryReceipts(this.archive.deliveryReceipts, action.assignment, this.input.state.environmentDigest, worker.id)) { - if (receipt.status !== 'needs-correction' || notified.get(receipt) === active) continue; - // Reserve this receipt while its soft notice waits, without blocking later worker deliveries. - notified.set(receipt, active); - const pending = Promise.resolve().then(async () => { - if (current() && receipt.status === 'needs-correction') await active.notify(deliveryReceiptFeedback(receipt)); - }).catch(() => { - if (notified.get(receipt) === active) notified.delete(receipt); - this.input.emit('delivery_receipt_notification_deferred', { workerId: worker.id, receiptId: receipt.id }); - }); - const notifications = this.notifications ??= new Set(); - notifications.add(pending); void pending.finally(() => notifications.delete(pending)); - } - } - protected resolveDeliveryReceipts(worker: ResearchWorker, action: Extract, - replacesReceipt?: unknown, complete = false) { - const scoped = assignmentDeliveryReceipts(this.archive.deliveryReceipts, action.assignment, this.input.state.environmentDigest, worker.id); - const byId = new Map(scoped.map(receipt => [receipt.id, receipt])); - const replaced = new Set(); - let id = typeof replacesReceipt === 'string' ? replacesReceipt : undefined; - while (id && !replaced.has(id)) { - const receipt = byId.get(id); - if (!receipt || receipt.status === 'superseded') break; - replaced.add(id); id = receipt.replacesReceipt; - } - const node = this.node(action.task.id); - for (const receipt of scoped) { - if (receipt.status !== 'needs-correction' || !complete && !replaced.has(receipt.id)) continue; - receipt.status = 'recorded'; - if (node?.feedback === deliveryReceiptFeedback({ ...receipt, status: 'needs-correction' })) - node.feedback = undefined; - } - const pending = scoped.findLast(receipt => receipt.status === 'needs-correction'); - if (pending && node && !node.feedback) node.feedback = deliveryReceiptFeedback(pending); - } - protected receiveProofReady(worker: ResearchWorker, action: Extract, submissionId: string) { - const created = proofReadyRecord({ assignment: action.assignment, workerId: worker.id, submissionId, - problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest, now: Date.now() }); - const records = this.archive.proofReadyRecords ??= []; - let record = records.find(item => item.id === created.id); - if (record && ['checked', 'failed', 'superseded'].includes(record.status)) return; - if (!record) { records.push(created); record = created; } - if (!this.current(action) || worker.id !== action.assignment.workerId) { - record.status = 'superseded'; record.reason = 'Assignment changed before readiness intake.'; this.changed(); return; - } - const fresh = this.freshProofReady.get(action) === record.id; - for (const other of records) if (other !== record && other.assignmentKey === record.assignmentKey && - other.workerId === worker.id && other.status === 'awaiting-freeze') { - other.status = 'superseded'; other.reason = 'A later readiness event replaced this request.'; - } - // Only a newly consumed event can grant this process permission to freeze a live workspace. - this.freshProofReady.set(action, record.id); - this.changed(); - const active = this.active.get(worker.id); - if (!fresh && record.status === 'awaiting-freeze' && active?.action === action && active.requestReady) { - const pending = active.requestReady().catch(() => { - this.input.emit('proof_ready_notification_deferred', { workerId: worker.id, receiptId: record!.id }); - }); - this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); - } - } - private proofReadyCurrent(record: ProofReadyRecord, worker: ResearchWorker, action: Extract) { - return record.workerId === worker.id && worker.id === action.assignment.workerId && - record.assignmentKey === assignmentDeliveryFile(action.assignment) && record.taskId === action.task.id && - record.taskDigest === action.assignment.taskDigest && record.seedCommit === action.assignment.seedCommit && - record.problemReceiptDigest === this.input.state.problem.receiptDigest && - record.environmentDigest === this.input.state.environmentDigest && this.current(action); - } - pendingProofReady(worker: ResearchWorker, action: Extract): ProofReadyRecord | undefined { - const records = (this.archive.proofReadyRecords ?? []).filter(record => record.workerId === worker.id && - record.assignmentKey === assignmentDeliveryFile(action.assignment) && ['awaiting-freeze', 'frozen'].includes(record.status)); - let changed = false; - for (const record of records) if (!this.proofReadyCurrent(record, worker, action)) { - record.status = 'superseded'; record.reason = 'Assignment or frozen input identity changed.'; changed = true; - } - if (changed) this.changed(); - return records.findLast(record => record.status === 'frozen' || record.status === 'awaiting-freeze' && - this.freshProofReady.get(action) === record.id); - } - proofReadyFrozen(worker: ResearchWorker, action: Extract, commit: string): ProofReadyRecord | undefined { - const record = this.pendingProofReady(worker, action); - if (!record) return; - if (record.snapshotCommit) { - if (record.snapshotCommit !== commit) throw new Error('math_proof_ready_snapshot_changed'); - return record; - } - // Callers stop the writer first. Every read here addresses the host's immutable commit. - const sourceDigest = ownedSourceDigest(this.input.state.problem, worker.worktree, commit); - this.pin(commit); - Object.assign(record, { status: 'frozen', snapshotCommit: commit, sourceDigest, frozenAt: Date.now() }); - this.changed(); - this.input.emit('proof_ready_frozen', { readyId: record.id, taskId: record.taskId, taskDigest: record.taskDigest, - workerId: record.workerId, assignmentKey: record.assignmentKey, seedCommit: record.seedCommit, - commit, snapshotCommit: commit, sourceDigest, frozenAt: record.frozenAt }); - return record; - } - proofReadyCompleted(worker: ResearchWorker, action: Extract, - proof?: ProofCheck & { conditions?: TaskProof['conditions'] }, reason?: string): void { - const record = this.pendingProofReady(worker, action); - if (!record) return; - if (!proof || !proof.passed) { - record.status = 'failed'; record.reason = reason ?? 'The fixed declaration did not pass independent checking.'; - } else { - if (record.status !== 'frozen' || proof.commit !== record.snapshotCommit || proof.sourceDigest !== record.sourceDigest || - !this.checkedDeliveries.has(proof as TaskProof) || !proof.verification.results.length) - throw new Error('math_proof_ready_check_identity_changed'); - Object.assign(record, { status: 'checked', evidence: proof.conditions?.length ? 'conditional' : 'unconditional', - conditions: proof.conditions ? [...proof.conditions] : [], receiptIds: proof.verification.results.map(result => result.receiptId) }); - delete record.reason; - } - this.freshProofReady.delete(action); this.changed(); - } - proofReadyFailedFreeze(worker: ResearchWorker, action: Extract, reason: string): void { - const record = this.pendingProofReady(worker, action); - if (!record || record.snapshotCommit) return; - record.status = 'failed'; record.reason = 'Freeze unconfirmed: ' + reason; - this.freshProofReady.delete(action); this.changed(); - } - activate(worker: ResearchWorker, action: CooperativeAction, interrupt: () => Promise, notify: (message: string, options?: { requireTurn?: boolean; mode?: 'advisory' }) => Promise, - requestReady?: () => Promise, requestAdvisoryCheckpoint?: (commit: string) => void) { - this.active.set(worker.id, { action, interrupt, notify, requestReady, requestAdvisoryCheckpoint }); this.changed(); - } - deactivate(worker: ResearchWorker) { this.active.delete(worker.id); this.changed(); } - protected nextCheckDispatchable(node: TaskRecord) { - return !node.nextCheckId || this.archive.nextChecks?.some(record => record.id === node.nextCheckId && - record.status === 'pending' && currentNextCheck(record, this.archive, this.explorationIdentity)) === true; - } - protected leadPublication(action: CooperativeAction) { - if (action.kind !== 'lead') return; - const nonce = action.initialPlanNonce ?? action.planNonce; - const publication = this.archive.planPublication ?? this.archive.initialPlanPublication; - return publication?.nonce === nonce ? publication : undefined; - } - protected openLeadPublicationTarget(action?: CooperativeAction) { - if (action?.kind === 'lead' && this.current(action) && !this.leadPublication(action)) return leadPlanPublicationTarget(action); - } - current(action: CooperativeAction) { - if (action.kind === 'assemble') return !this.failure && !this.stopping && this.liveWorkers.has(this.lead.id) && this.canAssemble(action.seedCommit); - if (action.kind === 'lead' && this.assemblyYieldedLeads.has(action)) return false; - if (action.kind === 'lead' && (action.planNonce || action.initialPlanNonce) && !this.leadEvidence.has(action)) return false; - if (isStatementAction(action)) { - const review = this.archive.statementReviews?.find(item => item.id === action.reviewId); - const node = this.node(action.taskId); - return Boolean(review && review.status === (action.kind === 'backtranslate' ? 'translating' : 'reviewing') && - review.assignmentId === action.assignmentId && - review.taskDigest === action.taskDigest && review.commit === action.seedCommit && - review.snapshotDigest === action.snapshotDigest && review.workspace === action.workspace && node && - digest(node.task) === action.taskDigest && this.statementReviewAllowed(node.task)); - } - if (action.kind === 'lead') { - const version = this.leadPublication(action)?.planVersion ?? action.planVersion; - return version === undefined || version === this.archive.planVersion; - } - if (action.kind === 'review') { - const review = this.archive.review; - return Boolean(review && review.status === 'running' && review.commit === action.seedCommit && - review.sourceDigest === action.sourceDigest && review.assignmentId === action.assignmentId); - } - return action.kind !== 'task' || !this.actionRouteRetired(action) && - this.archive.tasks.some(node => node.assignment === action.assignment && digest(node.task) === action.assignment.taskDigest && - this.nextCheckDispatchable(node) && - (!node.capacityExploration || currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity)) && - (!action.assignment.connectionCheck || taskReferenceDependencies(node) || taskConnectionCheckCurrent(node.task, - action.assignment, this.archive.tasks, { environmentDigest: this.input.state.environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest })) && - (!isFeasibilityReview(node.task) || this.input.workers.some(worker => worker.id === action.assignment.workerId && - independentFeasibilityWorker(node, worker, this.archive.tasks, this.archive.groups))) && - (taskReferenceDependencies(node) ?? action.assignment.dependencies ?? []).every(dependency => this.archive.tasks.some(item => item.task.id === dependency.taskId && digest(item.task) === dependency.taskDigest)) && - (node.task.status ?? 'active') === 'active' && this.archive.groups?.find(route => route.group.id === taskGroup(node.task))?.group.status === 'active'); - } - protected taskVersions() { - return new Map(this.archive.tasks.map(({ task }) => [task.id, { task, version: digest(task) }])); - } - protected deliveryVisible(record: DeliveryRecord, task: CooperativeTask | undefined, versions: TaskVersions, gapViewer = task) { - if (record.status === 'superseded') return false; - if (!mathematicalGapVisible(record, this.archive, gapViewer)) return false; - if (!record.taskId) return !task; - const node = versions.get(record.taskId); - return node && node.version === record.taskDigest && record.dependencies.every(dependency => - versions.get(dependency.taskId)?.version === dependency.taskDigest) && - (!task || taskGroup(node.task) === taskGroup(task) || node.task.sharing !== 'group'); - } - private inform(record: DeliveryRecord) { - const versions = this.taskVersions(); - for (const [id, active] of this.active) { - if (id === record.producer) continue; - if (isStatementAction(active.action)) continue; - const task = active.action.kind === 'task' ? active.action.task : undefined; - if (task && record.taskId && !this.deliveryVisible(record, task, versions)) continue; - const source = record.taskId && versions.get(record.taskId)?.task; - const forConsumer = task && source && !active.cancelled && record.kind === 'research' && - (record.status === 'advisory' || record.status === 'conditional') && record.summary.trim() && - (source.consumerGoalIds?.includes(task.id) || task.dependsOn.includes(source.id)) && this.current(active.action); - const update = `Cooperation update: ${record.kind} ${record.id}, task ${record.taskId ?? 'original'}, status ${record.status}. Read COOPERATION.json for peer state and current-version references; use M4 to choose relevant material. This notification grants no proof acceptance.`; - const notice = forConsumer ? update + '\nAdvisory finding for your current task (verify before using): ' + - JSON.stringify({ summary: bounded(record.summary, 1800), remainingObligations: record.remainingObligations.slice(0, 3) - .map(obligation => bounded(obligation, 280)) }) : update; - const pending = active.notify(notice, { mode: 'advisory' }).catch(() => { this.input.emit('notification_deferred', { workerId: id, deliveryId: record.id }); }); - this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); - } - this.input.emit('delivery_published', { deliveryId: record.id, producer: record.producer, workerId: record.producer, - taskId: record.taskId, taskDigest: record.taskDigest, assignmentKey: record.assignmentKey, - commit: record.commit, sourceDigest: record.sourceDigest, - receiptIds: record.evidence?.verification.results.map(result => result.receiptId), - kind: record.kind, status: record.status }); - } - protected pin(commit?: string) { - if (!commit || this.pinned.has(commit)) return; - if (!/^[a-f0-9]{40,64}$/u.test(commit)) throw new Error('math_delivery_invalid_commit'); - git(this.lead.worktree, ['update-ref', `refs/math/${this.input.state.runId}/evidence/${commit}`, commit]); - this.pinned.add(commit); - } - protected record(worker: ResearchWorker, task: CooperativeTask | undefined, kind: DeliveryRecord['kind'], status: DeliveryRecord['status'], - summary: string, options: Partial = {}) { - const record = this.createDeliveryRecord(worker, task, kind, status, summary, options); - (this.archive.deliveries ??= []).push(record); - this.publishDeliveryRecord(record); - return record; - } - protected createDeliveryRecord(worker: ResearchWorker, task: CooperativeTask | undefined, kind: DeliveryRecord['kind'], status: DeliveryRecord['status'], - summary: string, options: Partial = {}): DeliveryRecord { - if (options.mathematicalGap && task) options = { ...options, mathematicalGapScope: bindMathematicalGap(options.mathematicalGap, task, - this.archive, { problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest }) }; - const inputs = task && status !== 'superseded' ? this.dependencies(task) : []; - const references = task && kind === 'proof' && status === 'verified' ? taskReferenceDependencies(this.node(task.id)) : undefined; - const dependencies = references ?? inputs.map(node => ({ taskId: node.task.id, taskDigest: digest(node.task) })); - const remaining = inputs.filter(node => !['integrated', 'completed'].includes(node.status)).map(node => node.task.id); - const record: DeliveryRecord = { id: crypto.randomUUID(), producer: worker.id, taskId: task?.id, taskDigest: task && digest(task), - groupId: task && taskGroup(task), kind, status, statement: task?.type ?? task?.objective ?? this.input.state.problem.contract.formalStatement, - premises: task?.premises ?? this.input.state.problem.contract.assumptions, dependencies, remainingObligations: remaining, - summary: bounded(summary, 5000), evidenceRefs: [], createdAt: Date.now(), ...options }; - if (record.evidence) { - const { passed, verification: { status, targetCommit, results } } = record.evidence; - // Proof records own the receipts; deliveries refer to their immutable IDs. - record.evidence = { passed, verification: { status, targetCommit, - results: results.map(({ receiptId }) => ({ receiptId })) } }; - } - this.pin(record.commit); this.pin(record.artifacts?.commit); this.pin(record.evidence?.verification.targetCommit); - return record; - } - protected publishDeliveryRecord(record: DeliveryRecord) { - this.changed(); - if (record.status !== 'superseded') this.inform(record); - } - protected reportBlockers(task: CooperativeTask, value: unknown) { - const proposals = validateBlockerProposals(value, task, this.archive.tasks); - for (const blocker of recordRouteBlockers(this.archive.blockers ??= [], proposals, task, this.archive.tasks, - this.input.state.environmentDigest, this.input.state.problem.receiptDigest)) { - this.wakeLead('route-blocker-recorded'); - this.input.emit(blocker.status === 'parked' ? 'route_parked' : 'route_blocker_recorded', { - blockerId: blocker.id, taskId: blocker.taskId, groupId: blocker.groupId, count: blocker.count, - scope: blocker.scope, evidenceStatus: blocker.evidenceStatus, reopenOn: blocker.reopenOn }); - } - } - protected async wait() { - const signal = this.input.signal; signal.throwIfAborted(); - await new Promise(resolve => { - const wake = () => { signal.removeEventListener('abort', wake); this.waiters.delete(wake); resolve(); }; - this.waiters.add(wake); signal.addEventListener('abort', wake, { once: true }); - }); - signal.throwIfAborted(); - } - protected node(id: string) { return this.archive.tasks.find(node => node.task.id === id)!; } - protected dependencies(task: CooperativeTask, tasks: readonly TaskRecord[] = this.archive.tasks): TaskRecord[] { - return taskDependencyRecords(task, tasks); - } - protected synchronizationBlocked(task: CooperativeTask): boolean { - return [this.node(task.id), ...this.dependencies(task)].some(node => node && - (node.pendingValidation || this.preparingStatementTasks.has(node.task.id))); - } - protected async waitForDispatch(observedRevision = this.dispatchRevision): Promise { - // A wake between checking readiness and subscribing already invalidates the selection. - if (observedRevision === this.dispatchRevision) await this.wait(); - return RETRY_DISPATCH; - } - protected visible(task: CooperativeTask): TaskRecord[] { - const nodes = new Map(this.archive.tasks.map(node => [node.task.id, node])); - const visible = new Set(this.archive.tasks.filter(node => taskGroup(node.task) === taskGroup(task) || - (node.task.sharing !== 'group' && ['integrated', 'completed'].includes(node.status)))); - const seen = new Set(); - const visit = (node: TaskRecord) => { - if (seen.has(node.task.id)) return; seen.add(node.task.id); - for (const id of plannedTaskDependencyIds(node, this.archive.tasks)) { - const input = nodes.get(id); - if (!input || (taskGroup(input.task) !== taskGroup(task) && input.task.sharing === 'group')) continue; - visible.add(input); visit(input); - } - }; - const current = nodes.get(task.id); if (current) visit(current); - return this.archive.tasks.filter(node => visible.has(node)); - } - protected seed(worker: ResearchWorker, commit: string, task?: CooperativeTask): string { - this.suspendResearchDrafts(worker, task?.id); - const session = this.input.state.workers?.find(record => record.id === worker.id); - const previousGroup = session?.sessionGroupId; - if (task && (previousGroup && previousGroup !== taskGroup(task) || session?.sessionTaskId && session.sessionTaskId !== task.id) || - !task && worker.id !== this.lead.id) fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), ''); - const sources = Object.fromEntries(this.input.state.problem.ownedFiles.map(file => [file, - committedSource(this.lead.worktree, commit, `${this.input.state.problem.projectRelative}/${file}`)])); - for (const [file, source] of Object.entries(scopedResearchSources(this.input.state.problem, task, sources, - researchSourceTasks(this.archive.tasks)))) { - fs.writeFileSync(path.join(worker.worktree, this.input.state.problem.projectRelative, file), source); - } - const problem = this.input.state.problem; - if (fs.existsSync(path.join(worker.worktree, problem.projectRelative, '.lake/source-constraints.json'))) { - writeMathJsonDurable(path.join(worker.worktree, problem.projectRelative, '.lake/source-constraints.json'), - solverSourceConstraints(problem), 0o400); - } - const seed = commitSolverSources(this.input.state.problem, worker.worktree); - if (worker.id === this.lead.id) { - this.archive.leadSeedCommit = seed; this.pin(seed); this.input.save(); - } - return seed; - } -} diff --git a/src/solver/cooperationInputs.ts b/src/solver/cooperationInputs.ts deleted file mode 100644 index 943d7414..00000000 --- a/src/solver/cooperationInputs.ts +++ /dev/null @@ -1,558 +0,0 @@ -import { parseCooperationPlan, isAdvisoryTask as advisory } from './tasks'; -import path from 'node:path'; -import fs from 'node:fs'; -import crypto from 'node:crypto'; -import { VerificationCheckpointError } from './verificationCheckpoint'; -import { canonicalMathJson, mathDigest, parseMathJson, readMathFile } from '../math/mathRuntimeIo'; -import { assertMathCanonicalPath } from '../math/paths'; -import { mathGitResult } from '../math/mathGit'; -import { type ResearchWorker } from './modules/organization'; -import { taskCanStart } from './modules/search'; -import { deliveryDetails, pendingDeliveryLines, readMathResponse, parseMathResponse } from './deliveries'; -import { assertSolverSources, committedSource, commitSolverProjection, git, withSolverWorktree } from './problem'; -import { isStatementAction } from './statementReview'; -import { captureDeliveryArtifacts } from './deliveryArtifacts'; -import { bindMathematicalGap } from './mathematicalGaps'; -import { assignmentDeliveryFile, isFeasibilityReview, isFinalCandidateReview, leadPlanDeliveryFile, type TaskRecord, type CooperativeAction } from './tasks'; -import { directDeliveryRejections, rejectionCode, HumanEditRecord, TaskVersions, bounded, leadPlanPublicationFeedback, - leadPlanPublicationTarget, parseLeadPlan, type PlanPublicationRejection } from './cooperationShared'; -import { CooperationPlanning } from './cooperationPlanning'; -import { ResearchAdmissionError } from './researchAdmission'; -import { acceptContextCheckpoint, contextCheckpointRejection, contextCheckpointRejectionFeedback, savedContextCheckpoint } from './contextCheckpoint'; -import { MAX_PLAN_APPROVAL_REJECTIONS, planApprovalInputSchema, planApprovalLog, planApprovalStatus, type PlanApprovalInput } from './planApproval'; -import { latestProofSearchRecord, retainProofSearchCheckpoint } from './proofSearchRecords'; -import { recordHumanGuidanceDecisions } from './humanGuidance'; -import { helperNominationsSchema } from './incrementalHelpers'; - -/** Worker delivery intake. */ -export abstract class CooperationInputs extends CooperationPlanning { - abstract leadCheckpointInstruction(action: Extract): string; - protected abstract leadDecisionObligations(action?: Extract): { any: boolean }; - protected guidancePulse?: Promise; - protected async retainGuidanceDecisions(worker: ResearchWorker, action: CooperativeAction, decisions: unknown) { - if (decisions === undefined || isStatementAction(action)) return; - const pending = Promise.resolve(this.guidancePulse).then(async () => { - try { - await recordHumanGuidanceDecisions({ stateFile: path.join(path.dirname(this.lead.worktree), 'state.json'), - state: this.input.state, workerId: worker.id, decisions, - scope: action.kind === 'task' ? { taskRef: { id: action.task.id, version: action.assignment.taskDigest } } - : { planVersion: action.kind === 'lead' ? action.planVersion ?? this.archive.planVersion : this.archive.planVersion }, - current: () => !this.stopping && !this.input.signal.aborted && this.current(action) && - (action.kind === 'task' ? action.assignment.workerId === worker.id : - action.kind === 'review' ? this.archive.review?.workerId === worker.id : worker.id === this.lead.id), - onRecord: record => this.input.emit('human_guidance_decided', { id: record.id, decision: record.decision, evidence: 'advisory' }), - }); - } catch (error) { - this.input.emit('human_guidance_decision_rejected', { workerId: worker.id, - reason: error instanceof Error ? error.message : 'math_guidance_decision_invalid' }); - } - }); - this.guidancePulse = pending; - try { await pending; } finally { if (this.guidancePulse === pending) this.guidancePulse = undefined; } - } - /** A host import has no model writer; retain the normal readiness, snapshot and receipt boundary. */ - freezeImportedProof(worker: ResearchWorker, action: Extract, - submissionId: string, commit: string) { - this.receiveProofReady(worker, action, submissionId); - return this.proofReadyFrozen(worker, action, commit); - } - private planPublicationNotification?: PlanPublicationRejection; - private leadDraftBaselines = new WeakMap(); - private contextCheckpointNotifications?: WeakMap; - protected syncEditChecks(nodes: ReadonlyMap, versions: TaskVersions) { - for (const edit of this.archive.edits ?? []) { - if (edit.status !== 'applied' || !edit.recheck) continue; - const before = canonicalMathJson(edit.recheck); - for (const result of edit.recheck.tasks) { - if (['removed', 'superseded'].includes(result.status)) continue; - const node = nodes.get(result.taskId); - if (!node || versions.get(result.taskId)?.version !== result.taskDigest) { - result.status = 'superseded'; - continue; - } - const proof = node.integratedCheck ?? node.proof; - const fresh = !node.pendingValidation && proof && proof.taskDigest === result.taskDigest && this.checkedDeliveries.has(proof); - result.status = node.status === 'blocked' ? 'failed' : fresh && node.status === 'integrated' && proof.passed && !proof.conditions?.length ? 'passed' : - fresh && node.status === 'conditional' ? 'conditional' : 'pending'; - result.reason = node.status === 'blocked' ? node.feedback : undefined; - if (fresh) result.lastCheck = { commit: proof.commit, sourceDigest: proof.sourceDigest, - environmentDigest: this.input.state.environmentDigest, passed: proof.passed, conditional: Boolean(proof.conditions?.length), - receiptIds: proof.verification.results.map(receipt => receipt.receiptId) }; - } - const statuses = edit.recheck.tasks.map(result => result.status); - edit.recheck.status = statuses.every(status => status === 'removed') ? 'not-required' : - statuses.includes('failed') ? 'failed' : statuses.some(status => status === 'pending' || status === 'conditional') ? 'pending' : - statuses.includes('superseded') ? 'superseded' : 'passed'; - if (before !== canonicalMathJson(edit.recheck)) this.input.emit('edit_recheck_updated', { id: edit.id, recheck: edit.recheck }); - } - } - protected inputs() { - return this.pendingPulse ??= this.readInputs().finally(() => { this.pendingPulse = undefined; }); - } - /** Serialize input edits while allowing independent proof checks to continue. */ - private async readInputs(): Promise>> { - if (this.archive.tasks.some(node => node.pendingValidation) || this.archive.edits?.some(edit => edit.status === 'applied' && edit.pendingSync)) - this.schedulePlanSynchronization(); - const cursors = this.archive.cursors ??= {}; - const file = path.join(path.dirname(this.lead.worktree), 'edits.jsonl'); - // Drain queued edits before considering an approval of the resulting plan. - for (const entry of pendingDeliveryLines(file, cursors, 'edits', () => this.input.save(), 'drain')) { - this.input.signal.throwIfAborted(); - let id = crypto.randomUUID(); - let record: HumanEditRecord | undefined; - try { - if (entry.error) throw new Error(entry.error); - if (!entry.line?.trim()) continue; - let edit: any; - try { edit = JSON.parse(entry.line); } - catch { throw new Error('math_edit_invalid_json'); } - if (!edit || typeof edit !== 'object' || Array.isArray(edit)) throw new Error('math_edit_invalid'); - if (typeof edit.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/u.test(edit.id)) throw new Error('math_edit_invalid_id'); - id = edit.id; - record = this.archive.edits?.find(previous => previous.id === id); - if (record && record.status !== 'received') { - if (record.status === 'applied' && record.pendingSync) { - this.schedulePlanSynchronization(); - this.input.emit('edit_applied', { id, planVersion: record!.planVersion, affectedTasks: record!.affectedTasks, recheck: record!.recheck }); - } - continue; - } - if (!record) { - record = { id, status: 'received', receivedAt: Date.now(), - ...(typeof edit.baseVersion === 'string' ? { baseVersion: bounded(edit.baseVersion, 128) } : {}) }; - (this.archive.edits ??= []).push(record); this.changed(); - this.input.emit('edit_received', { id, baseVersion: record.baseVersion }); - } - if (edit.baseVersion !== this.archive.planVersion) throw new Error('math_edit_version_conflict'); - await this.input.exclusiveCheck(() => { - if (edit.baseVersion !== this.archive.planVersion) throw new Error('math_edit_version_conflict'); - return this.acceptPlan(parseCooperationPlan(this.input.state.problem, edit), record); - }); - for (const [workerId, active] of this.active) { - if (isStatementAction(active.action)) continue; - const pending = active.notify(`Human edit ${id} applied at plan version ${this.archive.planVersion}; this does not mean the affected proofs passed. Read the edit's separate recheck results in COOPERATION.json. Superseded assignments must stop; unrelated work continues.`) - .catch(() => { this.input.emit('notification_deferred', { workerId, editId: id }); }); - this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); - } - this.input.emit('edit_applied', { id, planVersion: record.planVersion, affectedTasks: record.affectedTasks, recheck: record.recheck }); - } catch (error) { - this.input.signal.throwIfAborted(); - const reason = error instanceof Error ? error.message : 'math_edit_invalid'; - if (record?.status === 'applied' || !(error instanceof Error) || error.name === 'AbortError' || - (entry.error !== reason && !/^math_(?:edit_(?:invalid(?:_json|_id)?|version_conflict)$|plan_[a-z_]+(?:$|:))/u.test(reason))) - throw error; - if (record) { record.status = 'rejected'; record.reason = reason; } - else (this.archive.edits ??= []).push({ id, status: 'rejected', reason, receivedAt: Date.now() }); - this.changed(); - this.input.emit('edit_rejected', { id, reason }); - } - } - this.readPlanApprovals(cursors); - await this.readPlanDelivery(cursors); - for (const worker of this.input.workers) { - if (this.deliveryChecks.has(worker.id)) continue; - const active = this.active.get(worker.id); - if (active?.action.kind !== 'task') continue; - const check = this.readWorkerDeliveries(worker, active.action, cursors); - this.deliveryChecks.set(worker.id, check); - this.refreshPlanApproval(); - void check.catch(error => { - this.input.emit('cooperation_poll_failed', { reason: error instanceof Error ? error.message : 'unknown' }); - if (error instanceof VerificationCheckpointError || error instanceof Error && error.message === 'math_verifier_unavailable') { this.failure = error; this.changed(); } - }).finally(() => { - if (this.deliveryChecks.get(worker.id) === check) this.deliveryChecks.delete(worker.id); - this.wake(); - }).catch(() => {}); - } - return new Map(this.deliveryChecks); - } - /** Inspect this dispatch's complete new response using the same validation as publication. */ - protected inspectLeadCheckpointDraft(action: Extract) { - let response: unknown; - // A partial write, ordinary mathematical notes or missing file is not a submission to correct. - try { response = readMathResponse(this.lead.worktree, 'math-plan'); } catch { return; } - const digest = mathDigest(canonicalMathJson(response)); - if (!this.leadDraftBaselines.has(action)) { - let baseline: string | null = null; - try { - if (git(this.lead.worktree, ['ls-tree', '--name-only', action.seedCommit, '--', 'RESEARCH.md'])) - baseline = mathDigest(canonicalMathJson(parseMathResponse( - committedSource(this.lead.worktree, action.seedCommit, 'RESEARCH.md'), 'math-plan'))); - } catch { /* An inherited notes-only seed has no control response. */ } - this.leadDraftBaselines.set(action, baseline); - } - if (this.leadDraftBaselines.get(action) === digest) { - const rejection = this.archive.planRejection; - // An accepted seed is not a new response. A previously rejected draft still owes its - // correction in this dispatch, even when the writer has not changed the saved response yet. - if (!this.leadDecisionObligations(action).any || !rejection || rejection.error !== this.archive.error || - rejection.proposalDigest !== this.proposedPlanDigest()) return; - } - try { - const plan = parseLeadPlan(this.input.state.problem, response, this.planPatchBase(), { goalPath: this.goalPathReview() }); - this.preparePlan(plan, action); - } catch (error) { - if (error instanceof Error && /^math_plan_/u.test(error.message)) - return { reason: bounded(error.message, 4000) }; - throw error; - } - return { reason: undefined }; - } - /** Human approvals queued by queuePlanApproval; each names the exact plan version it opens dispatch for. */ - private readPlanApprovals(cursors: Record) { - const file = planApprovalLog(path.join(path.dirname(this.lead.worktree), 'state.json')); - for (const entry of pendingDeliveryLines(file, cursors, 'planApprovals', () => this.input.save(), 'drain')) { - this.input.signal.throwIfAborted(); - if (!entry.error && !entry.line?.trim()) continue; - let parsed: PlanApprovalInput | undefined; - if (entry.line) try { parsed = planApprovalInputSchema.parse(JSON.parse(entry.line)); } catch { /* Report invalid approval below. */ } - this.applyPlanApproval(parsed, entry.error); - } - } - private applyPlanApproval(approval: PlanApprovalInput | undefined, readError?: string) { - const record = this.archive.planApproval ??= {}; - if (approval && record.approvedId === approval.id) return; - const status = planApprovalStatus(this.input.state); - const reason = readError ?? (!approval ? 'math_plan_approval_invalid' : status === 'not-required' ? 'math_plan_approval_not_required' : - status === 'approved' ? 'math_plan_approval_already_approved' : status === 'awaiting-plan' ? 'math_plan_approval_plan_unavailable' : - approval.planVersion !== this.archive.planVersion ? 'math_plan_approval_version_conflict' : undefined); - if (!approval || reason) { - const rejection = { id: approval?.id ?? crypto.randomUUID(), reason: reason!, at: Date.now(), - ...(approval ? { planVersion: approval.planVersion } : {}) }; - record.rejections = [...record.rejections ?? [], rejection].slice(-MAX_PLAN_APPROVAL_REJECTIONS); - this.input.emit('plan_approval_rejected', rejection); - } else { - Object.assign(record, { approvedId: approval.id, approvedVersion: approval.planVersion, approvedAt: Date.now() }); - this.input.emit('plan_approved', { id: approval.id, planVersion: approval.planVersion }); - } - this.changed(); - } - private async readPlanDelivery(cursors: Record) { - const active = this.active.get(this.lead.id), action = active?.action; - if (!action || action.kind !== 'lead') return; - const target = leadPlanPublicationTarget(action); - if (!target) return; - const { file, dispatchNonce: nonce, baseVersion } = target; - const initial = Boolean(action.initialPlanNonce); - const code = (reason: string) => `math_${initial ? 'initial_plan' : 'plan_publication'}_${reason}`; - const key = `${this.lead.id}/${file}`; - const research = this.input.state.workers?.find(record => record.id === this.lead.id) ?? this.input.state; - const current = () => this.active.get(this.lead.id) === active && !active.cancelled && - !this.stopping && !this.input.signal.aborted && this.current(action); - const open = () => current() && !this.leadPublication(action) && - !(initial && (this.archive.initialPlanPublication || this.archive.tasks.length)); - let advanced = false, feedbackChanged = false; - const reject = (reason: string, offset: number, checkpoint = false) => { - this.input.emit(initial ? 'initial_plan_rejected' : 'plan_publication_rejected', { workerId: this.lead.id, file, reason }); - if (checkpoint) { - const checkpoint = this.currentContextCheckpoint(this.lead, action); - if (!checkpoint || savedContextCheckpoint(checkpoint.research, this.lead.worktree)) return; - checkpoint.request.rejection = { file, offset, reason: bounded(reason, 4000) }; - } else { - if (!open()) return; - this.archive.planPublicationRejection = { nonce, file, offset, baseVersion, reason: bounded(reason, 4000) }; - } - feedbackChanged = true; - }; - try { - for (const entry of pendingDeliveryLines(path.join(this.lead.worktree, file), cursors, key, () => { advanced = true; })) { - this.input.signal.throwIfAborted(); - if (entry.error) { reject(entry.error, entry.offset); continue; } - const line = entry.line; - if (!line?.trim()) continue; - let checkpoint = false; - try { - const value = parseMathJson(line, code('invalid_json')); - if (!value || typeof value !== 'object' || Array.isArray(value)) - throw new Error(code('invalid') + ': expected a JSON object'); - const response = value as Record; - checkpoint = response.kind === 'checkpoint'; - if (checkpoint) { - await this.input.exclusiveCheck(async () => { - if (!current()) throw new Error(code('superseded')); - acceptContextCheckpoint(research, this.lead.worktree, response); - this.input.emit('context_checkpoint_published', { workerId: this.lead.id, threadId: research.threadId, - requestId: research.contextCheckpoint?.requestId, notesDigest: research.contextCheckpoint?.publishedNotesDigest }); - this.changed(); - }); - continue; - } - const fields: string[] = []; - if (response.kind !== target.kind) fields.push('kind must be "plan"'); - if (typeof response.baseVersion !== 'string') fields.push('baseVersion must be the current plan version'); - if ((!initial || response.dispatchNonce !== undefined) && response.dispatchNonce !== nonce) - fields.push('dispatchNonce must match this Lead dispatch'); - if (fields.length) throw new Error(code('invalid') + ': ' + fields.join(', ')); - const eventDigest = mathDigest(line), details = deliveryDetails(response); - await this.input.exclusiveCheck(async () => { - if (this.leadPublication(action)?.eventDigest === eventDigest) return; - if (!open()) throw new Error(code('superseded')); - if (response.baseVersion !== baseVersion || baseVersion !== this.archive.planVersion) - throw new Error(code('version_conflict')); - const plan = parseLeadPlan(this.input.state.problem, response, this.planPatchBase(), { goalPath: this.goalPathReview() }); - await this.acceptPlan(plan, undefined, { action, receipt: { nonce, file, - offset: entry.offset, eventDigest, baseVersion, acceptedAt: Date.now() } }); - await this.retainGuidanceDecisions(this.lead, action, response.guidanceDecisions); - this.rememberLeadDecision(action); - this.changed(); - this.input.emit(initial ? 'initial_plan_published' : 'plan_published', { ...this.archive.planPublication, - workerId: this.lead.id, summary: details.summary, taskIds: plan.tasks.map(task => task.id) }); - }); - } catch (error) { - this.input.signal.throwIfAborted(); - if (!(error instanceof Error) || !/^math_(?:initial_plan_|plan_|delivery_invalid)/u.test(error.message)) throw error; - reject(error.message, entry.offset, checkpoint); - } - } - } finally { if (advanced) { if (feedbackChanged) this.changed(); else this.input.save(); } } - const rejection = this.archive.planPublicationRejection; - if (rejection && rejection.nonce === nonce && open() && this.planPublicationNotification !== rejection) { - this.planPublicationNotification = rejection; - const pending = Promise.resolve().then(async () => { - if (this.archive.planPublicationRejection !== rejection || !open()) return; - await active.notify(leadPlanPublicationFeedback(action, this.archive)! + ' ' + this.leadCheckpointInstruction(action)); - }).catch(() => { - if (this.planPublicationNotification === rejection) this.planPublicationNotification = undefined; - this.input.emit('notification_deferred', { workerId: this.lead.id, file, offset: rejection.offset }); - }); - this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); - } - this.notifyContextCheckpointRejection(this.lead, action); - } - private currentContextCheckpoint(worker: ResearchWorker, action: Extract) { - const active = this.active?.get(worker.id); - if (!active || active.action !== action || active.cancelled || this.stopping || this.input.signal.aborted || - action.kind === 'task' && action.assignment.workerId !== worker.id || !this.current(action)) return; - const research = this.input.state.workers?.find(record => record.id === worker.id) ?? this.input.state; - const request = research.contextCheckpoint; - if (!research.threadId || request?.threadId !== research.threadId || !request.requestId) return; - return { active, research, request }; - } - private notifyContextCheckpointRejection(worker: ResearchWorker, action: Extract) { - const checkpoint = this.currentContextCheckpoint(worker, action), rejection = checkpoint?.request.rejection; - if (!checkpoint || !rejection || savedContextCheckpoint(checkpoint.research, worker.worktree)) return; - const file = action.kind === 'task' ? assignmentDeliveryFile(action.assignment) : leadPlanDeliveryFile(action); - if (!file) return; - const { active, request } = checkpoint; - const notified = this.contextCheckpointNotifications ??= new WeakMap(); - if (notified.get(rejection) === active) return; - notified.set(rejection, active); - const pending = Promise.resolve().then(async () => { - const current = this.currentContextCheckpoint(worker, action); - if (current?.active !== active || current.request !== request || request.rejection !== rejection || - savedContextCheckpoint(current.research, worker.worktree)) return; - await active.notify(contextCheckpointRejectionFeedback(contextCheckpointRejection(current.research), file)!); - }).catch(() => { - if (notified.get(rejection) === active) notified.delete(rejection); - this.input.emit('notification_deferred', { workerId: worker.id, file, offset: rejection.offset }); - }); - this.notifications.add(pending); void pending.finally(() => this.notifications.delete(pending)); - } - private async readWorkerDeliveries(worker: ResearchWorker, action: Extract, cursors: Record) { - const invalidInput = new Set([...directDeliveryRejections, 'math_delivery_invalid_commit', - 'math_delivery_requires_fixed_proof', 'math_delivery_unfinished_dependencies', 'math_route_blocker_invalid']); - const research = this.input.state.workers?.find(record => record.id === worker.id) ?? this.input.state; - const checkpointRejection = research.contextCheckpoint?.rejection; - let advanced = false; - const reject = (reason: Error | string, submission: string, checkpoint?: { file: string; offset: number }) => { - const error = typeof reason === 'string' ? new Error(reason) : reason; - if (checkpoint) { - const current = this.currentContextCheckpoint(worker, action); - if (current && checkpoint.file === assignmentDeliveryFile(action.assignment) && - !savedContextCheckpoint(current.research, worker.worktree)) - current.request.rejection = { ...checkpoint, reason: bounded(error.message, 4000) }; - } else this.rejectWorkerDelivery(worker, action, submission, error); - this.input.emit('delivery_rejected', { workerId: worker.id, reason: error.message }); - }; - try { - for (const log of [assignmentDeliveryFile(action.assignment), 'DELIVERIES.jsonl']) { - const scoped = log !== 'DELIVERIES.jsonl', key = scoped ? `${worker.id}/${log}` : worker.id; - for (const entry of pendingDeliveryLines(path.join(worker.worktree, log), cursors, key, () => { advanced = true; })) { - this.input.signal.throwIfAborted(); - if (entry.error) reject(entry.error, `${key}:${entry.offset}:${entry.error}`); - else if (entry.line?.trim()) { - let value: unknown; - try { value = JSON.parse(entry.line); } - catch { reject('math_delivery_invalid_json', entry.line); } - if (value !== undefined) { - try { await this.receive(worker, action, value, scoped); } - catch (error) { - this.input.signal.throwIfAborted(); - if (!(error instanceof Error) || !invalidInput.has(rejectionCode(error))) throw error; - reject(error, entry.line, (value as { kind?: unknown })?.kind === 'checkpoint' ? { file: log, offset: entry.offset } : undefined); - } - } - } - } - } - } finally { - if (advanced) { - if (research.contextCheckpoint?.rejection !== checkpointRejection) this.changed(); - else this.input.save(); - } - } - this.notifyContextCheckpointRejection(worker, action); - await this.notifyDeliveryReceipts(worker, action); - } - private async receive(worker: ResearchWorker, action: Extract, value: any, scoped = false) { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('math_delivery_invalid'); - const assignmentKey = assignmentDeliveryFile(action.assignment); - const automaticId = scoped ? mathDigest(canonicalMathJson({ file: assignmentKey, value })) : undefined; - if (scoped) value = { id: automaticId, kind: 'progress', taskId: action.task.id, - taskDigest: action.assignment.taskDigest, ...value }; - if (value.kind === 'helpers') { - const declarations = helperNominationsSchema.safeParse(value.declarations); - if (!scoped || value.taskId !== action.task.id || value.taskDigest !== action.assignment.taskDigest || - worker.id !== action.assignment.workerId || isFeasibilityReview(action.task) || isFinalCandidateReview(action.task) || - !declarations.success || typeof value.summary !== 'string' || value.summary.length > 3000) - throw new Error('math_delivery_invalid'); - if (!this.current(action)) return; - const problem = this.input.state.problem, head = git(worker.worktree, ['rev-parse', 'HEAD']); - // Freeze the bytes without staging in the writer's index or changing its checkout. - let commit: string; - try { - const files = problem.ownedFiles.map(file => { - const relative = path.join(problem.projectRelative, file); - const source = path.join(worker.worktree, relative); - assertMathCanonicalPath(source); - return { relative, bytes: readMathFile(source, 4 * 1024 * 1024).bytes }; - }); - commit = await withSolverWorktree(worker.worktree, head, async checkout => { - for (const { relative, bytes } of files) fs.writeFileSync(path.join(checkout, relative), bytes); - assertSolverSources(problem, checkout); - return commitSolverProjection(problem, checkout, 'Freeze standalone helper submission'); - }); - } catch (error) { - this.input.signal.throwIfAborted(); - this.input.emit('incremental_helpers_rejected', { workerId: worker.id, taskId: action.task.id, - reason: error instanceof Error ? error.message : 'math_helper_snapshot_failed' }); - return; - } - await this.integrateWorkerHelpers(worker, action, commit, declarations.data, value.summary); - return; - } - if (value.kind === 'research') { - const misplaced = ['mathematicalGap', 'lemmaRequests', 'blockers'].filter(key => Object.hasOwn(value, key)); - if (misplaced.length) throw new ResearchAdmissionError({ status: 'rejected', code: 'math_research_delivery_invalid', - recovery: 'correct-and-resubmit', issues: misplaced.map(key => ({ path: key, - message: `Move ${key} inside finding.${key}; research events publish the complete nested finding. Remove the outer field.` })) }); - } - const details = deliveryDetails(value); - if (!value || typeof value.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/u.test(value.id) || - !['progress', 'proof', 'research', 'ready', 'checkpoint'].includes(value.kind) || value.taskId !== action.task.id || value.taskDigest !== action.assignment.taskDigest) throw new Error('math_delivery_invalid'); - await this.retainGuidanceDecisions(worker, action, value.guidanceDecisions); - if (value.kind === 'checkpoint') { - if (!scoped || !this.current(action) || worker.id !== action.assignment.workerId) throw new Error('math_delivery_invalid'); - const research = this.input.state.workers?.find(record => record.id === worker.id) ?? this.input.state; - acceptContextCheckpoint(research, worker.worktree, value); - this.input.emit('context_checkpoint_published', { workerId: worker.id, threadId: research.threadId, - requestId: value.requestId, notesDigest: value.notesDigest }); - this.input.save(); - return; - } - if (value.kind === 'ready') { - if (!scoped || advisory(action.task)) throw new Error('math_delivery_invalid'); - // The host freezes the saved sources itself, so a ready event cannot name what to check. - const named = ['commit', 'targets'].filter(field => value[field] !== undefined); - if (named.length) throw new ResearchAdmissionError({ status: 'rejected', code: 'math_delivery_invalid', - issues: named.map(field => ({ path: field, message: `Omit ${field} from a ready event; the host checks the saved sources of the assigned declaration.` })), - recovery: 'correct-and-resubmit' }); - this.receiveProofReady(worker, action, value.id); - return; - } - // Legacy automatic ids already bind the assignment; unscoped old ids cannot identify a new seed. - const duplicate = this.archive.deliveries?.find(record => record.producer === worker.id && - (record.submissionId === value.id || record.submissionAliases?.includes(value.id)) && - record.taskId === action.task.id && record.taskDigest === action.assignment.taskDigest && - (record.assignmentKey === assignmentKey || record.assignmentKey === undefined && scoped && value.id === automaticId)); - if (duplicate) { - const replayed = this.node(action.task.id); - const resumable = replayed?.assignment === action.assignment && duplicate.status !== 'superseded' && - this.proofDeliveryCurrent(replayed) && - (duplicate.commit === replayed.proof?.commit || duplicate.commit === replayed.integratedCheck?.commit); - if (value.kind === 'proof' && duplicate.kind === 'proof' && (this.current(action) || resumable)) { - await this.settleProofDeliveries(annotations => this.queueIntegration(async () => { - const node = this.node(action.task.id); - // Resume the accepted submission, never a changed commit in the replayed line. - if (node?.assignment === action.assignment && duplicate.status !== 'superseded' && - (duplicate.commit === node.proof?.commit || duplicate.commit === node.integratedCheck?.commit)) { - const annotate = await this.publishProofDelivery(node); - if (annotate) annotations.push(annotate); - } - await this.integrateReadyNow(annotations); - })); - } - return; - } - if (!this.current(action)) { - this.record(worker, action.task, value.kind, 'superseded', details.summary, { ...details, submissionId: value.id, assignmentKey, - taskDigest: action.assignment.taskDigest, premises: action.task.premises ?? [], dependencies: action.assignment.dependencies ?? [], - remainingObligations: details.remainingObligations ?? [] }); - return; - } - const node = this.node(action.task.id); - if (value.kind === 'research') { - if (value.sources !== undefined && value.commit !== undefined) - throw new ResearchAdmissionError({ status: 'rejected', code: 'math_delivery_invalid', - issues: [{ path: 'sources', message: 'Use either an explicit source snapshot or a fixed supporting commit, not both.' }], - recovery: 'correct-and-resubmit' }); - const base = value.commit ?? action.assignment.seedCommit; - if (typeof base !== 'string' || !/^[a-f0-9]{40,64}$/u.test(base)) throw new Error('math_delivery_invalid_commit'); - const fixed = mathGitResult(worker.worktree, ['merge-base', '--is-ancestor', action.assignment.seedCommit, base], { maxBuffer: 4096 }); - if (fixed.error) throw fixed.error; - if (fixed.status !== 0) throw new Error('math_delivery_invalid_commit'); - const supportingArtifacts = value.commit ? captureDeliveryArtifacts({ problem: this.input.state.problem, - worktree: worker.worktree, commit: base, assignment: action.assignment }) : undefined; - await this.publishResearchFinding(worker, action, base, { kind: 'event', value: value.finding }, - { submissionId: value.id, assignmentKey, ...(supportingArtifacts ? { artifacts: supportingArtifacts } : {}) }, value.sources, value.probes); - return; - } - if (value.kind === 'progress') { - const searchAssignment = details.searchCheckpoint && this.proofSearchAssignment(action); - const search = searchAssignment && retainProofSearchCheckpoint({ - ...searchAssignment, - projectRoot: path.join(worker.worktree, this.input.state.problem.projectRelative), - runDirectory: path.dirname(this.lead.worktree), reference: details.searchCheckpoint!, - workerId: worker.id, assignmentKey, - }); - const latestSearch = search && latestProofSearchRecord(this.archive.proofSearchRecords?.[action.task.id], search); - if (details.mathematicalGap) bindMathematicalGap(details.mathematicalGap, node.task, this.archive, - { problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest }); - this.reportBlockers(node.task, value.blockers); - const remaining = [...new Set([...(value.remainingObligations ?? []), - ...this.dependencies(node.task).filter(dependency => !['integrated', 'completed'].includes(dependency.status)).map(dependency => dependency.task.id)])] as string[]; - if (value.needsDecision === true) this.wakeLead('progress-decision-requested'); - if (latestSearch) { - (this.archive.proofSearchRecords ??= {})[action.task.id] = latestSearch; - this.input.emit('proof_search_checkpoint_saved', { taskId: latestSearch.taskId, taskDigest: latestSearch.taskDigest, - workerId: worker.id, basisDigest: latestSearch.basisDigest, generation: latestSearch.generation, - checkpoint: latestSearch.checkpoint, proofAcceptance: 'not-accepted' }); - } - this.record(worker, node.task, 'progress', remaining.length || node.task.kind === 'sketch' ? 'conditional' : 'advisory', details.summary, - { ...details, ...(search ? { searchCheckpoint: search.checkpoint } : {}), - submissionId: value.id, assignmentKey, remainingObligations: remaining }); - return; - } - if (advisory(node.task) || typeof value.commit !== 'string' || !/^[a-f0-9]{40,64}$/u.test(value.commit)) throw new Error('math_delivery_requires_fixed_proof'); - if (!taskCanStart(node.task, this.archive.tasks)) throw new Error('math_delivery_unfinished_dependencies'); - this.input.signal.throwIfAborted(); - const fixed = mathGitResult(worker.worktree, ['rev-parse', '--verify', '--quiet', `${value.commit}^{commit}`], { maxBuffer: 4096 }); - if (fixed.error) throw fixed.error; - if (fixed.status === 1) throw new Error('math_delivery_invalid_commit'); - if (fixed.status !== 0) throw new Error('math_delivery_commit_unavailable'); - const ancestry = mathGitResult(worker.worktree, - ['merge-base', '--is-ancestor', this.input.state.problem.baseCommit, value.commit], { maxBuffer: 4096 }); - if (ancestry.error) throw ancestry.error; - if (ancestry.status === 1) throw new Error('math_delivery_invalid_commit'); - if (ancestry.status !== 0) throw new Error('math_delivery_commit_unavailable'); - try { - await this.publishTaskProof(worker, action, value.commit, details.summary, - { submissionId: value.id, assignmentKey, evidenceRefs: value.evidenceRefs }); - } catch (error) { - if (error instanceof Error && /^math_task_(?:missing_declaration|repeated_failed_input)\n/u.test(error.message) && this.current(action)) { - this.rejected(action, error.message, value.commit); return; - } - throw error; - } - } -} diff --git a/src/solver/cooperationIntegration.ts b/src/solver/cooperationIntegration.ts deleted file mode 100644 index 29994747..00000000 --- a/src/solver/cooperationIntegration.ts +++ /dev/null @@ -1,733 +0,0 @@ -import crypto from 'node:crypto'; -import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { committedSource, commitSolverSources, withSolverWorktree } from './problem'; -import { solverProofFeedback } from './feedback'; -import { taskDependenciesReady } from './modules/search'; -import { applyTaskChanges, checkTaskProof, checkTaskProofs, createTaskSourceProjector, isAttributedTaskProof, type TaskProof } from './cooperativeProof'; -import { hasDeterministicLeanFailure, hasLeanResourceLimitFailure } from './proofReuse'; -import { proofReferencesUnchanged } from './proofReferences'; -import { attributeTaskReferences } from './taskReferenceAttribution'; -import { hasTaskConnectionCheck } from './taskConnections'; -import { assignmentDeliveryFile, assumableLemma, taskGroup, taskReferenceDependencies, hasTaskAcceptance, type CooperativeTask, type TaskAssignment, type TaskRecord } from './tasks'; -import { digest, taskSourceRejections, integrationRejections, rejectionCode, bounded } from './cooperationShared'; -import { CooperationTaskProofs, type ProofDeliveryAnnotation, type ProofDeliveryState } from './cooperationTaskProofs'; -import { reusableFreshConditionalCheck } from './freshContinuationChecks'; -import type { ResearchWorker } from './modules/organization'; -import { VerifierFailureError } from './verifierFailure'; -import { IncrementalHelperRejection, landVerifiedHelpers, type HelperNomination } from './incrementalHelpers'; - -const recheckBatchFallbacks = new Set([...taskSourceRejections, 'math_task_batch_projection_mismatch', 'math_task_missing_declaration', - 'math_task_batch_resource_limit']); -const integrationBatchFallbacks = new Set([...taskSourceRejections, 'math_task_integration_conflict', 'math_task_integration_missing_context', - 'math_task_integration_missing_declaration', 'math_task_batch_projection_mismatch', 'math_task_batch_resource_limit']); -function verifierFailure(stage: string, proof?: TaskProof, task?: CooperativeTask) { - return new VerifierFailureError({ stage, taskId: task?.id, taskDigest: proof?.taskDigest, - sourceCommit: proof?.commit, seedCommit: proof?.seedCommit, projectionMode: proof?.projectionMode ?? 'full', - conditions: proof?.conditions, verification: proof?.verification }); -} -/** A changed check identity leaves no usable verifier result; aborts and unlisted failures propagate. */ -function expectedRejection(error: unknown, expected: ReadonlySet): Error { - if (error instanceof Error && rejectionCode(error) === 'math_task_check_identity_changed') - throw new Error('math_verifier_unavailable', { cause: error }); - if (!(error instanceof Error) || error.name === 'AbortError' || !expected.has(rejectionCode(error))) throw error; - return error; -} - -/** Integration of checked task proofs into the canonical commit and their rechecks. */ -export abstract class CooperationIntegration extends CooperationTaskProofs { - protected integrateWorkerHelpers(worker: ResearchWorker, action: Extract, - sourceCommit: string, declarations: HelperNomination[], summary: string) { - return this.queueIntegration(async () => { - const current = () => !this.stopping && !this.input.signal.aborted && this.current(action); - const state = this.input.state; - const environmentDigest = state.environmentDigest, problemReceiptDigest = state.problem.receiptDigest; - while (current() && state.environmentDigest === environmentDigest && state.problem.receiptDigest === problemReceiptDigest) { - const expectedCommit = this.archive.canonicalCommit!; - const eligible = ({ file, name }: HelperNomination) => worker.ownedFiles.includes(file) && - !this.archive.tasks.some(({ task }) => task.proofPath === file && task.theoremName === name); - let result: Awaited>; - try { - result = await landVerifiedHelpers({ - state, sourceWorktree: worker.worktree, sourceCommit, seedCommit: action.assignment.seedCommit, - worktree: this.lead.worktree, expectedCommit, declarations, allowHelper: eligible, - env: this.input.access.get(this.lead.id)!.environment, signal: this.input.signal, timeoutMs: this.input.timeoutMs, - }); - } catch (error) { - if (!(error instanceof IncrementalHelperRejection)) throw error; - this.input.emit('incremental_helpers_rejected', { workerId: worker.id, taskId: action.task.id, reason: error.message }); - const active = this.active.get(worker.id); - if (current() && active?.action === action) - void active.notify('Helper submission rejected: ' + error.message, { mode: 'advisory' }).catch(() => {}); - return; - } - if (!current() || state.environmentDigest !== environmentDigest || state.problem.receiptDigest !== problemReceiptDigest) return; - if (this.archive.canonicalCommit !== expectedCommit) continue; - if (!result.helpers.length || !result.helpers.every(helper => eligible({ file: helper.file, name: helper.qualifiedName }))) return; - this.pin(result.commit); - this.archive.canonicalCommit = result.commit; - (this.archive.landedHelpers ??= []).push(...result.helpers.map(helper => ({ ...helper, producer: worker.id }))); - this.changed(); - this.input.emit('incremental_helpers_landed', { workerId: worker.id, taskId: action.task.id, - commit: result.commit, declarations: result.helpers.map(helper => helper.qualifiedName), summary }); - const message = `Verified ${result.helpers.length} canonical helpers at ${result.commit}. Available in the next seeded worktree. ` + - 'Read landedHelpers in COOPERATION.json for the signature index.\n' + - result.helpers.slice(0, 8).map(helper => `${helper.type.slice(0, 240)} (${helper.file})`).join('\n'); - for (const active of this.active.values()) { - if (!active.cancelled && this.current(active.action)) - void active.notify(message, { mode: 'advisory' }).catch(() => {}); - } - return; - } - }); - } - private canonicalCheckAssignment(task: CooperativeTask, seedCommit: string, tasks: readonly TaskRecord[]): TaskAssignment { - return { taskId: task.id, taskDigest: digest(task), workerId: this.lead.id, seedCommit, - dependencies: this.dependencies(task, tasks).map(node => ({ taskId: node.task.id, taskDigest: digest(node.task) })) }; - } - protected queueIntegration(operation: () => Promise, worker?: ResearchWorker, task?: CooperativeTask): Promise { - const queuedAt = Date.now(); - const waiting = this.integrationQueueDepth++ > 0 && worker && task; - if (waiting) this.recordDispatchWait(worker, { stage: 'integration-queue', candidateCount: 1, omittedCandidates: 0, - candidates: [{ taskId: task.id, taskDigest: digest(task), reason: 'integration-queue' }] }); - this.refreshPlanApproval(); - const pending = this.integrationQueue.then(async () => { - if (waiting) { this.clearDispatchWait(worker, 'selected'); this.changed(); } - this.input.signal.throwIfAborted(); - this.input.emit('integration_queue_started', { waitedMs: Date.now() - queuedAt }); - return await operation(); - }).finally(() => { this.integrationQueueDepth--; this.wake(); }); - this.integrationQueue = pending.then(() => {}, () => {}); - return pending; - } - protected integrateReady() { - return this.settleProofDeliveries(annotations => this.queueIntegration(() => this.integrateReadyNow(annotations))); - } - protected async integrateReadyNow(annotations: ProofDeliveryAnnotation[] = []) { - for (;;) { - // A parent can reach canonical acceptance before a later snapshot or publication fails. - const unpublished = this.archive.tasks.find(item => !this.synchronizationBlocked(item.task) && item.status === 'integrated' && this.proofDeliveryCurrent(item) && item.proof && item.assignment && - item.integratedCheck?.passed && item.integratedCheck.taskDigest === digest(item.task) && this.checkedDeliveries.has(item.integratedCheck) && - !this.archive.deliveries?.some(record => record.taskId === item.task.id && record.taskDigest === digest(item.task) && - record.kind === 'proof' && record.status === 'verified' && - (record.commit === item.proof!.commit || record.commit === item.integratedCheck!.commit) && - !this.pendingProofDeliveryRecords.has(record))); - if (unpublished) { - const receipt = unpublished.integratedCheck, version = digest(unpublished.task); - const publication = this.proofDeliveryState(unpublished); - await this.syncPreparedStatements(); - if (this.archive.tasks.includes(unpublished) && unpublished.status === 'integrated' && - unpublished.integratedCheck === receipt && digest(unpublished.task) === version) { - const annotate = await this.publishProofDelivery(unpublished, undefined, publication); - if (annotate) annotations.push(annotate); - } - continue; - } - const node = this.archive.tasks.find(item => ['delivered', 'conditional'].includes(item.status) && this.integrationAllowed(item) && - taskDependenciesReady(item.task, this.archive.tasks)); - if (!node) return; - const publication = await this.integrateNow(node); - if (publication) { - const annotate = await this.publishProofDelivery(node, undefined, publication); - if (annotate) annotations.push(annotate); - } - } - } - protected synchronizationPending() { - return Boolean(this.planSynchronization || this.preparingStatements || this.archive.tasks.some(node => node.pendingValidation)); - } - protected candidateSynchronizationBlocked() { - const required = this.fixedStatementReviewTasks(); - return this.archive.tasks.some(node => (node.task.kind === 'goal' || required?.has(node.task.id)) && - this.synchronizationBlocked(node.task)); - } - protected markPendingValidation(nodes: readonly TaskRecord[], proofs: ReadonlySet = new Set()) { - for (const node of nodes) node.pendingValidation = { id: crypto.randomUUID(), taskDigest: digest(node.task), - canonicalCommit: this.archive.canonicalCommit!, environmentDigest: this.input.state.environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest, - ...(proofs.has(node.task.id) || node.pendingValidation?.proof ? { proof: true } : {}) }; - } - protected schedulePlanSynchronization(): Promise { - if (this.planSynchronization) return this.planSynchronization; - const pending = this.synchronizePlan(); - this.planSynchronization = pending; this.planSynchronizations.add(pending); - this.refreshPlanApproval(); - void pending.catch(error => { - if (!this.input.signal.aborted) { this.failure = error instanceof Error ? error : new Error(String(error)); this.changed(); } - }).finally(() => { - this.planSynchronizations.delete(pending); - if (this.planSynchronization === pending && !this.failure) this.planSynchronization = undefined; - if (!this.failure && !this.input.signal.aborted && (this.archive.tasks.some(node => node.pendingValidation) || - this.archive.edits?.some(edit => edit.status === 'applied' && edit.pendingSync))) this.schedulePlanSynchronization(); - this.wake(); - }).catch(() => {}); - return pending; - } - private async synchronizePlan() { - for (;;) { - const snapshot = await this.input.exclusiveCheck(async () => { - const targets = this.archive.tasks.filter(node => node.pendingValidation).map(node => ({ node, validation: node.pendingValidation! })); - const edits = (this.archive.edits ?? []).filter(edit => edit.status === 'applied' && edit.pendingSync); - if (!targets.length && !edits.length) return; - return { canonical: this.archive.canonicalCommit!, environmentDigest: this.input.state.environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest, - environment: { ...this.input.access.get(this.lead.id)!.environment }, targets, edits, - inputs: new Map(this.archive.tasks.map(node => [node.task.id, { node, taskDigest: digest(node.task), - status: node.status, proof: node.proof, integratedCheck: node.integratedCheck, pendingValidation: node.pendingValidation }])), - tasks: this.archive.tasks.map(node => ({ ...node, pendingValidation: undefined })) }; - }); - if (!snapshot) return; - const ids = new Set(snapshot.targets.filter(item => item.validation.proof).map(item => item.node.task.id)); - const fresh = snapshot.targets.some(item => item.validation.proof && item.node.integratedCheck && - !this.checkedDeliveries.has(item.node.integratedCheck)); - const current = () => this.archive.canonicalCommit === snapshot.canonical && - this.input.state.environmentDigest === snapshot.environmentDigest && - this.input.state.problem.receiptDigest === snapshot.problemReceiptDigest && - snapshot.targets.every(({ node, validation }) => this.archive.tasks.includes(node) && - node.pendingValidation === validation && digest(node.task) === validation.taskDigest); - const rechecked = await this.recheckIntegrated(snapshot.canonical, !fresh, { tasks: snapshot.tasks, ids, - environment: snapshot.environment, environmentDigest: snapshot.environmentDigest, current }); - if (rechecked && current()) { - const statements = this.prepareStatementContexts(snapshot.tasks, snapshot.canonical, - { environment: snapshot.environment, digest: snapshot.environmentDigest, current }); if (statements) await statements; - } - await this.input.exclusiveCheck(async () => { - this.input.signal.throwIfAborted(); - if (this.archive.canonicalCommit !== snapshot.canonical || this.input.state.environmentDigest !== snapshot.environmentDigest || - this.input.state.problem.receiptDigest !== snapshot.problemReceiptDigest) { - const current = snapshot.targets.filter(({ node, validation }) => this.archive.tasks.includes(node) && node.pendingValidation === validation); - this.markPendingValidation(current.map(item => item.node), ids); - this.input.emit('plan_recheck_rebased', { from: snapshot.canonical, to: this.archive.canonicalCommit, - taskIds: current.map(item => item.node.task.id) }); - this.changed(); return; - } - // An obsolete snapshot may still contain old receipts for targets not reached by the recheck. - if (!rechecked || !current()) return; - const inputCurrent = (id: string) => { - const baseline = snapshot.inputs.get(id), current = this.node(id); - return baseline && current === baseline.node && digest(current.task) === baseline.taskDigest && - current.status === baseline.status && current.proof === baseline.proof && current.integratedCheck === baseline.integratedCheck && - current.pendingValidation === baseline.pendingValidation; - }; - const dependencies = new Map(snapshot.targets.map(({ node }) => { - const checked = snapshot.tasks.find(item => item.task.id === node.task.id)!; - return [node.task.id, [...new Set([...this.dependencies(checked.task, snapshot.tasks).map(item => item.task.id), - ...(checked.integratedCheck?.references?.tasks?.map(reference => reference.taskId) ?? [])])]]; - })); - const publishable = new Set(snapshot.targets.filter(({ node, validation }) => inputCurrent(node.task.id) && - node.pendingValidation === validation && digest(node.task) === validation.taskDigest && - dependencies.get(node.task.id)!.every(inputCurrent)).map(({ node }) => node.task.id)); - for (;;) { - const invalid = [...publishable].filter(id => dependencies.get(id)!.some(dependency => - snapshot.inputs.get(dependency)?.pendingValidation && !publishable.has(dependency))); - if (!invalid.length) break; - for (const id of invalid) publishable.delete(id); - } - for (const { node, validation } of snapshot.targets) { - if (!this.archive.tasks.includes(node) || node.pendingValidation !== validation) continue; - if (!publishable.has(node.task.id)) { this.markPendingValidation([node], ids); continue; } - const checked = snapshot.tasks.find(item => item.task.id === node.task.id)!; - if (ids.has(node.task.id)) { - node.integratedCheck = checked.integratedCheck; this.moveTask(node, checked.status, 'integrated'); node.feedback = checked.feedback; - if (node.status === 'blocked') this.wakeLead('integration-blocked'); - } - delete node.pendingValidation; - } - this.syncStatementReviews(); - for (const edit of snapshot.edits) if (!edit.recheck?.tasks.some(result => { - const current = this.node(result.taskId); - return current?.pendingValidation && digest(current.task) === result.taskDigest; - })) edit.pendingSync = undefined; - this.input.emit('task_contract_sources_revalidated', { taskIds: [...ids].filter(id => !this.node(id)?.pendingValidation) }); - this.changed(); - }); - await this.integrateReady(); - } - } - private async recheckIntegrated(canonical: string, changedOnly = false, snapshot?: { tasks: TaskRecord[]; ids: ReadonlySet; - environment: NodeJS.ProcessEnv; environmentDigest: string; current: () => boolean }) { - // Persisted receipts and receipts for different sources cannot authorize dependent dispatch. - const tasks = snapshot?.tasks ?? this.archive.tasks; - const pending = tasks.filter(node => node.status === 'integrated' && (!snapshot || snapshot.ids.has(node.task.id))); - const selected = new Set(pending.map(node => node.task.id)); - const checked = new Set(); - const batched = new Map(); - const batchAttempted = new Set(); - // Phase-local receipts bind the fixed canonical, environment and task version. - // Restored integrated labels cannot authorize original-goal context. - const freshGoals = new Map(); - const retryable = new Map(); - const retried = new Set(); - const availableGoals = (node: TaskRecord) => tasks.filter(item => item.task.kind === 'goal' && - item.task.id !== node.task.id && item.status === 'integrated' && - freshGoals.get(item.task.id) === digest(item.task)); - const extraGoals = (node: TaskRecord) => { - const available = availableGoals(node); - if (retried.has(node) || !available.length) return available.map(item => item.task.theoremName!); - const inputs = new Set(this.sourceGoalInputs(node.task, tasks, this.lead.worktree, canonical).map(input => input.task.id)); - return available.filter(item => inputs.has(item.task.id)).map(item => item.task.theoremName!); - }; - const request = (node: TaskRecord) => ({ task: node.task, - assignment: this.canonicalCheckAssignment(node.task, canonical, tasks), - retainedGoals: [...new Set([...this.retainedTaskGoals(node.task, tasks, this.lead.worktree, canonical), ...extraGoals(node)])] }); - const prerequisites = new Map(pending.map(node => [node.task.id, [...new Set([ - ...this.dependencies(node.task, tasks).map(item => item.task.id), - ...this.sourceGoalInputs(node.task, tasks, this.lead.worktree, canonical).map(item => item.task.id) ])]])); - const ready = (node: TaskRecord) => prerequisites.get(node.task.id)!.every(id => !selected.has(id) || - tasks.find(item => item.task.id === id)?.status !== 'integrated' || checked.has(id)); - const projections = new Map(); - const projection = (node: TaskRecord, receipt?: TaskProof) => { - const retainedGoals = request(node).retainedGoals; - const compact = receipt?.projectionMode === 'compact'; - const preserved = compact ? receipt.changes : []; - const key = canonicalMathJson({ taskDigest: digest(node.task), retainedGoals, compact, preserved }); - let value = projections.get(key); - if (value === undefined) { - try { - const projector = this.sourceProjector(this.lead.worktree, canonical, compact, preserved); - value = mathDigest(canonicalMathJson([...projector(node.task, retainedGoals)])); - } catch (error) { value = error instanceof Error ? error : new Error(String(error)); } - projections.set(key, value); - } - if (value instanceof Error) throw value; - return value; - }; - const checkedProjections = new Map(); - const reusable = (node: TaskRecord) => { - const receipt = node.integratedCheck, references = receipt?.references; - if (!(changedOnly || snapshot) || !receipt?.passed || receipt.conditions?.length || - receipt.taskDigest !== digest(node.task) || !this.checkedDeliveries.has(receipt) || !hasTaskAcceptance(receipt) || - !references || references.environmentDigest !== (snapshot?.environmentDigest ?? this.input.state.environmentDigest) || - !taskDependenciesReady(node.task, tasks)) return false; - if (taskReferenceDependencies(node) && proofReferencesUnchanged(this.input.state.problem, this.lead.worktree, canonical, references, - snapshot?.environmentDigest ?? this.input.state.environmentDigest)) return true; - // Only the process-local acceptance gates above authorize this receipt's mode. - // A compact receipt must be compared with its compact projection, retaining - // every changed declaration that was checked with the delivery. - const commit = receipt.verification.targetCommit; - if (!commit) return false; - let checked = checkedProjections.get(commit); - if (checked === undefined) { - checked = mathDigest(canonicalMathJson(this.input.state.problem.ownedFiles.map(file => [file, - committedSource(this.lead.worktree, commit, `${this.input.state.problem.projectRelative}/${file}`)]))); - checkedProjections.set(commit, checked); - } - return projection(node, receipt) === checked; - }; - const progress = { canonicalCommit: canonical, total: pending.length, completed: 0, taskId: undefined as string | undefined }; - const persistProgress = async () => { - const publish = async () => { - if (snapshot && !snapshot.current()) return; - this.archive.recheck = { ...progress }; this.input.save(); - }; - if (snapshot) await this.input.exclusiveCheck(publish); - else await publish(); - }; - await persistProgress(); - const finish = async (node: TaskRecord, receipt?: TaskProof) => { - if (!checked.has(node.task.id)) { checked.add(node.task.id); progress.completed++; } - progress.taskId = undefined; - if (node.status === 'integrated' && node.task.kind === 'goal' && node.integratedCheck?.passed && - !node.integratedCheck.conditions?.length && this.checkedDeliveries.has(node.integratedCheck) && - hasTaskAcceptance(node.integratedCheck)) freshGoals.set(node.task.id, digest(node.task)); - this.input.emit('task_recheck_finished', { ...progress, taskId: node.task.id, passed: node.status === 'integrated', - commit: receipt?.commit, taskDigest: receipt?.taskDigest, ...(snapshot ? { staged: true } : {}) }); - await persistProgress(); - }; - while (pending.length || retryable.size) { - this.input.signal.throwIfAborted(); - if (snapshot && !snapshot.current()) return false; - if (!pending.length) { - for (const [node, previousGoals] of retryable) { - retryable.delete(node); - if (retried.has(node) || !availableGoals(node).some(item => !previousGoals.includes(item.task.theoremName!))) continue; - retried.add(node); pending.push(node); - this.input.emit('task_recheck_context_retry', { taskId: node.task.id, canonicalCommit: canonical, - retainedGoals: request(node).retainedGoals, ...(snapshot ? { staged: true } : {}) }); - } - if (!pending.length) break; - } - const index = pending.findIndex(ready); - if (index < 0) throw new Error('math_plan_dependency_cycle'); - const [node] = pending.splice(index, 1); - progress.taskId = node.task.id; - this.input.emit('task_recheck_started', { ...progress }); await persistProgress(); - this.input.signal.throwIfAborted(); - if (snapshot && !snapshot.current()) return false; - const assignment = this.canonicalCheckAssignment(node.task, canonical, tasks); - let savedReceipt: TaskProof | undefined; - try { - if (reusable(node)) { - node.feedback = undefined; - const receipt = node.integratedCheck!; - this.input.emit('task_check_reused', { taskId: node.task.id, passed: receipt.passed, - commit: receipt.commit, taskDigest: receipt.taskDigest, canonicalCommit: canonical }); - await finish(node, receipt); continue; - } - if (!batchAttempted.has(node) && (this.input.modules.M2.checkTask ?? checkTaskProof) === checkTaskProof) { - const source = projection(node); - const group = [node, ...pending.filter(item => { - if (batchAttempted.has(item) || !ready(item)) return false; - try { return !reusable(item) && projection(item) === source; } catch { return false; } - })].slice(0, 32); - if (group.length > 1) { - group.forEach(item => batchAttempted.add(item)); - this.input.emit('task_recheck_batch_started', { taskIds: group.map(item => item.task.id) }); - try { - const requests = group.map(request); - const proofs = await checkTaskProofs(this.input.state.problem, this.lead.worktree, canonical, requests, - snapshot?.environment ?? this.input.access.get(this.lead.id)!.environment, this.input.signal, this.input.timeoutMs, - snapshot?.environmentDigest ?? this.input.state.environmentDigest, this.taskProofCache); - this.input.signal.throwIfAborted(); - if (proofs.some(proof => hasLeanResourceLimitFailure(proof.verification))) throw new Error('math_task_batch_resource_limit'); - const failed = proofs.find(proof => ['unavailable', 'blocked'].includes(proof.verification.status) || !isAttributedTaskProof(proof)); - if (failed) throw verifierFailure('integrated-batch-recheck', failed); - if (snapshot && !snapshot.current()) return false; - group.forEach((item, index) => { - const proof = proofs[index]; - if (!proof) throw verifierFailure('integrated-batch-missing-receipt', undefined, item.task); - // A failed shared compilation cannot identify a bad member. Leave - // failed views to the ordinary single-target compact/full check. - if (proof.passed) batched.set(item, { proof, source, retainedGoals: canonicalMathJson(requests[index].retainedGoals) }); - }); - } catch (error) { - this.input.signal.throwIfAborted(); - const rejected = expectedRejection(error, recheckBatchFallbacks); - if (snapshot && !snapshot.current()) return false; - this.input.emit('task_recheck_batch_fallback', { taskIds: group.map(item => item.task.id), reason: bounded(rejected.message, 1000) }); - } - } - } - // Earlier batch members can invalidate goals retained by a later member. - // Recheck its current projection instead of submitting an obsolete receipt. - const prepared = batched.get(node); - const checkedProof = prepared && prepared.source === projection(node) && - prepared.retainedGoals === canonicalMathJson(request(node).retainedGoals) ? prepared.proof : undefined; - const beforeGoals = request(node).retainedGoals; - const receipt = await this.check(node.task, assignment, this.lead.worktree, canonical, [], checkedProof, false, false, tasks, - snapshot && { environment: snapshot.environment, digest: snapshot.environmentDigest }, extraGoals(node)); - this.input.signal.throwIfAborted(); - if (['unavailable', 'blocked'].includes(receipt.verification.status)) throw verifierFailure('integrated-task-recheck', receipt, node.task); - if (snapshot && !snapshot.current()) return false; - savedReceipt = node.integratedCheck = receipt; - if (!receipt.passed && !retried.has(node) && !receipt.conditions?.length && - hasDeterministicLeanFailure(receipt.verification)) retryable.set(node, beforeGoals); - if (!receipt.passed) { this.moveTask(node, 'blocked', 'invalidated'); node.feedback = solverProofFeedback(receipt); if (!snapshot) this.wakeLead('integration-blocked'); } - // A kernel-checked original can supply concrete source context even when - // an earlier helper projection failed. Settle graph readiness after the - // bounded recovery pass, before this snapshot can be published. - else { this.moveTask(node, 'integrated', 'integrated'); node.feedback = undefined; } - } catch (error) { - this.input.signal.throwIfAborted(); - const rejected = expectedRejection(error, integrationRejections); - if (snapshot && !snapshot.current()) return false; - this.moveTask(node, 'blocked', 'invalidated'); node.feedback = rejected.message; if (!snapshot) this.wakeLead('integration-blocked'); - } - await finish(node, savedReceipt); - } - this.input.signal.throwIfAborted(); - if (snapshot && !snapshot.current()) return false; - // Fresh receipts can reveal inputs absent from the planned graph, including - // restored receipts that could not authorize an earlier dependency order. - for (const node of tasks) if (selected.has(node.task.id) && node.status === 'integrated' && - !taskDependenciesReady(node.task, tasks)) { - this.moveTask(node, 'blocked', 'invalidated'); node.feedback = 'math_task_dependency_invalidated'; - if (!snapshot) this.wakeLead('integration-blocked'); - this.input.emit('task_recheck_dependency_invalidated', { ...progress, taskId: node.task.id, ...(snapshot ? { staged: true } : {}) }); - } - return !snapshot || snapshot.current(); - } - protected async recheckConditional() { - for (const node of this.archive.tasks.filter(node => node.status === 'conditional')) { - const group = this.archive.groups?.find(record => record.group.id === taskGroup(node.task)); - if ((node.task.status ?? 'active') !== 'active' || group && group.group.status !== 'active') continue; - const saved = node.proof; - let savedReceipt: TaskProof | undefined; - this.input.emit('task_conditional_recheck_started', { taskId: node.task.id }); - try { - if (!(node.task.conditional || node.assignment && hasTaskConnectionCheck(node.task, node.assignment)) || - !saved?.passed || saved.taskDigest !== digest(node.task) || - !saved.conditions?.length || !node.assignment) throw new Error('math_task_condition_version_invalid'); - const conditions = saved.conditions.map(condition => { - const input = this.node(condition.taskId); - if (!input || !assumableLemma(input.task) || digest(input.task) !== condition.taskDigest) - throw new Error('math_task_condition_version_invalid'); - return input.task; - }); - const proof = await withSolverWorktree(this.lead.worktree, saved.commit, async checkout => { - const checked = (this.input.modules.M2.checkTask ?? checkTaskProof) === checkTaskProof && - this.input.freshContinuationChecks?.includes(saved) && reusableFreshConditionalCheck(saved, { - task: node.task, assignment: node.assignment!, conditions, - retainedGoals: this.retainedTaskGoals(node.task, this.archive.tasks, checkout, saved.commit, conditions), - environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest, - environment: this.input.access.get(this.lead.id)!.environment, - }) ? saved : undefined; - const proof = await this.check(node.task, node.assignment!, checkout, saved.commit, conditions, checked); - if (checked) this.input.emit('task_conditional_check_reused', { taskId: node.task.id, commit: proof.commit }); - return proof; - }); - if (['unavailable', 'blocked'].includes(proof.verification.status)) throw verifierFailure('conditional-task-recheck', proof, node.task); - savedReceipt = node.proof = proof; - if (proof.passed) node.feedback = undefined; - else { - this.moveTask(node, 'blocked', 'invalidated'); node.feedback = solverProofFeedback(proof); this.wakeLead('conditional-recheck-failed'); - } - } catch (error) { - this.input.signal.throwIfAborted(); - node.feedback = expectedRejection(error, integrationRejections).message; this.moveTask(node, 'blocked', 'invalidated'); this.wakeLead('conditional-recheck-failed'); - } - this.input.emit('task_conditional_recheck_finished', { taskId: node.task.id, passed: node.status === 'conditional', - commit: savedReceipt?.commit, taskDigest: savedReceipt?.taskDigest }); - this.changed(); - } - } - protected integrate(node: TaskRecord) { return this.queueIntegration(() => this.integrateNow(node)); } - private integrationAllowed(node: TaskRecord) { - const group = this.archive.groups?.find(record => record.group.id === taskGroup(node.task)); - return !this.synchronizationBlocked(node.task) && !(node.proof?.references?.tasks ?? []).some(reference => { - const dependency = this.node(reference.taskId); - return !dependency || dependency.pendingValidation || this.preparingStatementTasks.has(reference.taskId); - }) && (node.task.status ?? 'active') === 'active' && (!this.archive.groups || group?.group.status === 'active'); - } - private integrationSnapshot(node: TaskRecord) { - if (!this.archive.tasks.includes(node) || !['delivered', 'conditional'].includes(node.status) || - !node.assignment || !node.proof || !this.integrationAllowed(node)) return; - const tasks = this.archive.tasks.map(item => ({ ...item })); - const dependencies = this.dependencies(node.task, tasks); - const group = this.archive.groups?.find(record => record.group.id === taskGroup(node.task)); - return { node, task: node.task, taskDigest: digest(node.task), assignment: node.assignment, proof: node.proof, status: node.status, - canonical: this.archive.canonicalCommit!, environmentDigest: this.input.state.environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest, groupDigest: canonicalMathJson(group?.group ?? null), - routesDigest: canonicalMathJson({ alternatives: node.alternativeRoutes ?? [], routes: this.archive.proofRoutes ?? [] }), tasks, - dependencies: dependencies.map(item => ({ id: item.task.id, taskDigest: digest(item.task), status: item.status, - proof: item.proof, integratedCheck: item.integratedCheck })) }; - } - private integrationTaskCurrent(snapshot: NonNullable>) { - const { node } = snapshot; - return this.archive.tasks.includes(node) && node.status === snapshot.status && node.assignment === snapshot.assignment && - node.proof === snapshot.proof && digest(node.task) === snapshot.taskDigest && this.integrationAllowed(node) && - this.input.state.environmentDigest === snapshot.environmentDigest && this.input.state.problem.receiptDigest === snapshot.problemReceiptDigest && - canonicalMathJson({ alternatives: node.alternativeRoutes ?? [], routes: this.archive.proofRoutes ?? [] }) === snapshot.routesDigest && - snapshot.dependencies.every(dependency => { - const current = this.node(dependency.id); - return current && digest(current.task) === dependency.taskDigest; - }); - } - private integrationInputsCurrent(snapshot: NonNullable>) { - const group = this.archive.groups?.find(record => record.group.id === taskGroup(snapshot.task)); - return canonicalMathJson(group?.group ?? null) === snapshot.groupDigest && snapshot.dependencies.every(dependency => { - const current = this.node(dependency.id); - return current?.status === dependency.status && current.proof === dependency.proof && current.integratedCheck === dependency.integratedCheck; - }); - } - /** Batch only work that is ready now; every target must check the same complete union projection. */ - private async integrateBatch(node: TaskRecord): Promise<'fallback' | 'retry' | ProofDeliveryState> { - if ((this.input.modules.M2.checkTask ?? checkTaskProof) !== checkTaskProof) return 'fallback'; - const batch = await this.input.exclusiveCheck(async () => { - const eligible = (item: TaskRecord) => item.task.kind === 'lemma' && item.proof?.passed && - this.checkedDeliveries.has(item.proof) && !item.proof.conditions?.length && taskDependenciesReady(item.task, this.archive.tasks); - const first = eligible(node) && this.integrationSnapshot(node); - if (!first) return; - const snapshots = [first], declarations = new Set(first.proof.changes.map(change => `${change.file}\0${change.name}`)); - const uses = (item: typeof first) => new Set([...item.task.dependsOn, ...item.dependencies.map(input => input.id), - ...(item.proof.references?.tasks ?? []).map(input => input.taskId)]); - for (const candidate of this.archive.tasks) { - if (snapshots.length === 32) break; - if (candidate === node || taskGroup(candidate.task) !== taskGroup(first.task) || !eligible(candidate)) continue; - const snapshot = this.integrationSnapshot(candidate); - if (!snapshot || snapshot.proof.changes.some(change => declarations.has(`${change.file}\0${change.name}`)) || - snapshots.some(item => uses(item).has(snapshot.task.id) || uses(snapshot).has(item.task.id))) continue; - snapshots.push({ ...snapshot, tasks: first.tasks }); - snapshot.proof.changes.forEach(change => declarations.add(`${change.file}\0${change.name}`)); - } - if (snapshots.length < 2) return; - const graph = canonicalMathJson(this.archive.tasks.map(item => [item.task.id, digest(item.task)])); - const environment = { ...this.input.access.get(this.lead.id)!.environment }; - const key = mathDigest(canonicalMathJson({ canonical: first.canonical, environment, environmentDigest: first.environmentDigest, - problemReceiptDigest: first.problemReceiptDigest, graph, group: first.groupDigest, - inputs: snapshots.map(item => ({ task: item.taskDigest, assignment: item.assignment, proof: item.proof, - routes: item.routesDigest, dependencies: item.dependencies })) })); - if (this.rejectedIntegrationBatches.has(key)) return; - return { snapshots, graph, environment, key }; - }); - if (!batch) return 'fallback'; - const { snapshots, environment } = batch, first = snapshots[0], problem = this.input.state.problem; - let merged: string | undefined, receipts: TaskProof[] | undefined, fallback: string | undefined; - try { - await withSolverWorktree(this.lead.worktree, first.canonical, async checkout => { - for (const snapshot of snapshots) applyTaskChanges(problem, checkout, snapshot.proof.changes, snapshot.proof.imports); - merged = commitSolverSources(problem, checkout); - // New declarations can expose source dependencies absent from the old canonical. - const requests = snapshots.map(snapshot => ({ task: snapshot.task, - retainedGoals: this.retainedTaskGoals(snapshot.task, snapshot.tasks, checkout, merged!), - assignment: this.canonicalCheckAssignment(snapshot.task, merged!, snapshot.tasks) })); - const projector = createTaskSourceProjector(problem, checkout, merged); - const projections = requests.map(request => canonicalMathJson([...projector(request.task, request.retainedGoals)])); - if (projections.some(projection => projection !== projections[0])) { - fallback = 'math_task_batch_projection_mismatch'; return; - } - this.input.emit('task_integration_batch_started', { taskIds: snapshots.map(snapshot => snapshot.task.id), commit: merged }); - const proofs = await checkTaskProofs(problem, checkout, merged, requests, environment, this.input.signal, - this.input.timeoutMs, first.environmentDigest, this.taskProofCache); - this.input.signal.throwIfAborted(); - // One merged run exceeding the limit says nothing about each member; integrate them separately. - if (proofs.some(proof => hasLeanResourceLimitFailure(proof.verification))) { - fallback = 'math_task_batch_resource_limit'; return; - } - const failed = proofs.find(proof => ['unavailable', 'blocked'].includes(proof.verification.status)); - if (failed) throw verifierFailure('task-batch-integration', failed); - const deterministic = proofs.every(proof => proof.passed || isAttributedTaskProof(proof) && hasDeterministicLeanFailure(proof.verification)); - receipts = []; - for (const [index, snapshot] of snapshots.entries()) receipts.push(await this.check(snapshot.task, requests[index].assignment, - checkout, merged, [], proofs[index], false, false, first.tasks, - { environment, digest: first.environmentDigest })); - if (receipts.some(receipt => !receipt.passed)) { - if (!deterministic) throw verifierFailure('task-batch-unattributed', receipts.find(receipt => !receipt.passed)); - fallback = 'math_task_merged_proof_failed'; - } else if (receipts.some(receipt => receipt.references?.tasks?.some(reference => - snapshots.some(snapshot => snapshot.task.id === reference.taskId)))) fallback = 'math_task_batch_dependency_changed'; - }); - } catch (error) { - this.input.signal.throwIfAborted(); - fallback = rejectionCode(expectedRejection(error, integrationBatchFallbacks)); - } - const result = await this.input.exclusiveCheck(async () => { - this.input.signal.throwIfAborted(); - if (this.archive.canonicalCommit !== first.canonical || snapshots.some(snapshot => - !this.integrationTaskCurrent(snapshot) || !this.integrationInputsCurrent(snapshot)) || - canonicalMathJson(this.archive.tasks.map(item => [item.task.id, digest(item.task)])) !== batch.graph) { - this.input.emit('task_integration_batch_superseded', { taskIds: snapshots.map(snapshot => snapshot.task.id) }); - return 'retry' as const; - } - if (fallback) { - if (this.rejectedIntegrationBatches.size >= 64) this.rejectedIntegrationBatches.delete(this.rejectedIntegrationBatches.values().next().value!); - this.rejectedIntegrationBatches.add(batch.key); - this.input.emit('task_integration_batch_fallback', { taskIds: snapshots.map(snapshot => snapshot.task.id), reason: fallback }); - return 'fallback' as const; - } - const checkedReceipts = receipts; - if (!merged || !checkedReceipts || checkedReceipts.length !== snapshots.length) throw new Error('math_task_integration_missing_receipt'); - if (checkedReceipts.some(receipt => receipt.references && canonicalMathJson(receipt.references.tasks) !== - canonicalMathJson(attributeTaskReferences(receipt.references, this.archive.tasks)))) return 'retry' as const; - this.archive.canonicalCommit = merged; - snapshots.forEach((snapshot, index) => { - snapshot.node.integratedCheck = checkedReceipts[index]; snapshot.node.feedback = undefined; - this.moveTask(snapshot.node, 'integrated', 'integrated'); - }); - snapshots.forEach((snapshot, index) => this.input.emit('task_integrated', { taskId: snapshot.task.id, - taskDigest: snapshot.taskDigest, assignmentKey: assignmentDeliveryFile(snapshot.assignment), - workerId: snapshot.assignment.workerId, seedCommit: snapshot.assignment.seedCommit, - sourceDigest: checkedReceipts[index].sourceDigest, receiptIds: checkedReceipts[index].verification.results.map(result => result.receiptId), - groupId: taskGroup(snapshot.task), sharing: snapshot.task.sharing ?? 'problem', commit: merged, batchSize: snapshots.length })); - this.changed(); - return this.proofDeliveryState(node); - }); - if (typeof result !== 'string') await this.syncPreparedStatements(); - return result; - } - protected async integrateNow(node: TaskRecord) { - const problem = this.input.state.problem; - for (;;) { - const batch = await this.integrateBatch(node); - if (batch === 'retry') continue; - if (batch !== 'fallback') return batch; - const snapshot = await this.input.exclusiveCheck(async () => this.integrationSnapshot(node)); - if (!snapshot) return; - let submitted = snapshot.proof, receipt: TaskProof | undefined, merged: string | undefined, failure: unknown; - try { - await withSolverWorktree(this.lead.worktree, snapshot.canonical, async checkout => { - const environment = this.input.access.get(this.lead.id)!.environment; - const check = (commit: string, assignment: TaskAssignment, conditions: readonly CooperativeTask[], checkedWorktree = checkout) => - this.check(snapshot.task, assignment, checkedWorktree, commit, conditions, undefined, false, false, snapshot.tasks, - { environment, digest: snapshot.environmentDigest }); - // Restored JSON needs fresh delivery evidence before its changes can enter a merge. - if (!this.checkedDeliveries.has(submitted)) { - const conditions = (submitted.conditions ?? []).map(condition => { - const dependency = snapshot.tasks.find(item => item.task.id === condition.taskId); - if (!dependency || digest(dependency.task) !== condition.taskDigest) throw new Error('math_task_condition_version_invalid'); - return dependency.task; - }); - submitted = await check(submitted.commit, snapshot.assignment, conditions); - } - this.input.signal.throwIfAborted(); - if (['unavailable', 'blocked'].includes(submitted.verification.status)) throw verifierFailure('task-integration-delivery', submitted, snapshot.task); - if (!submitted.passed) throw new Error('math_task_delivery_no_longer_checks'); - if (!taskDependenciesReady(snapshot.task, snapshot.tasks)) throw new Error('math_task_dependency_invalidated'); - const resolvedConditions = (submitted.conditions ?? []).map(condition => { - const input = snapshot.tasks.find(item => item.task.id === condition.taskId); - if (!input || !assumableLemma(input.task) || input.status !== 'integrated' || - digest(input.task) !== condition.taskDigest) throw new Error('math_task_condition_version_invalid'); - return input.task; - }); - try { - applyTaskChanges(problem, checkout, submitted.changes, submitted.imports, resolvedConditions, submitted); - } catch (conflict) { - if (!(conflict instanceof Error) || rejectionCode(conflict) !== 'math_task_integration_conflict') throw conflict; - // A peer may already have proved this exact task with a different body. Preserve - // its sources and check the untouched canonical, without the delivery's assumptions. - let existing: TaskProof; - try { - existing = await withSolverWorktree(this.lead.worktree, snapshot.canonical, canonicalCheckout => - check(snapshot.canonical, this.canonicalCheckAssignment(snapshot.task, snapshot.canonical, snapshot.tasks), - [], canonicalCheckout)); - } catch (error) { - this.input.signal.throwIfAborted(); - expectedRejection(error, integrationRejections); - throw conflict; - } - this.input.signal.throwIfAborted(); - if (['unavailable', 'blocked'].includes(existing.verification.status)) throw verifierFailure('task-integration-conflict', existing, snapshot.task); - if (!existing.passed) throw conflict; - receipt = existing; merged = snapshot.canonical; - return; - } - merged = commitSolverSources(problem, checkout); - receipt = await check(merged, this.canonicalCheckAssignment(snapshot.task, merged, snapshot.tasks), []); - this.input.signal.throwIfAborted(); - if (['unavailable', 'blocked'].includes(receipt.verification.status)) throw verifierFailure('task-integration-merged', receipt, snapshot.task); - }); - } catch (error) { failure = error; } - const result = await this.input.exclusiveCheck(async () => { - this.input.signal.throwIfAborted(); - if (!this.integrationTaskCurrent(snapshot)) { - this.input.emit('task_integration_superseded', { taskId: snapshot.task.id, commit: snapshot.proof.commit }); - this.changed(); return 'superseded'; - } - if (this.archive.canonicalCommit !== snapshot.canonical || !this.integrationInputsCurrent(snapshot)) { - this.input.emit('task_integration_rebased', { taskId: snapshot.task.id, from: snapshot.canonical, - to: this.archive.canonicalCommit }); - this.changed(); return 'retry'; - } - if (submitted.passed) node.proof = submitted; - if (!failure && receipt && !receipt.passed) { - node.integratedCheck = receipt; node.feedback = solverProofFeedback(receipt); - failure = new Error('math_task_merged_proof_failed'); - } - if (failure) { - this.changed(); - node.feedback = `${expectedRejection(failure, integrationRejections).message}\n${node.feedback ?? ''}`; this.moveTask(node, 'blocked', 'integrated'); - this.wakeLead('integration-blocked'); this.changed(); return this.proofDeliveryState(node); - } - if (!receipt || !merged) throw new Error('math_task_integration_missing_receipt'); - if (receipt.references?.tasks?.some(reference => { - const current = this.node(reference.taskId); - return !current || digest(current.task) !== reference.taskDigest; - })) { - this.input.emit('task_integration_superseded', { taskId: snapshot.task.id, reason: 'actual-reference-changed' }); - this.changed(); return 'superseded'; - } - node.integratedCheck = receipt; node.feedback = undefined; - this.archive.canonicalCommit = merged; this.moveTask(node, 'integrated', 'integrated'); - this.input.emit('task_integrated', { taskId: node.task.id, taskDigest: snapshot.taskDigest, - assignmentKey: assignmentDeliveryFile(snapshot.assignment), workerId: snapshot.assignment.workerId, - seedCommit: snapshot.assignment.seedCommit, sourceDigest: receipt.sourceDigest, - receiptIds: receipt.verification.results.map(result => result.receiptId), - groupId: taskGroup(node.task), sharing: node.task.sharing ?? 'problem', commit: merged }); - this.changed(); return this.proofDeliveryState(node); - }); - if (result === 'retry') continue; - if (typeof result === 'string') return; - if (result.status === 'integrated') await this.syncPreparedStatements(); - return result; - } - } -} diff --git a/src/solver/cooperationPlanning.ts b/src/solver/cooperationPlanning.ts deleted file mode 100644 index 99d7690e..00000000 --- a/src/solver/cooperationPlanning.ts +++ /dev/null @@ -1,636 +0,0 @@ -import { parseCooperationPlan, isActiveFinalCandidateReview, isAdvisoryTask as advisory } from './tasks'; -import { assertPlanTaskTypeContracts } from './taskTypeContract'; -import fs from 'node:fs'; -import path from 'node:path'; -import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; -import { commitSolverSources, committedSource, git, solverProofImports, withSolverWorktree } from './problem'; -import { originalGoalTaskFocus, routeAllowsTask, taskCanStart, plannedTaskDependencyIds } from './modules/search'; -import { readMathResponse as block, parseMathResponse, replacePlanInNotes, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; -import { applyTaskChanges, ownedSourceDigest, taskChanges } from './cooperativeProof'; -import { statementSnapshot } from './statementReview'; -import { proofReferencesUnchanged } from './proofReferences'; -import { captureObligationSnapshot } from './obligationProgress'; -import { taskConnectionCheckCurrent } from './taskConnections'; -import { keepRespacedObjectives, taskGroup, taskVersion, taskProofContractVersion, taskReferenceDependencies, invalidatedTaskIds, type TaskRecord, - type CooperativeAction } from './tasks'; -import { digest, HumanEditRecord, InitialPlanPublication, RETRY_DISPATCH, DispatchResult, deliveryInputFields, readCooperationPlan, - type LeadPlan } from './cooperationShared'; -import { formatPlanJson, liftNestedPlanPatch, type PlanPatchBase } from './planPatch'; -import { PlanValidationError, type PlanIssue } from './planDiagnostics'; -import { collapseTaskFamilies } from './taskFamilies'; -import { dropLeadWakes, LEAD_MAX_BACKOFF } from './leadWakes'; -import { CooperationIntegration } from './cooperationIntegration'; -import { assertPlanAssignments, researchRouteGroups } from './modules/organization'; -import { currentCapacityExploration } from './capacityExploration'; -import { currentNextCheck, prepareNextCheckDecisions } from './nextChecks'; -import { prepareGoalProgressDecision, requireGoalProgressDecision } from './goalProgress'; -import { answerResearchInputs } from './researchDecisions'; -import { leadResearchInputs } from './contextCompiler'; -import { retireCooperativeRoutes } from './cooperationRoutes'; -import { isStatementAction } from './statementReview'; - -class InvalidLeadPlanDraft extends Error { - readonly issues?: PlanIssue[]; - - constructor(cause: unknown) { - super(cause instanceof Error ? cause.message : 'math_plan_invalid', { cause }); - if (cause instanceof PlanValidationError) this.issues = cause.issues; - else if (cause instanceof SyntaxError) this.issues = [{ path: 'RESEARCH.md.math-plan', message: 'Invalid JSON: ' + cause.message }]; - else if (this.message === 'math_math-plan_requires_one_block') this.issues = [{ path: 'RESEARCH.md.math-plan', - message: 'Supply exactly one math-plan block with a complete JSON plan or revision.' }]; - } -} - -/** Lead plan acceptance, plan identity and the idle original-goal frontier. */ -export abstract class CooperationPlanning extends CooperationIntegration { - /** Notes beyond the legacy plan parser's limit remain available as a draft. */ - protected leadNotes(commit?: string): { text?: string; digest: string } { - const worktree = this.lead.worktree, file = path.join(worktree, 'RESEARCH.md'); - if (commit) { - const [blob, bytes] = git(worktree, ['ls-tree', '--format=%(objectname) %(objectsize)', commit, '--', 'RESEARCH.md']).split(' '); - if (blob && Number(bytes) > MAX_RESEARCH_NOTES_BYTES) return { digest: 'git-blob:' + blob }; - const text = blob ? committedSource(worktree, commit, 'RESEARCH.md') : ''; - return { text, digest: mathDigest(text) }; - } - try { - const text = fs.existsSync(file) ? readMathText(file, MAX_RESEARCH_NOTES_BYTES) : ''; - return { text, digest: mathDigest(text) }; - } catch (error) { - if (!(error instanceof Error) || error.message !== 'math_runtime_file_too_large') throw error; - return { digest: 'git-blob:' + git(worktree, ['hash-object', '--no-filters', '--', file]) }; - } - } - - protected syncPlanNotes() { - if (!this.archive.planEdited) return; - const file = path.join(this.lead.worktree, 'RESEARCH.md'); - const { text: source } = this.leadNotes(); - // The accepted graph is already durable. Leave a large journal intact and use the live plan channel. - if (source === undefined) return; - const notes = replacePlanInNotes(source, formatPlanJson({ - tasks: collapseTaskFamilies(this.plannedTasks().map(node => node.task)), - groups: this.archive.groups?.map(route => route.group), - ...(this.archive.proofRoutes?.length ? { proofRoutes: this.archive.proofRoutes } : {}), - })); - if (Buffer.byteLength(notes) > MAX_RESEARCH_NOTES_BYTES) return; - if (notes !== source) fs.writeFileSync(file, notes); - this.archive.planEdited = false; - } - /** The accepted Lead graph that a plan revision is written against; family members are rederived on parse. */ - protected planPatchBase(): PlanPatchBase | undefined { - const tasks = collapseTaskFamilies(this.plannedTasks().map(node => node.task)); - return tasks.length ? { version: this.archive.planVersion ?? this.planVersion(), tasks, - groups: this.archive.groups?.map(route => route.group) ?? [], proofRoutes: this.archive.proofRoutes } : undefined; - } - /** A dispatch's own live publication already applied its revision; the final notes may repeat it against the dispatch base. */ - protected readLeadPlan(action?: CooperativeAction): LeadPlan { - const base = this.planPatchBase(); - const dispatchBase = action && this.current(action) ? this.leadPublication(action)?.baseVersion : undefined; - const rebased = dispatchBase !== undefined && dispatchBase !== base?.version; - // A rebased repeat of an applied publication already answered the review it was written against. - const goalPath = rebased ? undefined : this.goalPathReview(); - try { - return readCooperationPlan(this.input.state.problem, this.lead.worktree, base, { - acceptedBaseVersions: [...(base ? [base.version] : []), ...(rebased ? [dispatchBase] : [])], - rebased, restoring: !action, goalPath }); - } catch (error) { throw new InvalidLeadPlanDraft(error); } - } - protected planningInputDigest(scope: 'dispatch' | 'pause' | 'rejection' = 'dispatch') { - // Starting or checkpointing the same unresolved task does not give a rejected plan new evidence. - const taskStatus = (node: TaskRecord) => scope === 'rejection' && node.status === 'running' ? 'pending' : node.status; - const tasks = scope === 'rejection' ? this.archive.tasks.map(node => ({ ...node, status: taskStatus(node) })) : this.archive.tasks; - const versions = new Map(tasks.map(node => [node.task.id, digest(node.task)])); - const deliveries = [...new Set((this.archive.deliveries ?? []).filter(record => record.status !== 'superseded' && - !(scope !== 'dispatch' && record.producer === this.lead.id && record.kind === 'progress' && - record.summary.startsWith('Saved Lead draft pending integration:')) && - (!record.taskId || versions.get(record.taskId) === record.taskDigest)) - .map(record => canonicalMathJson(deliveryInputFields(record))))].sort(); - return mathDigest(canonicalMathJson({ problemReceiptDigest: this.input.state.problem.receiptDigest, - environmentDigest: this.input.state.environmentDigest, planVersion: this.archive.planVersion, - sourceDigest: ownedSourceDigest(this.input.state.problem, this.lead.worktree, this.archive.canonicalCommit!), - liveWorkers: this.input.workers.filter(worker => this.liveWorkers.has(worker.id)).map(({ id, role }) => ({ id, role })), - progress: captureObligationSnapshot(tasks, { groups: this.archive.groups, - environmentDigest: this.input.state.environmentDigest, proofRoutes: this.archive.proofRoutes, blockers: this.archive.blockers }).digest, - tasks: this.plannedTasks().map(node => ({ id: node.task.id, status: taskStatus(node), feedback: node.feedback })), - deliveries })); - } - protected planningEvidenceDigest() { - // Plan invalidation can supersede old deliveries, so compare their immutable content. - return mathDigest(canonicalMathJson({ problemReceiptDigest: this.input.state.problem.receiptDigest, - environmentDigest: this.input.state.environmentDigest, - liveWorkers: this.input.workers.filter(worker => this.liveWorkers.has(worker.id)).map(({ id, role }) => ({ id, role })), - sourceDigest: ownedSourceDigest(this.input.state.problem, this.lead.worktree, this.archive.canonicalCommit!), - deliveries: (this.archive.deliveries ?? []).filter(record => record.producer !== this.lead.id) - .map(({ status: _status, evidence: _evidence, ...record }) => record) })); - } - /** Ignore the draft-preservation bookkeeping produced by pausing this same turn. */ - protected leadPauseInputDigest(commit?: string) { - const problem = this.input.state.problem; - const sourceDigest = commit ? ownedSourceDigest(problem, this.lead.worktree, commit) : - mathDigest(canonicalMathJson(problem.ownedFiles.map(file => [file, - mathDigest(fs.readFileSync(path.join(this.lead.worktree, problem.projectRelative, file)))]))); - // New peer evidence must release the pause, because a plan input drops any delivery whose task version - // has since advanced and would otherwise hide the finding that alone can wake the Lead. The immutable - // content of peer publications is that evidence; a peer saving its notes mid-slice is work this Lead - // already dispatched and must not re-open the turn on every checkpoint. - return mathDigest(canonicalMathJson({ inputDigest: this.planningInputDigest('pause'), - evidenceDigest: this.planningEvidenceDigest(), planVersion: this.planVersion(), - sourceDigest, notesDigest: this.leadNotes(commit).digest })); - } - /** A completed decision covers its own bookkeeping, but never evidence arriving during that dispatch. */ - protected rememberLeadDecision(action: CooperativeAction) { - if (action.kind === 'lead' && action.planningInputDigest) { - this.archive.lastLeadInputDigest = this.leadEvidence.get(action) === this.planningEvidenceDigest() - ? this.planningInputDigest() : action.planningInputDigest; - this.archive.lastLeadPauseInputDigest = undefined; - // Diagnostic only: an accepted plan does not answer a peer still in the same no-work episode. - this.archive.leadDecisionBasisAt = this.archive.leadInboxBasis?.at ?? Date.now(); - this.answerGoalProgressReview(action); - const pending = leadResearchInputs(this.archive.deliveries ?? [], - new Map(this.archive.tasks.map(node => [node.task.id, node])), this.archive.researchDecisions); - const merging = new Set((this.pendingSourceResearchDecisions.get(action) ?? []).map(item => item.deliveryId)); - if (pending.some(record => !merging.has(record.id)) && this.presentedResearchInputs.get(action)?.shown.length) { - // A second page was present at dispatch; evidence arriving later is already a different input digest. - const presented = this.presentedResearchInputs.get(action)!; - if (presented.total > presented.shown.length) this.archive.lastLeadInputDigest = undefined; - this.wakeLead('research-finding'); - } - } - } - protected activeGoalFrontier() { - const focus = originalGoalTaskFocus(this.archive.tasks, this.archive.groups, this.input.state.environmentDigest, { includeParkedTasks: true }); - return [...focus.frontier].map(taskId => { - const node = this.node(taskId); - return { taskId, status: node.status, attempts: node.attempts, goalIds: [...focus.frontierGoals.get(taskId)!], parkedBy: node.routeParking ?? [] }; - }); - } - protected resumeUnattemptedFrontier(frontier: ReturnType) { - const candidates = new Set(frontier.map(item => this.node(item.taskId))); - const seen = new Set(); - const visit = (node: TaskRecord) => { - if (seen.has(node.task.id) || !routeAllowsTask(node.task, this.archive.tasks, this.archive.groups) || - ['integrated', 'completed'].includes(node.status)) return; - seen.add(node.task.id); - if (node.status === 'blocked') candidates.add(node); - for (const id of plannedTaskDependencyIds(node, this.archive.tasks)) { - const dependency = this.archive.tasks.find(item => item.task.id === id); - if (dependency) visit(dependency); - } - }; - // An explicitly pending supporting task can have unfinished prerequisites outside the original-goal cone. - for (const node of this.archive.tasks) if (node.status === 'pending') visit(node); - const resumed = [...candidates].filter(node => node.status === 'blocked' && node.attempts === 0 && - !node.assignment && !node.proof && !node.integratedCheck && - node.typePreflight?.status !== 'invalid' && - !node.feedback?.startsWith('math_task_repeated_failed_input\n') && - !this.archive.blockers?.some(blocker => blocker.taskId === node.task.id && blocker.status === 'parked') && - routeAllowsTask(node.task, this.archive.tasks, this.archive.groups) && taskCanStart(node.task, this.archive.tasks, this.archive.groups) && - this.livePeers.some(worker => this.input.modules.M5.assign([node], worker, this.livePeers, this.archive.groups, this.archive.tasks, this.stoppedWorkers) === node)); - if (!resumed.length) return false; - // A planning assessment is not an execution attempt at an imported unresolved obligation. - for (const node of resumed) this.moveTask(node, 'pending', 'reopened'); - this.input.emit('unattempted_frontier_resumed', { taskIds: resumed.map(node => node.task.id), - goalIds: [...new Set(frontier.flatMap(item => item.goalIds))] }); - this.changed(); - return true; - } - protected proposedPlanDigest(source?: string) { - try { - const { tasks, groups, proofRoutes, upsert, remove, baseVersion, goalPath, progressReview, retireRoutes, - researchDecisions, nextCheckDecisions, guidanceDecisions } = liftNestedPlanPatch(source === undefined - ? block(this.lead.worktree, 'math-plan') : parseMathResponse(source, 'math-plan')) as Record; - const revision = upsert !== undefined || remove !== undefined || (retireRoutes !== undefined && tasks === undefined); - // A decision-only correction is a changed response even when its task graph stays the same. - // Publication nonces and prose are not part of the decision and cannot reopen an unchanged rejection. - return mathDigest(canonicalMathJson({ tasks, groups, proofRoutes, ...(revision ? { upsert, remove, baseVersion } : {}), - goalPath, progressReview, researchDecisions, nextCheckDecisions, guidanceDecisions, retireRoutes })); - } catch { - if (source !== undefined) return mathDigest(source); - // A notes-only commit must not make an identical malformed response new input. - const file = path.join(this.lead.worktree, 'RESEARCH.md'); - return fs.existsSync(file) ? git(this.lead.worktree, ['hash-object', '--', file]) : 'missing'; - } - } - protected rejectPlan(error: unknown, recoveryKind?: 'checkpoint' | 'request-failure' | 'scheduling-checkpoint' | 'restore') { - const reason = error instanceof Error ? error.message : 'math_plan_invalid'; - // Saving this same rejected draft is bookkeeping, not a new mathematical input for another retry. - const proposalDigest = this.proposedPlanDigest(), inputDigest = this.planningInputDigest('rejection'); - const previous = this.archive.planRejection; - const malformed = error instanceof InvalidLeadPlanDraft; - const stalled = Boolean(previous?.inputDigest === inputDigest && (malformed && previous.malformed || - previous.proposalDigest === proposalDigest && previous.error === reason)); - // Restore can reread the same saved draft without a new Lead submission. - if (stalled && recoveryKind === 'restore' && previous?.proposalDigest === proposalDigest) return; - this.archive.error = reason; - this.archive.planRejection = { proposalDigest, inputDigest, error: reason, stalled, - ...(malformed ? { malformed: true, issues: error.issues } : {}) }; - // Private feedback already gives the Lead one repair turn. Repeated malformed drafts on - // unchanged evidence do not earn another turn by changing prose, formatting or the bad field. - if (stalled) dropLeadWakes(this.archive.leadWakes!); - else if (!malformed) this.wakeLead('plan-rejected'); - this.input.emit('plan_rejected', { ...this.archive.planRejection, - ...(recoveryKind && recoveryKind !== 'restore' ? { incomplete: true, recoveryKind } : {}) }); - } - protected async mergeLeadSources(commit: string, seedCommit: string, canonical = this.archive.canonicalCommit!) { - const problem = this.input.state.problem; - git(this.lead.worktree, ['merge-base', '--is-ancestor', seedCommit, commit]); - const changes = taskChanges(problem, this.lead.worktree, commit, undefined, { seedCommit }); - const imports = problem.ownedFiles.filter(file => file.endsWith('.lean')).flatMap(file => { - const before = solverProofImports(problem, committedSource(this.lead.worktree, seedCommit, `${problem.projectRelative}/${file}`)); - return solverProofImports(problem, committedSource(this.lead.worktree, commit, `${problem.projectRelative}/${file}`)) - .filter(module => !before.includes(module)).map(module => ({ file, module })); - }); - return withSolverWorktree(this.lead.worktree, canonical, async checkout => { - applyTaskChanges(problem, checkout, changes, imports); - const merged = commitSolverSources(problem, checkout); - this.pin(merged); - return merged; - }); - } - protected preserveLeadDraft(commit: string, seedCommit: string | undefined, reason: string, - { requestDecision = true, shareSource = true } = {}) { - this.pin(commit); - const summary = `Saved Lead draft pending integration: ${requestDecision ? reason : 'owned Lean source changes'}. ` + - `Inspect git show ${commit}:PROJECT_RELATIVE_PATH and reapply the useful declarations against the current canonical sources. ` + - 'This draft has no proof acceptance.'; - if (shareSource && !this.archive.deliveries?.some(record => record.producer === this.lead.id && record.kind === 'progress' && - record.commit === commit && record.summary.startsWith('Saved Lead draft pending integration:'))) { - this.record(this.lead, undefined, 'progress', 'advisory', summary, { commit }); - } - if (requestDecision) { this.archive.error = reason; this.wakeLead('lead-draft-preserved'); } - this.input.emit('lead_draft_preserved', { commit, seedCommit, canonicalCommit: this.archive.canonicalCommit, reason }); - } - protected async restoreLeadSources() { - const problem = this.input.state.problem; - const seed = this.archive.leadSeedCommit; - const draft = commitSolverSources(problem, this.lead.worktree); - this.pin(draft); - if (ownedSourceDigest(problem, this.lead.worktree, draft) !== - ownedSourceDigest(problem, this.lead.worktree, this.archive.canonicalCommit!)) { - try { - if (!seed) throw new Error('math_lead_recovery_seed_unknown'); - this.archive.canonicalCommit = await this.mergeLeadSources(draft, seed); - this.input.emit('lead_draft_restored', { commit: draft, seedCommit: seed, canonicalCommit: this.archive.canonicalCommit }); - } catch (error) { - this.input.signal.throwIfAborted(); - this.preserveLeadDraft(draft, seed, error instanceof Error ? error.message : 'math_lead_recovery_failed'); - } - } - this.archive.canonicalCommit = this.seed(this.lead, this.archive.canonicalCommit!); - } - protected planInvalidation({ tasks, groups, proofRoutes }: ReturnType, proofContracts = false) { - const previousGroups = new Map(this.archive.groups?.map(record => [record.group.id, record])); - const changedGroups = new Set(groups.filter(group => { - const previous = previousGroups.get(group.id)?.group; - return previous && (previous.objective !== group.objective || previous.revision !== group.revision); - }).map(group => group.id)); - const dependencies = new Map(this.archive.tasks.map(node => { - const references = taskReferenceDependencies(node); - return [node.task.id, references && proofReferencesUnchanged(this.input.state.problem, this.lead.worktree, - this.archive.canonicalCommit!, node.integratedCheck!.references!, this.input.state.environmentDigest) - ? references.map(reference => reference.taskId) - : [...node.task.dependsOn, ...(node.alternativeRoutes?.flatMap(route => [...route.prerequisiteTaskIds, route.closingTaskId]) ?? []), - ...(node.assignment?.dependencies?.map(dependency => dependency.taskId) ?? [])]]; - })); - const proposed = tasks.map(task => ({ task, status: 'pending' as const, attempts: 0, - alternativeRoutes: proofRoutes?.filter(route => route.targetTaskId === task.id) })); - const routeChanges = new Set(this.archive.tasks.filter(node => node.status !== 'integrated' && - (canonicalMathJson(node.alternativeRoutes ?? []) !== canonicalMathJson(proofRoutes?.filter(route => route.targetTaskId === node.task.id) ?? []) || - node.assignment?.connectionCheck && !taskConnectionCheckCurrent(node.task, node.assignment, proposed))) - .map(node => node.task.id)); - const invalidated = invalidatedTaskIds(this.archive.tasks, tasks, changedGroups, dependencies, routeChanges, - proofContracts ? taskProofContractVersion : taskVersion); - const view = this.capacityPlanView({ tasks, groups, proofRoutes }); - for (const node of this.archive.tasks) if (node.capacityExploration && - tasks.some(task => task.id === node.task.id && digest(task) === digest(node.task)) && - currentCapacityExploration(node, view, this.explorationIdentity)) invalidated.delete(node.task.id); - const checkView = this.nextCheckPlanView({ tasks, groups, proofRoutes }); - for (const node of this.archive.tasks) if (node.nextCheckId && - tasks.some(task => task.id === node.task.id && digest(task) === digest(node.task))) { - const record = this.archive.nextChecks?.find(record => record.id === node.nextCheckId); - // Group revisions and unrelated consumers cannot strip a current check's host identity. - if (record && currentNextCheck(record, checkView, this.explorationIdentity)) invalidated.delete(node.task.id); - } - return invalidated; - } - /** Validate a proposed decision without publishing, changing tasks or claiming proof acceptance. */ - protected preparePlan(plan: LeadPlan, decidingAction?: Extract, - restoringPlan = false) { - this.includePortfolioFoundation(plan); - const retirement = retireCooperativeRoutes(plan, this.archive, plan.retireRoutes); - if (retirement) Object.assign(plan, retirement.plan); - plan.tasks = keepRespacedObjectives(plan.tasks, new Map(this.archive.tasks.map(node => [node.task.id, node.task]))); - const nextCheckDecisions = prepareNextCheckDecisions(this.archive, this.explorationIdentity, plan, - plan.nextCheckDecisions, decidingAction ? this.presentedNextCheckOutcomes.get(decidingAction) : []); - this.includeCapacityExplorations(plan); - this.includeNextCheckTasks(plan); - const { tasks, groups } = plan; - assertPlanTaskTypeContracts(tasks, this.archive.tasks.map(node => node.task)); - const shown = decidingAction?.kind === 'lead' ? this.presentedResearchInputs.get(decidingAction)?.shown ?? [] : - restoringPlan ? leadResearchInputs(this.archive.deliveries ?? [], - new Map(this.archive.tasks.map(node => [node.task.id, node])), this.archive.researchDecisions).slice(-8) : []; - const researchDecisions = answerResearchInputs(plan, shown, this.plannedTasks().map(node => node.task), - tasks, [...this.archive.researchDecisions ?? [], - ...(decidingAction ? this.pendingSourceResearchDecisions.get(decidingAction) ?? [] : [])], '', Date.now()); - for (const decision of researchDecisions.filter(item => item.outcome === 'source')) { - if (decidingAction?.kind !== 'lead') throw new Error('math_plan_research_source_invalid: no Lead source dispatch.'); - for (const file of decision.sourcePaths ?? []) { - const problem = this.input.state.problem; - if (!file.endsWith('.lean') || !problem.ownedFiles.includes(file) || problem.frozenFiles?.[file]) - throw new Error('math_plan_research_source_invalid: ' + file); - const relative = path.posix.join(problem.projectRelative, file); - if (fs.readFileSync(path.join(this.lead.worktree, relative), 'utf8') === - committedSource(this.lead.worktree, decidingAction.seedCommit, relative)) - throw new Error('math_plan_research_source_unchanged: ' + file); - } - } - // Peer evidence can settle a review while its Lead is still composing an otherwise valid plan. - // Only the still-owed review shown to this dispatch may contribute a new progress decision. - const requiredProgressDecision = requireGoalProgressDecision(this.archive.goalProgress, - decidingAction ? this.presentedGoalProgress.get(decidingAction) : undefined, plan.goalProgressDecision); - const progressDecision = requiredProgressDecision - ? prepareGoalProgressDecision(requiredProgressDecision, this.archive.goalProgress, plan, - this.archive.nextChecks, this.archive.tasks) : undefined; - assertPlanAssignments(plan, this.archive.tasks, this.input.workers); - const configuredGroups = researchRouteGroups(groups, this.input.workers); - return { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown, retirement }; - } - protected async acceptPlan(planInput?: LeadPlan, edit?: HumanEditRecord, - publication?: { action: Extract; - receipt: Omit }, - leadAction?: Extract) { - const decidingAction = publication?.action ?? leadAction; - const restoringPlan = !decidingAction && !edit && this.archive.tasks.length > 0; - const { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown, retirement } = this.preparePlan( - planInput ?? this.readLeadPlan(leadAction), decidingAction, restoringPlan); - const { tasks, proofRoutes } = plan; - const previousGroups = new Map(this.archive.groups?.map(record => [record.group.id, record])); - const current = new Map(this.archive.tasks.map(node => [node.task.id, node])); - const previousReviewIds = this.archive.tasks.filter(({ task }) => isActiveFinalCandidateReview(task)).map(({ task }) => task.id); - const reviewIds = tasks.filter(isActiveFinalCandidateReview).map(task => task.id); - // Scheduling status does not change a task's version. A pause or resume can still change the Reviewer's questions. - const reviewScopeChanged = reviewIds.length !== previousReviewIds.length || reviewIds.some(id => !previousReviewIds.includes(id)); - const invalidated = this.planInvalidation(plan); - const proofChanges = this.planInvalidation(plan, true); - const revalidate = new Set([...invalidated].filter(id => !proofChanges.has(id) && current.get(id)?.status === 'integrated')); - this.input.signal.throwIfAborted(); - for (const id of invalidated) if (this.archive.unchangedResearch) delete this.archive.unchangedResearch[id]; - for (const id of invalidated) if (this.archive.researchCheckpoints) delete this.archive.researchCheckpoints[id]; - for (const previousEdit of this.archive.edits ?? []) for (const result of previousEdit.recheck?.tasks ?? []) - if (invalidated.has(result.taskId) && result.status !== 'removed') result.status = 'superseded'; - for (const record of this.archive.deliveries ?? []) if (record.taskId && invalidated.has(record.taskId)) record.status = 'superseded'; - for (const id of invalidated) { - const previous = current.get(id); - if (previous) (this.archive.history ??= []).push( - { task: previous.task, producer: previous.assignment?.workerId, proof: previous.proof, integratedCheck: previous.integratedCheck, - finding: previous.finding, researchCompletion: previous.researchCompletion }); - } - this.archive.tasks = tasks.map(task => { - const previous = current.get(task.id); - if (previous && (!invalidated.has(task.id) || revalidate.has(task.id))) { - previous.task = task; - const owner = task.ownerId ?? (task.kind === 'goal' ? configuredGroups.find(group => group.id === taskGroup(task))?.engineerId : undefined); - if (owner && previous.assignment && previous.assignment.workerId !== owner && ['pending', 'running'].includes(previous.status)) { - this.moveTask(previous, 'pending', 'reassigned'); previous.assignment = undefined; - } - return previous; - } - return { task, status: 'pending', attempts: previous?.attempts ?? 0 }; - }); - this.archive.groups = configuredGroups.map(group => ({ group, turns: previousGroups.get(group.id)?.turns ?? 0 })); - this.archive.proofRoutes = proofRoutes; - if (retirement) { - this.archive.retiredRoutes = retirement.retiredRoutes; - this.archive.retiredRouteTasks = retirement.retiredRouteTasks; - this.stopRetiredRouteTasks(); - } - this.syncProofRoutes(); - if (invalidated.size || reviewScopeChanged) { this.archive.review = undefined; this.lastAssembly = undefined; } - const retiredWork: (() => Promise)[] = []; - for (const [id, active] of this.active) { - if (active.action.kind === 'review' && !this.archive.review && !active.cancelled) { active.cancelled = true; void active.interrupt().catch(() => {}); } - if (retirement && (active.action.kind === 'task' && this.actionRouteRetired(active.action) || - isStatementAction(active.action) && !this.current(active.action))) { - if (!active.cancelled) { active.cancelled = true; retiredWork.push(active.interrupt); } - continue; - } - if (active.action.kind !== 'task') continue; - const action = active.action; - const node = this.archive.tasks.find(item => item.task.id === action.task.id); - const group = configuredGroups.find(route => route.id === (node && taskGroup(node.task))); - if (!node || invalidated.has(action.task.id) || (node.task.status ?? 'active') !== 'active' || group?.status !== 'active' || - (node.task.ownerId && node.task.ownerId !== id) || - (node.task.kind === 'goal' && group.engineerId && group.engineerId !== id)) { - if (node && !invalidated.has(node.task.id) && node.status === 'running') { - this.moveTask(node, 'pending', 'interrupted'); - if ((node.task.ownerId && node.task.ownerId !== id) || (node.task.kind === 'goal' && group?.engineerId && group.engineerId !== id)) node.assignment = undefined; - } - if (!active.cancelled) { active.cancelled = true; void active.interrupt().catch(() => {}); } - } - } - this.archive.error = undefined; - this.archive.planRejection = undefined; - if (edit) { - edit.status = 'applied'; edit.appliedAt = Date.now(); edit.pendingSync = true; - edit.affectedTasks = [...new Set([...invalidated, ...tasks.filter(task => !current.has(task.id)).map(task => task.id)])]; - edit.recheck = { status: 'pending', tasks: edit.affectedTasks.filter(id => { - const task = this.node(id)?.task ?? current.get(id)?.task; - return task && !advisory(task); - }).map(id => ({ taskId: id, taskDigest: digest((this.node(id) ?? current.get(id)!).task), - status: this.node(id) ? 'pending' : 'removed' })) }; - this.archive.planEdited = true; - } - this.archive.planVersion = this.planVersion(); - const graphDecisions = researchDecisions.filter(decision => decision.outcome !== 'source'); - const sourceDecisions = researchDecisions.filter(decision => decision.outcome === 'source'); - if (sourceDecisions.length && decidingAction) - this.pendingSourceResearchDecisions.set(decidingAction, sourceDecisions); - if (graphDecisions.length) { - this.archive.researchDecisions = [...this.archive.researchDecisions ?? [], - ...graphDecisions.map(decision => ({ ...decision, planVersion: this.archive.planVersion! }))]; - this.input.emit('research_findings_decided', { decisions: graphDecisions.map(decision => - ({ deliveryId: decision.deliveryId, outcome: decision.outcome, taskIds: decision.taskIds })) }); - } - if (restoringPlan && shown.length && leadResearchInputs(this.archive.deliveries ?? [], - new Map(this.archive.tasks.map(node => [node.task.id, node])), this.archive.researchDecisions).length) { - this.archive.lastLeadInputDigest = undefined; - this.wakeLead('research-finding'); - } - for (const { record, decision, repeated } of nextCheckDecisions) if (!repeated) { - record.decision = { ...decision, at: Date.now(), planVersion: this.archive.planVersion }; record.status = 'decided'; - this.input.emit('next_check_decided', { checkId: record.id, outcomeDeliveryId: decision.outcomeDeliveryId, - action: decision.action, target: record.scope.target }); - } - if (plan.goalPathDecisions && decidingAction) this.recordGoalPathDecisions(decidingAction, plan.goalPathDecisions); - if (progressDecision && decidingAction) this.goalProgressDecisions.set(decidingAction, progressDecision); - // A revision is not a graph: the next dispatch's notes show the complete accepted result. - if (plan.fromPatch || retirement?.added.length) this.archive.planEdited = true; - // Replaying unchanged saved notes during restore does not correct a rejected live event. - if (edit || publication || leadAction || this.archive.planPublicationRejection?.baseVersion !== this.archive.planVersion) - this.archive.planPublicationRejection = undefined; - if (publication) { - // Publish the graph, receipt and dispatch continuation together before waking any peer. - this.archive.planPublication = { ...publication.receipt, planVersion: this.archive.planVersion }; - if (publication.action.kind === 'lead' && publication.action.initialPlanNonce) - this.archive.initialPlanPublication = this.archive.planPublication; - } - // Preserve a Lead's own initial publication, but reclaim turns superseded by a newer plan. - for (const active of this.active.values()) if (active.action.kind === 'lead' && !this.current(active.action) && !active.cancelled) { - active.cancelled = true; void active.interrupt().catch(() => {}); - } - // Restored reviews include elaboration; compare them only after rebuilding that context. - const missingStatementContext = (node: TaskRecord) => !this.statementContexts.has(statementSnapshot( - this.input.state.problem, node.task, this.lead.worktree, this.archive.canonicalCommit!, this.input.state.environmentDigest, - this.dependencies(node.task).map(dependency => ({ task: dependency.task, taskDigest: digest(dependency.task) }))).snapshotDigest); - const synchronize = this.archive.tasks.filter(node => revalidate.has(node.task.id) || - node.task.status !== 'stopped' && node.task.statementReview && - (invalidated.has(node.task.id) || !current.has(node.task.id) || !this.archive.statementReviews?.some(review => - review.taskId === node.task.id && review.taskDigest === digest(node.task) && review.status !== 'superseded') || - missingStatementContext(node))); - this.markPendingValidation(synchronize, revalidate); - this.changed(edit); - for (const interrupt of retiredWork) void interrupt().catch(() => {}); - for (const route of retirement?.added ?? []) this.input.emit('cooperative_route_retired', route); - this.input.emit('plan_updated', { groups: this.archive.groups, tasks: tasks.map(task => - ({ id: task.id, kind: task.kind, dependsOn: task.dependsOn, groupId: taskGroup(task), sharing: task.sharing ?? 'problem' })), invalidated: [...invalidated] }); - if (this.archive.tasks.some(node => node.pendingValidation)) this.schedulePlanSynchronization(); - else { - this.syncStatementReviews(invalidated); - if (edit) edit.pendingSync = undefined; - } - this.changed(edit); - } - private includePortfolioFoundation(plan: LeadPlan) { - const gate = this.input.state.portfolioExploration?.gate; - if (this.archive.tasks.length || !gate?.primaryRouteId || !gate.foundationLemmas.length) return; - const liveGroups = plan.groups.filter(group => group.status === 'active' && - !this.archive.retiredRoutes?.some(route => route.routeId === group.id) && - !plan.retireRoutes?.some(route => route.routeId === group.id)); - const selected = liveGroups.find(group => group.id === gate.primaryRouteId) ?? - liveGroups.find(group => group.id !== gate.backupRouteId && - plan.tasks.some(task => task.kind === 'goal' && taskGroup(task) === group.id)); - if (!selected) return; - const groupId = selected.id; - const goals = plan.tasks.filter(task => task.kind === 'goal' && taskGroup(task) === groupId); - if (!goals.length) return; - - const problem = this.input.state.problem; - for (const seed of gate.foundationLemmas) { - const { id, proofPath, theoremName, type, objective } = seed; - if (Object.hasOwn(problem.frozenFiles ?? {}, proofPath) || !problem.ownedFiles.includes(proofPath) || - (problem.declarations[proofPath] ?? []).some(item => item.name.split('.').at(-1) === theoremName.split('.').at(-1))) - continue; - const existing = plan.tasks.find(task => task.id === id || - task.theoremName?.split('.').at(-1) === theoremName.split('.').at(-1)); - if (existing && (existing.kind !== 'lemma' || existing.theoremName !== theoremName || existing.type !== type || - existing.proofPath !== proofPath || existing.status && existing.status !== 'active')) continue; - const input = existing ?? { id, proofPath, theoremName, type, objective, kind: 'lemma' as const, - groupId, sharing: 'problem' as const, dependsOn: [], revision: 0 }; - const tasks = plan.tasks.map(task => goals.some(goal => goal.id === task.id) && !task.dependsOn.includes(input.id) - ? { ...task, dependsOn: [...task.dependsOn, input.id] } : task); - if (!existing) tasks.unshift(input); - try { - const validated = parseCooperationPlan(problem, { ...plan, tasks }); - assertPlanTaskTypeContracts(validated.tasks); - plan.tasks = validated.tasks; - } catch (error) { - // Scout interfaces are advisory. Skip an invalid starter without rejecting a valid Lead plan. - if (!(error instanceof Error) || !error.message.startsWith('math_')) throw error; - } - } - } - /** A proposed source answer becomes durable only when its changed Lean file reaches the canonical commit. */ - protected settleSourceResearchDecisions(action: CooperativeAction, previousCommit: string, mergedCommit: string) { - const pending = this.pendingSourceResearchDecisions.get(action); - if (!pending?.length) return; - this.pendingSourceResearchDecisions.delete(action); - const root = this.input.state.problem.projectRelative; - const applied = pending.filter(decision => decision.sourcePaths?.every(file => { - const relative = path.posix.join(root, file); - return committedSource(this.lead.worktree, previousCommit, relative) !== - committedSource(this.lead.worktree, mergedCommit, relative); - })); - if (applied.length) { - this.archive.researchDecisions = [...this.archive.researchDecisions ?? [], ...applied.map(decision => - ({ ...decision, at: Date.now(), planVersion: this.archive.planVersion! }))]; - this.input.emit('research_findings_decided', { decisions: applied.map(decision => - ({ deliveryId: decision.deliveryId, outcome: decision.outcome, sourcePaths: decision.sourcePaths })) }); - } - if (applied.length !== pending.length) this.wakeLead('research-finding'); - } - /** A planning checkpoint without a graph must not leave every peer idle. */ - async startInitialTasks() { - if (this.archive.tasks.length) return; - const reason = this.archive.error ?? 'math_initial_plan_checkpoint'; - const researchers = this.input.workers.filter(worker => worker.role === 'researcher' && this.liveWorkers.has(worker.id)); - const engineer = this.input.workers.find(worker => worker.role === 'engineer' && this.liveWorkers.has(worker.id)); - const targets = this.input.state.problem.targets; - // Start the Engineer on original goals and preserve the Researchers' initial coverage. - // Once a Researcher has no ready investigation, it may share unstarted goals with a busy Engineer. - const goals = targets.map((target, index) => ({ id: `initial_goal_${index + 1}`, kind: 'goal' as const, - objective: `Prove the frozen original target ${target.theoremName}; use researcher findings as advisory guidance.`, - ...(engineer ? { preferredOwnerId: engineer.id } : {}), - proofPath: target.proofPath, theoremName: target.theoremName })); - // Identical investigation text makes two Researchers ask one question; each gets a distinct angle. - const angles = [ - 'the central construction or quantitative estimate, with its exact assumptions and the missing inference', - 'library connections: the exact existing lemmas or definitions that could discharge a step, with pinned versions and searches', - 'the hardest substantive inference: whether it holds as stated, with a counterexample search or a concrete reduction', - 'a concrete end-to-end proof route, naming the remaining gaps in order', - ]; - const tasks = [...goals, ...researchers.map((worker, index) => { - // Round-robin coverage, but never an empty assignment: one target belongs to every Researcher. - const primary = targets.filter((_, targetIndex) => targetIndex % researchers.length === index); - const coveredTargets = primary.length ? primary : targets; - const covered = coveredTargets.map(target => target.theoremName).join(', '); - const researchSource = (['public-literature', 'verified-library', 'mathlib'] as const)[index % 3]; - return { id: `initial_research_${index + 1}`, kind: 'research' as const, ownerId: worker.id, researchSource, - consumerGoalIds: goals.filter(goal => coveredTargets.some(target => target.proofPath === goal.proofPath && - target.theoremName === goal.theoremName)).map(goal => goal.id), - // The goal is an inspection input, never a proof dependency: a parked advisory review must not - // make the original goal unstartable (advisory tasks may depend on the consumer, not the reverse). - dependsOn: goals.map(goal => goal.id), - objective: `Investigate ${angles[index % angles.length]} for ${covered}` + - `${researchers.length > 1 ? ` (investigation ${index + 1} of ${researchers.length})` : ''}. ` + - `Focus on ${researchSource}; deliver sourceUses with exact assumptions and consumer adaptation, ` + - 'and typed lemmaRequests when the implementation method is known. Report concrete evidence and unresolved gaps; findings are advisory.' }; - })]; - await this.acceptPlan(parseCooperationPlan(this.input.state.problem, { tasks })); - dropLeadWakes(this.archive.leadWakes!); - this.archive.initialPlanFallback = { at: Date.now(), reason }; - this.archive.planEdited = true; - this.syncPlanNotes(); - this.input.emit('initial_plan_fallback', { reason, planVersion: this.archive.planVersion }); - this.changed(); - } - protected planVersion() { - return mathDigest(canonicalMathJson({ tasks: this.plannedTasks().map(node => node.task), - groups: this.archive.groups?.map(route => route.group), - ...(this.archive.retiredRoutes?.length ? { retiredRoutes: this.archive.retiredRoutes } : {}), - ...(this.archive.proofRoutes?.length ? { proofRoutes: this.archive.proofRoutes } : {}) })); - } - /** - * A checkpoint cut is not a Lead decision. When nothing else runs, the cut draft is the only possible input, - * so the Lead continues it on its backoff schedule; only a pause past the backoff cap, unchanged, ends the run. - */ - protected resumePausedLead() { - if (!this.archive.lastLeadPauseInputDigest || this.active.size) return false; - const research = this.input.state.workers?.find(record => record.id === this.lead.id) ?? this.input.state; - const streak = research.advisoryCheckpoint?.noProgressStreak ?? 0; - if (streak > LEAD_MAX_BACKOFF) return false; - this.archive.lastLeadPauseInputDigest = undefined; - this.wakeLead('lead-pause-idle'); - this.input.emit('lead_pause_resumed', { noProgressStreak: streak }); - this.changed(); - return true; - } - /** Nothing runs and the Lead already decided on these inputs: no process input can arrive, so the run ends. */ - protected async idleFrontier(frontier: ReturnType, inputDigest: string): Promise { - if (this.preparingTaskTypes.size) return this.waitForDispatch(); - if (this.resumeUnattemptedFrontier(frontier)) return RETRY_DISPATCH; - if (this.resumePausedLead()) return RETRY_DISPATCH; - this.input.emit('routes_idle', { groups: this.archive.groups, - goalIds: [...new Set(frontier.flatMap(item => item.goalIds))], frontier, - reason: frontier.length ? 'unchanged-mathematical-input' : 'no-active-goal-frontier', inputDigest }); - } -} diff --git a/src/solver/cooperationRoutes.ts b/src/solver/cooperationRoutes.ts deleted file mode 100644 index 94cf514d..00000000 --- a/src/solver/cooperationRoutes.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { LeadPlan } from './cooperationShared'; -import type { ProofRoute } from './proofRoutes'; -import type { RetiredRoute, RouteRetirement } from './routeControl'; -import { taskGroup, type CooperativeTask, type TaskRecord } from './tasks'; - -export function retireCooperativeRoutes( - proposal: Pick, - current: { tasks: readonly TaskRecord[]; proofRoutes?: readonly ProofRoute[]; retiredRoutes?: readonly RetiredRoute[]; - retiredRouteTasks?: Readonly> }, - requested: readonly RouteRetirement[] = [], - at = Date.now(), -) { - const routes = new Map((current.retiredRoutes ?? []).map(record => [record.routeId, record])); - const added: RetiredRoute[] = []; - for (const request of requested) if (!routes.has(request.routeId)) { - const record = { ...request, source: 'lead' as const, retiredAt: at }; - routes.set(record.routeId, record); - added.push(record); - } - if (!routes.size) return; - - const survivingRoutes = (proposal.proofRoutes ?? []).filter(route => !routes.has(route.id)); - const branchRoutes = [...current.proofRoutes ?? [], ...proposal.proofRoutes ?? []].filter(route => routes.has(route.id)); - const nodes = new Map([...current.tasks.map(node => node.task), ...proposal.tasks].map(task => [task.id, task])); - const branchInputs = (ids: readonly string[]) => { - const inputs = new Set(); - const visit = (id: string) => { - if (inputs.has(id)) return; - inputs.add(id); - nodes.get(id)?.dependsOn.forEach(visit); - }; - ids.forEach(visit); - return inputs; - }; - const protectedInputs = branchInputs([ - ...survivingRoutes.flatMap(route => [route.closingTaskId, ...route.prerequisiteTaskIds]), - ...proposal.tasks.filter(task => task.kind === 'goal' && !routes.has(taskGroup(task))).flatMap(task => task.dependsOn), - ]); - const taskRoutes = new Map(Object.entries(current.retiredRouteTasks ?? {})); - for (const route of branchRoutes) for (const id of branchInputs([route.closingTaskId, ...route.prerequisiteTaskIds])) { - // An input on a surviving branch only retires when it belongs to a retired group. - if (!protectedInputs.has(id) && nodes.get(id)?.kind !== 'goal' && !taskRoutes.has(id)) taskRoutes.set(id, route.id); - } - for (const node of current.tasks) { - const routeId = node.assignment?.routeId; - if (routeId && routes.has(routeId) && node.task.kind !== 'goal' && !protectedInputs.has(node.task.id) && !taskRoutes.has(node.task.id)) - taskRoutes.set(node.task.id, routeId); - } - return { - retiredRoutes: [...routes.values()], added, retiredRouteTasks: Object.fromEntries(taskRoutes), - plan: { - tasks: proposal.tasks, - groups: proposal.groups.map(group => routes.has(group.id) ? { ...group, status: 'stopped' as const } : group), - proofRoutes: survivingRoutes.length ? survivingRoutes : undefined, - }, - }; -} - -export function retiredCooperativeRoute(task: CooperativeTask, - state: { retiredRoutes?: readonly RetiredRoute[]; retiredRouteTasks?: Readonly> }) { - const branch = state.retiredRouteTasks && Object.hasOwn(state.retiredRouteTasks, task.id) - ? state.retiredRouteTasks[task.id] : undefined; - return state.retiredRoutes?.find(record => record.routeId === taskGroup(task) || record.routeId === branch); -} diff --git a/src/solver/cooperationStatements.ts b/src/solver/cooperationStatements.ts deleted file mode 100644 index 432eab8a..00000000 --- a/src/solver/cooperationStatements.ts +++ /dev/null @@ -1,197 +0,0 @@ -import path from 'node:path'; -import crypto from 'node:crypto'; -import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { type ResearchWorker } from './modules/organization'; -import type { ContextBundle } from './modules/context'; -import { routeAllowsTask } from './modules/search'; -import { deliveryDetails, reviewVerdict, readMathResponse as block } from './deliveries'; -import { assertStatementSnapshot, captureStatementContexts, createStatementSnapshotter, isStatementAction, readBacktranslation, resetStatementReview, - writeStatementSnapshot, type StatementAction } from './statementReview'; -import { captureProofReferences, proofReferencesUnchanged } from './proofReferences'; -import { taskGroup, hasTaskReferences, isDefinitionTask, type CooperativeTask, type RouteRecord, type TaskRecord } from './tasks'; -import { digest } from './cooperationShared'; -import { CooperationCore } from './cooperationCore'; -import { retiredCooperativeRoute } from './cooperationRoutes'; - -/** Statement translation reviews and their fixed-snapshot contexts. */ -export abstract class CooperationStatements extends CooperationCore { - protected statementTaskIdentity() { - return mathDigest(canonicalMathJson(this.archive.tasks.map(node => ({ taskId: node.task.id, - taskDigest: digest(node.task), statementReview: node.task.statementReview === true })))); - } - protected fixedStatementReviewTasks(): ReadonlyMap | undefined { - const scope = this.fixedReviewScope, review = this.archive.review; - return scope && review === scope.review && review.commit === scope.commit && review.sourceDigest === scope.sourceDigest && - this.archive.canonicalCommit === scope.commit && this.input.state.environmentDigest === scope.environmentDigest && - this.statementTaskIdentity() === scope.tasksDigest ? scope.required : undefined; - } - protected statementReviewAllowed(task: CooperativeTask, dispatch = false, - tasks: readonly TaskRecord[] = this.archive.tasks, groups: readonly RouteRecord[] | undefined = this.archive.groups) { - if (this.synchronizationBlocked(task)) return false; - const required = this.fixedStatementReviewTasks(); - if (required) return required.get(task.id) === digest(task); - return dispatch ? routeAllowsTask(task, tasks, groups) : - (task.status ?? 'active') === 'active' && - this.archive.groups?.find(route => route.group.id === taskGroup(task))?.group.status === 'active'; - } - protected pendingFixedStatementReviews() { - const required = this.fixedStatementReviewTasks(); - return required && this.archive.statementReviews?.some(review => required.get(review.taskId) === review.taskDigest && - ['pending', 'translating', 'translated', 'reviewing'].includes(review.status)); - } - protected async syncPreparedStatements() { - for (;;) { - const canonical = this.archive.canonicalCommit, planVersion = this.archive.planVersion; - const statements = this.prepareStatementContexts(); if (statements) await statements; - const synchronized = await this.input.exclusiveCheck(async () => { - if (canonical !== this.archive.canonicalCommit || planVersion !== this.archive.planVersion) return false; - this.syncStatementReviews(); this.changed(); return true; - }); - if (synchronized) return; - } - } - /** A lemma type naming a planned definition elaborates only after that definition's body is canonical. */ - private statementTasks(nodes: readonly TaskRecord[]) { - return nodes.filter(node => node.task.statementReview && - (node.status === 'integrated' || !retiredCooperativeRoute(node.task, this.archive)) && this.dependencies(node.task, nodes) - .every(dependency => !isDefinitionTask(dependency.task) || dependency.status === 'integrated')).map(node => node.task); - } - protected prepareStatementContexts(nodes: readonly TaskRecord[] = this.archive.tasks, - canonical = this.archive.canonicalCommit!, - checkEnvironment?: { environment: NodeJS.ProcessEnv; digest: string; current?: () => boolean }): Promise | undefined { - if (checkEnvironment?.current && !checkEnvironment.current()) return; - if (this.preparingStatements) return this.preparingStatements.then(() => this.prepareStatementContexts(nodes, canonical, checkEnvironment)); - const environmentDigest = checkEnvironment?.digest ?? this.input.state.environmentDigest; - const tasks = this.statementTasks(nodes); - const snapshot = createStatementSnapshotter(this.input.state.problem, this.lead.worktree, canonical, environmentDigest); - const keys = new Map(tasks.map(task => [task.id, snapshot(task, this.dependencies(task, nodes).map(dependency => - ({ task: dependency.task, taskDigest: digest(dependency.task) }))).snapshotDigest])); - const missing = tasks.filter(task => !this.statementContexts.has(keys.get(task.id)!)); - if (!missing.length) return; - for (const task of missing) this.preparingStatementTasks.add(task.id); - const pending = captureStatementContexts(this.input.state.problem, missing, this.lead.worktree, - canonical, checkEnvironment?.environment ?? this.input.access.get(this.lead.id)!.environment, this.input.signal, this.input.timeoutMs) - .then(contexts => { for (const task of missing) this.statementContexts.set(keys.get(task.id)!, contexts.get(task.id)!); }) - .finally(() => { - for (const task of missing) this.preparingStatementTasks.delete(task.id); - if (this.preparingStatements === pending) this.preparingStatements = undefined; - this.wake(); - }); - this.preparingStatements = pending; - this.refreshPlanApproval(); - return pending; - } - protected syncStatementReviews(invalidated = new Set()) { - if (!this.archive.statementReviews?.length && !this.archive.tasks.some(node => node.task.statementReview)) return; - const reviews = this.archive.statementReviews ??= []; - const tasks = this.statementTasks(this.archive.tasks); - const snapshot = createStatementSnapshotter(this.input.state.problem, this.lead.worktree, this.archive.canonicalCommit!, - this.input.state.environmentDigest); - const snapshots = new Map(tasks.map(task => [task.id, - snapshot(task, this.dependencies(task).map(dependency => - ({ task: dependency.task, taskDigest: digest(dependency.task) }))) ])); - for (const task of tasks) snapshots.set(task.id, snapshot(task, this.dependencies(task).map(dependency => - ({ task: dependency.task, taskDigest: digest(dependency.task) })), this.statementContexts.get(snapshots.get(task.id)!.snapshotDigest))); - for (const review of reviews.filter(item => item.status !== 'superseded')) { - const node = this.node(review.taskId), snapshot = snapshots.get(review.taskId); - const reuse = review.status === 'accepted' && node && snapshot?.snapshotDigest === review.snapshotDigest && - review.environmentDigest === this.input.state.environmentDigest && - review.intendedStatement === node.task.informalStatement && - canonicalMathJson(review.premises) === canonicalMathJson(node.task.premises ?? this.input.state.problem.contract.assumptions); - if (reuse) { - if (invalidated.has(review.taskId) || review.taskDigest !== digest(node.task) || !this.archive.deliveries?.some(delivery => - delivery.statementReviewId === review.id && delivery.kind === 'statement-review' && delivery.status === 'accepted' && - delivery.taskDigest === digest(node.task))) { - review.taskDigest = digest(node.task); - review.dependencies = snapshot.input.dependencies.map(({ taskId, taskDigest }) => ({ taskId, taskDigest })); - for (const delivery of this.archive.deliveries ?? []) if (delivery.statementReviewId === review.id && - delivery.taskDigest !== review.taskDigest) delivery.status = 'superseded'; - this.record(this.lead, node.task, 'statement-review', 'accepted', review.summary ?? 'Unchanged formal statement review reused.', - { statementReviewId: review.id, taskDigest: review.taskDigest, statement: review.leanStatement, - premises: review.premises, dependencies: review.dependencies, remainingObligations: [], commit: review.commit, sourceDigest: review.snapshotDigest }); - this.input.emit('statement_review_reused', { taskId: review.taskId, reviewId: review.id }); - } - } - if ((!reuse && (invalidated.has(review.taskId) || !node || digest(node.task) !== review.taskDigest)) || !snapshot || - review.intendedStatement !== node?.task.informalStatement || - canonicalMathJson(review.premises) !== canonicalMathJson(node?.task.premises ?? this.input.state.problem.contract.assumptions) || - (snapshot.snapshotDigest !== review.snapshotDigest && (!review.references || !this.checkedStatementReferences.has(review.references) || - !proofReferencesUnchanged(this.input.state.problem, this.lead.worktree, this.archive.canonicalCommit!, review.references, this.input.state.environmentDigest)))) { - this.supersedeStatementReview(review); - } - if (review.status !== 'superseded' && (!review.references || !this.checkedStatementReferences.has(review.references)) && snapshot?.snapshotDigest === review.snapshotDigest) { - const proof = node?.integratedCheck; - const references = snapshot.references ?? (proof?.references && hasTaskReferences(proof) - ? captureProofReferences(this.input.state.problem, this.lead.worktree, this.archive.canonicalCommit!, proof.references.root, - { statement: proof.references.statement, proof: [] }, this.input.state.environmentDigest, 'statement') : undefined); - if (references) { review.references = references; this.checkedStatementReferences.add(references); } - } - } - for (const [taskId, snapshot] of snapshots) { - if (reviews.some(review => review.taskId === taskId && review.status !== 'superseded')) continue; - const task = this.node(taskId).task, id = crypto.randomUUID(); - const workspace = path.join(path.dirname(this.lead.worktree), 'statement-reviews', id); - reviews.push({ id, taskId, taskDigest: digest(task), snapshotDigest: snapshot.snapshotDigest, - environmentDigest: this.input.state.environmentDigest, commit: this.archive.canonicalCommit!, - leanStatement: snapshot.input.leanStatement, intendedStatement: task.informalStatement!, - premises: task.premises ?? this.input.state.problem.contract.assumptions, - dependencies: task.kind === 'goal' ? [] : this.dependencies(task).map(node => ({ taskId: node.task.id, taskDigest: digest(node.task) })), - ...(snapshot.references ? { references: snapshot.references } : {}), - workspace, files: writeStatementSnapshot(workspace, snapshot), status: 'pending' }); - if (snapshot.references) this.checkedStatementReferences.add(snapshot.references); - this.input.emit('statement_review_requested', { taskId, reviewId: id, snapshotDigest: snapshot.snapshotDigest }); - } - for (const active of this.active.values()) if (isStatementAction(active.action) && !this.current(active.action) && !active.cancelled) { - const reviewId = active.action.reviewId; - const review = reviews.find(item => item.id === reviewId); - if (review && ['translating', 'reviewing'].includes(review.status)) resetStatementReview(review); - active.cancelled = true; void active.interrupt().catch(() => {}); - } - } - statementContext(action: StatementAction): ContextBundle { - const review = this.archive.statementReviews!.find(review => review.id === action.reviewId)!; - // The blind hook receives only the formal snapshot, never the intended mathematics or saved translation. - const visible = action.kind === 'backtranslate' ? { ...review, intendedStatement: '', premises: [], translation: undefined } : review; - const fixed = this.input.modules.M4.statement(visible, action, this.input.state.problem.receiptDigest); - if (fixed.scope !== 'fixed-statement' || fixed.sources.problemReceiptDigest !== this.input.state.problem.receiptDigest) - throw new Error('math_statement_context_invalid'); - return fixed; - } - async deliverStatement(worker: ResearchWorker, action: StatementAction): Promise<{ checkWhole: false }> { - const review = this.archive.statementReviews?.find(item => item.id === action.reviewId); - if (!review) throw new Error('math_statement_review_unknown'); - const kind = action.kind === 'backtranslate' ? 'backtranslation' : 'statement-review'; - const options = { statementReviewId: review.id, taskId: review.taskId, taskDigest: review.taskDigest, statement: review.leanStatement, - premises: review.premises, dependencies: review.dependencies, commit: review.commit, sourceDigest: review.snapshotDigest }; - if (!this.current(action) || review.workerId !== worker.id) { - this.record(worker, undefined, kind, 'superseded', 'Statement delivery belongs to a superseded assignment.', options); - return { checkWhole: false }; - } - let evidenceRefs: readonly string[] = []; - try { - assertStatementSnapshot(review); - const result = block(review.workspace, action.kind === 'backtranslate' ? 'math-backtranslation' : 'math-statement-review', - { reviewId: review.id, snapshotDigest: review.snapshotDigest }, action.kind === 'backtranslate' ? 'mathematics' : undefined); - if (result.reviewId !== review.id || result.snapshotDigest !== review.snapshotDigest) throw new Error('math_statement_review_identity_changed'); - if (action.kind === 'backtranslate') { - review.translation = readBacktranslation(result); review.status = 'translated'; - review.summary = 'Independent backtranslation saved; mathematical comparison remains pending.'; - evidenceRefs = review.translation.evidenceRefs; - } else { - const details = deliveryDetails(result); - if (!review.translation) throw new Error('math_statement_review_invalid'); - review.status = reviewVerdict(result.verdict, 'math_statement_review_invalid'); - review.summary = details.summary; evidenceRefs = details.evidenceRefs; - } - } catch (error) { - review.status = 'changes_requested'; review.summary = error instanceof Error ? error.message : 'math_statement_review_failed'; - } - review.workerId = undefined; - if (review.status === 'accepted') this.lastAssembly = undefined; - if (review.status === 'changes_requested') { this.archive.error = review.summary; this.wakeLead('statement-review-rejected'); } - this.record(worker, this.node(review.taskId).task, kind, review.status === 'translated' ? 'advisory' : review.status, - review.summary ?? '', { ...options, evidenceRefs }); - this.input.emit('statement_review_completed', { workerId: worker.id, taskId: review.taskId, reviewId: review.id, kind, status: review.status }); - return { checkWhole: false }; - } -} diff --git a/src/solver/cooperationTaskProofs.ts b/src/solver/cooperationTaskProofs.ts deleted file mode 100644 index d94c431a..00000000 --- a/src/solver/cooperationTaskProofs.ts +++ /dev/null @@ -1,1471 +0,0 @@ -import { isAdvisoryTask as advisory, isFeasibilityReview } from './tasks'; -import fs from 'node:fs'; -import path from 'node:path'; -import crypto from 'node:crypto'; -import { VerifierFailureError } from './verifierFailure'; -import { mathGitResult } from '../math/mathGit'; -import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { projectMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnvironment'; -import { hashMathFormalSourceDeclaration, inspectLeanDeclarationRegions } from '../math/leanSource'; -import { commitSolverSources, committedSource, git, withSolverWorktree } from './problem'; -import { solverProofFeedback, solverSourceFeedback } from './feedback'; -import { assessTaskResponsibility, independentFeasibilityWorker, type ResearchWorker } from './modules/organization'; -import { proofReceiptsMatch, type ProofCheck } from './modules/evidence'; -import { routeAllowsTask, taskCanStart, selectedTaskRoute, taskDependenciesReady } from './modules/search'; -import { deliveryDetails, deliveryFinding, MAX_RESEARCH_NOTES_BYTES, parseMathResponse, researchFindingRequestsDecision, type DeliveryRecord } from './deliveries'; -import { checkTaskProof, createTaskSourceProjector, isAttributedTaskProof, ownedSourceDigest, projectedGoalInputs, taskChanges, trustedTaskProjectionReuse, type TaskProof } from './cooperativeProof'; -import { proofReferencesUnchanged, type ProofReferences } from './proofReferences'; -import { captureDeliveryArtifacts, diagnoseUnbackedLeanClaims, validateDeliveryArtifactClaims, type DeliveryArtifactManifest } from './deliveryArtifacts'; -import { validateLemmaRequests } from './taskProposals'; -import { routeBlockerBasis, type BlockerBasis } from './routeControl'; -import { attributeTaskReferences } from './taskReferenceAttribution'; -import { checkpointCandidate } from './researchEvidence'; -import { committedResearchNotesDigest, feasibilityReviewInputDigest, researchCheckpointInputDigest, researchCheckpointLocalInputDigest, researchCheckpointOutputDigest, - researchHandoffNotesDigest, resumableFeasibilityReviewInput, UNCHANGED_RESEARCH_CHECKPOINT, type ResearchCheckpoint } from './researchCheckpoints'; -import { savedContextCheckpoint } from './contextCheckpoint'; -import { inspectKnowledgeUses, type KnowledgeUse } from './knowledgeUsage'; -import { checkKnowledgeApplications } from './knowledgeApplications'; -import { bindMathematicalGap, mathematicalGaps } from './mathematicalGaps'; -import { bindCheckOutcome } from './nextChecks'; -import { researchPublicationNotes } from './researchPublication'; -import { taskConnectionCheckCurrent, taskInputsMissingFromSeed } from './taskConnections'; -import { hasLeanResourceLimitFailure, hasLeanSourceDiagnostic } from './proofReuse'; -import { assumableLemma, taskGroup, taskReferenceDependencies, assignmentDeliveryFile, markTaskReferences, markTaskAcceptance, hasTaskAcceptance, type CooperativeTask, - type TaskAssignment, type TaskRecord, type CooperativeAction } from './tasks'; -import { digest, FailedTaskInput, bounded, directDeliveryRejections, rejectionCode } from './cooperationShared'; -import { CooperationStatements } from './cooperationStatements'; -import { prepareResearchDelivery, ResearchAdmissionError, type ResearchSubmission } from './researchAdmission'; -import { settleResearch } from './researchRecords'; -import { researchDecisionMatches } from './researchDecisions'; -import { leadResearchInputs } from './contextCompiler'; - -type ProofDeliveryRequest = { - worker: ResearchWorker; action: Extract; - commit: string; summary: string; options: Partial; record?: DeliveryRecord; - /** Host-only candidate: validate again, then claim its still-current assignment atomically. */ - prepared?: { proof: TaskProof; current: () => boolean; claim: () => void; advisorySummary?: string }; -}; -export type ProofDeliveryAnnotation = () => Promise; -export type ProofDeliveryState = Pick; - -/** Task proof checks, failed-input memory and research checkpoints. */ -export abstract class CooperationTaskProofs extends CooperationStatements { - // Implemented by later layers; listed here because this layer calls them. - protected abstract queueIntegration(operation: () => Promise, worker?: ResearchWorker, task?: CooperativeTask): Promise; - protected abstract integrateReadyNow(annotations: ProofDeliveryAnnotation[]): Promise; - protected abstract integrateNow(node: TaskRecord): Promise; - private proofDeliveryRequests = new Map(); - private proofDeliveryAnnotations = new WeakMap(); - protected pendingProofDeliveryRecords = new WeakSet(); - abstract interrupted(worker: ResearchWorker, action: CooperativeAction): void; - abstract rejected(action: CooperativeAction, feedback: string, commit?: string, incomplete?: boolean): void; - private feasibilityInput(task: CooperativeTask, workerId: string) { - const state = this.input.state; - return { task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], - problem: state.problem, environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, - retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest, - worktree: this.lead.worktree, canonicalCommit: this.archive.canonicalCommit! }; - } - protected feasibilityInputDigest(task: CooperativeTask, workerId: string) { - return feasibilityReviewInputDigest(this.feasibilityInput(task, workerId)); - } - private checkpointInputDigest(task: CooperativeTask, workerId: string, includeDeliveries = true) { - return researchCheckpointInputDigest({ task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], - environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest, - problem: this.input.state.problem, worktree: this.lead.worktree, canonicalCommit: this.archive.canonicalCommit!, includeDeliveries }); - } - private checkpointLocalInputDigest(task: CooperativeTask, workerId: string, legacyProgress = false) { - return researchCheckpointLocalInputDigest({ task, workerId, tasks: this.archive.tasks, deliveries: this.archive.deliveries ?? [], - environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest }, legacyProgress); - } - private checkpointInputMatches(node: TaskRecord, workerId: string, checkpoint: ResearchCheckpoint, localInputDigest: string) { - if (!checkpoint.localInputDigest) return this.checkpointInputDigest(node.task, workerId) === checkpoint.inputDigest; - return checkpoint.localInputDigest === localInputDigest || Boolean(node.nextCheckId && - checkpoint.localInputDigest === this.checkpointLocalInputDigest(node.task, workerId, true)); - } - private checkpointOutputDigests = new Map(); - private checkpointOutputDigest(worktree: string, commit: string) { - const key = `${worktree}\0${commit}`, cached = this.checkpointOutputDigests.get(key); - if (cached) return cached; - const value = researchCheckpointOutputDigest(this.input.state.problem, worktree, commit); - this.checkpointOutputDigests.set(key, value); - if (this.checkpointOutputDigests.size > 256) this.checkpointOutputDigests.delete(this.checkpointOutputDigests.keys().next().value!); - return value; - } - private checkpointOutputAdvanced(worker: ResearchWorker, node: TaskRecord, - checkpoint: Pick) { - const draft = this.archive.researchDrafts?.[node.task.id], assignment = node.assignment; - // The retained commit supplies the component identities missing from older checkpoint records. - // A worktree released for another responsibility is not this task's new output. - if (!draft || draft.suspended || !assignment || draft.taskDigest !== checkpoint.taskDigest || - draft.workerId !== worker.id || draft.assignmentId !== assignment.assignmentId || - draft.seedCommit !== assignment.seedCommit || draft.canonicalCommit !== assignment.canonicalCommit || - draft.outputDigest !== checkpoint.outputDigest) return false; - const commit = git(worker.worktree, ['rev-parse', 'HEAD']); - if (commit === draft.commit) return false; - const sourceDigest = this.leanSourceDigest(worker.worktree, commit); - const sourceChanged = sourceDigest !== this.leanSourceDigest(worker.worktree, draft.commit); - const notesBlob = git(worker.worktree, ['ls-tree', '--format=%(objectname)', commit, '--', 'RESEARCH.md']); - const notesChanged = Boolean(notesBlob && notesBlob !== git(worker.worktree, - ['ls-tree', '--format=%(objectname)', draft.commit, '--', 'RESEARCH.md']) && - committedSource(worker.worktree, commit, 'RESEARCH.md').trim()); - if (!sourceChanged && !notesChanged) return false; - const resets = [...new Set([assignment.seedCommit, assignment.canonicalCommit, this.archive.canonicalCommit] - .filter((value): value is string => Boolean(value)))]; - const sourceAdvanced = sourceChanged && resets.every(reset => this.leanSourceDigest(worker.worktree, reset) !== sourceDigest); - if (!sourceAdvanced && !notesChanged) return false; - const rewind = mathGitResult(worker.worktree, ['merge-base', '--is-ancestor', commit, draft.commit], { maxBuffer: 4096 }); - if (rewind.error) throw rewind.error; - if (rewind.status === 0) return false; - if (rewind.status !== 1) throw new Error('math_research_workspace_unavailable'); - // Reseeding may save a different HEAD without producing a new investigation. - const outputDigest = this.checkpointOutputDigest(worker.worktree, commit); - return outputDigest !== checkpoint.outputDigest && - this.checkpointOutputDigest(worker.worktree, draft.commit) === checkpoint.outputDigest && - !resets.some(reset => this.checkpointOutputDigest(worker.worktree, reset) === outputDigest); - } - private leanSourceDigest(worktree: string, commit: string) { - const key = `${worktree}\0${commit}`, cached = this.leanSourceDigests.get(key); - if (cached) return cached; - const problem = this.input.state.problem; - const value = mathDigest(canonicalMathJson(problem.ownedFiles.filter(file => file.endsWith('.lean')).sort().map(file => - [file, mathDigest(committedSource(worktree, commit, `${problem.projectRelative}/${file}`))]))); - this.leanSourceDigests.set(key, value); - if (this.leanSourceDigests.size > 256) this.leanSourceDigests.delete(this.leanSourceDigests.keys().next().value!); - return value; - } - private taskSourceDigest(task: CooperativeTask, worktree: string, commit: string, local = false) { - const source = committedSource(worktree, commit, `${this.input.state.problem.projectRelative}/${task.proofPath}`); - const targets = inspectLeanDeclarationRegions(source).filter(region => - region.name.split('.').at(-1) === task.theoremName?.split('.').at(-1)); - if (targets.length !== 1) return `declaration-count:${targets.length}`; - // Selecting a different saved proof is new input; renaming the same declaration is not. - const target = source.slice(targets[0].startOffset, targets[0].endOffset) - .replace(/^(theorem|lemma)(\s+)[^\s([{:\n]+/u, '$1$2__task_target'); - return mathDigest(canonicalMathJson({ ...(local ? {} : { file: task.proofPath, offset: targets[0].startOffset }), source: target })); - } - private failedTaskBasis(task: CooperativeTask, conditions?: readonly CooperativeTask[], - assignment = this.node(task.id)?.assignment) { - const taskDigest = digest(task); - const declarationDigest = mathDigest(canonicalMathJson([task.proofPath, task.theoremName])); - const normalized = task.kind === 'lemma' ? { ...task, theoremName: undefined, proofPath: undefined } : task; - conditions ??= this.assignmentConditions(task, assignment); - const node = this.node(task.id), routeId = node && selectedTaskRoute(node, this.archive.tasks)?.id; - const raw = routeBlockerBasis(normalized, this.archive.tasks, this.input.state.environmentDigest, - this.input.state.problem.receiptDigest, routeId); - const contractDigest = mathDigest(canonicalMathJson({ problemReceiptDigest: this.input.state.problem.receiptDigest, - kind: normalized.kind, proofPath: normalized.proofPath, theoremName: normalized.theoremName, - type: normalized.type, premises: normalized.premises ?? [], conditional: Boolean(normalized.conditional), - conditions: conditions.map(task => ({ kind: task.kind, type: task.type, premises: task.premises ?? [] })) })); - const environmentDigest = mathDigest(canonicalMathJson({ environmentDigest: this.input.state.environmentDigest, - buildDigest: this.input.state.buildDigest, evaluatorDigest: this.input.state.evaluatorDigest, - environment: projectMathematicsRuntimeEnvironment(this.input.access.get(this.lead.id)?.environment ?? {}) })); - const previous = this.archive.failedTaskInputs?.findLast(record => record.basis.contractDigest === contractDigest && - record.basis.environmentDigest === environmentDigest && this.sameFailedDeclaration(record, { taskDigest, declarationDigest })) ?? - this.archive.failedTaskInputs?.findLast(record => record.basis.contractDigest === contractDigest && - this.reusableMissingDeclaration(record, task.id)); - const basis: BlockerBasis = { contractDigest, environmentDigest, - dependencies: Object.fromEntries(Object.entries(raw.dependencies).map(([id, entry]) => { - const dependency = this.node(id), proof = dependency?.integratedCheck; - const fresh = dependency?.status === 'integrated' && proof && hasTaskAcceptance(proof) && - proof.taskDigest === digest(dependency.task) && !proof.conditions?.length; - const prior = previous?.basis.dependencies[id] ?? Object.values(previous?.basis.dependencies ?? {}) - .find(candidate => candidate.contractDigest === entry.contractDigest); - return [id, { ...entry, evidenceDigest: fresh && entry.evidenceDigest ? entry.evidenceDigest : - prior?.contractDigest === entry.contractDigest ? prior.evidenceDigest : undefined }]; - })) }; - // Dependency task IDs, revision counters and replayed receipts do not change the mathematics. - const inputDigest = mathDigest(canonicalMathJson({ contractDigest, environmentDigest, - dependencies: Object.values(basis.dependencies).map(entry => canonicalMathJson(entry)).sort() })); - return { basis, inputDigest, taskId: task.id, taskDigest, declarationDigest }; - } - private missingTaskDeclaration(record: FailedTaskInput) { - return record.targetDigest === 'declaration-count:0' && record.feedback.startsWith('math_task_missing_declaration\n'); - } - private sameFailedDeclaration(record: FailedTaskInput, candidate: Pick) { - return record.declarationDigest === undefined ? record.taskDigest === candidate.taskDigest : - record.declarationDigest === candidate.declarationDigest; - } - private reusableMissingDeclaration(record: FailedTaskInput, taskId: string) { - // Preserve deduplication when a plan replaces a missing helper with a renamed version of the same contract. - return this.missingTaskDeclaration(record) && (record.taskId === taskId || !this.node(record.taskId)); - } - private sameFailedTaskBasis(record: FailedTaskInput, - candidate: Pick) { - const sameDeclaration = this.sameFailedDeclaration(record, candidate); - const sameMissing = candidate.targetDigest === record.targetDigest && - (sameDeclaration ? this.missingTaskDeclaration(record) : this.reusableMissingDeclaration(record, candidate.taskId)); - if (!sameMissing && !sameDeclaration) return false; - if (record.inputDigest === candidate.inputDigest) return true; - // A different checker cannot materialize a declaration absent from these same sources. - // Still reopen for changed contracts, assumptions, checked dependencies or selected route inputs. - if (!sameMissing || record.basis.contractDigest !== candidate.basis.contractDigest) return false; - const dependencies = (basis: BlockerBasis) => Object.values(basis.dependencies).map(entry => canonicalMathJson(entry)).sort(); - return canonicalMathJson(dependencies(record.basis)) === canonicalMathJson(dependencies(candidate.basis)); - } - private previousTaskFailure(candidate: ReturnType) { - return this.archive.failedTaskInputs?.findLast(record => record.sourceDigest === candidate.sourceDigest && - record.targetDigest === candidate.targetDigest && this.sameFailedTaskBasis(record, candidate)); - } - protected failedTaskInput(task: CooperativeTask, assignment: TaskAssignment, worktree: string, commit: string, conditions?: readonly CooperativeTask[]) { - const input = this.failedTaskBasis(task, conditions, assignment), sourceDigest = this.leanSourceDigest(worktree, commit); - const targetDigest = this.taskSourceDigest(task, worktree, commit); - const localTargetDigest = this.taskSourceDigest(task, worktree, commit, true); - return { id: mathDigest(canonicalMathJson({ inputDigest: input.inputDigest, declarationDigest: input.declarationDigest, sourceDigest, targetDigest })), - ...input, - ...(!localTargetDigest.startsWith('declaration-count:') ? { - attemptFingerprint: mathDigest(canonicalMathJson({ inputDigest: input.inputDigest, target: localTargetDigest })), - } : {}), - sourceDigest, targetDigest, seedSourceDigest: this.leanSourceDigest(worktree, assignment.seedCommit), - seedTargetDigest: this.taskSourceDigest(task, worktree, assignment.seedCommit), - canonicalSourceDigest: this.leanSourceDigest(this.lead.worktree, this.archive.canonicalCommit!), - canonicalTargetDigest: this.taskSourceDigest(task, this.lead.worktree, this.archive.canonicalCommit!) }; - } - protected rememberTaskFailure(candidate: Omit, feedback: string, repair?: FailedTaskInput['repair']) { - const records = this.archive.failedTaskInputs ??= []; - const previous = records.find(record => record.id === candidate.id); - if (previous) return previous; - const related = candidate.attemptFingerprint && records.findLast(record => record.attemptFingerprint === candidate.attemptFingerprint); - const relatedFailureIds = related ? [related.id] : []; - const record: FailedTaskInput = { ...candidate, feedback: bounded(feedback, 8000), - ...(relatedFailureIds.length ? { relatedFailureIds } : {}), ...(repair ? { repair } : {}) }; - records.push(record); - if (relatedFailureIds.length) { - this.wakeLead('task-repeated-attempt'); - this.input.emit('task_attempt_repeated_advisory', { taskId: record.taskId, failureId: record.id, - attemptFingerprint: record.attemptFingerprint, relatedFailureIds, evidence: 'same-target-and-local-inputs-not-equivalence' }); - } - this.input.emit('task_failed_input_recorded', { taskId: record.taskId, taskDigest: record.taskDigest, - failureId: record.id, inputDigest: record.inputDigest, sourceDigest: record.sourceDigest }); - this.input.save(); - return record; - } - private deterministicTaskFailure(proof: TaskProof) { - if (!proof.passed && isAttributedTaskProof(proof) && proof.verification.results.length === 1 && - hasLeanResourceLimitFailure(proof.verification)) return true; - return !proof.passed && proof.verification.status === 'failed' && Boolean(proof.verification.targetCommit) && - proof.verification.results.length > 0 && proof.verification.results.every(result => !result.cleanupError && - ['failed', 'kernel_verified'].includes(result.status) && - !/(?:timed?\s*out|timeout|rate[- ]limit|unauthenticated|unauthorized|authentication|request (?:failed|error)|stream disconnected)/iu.test(result.error ?? '')) && - proof.verification.results.some(result => result.status === 'failed' && - ((result.sorryCount ?? 0) > 0 || (result.admitCount ?? 0) > 0 || - hasLeanSourceDiagnostic(`${result.stdoutPreview || ''}\n${result.stderrPreview || ''}`))); - } - protected pendingTaskRepair(node: TaskRecord, record: FailedTaskInput) { - const repair = record.repair; - return Boolean(repair?.pending && repair.taskId === node.task.id && repair.taskDigest === digest(node.task) && - node.assignment?.workerId === repair.workerId && node.assignment.taskDigest === repair.taskDigest); - } - /** Transport-only turns are not proof failures; source and typed corrections share one saved grant. */ - protected firstTaskRepair(node: TaskRecord, failureId?: string) { - const version = digest(node.task); - return node.sourceRepair?.taskDigest !== version && !this.archive.failedTaskInputs?.some(record => - record.taskId === node.task.id && record.taskDigest === version && (record.id !== failureId || record.repair)); - } - private reportedTaskMathematicalBlocker(node: TaskRecord, candidate: ReturnType) { - const assignment = node.assignment; - if (!assignment || assignment.taskDigest !== candidate.taskDigest || digest(node.task) !== candidate.taskDigest || - candidate.targetDigest !== 'declaration-count:0') return false; - const gaps = mathematicalGaps(this.archive, { problemReceiptDigest: this.input.state.problem.receiptDigest, - environmentDigest: this.input.state.environmentDigest }, node.task); - return gaps.some(gap => { - if (gap.scopeStatus !== 'current-contracts' || gap.scope.source.id !== node.task.id) return false; - const delivery = this.archive.deliveries!.find(record => record.id === gap.deliveryId)!; - if (delivery.producer !== assignment.workerId || delivery.assignmentKey !== assignmentDeliveryFile(assignment) || !delivery.commit) return false; - const finding = deliveryFinding(delivery); - if (!finding || this.leanSourceDigest(this.lead.worktree, delivery.commit) !== candidate.sourceDigest) return false; - const report = JSON.parse(finding); - return (report.needsDecision === true || delivery.leadDecisionRequested) && - ['inconclusive', 'refuted'].includes(report.conclusion); - }); - } - private repeatedTaskFeedback(record: FailedTaskInput) { - return 'math_task_repeated_failed_input\nThe same Lean source and mathematical inputs already failed. ' + - 'Save a changed proof or supply new premises, checked dependency evidence, or verifier inputs before retrying.\n' + record.feedback; - } - protected refreshFailedTaskInputs() { - if (!this.archive.failedTaskInputs?.length) return false; - let changed = false; - const canonicalSourceDigest = this.leanSourceDigest(this.lead.worktree, this.archive.canonicalCommit!); - for (const node of this.archive.tasks) { - if (advisory(node.task) || !['pending', 'blocked'].includes(node.status) || - [node.proof, node.integratedCheck].some(proof => proof?.passed && proof.taskDigest === digest(node.task))) continue; - const candidate = this.failedTaskBasis(node.task); - const worker = this.input.workers.find(worker => worker.id === node.assignment?.workerId); - const session = worker && this.input.state.workers?.find(record => record.id === worker.id); - const active = worker && this.active.get(worker.id)?.action; - const ownsOutput = worker && node.assignment?.taskDigest === candidate.taskDigest && - (!session || session.sessionTaskId === node.task.id && (!session.sessionTaskVersion || session.sessionTaskVersion === candidate.taskDigest)) && - (!active || active.kind === 'task' && active.task.id === node.task.id && active.assignment === node.assignment) && - ![...this.preparingTaskTypes].some(([other, prep]) => other !== node && prep.workerId === worker.id) && - !this.archive.tasks.some(other => other !== node && other.status === 'running' && other.assignment?.workerId === worker.id); - const worktree = ownsOutput ? worker.worktree : this.lead.worktree; - const commit = ownsOutput ? git(worktree, ['rev-parse', 'HEAD']) : this.archive.canonicalCommit!; - const sourceDigest = this.leanSourceDigest(worktree, commit); - const targetDigest = this.taskSourceDigest(node.task, worktree, commit); - // A host reseed can replace the failed candidate with its unchanged canonical inputs before a new session starts. - const record = this.archive.failedTaskInputs.findLast(record => this.sameFailedTaskBasis(record, { ...candidate, targetDigest }) && - (record.sourceDigest === sourceDigest && record.targetDigest === targetDigest || sourceDigest === canonicalSourceDigest && - (record.seedSourceDigest === sourceDigest && record.seedTargetDigest === targetDigest || - record.canonicalSourceDigest === sourceDigest && record.canonicalTargetDigest === targetDigest))); - if (record && !this.pendingTaskRepair(node, record)) { - const feedback = this.repeatedTaskFeedback(record); - if (node.status === 'blocked' && node.feedback === feedback) continue; - this.moveTask(node, 'blocked', 'input-blocked'); node.feedback = feedback; this.wakeLead('task-repeated-input-blocked'); changed = true; - this.input.emit('task_repeated_input_blocked', { taskId: node.task.id, taskDigest: candidate.taskDigest, - failureId: record.id, inputDigest: candidate.inputDigest, sourceDigest }); - } else if (!record && node.status === 'blocked' && node.feedback?.startsWith('math_task_repeated_failed_input\n')) { - this.moveTask(node, 'pending', 'reopened'); node.feedback = undefined; changed = true; - this.input.emit('task_failed_input_reopened', { taskId: node.task.id, inputDigest: candidate.inputDigest, sourceDigest }); - } - } - return changed; - } - protected refreshResearchCheckpoints() { - for (const [taskId, checkpoint] of Object.entries(this.archive.researchCheckpoints ?? {})) { - if (!checkpoint.paused) continue; - const node = this.node(taskId), worker = this.input.workers.find(worker => worker.id === node?.assignment?.workerId); - if (!node || digest(node.task) !== checkpoint.taskDigest) { delete this.archive.researchCheckpoints![taskId]; continue; } - if (!worker || node.status !== 'blocked' || !node.feedback?.startsWith('math_research_checkpoint_unchanged')) continue; - const localInputDigest = this.checkpointLocalInputDigest(node.task, worker.id); - const inputChanged = !this.checkpointInputMatches(node, worker.id, checkpoint, localInputDigest); - // Upgrade a matching old pause before processing the next publication after restore. - if (!inputChanged && node.nextCheckId) checkpoint.localInputDigest = localInputDigest; - // Seeding another responsibility suspends its old draft before the new model session exists. - // That host-written output cannot advance the paused task, even while its session id is stale. - const session = this.input.state.workers?.find(record => record.id === worker.id), active = this.active.get(worker.id)?.action; - const ownsOutput = !this.archive.researchDrafts?.[taskId]?.suspended && (!session || session.sessionTaskId === taskId && - (!session.sessionTaskVersion || session.sessionTaskVersion === checkpoint.taskDigest)) && - (!active || active.kind === 'task' && active.task.id === taskId && active.assignment.taskDigest === checkpoint.taskDigest) && - !this.archive.tasks.some(other => other.task.id !== taskId && other.status === 'running' && other.assignment?.workerId === worker.id); - const outputChanged = !inputChanged && ownsOutput && this.checkpointOutputAdvanced(worker, node, checkpoint); - if (!inputChanged && !outputChanged) { - // The pause is still current, so its obstruction now parks this input for the Lead instead of - // leaving silently blocked. Parking is a scheduling verdict only: it names what must change and - // never accepts or refutes anything. Escalate once so repeated passes stay quiet. - const parking = this.archive.blockers?.find(record => record.id === checkpoint.blockerId); - if (parking?.status === 'open') { - parking.status = 'parked'; parking.count = Math.max(parking.count, 2); parking.updatedAt = Date.now(); - this.input.emit('route_parked', { blockerId: parking.id, taskId: parking.taskId, groupId: parking.groupId, - count: parking.count, scope: parking.scope, evidenceStatus: parking.evidenceStatus, reopenOn: parking.reopenOn }); - } - continue; - } - const blocker = this.archive.blockers?.find(record => record.id === checkpoint.blockerId); - if (blocker) { blocker.status = 'reopened'; blocker.reopenedReason = inputChanged ? 'checkpoint-input-changed' : 'checkpoint-output-changed'; } - this.moveTask(node, 'pending', 'reopened'); node.feedback = undefined; - delete this.archive.researchCheckpoints![taskId]; - this.input.emit('research_checkpoint_reopened', { taskId, reason: inputChanged ? 'new-input' : 'new-output' }); - } - } - protected preserveResearchDraft(worker: ResearchWorker, action: Extract, - commit: string, artifacts: DeliveryArtifactManifest, restored?: { handoffNotesDigest?: string }) { - const notesDigest = committedResearchNotesDigest(worker.worktree, commit); - const previous = this.archive.researchDrafts?.[action.task.id], assignment = action.assignment; - const retainedNotesDigest = previous?.taskDigest === assignment.taskDigest && previous.workerId === worker.id && - previous.assignmentId === assignment.assignmentId && previous.seedCommit === assignment.seedCommit && - previous.canonicalCommit === assignment.canonicalCommit ? previous.handoffNotesDigest : undefined; - const research = this.input.state.workers?.find(record => record.id === worker.id) ?? this.input.state; - // Restoring bytes is a host operation, so it must carry attribution from the inspected old snapshot. - // Ordinary saves may establish it by changing the assignment's seed notes or acknowledging their digest. - const handoffNotesDigest = restored - ? notesDigest && notesDigest === restored.handoffNotesDigest ? notesDigest : undefined - : researchHandoffNotesDigest(notesDigest, committedResearchNotesDigest(worker.worktree, assignment.seedCommit), - retainedNotesDigest, savedContextCheckpoint(research, worker.worktree)); - (this.archive.researchDrafts ??= {})[action.task.id] = { taskDigest: action.assignment.taskDigest, - workerId: worker.id, assignmentId: action.assignment.assignmentId, - seedCommit: action.assignment.seedCommit, canonicalCommit: action.assignment.canonicalCommit, - commit, outputDigest: this.checkpointOutputDigest(worker.worktree, commit), artifacts, handoffNotesDigest, - ...(isFeasibilityReview(action.task) ? { feasibilityInputDigest: assignment.feasibilityInputDigest } : {}) }; - this.pin(commit); - } - private pendingConnectionFinding(assignment: TaskAssignment, checkpointCommit: string) { - const key = assignmentDeliveryFile(assignment); - const candidates = (this.archive.deliveries ?? []).filter(record => record.kind === 'research' && - record.assignmentKey === key && record.producer === assignment.workerId && - record.taskId === assignment.taskId && record.taskDigest === assignment.taskDigest && - (record.submissionId !== undefined || record.commit === checkpointCommit)); - if (!candidates.length) return; - return leadResearchInputs(candidates, new Map(this.archive.tasks.map(node => [node.task.id, node])), - this.archive.researchDecisions)[0]; - } - private bindConnectionFinding(node: TaskRecord, assignment: TaskAssignment, outputDigest: string, deliveryId: string) { - const connection = assignment.connectionCheck; - if (!connection) return false; - const inputDigest = this.checkpointInputDigest(node.task, assignment.workerId, false); - const previous = node.connectionCheckpoint; - if (previous?.basisDigest === connection.basisDigest && previous.inputDigest === inputDigest && - previous.outputDigest === outputDigest && previous.leadDeliveryId === deliveryId) return false; - node.connectionCheckpoint = { basisDigest: connection.basisDigest, inputDigest, outputDigest, leadDeliveryId: deliveryId }; - return true; - } - protected restoreConnectionHandoff(node: TaskRecord) { - const assignment = node.assignment, draft = this.archive.researchDrafts?.[node.task.id]; - if (!assignment?.connectionCheck || node.connectionCheckpoint?.leadDeliveryId || !draft || draft.suspended || - draft.taskDigest !== assignment.taskDigest || draft.workerId !== assignment.workerId || - draft.assignmentId !== assignment.assignmentId || draft.seedCommit !== assignment.seedCommit || - draft.canonicalCommit !== assignment.canonicalCommit) return; - // Older saves could capture the accepted finding and draft before binding the wait. - const pending = this.pendingConnectionFinding(assignment, draft.commit); - if (pending) this.bindConnectionFinding(node, assignment, draft.outputDigest, pending.id); - } - /** A scheduling handoff retains code without submitting an unfinished assigned declaration. */ - async retainContextDraft(worker: ResearchWorker, action: Extract, commit: string, - reason: 'context' | 'connection' = 'context') { - if (!this.current(action)) return; - const previous = this.archive.researchDrafts?.[action.task.id], assignment = action.assignment; - const previousOutput = previous?.taskDigest === assignment.taskDigest && previous.workerId === worker.id && - previous.assignmentId === assignment.assignmentId && previous.seedCommit === assignment.seedCommit && - previous.canonicalCommit === assignment.canonicalCommit ? previous.outputDigest : - this.checkpointOutputDigest(worker.worktree, assignment.seedCommit); - const artifacts = captureDeliveryArtifacts({ problem: this.input.state.problem, - worktree: worker.worktree, commit, assignment: action.assignment }); - this.preserveResearchDraft(worker, action, commit, artifacts); - const node = this.node(action.task.id), draft = this.archive.researchDrafts![action.task.id]; - const connection = reason === 'connection' ? assignment.connectionCheck : undefined; - const unchanged = previousOutput === draft.outputDigest; - const waiting = node.connectionCheckpoint; - const pending = assignment.connectionCheck && this.pendingConnectionFinding(assignment, commit); - const leadDeliveryId = pending?.id ?? (unchanged && waiting?.basisDigest === assignment.connectionCheck?.basisDigest - ? waiting?.leadDeliveryId : undefined); - if (leadDeliveryId) this.bindConnectionFinding(node, assignment, draft.outputDigest, leadDeliveryId); - else node.connectionCheckpoint = connection && unchanged - ? { basisDigest: connection.basisDigest, inputDigest: this.checkpointInputDigest(action.task, worker.id), - outputDigest: draft.outputDigest } : undefined; - if (draft.handoffNotesDigest) { - const notes = committedSource(worker.worktree, commit, 'RESEARCH.md'); - const finding = this.checkpointFinding(notes); - let report = finding?.checkOutcome === undefined && (finding?.conclusion === 'refuted' || finding?.needsDecision === true) - ? finding : undefined; - // Alert the Lead about stalled prose without interpreting it as a mathematical claim. - if (!finding && connection && unchanged && previous && - !this.dependencies(node.task).some(input => input.status === 'pending' && !advisory(input.task) && - assessTaskResponsibility(input, worker, this.responsibility).kind === 'matches' && - taskDependenciesReady(input.task, this.archive.tasks) && routeAllowsTask(input.task, this.archive.tasks, this.archive.groups)) && - !this.archive.deliveries?.some(record => record.kind === 'research' && record.status !== 'superseded' && - record.assignmentKey === assignmentDeliveryFile(assignment) && - record.sourceDigest === ownedSourceDigest(this.input.state.problem, worker.worktree, commit))) { - report = { conclusion: 'inconclusive', - summary: 'This proof checkpoint repeated with an unchanged draft. Inspect the saved RESEARCH.md and decide how to proceed.' }; - } - if (report) { - try { - taskChanges(this.input.state.problem, worker.worktree, commit, node.task, assignment); - await this.publishResearchFinding(worker, action, commit, { kind: 'event', value: { ...report, needsDecision: true } }, - { artifacts, checkpoint: true, connectionOutputDigest: assignment.connectionCheck && draft.outputDigest }); - } catch (error) { - if (!this.current(action)) return; - if (!(error instanceof Error) || !directDeliveryRejections.has(rejectionCode(error))) throw error; - this.rejectWorkerDelivery(worker, action, notes, error); - } - if (!this.current(action)) return; - } - } - if (!artifacts.artifacts.length || this.archive.deliveries?.some(record => record.producer === worker.id && - record.taskId === action.task.id && record.taskDigest === action.assignment.taskDigest && record.commit === commit)) return; - this.record(worker, action.task, 'progress', 'advisory', - `Supporting code saved at a ${reason} checkpoint. Inspect the retained commit and exact declarations before adopting typed work; the assigned proof remains unfinished.`, - { commit, artifacts, remainingObligations: [action.task.id] }); - } - /** New mathematical inputs or durable owned output earn another connection attempt. */ - protected refreshConnectionCheckpoints() { - for (const node of this.archive.tasks) { - const checkpoint = node.connectionCheckpoint, assignment = node.assignment; - if (!checkpoint || node.status !== 'pending') continue; - const worker = this.input.workers.find(worker => worker.id === assignment?.workerId); - if (!worker || !assignment || checkpoint.basisDigest !== assignment.connectionCheck?.basisDigest || - !taskConnectionCheckCurrent(node.task, assignment, this.archive.tasks, - { environmentDigest: this.input.state.environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest }) || - checkpoint.inputDigest !== this.checkpointInputDigest(node.task, worker.id, !checkpoint.leadDeliveryId) || - this.checkpointOutputAdvanced(worker, node, { taskDigest: assignment.taskDigest, outputDigest: checkpoint.outputDigest })) - node.connectionCheckpoint = undefined; - } - } - protected suspendResearchDrafts(worker: ResearchWorker, taskId?: string) { - let changed = false; - for (const [id, draft] of Object.entries(this.archive.researchDrafts ?? {})) - if (draft.workerId === worker.id && id !== taskId && !draft.suspended) { draft.suspended = true; changed = true; } - // Persist ownership before a different responsibility overwrites the worktree. - if (changed) this.input.save(); - } - protected researchWorkspaceChanged(worker: ResearchWorker, node: TaskRecord) { - if (isFeasibilityReview(node.task) && node.assignment?.feasibilityInputDigest !== - this.feasibilityInputDigest(node.task, worker.id)) return true; - const session = this.input.state.workers?.find(record => record.id === worker.id); - if (session?.sessionTaskId && (session.sessionTaskId !== node.task.id || - session.sessionTaskVersion && session.sessionTaskVersion !== digest(node.task))) return true; - if (!session?.sessionTaskId && - (session?.sessionStatementReview || session?.sessionRole && session.sessionRole !== 'researcher')) return true; - // Restoring another task's draft can move HEAD behind this assignment's seed. - // Session metadata alone does not establish ownership of the current checkout. - if (node.assignment) { - const ancestry = mathGitResult(worker.worktree, ['merge-base', '--is-ancestor', node.assignment.seedCommit, 'HEAD'], - { maxBuffer: 4096 }); - if (ancestry.error) throw ancestry.error; - if (ancestry.status === 1) return true; - if (ancestry.status !== 0) throw new Error('math_research_workspace_unavailable'); - } - if (session?.sessionTaskId) return false; - const checkpoint = this.archive.researchCheckpoints?.[node.task.id]; - return Boolean(checkpoint && checkpoint.outputDigest !== - this.checkpointOutputDigest(worker.worktree, git(worker.worktree, ['rev-parse', 'HEAD']))); - } - private async inspectResearchDraft(node: TaskRecord, assignment: TaskAssignment, - draft: NonNullable[string]) { - if (draft.taskDigest !== digest(node.task) || draft.workerId !== assignment.workerId || - draft.assignmentId !== assignment.assignmentId || draft.seedCommit !== assignment.seedCommit || - draft.canonicalCommit !== assignment.canonicalCommit || - draft.artifacts?.problemReceiptDigest !== this.input.state.problem.receiptDigest || - draft.artifacts?.taskId !== node.task.id || draft.artifacts?.taskDigest !== draft.taskDigest || - draft.artifacts?.seedCommit !== draft.seedCommit || draft.artifacts?.commit !== draft.commit) return; - const problem = this.input.state.problem; - return withSolverWorktree(this.lead.worktree, draft.commit, async checkout => { - const feedback = solverSourceFeedback(problem, checkout); - if (feedback) throw new Error(feedback); - if (this.checkpointOutputDigest(checkout, draft.commit) !== draft.outputDigest) - throw new Error('math_research_draft_output_changed'); - captureDeliveryArtifacts({ problem, worktree: checkout, commit: draft.commit, assignment }); - return { notes: git(checkout, ['ls-tree', '--format=%(objectname)', draft.commit, '--', 'RESEARCH.md']) - ? committedSource(checkout, draft.commit, 'RESEARCH.md') : undefined, - handoffNotesDigest: researchHandoffNotesDigest(committedResearchNotesDigest(checkout, draft.commit), - committedResearchNotesDigest(checkout, draft.seedCommit), draft.handoffNotesDigest), - canonicalSourceDigest: ownedSourceDigest(problem, checkout, draft.canonicalCommit ?? draft.seedCommit) }; - }); - } - /** Move a stopped research snapshot, never a live writer or its session, to a free peer. */ - protected async transferResearchDraft(worker: ResearchWorker, node: TaskRecord, current: () => boolean): Promise { - const assignment = node.assignment, draft = this.archive.researchDrafts?.[node.task.id]; - if (!assignment || !draft || !current()) return false; - const problem = this.input.state.problem; - const checkpoint = this.archive.researchCheckpoints?.[node.task.id]; - let sameCheckpointInput = false; - let prepared: { successor: TaskAssignment; commit: string; artifacts: DeliveryArtifactManifest; canonicalChanged: boolean; - handoffNotesDigest?: string }; - try { - const saved = await this.inspectResearchDraft(node, assignment, draft); - if (!saved || !current() || node.assignment !== assignment || this.archive.researchDrafts?.[node.task.id] !== draft) return false; - // Snapshot inspection yields to other publications. Only the inputs still - // current after that wait may inherit the old unchanged counters. - sameCheckpointInput = checkpoint?.taskDigest === digest(node.task) && this.checkpointInputMatches(node, assignment.workerId, - checkpoint, this.checkpointLocalInputDigest(node.task, assignment.workerId)); - const canonical = this.archive.canonicalCommit!; - const canonicalChanged = ownedSourceDigest(problem, this.lead.worktree, canonical) !== saved.canonicalSourceDigest; - this.suspendResearchDrafts(worker, node.task.id); - if (canonicalChanged) this.seed(worker, canonical, node.task); - else git(worker.worktree, ['reset', '--hard', draft.commit]); - const notesFile = path.join(worker.worktree, 'RESEARCH.md'); - if (saved.notes === undefined) fs.rmSync(notesFile, { force: true }); - else fs.writeFileSync(notesFile, saved.notes); - const commit = commitSolverSources(problem, worker.worktree); - const successor: TaskAssignment = { taskId: node.task.id, taskDigest: digest(node.task), workerId: worker.id, - assignmentId: crypto.randomUUID(), seedCommit: canonicalChanged ? commit : assignment.seedCommit, - canonicalCommit: canonicalChanged ? canonical : assignment.canonicalCommit, groupId: taskGroup(node.task), - routeId: assignment.routeId, - dependencies: this.dependencies(node.task).map(input => ({ taskId: input.task.id, taskDigest: digest(input.task) })) }; - const artifacts = captureDeliveryArtifacts({ problem, worktree: worker.worktree, commit, assignment: successor }); - this.pin(draft.commit); this.pin(commit); - prepared = { successor, commit, artifacts, canonicalChanged, handoffNotesDigest: saved.handoffNotesDigest }; - } catch (error) { - this.input.signal.throwIfAborted(); - this.input.emit('research_draft_transfer_failed', { taskId: node.task.id, workerId: worker.id, - reason: error instanceof Error ? error.message : 'math_research_draft_transfer_failed' }); - return false; - } - const { successor, commit, artifacts, canonicalChanged, handoffNotesDigest } = prepared; - node.assignment = successor; - this.preserveResearchDraft(worker, { kind: 'task', task: node.task, assignment: successor }, commit, artifacts, { handoffNotesDigest }); - // Keep the original writer and immutable source as advisory provenance; its - // late events no longer match the successor assignment object or delivery log. - // Persistence failures propagate after installing the successor, rather than - // returning a retryable failure for a transfer that already changed ownership. - const previousWorker = this.input.workers.find(peer => peer.id === assignment.workerId)!; - this.record(previousWorker, node.task, 'progress', 'advisory', - 'Saved research draft transferred to an available peer. The original snapshot remains advisory and requires independent checking.', - { commit: draft.commit, artifacts: draft.artifacts, assignmentKey: assignmentDeliveryFile(assignment), - remainingObligations: [node.task.id] }); - if (checkpoint && sameCheckpointInput && this.archive.researchCheckpoints?.[node.task.id] === checkpoint && - checkpoint.outputDigest === this.checkpointOutputDigest(worker.worktree, commit)) { - // Changing the writer and emitting handoff provenance is not mathematical - // progress. Keep the task's unchanged-count and backoff across the transfer. - checkpoint.localInputDigest = this.checkpointLocalInputDigest(node.task, worker.id); - checkpoint.inputDigest = this.checkpointInputDigest(node.task, worker.id); - } - this.input.emit('research_draft_transferred', { taskId: node.task.id, taskDigest: successor.taskDigest, - fromWorkerId: assignment.workerId, workerId: worker.id, sourceCommit: draft.commit, commit, - previousAssignmentId: assignment.assignmentId, assignmentId: successor.assignmentId, canonicalChanged }); - this.input.save(); - return true; - } - protected async restoreResearchDraft(worker: ResearchWorker, node: TaskRecord, refreshDependencies = false): Promise { - const draft = this.archive.researchDrafts?.[node.task.id], assignment = node.assignment!; - if (!draft || assignment.workerId !== worker.id) return false; - const problem = this.input.state.problem; - try { - const feasibility = isFeasibilityReview(node.task); - const resumeInput = () => draft.feasibilityInputDigest === assignment.feasibilityInputDigest - ? resumableFeasibilityReviewInput(this.feasibilityInput(node.task, worker.id), draft) : undefined; - let feasibilityInputDigest = feasibility ? resumeInput() : undefined; - if (feasibility && !feasibilityInputDigest) { - draft.suspended = true; - this.input.emit('research_draft_restore_failed', { taskId: node.task.id, - reason: 'math_feasibility_draft_input_changed' }); - this.input.save(); - return false; - } - const saved = await this.inspectResearchDraft(node, assignment, draft); - if (!saved || !this.archive.tasks.includes(node) || node.assignment !== assignment || - this.archive.researchDrafts?.[node.task.id] !== draft || digest(node.task) !== draft.taskDigest || - node.status !== 'pending' || assignment.workerId !== worker.id || node.task.ownerId && node.task.ownerId !== worker.id || - !independentFeasibilityWorker(node, worker, this.archive.tasks, this.archive.groups) || - !taskCanStart(node.task, this.archive.tasks, this.archive.groups) || !routeAllowsTask(node.task, this.archive.tasks, this.archive.groups)) return false; - // Snapshot inspection yields. Recheck against the latest inputs before restoring. - if (feasibility && !(feasibilityInputDigest = resumeInput())) { - draft.suspended = true; - this.input.save(); - return false; - } - const canonicalChanged = ownedSourceDigest(problem, this.lead.worktree, this.archive.canonicalCommit!) !== saved.canonicalSourceDigest; - const reseed = canonicalChanged || refreshDependencies; - const hasDraftSources = draft.artifacts.artifacts.some(artifact => artifact.kind === 'owned-source'); - let restoredAssignment = assignment; - this.suspendResearchDrafts(worker, node.task.id); - if (reseed) { - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), ''); - const seedCommit = this.seed(worker, this.archive.canonicalCommit!, node.task); - // A connection permission binds the old seed and dispatch, so the normal - // dispatcher must rebuild it for the restored sources and new identity. - restoredAssignment = { ...assignment, assignmentId: crypto.randomUUID(), seedCommit, - canonicalCommit: this.archive.canonicalCommit, connectionCheck: undefined, - ...(refreshDependencies ? { researchBasis: undefined, canonicalProbe: undefined } : {}), - ...(feasibility ? { feasibilityInputDigest } : {}) }; - } else { - // Restore the validated snapshot so its frozen seed remains an ancestor. - git(worker.worktree, ['reset', '--hard', draft.commit]); - } - // Preserve the distinction between missing notes and an empty tracked file. - const notesFile = path.join(worker.worktree, 'RESEARCH.md'); - if (saved.notes === undefined) fs.rmSync(notesFile, { force: true }); - else fs.writeFileSync(notesFile, saved.notes); - const seed = commitSolverSources(problem, worker.worktree); - // A rebased assignment starts with the restored notes too. Otherwise the host's restoration - // looks like a fresh notes write relative to an empty seed and can attribute inherited text. - if (reseed) restoredAssignment.seedCommit = seed; - const replay = reseed && !advisory(node.task) - ? this.replayDraftSources(worker, node.task, restoredAssignment, draft.seedCommit, draft.commit) : undefined; - const commit = replay?.commit ?? seed; - const artifacts = replay?.artifacts ?? captureDeliveryArtifacts({ problem, worktree: worker.worktree, commit, assignment: restoredAssignment }); - node.assignment = restoredAssignment; - this.preserveResearchDraft(worker, { kind: 'task', task: node.task, assignment: restoredAssignment }, - commit, artifacts, { handoffNotesDigest: saved.handoffNotesDigest }); - if (reseed && !replay && hasDraftSources) { - this.record(worker, node.task, 'progress', 'advisory', - 'Saved research source draft retained separately while the canonical proof advanced. Inspect the retained commit to recover useful edits.', - { commit: draft.commit, artifacts: draft.artifacts, remainingObligations: [node.task.id] }); - } - this.input.emit('research_draft_restored', { taskId: node.task.id, commit, canonicalChanged }); - this.input.save(); - return true; - } catch (error) { - this.input.signal.throwIfAborted(); - this.input.emit('research_draft_restore_failed', { taskId: node.task.id, - reason: error instanceof Error ? error.message : 'math_research_draft_restore_failed' }); - return false; - } - } - private replayDraftSources(worker: ResearchWorker, task: CooperativeTask, assignment: TaskAssignment, oldSeed: string, draft: string) { - const problem = this.input.state.problem; - const files = problem.ownedFiles.filter(file => file.endsWith('.lean') && !Object.hasOwn(problem.frozenFiles ?? {}, file)) - .map(file => path.join(problem.projectRelative, file)); - if (oldSeed === draft || !files.length) return; - const options = { maxBuffer: 16 * 1024 * 1024 }; - const patch = mathGitResult(worker.worktree, ['--literal-pathspecs', 'diff', '--no-ext-diff', '--no-textconv', '--binary', - '--no-renames', '--src-prefix=a/', '--dst-prefix=b/', oldSeed, draft, '--', ...files], options); - if (patch.error || patch.status !== 0 || !patch.stdout.length) return; - const applied = mathGitResult(worker.worktree, ['apply', '--3way', '--whitespace=nowarn', '-'], - { ...options, input: patch.stdout }); - if (!applied.error && applied.status === 0) { - try { - const commit = commitSolverSources(problem, worker.worktree); - taskChanges(problem, worker.worktree, commit, task, assignment); - return { commit, artifacts: captureDeliveryArtifacts({ problem, worktree: worker.worktree, commit, assignment }) }; - } catch { /* An invalid draft can still be inspected at its original commit. */ } - } - git(worker.worktree, ['reset', '--hard', assignment.seedCommit]); - } - protected async researchCheckpoint(worker: ResearchWorker, action: Extract, commit: string, countStagnation: boolean) { - if (isFeasibilityReview(action.task) && !this.node(action.task.id).nextCheckId) { - // A saved independent review is only a handoff, even if its notes contain a provisional result. - // Do not publish it, complete the review or apply ordinary research stagnation parking. - // Host-scoped next checks retain their explicit partial-finding/outcome protocol below. - this.input.emit('feasibility_review_checkpoint_saved', { taskId: action.task.id, workerId: worker.id, - commit, inputDigest: action.assignment.feasibilityInputDigest, acceptance: 'not-assessed' }); - this.interrupted(worker, action); - return; - } - const node = this.node(action.task.id), taskDigest = digest(node.task); - const notesBlob = git(worker.worktree, ['ls-tree', '--format=%(objectname)', commit, '--', 'RESEARCH.md']); - const notes = notesBlob ? committedSource(worker.worktree, commit, 'RESEARCH.md') : ''; - const artifacts = this.archive.researchDrafts?.[node.task.id]?.artifacts; - const previous = this.archive.researchCheckpoints?.[node.task.id]; - const advisoryCheckpoint = this.input.state.workers?.find(record => record.id === worker.id)?.advisoryCheckpoint; - const checkpointScope = mathDigest(canonicalMathJson({ kind: 'task', taskDigest })); - let checkpoint: NonNullable[string] | undefined; - if (countStagnation) { - const inputDigest = this.checkpointInputDigest(node.task, worker.id), outputDigest = this.checkpointOutputDigest(worker.worktree, commit); - const localInputDigest = this.checkpointLocalInputDigest(node.task, worker.id); - const candidate = checkpointCandidate(notes, artifacts); - const sameInput = previous?.taskDigest === taskDigest && this.checkpointInputMatches(node, worker.id, previous, localInputDigest); - const count = sameInput && previous.outputDigest === outputDigest - ? previous.count + 1 : 1; - const unchangedEvidenceCount = sameInput && previous.candidateOutputDigest === candidate.digest - ? (previous.unchangedEvidenceCount ?? 1) + 1 : 1; - const paused = count >= 3 && unchangedEvidenceCount >= 2; - checkpoint = (this.archive.researchCheckpoints ??= {})[node.task.id] = { taskDigest, inputDigest, outputDigest, - localInputDigest, candidateOutputDigest: candidate.digest, candidateStatus: candidate.status, unchangedEvidenceCount, count, paused, - ...(advisoryCheckpoint?.scope === checkpointScope ? { advisoryCheckpoint: { ...advisoryCheckpoint } } : {}) }; - this.input.emit('research_checkpoint_recorded', { taskId: node.task.id, ...checkpoint }); - } else { - if (previous?.taskDigest === taskDigest && advisoryCheckpoint?.scope === checkpointScope) - previous.advisoryCheckpoint = { ...advisoryCheckpoint }; - this.input.emit('research_proof_handoff_saved', { taskId: node.task.id, workerId: worker.id, commit }); - } - // A checkpoint is a partial publication, not a completed investigation. Only - // explicit control JSON is eligible; ordinary prose and unfinished JSON remain drafts. - const finding = this.checkpointFinding(notes); - const inherited = git(worker.worktree, ['ls-tree', '--format=%(objectname)', action.assignment.seedCommit, '--', 'RESEARCH.md']); - // Scoped checkOutcome has a separate completion protocol; never settle it merely - // because the scheduler yielded its writer. - if (finding && finding.checkOutcome === undefined && notesBlob !== inherited) { - taskChanges(this.input.state.problem, worker.worktree, commit, node.task, action.assignment); - await this.publishResearchFinding(worker, action, commit, { kind: 'notes', text: notes }, { artifacts, checkpoint: true }); - if (!this.current(action)) return; - } - if (checkpoint?.paused) { - const { inputDigest, outputDigest } = checkpoint; - const scope = `assigned-local-inference/checkpoint:${mathDigest(canonicalMathJson({ inputDigest, outputDigest }))}`; - this.reportBlockers(node.task, [{ mechanism: 'unchanged-research-checkpoint', scope }]); - Object.assign(checkpoint, { blockerId: this.archive.blockers?.find(record => record.taskId === node.task.id && record.scope === scope)?.id }); - this.rejected(action, UNCHANGED_RESEARCH_CHECKPOINT, commit); - } else this.interrupted(worker, action); - } - private checkpointFinding(notes: string): Record | undefined { - try { return parseMathResponse(notes, 'math-result') as Record; } - catch (error) { - if (!(error instanceof SyntaxError) && !(error instanceof Error && - ['math_math-result_requires_one_block', 'math_response_invalid'].includes(error.message))) throw error; - } - } - - protected async publishResearchFinding(worker: ResearchWorker, action: Extract, commit: string, - submission: ResearchSubmission, options: Partial & { checkpoint?: boolean; connectionOutputDigest?: string } = {}, - sources?: unknown, probes?: unknown) { - const { checkpoint = false, connectionOutputDigest, ...deliveryOptions } = options; - // A publication belongs to the inputs dispatched to this writer, even if its live - // assignment gains a newer context while the asynchronous checks are running. - const assignment = structuredClone(action.assignment), basis = assignment.researchBasis; - const assignmentKey = assignmentDeliveryFile(assignment); - const environmentDigest = this.input.state.environmentDigest, problemReceiptDigest = this.input.state.problem.receiptDigest; - // Explicit bytes form one immutable event snapshot. Never read the live writer's - // source files or index while publishing advisory support. - let sourceSnapshot: [string, string][] | undefined; - if (sources !== undefined) { - const owned = this.input.state.problem.ownedFiles.filter(file => file.endsWith('.lean') && - !Object.hasOwn(this.input.state.problem.frozenFiles ?? {}, file)); - const invalid = (message: string) => new ResearchAdmissionError({ status: 'rejected', code: 'math_delivery_invalid', - issues: [{ path: 'sources', message }], recovery: 'correct-and-resubmit' }); - if (submission.kind !== 'event' || !sources || typeof sources !== 'object' || Array.isArray(sources)) - throw invalid('Provide the complete owned Lean sources as an object of file paths to source strings.'); - const entries = Object.entries(sources); - if (entries.length !== owned.length || entries.some(([file, source]) => !owned.includes(file) || typeof source !== 'string')) - throw invalid('Include every owned .lean file exactly once, using problem-relative paths and complete source strings.'); - sourceSnapshot = entries as [string, string][]; - if (sourceSnapshot.reduce((bytes, [, source]) => bytes + Buffer.byteLength(source), 0) > MAX_RESEARCH_NOTES_BYTES) - throw invalid('The combined owned Lean source snapshot must not exceed ' + MAX_RESEARCH_NOTES_BYTES + ' UTF-8 bytes.'); - } - const admission = prepareResearchDelivery(checkpoint && submission.kind === 'notes' - ? { kind: 'event', value: { ...parseMathResponse(submission.text, 'math-result'), needsDecision: true } } : submission, { source: action.task, - assignment, tasks: this.archive.tasks, deliveries: this.archive.deliveries, - nextChecks: this.archive.nextChecks, proofSearchRecords: this.archive.proofSearchRecords, - identity: { problemReceiptDigest, environmentDigest } }); - if (admission.status === 'rejected') throw new ResearchAdmissionError(submission.kind === 'event' && admission.code === 'math_route_blocker_invalid' - ? { ...admission, issues: admission.issues.map(issue => ({ ...issue, path: 'finding.' + issue.path })) } : admission); - const finding = structuredClone(admission.finding), text = JSON.stringify(finding); - const complete = !checkpoint && (submission.kind === 'notes' || finding.checkOutcome !== undefined); - const node = this.node(action.task.id), details = deliveryDetails(finding); - const lemmaRequests = validateLemmaRequests(this.input.state.problem, this.archive.tasks.map(node => node.task), - this.archive.groups?.map(route => route.group) ?? [], node.task, finding.lemmaRequests, - this.archive.deliveries?.filter(delivery => delivery.kind === 'research' && delivery.status !== 'superseded' && - delivery.taskId === node.task.id && delivery.taskDigest === digest(node.task)).flatMap(delivery => delivery.lemmaRequests ?? [])); - const explorationIds = new Set(this.archive.tasks.filter(item => item.capacityExploration).map(item => item.task.id)); - if (lemmaRequests.some(proposal => proposal.dependsOn.some(id => explorationIds.has(id)))) - throw new Error('math_research_lemma_requests_invalid: advisory exploration IDs are provenance, not typed proof inputs.'); - const publish = async (fixedWorker: ResearchWorker, fixedCommit: string) => { - if (!this.current(action)) return; - let artifacts = deliveryOptions.artifacts ?? captureDeliveryArtifacts({ problem: this.input.state.problem, - worktree: fixedWorker.worktree, commit: fixedCommit, assignment }); - artifacts = { ...artifacts, reportedChecks: validateDeliveryArtifactClaims(finding, artifacts) }; - const sourceDigest = ownedSourceDigest(this.input.state.problem, fixedWorker.worktree, fixedCommit); - const findingKey = canonicalMathJson(finding); - const checkpointFindingKey = canonicalMathJson({ ...finding, needsDecision: undefined }); - const evidenceKey = (manifest: DeliveryArtifactManifest) => canonicalMathJson([...new Set(manifest.artifacts - .map(artifact => canonicalMathJson([artifact.kind, artifact.file, artifact.sha256])))].sort()); - const artifactKey = evidenceKey(artifacts); - const basisKey = canonicalMathJson(basis ?? assignmentKey); - // Compare immutable content and dispatch inputs, not Git metadata or note offsets. - // The existing deliveries persist this identity across task switches and restarts. - const matchingPublication = () => (this.archive.deliveries ?? []).find(record => { - if (record.kind !== 'research' || record.status === 'superseded' || record.producer !== worker.id || - record.taskId !== action.task.id || record.taskDigest !== assignment.taskDigest || record.sourceDigest !== sourceDigest || - !checkpoint && record.assignmentKey !== assignmentKey || - record.artifacts?.problemReceiptDigest !== problemReceiptDigest || - canonicalMathJson(record.researchRecord?.basis ?? record.assignmentKey ?? null) !== basisKey || - evidenceKey(record.artifacts) !== artifactKey) return false; - const previous = deliveryFinding(record); - try { - if (previous === undefined) return false; - const parsed = JSON.parse(previous); - if (canonicalMathJson(parsed) === findingKey) return true; - // Checkpoint intake can promote an identical finding to a decision request. - // Preserve the original bytes and any answer attached to them. - const addedByCheckpoint = checkpoint && finding.needsDecision === true && - (parsed.needsDecision === undefined || parsed.needsDecision === false); - const alreadyRequested = parsed.needsDecision === true && - (finding.needsDecision === undefined || finding.needsDecision === false); - return (addedByCheckpoint || alreadyRequested) && - canonicalMathJson({ ...parsed, needsDecision: undefined }) === checkpointFindingKey; - } - catch { return false; } - }); - const completeResearch = (record: DeliveryRecord) => { - node.finding = record.finding; this.moveTask(node, 'completed', 'research-completed'); node.feedback = undefined; - node.researchCompletion = record.researchRecord; - if (this.archive.unchangedResearch) delete this.archive.unchangedResearch[node.task.id]; - if (this.archive.researchCheckpoints) delete this.archive.researchCheckpoints[node.task.id]; - }; - const reusePublication = () => { - const record = matchingPublication(); - if (!record) return; - if (checkpoint) { - let changed = connectionOutputDigest !== undefined && - this.bindConnectionFinding(node, assignment, connectionOutputDigest, record.id); - if (finding.needsDecision === true && !researchFindingRequestsDecision(record) && - !this.archive.researchDecisions?.some(decision => researchDecisionMatches(record, decision))) { - const alreadyPending = record.lemmaRequests?.some(task => !this.node(task.id)); - record.leadDecisionRequested = true; - if (!alreadyPending) this.wakeLead('research-finding'); - changed = true; - } - if (changed) this.changed(); - } else { - const { submissionId } = deliveryOptions; - if (submissionId !== undefined) { - if (record.submissionId === undefined) record.submissionId = submissionId; - else if (record.submissionId !== submissionId && !record.submissionAliases?.includes(submissionId)) - record.submissionAliases = [...(record.submissionAliases ?? []), submissionId]; - } - if (complete) { - record.researchRecord = settleResearch({ id: record.id, assignment, basis, - commit: record.commit!, finding: deliveryFinding(record)!, complete }); - // An advisory challenge does not count as a final refutation until completion. - if (!finding.blockers && finding.conclusion === 'refuted') - this.reportBlockers(node.task, [{ mechanism: 'reported-local-refutation', - scope: 'assigned-local-inference', evidenceRefs: details.evidenceRefs }]); - completeResearch(record); - this.input.emit('research_delivered', { taskId: node.task.id, conclusion: finding.conclusion, complete }); - } - this.resolveDeliveryReceipts(worker, action, finding.replacesReceipt, complete); - this.changed(); - } - return record; - }; - const previous = reusePublication(); - if (previous) return previous; - const artifactWarning = diagnoseUnbackedLeanClaims(finding, artifacts); - const knowledge = this.captureKnowledgeUseCheck(fixedWorker, node.task, fixedCommit); - const knowledgeUses = await checkKnowledgeApplications(knowledge.uses, knowledge.input); - if (!this.current(action) || this.node(action.task.id) !== node || worker.id !== assignment.workerId || - assignmentDeliveryFile(action.assignment) !== assignmentKey || environmentDigest !== this.input.state.environmentDigest || - problemReceiptDigest !== this.input.state.problem.receiptDigest) return; - const concurrent = reusePublication(); - if (concurrent) return concurrent; - if (details.mathematicalGap) bindMathematicalGap(details.mathematicalGap, node.task, this.archive, - { problemReceiptDigest, environmentDigest }); - const checkOutcomeScope = details.checkOutcome && bindCheckOutcome(details.checkOutcome, node.task, assignment, - this.archive, { problemReceiptDigest, environmentDigest }); - const remaining = [...new Set([...(details.remainingObligations ?? []), - ...this.dependencies(node.task).filter(dependency => !['integrated', 'completed'].includes(dependency.status)).map(dependency => dependency.task.id)])]; - // Creating the delivery pins its immutable evidence before completed becomes - // observable. The delivery and its completion record publish together below. - const record = this.createDeliveryRecord(worker, node.task, 'research', - !remaining.length && node.task.kind !== 'sketch' ? 'advisory' : 'conditional', details.summary, - { ...details, ...deliveryOptions, assignmentKey, remainingObligations: remaining, commit: fixedCommit, artifacts, - sourceDigest, - lemmaRequests, finding: text, findingDigest: mathDigest(text), knowledgeUses, - ...(checkOutcomeScope ? { checkOutcomeScope } : {}), - ...(artifactWarning ? { artifactWarning } : {}) }); - record.researchRecord = settleResearch({ id: record.id, assignment, basis, commit: fixedCommit, finding: text, complete }); - // A challenge alone is never a repeated-blocker report that parks the proof task. - this.reportBlockers(node.task, finding.blockers ?? (complete && finding.conclusion === 'refuted' ? [{ - mechanism: 'reported-local-refutation', scope: 'assigned-local-inference', evidenceRefs: details.evidenceRefs, - }] : undefined)); - (this.archive.deliveries ??= []).push(record); - if (connectionOutputDigest !== undefined) - this.bindConnectionFinding(node, assignment, connectionOutputDigest, record.id); - if (complete) completeResearch(record); - if (finding.needsDecision === true || finding.conclusion === 'refuted' || lemmaRequests.length || artifactWarning) { - this.wakeLead('research-finding'); - } - this.resolveDeliveryReceipts(worker, action, finding.replacesReceipt, complete); - this.publishDeliveryRecord(record); - this.observeKnowledgeUses(node.task, fixedCommit, knowledgeUses, knowledge.rejected); - this.input.emit('research_delivered', { taskId: node.task.id, conclusion: finding.conclusion, complete }); - return record; - }; - if (checkpoint || submission.kind === 'notes') return publish(worker, commit); - else { - // Explicit events leave the writer's live files and Git index untouched. - return withSolverWorktree(worker.worktree, commit, async checkout => { - for (const [file, source] of sourceSnapshot ?? []) - fs.writeFileSync(path.join(checkout, this.input.state.problem.projectRelative, file), source); - fs.writeFileSync(path.join(checkout, 'RESEARCH.md'), researchPublicationNotes(finding, probes)); - return publish({ ...worker, worktree: checkout }, commitSolverSources(this.input.state.problem, checkout)); - }); - } - } - protected sourceProjector(worktree: string, commit: string, compact = false, - preserved: readonly { file: string; name: string }[] = []) { - const identity = mathDigest(canonicalMathJson({ problem: this.input.state.problem, worktree, commit, compact, preserved })); - let cached = this.preparedSources.get(compact); - if (cached?.identity !== identity) { - cached = { identity, project: createTaskSourceProjector(this.input.state.problem, worktree, commit, { compact, preserved }) }; - this.preparedSources.set(compact, cached); - } - return cached.project; - } - protected sourceGoalInputs(task: CooperativeTask, tasks: readonly TaskRecord[], worktree: string, commit: string, - conditions: readonly CooperativeTask[] = []) { - try { return projectedGoalInputs(this.sourceProjector(worktree, commit), task, tasks, conditions, (sourceTask, error) => { - if (sourceTask.id !== task.id) this.input.emit('task_source_input_unavailable', { taskId: task.id, - sourceTaskId: sourceTask.id, commit, reason: bounded(error instanceof Error ? error.message : String(error), 2000) }); - }); } - catch { return []; } // Missing draft declarations are diagnosed by the actual proof check. - } - protected retainedTaskGoals(task: CooperativeTask, tasks: readonly TaskRecord[], worktree: string, commit: string, - conditions: readonly CooperativeTask[] = []) { - const goals = new Set(this.dependencies(task, tasks).filter(node => node.task.kind === 'goal' && - node.task.id !== task.id && node.status === 'integrated').map(node => node.task.theoremName!)); - for (const node of this.sourceGoalInputs(task, tasks, worktree, commit, conditions)) { - const proof = node.integratedCheck; - // Retain this candidate's source for a new kernel check, rather than reuse - // the earlier receipt. Whole-module references may change with unrelated helpers. - if (node.status === 'integrated' && proof?.passed && !proof.conditions?.length && - proof.taskDigest === digest(node.task) && this.checkedDeliveries.has(proof) && hasTaskAcceptance(proof)) - goals.add(node.task.theoremName!); - } - return [...goals]; - } - protected assignmentConditions(task: CooperativeTask, assignment?: TaskAssignment, - tasks: readonly TaskRecord[] = this.archive.tasks, worktree = this.lead.worktree): readonly CooperativeTask[] { - const dependencies = this.dependencies(task, tasks); - const readInput = (commit: string) => (dependency: CooperativeTask) => - committedSource(worktree, commit, `${this.input.state.problem.projectRelative}/${dependency.proofPath}`); - if (!assignment?.connectionCheck) { - if (!task.conditional) return []; - if (!assignment) return dependencies.filter(node => assumableLemma(node.task) && node.status !== 'integrated').map(node => node.task); - if (assignment.taskId !== task.id || assignment.taskDigest !== digest(task)) throw new Error('math_task_condition_version_invalid'); - // Explicit conditional contracts also authorize only their frozen, exact dispatch inputs. - const inputs = (assignment.dependencies ?? []).filter(reference => { - const input = tasks.find(node => node.task.id === reference.taskId); - if (!input || digest(input.task) !== reference.taskDigest) throw new Error('math_task_condition_version_invalid'); - return assumableLemma(input.task); - }); - // Read the frozen canonical base as well as the scoped seed so an unaccepted draft - // declaration alone does not remove an assumption. Older records may lack that base. - const canonical = assignment.canonicalCommit; - const unresolved = canonical ? inputs.filter(reference => - taskInputsMissingFromSeed([reference], tasks, readInput(canonical)).length || - taskInputsMissingFromSeed([reference], tasks, readInput(assignment.seedCommit)).length) : inputs; - return unresolved.map(reference => tasks.find(node => node.task.id === reference.taskId)!.task); - } - if (!taskConnectionCheckCurrent(task, assignment, tasks)) throw new Error('math_task_condition_version_invalid'); - const check = assignment.connectionCheck; - // Historical dispatches predate assumedInputs. Reconstruct only from their immutable seed, - // never from a dependency's integration status at the time this delivery is checked. - const assumed = check.assumedInputs ?? taskInputsMissingFromSeed(check.inputs, tasks, readInput(assignment.seedCommit)); - return assumed.map(reference => tasks.find(node => node.task.id === reference.taskId)!.task); - } - protected async check(task: CooperativeTask, assignment: TaskAssignment, worktree: string, commit: string, - conditions?: readonly CooperativeTask[], checked?: TaskProof, reuseDeliveryFailure = false, incompleteDelivery = false, - taskGraph: readonly TaskRecord[] = this.archive.tasks, - checkEnvironment?: { environment: NodeJS.ProcessEnv; digest: string }, - additionalRetainedGoals: readonly string[] = []): Promise { - this.input.signal.throwIfAborted(); - if (reuseDeliveryFailure && !checked) { - const candidate = this.failedTaskInput(task, assignment, worktree, commit, conditions); - const previous = this.previousTaskFailure(candidate); - if (previous) { - this.input.emit('task_failure_check_reused', { taskId: task.id, taskDigest: digest(task), commit, failureId: previous.id }); - throw new Error(this.repeatedTaskFeedback(previous)); - } - const pending = this.checkingTaskInputs.get(candidate.id); - if (pending) { - await pending; - return this.check(task, assignment, worktree, commit, conditions, checked, true, incompleteDelivery); - } - let finish!: () => void; - const checking = new Promise(resolve => { finish = resolve; }); - this.checkingTaskInputs.set(candidate.id, checking); - this.refreshPlanApproval(); - const reserveRepair = () => { - const node = this.node(task.id); - return node?.assignment === assignment && digest(node.task) === candidate.taskDigest && - (incompleteDelivery || this.firstTaskRepair(node, candidate.id)) - ? { taskId: task.id, taskDigest: candidate.taskDigest, workerId: assignment.workerId, pending: true } : undefined; - }; - try { - const proof = await this.check(task, assignment, worktree, commit, conditions, checked); - if (this.deterministicTaskFailure(proof)) this.rememberTaskFailure(candidate, solverProofFeedback(proof), reserveRepair()); - return proof; - } catch (error) { - if (error instanceof Error && error.message.startsWith('math_task_missing_declaration\n')) { - const node = this.node(task.id); - const mathematicalBlocker = node?.assignment === assignment && this.reportedTaskMathematicalBlocker(node, candidate); - // Persist the block with the failure so restart recovery cannot invent a code repair. - if (mathematicalBlocker) { this.moveTask(node, 'blocked', 'input-blocked'); node.feedback = error.message; this.wakeLead('task-blocked'); } - this.rememberTaskFailure(candidate, error.message, mathematicalBlocker ? undefined : reserveRepair()); - } - throw error; - } finally { - this.checkingTaskInputs.delete(candidate.id); finish(); this.wake(); - } - } - const tasks = taskGraph.map(node => ({ ...node })); - const taskDigest = digest(task); - const environmentDigest = checkEnvironment?.digest ?? this.input.state.environmentDigest; - if (assignment.connectionCheck && !taskConnectionCheckCurrent(task, assignment, tasks, - { environmentDigest, problemReceiptDigest: this.input.state.problem.receiptDigest })) - throw new Error('math_task_condition_version_invalid'); - conditions ??= this.assignmentConditions(task, assignment, tasks, worktree); - const retainedGoals = [...new Set([...this.retainedTaskGoals(task, tasks, worktree, commit, conditions), - ...additionalRetainedGoals.filter(name => name !== task.theoremName)])]; - const checker = this.input.modules.M2.checkTask ?? checkTaskProof; - const environment = checkEnvironment?.environment ?? this.input.access.get(this.lead.id)!.environment; - const proof = checked ?? await checker(this.input.state.problem, worktree, commit, task, assignment, retainedGoals, - environment, this.input.signal, this.input.timeoutMs, conditions, environmentDigest, - ...(checker === checkTaskProof ? [this.taskProofCache] : [])); - const failureContext = { taskId: task.id, taskDigest, sourceCommit: commit, - seedCommit: assignment.seedCommit, projectionMode: proof.projectionMode ?? 'full' as const, - conditions: conditions.map(task => ({ taskId: task.id, taskDigest: digest(task) })), verification: proof.verification }; - const identityFailure = () => new VerifierFailureError({ ...failureContext, stage: 'task-proof-identity' }, - undefined, 'math_task_check_identity_changed'); - const reuse = trustedTaskProjectionReuse(proof); - if (proof.projectionReuse && !reuse || checker === checkTaskProof && proof.passed && !isAttributedTaskProof(proof)) - throw identityFailure(); - if (checker === checkTaskProof && !isAttributedTaskProof(proof)) throw new VerifierFailureError({ - ...failureContext, stage: 'task-proof-attribution' }); - const projectionCommit = reuse?.projectionCommit ?? proof.verification.targetCommit; - if (reuse && (reuse.checkedProjectionCommit !== proof.verification.targetCommit || - git(worktree, ['rev-parse', `${reuse.projectionCommit}^{tree}`]) !== reuse.projectionTree || - git(worktree, ['rev-parse', `${reuse.checkedProjectionCommit}^{tree}`]) !== reuse.projectionTree)) - throw identityFailure(); - const declarationHash = proof.passed && proof.verification.targetCommit && hashMathFormalSourceDeclaration( - committedSource(worktree, proof.verification.targetCommit, `${this.input.state.problem.projectRelative}/${task.proofPath}`), task.theoremName!); - const compact = isAttributedTaskProof(proof) && proof.projectionMode === 'compact'; - const projected = (proof.passed || reuse) && this.sourceProjector(worktree, commit, compact, - compact ? proof.changes : [])(task, retainedGoals, conditions); - const allowed = new Set(this.input.state.problem.ownedFiles.map(file => `${this.input.state.problem.projectRelative}/${file}`)); - allowed.add('RESEARCH.md'); - const projectionMatches = projected && projectionCommit && - [...projected].every(([file, source]) => source === committedSource(worktree, projectionCommit, - `${this.input.state.problem.projectRelative}/${file}`)) && - git(worktree, ['diff', '--no-renames', '--name-only', '-z', commit, projectionCommit, '--']) - .split('\0').filter(Boolean).every(file => allowed.has(file)); - if (proof.commit !== commit || proof.taskDigest !== taskDigest || proof.seedCommit !== assignment.seedCommit || - proof.sourceDigest !== ownedSourceDigest(this.input.state.problem, worktree, commit) || - canonicalMathJson(proof.conditions ?? []) !== canonicalMathJson(conditions.map(task => ({ taskId: task.id, taskDigest: digest(task) }))) || - (reuse && !projectionMatches) || - (proof.passed && (!projectionMatches || !declarationHash || !proofReceiptsMatch(proof.verification, proof.verification.targetCommit, - [{ proofPath: task.proofPath!, theoremName: task.theoremName!, expectedSourceDeclarationHash: declarationHash, - statementHash: taskDigest, leanStatementHash: taskDigest, claim: 'statement' }])))) - throw identityFailure(); - if (proof.passed && conditions.length && projected) proof.projection = { - environmentDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest, - sourceDigest: mathDigest(canonicalMathJson([...projected])), - }; - else delete proof.projection; - if (proof.references) { - const references = proof.references; - references.tasks = attributeTaskReferences(references, tasks); - markTaskReferences(proof); - } - this.pin(proof.commit); this.pin(projectionCommit); this.pin(proof.verification.targetCommit); - this.checkedDeliveries.add(proof); markTaskAcceptance(proof); - return proof; - } - /** Check isolated sources concurrently; only publishing and canonical integration are serialized. */ - protected async publishTaskProof(worker: ResearchWorker, action: Extract, - commit: string, summary: string, options: Partial = {}, recovering = false, - prepared?: ProofDeliveryRequest['prepared']) { - const key = canonicalMathJson([worker.id, assignmentDeliveryFile(action.assignment), commit]); - const previous = this.proofPublications.get(key); - if (previous) { - const request = this.proofDeliveryRequests.get(key); - if (request) { - for (const field of Object.keys(options) as (keyof DeliveryRecord)[]) { - const value = options[field]; - if (value !== undefined && request.options[field] === undefined) Object.assign(request.options, { [field]: value }); - } - if (options.evidenceRefs) request.options.evidenceRefs = [...new Set([...(request.options.evidenceRefs ?? []), ...options.evidenceRefs])]; - if (request.record) await this.input.exclusiveCheck(async () => this.mergeProofDeliveryMetadata(request)); - } - return previous.pending; - } - const request: ProofDeliveryRequest = { worker, action, commit, summary, options: { ...options }, prepared }; - this.proofDeliveryRequests.set(key, request); - const pending = this.publishCheckedTaskProof(request, recovering); - const publication = { workerId: worker.id, action, pending }; - this.proofPublications.set(key, publication); - try { this.changed(); return await pending; } - finally { - const current = this.proofPublications.get(key) === publication; - if (current) this.proofPublications.delete(key); - if (this.proofDeliveryRequests.get(key) === request) this.proofDeliveryRequests.delete(key); - if (current) this.changed(); - } - } - private async publishCheckedTaskProof(request: ProofDeliveryRequest, recovering: boolean): Promise { - const { worker, action, commit, options, prepared } = request; - if (prepared && !prepared.current()) return; - const previous = this.node(action.task.id); - // Notes-only completion cannot renew obsolete conditional inputs after unconditional integration. - const notesOnly = previous?.status === 'integrated' && previous.proof && taskReferenceDependencies(previous) && - proofReferencesUnchanged(this.input.state.problem, this.lead.worktree, this.archive.canonicalCommit!, - previous.integratedCheck!.references!, this.input.state.environmentDigest) && - git(worker.worktree, ['diff', '--no-renames', '--name-only', '-z', previous.proof.commit, commit, '--']) - .split('\0').filter(Boolean).every(file => file === 'RESEARCH.md'); - const proof = previous?.proof && (previous.proof.commit === commit || notesOnly) && - ['delivered', 'conditional', 'integrated'].includes(previous.status) && this.checkedDeliveries.has(previous.proof) ? previous.proof : - await this.check(action.task, action.assignment, worker.worktree, commit, undefined, prepared?.proof, true, recovering); - const staged = await this.input.exclusiveCheck(async () => { - if (prepared) { - if (!prepared.current()) return; - prepared.claim(); - } - if (!this.current(action) || !(proof.references?.tasks ?? []).every(reference => - this.archive.tasks.some(node => node.task.id === reference.taskId && digest(node.task) === reference.taskDigest))) { - this.record(worker, action.task, 'proof', 'superseded', 'Assignment changed while its proof was being checked.', - { ...options, commit, taskDigest: action.assignment.taskDigest, dependencies: action.assignment.dependencies ?? [] }); - this.input.emit('task_delivery_superseded', { taskId: action.task.id, workerId: worker.id, commit }); - return; - } - const node = this.node(action.task.id); - if (['conditional', 'integrated'].includes(node.status)) { - return { node, proof: node.proof?.commit === commit ? node.proof : undefined, publication: this.proofDeliveryState(node) }; - } - if (recovering && !proof.passed && proof.verification.status === 'failed') { - node.feedback = solverProofFeedback(proof); - if (this.deterministicTaskFailure(proof)) this.continueTaskCheckpoint(worker, node, commit); - this.interrupted(worker, action); - return { node: undefined, proof }; - } - this.deliverProof(node, proof); - return { node, proof, publication: this.proofDeliveryState(node) }; - }); - if (!staged?.node) return staged?.proof; - return this.settleProofDeliveries(annotations => this.queueIntegration(async () => { - const node = staged.node, submitted = staged.proof; - if (submitted && this.current(action) && node.proof === submitted) { - let publication: ProofDeliveryState | undefined = staged.publication; - if (node.status === 'delivered') publication = await this.integrateNow(node); - else if (node.status === 'integrated') await this.syncPreparedStatements(); - if (publication) { - const annotate = await this.publishProofDelivery(node, request, publication); - if (annotate) annotations.push(annotate); - } - } - await this.integrateReadyNow(annotations); - return submitted; - }, worker, action.task)); - } - protected currentTaskSourceRepair(node: TaskRecord) { - const repair = node.sourceRepair, assignment = node.assignment; - return repair && assignment && repair.taskDigest === digest(node.task) && repair.taskDigest === assignment.taskDigest && - repair.workerId === assignment.workerId && repair.assignmentId === assignment.assignmentId && - repair.seedCommit === assignment.seedCommit ? repair : undefined; - } - protected restoreTaskSourceRepair(node: TaskRecord) { - const repair = this.currentTaskSourceRepair(node); - if (!repair || repair.pending || repair.startedAttempt !== node.attempts) return; - repair.pending = true; delete repair.startedAttempt; - this.input.emit('task_repair_interrupted', { taskId: node.task.id, workerId: repair.workerId, reason: 'source-contract' }); - } - protected settleTaskSourceRepair(node: TaskRecord) { - const repair = this.currentTaskSourceRepair(node); - if (repair && !repair.pending) delete repair.startedAttempt; - } - protected retryTaskSourceLocally(node: TaskRecord): boolean { - const assignment = node.assignment; - if (!assignment || !this.liveWorkers.has(assignment.workerId)) return false; - let repair = this.currentTaskSourceRepair(node); - if (repair ? !repair.pending : !this.firstTaskRepair(node)) return false; - repair ??= node.sourceRepair = { taskDigest: digest(node.task), workerId: assignment.workerId, - assignmentId: assignment.assignmentId, seedCommit: assignment.seedCommit, pending: true }; - this.moveTask(node, 'pending', 'local-repair'); - this.input.emit('task_repair_requested', { taskId: node.task.id, workerId: assignment.workerId, - taskDigest: assignment.taskDigest, reason: 'source-contract' }); - return true; - } - protected retryTaskLocally(node: TaskRecord, commit?: string): boolean { - if (!node.assignment || !this.liveWorkers.has(node.assignment.workerId)) return false; - const worker = this.input.workers.find(worker => worker.id === node.assignment!.workerId); - const candidate = worker && this.failedTaskInput(node.task, node.assignment, worker.worktree, - commit ?? node.proof?.commit ?? git(worker.worktree, ['rev-parse', 'HEAD'])); - const failed = candidate && this.previousTaskFailure(candidate); - if (candidate && failed?.feedback.startsWith('math_task_missing_declaration\n') && - this.reportedTaskMathematicalBlocker(node, candidate)) { - delete failed.repair; - this.input.emit('task_mathematical_gap_blocked', { taskId: node.task.id, taskDigest: digest(node.task), - failureId: failed.id, evidence: 'model-reported-advisory' }); - return false; - } - if (failed?.repair ? !this.pendingTaskRepair(node, failed) : - failed ? !this.firstTaskRepair(node, failed.id) : node.attempts !== 1) return false; - if (failed && !failed.repair) failed.repair = { taskId: node.task.id, taskDigest: digest(node.task), - workerId: node.assignment.workerId, pending: true }; - this.moveTask(node, 'pending', 'local-repair'); - this.input.emit('task_repair_requested', { taskId: node.task.id, workerId: node.assignment.workerId, - taskDigest: node.assignment.taskDigest }); - return true; - } - /** A failed request that left the seed's Lean sources untouched is no attempt, so it must not record a failed input. */ - protected untouchedTaskSeed(worker: ResearchWorker, action: Extract, commit: string) { - const node = this.node(action.task.id); - if (this.leanSourceDigest(worker.worktree, commit) !== this.leanSourceDigest(worker.worktree, action.assignment.seedCommit)) return false; - const candidate = this.failedTaskInput(action.task, action.assignment, worker.worktree, commit); - return !this.previousTaskFailure(candidate) && - !(node.assignment === action.assignment && this.reportedTaskMathematicalBlocker(node, candidate)); - } - protected restoreInterruptedRepair(worker: ResearchWorker, action: Extract, commit: string) { - const node = this.node(action.task.id), candidate = this.failedTaskInput(action.task, action.assignment, worker.worktree, commit); - const failed = this.previousTaskFailure(candidate), repair = failed?.repair; - if (!repair || repair.pending || repair.taskId !== node.task.id || repair.taskDigest !== digest(node.task) || - repair.workerId !== worker.id || repair.startedAttempt !== node.attempts) return false; - repair.pending = true; delete repair.startedAttempt; - node.feedback = failed!.feedback; this.moveTask(node, 'pending', 'local-repair'); - this.input.emit('task_repair_interrupted', { taskId: node.task.id, workerId: worker.id, failureId: failed!.id }); - this.changed(); return true; - } - protected continueTaskCheckpoint(worker: ResearchWorker, node: TaskRecord, commit: string) { - const candidate = this.failedTaskInput(node.task, node.assignment!, worker.worktree, commit); - const failed = this.previousTaskFailure(candidate); - if (!failed) return true; - if (failed.feedback.startsWith('math_task_missing_declaration\n') && - this.reportedTaskMathematicalBlocker(node, candidate)) return false; - this.settleTaskRepair(node); - failed.repair ??= { taskId: node.task.id, taskDigest: digest(node.task), workerId: worker.id, pending: true }; - this.input.emit('task_checkpoint_continuation_requested', { taskId: node.task.id, workerId: worker.id, failureId: failed.id }); - return true; - } - protected settleTaskRepair(node: TaskRecord) { - for (const { repair } of this.archive.failedTaskInputs ?? []) if (repair && !repair.pending && - repair.taskId === node.task.id && repair.taskDigest === digest(node.task) && - repair.workerId === node.assignment?.workerId && repair.startedAttempt === node.attempts) delete repair.startedAttempt; - } - private deliverProof(node: TaskRecord, proof: TaskProof) { - if (['unavailable', 'blocked'].includes(proof.verification.status)) { - node.proof ??= proof; - throw new VerifierFailureError({ stage: 'task-proof-delivery', taskId: node.task.id, - taskDigest: digest(node.task), sourceCommit: proof.commit, seedCommit: proof.seedCommit, - projectionMode: proof.projectionMode ?? 'full', conditions: proof.conditions, verification: proof.verification }); - } - node.proof = proof; - this.settleTaskSourceRepair(node); - if (proof.passed || this.deterministicTaskFailure(proof)) this.settleTaskRepair(node); - this.moveTask(node, proof.passed ? proof.conditions?.length ? 'conditional' : 'delivered' : 'blocked', 'proof-checked'); - if (proof.passed) node.feedback = undefined; - else { - node.feedback = solverProofFeedback(proof); - const repairable = this.deterministicTaskFailure(proof) || proof.verification.status === 'failed' && proof.verification.results.some(result => - result.status === 'failed' && ((result.sorryCount ?? 0) > 0 || result.error === 'Lean exited with status 1.')); - if (!repairable || !this.retryTaskLocally(node, proof.commit)) this.wakeLead('task-check-failed'); - } - this.input.emit('task_checked', { taskId: node.task.id, passed: proof.passed, conditional: Boolean(proof.conditions?.length), - commit: proof.commit, taskDigest: proof.taskDigest }); - this.changed(); - } - /** Keep canonical failures authoritative, while draining all checks before a caller releases its workspace. */ - protected async settleProofDeliveries(operation: (annotations: ProofDeliveryAnnotation[]) => Promise): Promise { - const annotations: ProofDeliveryAnnotation[] = []; - let result: T, failure: unknown, failed = false; - try { result = await operation(annotations); } - catch (error) { failed = true; failure = error; } - const checks = await Promise.allSettled(annotations.map(annotate => annotate())); - if (failed) throw failure; - const rejected = checks.find(check => check.status === 'rejected'); - if (rejected?.status === 'rejected') throw rejected.reason; - return result!; - } - private updateProofDeliveryMetadata(record: DeliveryRecord, metadata: Partial) { - const fields = Object.keys(metadata) as (keyof DeliveryRecord)[]; - if (fields.every(field => record[field] === metadata[field] || - record[field] !== undefined && metadata[field] !== undefined && canonicalMathJson(record[field]) === canonicalMathJson(metadata[field]))) return false; - this.pin(metadata.commit); this.pin(metadata.artifacts?.commit); this.pin(metadata.evidence?.verification.targetCommit); - const previous = Object.fromEntries(fields.map(field => [field, record[field]])); - Object.assign(record, metadata); - try { this.changed(); } - catch (error) { Object.assign(record, previous); throw error; } - return true; - } - private mergeProofDeliveryMetadata(request: ProofDeliveryRequest) { - const { record, action, options } = request; - if (!record || record.status === 'superseded' || !this.current(action) || !this.archive.deliveries?.includes(record)) return; - this.updateProofDeliveryMetadata(record, { - submissionId: record.submissionId ?? options.submissionId, - assignmentKey: record.assignmentKey ?? options.assignmentKey, - artifacts: record.artifacts ?? options.artifacts, - artifactWarning: record.artifactWarning ?? options.artifactWarning, - evidenceRefs: [...new Set([...(record.evidenceRefs ?? []), ...(options.evidenceRefs ?? [])])], - }); - } - protected proofDeliveryCurrent(node: TaskRecord): boolean { - const { proof, assignment, integratedCheck, status } = node, version = digest(node.task); - return this.archive.tasks.includes(node) && !!proof && !!assignment && assignment.taskDigest === version && proof.taskDigest === version && - (status === 'integrated' ? !!integratedCheck?.passed && integratedCheck.taskDigest === version && this.checkedDeliveries.has(integratedCheck) - : this.checkedDeliveries.has(proof)); - } - protected proofDeliveryState(node: TaskRecord): ProofDeliveryState { - const { assignment, proof, integratedCheck, status, feedback } = node; - return { assignment, proof, integratedCheck, status, feedback }; - } - /** Publish the proof now; return optional annotation work for the caller to await outside the canonical queue. */ - protected async publishProofDelivery(node: TaskRecord, request?: ProofDeliveryRequest, - expected?: ProofDeliveryState): Promise { - const expectedState = expected ?? this.proofDeliveryState(node); - return this.input.exclusiveCheck(async () => { - const proof = node.proof, assignment = node.assignment; - // Feedback can change after this stage settles; the saved state owns its summary. - if (!proof || !assignment || !this.proofDeliveryCurrent(node) || node.proof !== expectedState.proof || - node.assignment !== expectedState.assignment || node.status !== expectedState.status || - node.integratedCheck !== expectedState.integratedCheck) return; - request ??= this.proofDeliveryRequests.get(canonicalMathJson([ - assignment.workerId, assignmentDeliveryFile(assignment), proof.commit, - ])); - if (request && request.commit !== proof.commit) return; - const worker = request?.worker ?? this.input.workers.find(worker => worker.id === assignment.workerId) ?? this.lead; - const action = request?.action ?? { kind: 'task' as const, task: node.task, assignment }; - if (this.node(action.task.id) !== node || node.assignment !== action.assignment || digest(node.task) !== action.assignment.taskDigest) return; - const task = structuredClone(node.task), taskDigest = digest(task), integratedProof = node.integratedCheck, status = node.status; - const environmentDigest = this.input.state.environmentDigest, problemReceiptDigest = this.input.state.problem.receiptDigest; - const verdict: DeliveryRecord['status'] | undefined = status === 'integrated' ? 'verified' : status === 'conditional' ? 'conditional' : - !proof.passed || status === 'blocked' ? 'failed' : undefined; - if (!verdict) return; - // A verified publication describes canonical acceptance; artifacts still identify the worker's original submission. - const evidence = verdict === 'verified' ? integratedProof! : request ? proof : integratedProof ?? proof; - const options = request?.options ?? {}, assignmentKey = options.assignmentKey ?? assignmentDeliveryFile(assignment); - let record = this.archive.deliveries?.find(record => record.producer === worker.id && record.kind === 'proof' && record.status === verdict && - record.taskId === task.id && record.taskDigest === taskDigest && record.assignmentKey === assignmentKey && - (verdict === 'verified' || record.commit === proof.commit)); - // Preserve host probe findings; a worker's own completion summary is not an acceptance verdict. - const hostAdvisorySummary = request?.prepared?.advisorySummary ?? record?.hostAdvisorySummary; - const summary = verdict === 'verified' ? 'Checked proof integrated with freshly validated dependencies.' + - (hostAdvisorySummary ? ' ' + hostAdvisorySummary : '') : - (verdict === 'failed' ? expectedState.feedback : undefined) ?? request?.summary ?? - (verdict === 'conditional' ? 'Fixed declaration checked; unresolved lemma assumptions remain obligations.' : - 'Proof did not pass host acceptance.'); - // A passing proof needs this integration's failure state; a replay can only resume its existing record. - if (verdict === 'failed' && proof.passed && !expected && !record) return; - if (record && verdict === 'verified' && this.updateProofDeliveryMetadata(record, { - commit: evidence.commit, sourceDigest: evidence.sourceDigest, summary, hostAdvisorySummary, actualReferences: evidence.references, - evidence: { passed: evidence.passed, verification: { status: evidence.verification.status, - targetCommit: evidence.verification.targetCommit, - results: evidence.verification.results.map(({ receiptId }) => ({ receiptId })) } }, - })) this.pendingProofDeliveryRecords.add(record); - if (record && request) { request.record = record; this.mergeProofDeliveryMetadata(request); } - let knowledge: ReturnType | undefined; - if (!record) { - knowledge = this.captureKnowledgeUseCheck(worker, task, proof.commit, - this.checkedDeliveries.has(proof) ? proof : integratedProof); - record = this.createDeliveryRecord(worker, task, 'proof', verdict, - summary, - { ...options, assignmentKey, commit: evidence.commit, sourceDigest: evidence.sourceDigest, - ...(hostAdvisorySummary ? { hostAdvisorySummary } : {}), - evidence, actualReferences: evidence.references, knowledgeUses: knowledge.uses }); - (this.archive.deliveries ??= []).push(record); - this.pendingProofDeliveryRecords.add(record); - if (request) request.record = record; - } - if (this.pendingProofDeliveryRecords.has(record)) { - knowledge ??= this.captureKnowledgeUseCheck(worker, task, proof.commit, - this.checkedDeliveries.has(proof) ? proof : integratedProof); - this.publishDeliveryRecord(record); - this.pendingProofDeliveryRecords.delete(record); - } - const pendingAnnotation = this.proofDeliveryAnnotations.get(record); - if (pendingAnnotation) return pendingAnnotation; - if (!knowledge && record.knowledgeUses !== undefined && record.knowledgeUses.every(use => !use.application || use.application.check)) return; - knowledge ??= this.captureKnowledgeUseCheck(worker, task, proof.commit, - this.checkedDeliveries.has(proof) ? proof : integratedProof); - if (!knowledge.uses.some(use => use.application)) { - if (record.knowledgeUses !== knowledge.uses) { record.knowledgeUses = knowledge.uses; this.changed(); } - if (!this.input.signal.aborted && this.current(action)) - this.observeKnowledgeUses(task, proof.commit, knowledge.uses, knowledge.rejected); - return; - } - const publication = record; - const capturedKnowledge = knowledge; - let pending: Promise | undefined; - const annotate = () => { - if (pending) return pending; - pending = (async () => { - if (this.input.signal.aborted) return; - const knowledgeUses = await checkKnowledgeApplications(capturedKnowledge.uses, capturedKnowledge.input); - await this.input.exclusiveCheck(async () => { - if (this.input.signal.aborted || !this.current(action) || this.node(task.id) !== node || digest(node.task) !== taskDigest || node.status !== status || - node.assignment !== assignment || node.proof !== proof || node.integratedCheck !== integratedProof || - this.input.state.environmentDigest !== environmentDigest || this.input.state.problem.receiptDigest !== problemReceiptDigest || - publication.status !== verdict || !this.archive.deliveries?.includes(publication)) return; - const previous = publication.knowledgeUses; - publication.knowledgeUses = knowledgeUses; - try { this.changed(); } - catch (error) { publication.knowledgeUses = previous; throw error; } - this.observeKnowledgeUses(task, proof.commit, knowledgeUses, capturedKnowledge.rejected); - }); - })(); - this.proofDeliveryChecks.add(pending); - this.refreshPlanApproval(); - void pending.then(() => { - this.proofDeliveryChecks.delete(pending!); this.proofDeliveryAnnotations.delete(publication); - this.wake(); - }, () => { - this.proofDeliveryChecks.delete(pending!); this.proofDeliveryAnnotations.delete(publication); - this.wake(); - }); - return pending; - }; - this.proofDeliveryAnnotations.set(publication, annotate); - return annotate; - }); - } - private captureKnowledgeUseCheck(worker: ResearchWorker, task: CooperativeTask, commit: string, proof?: ProofCheck & { references?: ProofReferences }) { - task = structuredClone(task); - let value: unknown; - try { value = parseMathResponse(committedSource(worker.worktree, commit, 'RESEARCH.md'), 'math-result', {}, 'summary').knowledgeUses; } - catch { /* Host reference observation also works without optional model reports. */ } - // Consume the pinned source snapshots now; only normalized uses cross the async seam. - const access = this.input.access.get(worker.id); - const { uses, rejected } = inspectKnowledgeUses(value, access?.knowledgeSnapshot, task, proof, access?.installedLibrary); - const worktree = worker.worktree, projectRelative = this.input.state.problem.projectRelative; - return { uses, rejected, input: { task, projectRoot: path.join(worktree, projectRelative), - env: { ...this.input.access.get(worker.id)?.environment }, environmentDigest: this.input.state.environmentDigest, - commit, signal: this.input.signal, timeoutMs: this.input.timeoutMs ?? Infinity, - originalContexts: this.input.state.problem.targets.map(({ proofPath, theoremName }) => ({ proofPath, theoremName })), - sourceAtCommit: (file: string) => committedSource(worktree, commit, path.posix.join(projectRelative, file)), - previous: uses.some(use => use.application) - ? structuredClone(this.archive.deliveries?.flatMap(delivery => delivery.knowledgeUses ?? [])) : undefined } }; - } - private observeKnowledgeUses(task: CooperativeTask, commit: string, observed: readonly KnowledgeUse[], rejected: number) { - if (rejected) this.input.emit('knowledge_use_rejected', { taskId: task.id, commit, rejected }); - for (const use of observed) this.input.emit('knowledge_use_observed', { ...use, taskId: task.id, commit }); - } -} diff --git a/src/solver/cooperativeProof.ts b/src/solver/cooperativeProof.ts index 9ad64582..30d937b5 100644 --- a/src/solver/cooperativeProof.ts +++ b/src/solver/cooperativeProof.ts @@ -94,9 +94,10 @@ const keyedRegions = (source: string) => { export { committedSource } from './problem'; -export function ownedSourceDigest(problem: SolverProblem, worktree: string, commit: string): string { +export function ownedSourceDigest(problem: SolverProblem, worktree: string, commit: string, + readSource = (revision: string, file: string) => committedSource(worktree, revision, `${problem.projectRelative}/${file}`)): string { return mathDigest(canonicalMathJson(problem.ownedFiles.map(file => - [file, mathDigest(committedSource(worktree, commit, `${problem.projectRelative}/${file}`))]))); + [file, mathDigest(readSource(commit, file))]))); } /** Omit helper artifacts outside a task's visible scope while preserving every original declaration. */ @@ -113,13 +114,13 @@ export function omitTaskHelpers(problem: SolverProblem, file: string, source: st /** Freeze edits while preserving original goals, helper statements, and definition bodies. */ export function taskChanges(problem: SolverProblem, worktree: string, sourceCommit: string, - task: CooperativeTask | undefined, assignment: Pick): DeclarationChange[] { + task: CooperativeTask | undefined, assignment: Pick, + readSource = (commit: string, file: string) => committedSource(worktree, commit, `${problem.projectRelative}/${file}`)): DeclarationChange[] { // This only computes edits; callers still validate source availability and the frozen statement. if (sourceCommit === assignment.seedCommit && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(sourceCommit)) return []; const changes: DeclarationChange[] = []; for (const file of problem.ownedFiles) { - const read = (commit: string) => committedSource(worktree, commit, `${problem.projectRelative}/${file}`); - const before = read(assignment.seedCommit), after = read(sourceCommit); + const before = readSource(assignment.seedCommit, file), after = readSource(sourceCommit, file); if (before === after) continue; if (task && (['research', 'sketch'].includes(task.kind) || !file.endsWith('.lean'))) throw new Error('math_task_source_outside_scope'); if (Object.hasOwn(problem.frozenFiles ?? {}, file)) diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index d4421fd3..a2787a63 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -20,13 +20,15 @@ export const DECLARATION_SUBMISSION_FILE = 'declaration-submission.json'; export const DECLARATION_ARTIFACTS_FILE = 'declarations.json'; const hash = z.string().regex(/^[a-f0-9]{64}$/u); const commitHash = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u); -export const declarationSubmissionSchema = z.object({ declarations: z.array(z.object({ +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), description: z.string().max(8000).optional(), premises: z.array(z.string().max(8000)).max(128).optional(), -}).strict()).min(1).max(32) }).strict(); +}).strict()).min(1); +export const declarationSubmissionSchema = z.object({ declarations: teamDeclarationListSchema.max(32) }).strict(); +const teamDeclarationSubmissionSchema = z.object({ declarations: teamDeclarationListSchema }).strict(); export type DeclarationSubmission = z.infer; export type DeclarationArtifactIdentity = Pick; export type DeclarationArtifact = Readonly<{ @@ -73,8 +75,8 @@ const sameIdentity = (value: Partial, state: DeclarationArtifactIdentity) => Object.entries(identityOf(state)).every(([key, expected]) => value[key as keyof ReturnType] === expected); const submissionFail = (reason: string): never => { throw new DeclarationSubmissionError(`math_declaration_artifact_${reason}`); }; -function parseDeclarationSubmission(value: unknown): DeclarationSubmission { - const parsed = declarationSubmissionSchema.safeParse(value); +function parseDeclarationSubmission(value: unknown, schema = declarationSubmissionSchema): DeclarationSubmission { + const parsed = schema.safeParse(value); if (!parsed.success) throw new DeclarationSubmissionError(`math_declaration_artifact_submission_invalid:${parsed.error.message}`, { cause: parsed.error }); return parsed.data; @@ -244,31 +246,51 @@ export function writeDeclarationArtifacts(directory: string, state: DeclarationA } satisfies z.infer); } -/** The caller must hold its writer-stop guarantee until this operation and persistence finish. */ -export async function checkDeclarationArtifacts(input: { +type DeclarationCheckInput = { state: DeclarationArtifactIdentity; worktree: string; commit: string; declarations: DeclarationSubmission['declarations']; env: NodeJS.ProcessEnv; signal: AbortSignal; timeoutMs?: number; - allowAuxiliaryDefinitions?: boolean; +}; +type TeamDeclarationCheckInput = DeclarationCheckInput & { + /** Checks writer shutdown, run identity and the exact commit of the input workspace. */ + assertFrozenSource: () => void; /** Only for host-selected declarations whose signature comes from independently checked source. */ inferredExpectedTypes?: ReadonlySet; +}; + +/** The caller must hold its writer-stop guarantee until this operation and persistence finish. */ +export async function checkDeclarationArtifacts(input: DeclarationCheckInput & { assertWriterStopped: () => void; }): Promise { - const declarations = parseDeclarationSubmission({ declarations: input.declarations }).declarations; const { state, worktree, commit, signal } = input, { problem } = state; - commitHash.parse(commit); const identity = canonicalMathJson(identityOf(state)); - const stable = () => { + const assertFrozenSource = () => { signal.throwIfAborted(); input.assertWriterStopped(); assertSolverSources(problem, worktree); if (canonicalMathJson(identityOf(state)) !== identity) return fail('run_identity_changed'); if (git(worktree, ['rev-parse', 'HEAD']) !== commit || git(worktree, ['status', '--porcelain', '--', ...problem.ownedFiles.map(file => path.join(problem.projectRelative, file))])) return fail('source_changed'); }; - stable(); + return checkArtifacts({ ...input, assertFrozenSource }, declarationSubmissionSchema, false); +} + +/** Host deliveries can include checked peer declarations in addition to a bounded member submission. */ +export async function checkTeamDeclarationArtifacts(input: TeamDeclarationCheckInput): Promise { + return checkArtifacts(input, teamDeclarationSubmissionSchema, true); +} + +async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof declarationSubmissionSchema, allowAuxiliaryDefinitions: boolean) { + const declarations = parseDeclarationSubmission({ declarations: input.declarations }, schema).declarations; + const { state, worktree, commit, signal, assertFrozenSource } = input, { problem } = state; + commitHash.parse(commit); + assertFrozenSource(); if (new Set(declarations.map(item => `${item.file}\0${item.name}`)).size !== declarations.length) return submissionFail('duplicate_declaration'); const environment = proofReuseEnvironment(path.join(worktree, problem.projectRelative), input.env); const records: DeclarationArtifact[] = []; + // Share the frozen snapshot across declarations. Each projection is still + // written to its own checkout and checked independently. + let project: ReturnType | undefined; + let sourceDigest: string | undefined; for (const declaration of declarations) { - stable(); + assertFrozenSource(); if (!problem.ownedFiles.includes(declaration.file)) return submissionFail('outside_ownership'); const checked = await withSolverWorktree(worktree, commit, async checkout => { const source = fs.readFileSync(path.join(checkout, problem.projectRelative, declaration.file), 'utf8'); @@ -276,7 +298,7 @@ export async function checkDeclarationArtifacts(input: { ['math_knowledge_declaration_missing_or_ambiguous']); const definition = declaration.kind === 'definition'; if (definition) { - if (!input.allowAuxiliaryDefinitions) return submissionFail('requires_theorem'); + if (!allowAuxiliaryDefinitions) return submissionFail('requires_theorem'); if (location.kind !== 'definition' || !/^(?:def|abbrev)\s/u.test(source.slice(location.startOffset, location.bodyOffset))) return submissionFail('requires_definition'); } else if (location.kind !== 'theorem') return submissionFail('requires_theorem'); @@ -292,8 +314,8 @@ export async function checkDeclarationArtifacts(input: { theoremName: declaration.name, type, dependsOn: [], revision: 0 }; let checkedCommit = commit; if (!checkHelperInDraft) { - const project = createTaskSourceProjector(problem, checkout, commit, { compact: true }); - const sources = submissionContent(() => project(task, []), ['math_task_type_invalid', 'math_task_missing_declaration', + const projector = project ??= createTaskSourceProjector(problem, worktree, commit, { compact: true }); + const sources = submissionContent(() => projector(task, []), ['math_task_type_invalid', 'math_task_missing_declaration', 'math_task_ambiguous_declaration', 'math_task_requires_theorem', 'math_task_requires_definition', 'math_task_helper_is_original_declaration']); for (const [file, text] of sources) fs.writeFileSync(path.join(checkout, problem.projectRelative, file), text); checkedCommit = commitSolverProjection(problem, checkout, `Check declaration ${declaration.name}`); @@ -313,12 +335,13 @@ export async function checkDeclarationArtifacts(input: { const references = result.verification.results[0]?.declarationReferences; const record: DeclarationArtifact = { schema: 'theorem-os.declaration-artifact.v1', id: '', ...identityOf(state), declaration, declarationHash, declarationDigest, - proof: { commit, sourceDigest: ownedSourceDigest(problem, worktree, commit), passed: true, verification: result.verification }, + proof: { commit, sourceDigest: sourceDigest ??= ownedSourceDigest(problem, worktree, commit), + passed: true, verification: result.verification }, ...(references ? { references: captureProofReferences(problem, checkout, commit, { file: declaration.file, name: declaration.name }, references, state.environmentDigest) } : {}) }; return { ...record, id: artifactId(record) }; }); - stable(); + assertFrozenSource(); const after = proofReuseEnvironment(path.join(worktree, problem.projectRelative), input.env); if (canonicalMathJson({ reusable: after.reusable, digest: after.digest, env: after.env }) !== canonicalMathJson({ reusable: environment.reusable, digest: environment.digest, env: environment.env })) return fail('environment_changed'); diff --git a/src/solver/freshContinuationChecks.ts b/src/solver/freshContinuationChecks.ts deleted file mode 100644 index 50403778..00000000 --- a/src/solver/freshContinuationChecks.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { projectMathematicsRuntimeEnvironment, resolveMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnvironment'; -import { isAttributedTaskProof, type TaskProof, type TaskProofRequest } from './cooperativeProof'; -import { taskVersion } from './tasks'; - -type ConditionalCheckInput = TaskProofRequest & { - environmentDigest: string; problemReceiptDigest: string; environment: NodeJS.ProcessEnv; -}; -// This binds a seed receipt to its live inputs, not to persisted acceptance. -const freshConditionalChecks = new WeakMap(); -const inputDigest = ({ task, assignment, retainedGoals, conditions = [], environment, - environmentDigest, problemReceiptDigest }: ConditionalCheckInput) => { - // The loader's path can change from the host config to the solver's frozen - // projection. Compare the effective settings, including the live proof seal. - const { DEEPSCIENTIST_MATH_ENV_FILE: _file, ...runtime } = - projectMathematicsRuntimeEnvironment(resolveMathematicsRuntimeEnvironment(environment)); - return mathDigest(canonicalMathJson({ taskDigest: taskVersion(task), assignment, retainedGoals: retainedGoals.toSorted(), - conditions: conditions.map(task => ({ taskId: task.id, taskDigest: taskVersion(task) })), - environmentDigest, problemReceiptDigest, environment: runtime })); -}; - -/** Only seeding with the caller's still-live prepared environment may hand off this receipt. */ -export function rememberFreshConditionalCheck(proof: TaskProof, input: ConditionalCheckInput) { - if (proof.passed && proof.conditions?.length && isAttributedTaskProof(proof)) - freshConditionalChecks.set(proof, inputDigest(input)); -} - -/** The caller must still apply its ordinary task, source, projection and receipt checks. */ -export function reusableFreshConditionalCheck(proof: TaskProof, input: ConditionalCheckInput): boolean { - return isAttributedTaskProof(proof) && freshConditionalChecks.get(proof) === inputDigest(input); -} diff --git a/src/solver/knowledgeContext.ts b/src/solver/knowledgeContext.ts index 79fc969a..d76dc52a 100644 --- a/src/solver/knowledgeContext.ts +++ b/src/solver/knowledgeContext.ts @@ -1,5 +1,5 @@ import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import type { CooperationState } from './cooperation'; +import type { CooperationState } from './cooperationShared'; import type { ContextSection } from './contextCompiler'; import { originalGoalTaskFocus } from './modules/search'; import type { SolverProblem } from './problem'; diff --git a/src/solver/libraryAccess.ts b/src/solver/libraryAccess.ts index 995fd471..a2f710c6 100644 --- a/src/solver/libraryAccess.ts +++ b/src/solver/libraryAccess.ts @@ -19,7 +19,7 @@ export const libraryRequestSchema = z.object({ schema: z.literal('theorem-os.lib export type LibraryRequest = z.infer; const contextSchema = z.object({ schema: z.literal('theorem-os.library-access.v1'), catalog: z.object({ file: z.string(), digest: hash }).strict(), problemReceiptDigest: hash, - seedCommit: z.string(), frozenFiles: z.record(hash) }).strict(); + seedCommit: z.string(), frozenFiles: z.record(hash), requestInstallation: z.literal(false).optional() }).strict(); /** Full release search and installation have no task-policy projection yet. */ export function assertLibraryCatalogAccess(problem: SolverProblem): void { @@ -27,11 +27,11 @@ export function assertLibraryCatalogAccess(problem: SolverProblem): void { } /** Published by the host before a turn; shell requests are advisory until the host validates them. */ -export function writeLibraryAccess(problem: SolverProblem, worktree: string, catalog: LibraryAccess) { +export function writeLibraryAccess(problem: SolverProblem, worktree: string, catalog: LibraryAccess, requestInstallation = true) { assertLibraryCatalogAccess(problem); writeMathJsonDurable(path.join(worktree, LIBRARY_ACCESS_FILE), { schema: 'theorem-os.library-access.v1', catalog, problemReceiptDigest: problem.receiptDigest, seedCommit: git(worktree, ['rev-parse', 'HEAD']), - frozenFiles: problem.frozenFiles ?? {} }, 0o400); + frozenFiles: problem.frozenFiles ?? {}, ...(requestInstallation ? {} : { requestInstallation: false }) }, 0o400); } export function agentLibrary(worktreeInput: string) { @@ -60,6 +60,7 @@ export function agentLibrary(worktreeInput: string) { 'library_source_budget'); }, request(requestedNames: string[], reason: string) { + if (context.requestInstallation === false) throw new Error('math_library_request_lead_required: send Lead the declaration name and intended application'); const request = libraryRequestSchema.parse({ schema: 'theorem-os.library-request.v1', catalogDigest: context.catalog.digest, problemReceiptDigest: context.problemReceiptDigest, seedCommit: context.seedCommit, names: [...new Set(requestedNames.map(name => name.replace(/^_root_\./u, '')))], reason }); diff --git a/src/solver/modules/context.ts b/src/solver/modules/context.ts index aa3b385c..0ef6ce36 100644 --- a/src/solver/modules/context.ts +++ b/src/solver/modules/context.ts @@ -14,7 +14,7 @@ import { committedSource, type SolverProblem } from '../problem'; import type { ProofCheck } from './evidence'; import { solverProofFeedback, type SolverFailure } from '../feedback'; import { assignmentDeliveryFile, leadPlanDeliveryFile, isActiveFinalCandidateReview, isFeasibilityReview, isFinalCandidateReview, taskGroup, taskVersion, type CooperativeAction } from '../tasks'; -import type { CooperationState } from '../cooperation'; +import type { CooperationState } from '../cooperationShared'; import { leadPlanPublicationFeedback } from '../cooperationShared'; import { contextCheckpointRejectionFeedback } from '../contextCheckpoint'; import { assignmentDeliveryReceipts } from '../deliveryReceipts'; @@ -29,7 +29,7 @@ import { continuationReferenceSection, referenceQuery } from '../continuationSea import { knowledgeApplicationContextSections } from '../knowledgeApplications'; import { installedLibraryContextSections } from '../installedLibraryContext'; import type { LibraryAccess } from '../libraryAccess'; -import { compileContextSections, compileTaskContext, cooperativeResponseSections, deliveryIndexRow, frozenSourceContext, landedHelperSection, leadPlanRejectionSection, leadResearchInputSection, portfolioContextSections, TaskContextError, +import { compileContextSections, compileTaskContext, cooperativeResponseSections, deliveryIndexRow, frozenSourceContext, landedHelperSection, leadPlanRejectionSection, leadResearchInputSection, TaskContextError, type CompiledContext, type ContextManifest, type ContextSection, type TaskContextInput } from '../contextCompiler'; import type { CustomResearchModule, ResearchModuleSlot } from './policy'; import { defaultResearchRouteConcurrency, researchTaskRole, type ResearchWorker } from './organization'; @@ -180,12 +180,14 @@ export function buildResearchContext(task: SolverProblem, state: Readonly target.proofPath))]; const proofFileArguments = proofFiles.length ? proofFiles.map(file => `--file ${shellArgument(file)}`).join(' ') : "--file 'OWNED_FILE.lean'"; const singleSolverDelivery = (state.workerCount ?? 1) === 1 && !cooperative && !access.assignment @@ -259,7 +254,7 @@ Temporary ${planningLead ? 'mathematical notes and tool output' : 'probes, backu Preserve original declaration kinds, names, parameters, types, assumptions, options and namespace/section context. Keep all existing imports. ${fixedReview ? 'Review original definition bodies and statement types without changing them.' : planningLead ? 'Inspect original definition bodies and statement types without changing them.' : 'Original goals may include def declarations whose bodies must be filled; retain all other original definition bodies.'} ${readOnlySources ? 'Leave all Lean source files, imports and environment configuration unchanged.' : 'In a Mathlib project, you may add import Mathlib or any pinned Mathlib.* import in owned files. You may also import installed frozen Submission.Library.* modules, frozen local modules already imported by the original owned files, or other owned modules. Avoid import cycles and do not edit trusted problem or package files.'} Proofs you submit for acceptance must not use sorry, admit, native_decide, unsafe or new axioms. Do not read external candidate solutions. ${longCommandGuidance} ${taskRules}${knowledgeRules}${readOnlyLibraryRules}${access.libraryCatalog && !readOnlySources && !(access.assignment?.kind === 'task' && (isFeasibilityReview(access.assignment.task) || isFinalCandidateReview(access.assignment.task))) ? -`Search the complete pinned TheoremOS release before reproving a fact or reporting a library gap: ${command} library search --worktree ${shellArgument(access.worktree)} --query 'MATHEMATICAL_KEYWORDS' --goal 'EXACT_LEAN_GOAL_AND_CONTEXT'. This also finds modules not installed in this problem. Inspect the full interface and module context with ${command} library get --worktree ${shellArgument(access.worktree)} --name 'QUALIFIED_NAME' --max-bytes 16000; follow source.nextOffset with --offset until source.complete is true. A source-header type may depend on section assumptions. For installed-frozen hits, import the given module and test the actual application in Lean. For a needed not-installed hit, submit ${command} library request --worktree ${shellArgument(access.worktree)} --name 'QUALIFIED_NAME' --reason 'EXACT_USE_AND_PREMISES', save your current proof work and RESEARCH.md, and return. You may request up to eight names. The host validates a pinned dependency closure and starts a new frozen continuation of the same original problem; requests neither mutate this run's library nor grant proof acceptance. Do not copy or redeclare library sources.\n` : ''}${proofSearchRules}${strategyAdvice(access, 'M1', fixedReview ? 'Inspect the fixed proof and its exact source-bound evidence. Batch independent reads and bound output in bytes.' : planningLead ? 'Inspect the frozen problem, relevant library interfaces and saved findings to develop the mathematical route. Batch independent read-only searches and bound output in bytes.' : 'Use installed library lemmas and test uncertain bridges early. Batch independent searches and reads, reuse results, bound output in bytes and show the earliest Lean error and goal.')} ${cooperative ? 'The host launches the cooperative agents; do not spawn agents inside this session.' : 'Do not spawn agents inside this session.'} ${strategyAdvice(access, 'M5', 'Lead planning saves a task graph and returns promptly; assigned workers investigate and prove it.', cooperative)} +`Search the complete pinned TheoremOS release before reproving a fact or reporting a library gap: ${command} library search --worktree ${shellArgument(access.worktree)} --query 'MATHEMATICAL_KEYWORDS' --goal 'EXACT_LEAN_GOAL_AND_CONTEXT'. This also finds modules not installed in this problem. Inspect the full interface and module context with ${command} library get --worktree ${shellArgument(access.worktree)} --name 'QUALIFIED_NAME' --max-bytes 16000; follow source.nextOffset with --offset until source.complete is true. A source-header type may depend on section assumptions. For installed-frozen hits, import the given module and test the actual application in Lean. For a needed not-installed hit, submit ${command} library request --worktree ${shellArgument(access.worktree)} --name 'QUALIFIED_NAME' --reason 'EXACT_USE_AND_PREMISES', save your current proof work and RESEARCH.md, and return. You may request up to eight names. The host validates a pinned dependency closure and starts a new frozen continuation of the same original problem; requests neither mutate this run's library nor grant proof acceptance. Do not copy or redeclare library sources.\n` : ''}${strategyAdvice(access, 'M1', fixedReview ? 'Inspect the fixed proof and its exact source-bound evidence. Batch independent reads and bound output in bytes.' : planningLead ? 'Inspect the frozen problem, relevant library interfaces and saved findings to develop the mathematical route. Batch independent read-only searches and bound output in bytes.' : 'Use installed library lemmas and test uncertain bridges early. Batch independent searches and reads, reuse results, bound output in bytes and show the earliest Lean error and goal.')} ${cooperative ? 'The host launches the cooperative agents; do not spawn agents inside this session.' : 'Do not spawn agents inside this session.'} ${strategyAdvice(access, 'M5', 'Lead planning saves a task graph and returns promptly; assigned workers investigate and prove it.', cooperative)} ${planningLead ? strategyAdvice(access, 'M3', 'Use the current mathematical route and saved peer evidence to choose the next planning decision.') : `For diagnostics, run ${command} check-lean --workspace ${shellArgument(path.join(access.worktree, task.projectRelative))} --file 'OWNED_FILE.lean' --timeout-seconds 0. Its --file path is relative to --workspace: use Submission.lean or Submission/Theory/Topic.lean without repeating the Lean project prefix. It writes JSON to stdout and progress to stderr; capture them separately (for example, > "$TMPDIR/check.json" 2> "$TMPDIR/check.log") and parse only stdout. It compiles saved sources with pinned imports and bounded output. ${diagnosticExecutionRules}Read firstBlocking and its exact position; follow diagnosticArtifacts for captured messages, local hypotheses and goals when previews are incomplete. Source/environment digests identify the checked inputs; inspect captureComplete before treating captured output as complete. The diagnostic sourceDigest hashes project configuration and transitive source files; it is not the file SHA256 or the host owned-source digest. Its environmentDigest also uses the diagnostic tool's identity scheme; different digest schemes need not match. Compare file bytes with the sourceFiles entries in .lake/lean-diagnostics-latest.json or diagnosticArtifacts, and compare digests only within the same scheme. phases[].cached:true means the tool matched source, configuration, environment and compiled artifact digests; it reuses a saved diagnostic, not a new compilation or proof acceptance. A new source change or a concrete failure needs a new check; an unchanged successful check does not need a copy or rebuild just to clear cached:true. To preflight an uncertain closed task type, add --type 'CLOSED_LEAN_TYPE' --context 'EXISTING_QUALIFIED_DECLARATION' with exactly one --file. This elaborates a type in a disposable proof-erased snapshot using that declaration's scopes; it does not check a proof or make future helper names available. Keep unavailable future dependencies explicit and revise an invalid interface before sending workers to prove it. Poll a returned process ID. A timeout is inconclusive. ${strategyAdvice(access, 'M3', fixedReview ? 'Report a failed check against the fixed candidate without changing its sources; resolve the discrepancy or request changes.' : 'Repair the earliest error; avoid rebuilding dependencies or repeating unchanged checks.')} ${fixedReview ? 'If the environment is unavailable, report the exact limitation in your verdict and return.' : 'For math_original_context_changed or math_original_declaration_changed, use the reported file and recovery instructions to restore the offending context or declaration from the seed commit while preserving new proof work, then retry the saved-file check. Keep helper-specific scopes and instances inside their proofs. If the environment is unavailable or the same startup error remains after a repair, report it and return.'}`} ${planningLead ? '' : `For a finite Boolean inference, use ${command} check-finite --json 'JSON' --witnesses 16. Supply {"schema":"theorem-os.finite-boolean-cnf.v1","variables":["A"],"fixed":[],"clauses":[[{"variable":"A","value":true}]]}. Each clause is a disjunction of matching literals and all clauses must hold. Preserve the exact input data and returned digests, satisfyingCount and complete witnesses in your research evidence. A satisfying assignment can refute only a claimed contradiction of those constraints; it does not refute their geometric construction or the original theorem. Size-unsupported results are inconclusive. Enumeration and its translation remain advisory and must be formalized for proof acceptance.\n`} ${declarationIndexRules(access.worktree, command)}${readOnlySources && !planningLead ? 'Inspect relevant declarations and their original assumptions without editing them.' : planningLead ? `Inspect relevant declarations and their original assumptions without editing them. ${strategyAdvice(access, 'M4', 'Keep RESEARCH.md as a concise mathematical route checkpoint with exact open questions and intended consumers.')}` : `${kernelCertificateRules(task, command, path.join(access.worktree, task.projectRelative))}${theoryModuleRules(task)}${libraryModuleRules(task)}Add helpers in owned modules; definitions may be noncomputable. For type lookup, add single-name #check commands such as #check Finset.sum_eq_single in the existing namespace. For instance lookup, use #synth MeasureSpace ℝ or parenthesize complex types, such as #synth Fintype (Fin 2). If a known library declaration is unavailable, find its module in the installed corpus and import that explicit Mathlib.* module in the owned file; an unknown name alone does not establish a missing library theorem. Check the actual saved file, remove probes before delivery, and save checked helpers, gaps and next steps in RESEARCH.md. ${strategyAdvice(access, 'M4', 'Keep this file as a concise current checkpoint; replace obsolete status instead of appending transcripts. Earlier committed notes remain in git history.')} ${singleSolverDelivery || 'Then return for independent host checking. '}Turns may be checkpointed and resumed. Verify computational results in Lean.`} @@ -268,7 +263,6 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac let message = access.sourceFeedback || (state.check && !state.check.passed ? solverProofFeedback(state.check, access.previousCheck, access.previousFailures ?? state.failures) : originalProblem); - const cooperation = state.cooperation; let checkpoint: string | undefined; if (!state.threadId && state.previousThreadIds?.length) { const notes = path.join(access.worktree, 'RESEARCH.md'); @@ -322,8 +316,7 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac frozenContexts: readFrozenContexts(task, access), maxContextBytes: access.maxContextBytes, maxOptionalContextBytes: access.maxOptionalContextBytes, environmentDigest: state.environmentDigest, - mandatory: [...(fixedReview ? [] : portfolioContextSections(state)), - ...(continuation ? [continuationContextSection(continuation, command, task.projectRelative)] : []), + mandatory: [...(continuation ? [continuationContextSection(continuation, command, task.projectRelative)] : []), ...(singleSkill && state.researchDelegation?.mode === 'team' ? [agentTeamContextSection(state)] : []), ...(skillWorkflow ? [{ id: 'research-skill-identity', kind: 'assignment' as const, text: 'Frozen research skill:\n' + canonicalMathJson(state.researchSkill) }] : []), diff --git a/src/solver/planApproval.ts b/src/solver/planApproval.ts index b2e248cb..b78a1471 100644 --- a/src/solver/planApproval.ts +++ b/src/solver/planApproval.ts @@ -1,6 +1,10 @@ import path from 'node:path'; +import crypto from 'node:crypto'; import { z } from 'zod'; import type { SolverRunState } from './archive'; +import { pendingDeliveryLines } from './deliveries'; +import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; +import type { TaskRecord } from './tasks'; /** * A run started with --plan-approval holds every worker after its first accepted plan until a human approves @@ -41,3 +45,74 @@ export function planApprovalInspection(state: SolverRunState) { worker.role === 'lead' && worker.scheduling?.status === 'working' && worker.scheduling.action === 'lead' && worker.scheduling.since >= record.revisionAt!)) }; } + +/** Both kinds of Lead consume the same approval log and persist the result before advancing its cursor. */ +export function drainPlanApprovals(state: SolverRunState, stateFile: string, signal: AbortSignal, save: () => void, + emit: (event: string, details: Record) => void, changed = save) { + const archive = state.cooperation; + if (!archive) return; + for (const entry of pendingDeliveryLines(planApprovalLog(stateFile), archive.cursors ??= {}, 'planApprovals', save, 'drain')) { + signal.throwIfAborted(); + if (!entry.error && !entry.line?.trim()) continue; + let approval: PlanApprovalInput | undefined; + if (entry.line) try { approval = planApprovalInputSchema.parse(JSON.parse(entry.line)); } catch { /* Invalid logged entry. */ } + const record = archive.planApproval ??= {}; + if (approval && record.approvedId === approval.id) continue; + const status = planApprovalStatus(state); + const reason = entry.error ?? (!approval ? 'math_plan_approval_invalid' : status === 'not-required' ? 'math_plan_approval_not_required' : + status === 'approved' ? 'math_plan_approval_already_approved' : status === 'awaiting-plan' ? 'math_plan_approval_plan_unavailable' : + approval.planVersion !== archive.planVersion ? 'math_plan_approval_version_conflict' : undefined); + if (!approval || reason) { + const rejection = { id: approval?.id ?? crypto.randomUUID(), reason: reason!, at: Date.now(), + ...(approval ? { planVersion: approval.planVersion } : {}) }; + record.rejections = [...record.rejections ?? [], rejection].slice(-MAX_PLAN_APPROVAL_REJECTIONS); + changed(); + emit('plan_approval_rejected', rejection); + } else { + Object.assign(record, { approvedId: approval.id, approvedVersion: approval.planVersion, approvedAt: Date.now() }); + changed(); + emit('plan_approved', { id: approval.id, planVersion: approval.planVersion }); + } + } +} + +export const nativePlanApprovalSchema = z.object({ + operation: z.literal('publish_plan'), + goals: z.array(z.object({ theoremName: z.string().trim().min(1).max(512), + objective: z.string().trim().min(1).max(2000) }).strict()).min(1), + investigations: z.array(z.string().trim().min(1).max(2000)).max(32).optional(), +}).strict(); + +export function nativeApprovalPlanBrief(tasks: readonly TaskRecord[]) { + return canonicalMathJson(tasks.map(({ task }) => ({ + objective: task.objective, ...(task.theoremName ? { theoremName: task.theoremName } : {}), + }))); +} + +export function publishNativeApprovalPlan(state: SolverRunState, plan: z.infer, + save: () => void, emit: (event: string, details: Record) => void) { + const goals = new Map(plan.goals.map(goal => [goal.theoremName, goal.objective])); + if (goals.size !== plan.goals.length || goals.size !== state.problem.targets.length || + state.problem.targets.some(target => !goals.has(target.theoremName))) + throw new Error('math_team_plan_targets_mismatch: Supply exactly one objective for each frozen original target, using its full theorem name.'); + const tasks: TaskRecord[] = [ + ...state.problem.targets.map((target, index): TaskRecord => ({ status: 'pending', attempts: 0, + task: { id: 'goal_' + (index + 1), kind: 'goal', theoremName: target.theoremName, proofPath: target.proofPath, + objective: goals.get(target.theoremName)!, dependsOn: [], revision: 1 } })), + ...(plan.investigations ?? []).map((objective, index): TaskRecord => ({ status: 'pending', attempts: 0, + task: { id: 'research_' + (index + 1), kind: 'research', objective, dependsOn: [], revision: 1 } })), + ]; + if (Buffer.byteLength(nativeApprovalPlanBrief(tasks)) > 24 * 1024) + throw new Error('math_team_plan_too_large: Keep the complete plan below 24 KiB so it fits in a resumed Lead context.'); + const planVersion = mathDigest(canonicalMathJson({ receipt: state.problem.receiptDigest, tasks })); + const status = planApprovalStatus(state); + if (status === 'pending' && state.cooperation?.planVersion === planVersion) + return { ok: true, status, planVersion }; + if (status !== 'awaiting-plan') throw new Error('math_team_plan_already_published'); + // Reuse the workbench's plan projection while Codex retains all decisions about assignments. + state.cooperation = { tasks, planVersion, planApproval: { requestedAt: Date.now(), requestedVersion: planVersion } }; + save(); + emit('plan_approval_requested', { planVersion }); + return { ok: true, status: 'pending', planVersion, + hint: 'The host is waiting for approval. Return from this turn. Continue on the next turn after the host confirms approval.' }; +} diff --git a/src/solver/planTool.ts b/src/solver/planTool.ts index 0e5fa2f3..a036f93a 100644 --- a/src/solver/planTool.ts +++ b/src/solver/planTool.ts @@ -1,9 +1,9 @@ import fs from 'node:fs'; import path from 'node:path'; -import { canonicalMathJson, mathDigest, readMathText, writeMathTextDurable } from '../math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath } from '../math/paths'; import { leadPlanPublicationTarget, parseLeadPlan } from './cooperationShared'; -import { appendDeliveryEvent, MAX_RESEARCH_NOTES_BYTES, parseMathResponse, replacePlanInNotes } from './deliveries'; +import { MAX_RESEARCH_NOTES_BYTES } from './deliveries'; import type { GoalPathReview } from './goalPathReview'; import { invalidPlanField, PlanValidationError, type PlanIssue } from './planDiagnostics'; import { liftNestedPlanPatch, type PlanPatchBase } from './planPatch'; @@ -29,17 +29,16 @@ function validated(value: unknown, context: PlanToolContext) { if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) throw invalidPlanField('math_plan_invalid', '$', 'Supply one JSON object containing a complete plan or revision.'); const plan = parseLeadPlan(context.problem, candidate, context.base, { goalPath: context.goalPath }); - const canonical = canonicalMathJson(candidate); const result: PlanValidation = { ok: true, planVersion: mathDigest(canonicalMathJson(plan)), baseVersion: context.base?.version, summary: `Validated ${plan.tasks.length} tasks in ${plan.groups.length} groups.`, tasksCount: plan.tasks.length, groupsCount: plan.groups.length, retireRoutesCount: plan.retireRoutes?.length ?? 0, }; - return { canonical, result }; + return result; } export function validateCooperationPlan(value: unknown, context: PlanToolContext): PlanValidation | PlanFailure { - try { return validated(value, context).result; } catch (error) { return failure(error); } + try { return validated(value, context); } catch (error) { return failure(error); } } function readCandidate(input: PlanInput): unknown { @@ -75,53 +74,9 @@ function prepare(input: PlanInput) { const candidate = readCandidate(input); const worktree = fs.realpathSync(input.workspace); assertMathCanonicalPath(worktree); - return { worktree, ...validated(candidate, workspacePlanContext(worktree)) }; + return validated(candidate, workspacePlanContext(worktree)); } export function validateCooperationPlanFile(input: PlanInput): PlanValidation | PlanFailure { - try { return prepare(input).result; } catch (error) { return failure(error); } -} - -/** Bind a draft to the projected dispatch. The host still admits it against live state. */ -export function publishCooperationPlanFile(input: PlanInput): (PlanValidation & { file: string; status: 'queued' }) | PlanFailure { - try { - const worktree = fs.realpathSync(input.workspace); - assertMathCanonicalPath(worktree); - const context = workspacePlanContext(worktree); - const target = context.publication; - if (!target) throw invalidPlanField('math_plan_publication_unavailable', '--publish', - 'Use the current Lead dispatch, or omit --publish to save a draft in RESEARCH.md.'); - if (context.base && context.base.version !== target.baseVersion) - throw invalidPlanField('math_plan_publication_version_conflict', 'baseVersion', 'The live dispatch base has changed.'); - const draft = liftNestedPlanPatch(readCandidate(input)); - if (!draft || typeof draft !== 'object' || Array.isArray(draft)) - throw invalidPlanField('math_plan_invalid', '$', 'Supply one JSON object containing a complete plan or revision.'); - const value = draft as Record; - if (value.baseVersion !== undefined && value.baseVersion !== target.baseVersion) - throw invalidPlanField('math_plan_patch_version_conflict', 'baseVersion', 'Rewrite this draft against the current accepted graph.'); - const { file, ...binding } = target; - const event = { ...value, ...binding }; - const { result } = validated(event, context); - appendDeliveryEvent(worktree, file, event); - return { ...result, file, status: 'queued' }; - } catch (error) { return failure(error); } -} - -/** Write a validated draft in one rename. Any revision keeps its baseVersion and decision fields until host intake. */ -export function applyCooperationPlanFile(input: PlanInput): (PlanValidation & { file: string }) | PlanFailure { - let candidate: ReturnType; - try { candidate = prepare(input); } catch (error) { return failure(error); } - const { worktree, result, canonical } = candidate; - const file = path.join(worktree, 'RESEARCH.md'); - try { - assertMathCanonicalPath(file); - const source = fs.existsSync(file) ? readMathText(file, MAX_RESEARCH_NOTES_BYTES) : ''; - const next = replacePlanInNotes(source, canonical); - if (Buffer.byteLength(next) > MAX_RESEARCH_NOTES_BYTES) - throw invalidPlanField('math_plan_notes_too_large', 'RESEARCH.md', 'Shorten the existing notes or the plan so they fit within 1 MB.'); - if (canonicalMathJson(parseMathResponse(next, 'math-plan')) !== canonical) - throw invalidPlanField('math_plan_notes_invalid', 'RESEARCH.md', 'Repair the existing plan fence before applying the draft.'); - if (source !== next) writeMathTextDurable(file, next); - return { ...result, file }; - } catch (error) { return failure(error, 'RESEARCH.md'); } + try { return prepare(input); } catch (error) { return failure(error); } } diff --git a/src/solver/portfolioExploration.ts b/src/solver/portfolioExploration.ts index aa09a53b..88542d67 100644 --- a/src/solver/portfolioExploration.ts +++ b/src/solver/portfolioExploration.ts @@ -1,29 +1,12 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { randomUUID } from 'node:crypto'; import { z } from 'zod'; import { isSimpleLeanName } from '../math/leanSyntax'; -import { mathDigest, readMathText } from '../math/mathRuntimeIo'; -import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; -import type { MathAgentOptions, MathAgentSession } from '../runtime/agentSession'; -import { projectResearchHarnessProfile } from '../runtime/researchHarness'; import type { SolverRunState } from './archive'; -import { withSolverWorktree } from './problem'; import { portfolioRouteIdSchema as routeId, retiredRouteSchema } from './routeControl'; -import { ResearchUsage } from './researchUsage'; -import { buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed, type RequestUsageAccounting, type UsageAccounting } from './usageBudget'; +import type { RequestUsageAccounting, UsageAccounting } from './usageBudget'; -export const PORTFOLIO_DEFAULT_SECONDS = 1800; export const PORTFOLIO_MAX_SECONDS = 86_400; -const profiles = ['structural-symmetry', 'explicit-constructive', 'falsification-obstruction'] as const; -const profileSchema = z.enum(profiles); -type ScoutProfile = z.infer; -const profileInstructions: Record = { - 'structural-symmetry': 'Look for coordinate changes, symmetries, invariants, convexity, monotonicity and conceptual reductions.', - 'explicit-constructive': 'Find an explicit formula, witness, rational bound or direct construction.', - 'falsification-obstruction': 'Attack the key reductions in the other routes. Seek concrete counterexamples, degeneracies and complexity blowup.', -}; +const profileSchema = z.enum(['structural-symmetry', 'explicit-constructive', 'falsification-obstruction']); const text = (max: number) => z.string().trim().min(1).max(max); const probeName = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,79}$/u); const timestamp = z.number().int().nonnegative(); @@ -67,285 +50,3 @@ export type PortfolioExploration = Omit) => state.portfolioExploration?.scouts ?? []; - -/** The gate ranks proposals and records scoped negative knowledge. It never emits proof receipts. */ -export function evaluatePortfolioGate(reports: readonly PortfolioScoutReport[], at = Date.now()): z.infer { - const retired = new Map>(); - for (const report of reports) { - const evidence = report.falsificationEvidence[0]; - if (report.status !== 'refuted' || !evidence || retired.has(report.routeId)) continue; - retired.set(report.routeId, { routeId: report.routeId, source: 'portfolio', retiredAt: at, - reason: `${evidence.claim}: ${evidence.result}`.slice(0, 1500), - evidenceRefs: [`portfolio:${report.profile}/${report.routeId}`, ...report.probeRefs.map(ref => `portfolio:${report.profile}/${ref}`)] }); - } - const viable = reports.filter(report => report.status === 'proposed' && !retired.has(report.routeId)).sort((a, b) => - a.obstructions.length - b.obstructions.length || - Number(b.proposedFoundationLemmas.length > 0) - Number(a.proposedFoundationLemmas.length > 0) || - b.probeRefs.length - a.probeRefs.length || - a.proposedFoundationLemmas.length - b.proposedFoundationLemmas.length || - a.keyTransformations.length - b.keyTransformations.length || - a.routeId.localeCompare(b.routeId)); - const primary = viable[0], backup = viable.find(report => report.routeId !== primary.routeId); - return { ...(primary ? { primaryRouteId: primary.routeId } : {}), ...(backup ? { backupRouteId: backup.routeId } : {}), - retiredRoutes: [...retired.values()], foundationLemmas: primary?.proposedFoundationLemmas ?? [] }; -} - -export function portfolioPhase2Guidance(portfolio?: PortfolioExploration): string { - if (portfolio?.phase !== 'completed' || !portfolio.gate) return ''; - const { gate } = portfolio; - if (!portfolio.scouts.some(scout => scout.reports?.length)) - return 'Phase 1 ended without a usable report. Proceed with the frozen problem and delegate independent gaps using available worker capacity.'; - const summaries = [gate.primaryRouteId, gate.backupRouteId].flatMap(id => { - if (!id) return []; - const report = portfolio.scouts.flatMap(scout => scout.reports ?? []).find(report => - report.routeId === id && report.status === 'proposed'); - return report ? [{ routeId: id, blueprintSummary: report.blueprintSummary, - keyTransformations: report.keyTransformations }] : [{ routeId: id }]; - }); - return 'Phase 1 portfolio gate (advisory mathematical evidence). Use the primary blueprint and schedule shared foundation lemmas ' + - 'as small exact obligations before dispatching goal families. Treat retired routes and their evidence as negative knowledge. ' + - 'Carry every proposed lemma through normal Lean preflight and independent proof checks.\n' + - JSON.stringify({ primaryRouteId: gate.primaryRouteId, backupRouteId: gate.backupRouteId, blueprints: summaries, - retiredRoutes: gate.retiredRoutes, foundationLemmas: gate.foundationLemmas }); -} - -/** Omitting both flags leaves older runs on their historical direct-start path. */ -export function configurePortfolioExploration(saved: PortfolioExploration | undefined, input: { - enable?: boolean; skip?: boolean; durationMs?: number; capacity: number; startedResearch: boolean; -}): PortfolioExploration | undefined { - if (input.enable && input.skip) throw new Error('conflicting --portfolio-exploration and --skip-portfolio'); - if (input.durationMs !== undefined && (!input.enable && !saved || input.skip)) - throw new Error('--portfolio-seconds requires --portfolio-exploration'); - if (saved) { - if (input.durationMs !== undefined && input.durationMs !== saved.durationMs) throw new Error('math_resume_portfolio_duration_changed'); - if (input.skip && saved.phase === 'exploring') return { ...saved, phase: 'skipped' }; - return saved; - } - if (!input.enable) return undefined; - if (input.startedResearch) throw new Error('math_portfolio_must_precede_phase_two'); - if (input.capacity < 2) throw new Error('--portfolio-exploration requires at least two workers or a team with at least two agents'); - const durationMs = portfolioExplorationSchema.shape.durationMs.parse(input.durationMs ?? PORTFOLIO_DEFAULT_SECONDS * 1000); - return { phase: 'exploring', durationMs, - scouts: profiles.slice(0, Math.min(3, input.capacity)).map(profile => ({ profile, status: 'pending', turns: 0 })) }; -} - -const reportFile = 'PORTFOLIO.json'; -const instructions = (profile: ScoutProfile, ownedFiles: readonly string[], budgetMs: number) => { - const example = { reports: [{ routeId: profile, status: 'proposed', blueprintSummary: 'Reduction with explicit remaining premises.', - keyTransformations: ['First reduction'], proposedFoundationLemmas: [{ id: 'base-identity', - proofPath: ownedFiles[0], theoremName: 'Portfolio.baseIdentity', type: '∀ (n : Nat), n = n', - objective: 'State one small shared prerequisite with its exact mathematical meaning.' }], - falsificationEvidence: [], obstructions: [], probeRefs: [] }] }; - return [ - 'Phase 1 portfolio scout: ' + profile + '. ' + profileInstructions[profile], - `Wall-clock budget remaining: ${Math.ceil(budgetMs / 1000)} seconds. Write an initial valid ${reportFile} by halfway, even if your finding is inconclusive. ` + - 'Update it as evidence improves by writing a temporary file in the same directory and renaming it over the report.', - 'Inspect the fixed Lean statement. Use mathematical derivations and quick numerical or symbolic probes with Python, PARI/GP, SymPy or SAT as available.', - 'Keep original Lean files read-only. If necessary, write at most two Lean API probes of fewer than 40 lines each under .scratch/portfolio. Do not formalize full proofs.', - 'Test the key claim in your own route even when another scout is assigned to falsification. The route IDs are ' + profiles.join(', ') + '.', - 'For a refutation, use the affected routeId and include falsificationEvidence entries with kind (counterexample or obstruction), exact claim, reproducible probe or derivation, and result.', - 'Report uncertainty as inconclusive. List up to six small shared foundation lemma statements with exact closed Lean types and a proofPath from ' + JSON.stringify(ownedFiles) + '.', - 'Save probes under .scratch/portfolio and list their basenames in probeRefs. Write one JSON object to ' + reportFile + ' with up to three reports and return.', - JSON.stringify(example), - ].join('\n'); -}; - -function readScoutReports(worktree: string, profile: ScoutProfile, problem: SolverRunState['problem']) { - const file = path.join(worktree, reportFile); - assertMathCanonicalPath(file); - const { reports } = z.object({ reports: z.array(reportBodySchema).min(1).max(3) }).strict() - .parse(JSON.parse(readMathText(file, 96 * 1024))); - const editable = new Set(problem.ownedFiles.filter(file => file.endsWith('.lean') && !Object.hasOwn(problem.frozenFiles ?? {}, file))); - if (new Set(reports.map(report => report.routeId)).size !== reports.length || - reports.some(report => !profileSchema.safeParse(report.routeId).success || - report.status === 'proposed' && report.routeId !== profile)) throw new Error('math_portfolio_route_outside_assignment'); - const probes = []; - for (const ref of new Set(reports.flatMap(report => report.probeRefs))) { - const file = path.join(worktree, '.scratch', 'portfolio', ref); - assertMathCanonicalPath(file); - const text = readMathText(file, 8192); - probes.push({ ref, text, digest: mathDigest(text) }); - } - return { probes, reports: reports.map(report => ({ ...report, profile, - proposedFoundationLemmas: report.proposedFoundationLemmas.filter(lemma => editable.has(lemma.proofPath)) })) }; -} - -/** Run once before planning, on disposable worktrees pinned to the original commit. */ -export async function runPortfolioExploration(input: { - state: SolverRunState; executable: string; profile: string; taskText: string; signal: AbortSignal; - open: (options: MathAgentOptions) => Promise; remainingMs: () => number; - maxTurns: number; maxTurnMs: number; maxTotalTokens: number; - prepareWorkspace: (workspace: string) => { project: string; environment: NodeJS.ProcessEnv }; - assertCurrent?: () => void; - save: () => void; emit: (event: string, details?: Record) => void; -}): Promise { - const { state, save, emit } = input; - const portfolio = state.portfolioExploration; - if (portfolio?.phase !== 'exploring') return; - input.signal.throwIfAborted(); - input.assertCurrent?.(); - const proofRecords = [...(state.workers ?? [state]), ...(state.agentTeam?.workers ?? [])]; - for (const record of [...proofRecords, ...portfolio.scouts]) initializeUsageAccounting(record); - portfolio.deadlineAt ??= Date.now() + Math.min(portfolio.durationMs, input.remainingMs()); - const remainingMs = () => Math.max(0, Math.min(input.remainingMs(), portfolio.deadlineAt! - Date.now())); - const changed = () => { - state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [...proofRecords, ...portfolio.scouts], state.tokenBudget?.enforcement); - save(); - }; - const eligible = portfolio.scouts.filter(scout => scout.status === 'pending' || scout.status === 'running'); - const capacity = Math.max(0, input.maxTurns - state.turns - 1); - const selected = portfolio.scouts.length - eligible.length + capacity >= 2 ? eligible.slice(0, capacity) : []; - for (const scout of eligible) if (!selected.includes(scout)) scout.status = 'failed'; - changed(); - emit('portfolio_exploration_started', { deadlineAt: portfolio.deadlineAt, profiles: selected.map(scout => scout.profile) }); - const deadline = new AbortController(); - const signal = AbortSignal.any([input.signal, deadline.signal]); - const runRoot = path.dirname(state.worktree); - const portfolioWorktreeRoot = path.join(runRoot, 'portfolio-worktrees'); - const portfolioProfileRoot = path.join(runRoot, 'portfolio-profiles'); - const timedOut = () => !input.signal.aborted && (deadline.signal.aborted || !remainingMs()); - const deadlineTimer = setTimeout(() => deadline.abort(new Error('math_portfolio_scout_timed_out')), Math.ceil(remainingMs())); - deadlineTimer.unref(); - let falsifier: MathAgentSession | undefined; - const proposals = () => portfolio.scouts.flatMap(scout => (scout.reports ?? []).filter(report => report.status === 'proposed') - .map(({ routeId, blueprintSummary, keyTransformations }) => ({ routeId, blueprintSummary, keyTransformations }))); - try { - if (selected.length && remainingMs() && modelDispatchAllowed(state.tokenBudget!)) { - const sourceProfile = path.resolve(input.profile); - if (isMathPathWithin(sourceProfile, portfolioProfileRoot) || isMathPathWithin(sourceProfile, portfolioWorktreeRoot)) - throw new Error('math_portfolio_profile_must_be_separate'); - for (const directory of [portfolioWorktreeRoot, portfolioProfileRoot]) { - assertMathCanonicalPath(directory); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - } - } - const outcomes = await Promise.allSettled(selected.map(async scout => { - if (!remainingMs() || !modelDispatchAllowed(state.tokenBudget!)) { - scout.status = remainingMs() ? 'failed' : 'timed-out'; changed(); return; - } - const profile = scout.profile; - const workerId = 'portfolio-' + profile; - // A retry uses a fresh thread. Preserve the cumulative usage already observed for the earlier attempt. - scout.usageBeforeThread = scout.usage; - scout.status = 'running'; save(); - try { - await withSolverWorktree(state.worktree, state.problem.baseCommit, async worktree => { - const prepared = input.prepareWorkspace(worktree); - fs.mkdirSync(path.join(worktree, '.scratch', 'portfolio'), { recursive: true, mode: 0o700 }); - let session: MathAgentSession | undefined, started = false, result: string | undefined; - let wrapUpTimer: ReturnType | undefined; - const usage = new ResearchUsage({ state, research: scout, maxTotalTokens: input.maxTotalTokens, - signal, remainingMs, changed, emit: (event, details) => emit(event, { ...details, profile }) }); - const sessionId = randomUUID(); - const profileDirectory = path.join(portfolioProfileRoot, `${profile}-${sessionId}`); - const scoutProfile = path.join(profileDirectory, 'profile'); - try { - signal.throwIfAborted(); - fs.mkdirSync(profileDirectory, { mode: 0o700 }); - if (state.agentHarness && state.agentHarness.id !== 'codex') { - projectResearchHarnessProfile(state.agentHarness, scoutProfile, prepared.environment, state.model); - } else { - fs.mkdirSync(scoutProfile, { mode: 0o700 }); - // Provider environment keys and configured auth commands still work. Never copy credential stores. - const config = path.resolve(input.profile, 'config.toml'); - assertMathCanonicalPath(config); - if (fs.existsSync(config)) fs.writeFileSync(path.join(scoutProfile, 'config.toml'), fs.readFileSync(config), - { flag: 'wx', mode: 0o400 }); - } - const scoutBudgetMs = Math.max(1, Math.min(input.maxTurnMs, remainingMs())); - session = await input.open({ executable: input.executable, profile: scoutProfile, workspace: worktree, - proofProjectRoot: prepared.project, model: state.model, effort: state.effort, isolateProcess: true, - isolatedWorkspaceParent: portfolioWorktreeRoot, - environment: { ...prepared.environment, DEEPSCIENTIST_MATH_WORKER_ID: workerId, - DEEPSCIENTIST_MATH_WORKER_WORKTREE: worktree }, - instructions: instructions(profile, state.problem.ownedFiles, scoutBudgetMs), signal, - turnTimeoutMs: scoutBudgetMs, - ...usage.bindSession(sessionId, () => session?.lastInputTokens) }); - signal.throwIfAborted(); - if (!remainingMs()) throw new Error('math_portfolio_scout_timed_out'); - if (!modelDispatchAllowed(state.tokenBudget!)) { - scout.status = 'failed'; - return; - } - usage.sessionOpened(session); - state.turns++; scout.turns++; - const counts = state.dispatchCounts ??= {}; - counts.research = (counts.research ?? 0) + 1; - started = true; usage.begin(undefined, 'portfolio-' + profile); - emit('portfolio_scout_started', { profile, workerId }); - const attacks = profile === 'falsification-obstruction'; - const currentProposals = attacks ? proposals() : []; - const turnBudgetMs = Math.min(remainingMs(), scoutBudgetMs); - const wrapUpLeadMs = Math.min(60_000, Math.max(15_000, Math.floor(turnBudgetMs * 0.3))); - try { - const activeScout = session; - result = await activeScout.run(input.taskText + '\n\nRead the frozen statement in ' + state.problem.projectRelative + '.' + - (currentProposals.length ? '\nProposals to test:\n' + JSON.stringify(currentProposals) : ''), randomUUID(), worktree, - turnId => { - usage.turnStarted(turnId); - if (attacks) falsifier = activeScout; - const remaining = Math.min(remainingMs(), turnBudgetMs); - if (remaining <= 20_000) return; - wrapUpTimer = setTimeout(() => { - if (signal.aborted) return; - const notice = `Stop starting probes and stop any running experiments. Write or finalize ${reportFile} now ` + - 'with your best route, exact obstruction or reproducible refutation. Use inconclusive if needed. Save it atomically and return.'; - void activeScout.notify?.(notice, activeScout.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : undefined) - .catch(async error => { - // Older app-servers may lack advisory history injection. Their normal steer still works. - if (!signal.aborted && activeScout.advisoryNotifications === 'native-history' && - error instanceof Error && error.message.startsWith('math_codex_rpc_failed:-32601:')) - await activeScout.notify?.(notice).catch(() => {}); - }); - }, Math.max(1000, remaining - wrapUpLeadMs)); - wrapUpTimer.unref(); - }); - } catch (error) { - if (!signal.aborted && !timedOut()) throw error; - } - } finally { - clearTimeout(wrapUpTimer); - if (falsifier === session) falsifier = undefined; - try { - const stopped = await session?.stopForFreeze?.(); - if (session && stopped?.status !== 'stopped') throw new Error('math_portfolio_scout_stop_unconfirmed'); - } finally { - try { await session?.close(); } - finally { - if (started) usage.finish(result === 'completed' || result === 'submitted'); - usage.sessionClosed(sessionId); - fs.rmSync(profileDirectory, { recursive: true, force: true }); - } - } - } - // Only accept validated advisory files. Reports atomically saved before a deadline remain useful. - if (fs.existsSync(path.join(worktree, reportFile))) { - Object.assign(scout, readScoutReports(worktree, profile, state.problem)); - scout.status = 'reported'; - void falsifier?.notify?.('Scout route proposals to test:\n' + JSON.stringify(proposals()), - falsifier.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }).catch(() => {}); - } else if (!input.signal.aborted) throw new Error('math_portfolio_scout_report_missing'); - }, portfolioWorktreeRoot); - } catch (error) { - if (!input.signal.aborted) scout.status = timedOut() ? 'timed-out' : 'failed'; - const reason = error instanceof Error ? /^math_[a-z0-9_]{1,72}(?=:|$)/u.exec(error.message)?.[0] : undefined; - emit('portfolio_scout_unavailable', { profile, workerId, status: scout.status, - reason: timedOut() ? 'math_portfolio_scout_timed_out' : reason ?? 'math_portfolio_scout_failed' }); - } finally { changed(); } - emit('portfolio_scout_finished', { profile, workerId, status: scout.status, reports: scout.reports?.length ?? 0 }); - })); - const failure = outcomes.find(outcome => outcome.status === 'rejected'); - if (failure?.status === 'rejected') throw failure.reason; - } finally { - clearTimeout(deadlineTimer); - for (const directory of [portfolioWorktreeRoot, portfolioProfileRoot]) { - if (fs.existsSync(directory) && fs.readdirSync(directory).length === 0) fs.rmdirSync(directory); - } - } - input.signal.throwIfAborted(); - input.assertCurrent?.(); - portfolio.gate = evaluatePortfolioGate(portfolio.scouts.flatMap(scout => scout.reports ?? [])); - portfolio.phase = 'completed'; - changed(); - emit('portfolio_gate_evaluated', { ...portfolio.gate }); -} diff --git a/src/solver/proofImport.ts b/src/solver/proofImport.ts deleted file mode 100644 index 1bbfdd7a..00000000 --- a/src/solver/proofImport.ts +++ /dev/null @@ -1,244 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { canonicalMathJson, mathDigest, readMathText, syncMathDirectory, withMathRuntimeLease } from '../math/mathRuntimeIo'; -import { inspectLeanDeclarationRegions, inspectLeanSource, inspectScopedLeanDeclarations } from '../math/leanSource'; -import { leanScopeCommands, leanScopeNamespace, maskLeanCommentsAndStrings, updateLeanScopes, type LeanScope } from '../math/leanSyntax'; -import type { SolverRunState } from './archive'; -import type { CooperativeResearch } from './cooperation'; -import { applyTaskChanges, declarationStartWithDoc, type DeclarationChange } from './cooperativeProof'; -import { readRunInspection } from './inspection'; -import type { ResearchWorker } from './modules/organization'; -import { committedSource, commitSolverSources } from './problem'; -import { proofImportRequestSchema, type ProofImportRequest, type ProofImportRecord } from './proofImportRecord'; -import { assignmentDeliveryFile, taskVersion, type CooperativeAction } from './tasks'; -import type { WorkerProofLifecycle } from './workerProofLifecycle'; - -const logName = 'proof-imports.jsonl'; -const fragmentLimit = 256 * 1024; -const requestDigest = (request: ProofImportRequest) => mathDigest(canonicalMathJson(request)); - -function fragmentDeclarations(fragment: string) { - if (Buffer.byteLength(fragment) > fragmentLimit) throw new Error('math_proof_import_too_large'); - const inspected = inspectLeanSource(fragment), clean = maskLeanCommentsAndStrings(fragment); - if (inspected.sorryCount || inspected.admitCount || inspected.axioms.length) throw new Error('math_proof_import_incomplete'); - const regions = inspectLeanDeclarationRegions(clean); - if (!regions.length || new Set(regions.map(region => region.name)).size !== regions.length || - regions.some(region => !/^(?:theorem|lemma)\s/u.test(clean.slice(region.startOffset, region.bodyOffset)))) - throw new Error('math_proof_import_requires_lemmas'); - // A fragment supplies declarations, never imports, scopes, options, attributes, commands or elaborators. - if (/^[ \t]*(?:#|import\b|namespace\b|section\b|end\b|open\b|variable\b|universe\b|set_option\b|attribute\b|export\b|syntax\b|macro\b|elab\b|notation\b|initialize\b|builtin_initialize\b)/mu.test(clean)) - throw new Error('math_proof_import_context_changed'); - let rest = clean; - for (const region of regions.toReversed()) rest = rest.slice(0, region.startOffset) + rest.slice(region.endOffset); - if (rest.trim()) throw new Error('math_proof_import_context_changed'); - return inspectLeanDeclarationRegions(fragment); -} - -function requests(directory: string): ProofImportRequest[] { - const file = path.join(directory, logName); - if (!fs.existsSync(file)) return []; - const source = readMathText(file, 8 * 1024 * 1024); - if (source && !source.endsWith('\n')) throw new Error('math_proof_import_incomplete_log'); - return source.split('\n').filter(Boolean).map(line => { - let parsed: unknown; - try { parsed = JSON.parse(line); } catch { throw new Error('math_proof_import_invalid'); } - const request = proofImportRequestSchema.safeParse(parsed); - if (!request.success) throw new Error('math_proof_import_invalid'); - return request.data; - }); -} - -/** Capture fragment bytes under the same CAS/append lease as human edits; never write the run checkpoint. */ -export async function queueProofImport(run: string, input: { - taskId: string; fragmentFile: string; sha256: string; baseVersion: string; id?: string; beforeTheorem?: string; -}, dryRun = false) { - const fragment = readMathText(input.fragmentFile, fragmentLimit); - if (!/^[a-f0-9]{64}$/u.test(input.sha256) || mathDigest(fragment) !== input.sha256) - throw new Error('math_proof_import_hash_mismatch'); - fragmentDeclarations(fragment); - const directory = path.dirname(readRunInspection(run).stateFile); - return withMathRuntimeLease({ lockPath: path.join(directory, 'edits.lock'), flockExecutable: '/usr/bin/flock' }, async lease => { - const { state } = readRunInspection(run), archive = state.cooperation; - const node = archive?.tasks.find(node => node.task.id === input.taskId); - if (!archive?.planVersion || !archive.canonicalCommit) throw new Error('math_proof_import_plan_unavailable'); - if (!node || node.task.kind !== 'lemma' || !node.task.proofPath || !node.task.theoremName || - (node.task.status ?? 'active') !== 'active') throw new Error('math_proof_import_task_invalid'); - if (input.beforeTheorem !== undefined) insertionOffset(committedSource(state.worktree, archive.canonicalCommit, - `${state.problem.projectRelative}/${node.task.proofPath}`), node.task.theoremName, input.beforeTheorem); - const value = { schema: 'theorem-os.proof-fragment.v1' as const, runId: state.runId, - baseVersion: input.baseVersion, taskId: node.task.id, taskDigest: taskVersion(node.task), - proofPath: node.task.proofPath, theoremName: node.task.theoremName, seedCommit: archive.canonicalCommit, - ...(input.beforeTheorem !== undefined ? { beforeTheorem: input.beforeTheorem } : {}), - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, - fragment, fragmentSha256: input.sha256 }; - const id = input.id ?? mathDigest(canonicalMathJson({ runId: state.runId, baseVersion: input.baseVersion, - taskId: input.taskId, fragmentSha256: input.sha256, - ...(input.beforeTheorem !== undefined ? { beforeTheorem: input.beforeTheorem } : {}) })); - const parsed = proofImportRequestSchema.safeParse({ ...value, id }); - if (!parsed.success) throw new Error('math_proof_import_invalid'); - const request = parsed.data, queued = requests(directory), previous = queued.find(item => item.id === id); - if (previous) { - if (requestDigest(previous) !== requestDigest({ ...request, seedCommit: previous.seedCommit, - problemReceiptDigest: previous.problemReceiptDigest, environmentDigest: previous.environmentDigest })) - throw new Error('math_proof_import_id_conflict'); - return { id, status: 'already_queued', taskId: request.taskId, fragmentSha256: request.fragmentSha256 }; - } - if (archive.proofImports?.some(item => item.id === id)) throw new Error('math_proof_import_id_conflict'); - if (input.baseVersion !== archive.planVersion) throw new Error('math_proof_import_version_conflict'); - if (node.status !== 'pending') throw new Error('math_proof_import_task_busy'); - if (queued.some(item => item.taskId === request.taskId && !archive.proofImports?.some(record => - record.id === item.id && !['received', 'frozen'].includes(record.status)))) - throw new Error('math_proof_import_task_queued'); - if (dryRun) return { id, status: 'validated', taskId: request.taskId, fragmentSha256: request.fragmentSha256 }; - const bytes = Buffer.from(JSON.stringify(request) + '\n'); - if (bytes.length > 1024 * 1024) throw new Error('math_proof_import_too_large'); - lease.assertHeld(); - const fd = fs.openSync(path.join(directory, logName), fs.constants.O_CREAT | fs.constants.O_WRONLY | - fs.constants.O_APPEND | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 0o600); - try { - const stat = fs.fstatSync(fd); - if (!stat.isFile() || stat.nlink !== 1) throw new Error('math_proof_import_log_invalid'); - let offset = 0; - while (offset < bytes.length) offset += fs.writeSync(fd, bytes, offset, bytes.length - offset); - fs.fsyncSync(fd); - } finally { fs.closeSync(fd); } - syncMathDirectory(directory); - return { id, status: 'queued', taskId: request.taskId, fragmentSha256: request.fragmentSha256 }; - }); -} - -/** Choose an existing namespace boundary; importing does not add or alter source context. */ -function insertionOffset(source: string, theoremName: string, beforeTheorem?: string): number { - const namespace = theoremName.includes('.') ? theoremName.slice(0, theoremName.lastIndexOf('.')) : ''; - const declarations = inspectScopedLeanDeclarations(source), regions = inspectLeanDeclarationRegions(source); - if (beforeTheorem !== undefined) { - const anchor = declarations.find(declaration => declaration.qualifiedName === beforeTheorem); - if (!anchor || anchor.namespace !== namespace) throw new Error('math_proof_import_invalid_anchor'); - return declarationStartWithDoc(source, anchor.startOffset); - } - const previous = declarations.findLast(declaration => declaration.namespace === namespace); - if (previous) return regions.find(region => region.startOffset === previous.startOffset)!.endOffset; - const scopes: LeanScope[] = []; - let offset = -1; - for (const command of leanScopeCommands(maskLeanCommentsAndStrings(source))) { - if (command[1] === 'end' && scopes.at(-1)?.kind !== 'mutual' && leanScopeNamespace(scopes) === namespace) offset = command.index; - updateLeanScopes(scopes, command[1], command[2]?.trim()); - } - if (leanScopeNamespace(scopes) === namespace) offset = source.length; - if (offset < 0) throw new Error('math_proof_import_missing_context'); - return offset; -} - -export function proofFragmentChanges(source: string, - request: Pick): { - changes: DeclarationChange[]; source: string; -} { - const regions = fragmentDeclarations(request.fragment), existing = inspectLeanDeclarationRegions(source); - const offset = insertionOffset(source, request.theoremName, request.beforeTheorem), tail = source.slice(offset); - const text = (value: string, region: typeof regions[number]) => value.slice( - value.lastIndexOf('\n', region.startOffset - 1) + 1, region.endOffset).trimEnd() + '\n'; - const additions = regions.filter(region => { - const previous = existing.find(item => item.name.split('.').at(-1) === region.name.split('.').at(-1)); - if (!previous) return true; - if (previous.name !== region.name || text(source, previous) !== text(request.fragment, region)) - throw new Error('math_proof_import_declaration_conflict'); - return false; - }); - const added = additions.map(region => text(request.fragment, region)).join(''); - const result = source.slice(0, offset) + added + tail; - const targets = inspectScopedLeanDeclarations(result).filter(declaration => - declaration.qualifiedName === request.theoremName || !request.theoremName.includes('.') && declaration.name === request.theoremName); - if (targets.length !== 1) throw new Error('math_proof_import_target_missing'); - return { source: result, changes: additions.map(region => ({ file: request.proofPath, - name: region.name, after: text(request.fragment, region), tail })) }; -} - -/** Mirror proof-ready progress; imported bytes and old receipts never establish proof acceptance. */ -export function syncProofImports(state: SolverRunState): void { - for (const record of state.cooperation?.proofImports ?? []) { - const ready = state.cooperation?.proofReadyRecords?.find(ready => ready.id === record.readyId || - ready.submissionId === record.id && ready.workerId === record.workerId && - ready.assignmentKey === record.assignmentKey && ready.snapshotCommit === record.snapshotCommit); - if (ready && ['frozen', 'checked', 'failed', 'superseded'].includes(ready.status)) { - record.readyId = ready.id; - record.status = ready.status as 'frozen' | 'checked' | 'failed' | 'superseded'; record.reason = ready.reason; - } - } -} - -/** Consume an import only after normal M3/M5 assignment and before opening a model writer. */ -export async function importAssignedProof(input: { - state: SolverRunState; directory: string; worker: ResearchWorker; action: CooperativeAction | undefined; - cooperation: CooperativeResearch; lifecycle: Pick; - close: () => Promise; save: () => void; emit: (event: string, details?: Record) => void; -}): Promise { - const { state, worker, action, cooperation, save, emit } = input; - if (action?.kind !== 'task' || action.task.kind !== 'lemma') return false; - syncProofImports(state); - const archive = state.cooperation!, records = archive.proofImports ??= []; - const request = requests(input.directory).find(request => request.taskId === action.task.id && - !records.some(record => record.id === request.id && !['received', 'frozen'].includes(record.status))); - if (!request) return false; - let record = records.find(record => record.id === request.id); - if (!record) { - record = { id: request.id, requestDigest: requestDigest(request), taskId: request.taskId, taskDigest: request.taskDigest, - fragmentSha256: request.fragmentSha256, status: 'received', receivedAt: Date.now() }; - records.push(record); save(); - } - const progress = record; - const finish = (status: ProofImportRecord['status'], reason?: string) => { - progress.status = status; progress.reason = reason; save(); - emit('proof_import_' + status, { id: request.id, taskId: request.taskId, fragmentSha256: request.fragmentSha256, - commit: progress.snapshotCommit, reason }); - }; - const current = () => cooperation.current(action) && request.runId === state.runId && - request.taskDigest === taskVersion(action.task) && request.proofPath === action.task.proofPath && request.theoremName === action.task.theoremName && - request.problemReceiptDigest === state.problem.receiptDigest && request.environmentDigest === state.environmentDigest; - if (progress.requestDigest !== requestDigest(request) || mathDigest(request.fragment) !== request.fragmentSha256) { - finish('rejected', 'math_proof_import_hash_mismatch'); return false; - } - if (!current() || !progress.snapshotCommit && (request.baseVersion !== archive.planVersion || - request.seedCommit !== (action.assignment.canonicalCommit ?? action.assignment.seedCommit))) { - finish('superseded', 'math_proof_import_basis_changed'); return false; - } - await input.close(); - if (!current()) { finish('superseded', 'math_proof_import_assignment_changed'); return true; } - const assignmentKey = assignmentDeliveryFile(action.assignment); - if (progress.snapshotCommit && (progress.workerId !== worker.id || progress.assignmentKey !== assignmentKey)) { - finish('superseded', 'math_proof_import_assignment_changed'); return false; - } - if (!progress.snapshotCommit) { - const file = path.join(worker.worktree, state.problem.projectRelative, request.proofPath); - const notes = path.join(worker.worktree, 'RESEARCH.md'), original = fs.readFileSync(file, 'utf8'); - const previousNotes = fs.existsSync(notes) ? fs.readFileSync(notes) : undefined; - let committed = false; - try { - const seed = committedSource(worker.worktree, action.assignment.seedCommit, `${state.problem.projectRelative}/${request.proofPath}`); - const prepared = proofFragmentChanges(seed, request); - for (const owned of state.problem.ownedFiles) { - const actual = fs.readFileSync(path.join(worker.worktree, state.problem.projectRelative, owned), 'utf8'); - const before = committedSource(worker.worktree, action.assignment.seedCommit, `${state.problem.projectRelative}/${owned}`); - if (actual !== before && !(owned === request.proofPath && actual === prepared.source)) - throw new Error('math_proof_import_workspace_changed'); - } - applyTaskChanges(state.problem, worker.worktree, prepared.changes); - fs.writeFileSync(notes, `Imported proof fragment ${request.id}\nSHA-256: ${request.fragmentSha256}\n`); - progress.snapshotCommit = commitSolverSources(state.problem, worker.worktree); committed = true; - progress.workerId = worker.id; progress.assignmentKey = assignmentKey; save(); - } catch (error) { - if (committed) throw error; - fs.writeFileSync(file, original); - if (previousNotes) fs.writeFileSync(notes, previousNotes); else fs.rmSync(notes, { force: true }); - if (!(error instanceof Error) || !error.message.startsWith('math_')) throw error; - finish('rejected', error.message); return false; - } - } - const ready = cooperation.freezeImportedProof(worker, action, request.id, progress.snapshotCommit!); - if (!ready) { finish('superseded', 'math_proof_import_assignment_changed'); return true; } - progress.readyId = ready.id; finish('frozen'); - await input.lifecycle.resumeFrozen(action); - syncProofImports(state); save(); - emit('proof_import_completed', { id: request.id, taskId: request.taskId, status: progress.status, - commit: progress.snapshotCommit, readyId: progress.readyId }); - return true; -} diff --git a/src/solver/research.ts b/src/solver/research.ts index 87f26d1f..6aab405f 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -10,43 +10,33 @@ import { VerifierFailureError, verifierFailureDiagnostic } from './verifierFailu import { readMathBuildManifest } from '../math/mathBuildManifest'; import { MathGitError } from '../math/mathGit'; import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; -import type { SolverRunState, SolverWorkerState } from './archive'; -import { commitSolverSources, git, solverScratchDigest, pinSolverResearchSkill } from './problem'; -import { CooperativeResearch } from './cooperation'; +import type { SolverRunState } from './archive'; +import { commitSolverSources, pinSolverResearchSkill } from './problem'; import { AgentResearchTeam, assertAgentTeamProcessesStopped } from './agentTeam'; +import { drainPlanApprovals, nativeApprovalPlanBrief, planApprovalStatus } from './planApproval'; import { LeanEnvironmentHealthCheckError } from '../runtime/leanHealthCheck'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, isFeasibilityReview, isFinalCandidateReview, taskGroup, type CooperativeAction } from './tasks'; -import { isStatementAction } from './statementReview'; import { rememberSolverFailure, solverSourceFeedback } from './feedback'; import type { SolverModules } from './modules'; import { solverProofIsCurrent, type ProofCheck } from './modules/evidence'; import { compactedResearchDispatch, finalizeResearchDispatch, type ContextBundle } from './modules/context'; import type { KnowledgeContextSnapshot } from './knowledgeContext'; -import { researchTaskRole, type ResearchWorker } from './modules/organization'; import type { ResearchOperation } from './modules/value'; -import { completedGuidanceDecisions, runResearchTurn, type ResearchCandidate } from './modules/execution'; +import { type ResearchCandidate } from './modules/execution'; import { planResearchCooldown, recoverableResearchFailure, researchFailureDetail, researchFailureReason } from './modules/search'; -import { aggregateUsage, buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; +import { buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; import { ResearchUsage } from './researchUsage'; import { inspectKnowledgeUses } from './knowledgeUsage'; import { checkKnowledgeApplications } from './knowledgeApplications'; -import { parseMathResponse, readMathResponse } from './deliveries'; +import { parseMathResponse } from './deliveries'; import { readCheckpointNotesDigest, savedContextCheckpoint } from './contextCheckpoint'; -import { checkpointCommand, researchToolCommand } from './researchToolGuide'; import { committedSource } from './problem'; import type { ContinuationSnapshot } from './continuationInput'; import type { MathTools } from '../math/mathTools'; -import { setWorkerResearchPhase, WorkerProofLifecycle } from './workerProofLifecycle'; -import { importAssignedProof, syncProofImports } from './proofImport'; -import { checkTaskProof, type TaskProof } from './cooperativeProof'; -import { captureResearchBasis, researchSourceDigest, type ResearchBasis } from './researchRecords'; +import { checkTaskProof } from './cooperativeProof'; import { writeOwnedDeclarationIndex } from './declarationIndex'; -import { LEAD_MAX_BACKOFF } from './leadWakes'; import { applyOriginalLibraryTasks } from './libraryApplication'; import { LibraryInstallationRequested, takeLibraryRequest, writeLibraryAccess, type LibraryAccess } from './libraryAccess'; -import { hasTaskConnectionCheck } from './taskConnections'; import { prepareTacticBatteryFailureCacheRoot } from './tacticBatteryFailureCache'; -import { committedResearchNotesDigest, researchHandoffNotesDigest } from './researchCheckpoints'; import { SingleSolverProofHandoff } from './singleSolverProofHandoff'; import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills'; import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext'; @@ -54,77 +44,10 @@ import { recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter'; import { createSkillProofLifecycle } from './skillProofLifecycle'; import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; import { materializeResearchToolHelp } from './researchToolHelp'; -import { portfolioUsageRecords } from './portfolioExploration'; +import { assertActiveResearchState } from './researchRetirement'; -// Scheduling checkpoints preserve unlimited solving budgets and resume the same assignment/thread. -const advisoryCheckpointNoticeMs = 90_000; -const advisoryCheckpointMs = 120_000; -const advisoryInterruptGraceMs = 10_000; -const advisoryProgressPollMs = 5_000; -const MIN_ADVISORY_SLICE_MS = 180_000; -export const LEAD_MAX_PLANNING_COMMANDS = 15; -const advisoryMaxBackoff = LEAD_MAX_BACKOFF; -// Provider latency is not mathematical work: the advisory clock starts only at the model's first -// item, with a hard cap so a turn that never responds still yields a resumable checkpoint. -const advisoryFirstActivityMs = 15 * 60_000; -// An unconditional goal turn can close the problem, so it is never yielded. It still owes a -// durable handoff: this is the long cadence of the save-only reminder, which never interrupts it. -const advisoryGoalNoticeMs = 15 * 60_000; -// The first graph can be small, but a 2-minute cut discarded initial plans before publication. -// Keep the long writing slice while asking for executable work early enough for peers to start. -const advisoryInitialPlanMs = 20 * 60_000; -const advisoryInitialPlanNoticeMs = 90_000; -// A plan revision is one decision on new peer evidence, not a search. Observed Lead slices of two to sixteen -// minutes ended at a checkpoint in 1095 of 1210 turns, and only 22 of those changed the plan. -// A revision gets one fixed slice that a returned decision normally ends, and an early decide-now reminder. -const advisoryRevisionMs = 10 * 60_000; -const advisoryRevisionNoticeMs = 4 * 60_000; -// A yielding slice that ends while the model is streaming waits for that request to settle, up to this long. -// Completed deepseek-flash requests in the OpenAI-math campaign took p99 446 s (workers) and 582 s (Lead). -const advisoryRequestWaitMs = 10 * 60_000; -// Codex reports streamed output at most every 30 s and the provider stream idles out at 60 s, so output -// newer than this means a model request is still producing. -const advisoryModelStreamingMs = 90_000; -// Items the model itself produces; userMessage and contextCompaction are neither model output nor tools. -const modelOutputItems = new Set(['reasoning', 'agentMessage']); +const interruptGraceMs = 10_000; const nonToolItems = new Set(['reasoning', 'agentMessage', 'userMessage', 'contextCompaction']); -// Compaction is maintenance, not a mathematical attempt. A stalled operation restarts from saved work. -const compactionRecoveryMs = 10 * 60_000; - -/** Host publication provenance is never part of the model's mathematical responsibility. */ -function promptAction(action?: CooperativeAction): CooperativeAction | undefined { - if (action?.kind !== 'task') return action; - const { researchBasis: _basis, ...assignment } = action.assignment; - return { ...action, assignment }; -} - -export function advisoryCheckpointScope(assignment: CooperativeAction | undefined): string | undefined { - if (assignment?.kind === 'lead') { - // New input warrants reconsideration, but does not change the mathematical responsibility. - return mathDigest(canonicalMathJson({ kind: 'lead', - phase: assignment.initialPlanNonce ? 'initial' : 'revision', - responsibility: assignment.responsibilityDigest })); - } - if (assignment?.kind === 'task' && isFeasibilityReview(assignment.task)) - return mathDigest(canonicalMathJson({ kind: 'feasibility-review', taskDigest: assignment.assignment.taskDigest, - workerId: assignment.assignment.workerId, inputDigest: assignment.assignment.feasibilityInputDigest, noticeOnly: true })); - if (assignment?.kind === 'task' && ['research', 'sketch'].includes(assignment.task.kind)) - return mathDigest(canonicalMathJson({ kind: 'task', taskDigest: assignment.assignment.taskDigest })); - if (assignment?.kind === 'task' && hasTaskConnectionCheck(assignment.task, assignment.assignment)) - return mathDigest(canonicalMathJson({ kind: 'connection', taskDigest: assignment.assignment.taskDigest, - basisDigest: assignment.assignment.connectionCheck!.basisDigest })); - // An original goal is the only work that can close the problem, so its writer is never yielded; - // it still owes a durable handoff, which the notice-only checkpoint asks for without interrupting. - if (assignment?.kind === 'task' && assignment.task.kind === 'goal') - return mathDigest(canonicalMathJson({ kind: 'task', taskDigest: assignment.assignment.taskDigest, noticeOnly: true })); - return undefined; -} - -/** Proof work and independent reviews save notes without a timed scheduling interruption. */ -export function advisoryCheckpointNoticeOnly(assignment: CooperativeAction | undefined): boolean { - return assignment?.kind === 'task' && (isFeasibilityReview(assignment.task) || assignment.task.kind === 'goal' && - !hasTaskConnectionCheck(assignment.task, assignment.assignment)); -} export type WorkerAccess = { environment: NodeJS.ProcessEnv; corpusFile?: string; retrievalRoot: string; /** Execution-only credentials are never projected into host Lean or saved environment records. */ @@ -140,29 +63,30 @@ export type WorkerAccess = { environment: NodeJS.ProcessEnv; corpusFile?: string libraryCatalog?: LibraryAccess; knowledgeFile?: string; knowledgeDigest?: string; knowledgeSnapshot?: KnowledgeContextSnapshot }; -/** Lead and isolated task workers share one budget; only a full canonical check grants acceptance. */ -export async function runResearchWorkers(input: { - state: SolverRunState; workers: readonly ResearchWorker[]; access: ReadonlyMap; +/** Run the Lead writer and connect any native team members to the same proof budget. */ +export async function runResearchLead(input: { + state: SolverRunState; access: WorkerAccess; modules: SolverModules; root: string; buildFile: string; taskText: string; executable: string; profile: string; signal: AbortSignal; deadline: number; maxTurns: number; maxTurnMs: number; maxTotalTokens: number; proofTimeoutMs?: number; executionBudget?: { remainingMs(): number; setWaiting(waiting: boolean): void }; prepareTeamWorker?: (id: string, worktree: string) => Promise; - freshContinuationChecks?: readonly TaskProof[]; goalProgressReviewMs?: number; minAdvisorySliceMs?: number; softSlice?: SoftSliceSettings; - leadMaxPlanningCommands?: number; save: () => void; emit: (event: string, details?: Record) => void; }): Promise<{ worktree: string; check: ProofCheck } | undefined> { - const { state, modules, save } = input; + const { state, access, modules, save } = input; const milestoneSettings = softSliceSettings(input.softSlice ?? {}); - const leadMaxPlanningCommands = input.leadMaxPlanningCommands ?? LEAD_MAX_PLANNING_COMMANDS; + const research = state; + const worker = { id: 'solver', role: 'lead' as const, worktree: state.worktree, ownedFiles: state.problem.ownedFiles }; + assertActiveResearchState(state); assertAgentTeamProcessesStopped(state); - const parallel = Boolean(state.workers); - const skillResearch = state.researchMode === 'skill'; - const fullSkillWorkflow = skillResearch && state.researchSkillWorkflow === 'full'; - const skillMode = skillResearch && !parallel; - if (skillResearch && (!state.researchSkill || !fullSkillWorkflow && - (parallel || state.cooperation || input.workers.length !== 1))) - throw new Error('math_skill_research_state_invalid'); + const skillMode = state.researchMode === 'skill'; + const fullSkillWorkflow = skillMode && state.researchSkillWorkflow === 'full'; + const nativePlanReview = state.planApproval && state.researchDelegation?.mode === 'team' && + state.agentTeam?.transport === 'native-agent-control'; + if (nativePlanReview && planApprovalStatus(state) === 'approved' && + state.cooperation?.planApproval?.approvedVersion !== state.cooperation?.planVersion) + throw new Error('math_plan_approval_version_conflict'); + if (skillMode && !state.researchSkill) throw new Error('math_skill_research_state_invalid'); if (state.pendingProofCheck && (!skillMode || state.pendingProofCheck.environmentDigest !== state.environmentDigest || state.pendingProofCheck.problemReceiptDigest !== state.problem.receiptDigest)) throw new Error('math_proof_checkpoint_identity_changed'); @@ -170,42 +94,33 @@ export async function runResearchWorkers(input: { state.pendingResearchFreeze.problemReceiptDigest !== state.problem.receiptDigest)) throw new Error('math_research_freeze_identity_changed'); if (state.researchDelegation && !skillMode) throw new Error('math_native_delegation_requires_skill'); - for (const agent of state.nativeAgents ?? []) if (agent.status === 'running' && !agent.stoppedAt) { - agent.status = 'unknown'; agent.updatedAt = Date.now(); - input.emit('investigator_recovery_recorded', { threadId: agent.threadId, replayed: false }); save(); - } - if (skillResearch || state.commonResearchSkill) for (const worker of input.workers) { - const access = input.access.get(worker.id); - const skill = access?.commonResearchSkill ?? access?.researchSkill; + if (skillMode || state.commonResearchSkill) { + const skill = access.commonResearchSkill ?? access.researchSkill; const identity = state.commonResearchSkill ?? state.researchSkill; if (!skill || !identity || skill.digest !== identity.digest || skill.loading !== identity.loading) throw new Error('math_research_skill_changed'); pinSolverResearchSkill(state.problem, worker.worktree, skill); } - const records = input.workers.map(worker => ({ worker, - research: parallel ? state.workers!.find(item => item.id === worker.id)! : state })); - const quarantined = records.find(({ research }) => research.writerStopUnconfirmed); - if (quarantined) throw new Error('math_writer_stop_unconfirmed:' + quarantined.worker.id + + if (research.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id + ': recover into a new isolated workspace before starting another writer.'); - for (const { research } of records) initializeUsageAccounting(research); + initializeUsageAccounting(research); const enforcement = state.tokenBudget?.enforcement; state.tokenBudget = buildTokenBudget(input.maxTotalTokens, - [...records.map(record => record.research), ...(state.agentTeam?.workers ?? []), ...portfolioUsageRecords(state)], enforcement); + [research, ...(state.agentTeam?.workers ?? [])], enforcement); const dispatchAllowed = () => modelDispatchAllowed(state.tokenBudget!); - const accepted = records.find(({ worker }) => worker.id === (state.winningWorker ?? 'solver')); - if (accepted && !state.pendingResearchFreeze && state.check?.passed && ['running', 'checking', 'evaluating', 'finished'].includes(state.phase) && - !solverSourceFeedback(state.problem, accepted.worker.worktree) && - solverProofIsCurrent(state.problem, accepted.worker.worktree, state.check)) { + if ((!nativePlanReview || planApprovalStatus(state) === 'approved') && + !state.pendingResearchFreeze && state.check?.passed && ['running', 'checking', 'evaluating', 'finished'].includes(state.phase) && + !solverSourceFeedback(state.problem, worker.worktree) && + solverProofIsCurrent(state.problem, worker.worktree, state.check)) { if (state.pendingProofCheck) { if (state.pendingProofCheck.commit !== state.check.commit || state.pendingProofCheck.sourceDigest !== state.check.sourceDigest) throw new Error('math_proof_checkpoint_identity_changed'); state.pendingProofCheck = undefined; save(); } - return { worktree: accepted.worker.worktree, check: state.check }; + return { worktree: worker.worktree, check: state.check }; } if (state.check?.passed) { state.check = undefined; state.winningWorker = undefined; - if (accepted) accepted.research.check = undefined; save(); } const controller = new AbortController(); @@ -224,15 +139,8 @@ export async function runResearchWorkers(input: { await previous; try { signal.throwIfAborted(); return await check(); } finally { release(); } }; - const cooperation = parallel && state.coordination !== 'independent' - ? new CooperativeResearch({ ...input, signal, exclusiveCheck, timeoutMs: input.proofTimeoutMs, - // A finite solving deadline still permits frontier recovery while budget remains. - // The caller's abort timer and dispatch admission enforce the time limit. - continuousResearch: input.maxTurns === Infinity, - onPlanApprovalWaiting: waiting => input.executionBudget?.setWaiting(waiting), - modelDispatchAllowed: dispatchAllowed }) : undefined; const team = state.researchDelegation?.mode === 'team' ? new AgentResearchTeam({ - state, root: input.root, taskText: input.taskText, leadAccess: input.access.get(input.workers[0].id)!, + state, root: input.root, taskText: input.taskText, leadAccess: access, modules, executable: input.executable, profile: input.profile, signal, maxAgents: state.researchDelegation.maxAgents, maxTurns: input.maxTurns, maxTurnMs: input.maxTurnMs, maxTotalTokens: input.maxTotalTokens, proofTimeoutMs: input.proofTimeoutMs, remainingMs: () => budget().remainingMs, @@ -241,1683 +149,757 @@ export async function runResearchWorkers(input: { const turnTiming = team ? teamTurnTiming(input.maxTurnMs) : { turnTimeoutMs: Number.isFinite(input.maxTurnMs) ? input.maxTurnMs : undefined }; const updateUsage = () => { - if (parallel) state.usage = aggregateUsage(state.workers!); const previous = state.tokenBudget!.status; - const usageRecords = [...records.map(record => record.research), ...(team?.usageRecords ?? []), ...portfolioUsageRecords(state)]; - state.tokenBudget = buildTokenBudget(input.maxTotalTokens, usageRecords, enforcement); - if (team) state.teamUsage = aggregateUsage(usageRecords); + if (team) team.refreshUsage(); + else state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [research], enforcement); if (state.tokenBudget.status !== previous && !dispatchAllowed()) input.emit('model_budget_stopped', { ...state.tokenBudget }); - cooperation?.modelBudgetChanged(); }; const errors: unknown[] = []; const cleanupErrors: unknown[] = []; state.error = undefined; try { await team?.restore(); - await cooperation?.restore(); - cooperation?.start(); - await Promise.all(records.map(async ({ worker, research }) => { - let session: MathAgentSession | undefined; - let sessionInstructions: string | undefined; - let closing: Promise | undefined; - let retries = 0; - let nativeContextRecovery: 'pending' | 'attempted' | undefined; - let lastCheck: ProofCheck | undefined; - research.error = undefined; - const access = input.access.get(worker.id)!; - if (skillResearch && !access.researchSkill) throw new Error('math_research_skill_missing'); - const view = (): SolverRunState => ({ ...state, ...research, turns: state.turns }); - const emit = (event: string, details = {}) => input.emit(event, { workerId: worker.id, ...details }); - // The host has one Lead writer in team mode too. This watches the full-proof Lean diagnostic, - // while the stopped-writer Skill lifecycle handles optional declaration nominations. - const singleHandoff = !parallel ? new SingleSolverProofHandoff(state.problem, worker.worktree, - submission => emit('proof_ready_checkpoint_requested', { ...submission, reason: 'current-lean-diagnostics' })) : undefined; - // Cooperative callers keep their existing stopped-writer quarantine; other callers receive exact correction feedback. - const sourceFeedback = () => solverSourceFeedback(state.problem, worker.worktree, - cooperation ? paths => emit('source_quarantined', { paths: paths.slice(0, 32), count: paths.length }) : undefined); - const recovered = () => { - const recovery = research.recovery; - if (!recovery || recovery.phase === 'recovered') return; - recovery.phase = 'recovered'; recovery.recoveredAt = Date.now(); - emit('worker_recovered', { reason: recovery.reason, cycles: recovery.cycles, waitedMs: recovery.waitedMs }); - save(); - }; - const waitForRecovery = async (resumed = false) => { - const recovery = research.recovery; - if (recovery?.phase !== 'cooling-down' || !dispatchAllowed() || budget().remainingMs <= 0 || - state.turns - Number(reservedTurn) >= input.maxTurns) return; + let session: MathAgentSession | undefined; + let sessionInstructions: string | undefined; + let closing: Promise | undefined; + let retries = 0; + let nativeContextRecovery: 'pending' | 'attempted' | undefined; + let lastCheck: ProofCheck | undefined; + research.error = undefined; + const emit = (event: string, details = {}) => input.emit(event, { workerId: worker.id, ...details }); + // The host has one Lead writer in team mode too. This watches the full-proof Lean diagnostic, + // while the stopped-writer Skill lifecycle handles optional declaration nominations. + const singleHandoff = new SingleSolverProofHandoff(state.problem, worker.worktree, + submission => emit('proof_ready_checkpoint_requested', { ...submission, reason: 'current-lean-diagnostics' })); + const sourceFeedback = () => solverSourceFeedback(state.problem, worker.worktree); + const recovered = () => { + const recovery = research.recovery; + if (!recovery || recovery.phase === 'recovered') return; + recovery.phase = 'recovered'; recovery.recoveredAt = Date.now(); + emit('worker_recovered', { reason: recovery.reason, cycles: recovery.cycles, waitedMs: recovery.waitedMs }); + save(); + }; + const waitForRecovery = async (resumed = false) => { + const recovery = research.recovery; + if (recovery?.phase !== 'cooling-down' || !dispatchAllowed() || budget().remainingMs <= 0 || + state.turns - Number(reservedTurn) >= input.maxTurns) return; + signal.throwIfAborted(); + const started = Date.now(), delayMs = Math.max(0, recovery.nextRetryAt - started); + if (resumed) emit('worker_recovery_resumed', { reason: recovery.reason, cycle: recovery.cycles, + delayMs, nextRetryAt: recovery.nextRetryAt }); + try { + if (delayMs > 0) await delay(delayMs, undefined, { signal }); signal.throwIfAborted(); - const started = Date.now(), delayMs = Math.max(0, recovery.nextRetryAt - started); - if (resumed) emit('worker_recovery_resumed', { reason: recovery.reason, cycle: recovery.cycles, - delayMs, nextRetryAt: recovery.nextRetryAt }); - try { - if (delayMs > 0) await delay(delayMs, undefined, { signal }); - signal.throwIfAborted(); - recovery.phase = 'retrying'; - cooperation?.workerAvailabilityChanged(); - } finally { - recovery.waitedMs += Math.max(0, Date.now() - started); save(); - } - }; - const contextResearchBases = new WeakMap { - basis: ResearchBasis; publishedBasis?: ResearchBasis; dispatchDigest: string; - }>(); - const context = (feedback?: string, previousCheck?: ProofCheck, previousFailures = research.failures, - assignment?: CooperativeAction) => { - access.assertKnowledgeCurrent?.(); - if (access.libraryCatalog) writeLibraryAccess(state.problem, worker.worktree, access.libraryCatalog); - const scoped = cooperation?.contextState(assignment, worker); - const contextState = { ...view(), ...(scoped ? { cooperation: scoped } : {}) }; - const contextAccess = { - root: input.root, worktree: worker.worktree, taskText: input.taskText, ...access, - ...(modules.M4.tools ? { tools: modules.M4.tools } : {}), - sourceFeedback: feedback, previousCheck, previousFailures, assignment: promptAction(assignment), - maxOptionalContextBytes: research.contextOverflow?.maxOptionalContextBytes, - ...(skillResearch ? { executionLimits: { ...turnTiming, remainingRunMs: () => budget().remainingMs } } : {}), - ...(team ? { teamRole: { id: 'lead', role: 'lead' as const } } : {}), - ...(access.researchSkill ? { researchSkill: access.researchSkill } : {}), - }; - const currentContext = { ...(skillMode && !fullSkillWorkflow && !access.commonResearchSkill - ? buildSkillResearchContext(state.problem, contextState, { ...contextAccess, researchSkill: access.researchSkill! }) - : modules.M4.build(state.problem, contextState, contextAccess)), ...(assignment ? { assignment } : {}) }; - materializeResearchToolHelp(currentContext, worker.worktree); - if (assignment?.kind === 'task' && scoped) { - const basis = captureResearchBasis(assignment.task, { - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, - retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest, - sourceDigest: researchSourceDigest(Object.fromEntries(state.problem.ownedFiles.map(file => [file, - committedSource(worker.worktree, assignment.assignment.seedCommit, `${state.problem.projectRelative}/${file}`)]))), - tasks: scoped.tasks, deliveries: scoped.deliveries, - }); - const previous = assignment.assignment.researchBasis; - const dependencyIds = new Set(basis.dependencies.map(input => input.taskId)); - const dependencySections = new Set(basis.dependencies.map(input => `finding:${input.taskId}`)); - for (const delivery of scoped.deliveries ?? []) if (delivery.kind === 'research' && delivery.taskId && dependencyIds.has(delivery.taskId)) { - dependencySections.add(`delivery:${delivery.id}`); - dependencySections.add(`finding:delivery:${delivery.id}`); - } - contextResearchBases.set(currentContext, manifest => { - const included = new Set(manifest?.included.map(item => item.id)); - const missing = manifest && basis.dependencies.some(input => { - const known = previous?.dependencies.find(item => item.taskId === input.taskId); - if (known && canonicalMathJson(known) === canonicalMathJson(input)) return false; - if (input.findingDigest && !included.has(`finding:${input.taskId}`)) return true; - return scoped.deliveries?.some(delivery => delivery.kind === 'research' && delivery.status !== 'superseded' && - delivery.taskId === input.taskId && delivery.taskDigest === input.taskDigest && - (!included.has(`delivery:${delivery.id}`) || Boolean(delivery.finding) && - !included.has(`finding:delivery:${delivery.id}`) && !included.has(`finding:${input.taskId}`))); - }); - // Selection matters: a previously omitted finding may now fit without changing the basis. - const dispatchDigest = mathDigest(canonicalMathJson({ basis, included: manifest?.included - .filter(item => dependencySections.has(item.id)).map(item => item.id).sort() })); - return { basis, publishedBasis: missing ? previous : basis, dispatchDigest }; - }); - } - return currentContext; - }; - let feedbackCheck: ProofCheck | undefined; - let feedbackFailures = research.failures; - let unstarted: CooperativeAction | undefined; - let reservedTurn = false; - let pendingTurn: Promise | undefined; - let planningCheckpoint = false; - let cooperativeCheckpoint = false; - let proofHandoffCheckpoint = false; - let finalReviewHandoffCheckpoint = false; - let checkpointAtModelBoundary: (() => boolean) | undefined; - let softSliceAtModelBoundary: (() => boolean) | undefined; - let softSliceCheckpoint = false; - let contextSchedulingCheckpoint = false; - let compactionRestart = false; - let explicitCompaction = false, contextUsageVersion = 0, compactedUsageVersion = -1; - let sessionHasHistory = false; - let turnActivity: ((activity: MathAgentActivity) => void) | undefined; - let advisoryTurn: { scope: string; contentDigest?: string; inputDigest?: string } | undefined; - let turnContext: { digest: string; fresh: boolean } | undefined; - // A thread can revisit a responsibility after other tasks. After compaction only its - // most recent responsibility can use a smaller dispatch, with exact inputs re-anchored. - const dispatchedContexts = new Map(); - const markCompaction = (threadId: string, compaction: 'pending' | 'completed') => { - const latest = [...dispatchedContexts].at(-1); - dispatchedContexts.clear(); - if (latest?.[1].threadId === threadId) - dispatchedContexts.set(latest[0], { ...latest[1], compaction }); - }; - let rebuildContext = false; - const usage = new ResearchUsage({ state, research, maxTotalTokens: input.maxTotalTokens, - signal, remainingMs: () => budget().remainingMs, changed: () => { updateUsage(); save(); }, emit }); - const failureDetail = (error: unknown, sessionError?: string, diagnostic?: MathAgentFailureDiagnostic) => - researchFailureDetail(error, sessionError, diagnostic, usage.stopReason); - const locallyStopped = (detail?: string) => usage.stopReason !== undefined && detail === usage.stopReason; - const advisoryContentDigest = () => { - try { - const notes = path.join(worker.worktree, 'RESEARCH.md'); - // Scratch probes are advisory: they can show exploration advanced, never that a proof exists. - return mathDigest(canonicalMathJson([ - ...state.problem.ownedFiles.map(file => [file, mathDigest(fs.readFileSync( - path.join(worker.worktree, state.problem.projectRelative, file)))]), - ['RESEARCH.md', mathDigest(fs.existsSync(notes) ? fs.readFileSync(notes) : '')], - ['scratch', solverScratchDigest(state.problem, worker.worktree) ?? 'none'], - ])); - } catch { return undefined; } - }; - const checkpointNotesDigest = () => readCheckpointNotesDigest(worker.worktree); - const currentCheckpointNotesDigest = () => savedContextCheckpoint(research, worker.worktree); - const researchFindingInstruction = (assignment?: CooperativeAction) => { - if (assignment?.kind !== 'task' || !['research', 'sketch'].includes(assignment.task.kind)) return ''; - return 'If a finding can help a peer or requires a Lead decision, save the argument and exact gap in RESEARCH.md ' + - 'and publish it with research-observe from the worktree root. '; - }; - const proofFindingInstruction = 'If a precise mathematical finding needs a Lead decision, publish it through the current assignment log, ' + - 'or save a JSON math-result code block in RESEARCH.md with summary, conclusion ("refuted" for an actual counterexample), ' + - 'needsDecision:true and the exact argument and assumptions. A saved finding is advisory and does not submit a proof. '; - const contextCheckpointInstruction = (assignment?: CooperativeAction) => { - const file = assignment?.kind === 'task' ? assignmentDeliveryFile(assignment.assignment) : - assignment && leadPlanDeliveryFile(assignment); - const request = research.contextCheckpoint; - const lead = assignment?.kind === 'lead'; - const proof = assignment?.kind === 'task' && !['research', 'sketch'].includes(assignment.task.kind); - return 'Before further searches or experiments, save the exact current argument, ' + - 'attempted methods and negative search scope, useful declaration/file references, and any precise unresolved inference in RESEARCH.md. ' + - (lead ? 'Save or publish any planning decision as the math-plan revision your instructions describe; a Lead publishes no findings. ' - : proof ? proofFindingInstruction - : researchFindingInstruction(assignment)) + - 'Propose independently checkable, strictly smaller typed obligations when possible; do not rename the original hard theorem or ' + - 'assume it in a wrapper. Scratch experiments and an activity report alone are not a durable handoff or an accepted proof. ' + - (proof && file ? 'If the assigned declaration is complete, save its proof and append one complete JSON line to ' + - JSON.stringify(path.join(worker.worktree, file)) + ': ' + JSON.stringify({ kind: 'ready', summary: 'saved proof' }) + - '. Use ready instead of checkpoint, then stop editing and return. Omit commit and targets. ' + - 'The host confirms the writer stopped, freezes the saved sources and checks the assigned declaration independently before integration. ' + - 'Preserve other original goals, including their existing sorry bodies; they do not prevent this declaration check. ' + - 'A local check or a DONE note is not host acceptance. For an unfinished declaration, use the checkpoint acknowledgment below. ' : '') + - (file && request?.requestId ? (proof ? 'Only if the assigned declaration remains unfinished, after saving all notes and source drafts, ' : - 'After saving all notes and source drafts and publishing any findings or planning decisions, ') + - 'run this command to acknowledge the checkpoint, then stop editing and return:\n' + - checkpointCommand(researchToolCommand(input.root, modules.M4.tools), worker.worktree, file, request.requestId) + '\n' + - 'Unchanged but accurate notes and an unfinished argument are allowed; this event yields writing and never claims a proof. ' + - 'A notes save alone is not checkpoint completion.' : ''); - }; - const requestContextCheckpoint = (lastInputTokens: number) => { - const threadId = research.threadId; - if (!threadId || research.contextCheckpoint?.threadId === threadId && research.contextCheckpoint.requestId) return false; - research.contextCheckpoint = { threadId, requestId: crypto.randomUUID(), requestedAt: Date.now(), notesDigest: checkpointNotesDigest() }; - emit('context_checkpoint_requested', { threadId, reason: 'context-threshold', lastInputTokens }); - save(); return true; - }; - const rememberAdvisoryCheckpoint = (checkpoint: NonNullable) => { - const { scope, ...record } = checkpoint; - (research.advisoryCheckpoints ??= {})[scope] = record; - research.advisoryCheckpoint = checkpoint; - }; - // Lazily retain the last responsibility from archives written before scoped history existed. - if (research.advisoryCheckpoint && !research.advisoryCheckpoints?.[research.advisoryCheckpoint.scope]) { - rememberAdvisoryCheckpoint(research.advisoryCheckpoint); save(); + recovery.phase = 'retrying'; + } finally { + recovery.waitedMs += Math.max(0, Date.now() - started); save(); } - const recordAdvisoryOutput = (checkpoint: boolean, completed = false) => { - const previous = research.advisoryCheckpoint; - if (!advisoryTurn || previous?.scope !== advisoryTurn.scope) return; - const contentDigest = advisoryContentDigest(); - const progress = contentDigest !== undefined && contentDigest !== advisoryTurn.contentDigest; - const noProgressStreak = completed || progress ? 0 : checkpoint && !proofHandoffCheckpoint && !finalReviewHandoffCheckpoint - ? Math.min(Number.MAX_SAFE_INTEGER, previous.noProgressStreak + 1) : previous.noProgressStreak; - rememberAdvisoryCheckpoint({ scope: previous.scope, noProgressStreak, - contentDigest: contentDigest ?? previous.contentDigest, inputDigest: advisoryTurn.inputDigest }); - if (checkpoint) emit('cooperative_checkpoint_saved', { noProgressStreak, progress, - protected: false, ...(proofHandoffCheckpoint ? { reason: 'proof-handoff' } : - finalReviewHandoffCheckpoint ? { reason: 'final-review-handoff' } : {}) }); - save(); + }; + const context = (feedback?: string, previousCheck?: ProofCheck, previousFailures = research.failures) => { + access.assertKnowledgeCurrent?.(); + if (access.libraryCatalog) writeLibraryAccess(state.problem, worker.worktree, access.libraryCatalog); + const contextAccess = { + root: input.root, worktree: worker.worktree, taskText: input.taskText, ...access, + ...(modules.M4.tools ? { tools: modules.M4.tools } : {}), + sourceFeedback: feedback, previousCheck, previousFailures, + maxOptionalContextBytes: research.contextOverflow?.maxOptionalContextBytes, + ...(skillMode ? { executionLimits: { ...turnTiming, remainingRunMs: () => budget().remainingMs } } : {}), + ...(team ? { teamRole: { id: 'lead', role: 'lead' as const } } : {}), }; - const modelTurn = async (run: (started: (turnId: string) => void) => Promise, - assignment: CooperativeAction | undefined, onStarted: (turnId: string) => void, - inputBasis?: ResearchBasis): Promise => { - // No await separates this final admission check from invoking the model request. - if (!dispatchAllowed() || budget().remainingMs <= 0 || signal.aborted || - (assignment && !cooperation!.started(worker, assignment))) return undefined; - const kind = assignment?.kind === 'lead' ? 'planning' : assignment && (assignment.kind === 'review' || isStatementAction(assignment)) - ? 'review' : assignment?.kind === 'task' && ['research', 'sketch'].includes(assignment.task.kind) ? 'research' : 'proof'; - for (const record of parallel ? [state, research] : [state]) { - record.dispatchCounts ??= {}; - record.dispatchCounts[kind] = (record.dispatchCounts[kind] ?? 0) + 1; - } - reservedTurn = false; unstarted = undefined; - cooperation?.settleTurn(worker); - planningCheckpoint = false; - cooperativeCheckpoint = false; - proofHandoffCheckpoint = false; - finalReviewHandoffCheckpoint = false; - contextSchedulingCheckpoint = false; - softSliceCheckpoint = false; - advisoryTurn = undefined; - usage.begin(assignment); - team?.beginLeadTurn(); - const activeSession = session!; - const advisoryScope = advisoryCheckpointScope(assignment); - const researchAssignment = assignment?.kind === 'task' && - ['research', 'sketch'].includes(assignment.task.kind) ? assignment : undefined; - const initialNotesDigest = researchAssignment ? checkpointNotesDigest() : undefined; - const seedNotesDigest = researchAssignment && committedResearchNotesDigest(worker.worktree, researchAssignment.assignment.seedCommit); - const retainedDraft = researchAssignment && state.cooperation?.researchDrafts?.[researchAssignment.task.id]; - const retainedNotesDigest = researchAssignment && retainedDraft && - retainedDraft.taskDigest === researchAssignment.assignment.taskDigest && retainedDraft.workerId === worker.id && - retainedDraft.assignmentId === researchAssignment.assignment.assignmentId && - retainedDraft.seedCommit === researchAssignment.assignment.seedCommit && - retainedDraft.canonicalCommit === researchAssignment.assignment.canonicalCommit - ? researchHandoffNotesDigest(committedResearchNotesDigest(worker.worktree, retainedDraft.commit), seedNotesDigest, - retainedDraft.handoffNotesDigest) : undefined; - const researchHandoffNotes = () => { - const notesDigest = checkpointNotesDigest(); - if (!notesDigest) return undefined; - // A prior task's seed notes are not this investigation's handoff. A matching saved draft, - // a fresh notes write or the existing digest-bound acknowledgment establishes attribution. - return notesDigest === retainedNotesDigest || notesDigest !== initialNotesDigest && notesDigest !== seedNotesDigest || - currentCheckpointNotesDigest() === notesDigest ? notesDigest : undefined; - }; - let finished = false, armed = false, checkpointRequested = false, checkpointClosing = false, readyRequested = false; - let stopRequested = false; - let noticeTimer: ReturnType | undefined; - let checkpointTimer: ReturnType | undefined; - let interruptTimer: ReturnType | undefined; - let proofHandoffTimer: ReturnType | undefined; - let contextTimer: ReturnType | undefined; - let compactionTimer: ReturnType | undefined; - let compactionStartedAt: number | undefined; - let sliceStartedAt: number | undefined; - let activeSliceMs = 0, noticeSent = false; - let scheduleSlice: (() => void) | undefined; - let clockArmed = false; - let firstActivityTimer: ReturnType | undefined; - let lastModelOutputAt: number | undefined, toolsRunning = 0, requestWaited = false; - let requestWaitTimer: ReturnType | undefined; - let cutAtRequestBoundary: (() => void) | undefined; - let noticeDelivery: 'unavailable' | 'pending' | 'delivered' | 'failed' = 'unavailable'; - let planningCommands = 0; - let requestedProof: (NonNullable> & { turnId: string }) | undefined; - let requestedFinalReview: string | undefined; - let proofNoticeDelivered = false, handoffAtBoundary = false; - let afterNotice: ((delivered: boolean) => void) | undefined; - const live = () => !finished && !signal.aborted && session === activeSession; - const current = () => live() && Boolean(assignment && cooperation?.current(assignment)); - const noticeFailureReason = (error: unknown) => { - // interrupt() deliberately cancels queued notices, including context-save reminders. - if ((checkpointRequested || readyRequested || checkpointClosing || stopRequested) && - error instanceof Error && error.message === 'math_codex_notification_turn_settled') return; - return (error instanceof Error ? error.message : - typeof error === 'string' ? error : 'math_codex_notification_failed').slice(0, 1000); - }; - const closeStalledTurn = () => { - // A superseded assignment still owns a live writer until it actually stops. - if (!live() || checkpointClosing) return; - checkpointClosing = true; - emit(readyRequested ? 'proof_ready_session_closed' : 'cooperative_checkpoint_session_closed', - { reason: 'interrupt-not-settled' }); - // close() retains research.threadId; the next session resumes the saved thread. - void close().catch(() => {}); - }; - const interruptForCheckpoint = (event: string, details: Record, accepts = current) => { - if (!accepts() || checkpointRequested || readyRequested) return false; - checkpointRequested = true; - emit(event, details); - interruptTimer = setTimeout(closeStalledTurn, advisoryInterruptGraceMs); - interruptTimer.unref(); - void Promise.resolve().then(async () => { - if (accepts()) await activeSession.interrupt(); - }).catch(closeStalledTurn); - return true; - }; - let milestoneTurnId: string | undefined; - const milestoneOwner = () => live() && (!assignment || current()) && !stopRequested; - const milestoneCurrent = () => milestoneOwner() && !checkpointRequested && !readyRequested && !softSliceCheckpoint; - const milestone = (kind === 'proof' || kind === 'research') && - !(assignment?.kind === 'task' && (isFeasibilityReview(assignment.task) || isFinalCandidateReview(assignment.task))) - ? createSoftSlice(milestoneSettings, { - current: milestoneCurrent, - notice: (reason, completedCompactions) => { - emit(reason === 'time' ? 'soft_slice_milestone_requested' : 'compaction_circuit_breaker_triggered', - { turnId: milestoneTurnId, completedCompactions, graceMs: milestoneSettings.graceMs }); - const submission = team - ? 'Use theoremos_team route_summary to review the team. Collect useful checked results and coordinate active teammates. ' + - 'If slots are free, delegate focused independent obligations using the team tools. ' - : assignment?.kind === 'task' - ? 'Publish standalone helpers as a helpers event in the assignment delivery log. ' - : skillMode ? 'Write .scratch/declaration-submission.json only if you have at least one locally compiled standalone helper to nominate. Never write an empty declarations array. ' - : 'Save standalone helpers in the owned Lean files for host checking. '; - void activeSession.notify?.(submission + - 'Write fewer than 20 lines in worktree-root RESEARCH.md covering what is established, the exact obstruction, ' + - 'and the next route or smaller obligation. Save your files and return after the current request and tools settle.', - activeSession.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }) - .catch(error => { - const reason = noticeFailureReason(error); - if (reason !== undefined && milestoneCurrent()) emit('soft_slice_notice_failed', { reason }); - }); - }, - interrupt: () => { softSliceCheckpoint = interruptForCheckpoint('soft_slice_checkpoint_requested', - { turnId: milestoneTurnId, boundary: 'wait-limit' }, milestoneOwner); }, - }) : undefined; - if (milestone) softSliceAtModelBoundary = () => { - if (toolsRunning || !milestone.useBoundary()) return false; - softSliceCheckpoint = true; - emit('soft_slice_checkpoint_requested', { turnId: milestoneTurnId, boundary: 'request' }); - return true; - }; - const watchCompaction = () => { - if (!current() || compactionStartedAt === undefined || compactionTimer) return; - compactionTimer = setTimeout(() => { - if (!current() || compactionStartedAt === undefined) return; - if (interruptForCheckpoint('context_compaction_recovery_requested', - { threadId: research.threadId, maintenanceMs: Date.now() - compactionStartedAt })) { - compactionRestart = true; - contextSchedulingCheckpoint = true; - } - }, Math.max(0, compactionRecoveryMs - (Date.now() - compactionStartedAt))); - compactionTimer.unref(); - }; - turnActivity = activity => { - if (assignment?.kind === 'lead' && current() && activity.event === 'item_started' && - activity.itemType === 'commandExecution' && ++planningCommands === leadMaxPlanningCommands + 1) { - emit('lead_planning_command_guardrail_triggered', { - commandCount: planningCommands, limit: leadMaxPlanningCommands, planVersion: assignment.planVersion, - }); - void activeSession.notify?.( - 'Stop running exploratory commands in this planning turn. Use the evidence you have to decide and publish the plan now. ' + - 'Delegate further computations and route probes to workers, and assign the smallest shared foundation lemmas before their consumers.', - activeSession.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }, - ).catch(() => {}); - } - // Echoed input and compaction are not model work. Start the advisory clock at the first - // model output or tool activity, preserving the independent fallback for a silent turn. - if (!clockArmed && activity.itemType !== 'userMessage' && activity.itemType !== 'contextCompaction') { - clockArmed = true; - clearTimeout(firstActivityTimer); firstActivityTimer = undefined; - if (advisoryScope) emit('cooperative_checkpoint_clock_started', { itemType: activity.itemType }); - scheduleSlice?.(); - } - if (activity.event === 'reasoning' || activity.event === 'message' || modelOutputItems.has(activity.itemType ?? '')) - lastModelOutputAt = Date.now(); - else if (activity.itemType && !nonToolItems.has(activity.itemType)) { - if (activity.event === 'item_started') toolsRunning++; - else if (activity.event === 'item_completed') { - toolsRunning = Math.max(0, toolsRunning - 1); - // The request that was streaming has returned and its tool results are recorded: cut here. - if (!toolsRunning) cutAtRequestBoundary?.(); - if (!toolsRunning && activeSession.usageSource !== 'upstream-requests' && milestone?.useBoundary()) - softSliceCheckpoint = interruptForCheckpoint('soft_slice_checkpoint_requested', - { turnId: milestoneTurnId, boundary: 'tool' }, milestoneOwner); - } - } - // Native context maintenance applies to Skill sessions without cooperative assignments too. - if (live() && activity.itemType === 'contextCompaction' && - (activity.event === 'item_started' || activity.event === 'item_completed')) - markCompaction(activeSession.threadId, activity.event === 'item_started' ? 'pending' : 'completed'); - if (activity.itemType === 'contextCompaction' && activity.event === 'item_completed') milestone?.compacted(); - if (current() && activity.itemType === 'contextCompaction') { - if (activity.event === 'item_started' && compactionStartedAt === undefined) { - compactionStartedAt = Date.now(); - if (sliceStartedAt !== undefined) activeSliceMs += Date.now() - sliceStartedAt; - sliceStartedAt = undefined; - clearTimeout(noticeTimer); clearTimeout(checkpointTimer); clearTimeout(firstActivityTimer); - firstActivityTimer = undefined; - emit('context_compaction_started', { threadId: research.threadId }); - watchCompaction(); - } else if (activity.event === 'item_completed' && compactionStartedAt !== undefined) { - const maintenanceMs = Date.now() - compactionStartedAt; - compactionStartedAt = undefined; - clearTimeout(compactionTimer); compactionTimer = undefined; - emit('context_compaction_completed', { threadId: research.threadId, maintenanceMs }); - scheduleSlice?.(); - } - } - const lastInputTokens = Math.max(activeSession.lastInputTokens ?? 0, research.lastInputTokens ?? 0); - if (current() && assignment && !isStatementAction(assignment) && lastInputTokens >= 90_000 && requestContextCheckpoint(lastInputTokens)) - void activeSession.notify?.(contextCheckpointInstruction(assignment)).catch(error => { - const reason = noticeFailureReason(error); - if (reason !== undefined && current()) emit('context_checkpoint_notice_failed', { reason }); - }); - }; - if (assignment) cooperation!.activate(worker, assignment, - async () => { - if (!live()) return; - stopRequested = true; - interruptTimer ??= setTimeout(closeStalledTurn, advisoryInterruptGraceMs); - interruptTimer.unref(); - try { await activeSession.interrupt(); } catch { closeStalledTurn(); } - }, - async (message, options) => { - // A queued human message needs a real active turn; optional/no-op notifications cannot earn a delivery receipt. - if (options?.requireTurn && (!live() || !armed || isStatementAction(assignment) || !activeSession.notify)) - throw new Error('math_guidance_recipient_not_running'); - if (!isStatementAction(assignment)) try { - // Guidance polling must not wait for a long provider request or claim an enqueue as delivery. - await activeSession.notify?.(message, options?.mode === 'advisory' && !options.requireTurn && - activeSession.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: !options?.requireTurn }); - } catch (error) { - if (options?.requireTurn && error instanceof Error && - /^math_codex_notification_(?:request_active|turn_settled)$/u.test(error.message)) - throw new Error('math_guidance_recipient_not_running'); - throw error; - } - }, - async () => { - if (!current() || readyRequested) return; - readyRequested = true; - emit('proof_ready_checkpoint_requested'); - // Ready explicitly hands back writing; this bounds cleanup, not proof work. - interruptTimer ??= setTimeout(closeStalledTurn, advisoryInterruptGraceMs); - interruptTimer.unref(); - try { await activeSession.interrupt(); } catch { closeStalledTurn(); } - }, - researchAssignment && (commit => { - if (requestedFinalReview || !current() || checkpointRequested || readyRequested || stopRequested) return; - requestedFinalReview = commit; - scheduleSlice?.(); - })); - const started = (turnId: string) => { - usage.turnStarted(turnId); - onStarted(turnId); - milestoneTurnId = turnId; - milestone?.start(); - if (armed || !current()) return; - armed = true; - if (assignment && !isStatementAction(assignment)) { - contextTimer = setInterval(() => { - if (!current()) return; - if (research.contextCheckpoint?.threadId !== research.threadId) return; - const notesDigest = currentCheckpointNotesDigest(); - if (!notesDigest) return; - // Only the final, host-consumed control event yields writing; notes may precede publication. - contextSchedulingCheckpoint = interruptForCheckpoint('context_checkpoint_interrupted', - { turnId, threadId: research.threadId, notesDigest }) || contextSchedulingCheckpoint; - }, advisoryProgressPollMs); - contextTimer.unref(); - } - if (!advisoryScope) { - if (research.advisoryCheckpoint) { research.advisoryCheckpoint = undefined; save(); } - watchCompaction(); - return; - } - const contentDigest = advisoryContentDigest(); - const taskCheckpoint = assignment?.kind === 'task' ? - state.cooperation?.researchCheckpoints?.[assignment.task.id] : undefined; - // A worker has one current slot, but can alternate between several investigations. - // Restore the task's saved backoff instead of restarting its two-minute slice on every switch. - const previous = research.advisoryCheckpoint?.scope === advisoryScope ? research.advisoryCheckpoint : - assignment?.kind === 'task' && taskCheckpoint?.taskDigest === assignment.assignment.taskDigest - ? taskCheckpoint.advisoryCheckpoint ?? (research.advisoryCheckpoints?.[advisoryScope] && { scope: advisoryScope, ...research.advisoryCheckpoints[advisoryScope] }) - : research.advisoryCheckpoints?.[advisoryScope] && { scope: advisoryScope, ...research.advisoryCheckpoints[advisoryScope] }; - const inputDigest = assignment?.kind === 'task' && ['research', 'sketch'].includes(assignment.task.kind) && inputBasis - ? mathDigest(canonicalMathJson(inputBasis)) : undefined; - const noticeOnly = advisoryCheckpointNoticeOnly(assignment); - const noProgressStreak = noticeOnly ? 0 : previous?.scope === advisoryScope && - (previous.inputDigest === undefined || previous.inputDigest === inputDigest) && - (contentDigest === undefined || contentDigest === previous.contentDigest) ? previous.noProgressStreak : 0; - rememberAdvisoryCheckpoint({ scope: advisoryScope, contentDigest, inputDigest, noProgressStreak }); - advisoryTurn = { scope: advisoryScope, contentDigest, inputDigest }; - save(); - // The initial plan gets one long slice and a revision one fixed decision slice; advisory research backs - // off after unchanged checkpoints, so a worker that keeps returning the same response gets more time. - const initialPlan = assignment?.kind === 'lead' && Boolean(assignment.initialPlanNonce); - const revision = assignment?.kind === 'lead' && !initialPlan; - const backoff = !noticeOnly && !initialPlan && !revision; - const checkpointAfterMs = noticeOnly ? advisoryGoalNoticeMs : initialPlan ? advisoryInitialPlanMs : - revision ? advisoryRevisionMs : - advisoryCheckpointMs * (backoff ? 2 ** Math.min(noProgressStreak, advisoryMaxBackoff) : 1); - const noticeAfterMs = initialPlan ? advisoryInitialPlanNoticeMs : revision ? advisoryRevisionNoticeMs : - checkpointAfterMs * advisoryCheckpointNoticeMs / advisoryCheckpointMs; - emit('cooperative_checkpoint_scheduled', { turnId, checkpointAfterMs, noticeAfterMs, noProgressStreak, - protected: false, ...(noticeOnly ? { noticeOnly: true } : {}), - backoffCapped: Boolean(backoff) && noProgressStreak >= advisoryMaxBackoff }); - if (noProgressStreak && backoff) emit('cooperative_checkpoint_deferred', { turnId, checkpointAfterMs, - noProgressStreak, protected: false, reason: 'no-durable-progress' }); - let noticeSequence = 0; - const sendNotice = () => { - if (!current() || noticeSent || assignment?.kind === 'lead' && cooperation?.hasLeadPublication(assignment)) return; - noticeSent = true; - const sequence = ++noticeSequence; - noticeDelivery = activeSession.notify ? 'pending' : 'unavailable'; - emit('cooperative_checkpoint_requested', { turnId, checkpointAfterMs, noProgressStreak, protected: false }); - void Promise.resolve().then(() => { - // An accepted live plan already fulfilled this decision, including while human approval - // is pending. Recheck at delivery in case publication raced the queued notification. - if (!current() || assignment?.kind === 'lead' && cooperation?.hasLeadPublication(assignment)) return; - // A goal turn is never yielded, so its reminder must not promise a checkpoint that will - // not come: it asks for the durable handoff and leaves the writing turn running. - return activeSession.notify?.(assignment?.kind === 'task' && isFeasibilityReview(assignment.task) - ? 'Save this independent review\'s intermediate work in root RESEARCH.md now: the exact inspected inputs, ' + - 'methods already tried, exact failed search scope, remaining uncertainties, and complete useful scratch-probe ' + - 'code with reproduction commands and observed results. A scratch path alone is not a recoverable probe; ' + - 'embed the useful contents in RESEARCH.md. These notes are advisory, not a completed review verdict or proof acceptance. ' + - 'This turn keeps running without a timed interruption; save incrementally and continue the independent review.' - : noticeOnly - ? 'Save the current mathematical argument, the exact unresolved step and useful references in RESEARCH.md now. ' + - 'This turn keeps running: no checkpoint will interrupt or end it, so save notes incrementally and continue proving.' - : initialPlan - ? 'If the first plan is still unpublished, publish it now with plan-apply --publish from the Lead tool help. ' + - 'Start with a direct goal task for each original target and separate research tasks for specific open questions. ' + - 'Save the route and uncertainties in RESEARCH.md and return once the host has the plan.' - : revision - ? 'Decide now, before further searches or experiments. ' + cooperation!.leadCheckpointInstruction(assignment!) + - 'Delegate any open search as a research task instead of ' + - 'running it in this turn. This turn yields a scheduling checkpoint at ' + Math.round(checkpointAfterMs / 60_000) + - ' minutes; the same thread and saved work remain available.' - : 'Save the current mathematical argument, exact unresolved step and useful references in RESEARCH.md now. ' + - (assignment?.kind === 'task' && hasTaskConnectionCheck(assignment.task, assignment.assignment) - ? proofFindingInstruction : researchFindingInstruction(assignment)) + - 'This advisory turn will yield a scheduling checkpoint shortly, including when no new notes are saved. ' + - 'The same thread and saved work will remain available for continuation; this does not end the solving budget.'); - }).then(() => { - if (!current() || sequence !== noticeSequence) return; - const delivered = noticeDelivery === 'pending'; - noticeDelivery = delivered ? 'delivered' : 'unavailable'; - afterNotice?.(delivered); - }, error => { - if (sequence !== noticeSequence) return; - const reason = noticeFailureReason(error); - noticeDelivery = reason === undefined ? 'unavailable' : 'failed'; - if (reason === undefined || !current()) return; - emit('cooperative_checkpoint_notice_failed', { reason }); - afterNotice?.(false); - }); - }; - const checkpoint = () => { - if (compactionStartedAt !== undefined) return; - if (researchAssignment && !researchHandoffNotes() && current() && !checkpointRequested && !readyRequested) - emit('research_checkpoint_missing_notes', { taskId: researchAssignment.task.id, - assignmentId: researchAssignment.assignment.assignmentId }); - if (interruptForCheckpoint('cooperative_checkpoint_interrupted', - { turnId, checkpointAfterMs, noProgressStreak, protected: false })) { - finalReviewHandoffCheckpoint = requestedFinalReview !== undefined; - } - }; - // Interrupting a streaming request discards its unfinished reasoning and tool call, and research whose every - // cut lands mid-request saves nothing and is parked as unchanged. A slice cut (initial plan, revision or - // research) lets that one request return (its tool results recorded) first, bounded by advisoryRequestWaitMs. - let waitStartedAt: number; - let handoffRequested = false; - const cut = (boundary: 'request-returned' | 'wait-limit' | 'notice-failed') => { - if (!current() || compactionStartedAt !== undefined || checkpointRequested || readyRequested) return; - const leadHandoff = boundary === 'request-returned' && assignment?.kind === 'lead' && noticeDelivery === 'delivered' - ? cooperation?.leadCheckpointHandoff(assignment) : undefined; - if (leadHandoff && assignment?.kind === 'lead') { - // Reading the current graph is not a decision. Give this dispatch the remainder of - // the same wait window to save a complete answer before freezing its workspace. - if (!handoffRequested) { - handoffRequested = true; - emit('lead_handoff_requested', { turnId, - remainingMs: Math.max(0, advisoryRequestWaitMs - (Date.now() - waitStartedAt)) }); - void Promise.resolve().then(() => { - if (!current() || checkpointRequested || readyRequested) return; - const handoff = cooperation!.leadCheckpointHandoff(assignment); - if (!handoff) return; - const correction = handoff.reason ? 'Correct the saved math-plan draft. ' + handoff.reason + '\n' : ''; - return activeSession.notify?.(correction + cooperation!.leadCheckpointInstruction(assignment) + - 'Save the complete decision now, before another search. The host is waiting only until the existing ' + - 'checkpoint deadline; reading the inherited plan or saving prose does not answer the required decisions.'); - }).catch(error => { - const reason = noticeFailureReason(error); - if (reason === undefined || !current()) return; - emit('cooperative_checkpoint_notice_failed', { reason }); - cut('notice-failed'); - }); - } - return; - } - if (boundary === 'request-returned' && researchAssignment && noticeDelivery === 'delivered' && - !researchHandoffNotes()) { - // A search result may be the first tool after a long request. Let the model write - // its argument before yielding, using this turn's original fixed wait deadline. - if (!handoffRequested) { - handoffRequested = true; - emit('research_handoff_requested', { taskId: researchAssignment.task.id, - assignmentId: researchAssignment.assignment.assignmentId, - remainingMs: Math.max(0, advisoryRequestWaitMs - (Date.now() - waitStartedAt)) }); - void Promise.resolve().then(() => { - if (!current() || checkpointRequested || readyRequested) return; - return activeSession.notify?.('Save a concise handoff for this assignment in worktree-root RESEARCH.md now, ' + - 'before another search. Record the actual argument or attempted method, exact search scope and results, ' + - 'useful references and the precise unresolved inference. If nothing is established, state that accurately ' + - 'and identify the remaining question; do not invent a finding or proof. Replace inherited notes with this ' + - 'assignment\'s account and save it even when unfinished. The host is waiting only until the existing ' + - 'checkpoint deadline; after saving the notes, stop editing and return.'); - }).catch(error => { - const reason = noticeFailureReason(error); - if (reason === undefined || !current()) return; - emit('cooperative_checkpoint_notice_failed', { reason }); - cut('notice-failed'); - }); - } - return; - } - cutAtRequestBoundary = undefined; afterNotice = undefined; clearTimeout(requestWaitTimer); - emit('cooperative_checkpoint_request_settled', { turnId, boundary, waitedMs: Date.now() - waitStartedAt }); - checkpoint(); - }; - const startWait = (noticePending = false) => { - requestWaited = true; - waitStartedAt = Date.now(); - requestWaitTimer = setTimeout(() => cut('wait-limit'), advisoryRequestWaitMs); - requestWaitTimer.unref(); - emit('cooperative_checkpoint_awaiting_request', { turnId, checkpointAfterMs, - maxWaitMs: advisoryRequestWaitMs, ...(noticePending ? { noticePending: true } : {}), - ...(lastModelOutputAt !== undefined ? { outputAgeMs: Date.now() - lastModelOutputAt } : {}) }); - }; - const awaitRequest = (handoff = false) => { - if (!current() || compactionStartedAt !== undefined || checkpointRequested || readyRequested) return; - // One fixed wait window per turn, also covering a queued save notice and its response. - // Notes may become visible before their writing tool finishes; wait for its result before freezing them. - const waitForHandoffTool = noticeDelivery === 'delivered' && (researchAssignment || assignment?.kind === 'lead'); - const pendingLeadHandoff = handoff && noticeDelivery === 'delivered' && assignment?.kind === 'lead' && - cooperation?.leadCheckpointHandoff(assignment); - const modelOutputStale = lastModelOutputAt === undefined || Date.now() - lastModelOutputAt > advisoryModelStreamingMs; - if ((requestWaited && !handoff) || (toolsRunning ? !waitForHandoffTool : modelOutputStale && !pendingLeadHandoff)) { - clearTimeout(requestWaitTimer); checkpoint(); return; - } - if (!requestWaited) startWait(); - cutAtRequestBoundary = () => cut('request-returned'); - }; - const endSlice = () => { - if (compactionStartedAt !== undefined) return; - if (requestWaited && Date.now() - waitStartedAt >= advisoryRequestWaitMs) { cut('wait-limit'); return; } - if (cutAtRequestBoundary || afterNotice) return; - if (noticeDelivery === 'pending') { - // The provider can take longer than the slice. Let the queued save instruction reach - // the model before cutting its first tool result, then give it the ordinary save gap. - // The same fixed request-wait deadline bounds both notification and handoff; a missing - // or failed notification can never extend the turn indefinitely. - if (!requestWaited) startWait(true); - afterNotice = delivered => { - afterNotice = undefined; - if (!current() || checkpointRequested || readyRequested) return; - if (!delivered) { cut('notice-failed'); return; } - checkpointTimer = setTimeout(() => awaitRequest(true), advisoryCheckpointMs - advisoryCheckpointNoticeMs); - checkpointTimer.unref(); - }; - return; - } - // Compaction can re-enter this slice after the queued save notice was delivered. - // Resume the same Lead handoff; its existing wait is not a second checkpoint. - awaitRequest(requestWaited && noticeDelivery === 'delivered' && assignment?.kind === 'lead'); - }; - scheduleSlice = () => { - if (!current() || compactionStartedAt !== undefined || checkpointRequested || readyRequested) return; - if (requestedFinalReview) { - clearTimeout(noticeTimer); clearTimeout(checkpointTimer); clearTimeout(firstActivityTimer); - sendNotice(); - endSlice(); - return; - } - // The advisory clock measures mathematical work, not provider latency. Until the model - // produces its first item the turn is held open, bounded only by the silent-turn cap. - if (!clockArmed) { - firstActivityTimer ??= setTimeout(() => { - firstActivityTimer = undefined; - if (!current() || clockArmed) return; - clockArmed = true; - emit('cooperative_checkpoint_clock_started', { itemType: 'none', silentMs: advisoryFirstActivityMs }); - scheduleSlice?.(); - }, advisoryFirstActivityMs); - firstActivityTimer.unref(); - return; - } - sliceStartedAt = Date.now(); - if (!noticeSent) { - noticeTimer = setTimeout(sendNotice, Math.max(0, noticeAfterMs - activeSliceMs)); - noticeTimer.unref(); - } - // A goal writer keeps its turn; only the reminder above is scheduled for it. - if (noticeOnly) return; - checkpointTimer = setTimeout(endSlice, Math.max(0, checkpointAfterMs - activeSliceMs)); - checkpointTimer.unref(); - }; - scheduleSlice(); watchCompaction(); - if (researchAssignment && activeSession.advisoryNotifications === 'native-history' && activeSession.notify) { - const handoffAfter = Date.now() + (input.minAdvisorySliceMs ?? MIN_ADVISORY_SLICE_MS); - const proofTarget = () => { - if (Date.now() < handoffAfter || compactionStartedAt !== undefined || !current() || - checkpointRequested || readyRequested || stopRequested) return; - return cooperation?.proofHandoffTarget(worker, researchAssignment); - }; - const sameTarget = () => { - const target = proofTarget(); - return Boolean(target && requestedProof?.taskId === target.taskId && requestedProof?.taskDigest === target.taskDigest); - }; - if (activeSession.usageSource === 'upstream-requests') { - checkpointAtModelBoundary = () => { - if (!proofNoticeDelivered || toolsRunning || !sameTarget() || !researchHandoffNotes()) return false; - handoffAtBoundary = true; - return true; - }; - } - proofHandoffTimer = setInterval(() => { - if (requestedProof || !clockArmed) return; - const target = proofTarget(); - if (!target) return; - requestedProof = { ...target, turnId }; - // Native history is consumed after the current response and its tools. Steering here - // would cancel the response on direct-provider sessions with no host request relay. - void activeSession.notify!( - 'A typed proof task is now ready. Finish the current model response and tool work, then save ' + - 'worktree-root RESEARCH.md. If the investigation is complete, write the normal JSON math-result. ' + - 'If unfinished, save a Markdown draft with the exact inputs, current argument, reproduction commands, ' + - 'results and next unresolved step. After saving, return so the host can recheck the proposed switch.', - { mode: 'advisory' }).then(() => { - if (current()) { - proofNoticeDelivered = true; - emit('proof_handoff_notice_delivered', { turnId, taskId: researchAssignment.task.id, - successorTaskId: target.taskId, successorTaskDigest: target.taskDigest }); - } - }, error => { - if (!current()) return; - requestedProof = undefined; - const reason = noticeFailureReason(error); - if (reason !== undefined) emit('proof_handoff_notice_failed', { turnId, reason }); - }); - }, advisoryProgressPollMs); - proofHandoffTimer.unref(); - } - }; - let completed = false; - try { - const result = await run(started); - const detail = failureDetail(undefined, activeSession.lastError, activeSession.lastFailureDiagnostic); - if (usage.stopReason && detail !== usage.stopReason) throw new Error(detail); - planningCheckpoint = usage.stopReason === 'math_initial_planning_limit'; - const resultStatus = typeof result === 'string' ? result : result && typeof result === 'object' && 'status' in result ? result.status : undefined; - if (milestone?.requested && resultStatus === 'completed') softSliceCheckpoint = true; - const completedAfterNotice = proofNoticeDelivered && resultStatus === 'completed'; - let submittedResult = false; - if (completedAfterNotice && !handoffAtBoundary && researchHandoffNotes()) { - // Only an explicit result distinguishes a normal return from saving prose for the handoff. - // The regular delivery path still validates the result and its frozen assignment. - try { - const finding = readMathResponse(worker.worktree, 'math-result'); - submittedResult = typeof finding.summary === 'string' && Boolean(finding.summary.trim()); - } catch { /* Missing or unfinished control responses remain handoff drafts. */ } - } - proofHandoffCheckpoint = handoffAtBoundary || (completedAfterNotice && !submittedResult); - cooperativeCheckpoint = proofHandoffCheckpoint || checkpointRequested && (resultStatus === 'interrupted' || resultStatus === 'checkpoint' || - checkpointClosing && resultStatus === 'failed' && researchFailureReason(detail) === 'math_codex_transport_closed'); - completed = resultStatus === 'completed'; - // An acknowledged scheduler interruption also proves the worker can run again. - if (completed || armed && cooperativeCheckpoint && (resultStatus === 'interrupted' || resultStatus === 'checkpoint')) recovered(); - return result; - } - catch (error) { - proofHandoffCheckpoint = handoffAtBoundary; - planningCheckpoint = usage.stopReason === 'math_initial_planning_limit' && - failureDetail(error, activeSession.lastError, activeSession.lastFailureDiagnostic) === usage.stopReason; - cooperativeCheckpoint = proofHandoffCheckpoint || checkpointRequested && checkpointClosing && - researchFailureReason(failureDetail(error, activeSession.lastError, activeSession.lastFailureDiagnostic)) === 'math_codex_transport_closed'; - throw error; - } - finally { - finished = true; - milestone?.stop(); - softSliceAtModelBoundary = undefined; - clearTimeout(noticeTimer); clearTimeout(checkpointTimer); clearTimeout(interruptTimer); clearTimeout(requestWaitTimer); - cutAtRequestBoundary = undefined; - afterNotice = undefined; - clearTimeout(compactionTimer); clearTimeout(firstActivityTimer); turnActivity = undefined; - clearInterval(proofHandoffTimer); clearInterval(contextTimer); - checkpointAtModelBoundary = undefined; - // A transport failure may settle run() before process-group teardown finishes. - // Do not freeze sources or reopen this thread until the writer is fully closed. - try { - if (proofHandoffCheckpoint && researchAssignment && requestedProof) { - const target = cooperation!.proofHandoffTarget(worker, researchAssignment); - const valid = target?.taskId === requestedProof.taskId && target?.taskDigest === requestedProof.taskDigest; - // A boundary cut already displaced the turn even if the target changed while it settled. - if (valid || handoffAtBoundary) cooperation!.recordProofHandoff(worker, researchAssignment.task.id, requestedProof.taskId); - emit(valid ? requestedProof.capacity ? 'capacity_exploration_yielded' : 'advisory_yielded_for_typed_work' - : 'proof_handoff_target_changed', { turnId: requestedProof.turnId, taskId: researchAssignment.task.id, - successorTaskId: requestedProof.taskId, successorTaskDigest: requestedProof.taskDigest, - reason: valid ? 'typed-work-ready' : 'successor-no-longer-dispatchable' }); - } - if (checkpointClosing) await close(); - if (completed && !proofHandoffCheckpoint) recordAdvisoryOutput(false, true); - } finally { usage.finish(completed); } - } + const currentContext = skillMode && !fullSkillWorkflow && !access.commonResearchSkill + ? buildSkillResearchContext(state.problem, state, { ...contextAccess, researchSkill: access.researchSkill! }) + : modules.M4.build(state.problem, state, contextAccess); + materializeResearchToolHelp(currentContext, worker.worktree); + return { ...currentContext }; + }; + let feedbackCheck: ProofCheck | undefined; + let feedbackFailures = research.failures; + let reservedTurn = false; + let softSliceAtModelBoundary: (() => boolean) | undefined; + let softSliceCheckpoint = false; + let contextSchedulingCheckpoint = false; + let explicitCompaction = false, contextUsageVersion = 0, compactedUsageVersion = -1; + let sessionHasHistory = false; + let turnActivity: ((activity: MathAgentActivity) => void) | undefined; + let turnContext: { digest: string; fresh: boolean } | undefined; + let dispatched: { responsibility: string; threadId: string; compaction?: 'pending' | 'completed' } | undefined; + const markCompaction = (threadId: string, compaction: 'pending' | 'completed') => { + if (dispatched?.threadId === threadId) dispatched = { ...dispatched, compaction }; + else dispatched = undefined; + }; + let rebuildContext = false; + const usage = new ResearchUsage({ state, research, + signal, remainingMs: () => budget().remainingMs, changed: () => { updateUsage(); save(); }, emit }); + const failureDetail = (error: unknown, sessionError?: string, diagnostic?: MathAgentFailureDiagnostic) => + researchFailureDetail(error, sessionError, diagnostic, usage.stopReason); + const locallyStopped = (detail?: string) => usage.stopReason !== undefined && detail === usage.stopReason; + const checkpointNotesDigest = () => readCheckpointNotesDigest(worker.worktree); + const currentCheckpointNotesDigest = () => savedContextCheckpoint(research, worker.worktree); + const contextCheckpointInstruction = 'Before further searches or experiments, save the exact current argument, ' + + 'attempted methods, useful declaration and file references, and the unresolved inference in RESEARCH.md.'; + const requestContextCheckpoint = (lastInputTokens: number) => { + const threadId = research.threadId; + if (!threadId || research.contextCheckpoint?.threadId === threadId && research.contextCheckpoint.requestId) return false; + research.contextCheckpoint = { threadId, requestId: crypto.randomUUID(), requestedAt: Date.now(), notesDigest: checkpointNotesDigest() }; + emit('context_checkpoint_requested', { threadId, reason: 'context-threshold', lastInputTokens }); + save(); return true; + }; + const modelTurn = async (run: (started: (turnId: string) => void) => Promise, + onStarted: (turnId: string) => void): Promise => { + if (!dispatchAllowed() || budget().remainingMs <= 0 || signal.aborted) return undefined; + const kind = team && !team.mayStartProofWork ? 'planning' : 'proof'; + state.dispatchCounts ??= {}; + state.dispatchCounts[kind] = (state.dispatchCounts[kind] ?? 0) + 1; + reservedTurn = false; + contextSchedulingCheckpoint = false; + softSliceCheckpoint = false; + usage.begin(); + team?.beginLeadTurn(); + const activeSession = session!; + let finished = false; + let toolsRunning = 0; + let interruptTimer: ReturnType | undefined; + let checkpointClosing = false; + const live = () => !finished && !signal.aborted && session === activeSession; + const closeStalledTurn = () => { + if (!live() || checkpointClosing) return; + checkpointClosing = true; + void close().catch(() => {}); }; - const waitForTurn = () => budget().remainingMs > 0 ? cooperation?.waitForTurn(input.maxTurns) : undefined; - const reserveTurn = () => { - if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0 || signal.aborted) return false; - // Reserve synchronously before opening a session so peers cannot overspend the shared budget. - reservedTurn = true; - state.turns++; - if (parallel) research.turns++; - cooperation?.reserveTurn(worker); - setWorkerResearchPhase(state, research, 'running'); save(); + const interruptForCheckpoint = (event: string, details: Record) => { + if (!live() || interruptTimer) return false; + emit(event, details); + interruptTimer = setTimeout(closeStalledTurn, interruptGraceMs); + interruptTimer.unref(); + void activeSession.interrupt().catch(closeStalledTurn); return true; }; - /** Return a reserved but unstarted turn to the shared budget; false when none was reserved. */ - const unreserveTurn = () => { - if (!reservedTurn) return false; - state.turns--; if (parallel) research.turns--; - reservedTurn = false; cooperation?.settleTurn(worker); + let milestoneTurnId: string | undefined; + const milestoneCurrent = () => live() && !interruptTimer && !softSliceCheckpoint; + const milestone = kind === 'proof' ? createSoftSlice(milestoneSettings, { + current: milestoneCurrent, + notice: (reason, completedCompactions) => { + emit(reason === 'time' ? 'soft_slice_milestone_requested' : 'compaction_circuit_breaker_triggered', + { turnId: milestoneTurnId, completedCompactions, graceMs: milestoneSettings.graceMs }); + const submission = team + ? 'Use theoremos_team route_summary to review the team. Collect useful checked results and coordinate active teammates. ' + + 'If slots are free, delegate focused independent obligations using the team tools. ' + : skillMode ? 'Write .scratch/declaration-submission.json only if you have at least one locally compiled standalone helper to nominate. Never write an empty declarations array. ' + : 'Save standalone helpers in the owned Lean files for host checking. '; + void activeSession.notify?.(submission + + 'Write fewer than 20 lines in worktree-root RESEARCH.md covering what is established, the exact obstruction, ' + + 'and the next route or smaller obligation. Save your files and return after the current request and tools settle.', + activeSession.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }) + .catch(error => { + if (milestoneCurrent()) emit('soft_slice_notice_failed', { reason: failureDetail(error) }); + }); + }, + interrupt: () => { softSliceCheckpoint = interruptForCheckpoint('soft_slice_checkpoint_requested', + { turnId: milestoneTurnId, boundary: 'wait-limit' }); }, + }) : undefined; + if (milestone) softSliceAtModelBoundary = () => { + if (toolsRunning || !milestone.useBoundary()) return false; + softSliceCheckpoint = true; + emit('soft_slice_checkpoint_requested', { turnId: milestoneTurnId, boundary: 'request' }); return true; }; - const releaseUnstartedTurn = (assignment: CooperativeAction) => { - const superseded = !cooperation!.current(assignment); - unreserveTurn(); - cooperation!.release(worker, assignment); - unstarted = undefined; retries = 0; - if (superseded) emit('assignment_superseded', { beforeStart: true }); - else emit('assignment_deferred', { reason: 'turn-admission-declined' }); - save(); - }; - const close = async () => { - if (!session) { await closing; return; } - const current = session, closingSessionId = usage.sessionId; session = undefined; - team?.setLeadSession(undefined); - try { - closing = current.close(); await closing; - if (team && current.processIdentity && confirmHarnessProcessStopped(current.processIdentity).status === 'stopped') { - team.leadWriterStopped(); state.writerProcess = undefined; save(); + turnActivity = activity => { + if (activity.itemType && !nonToolItems.has(activity.itemType)) { + if (activity.event === 'item_started') toolsRunning++; + else if (activity.event === 'item_completed') { + toolsRunning = Math.max(0, toolsRunning - 1); + if (!toolsRunning && activeSession.usageSource !== 'upstream-requests' && milestone?.useBoundary()) + softSliceCheckpoint = interruptForCheckpoint('soft_slice_checkpoint_requested', + { turnId: milestoneTurnId, boundary: 'tool' }); } - } catch (error) { cleanupErrors.push(error); throw error; } - finally { usage.sessionClosed(closingSessionId); } - }; - const cancel = () => { void close().catch(() => {}); }; - signal.addEventListener('abort', cancel, { once: true }); - const beginTurn = async (currentContext: ContextBundle, assignment?: CooperativeAction, operation: ResearchOperation = 'direct') => { - access.assertHarnessCurrent?.(); - usage.resetTurn(); planningCheckpoint = false; cooperativeCheckpoint = false; proofHandoffCheckpoint = false; - finalReviewHandoffCheckpoint = false; - rebuildContext = false; - while ((pendingTurn = waitForTurn())) await pendingTurn; - if (assignment && !cooperation!.current(assignment)) return false; - // Feedback counters and dispatch UUIDs must not defeat the fresh-input capacity guard. - const target = assignment?.kind === 'task' ? { kind: assignment.kind, taskDigest: assignment.assignment.taskDigest, - dependencies: assignment.assignment.dependencies } : assignment && isStatementAction(assignment) - ? { kind: assignment.kind, snapshotDigest: assignment.snapshotDigest } : { kind: assignment?.kind ?? operation }; - turnContext = { digest: mathDigest(canonicalMathJson({ instructions: currentContext.instructions, target, - problem: state.problem.receiptDigest, environment: state.environmentDigest, model: state.model, - planVersion: cooperation?.contextState(assignment, worker).planVersion, - optionalBytes: research.contextOverflow?.maxOptionalContextBytes ?? currentContext.manifest?.maxOptionalBytes, - sources: state.problem.ownedFiles.map(file => [file, mathDigest(fs.readFileSync(path.join(worker.worktree, - state.problem.projectRelative, file)))]), - })), fresh: access.nativeContinuity === false || !research.threadId }; - if (turnContext.fresh && research.contextOverflow?.failedFreshContextDigests.includes(turnContext.digest)) - throw new Error('math_model_context_capacity_blocked'); - // Statement reviews work in their own fixed-statement workspace; proof turns get a current owned-declaration index. - if (!(assignment && isStatementAction(assignment))) writeOwnedDeclarationIndex(state.problem, worker.worktree); - if (currentContext.manifest) { - research.lastContextManifest = currentContext.manifest; - writeMathJsonDurable(path.join(worker.worktree, 'CONTEXT-MANIFEST.json'), currentContext.manifest); - emit('context_compiled', { taskId: assignment?.kind === 'task' ? assignment.task.id : undefined, - contentDigest: currentContext.manifest.contentDigest, requiredTaskIds: currentContext.manifest.requiredTaskIds, - included: currentContext.manifest.included.length, omitted: currentContext.manifest.omitted.length, - usedBytes: currentContext.manifest.usedBytes, mandatoryBytes: currentContext.manifest.mandatoryBytes, - optionalBytes: currentContext.manifest.optionalBytes, maxOptionalBytes: currentContext.manifest.maxOptionalBytes, - maxBytes: currentContext.manifest.maxBytes }); - } - if (!reserveTurn()) return false; - if (currentContext.knowledgeRetrievals?.length && currentContext.manifest) { - const ledger = state.knowledgeRetrievals ??= { dropped: 0, observations: [] }; - for (const retrieval of currentContext.knowledgeRetrievals) { - const observation = { ...retrieval, workerId: worker.id, workerTurn: research.turns, runTurn: state.turns, - contextDigest: currentContext.manifest.contentDigest, at: Date.now() }; - ledger.observations.push(observation); - emit('knowledge_retrieval_observed', { ...observation }); - } - const excess = Math.max(0, ledger.observations.length - 128); - ledger.observations.splice(0, excess); ledger.dropped += excess; - save(); } - if (!session) { - const statement = assignment && isStatementAction(assignment) ? assignment : undefined; - const workspace = statement?.workspace ?? worker.worktree; - const environment = statement ? { ...Object.fromEntries(Object.entries(access.environment).filter(([key]) => - !key.startsWith('DEEPSCIENTIST_MATH_') && key !== 'PWD' && key !== 'OLDPWD')), PWD: workspace } : access.environment; - while (!session) { - signal.throwIfAborted(); - if (!dispatchAllowed() || budget().remainingMs <= 0 || - (assignment && !cooperation!.current(assignment))) return false; - try { - const sessionId = crypto.randomUUID(); - const resumingThread = research.threadId; - const usageCallbacks = usage.bindSession(sessionId, () => session?.lastInputTokens); - if (usageCallbacks.requestGate) usageCallbacks.requestGate.checkpoint = () => - (softSliceAtModelBoundary?.() ?? false) || (checkpointAtModelBoundary?.() ?? false); - if (team && usageCallbacks.requestGate) usageCallbacks.requestGate = team.leadRequestGate(usageCallbacks.requestGate); - access.assertHarnessCurrent?.(); - session = await modules.M1.open({ executable: input.executable, profile: input.profile, - ...((access.commonResearchSkill ?? access.researchSkill) ? { skills: [(access.commonResearchSkill ?? access.researchSkill)!] } : {}), - ...(state.researchDelegation?.mode === 'read-only' ? { delegation: { ...state.researchDelegation, mode: 'read-only' as const } } : {}), - ...(team ? { tools: team.tools(), isolateProcess: true, - ...(team.nativeAgentControlEnabled ? { nativeAgentControl: team.nativeAgentControlOptions() } : {}) } : {}), - ...(team && !statement ? { leanHealthCheck: { executable: process.execPath, arguments: [path.join(input.root, 'out/main/check-lean.js'), - '--workspace', path.join(worker.worktree, state.problem.projectRelative), '--health', '--timeout-seconds', '0'] } } : {}), - ...(state.researchDelegation?.mode === 'read-only' ? { onNativeAgent: (agent: import('../runtime/nativeDelegation').NativeResearchAgent) => { - const agents = state.nativeAgents ??= [], index = agents.findIndex(item => item.threadId === agent.threadId); - if (index < 0) agents.push(agent); else agents[index] = agent; - emit('investigator_observed', { ...agent }); save(); - } } : {}), - hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), ...(team?.hiddenRoots ?? [])], - ...(!statement ? { proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative) } : {}), - ...(singleHandoff ? { completedOutput: singleHandoff.output } : {}), - workspace, environment: { ...environment, ...access.harnessEnvironment, - DEEPSCIENTIST_MATH_WORKER_ID: worker.id, DEEPSCIENTIST_MATH_WORKER_WORKTREE: workspace }, - model: state.model, effort: state.effort, threadId: research.threadId, - ...turnTiming, - instructions: currentContext.instructions, - onActivity: activity => { - research.lastActivity = { ...activity, at: Date.now() }; - emit('worker_activity', { activity: activity.event, itemType: activity.itemType }); save(); - if (activity.event === 'lean_environment_ready') emit('lean_environment_ready', { workerId: worker.id, health: activity.health }); - turnActivity?.(activity); - }, ...usageCallbacks, onUsage: (value, context) => { - usageCallbacks.onUsage(value, context); - if (!explicitCompaction) contextUsageVersion++; - } }); - if (state.agentSessionPlan && session.executionPlan && - canonicalMathJson(state.agentSessionPlan) !== canonicalMathJson(session.executionPlan)) - throw new Error('math_agent_session_plan_changed'); - usage.sessionOpened(session); - sessionHasHistory = Boolean(resumingThread && resumingThread === session.threadId); - team?.setLeadSession(session); - if (team && session.processIdentity) { state.writerProcess = session.processIdentity; save(); } - } catch (error) { - if (recordUnconfirmedWriterStartup(research, error, save)) throw error; - signal.throwIfAborted(); - // M1.open disposes failed launches before rejecting. Rebuild Lead's - // instructions for host tools before reserving the same turn again. - const fallback = !session && state.turns - Number(reservedTurn) <= - portfolioUsageRecords(state).reduce((total, scout) => total + scout.turns, 0) - ? team?.fallbackLeadTransport(error) : undefined; - if (fallback) { - usage.sessionClosed(usage.sessionId); - rebuildContext = true; - unreserveTurn(); save(); - input.emit('team_transport_fallback', fallback); - return false; - } - if (error instanceof LeanEnvironmentHealthCheckError) - emit('lean_environment_unavailable', { workerId: worker.id, health: error.health }); - if (assignment && !cooperation!.current(assignment)) return false; - const detail = failureDetail(error); - if (!recoverableResearchFailure(detail)) throw error; - await retryFailedTurn(detail); - if (researchFailureReason(detail) === 'math_model_context_window_exceeded') { - rebuildContext = true; - if (unreserveTurn()) save(); - return false; - } - } - } - if (signal.aborted) { await close(); signal.throwIfAborted(); } - if (assignment && !cooperation!.current(assignment)) return false; - sessionInstructions = currentContext.instructions; - if (session.threadId) { - if (!research.threadId || research.threadId !== session.threadId) - research.contextCheckpointBaseline = { threadId: session.threadId, notesDigest: checkpointNotesDigest() }; - research.threadId = session.threadId; save(); + if (live() && activity.itemType === 'contextCompaction') { + if (activity.event === 'item_started') markCompaction(activeSession.threadId, 'pending'); + if (activity.event === 'item_completed') { + markCompaction(activeSession.threadId, 'completed'); + milestone?.compacted(); } } - if (await maintainContext(assignment) !== 'unchanged') { - // Select the dispatch again if maintenance changed what this thread retains. - rebuildContext = true; - if (unreserveTurn()) save(); - return false; - } - // Opening a session can await while another worker exhausts the shared allowance. - return dispatchAllowed(); }; - const retryFailedTurn = async (error?: string, diagnostic?: MathAgentFailureDiagnostic): Promise => { - research.lastFailure = { at: Date.now(), reason: researchFailureReason(error, diagnostic), - ...(diagnostic ? { diagnostic: safeFailureDiagnostic(diagnostic) } : {}), - taskId: parallel ? (research as SolverWorkerState).sessionTaskId : undefined }; - save(); - if (!dispatchAllowed()) return; - if (researchFailureReason(error) === 'math_model_context_window_exceeded') { - const overflow = research.contextOverflow ??= { maxOptionalContextBytes: 0, failedFreshContextDigests: [] }; - overflow.maxOptionalContextBytes = 0; - if (turnContext?.fresh && !overflow.failedFreshContextDigests.includes(turnContext.digest)) - overflow.failedFreshContextDigests.push(turnContext.digest); - if (team?.nativeAgentControlEnabled && research.threadId && team.archive.nativeControl?.rootThreadId === research.threadId) { - if (nativeContextRecovery === 'attempted') throw new Error('math_model_context_capacity_blocked'); - nativeContextRecovery = 'pending'; - } - await rotateSession('context'); - retries = 0; - emit('worker_context_recovering', { reason: research.lastFailure.reason, - contextDigest: turnContext?.digest, maxOptionalContextBytes: 0 }); - save(); return; - } - const retry = modules.M3.retry(error, retries, { ...view(), turns: state.turns - Number(reservedTurn) }, budget()); - if (!retry) { - const previous = research.recovery?.phase !== 'recovered' ? research.recovery : undefined; - const cooldown = retries >= 3 ? planResearchCooldown(error, previous?.cycles ?? 0, budget()) : undefined; - if (!cooldown) throw new Error(researchFailureReason(error)); - await rotateSession('request'); - const now = Date.now(); - research.recovery = { phase: 'cooling-down', reason: cooldown.reason, cycles: cooldown.cycle, - startedAt: previous?.startedAt ?? now, nextRetryAt: now + cooldown.delayMs, waitedMs: previous?.waitedMs ?? 0 }; - emit('worker_cooling_down', { reason: cooldown.reason, cycle: cooldown.cycle, - delayMs: cooldown.delayMs, nextRetryAt: research.recovery.nextRetryAt }); - save(); - cooperation?.workerAvailabilityChanged(); - await waitForRecovery(); - retries = 0; - return; - } - retries = retry.attempt; - // Close failed writers before retrying. A bound native team must reopen its existing root. - if (research.threadId && (retry.reason === 'math_model_tool_failed' || - retry.reason === 'math_model_request_failed' && retries === 2 || retries === 1 && - ['math_model_request_timeout', 'math_codex_transport_closed'].includes(retry.reason))) - await rotateSession('request'); - emit('worker_recovering', { reason: retry.reason, attempt: retries, delayMs: retry.delayMs }); - emit('turn_retry', { reason: retry.reason, attempt: retries, delayMs: retry.delayMs, - ...(error?.startsWith('math_codex_transport_closed:') ? { detail: error } : {}) }); - await delay(retry.delayMs, undefined, { signal }); + const started = (turnId: string) => { + onStarted(turnId); + milestoneTurnId = turnId; + milestone?.start(); }; - const rotateSession = async (reason: 'context' | 'responsibility' | 'route' | 'request') => { - dispatchedContexts.clear(); - sessionInstructions = undefined; - if (parallel) { - (research as SolverWorkerState).sessionRouteId = undefined; - (research as SolverWorkerState).sessionTaskContextDigest = undefined; - } - const previous = research.threadId; - await close(); - if (previous && team?.nativeAgentControlEnabled && team.archive.nativeControl?.rootThreadId === previous) { - // Child lineage, mailbox ownership and the host's usage baseline all bind this thread ID. - sessionHasHistory = false; compactedUsageVersion = -1; - save(); - emit('context_reconnecting', { threadId: previous, turns: research.turns, reason }); - return; + let completed = false; + try { + const result = await run(started); + const detail = failureDetail(undefined, activeSession.lastError, activeSession.lastFailureDiagnostic); + if (usage.stopReason && detail !== usage.stopReason) throw new Error(detail); + const resultStatus = typeof result === 'string' ? result : result && typeof result === 'object' && 'status' in result ? result.status : undefined; + completed = resultStatus === 'completed'; + if (milestone?.requested && completed) softSliceCheckpoint = true; + if (completed) recovered(); + return result; + } finally { + finished = true; + milestone?.stop(); + softSliceAtModelBoundary = undefined; + clearTimeout(interruptTimer); + turnActivity = undefined; + try { if (checkpointClosing) await close(); } finally { usage.finish(completed); } + } + }; + const reserveTurn = () => { + if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0 || signal.aborted) return false; + // Reserve synchronously before opening a session so peers cannot overspend the shared budget. + reservedTurn = true; + state.turns++; + research.phase = 'running'; save(); + return true; + }; + /** Return a reserved but unstarted turn to the shared budget; false when none was reserved. */ + const unreserveTurn = () => { + if (!reservedTurn) return false; + state.turns--; + reservedTurn = false; + return true; + }; + const close = async () => { + if (!session) { await closing; return; } + const current = session, closingSessionId = usage.sessionId; session = undefined; + team?.setLeadSession(undefined); + try { + closing = current.close(); await closing; + if (team && current.processIdentity && confirmHarnessProcessStopped(current.processIdentity).status === 'stopped') { + team.leadWriterStopped(); state.writerProcess = undefined; save(); } - if (previous) research.previousThreadIds = [...(research.previousThreadIds ?? []), previous]; - research.threadId = undefined; research.lastInputTokens = undefined; research.contextCheckpoint = undefined; research.contextCheckpointBaseline = undefined; - sessionHasHistory = false; compactedUsageVersion = -1; - research.usageBeforeThread = research.usage; save(); - emit('context_restarted', { previousThreadId: previous, turns: research.turns, reason }); - }; - const maintainContext = async (assignment?: CooperativeAction): Promise<'unchanged' | 'compacted' | 'rotated'> => { - const recoverNative = nativeContextRecovery === 'pending'; - if (skillMode && !recoverNative || !research.threadId) return 'unchanged'; - const threadId = research.threadId; - const notesDigest = currentCheckpointNotesDigest(); - if (!session) { - if (!notesDigest) return 'unchanged'; - emit('context_checkpoint_ready', { threadId, notesDigest }); - await rotateSession('context'); return 'rotated'; + } catch (error) { cleanupErrors.push(error); throw error; } + finally { usage.sessionClosed(closingSessionId); } + }; + const cancel = () => { void close().catch(() => {}); }; + signal.addEventListener('abort', cancel, { once: true }); + const beginTurn = async (currentContext: ContextBundle, operation: ResearchOperation) => { + access.assertHarnessCurrent?.(); + usage.resetTurn(); + rebuildContext = false; + turnContext = { digest: mathDigest(canonicalMathJson({ instructions: currentContext.instructions, operation, + problem: state.problem.receiptDigest, environment: state.environmentDigest, model: state.model, + optionalBytes: research.contextOverflow?.maxOptionalContextBytes ?? currentContext.manifest?.maxOptionalBytes, + sources: state.problem.ownedFiles.map(file => [file, mathDigest(fs.readFileSync(path.join(worker.worktree, + state.problem.projectRelative, file)))]), + })), fresh: access.nativeContinuity === false || !research.threadId }; + if (turnContext.fresh && research.contextOverflow?.failedFreshContextDigests.includes(turnContext.digest)) + throw new Error('math_model_context_capacity_blocked'); + writeOwnedDeclarationIndex(state.problem, worker.worktree); + if (currentContext.manifest) { + research.lastContextManifest = currentContext.manifest; + writeMathJsonDurable(path.join(worker.worktree, 'CONTEXT-MANIFEST.json'), currentContext.manifest); + emit('context_compiled', { + contentDigest: currentContext.manifest.contentDigest, requiredTaskIds: currentContext.manifest.requiredTaskIds, + included: currentContext.manifest.included.length, omitted: currentContext.manifest.omitted.length, + usedBytes: currentContext.manifest.usedBytes, mandatoryBytes: currentContext.manifest.mandatoryBytes, + optionalBytes: currentContext.manifest.optionalBytes, maxOptionalBytes: currentContext.manifest.maxOptionalBytes, + maxBytes: currentContext.manifest.maxBytes }); + } + if (!reserveTurn()) return false; + if (currentContext.knowledgeRetrievals?.length && currentContext.manifest) { + const ledger = state.knowledgeRetrievals ??= { dropped: 0, observations: [] }; + for (const retrieval of currentContext.knowledgeRetrievals) { + const observation = { ...retrieval, workerId: worker.id, workerTurn: research.turns, runTurn: state.turns, + contextDigest: currentContext.manifest.contentDigest, at: Date.now() }; + ledger.observations.push(observation); + emit('knowledge_retrieval_observed', { ...observation }); } - if (!sessionHasHistory) return 'unchanged'; - const lastInputTokens = Math.max(session.lastInputTokens ?? 0, research.lastInputTokens ?? 0); - if (!recoverNative && lastInputTokens < 96_000 && !notesDigest) return 'unchanged'; - if (recoverNative) nativeContextRecovery = 'attempted'; - if (session.compact && (recoverNative || compactedUsageVersion !== contextUsageVersion || notesDigest)) { - const startedAt = Date.now(); - if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); - emit('context_compaction_requested', { threadId, lastInputTokens }); - usage.beginMaintenance(assignment); explicitCompaction = true; + const excess = Math.max(0, ledger.observations.length - 128); + ledger.observations.splice(0, excess); ledger.dropped += excess; + save(); + } + if (!session) { + const workspace = worker.worktree; + while (!session) { + signal.throwIfAborted(); + if (!dispatchAllowed() || budget().remainingMs <= 0) return false; try { - await session.compact(); signal.throwIfAborted(); - markCompaction(threadId, 'completed'); compactedUsageVersion = contextUsageVersion; - research.contextCheckpoint = undefined; - research.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() }; - research.lastInputTokens = session.lastInputTokens; - emit('context_compaction_completed', { threadId, maintenanceMs: Date.now() - startedAt }); save(); - return 'compacted'; + const sessionId = crypto.randomUUID(); + const resumingThread = research.threadId; + const usageCallbacks = usage.bindSession(sessionId, () => session?.lastInputTokens); + if (usageCallbacks.requestGate) usageCallbacks.requestGate.checkpoint = () => + (softSliceAtModelBoundary?.() ?? false); + if (team && usageCallbacks.requestGate) usageCallbacks.requestGate = team.leadRequestGate(usageCallbacks.requestGate); + access.assertHarnessCurrent?.(); + session = await modules.M1.open({ executable: input.executable, profile: input.profile, + ...((access.commonResearchSkill ?? access.researchSkill) ? { skills: [(access.commonResearchSkill ?? access.researchSkill)!] } : {}), + ...(team ? { tools: team.tools(), isolateProcess: true, + ...(!team.mayStartProofWork ? { readOnlyWorkspace: true } : {}), + nativeAgentControl: team.nativeAgentControlOptions() } : {}), + ...(team ? { leanHealthCheck: { executable: process.execPath, arguments: [path.join(input.root, 'out/main/check-lean.js'), + '--workspace', path.join(worker.worktree, state.problem.projectRelative), '--health', '--timeout-seconds', '0'] } } : {}), + hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), ...(team?.hiddenRoots ?? [])], + proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative), + completedOutput: singleHandoff.output, + workspace, environment: { ...access.environment, ...access.harnessEnvironment, + DEEPSCIENTIST_MATH_WORKER_ID: worker.id, DEEPSCIENTIST_MATH_WORKER_WORKTREE: workspace }, + model: state.model, effort: state.effort, threadId: research.threadId, + ...turnTiming, + instructions: currentContext.instructions, + onActivity: activity => { + research.lastActivity = { ...activity, at: Date.now() }; + emit('worker_activity', { activity: activity.event, itemType: activity.itemType }); save(); + if (activity.event === 'lean_environment_ready') emit('lean_environment_ready', { workerId: worker.id, health: activity.health }); + turnActivity?.(activity); + }, ...usageCallbacks, onUsage: (value, context) => { + usageCallbacks.onUsage(value, context); + if (!explicitCompaction) contextUsageVersion++; + } }); + if (state.agentSessionPlan && session.executionPlan && + canonicalMathJson(state.agentSessionPlan) !== canonicalMathJson(session.executionPlan)) + throw new Error('math_agent_session_plan_changed'); + usage.sessionOpened(session); + sessionHasHistory = Boolean(resumingThread && resumingThread === session.threadId); + team?.setLeadSession(session); + if (team && session.processIdentity) { state.writerProcess = session.processIdentity; save(); } } catch (error) { + if (recordUnconfirmedWriterStartup(research, error, save)) throw error; signal.throwIfAborted(); - emit('context_compaction_failed', { threadId, reason: failureDetail(error) }); - if (recoverNative) throw new Error('math_model_context_capacity_blocked', { cause: error }); - } finally { explicitCompaction = false; usage.finishMaintenance(); } - await rotateSession('context'); return 'rotated'; + if (error instanceof LeanEnvironmentHealthCheckError) + emit('lean_environment_unavailable', { workerId: worker.id, health: error.health }); + const detail = failureDetail(error); + if (!recoverableResearchFailure(detail)) throw error; + await retryFailedTurn(detail); + if (researchFailureReason(detail) === 'math_model_context_window_exceeded') { + rebuildContext = true; + if (unreserveTurn()) save(); + return false; + } + } } - if (recoverNative) throw new Error('math_model_context_capacity_blocked'); - if (session.compact) return 'unchanged'; // Wait for a new usage observation before another native maintenance request. - if (!cooperation || !assignment || notesDigest) { - if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); - await rotateSession('context'); return 'rotated'; + if (signal.aborted) { await close(); signal.throwIfAborted(); } + sessionInstructions = currentContext.instructions; + if (session.threadId) { + if (!research.threadId || research.threadId !== session.threadId) + research.contextCheckpointBaseline = { threadId: session.threadId, notesDigest: checkpointNotesDigest() }; + research.threadId = session.threadId; save(); } - requestContextCheckpoint(lastInputTokens); - if (research.contextCheckpoint && research.contextCheckpoint.deferredAt === undefined) { - research.contextCheckpoint.deferredAt = Date.now(); - emit('context_rotation_deferred', { threadId, reason: 'checkpoint-not-published', lastInputTokens }); save(); + } + if (await maintainContext() !== 'unchanged') { + // Select the dispatch again if maintenance changed what this thread retains. + rebuildContext = true; + if (unreserveTurn()) save(); + return false; + } + // Opening a session can await while another worker exhausts the shared allowance. + return dispatchAllowed(); + }; + const retryFailedTurn = async (error?: string, diagnostic?: MathAgentFailureDiagnostic): Promise => { + research.lastFailure = { at: Date.now(), reason: researchFailureReason(error, diagnostic), + ...(diagnostic ? { diagnostic: safeFailureDiagnostic(diagnostic) } : {}) }; + save(); + if (!dispatchAllowed()) return; + if (researchFailureReason(error) === 'math_model_context_window_exceeded') { + const overflow = research.contextOverflow ??= { maxOptionalContextBytes: 0, failedFreshContextDigests: [] }; + overflow.maxOptionalContextBytes = 0; + if (turnContext?.fresh && !overflow.failedFreshContextDigests.includes(turnContext.digest)) + overflow.failedFreshContextDigests.push(turnContext.digest); + if (team && research.threadId && team.archive.nativeControl?.rootThreadId === research.threadId) { + if (nativeContextRecovery === 'attempted') throw new Error('math_model_context_capacity_blocked'); + nativeContextRecovery = 'pending'; } - return 'unchanged'; - }; - const checkWhole = async (candidate = research.candidate) => { - const previousFailures = research.failures; - const checkStarted = Date.now(); - emit('proof_check_started', { turn: research.turns }); - research.check = lastCheck?.passed && commitSolverSources(state.problem, worker.worktree) === lastCheck.commit ? lastCheck : - await modules.M2.check(state.problem, worker.worktree, access.environment, signal, lastCheck, input.proofTimeoutMs); - research.failures = rememberSolverFailure(research.check, previousFailures); - const reused = research.check === lastCheck || research.check.verification === lastCheck?.verification; - emit('proof_checked', { passed: research.check.passed, commit: research.check.commit, - reused, - durationMs: Date.now() - checkStarted }); - if (access.knowledgeSnapshot || access.installedLibrary) { - let claims: unknown; - try { claims = parseMathResponse(committedSource(worker.worktree, research.check.commit, 'RESEARCH.md'), - 'math-result', {}, 'summary').knowledgeUses; } catch { /* Ordinary notes need no usage response. */ } - { - const records = state.knowledgeUses ??= []; - for (const [index, target] of state.problem.targets.entries()) { - const task = state.cooperation?.tasks.find(node => node.task.kind === 'goal' && node.task.theoremName === target.theoremName && - node.task.proofPath === target.proofPath)?.task ?? { id: `original_goal_${index + 1}`, kind: 'goal' as const, - objective: `Prove ${target.theoremName}`, revision: 0, dependsOn: [], ...target }; - const observed = inspectKnowledgeUses(claims, access.knowledgeSnapshot, task, research.check, access.installedLibrary); - const checked = await checkKnowledgeApplications(observed.uses, { task, projectRoot: path.join(worker.worktree, state.problem.projectRelative), - env: access.environment, environmentDigest: state.environmentDigest, commit: research.check.commit, - signal, timeoutMs: input.proofTimeoutMs ?? Infinity, originalContexts: state.problem.targets, previous: records, - sourceAtCommit: file => committedSource(worker.worktree, research.check!.commit, path.posix.join(state.problem.projectRelative, file)) }); - for (const use of checked) { - const record = { ...use, workerId: worker.id, commit: research.check!.commit }; - const key = canonicalMathJson(record); - if (!records.some(previous => canonicalMathJson(previous) === key)) { - records.push(record); emit('knowledge_use_observed', { ...record }); - } + await rotateSession('context'); + retries = 0; + emit('worker_context_recovering', { reason: research.lastFailure.reason, + contextDigest: turnContext?.digest, maxOptionalContextBytes: 0 }); + save(); return; + } + const retry = modules.M3.retry(error, retries, { ...state, turns: state.turns - Number(reservedTurn) }, budget()); + if (!retry) { + const previous = research.recovery?.phase !== 'recovered' ? research.recovery : undefined; + const cooldown = retries >= 3 ? planResearchCooldown(error, previous?.cycles ?? 0, budget()) : undefined; + if (!cooldown) throw new Error(researchFailureReason(error)); + await rotateSession('request'); + const now = Date.now(); + research.recovery = { phase: 'cooling-down', reason: cooldown.reason, cycles: cooldown.cycle, + startedAt: previous?.startedAt ?? now, nextRetryAt: now + cooldown.delayMs, waitedMs: previous?.waitedMs ?? 0 }; + emit('worker_cooling_down', { reason: cooldown.reason, cycle: cooldown.cycle, + delayMs: cooldown.delayMs, nextRetryAt: research.recovery.nextRetryAt }); + save(); + await waitForRecovery(); + retries = 0; + return; + } + retries = retry.attempt; + // Close failed writers before retrying. A bound native team must reopen its existing root. + if (research.threadId && (retry.reason === 'math_model_tool_failed' || + retry.reason === 'math_model_request_failed' && retries === 2 || retries === 1 && + ['math_model_request_timeout', 'math_codex_transport_closed'].includes(retry.reason))) + await rotateSession('request'); + emit('worker_recovering', { reason: retry.reason, attempt: retries, delayMs: retry.delayMs }); + emit('turn_retry', { reason: retry.reason, attempt: retries, delayMs: retry.delayMs, + ...(error?.startsWith('math_codex_transport_closed:') ? { detail: error } : {}) }); + await delay(retry.delayMs, undefined, { signal }); + }; + const rotateSession = async (reason: 'context' | 'request') => { + dispatched = undefined; + sessionInstructions = undefined; + const previous = research.threadId; + await close(); + if (previous && team && team.archive.nativeControl?.rootThreadId === previous) { + // Child lineage, mailbox ownership and the host's usage baseline all bind this thread ID. + sessionHasHistory = false; compactedUsageVersion = -1; + save(); + emit('context_reconnecting', { threadId: previous, turns: research.turns, reason }); + return; + } + if (previous) research.previousThreadIds = [...(research.previousThreadIds ?? []), previous]; + research.threadId = undefined; research.lastInputTokens = undefined; research.contextCheckpoint = undefined; research.contextCheckpointBaseline = undefined; + sessionHasHistory = false; compactedUsageVersion = -1; + research.usageBeforeThread = research.usage; save(); + emit('context_restarted', { previousThreadId: previous, turns: research.turns, reason }); + }; + const maintainContext = async (): Promise<'unchanged' | 'compacted' | 'rotated'> => { + const recoverNative = nativeContextRecovery === 'pending'; + if (skillMode && !recoverNative || !research.threadId) return 'unchanged'; + const threadId = research.threadId; + const notesDigest = currentCheckpointNotesDigest(); + if (!session) { + if (!notesDigest) return 'unchanged'; + emit('context_checkpoint_ready', { threadId, notesDigest }); + await rotateSession('context'); return 'rotated'; + } + if (!sessionHasHistory) return 'unchanged'; + const lastInputTokens = Math.max(session.lastInputTokens ?? 0, research.lastInputTokens ?? 0); + if (!recoverNative && lastInputTokens < 96_000 && !notesDigest) return 'unchanged'; + if (recoverNative) nativeContextRecovery = 'attempted'; + if (session.compact && (recoverNative || compactedUsageVersion !== contextUsageVersion || notesDigest)) { + const startedAt = Date.now(); + if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); + emit('context_compaction_requested', { threadId, lastInputTokens }); + usage.beginMaintenance(); explicitCompaction = true; + try { + await session.compact(); signal.throwIfAborted(); + markCompaction(threadId, 'completed'); compactedUsageVersion = contextUsageVersion; + research.contextCheckpoint = undefined; + research.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() }; + research.lastInputTokens = session.lastInputTokens; + emit('context_compaction_completed', { threadId, maintenanceMs: Date.now() - startedAt }); save(); + return 'compacted'; + } catch (error) { + signal.throwIfAborted(); + emit('context_compaction_failed', { threadId, reason: failureDetail(error) }); + if (recoverNative) throw new Error('math_model_context_capacity_blocked', { cause: error }); + } finally { explicitCompaction = false; usage.finishMaintenance(); } + await rotateSession('context'); return 'rotated'; + } + if (recoverNative) throw new Error('math_model_context_capacity_blocked'); + if (session.compact) return 'unchanged'; // Wait for a new usage observation before another native maintenance request. + if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); + await rotateSession('context'); + return 'rotated'; + }; + const checkWhole = async (candidate = research.candidate) => { + const previousFailures = research.failures; + const checkStarted = Date.now(); + emit('proof_check_started', { turn: research.turns }); + research.check = lastCheck?.passed && commitSolverSources(state.problem, worker.worktree) === lastCheck.commit ? lastCheck : + await modules.M2.check(state.problem, worker.worktree, access.environment, signal, lastCheck, input.proofTimeoutMs); + research.failures = rememberSolverFailure(research.check, previousFailures); + const reused = research.check === lastCheck || research.check.verification === lastCheck?.verification; + emit('proof_checked', { passed: research.check.passed, commit: research.check.commit, + reused, + durationMs: Date.now() - checkStarted }); + if (access.knowledgeSnapshot || access.installedLibrary) { + let claims: unknown; + try { claims = parseMathResponse(committedSource(worker.worktree, research.check.commit, 'RESEARCH.md'), + 'math-result', {}, 'summary').knowledgeUses; } catch { /* Ordinary notes need no usage response. */ } + { + const records = state.knowledgeUses ??= []; + for (const [index, target] of state.problem.targets.entries()) { + const task = { id: `original_goal_${index + 1}`, kind: 'goal' as const, + objective: `Prove ${target.theoremName}`, revision: 0, dependsOn: [], ...target }; + const observed = inspectKnowledgeUses(claims, access.knowledgeSnapshot, task, research.check, access.installedLibrary); + const checked = await checkKnowledgeApplications(observed.uses, { task, projectRoot: path.join(worker.worktree, state.problem.projectRelative), + env: access.environment, environmentDigest: state.environmentDigest, commit: research.check.commit, + signal, timeoutMs: input.proofTimeoutMs ?? Infinity, originalContexts: state.problem.targets, previous: records, + sourceAtCommit: file => committedSource(worker.worktree, research.check!.commit, path.posix.join(state.problem.projectRelative, file)) }); + for (const use of checked) { + const record = { ...use, workerId: worker.id, commit: research.check!.commit }; + const key = canonicalMathJson(record); + if (!records.some(previous => canonicalMathJson(previous) === key)) { + records.push(record); emit('knowledge_use_observed', { ...record }); } - if (observed.rejected) emit('knowledge_use_rejected', { commit: research.check!.commit, rejected: observed.rejected }); } - if (records.length > 256) records.splice(0, records.length - 256); + if (observed.rejected) emit('knowledge_use_rejected', { commit: research.check!.commit, rejected: observed.rejected }); } + if (records.length > 256) records.splice(0, records.length - 256); } - lastCheck = research.check; save(); - if (research.check.passed) { - if (cooperation && !cooperation.candidateReady(research.check)) return; - state.check = research.check; state.candidate = candidate; - if (parallel) state.winningWorker = worker.id; - winner = { worktree: worker.worktree, check: research.check }; - save(); emit('candidate_selected', { commit: research.check.commit }); abort(); - return; - } - if (['unavailable', 'blocked'].includes(research.check.verification.status)) - throw new VerifierFailureError({ stage: 'solver-proof-check', sourceCommit: research.check.commit, - verification: research.check.verification }); - }; - const skillProofLifecycle = skillMode ? createSkillProofLifecycle({ state, worktree: worker.worktree, - environment: access.environment, skill: access.researchSkill!, signal, proofTimeoutMs: input.proofTimeoutMs, - writerStopped: () => !session && !research.writerStopUnconfirmed, sourceFeedback, - exclusiveCheck, checkWhole, save, emit }) : undefined; - const proofLifecycle = cooperation && new WorkerProofLifecycle({ state, research, worker, cooperation, - close, save, emit, checked: () => { retries = 0; } }); + } + lastCheck = research.check; save(); + if (research.check.passed) { + state.check = research.check; state.candidate = candidate; + winner = { worktree: worker.worktree, check: research.check }; + save(); emit('candidate_selected', { commit: research.check.commit }); abort(); + return; + } + if (['unavailable', 'blocked'].includes(research.check.verification.status)) + throw new VerifierFailureError({ stage: 'solver-proof-check', sourceCommit: research.check.commit, + verification: research.check.verification }); + }; + const skillProofLifecycle = skillMode ? createSkillProofLifecycle({ state, worktree: worker.worktree, + environment: access.environment, skill: access.researchSkill!, signal, proofTimeoutMs: input.proofTimeoutMs, + writerStopped: () => !session && !research.writerStopUnconfirmed, sourceFeedback, + exclusiveCheck, checkWhole, save, emit }) : undefined; + const awaitNativePlanApproval = async () => { + if (planApprovalStatus(state) !== 'pending') return true; + if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0) { + emit('plan_approval_unanswered', { planVersion: state.cooperation?.planVersion }); + return false; + } + // A resumed run can be waiting on a saved plan before it reserves a new turn. + if (state.phase !== 'running') { + research.phase = 'running'; save(); + } + const stateFile = path.join(path.dirname(state.worktree), 'state.json'); + const read = () => drainPlanApprovals(state, stateFile, signal, save, input.emit); + read(); + if (planApprovalStatus(state) !== 'pending') return true; + input.executionBudget?.setWaiting(true); save(); try { - await waitForRecovery(true); - await skillProofLifecycle?.resumePending(); - if (winner) return; - access.assertKnowledgeCurrent?.(); - if ((!skillMode || fullSkillWorkflow) && !team && !access.commonResearchSkill && !cooperation && !research.turns && access.installedLibrary && modules.M2.applyLibrary && budget().remainingMs > 0) { - const closed = await applyOriginalLibraryTasks({ problem: state.problem, library: access.installedLibrary, - taskText: input.taskText, environmentDigest: state.environmentDigest, worktree: worker.worktree, workerId: worker.id, - env: access.environment, signal, timeoutMs: Math.min(input.proofTimeoutMs ?? Infinity, budget().remainingMs), - prepare: modules.M2.applyLibrary, check: modules.M2.checkTask ?? checkTaskProof, emit, - onProof: (task, proof) => { - // A saved host proof still needs whole-problem acceptance after a restart. - setWorkerResearchPhase(state, research, 'checking'); - const records = state.knowledgeUses ??= []; - for (const use of inspectKnowledgeUses(undefined, access.knowledgeSnapshot, task, proof, access.installedLibrary).uses) { - const record = { ...use, workerId: worker.id, commit: proof.commit }; - if (!records.some(previous => canonicalMathJson(previous) === canonicalMathJson(record))) { - records.push(record); emit('knowledge_use_observed', { ...record }); - } - } - save(); - } }); - if ((closed || research.phase === 'checking') && !signal.aborted) await exclusiveCheck(() => checkWhole()); - } - while (!signal.aborted) { - await skillProofLifecycle?.resumePending(); - if (winner) break; - if (research.phase === 'checking') { setWorkerResearchPhase(state, research, 'running'); save(); } - if (compactionRestart) { - await rotateSession('context'); - compactionRestart = false; - } - const assignment = await cooperation?.next(worker, budget()); - unstarted = assignment?.kind === 'assemble' ? undefined : assignment; - if (cooperation && !assignment) break; - if (assignment?.kind === 'assemble') { - setWorkerResearchPhase(state, research, 'checking'); save(); - emit('assembly_started', { commit: assignment.seedCommit }); - try { - await exclusiveCheck(async () => { - if (!cooperation!.current(assignment)) return; - await checkWhole(); - if (!winner && !research.check!.passed) cooperation!.assemblyFailed(research.check!); - }); - } finally { setWorkerResearchPhase(state, research, 'running'); save(); } - continue; - } - if (await proofLifecycle?.resumeFrozen(assignment)) { syncProofImports(state); save(); continue; } - if (cooperation && proofLifecycle && await importAssignedProof({ state, - directory: path.dirname(input.workers[0].worktree), worker, action: assignment, cooperation, - lifecycle: proofLifecycle, close, save, emit })) { unstarted = undefined; continue; } - while ((pendingTurn = waitForTurn())) await pendingTurn; - if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0) break; - let sameRouteSwitch = false; - if (assignment) { - const record = research as SolverWorkerState; - const taskReview = assignment.kind === 'task' && - (isFeasibilityReview(assignment.task) || isFinalCandidateReview(assignment.task)); - const role = assignment.kind === 'review' || isStatementAction(assignment) || taskReview ? 'reviewer' : - assignment.kind === 'task' ? researchTaskRole(assignment.task) : worker.role; - const groupId = assignment.kind === 'task' ? taskGroup(assignment.task) : undefined; - const roleChanged = record.sessionRole && record.sessionRole !== role; - const leadMode = assignment.kind === 'lead' ? 'planning' as const : undefined; - // A legacy saved coordination thread is replaced once; refreshed nonces reuse the planning thread. - const leadModeChanged = leadMode !== undefined && record.sessionLeadMode !== undefined && - record.sessionLeadMode !== leadMode; - const routeId = assignment.kind === 'task' ? assignment.assignment.routeId : undefined; - const groupChanged = (record.sessionGroupId !== undefined && record.sessionGroupId !== groupId) || - (record.sessionTaskId !== undefined && record.sessionRouteId !== routeId); - const versionChanged = assignment.kind === 'task' && record.sessionTaskId === assignment.task.id && - record.sessionTaskVersion && record.sessionTaskVersion !== assignment.assignment.taskDigest; - const sessionAssignmentId = assignment.kind === 'task' - ? assignment.assignment.assignmentId ?? `legacy-task:${assignment.assignment.seedCommit}` - : assignment.kind === 'review' ? assignment.assignmentId ?? `legacy-review:${assignment.seedCommit}` : undefined; - const reviewAssignmentChanged = (taskReview || assignment.kind === 'review' && record.sessionRole === 'reviewer') && - record.sessionAssignmentId !== sessionAssignmentId; - const reviewTargetChanged = (taskReview || record.sessionRole === 'reviewer') && - (record.sessionTaskId !== (assignment.kind === 'task' ? assignment.task.id : undefined) || versionChanged); - const taskChanged = assignment.kind === 'task' && record.sessionTaskId && - record.sessionTaskId !== assignment.task.id; - if (isStatementAction(assignment) || record.sessionStatementReview || roleChanged || leadModeChanged || - reviewTargetChanged || reviewAssignmentChanged) - await rotateSession('responsibility'); - else if (groupChanged) await rotateSession('route'); - else if (versionChanged) await rotateSession('context'); - else if (taskChanged && research.threadId && (research.contextCheckpoint || - Math.max(session?.lastInputTokens ?? 0, research.lastInputTokens ?? 0) >= 90_000)) - await rotateSession('context'); - else sameRouteSwitch = Boolean(taskChanged && record.sessionGroupId === groupId); - if (groupChanged) { - research.check = undefined; feedbackCheck = undefined; - } - record.sessionRole = role; - record.sessionLeadMode = leadMode; - record.sessionGroupId = groupId; - record.sessionTaskId = assignment.kind === 'task' ? assignment.task.id : undefined; - record.sessionTaskVersion = assignment.kind === 'task' ? assignment.assignment.taskDigest : undefined; - record.sessionAssignmentId = sessionAssignmentId; - record.sessionStatementReview = isStatementAction(assignment); - } - if (!skillMode && research.threadId && research.contextCheckpoint?.threadId === research.threadId && !research.contextCheckpoint.requestId) - requestContextCheckpoint(Math.max(session?.lastInputTokens ?? 0, research.lastInputTokens ?? 0)); - await maintainContext(assignment); - const options: readonly ResearchOperation[] = ['direct']; - while ((pendingTurn = waitForTurn())) await pendingTurn; - const action = skillMode && !fullSkillWorkflow ? { operation: 'direct' as const, reason: 'continue' as const } - : modules.M3.select(view(), options, budget(), assignment); - if (action.operation === 'stop') break; - const operation = action.operation; - if (!options.includes(action.operation)) throw new Error('math_research_operation_unavailable'); - emit('research_action', { operation: action.operation, reason: action.reason }); - readMathBuildManifest(input.buildFile, input.root, path.join(input.root, 'out', 'main')); - const onStarted = (turnId: string) => { - // Some headless CLIs report a native ID only after starting. Persist that exact - // identity before publishing a turn; an empty ID cannot stand for a saved thread. - if (!session?.threadId) throw new Error('math_agent_session_binding_missing'); - if (research.threadId !== session.threadId) { - research.contextCheckpointBaseline = { threadId: session.threadId, notesDigest: checkpointNotesDigest() }; - research.threadId = session.threadId; save(); - } - emit('turn_started', { turnId, threadId: session?.threadId, turn: research.turns, totalTurns: state.turns, - ...(assignment?.kind === 'task' ? { taskId: assignment.task.id, taskDigest: assignment.assignment.taskDigest, - assignmentKey: assignmentDeliveryFile(assignment.assignment), seedCommit: assignment.assignment.seedCommit } - : assignment ? { seedCommit: assignment.seedCommit } : {}) }); - if (assignment && cooperation && !cooperation.current(assignment)) void session?.interrupt().catch(() => {}); - }; - if (assignment && isStatementAction(assignment)) { - const currentContext = cooperation!.statementContext(assignment); - try { - if (!await beginTurn(currentContext, assignment, operation)) { - if (rebuildContext) { releaseUnstartedTurn(assignment); continue; } - if (!cooperation!.current(assignment)) { releaseUnstartedTurn(assignment); continue; } - break; - } - let status: string | undefined; - let executionError: string | undefined; - try { - status = await modelTurn(started => runResearchTurn(session!, currentContext.message, assignment.workspace, signal, started), assignment, onStarted); - } catch (error) { - signal.throwIfAborted(); - executionError = failureDetail(error, session?.lastError, session?.lastFailureDiagnostic); - if (!recoverableResearchFailure(executionError) && !locallyStopped(executionError)) throw error; - status = 'failed'; - } - if (status === undefined) { - if (dispatchAllowed() && budget().remainingMs > 0 && !signal.aborted) { - releaseUnstartedTurn(assignment); continue; - } - break; - } - await cooperation!.pulse(worker.id); - if (!cooperation!.current(assignment) || status === 'completed') { - retries = 0; - await close(); - await exclusiveCheck(() => cooperation!.deliverStatement(worker, assignment)); - } else if (['interrupted', 'checkpoint'].includes(status)) { - retries = 0; - cooperation!.interrupted(worker, assignment); emit('turn_checkpoint', { turn: research.turns }); - } else { - const diagnostic = safeFailureDiagnostic(session?.lastFailureDiagnostic); - const turnError = executionError ?? failureDetail(session?.lastError, undefined, diagnostic); - await close(); - if (!cooperation!.current(assignment)) { - retries = 0; - await exclusiveCheck(() => cooperation!.deliverStatement(worker, assignment)); - emit('assignment_superseded'); continue; - } - emit('turn_failed', { reason: researchFailureReason(turnError), ...(diagnostic ? { diagnostic } : {}) }); - cooperation!.interrupted(worker, assignment); - await retryFailedTurn(turnError, diagnostic); + do { + await delay(200, undefined, { signal }); + read(); + } while (planApprovalStatus(state) === 'pending'); + } finally { + input.executionBudget?.setWaiting(false); save(); + } + return true; + }; + let deliveredApprovedPlan = false; + try { + await waitForRecovery(true); + if (!team || team.mayStartProofWork) await skillProofLifecycle?.resumePending(); + if (winner) return winner; + access.assertKnowledgeCurrent?.(); + if ((!skillMode || fullSkillWorkflow) && !team && !access.commonResearchSkill && !research.turns && access.installedLibrary && modules.M2.applyLibrary && budget().remainingMs > 0) { + const closed = await applyOriginalLibraryTasks({ problem: state.problem, library: access.installedLibrary, + taskText: input.taskText, environmentDigest: state.environmentDigest, worktree: worker.worktree, workerId: worker.id, + env: access.environment, signal, timeoutMs: Math.min(input.proofTimeoutMs ?? Infinity, budget().remainingMs), + prepare: modules.M2.applyLibrary, check: modules.M2.checkTask ?? checkTaskProof, emit, + onProof: (task, proof) => { + // A saved host proof still needs whole-problem acceptance after a restart. + research.phase = 'checking'; + const records = state.knowledgeUses ??= []; + for (const use of inspectKnowledgeUses(undefined, access.knowledgeSnapshot, task, proof, access.installedLibrary).uses) { + const record = { ...use, workerId: worker.id, commit: proof.commit }; + if (!records.some(previous => canonicalMathJson(previous) === canonicalMathJson(record))) { + records.push(record); emit('knowledge_use_observed', { ...record }); } - } finally { - try { await rotateSession('context'); } finally { cooperation!.deactivate(worker); } - (research as SolverWorkerState).sessionStatementReview = false; save(); - } - continue; - } - const repair = sourceFeedback(); - if (repair) research.check = undefined; - const currentContext = context(repair, feedbackCheck, feedbackFailures, assignment); - const taskContextDigest = assignment?.kind === 'task' ? mathDigest(canonicalMathJson({ - instructions: currentContext.instructions, environment: state.environmentDigest, - })) : undefined; - const previousTaskContextDigest = (research as SolverWorkerState).sessionTaskContextDigest; - if (taskContextDigest && research.threadId && previousTaskContextDigest && previousTaskContextDigest !== taskContextDigest) - await rotateSession('responsibility'); - const responsibility = skillMode ? canonicalMathJson({ kind: 'skill', taskDigest: state.taskDigest, - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, - researchSkill: state.researchSkill, commonResearchSkill: state.commonResearchSkill, - instructions: currentContext.instructions }) - : assignment?.kind === 'lead' ? canonicalMathJson({ planVersion: assignment.planVersion, - initial: Boolean(assignment.initialPlanNonce), - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest }) - : assignment?.kind === 'task' && !isFeasibilityReview(assignment.task) && !isFinalCandidateReview(assignment.task) ? canonicalMathJson({ - kind: 'task', task: assignment.task, assignment: promptAction(assignment), - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, - workContract: currentContext.workContract, instructions: currentContext.instructions }) : undefined; - const selectBasis = contextResearchBases.get(currentContext); - const fullContextBasis = selectBasis?.(currentContext.manifest); - const dispatchedContext = responsibility === undefined ? undefined : dispatchedContexts.get(responsibility); - const researchInputsChanged = fullContextBasis && dispatchedContext?.researchInputDigest !== fullContextBasis.dispatchDigest; - const sameResponsibility = access.nativeContinuity !== false && !researchInputsChanged && responsibility !== undefined && Boolean(research.threadId) && - currentContext.continuationMessage !== undefined && - dispatchedContext?.threadId === research.threadId; - const continuation = sameResponsibility && !dispatchedContext?.compaction; - const taskSwitch = access.nativeContinuity !== false && sameRouteSwitch && !dispatchedContext && - Boolean(research.threadId && dispatchedContexts.size) && currentContext.continuationMessage !== undefined && - ![...dispatchedContexts.values()].some(context => context.compaction); - const checkpointInstruction = research.threadId && research.contextCheckpoint?.threadId === research.threadId && !currentCheckpointNotesDigest() - ? contextCheckpointInstruction(assignment) : undefined; - const smallerContext = sameResponsibility && dispatchedContext?.compaction === 'completed' - ? compactedResearchDispatch(currentContext, { checkpointInstruction }) : undefined; - // Preserve the entire admitted research dependency inventory even if its evidence was optional. - const compacted = smallerContext && selectBasis?.(smallerContext.manifest).dispatchDigest === fullContextBasis?.dispatchDigest - ? smallerContext : undefined; - Object.assign(currentContext, compacted ?? finalizeResearchDispatch(currentContext, { continuation, taskSwitch, checkpointInstruction })); - const contextBasis = taskSwitch ? selectBasis?.(currentContext.manifest) : fullContextBasis; - // A refreshed Lead nonce updates session instructions while preserving its planning history. - if (session && sessionInstructions !== currentContext.instructions) await close(); - if (!await beginTurn(currentContext, assignment, operation)) { - if (rebuildContext) { if (assignment) releaseUnstartedTurn(assignment); continue; } - if (assignment && !cooperation!.current(assignment)) { - releaseUnstartedTurn(assignment); await rotateSession('context'); continue; } - break; + save(); + } }); + if ((closed || research.phase === 'checking') && !signal.aborted) await exclusiveCheck(() => checkWhole()); + } + while (!signal.aborted) { + if (team?.reviewPlan && !await awaitNativePlanApproval()) break; + if (!team || team.mayStartProofWork) await skillProofLifecycle?.resumePending(); + if (winner) break; + if (research.phase === 'checking') { research.phase = 'running'; save(); } + if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0) break; + if (!skillMode && research.threadId && research.contextCheckpoint?.threadId === research.threadId && !research.contextCheckpoint.requestId) + requestContextCheckpoint(Math.max(session?.lastInputTokens ?? 0, research.lastInputTokens ?? 0)); + await maintainContext(); + const options: readonly ResearchOperation[] = ['direct']; + const action = skillMode && !fullSkillWorkflow ? { operation: 'direct' as const, reason: 'continue' as const } + : modules.M3.select(state, options, budget()); + if (action.operation === 'stop') break; + const operation = action.operation; + if (!options.includes(action.operation)) throw new Error('math_research_operation_unavailable'); + emit('research_action', { operation: action.operation, reason: action.reason }); + readMathBuildManifest(input.buildFile, input.root, path.join(input.root, 'out', 'main')); + const onStarted = (turnId: string) => { + // Some headless CLIs report a native ID only after starting. Persist that exact + // identity before publishing a turn; an empty ID cannot stand for a saved thread. + if (!session?.threadId) throw new Error('math_agent_session_binding_missing'); + if (research.threadId !== session.threadId) { + research.contextCheckpointBaseline = { threadId: session.threadId, notesDigest: checkpointNotesDigest() }; + research.threadId = session.threadId; save(); } - if (compacted && assignment && session!.threadId !== dispatchedContext?.threadId) { - dispatchedContexts.clear(); - releaseUnstartedTurn(assignment); continue; + emit('turn_started', { turnId, threadId: session.threadId, turn: research.turns, totalTurns: state.turns }); + }; + const repair = sourceFeedback(); + if (repair) research.check = undefined; + const currentContext = context(repair, feedbackCheck, feedbackFailures); + const responsibility = skillMode ? mathDigest(currentContext.instructions) : undefined; + const sameResponsibility = access.nativeContinuity !== false && responsibility !== undefined && + dispatched?.responsibility === responsibility && Boolean(research.threadId) && + dispatched.threadId === research.threadId && currentContext.continuationMessage !== undefined; + const continuation = sameResponsibility && !dispatched?.compaction; + const checkpointInstruction = research.threadId && research.contextCheckpoint?.threadId === research.threadId && !currentCheckpointNotesDigest() + ? contextCheckpointInstruction : undefined; + const compacted = sameResponsibility && dispatched?.compaction === 'completed' + ? compactedResearchDispatch(currentContext, { checkpointInstruction }) : undefined; + Object.assign(currentContext, compacted ?? finalizeResearchDispatch(currentContext, { continuation, checkpointInstruction })); + if (team?.reviewPlan && !deliveredApprovedPlan) { + const approval = state.cooperation?.planApproval; + currentContext.message = (team.mayStartProofWork + ? `The human approved plan version ${approval!.approvedVersion}. Begin proof research and coordinate the native team. Approved route:\n` + + nativeApprovalPlanBrief(state.cooperation!.tasks) + : 'This turn is for planning only. Read the frozen statement and publish one concrete route objective for each original theorem ' + + 'through theoremos_team publish_plan. You may include investigations for unresolved steps. Do not write proofs or dispatch agents yet. ' + + 'The workspace is read-only except .scratch. Save any planning notes there, then return as soon as the host records the proposal.') + '\n\n' + currentContext.message; + } + if (session && sessionInstructions !== currentContext.instructions) await close(); + if (!await beginTurn(currentContext, operation)) { + if (rebuildContext) continue; + break; + } + let candidate: ResearchCandidate | undefined; + let executionError: string | undefined; + const turnSession = session!; + try { + candidate = await modelTurn(started => modules.M1.execute(state.problem, currentContext, operation, worker, turnSession, signal, turnId => { + if (team?.reviewPlan && team.mayStartProofWork) deliveredApprovedPlan = true; + dispatched = responsibility === undefined ? undefined : { responsibility, threadId: turnSession.threadId }; + emit('context_dispatched', { mode: compacted ? 'compacted' : continuation ? 'continuation' : 'full', threadId: turnSession.threadId, + messageBytes: Buffer.byteLength(currentContext.message), messageDigest: mathDigest(currentContext.message), + compiledContentDigest: currentContext.manifest?.contentDigest }); + started(turnId); + }), onStarted); + } catch (error) { + signal.throwIfAborted(); + executionError = failureDetail(error, turnSession.lastError, turnSession.lastFailureDiagnostic); + if (!softSliceCheckpoint && !(team?.reviewPlan && planApprovalStatus(state) === 'pending') && + !recoverableResearchFailure(executionError) && !locallyStopped(executionError)) throw error; + candidate = { status: 'failed', worktree: worker.worktree, problemReceiptDigest: state.problem.receiptDigest, + operation, provenance: { workerId: worker.id, threadId: turnSession.threadId } }; + } + if (!candidate) break; + if (candidate.status !== 'failed' && currentCheckpointNotesDigest()) contextSchedulingCheckpoint = true; + if (softSliceCheckpoint || contextSchedulingCheckpoint) candidate = { ...candidate, status: 'checkpoint' }; + const lastInputTokens = session?.lastInputTokens; + sessionHasHistory = true; + const diagnostic = safeFailureDiagnostic(session?.lastFailureDiagnostic); + const turnError = executionError ?? failureDetail(session?.lastError, undefined, diagnostic); + if (team && !team.mayStartProofWork) { + // The planner's response never becomes a proof candidate. Stop its process before + // pausing the execution clock and wait in the host, outside any model turn. + await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, close, save, + deferred: reason => emit('proof_ready_freeze_deferred', { reason }) }); + team.leadWriterStopped(); state.writerProcess = undefined; save(); + if (planApprovalStatus(state) === 'pending') { + retries = 0; + emit('turn_checkpoint', { turn: research.turns, reason: 'math_team_plan_approval' }); + } else if (candidate.status === 'failed') await retryFailedTurn(turnError, diagnostic); + continue; + } + if (access.libraryCatalog && candidate.status !== 'failed') { + let request: LibraryInstallationRequested | undefined; + try { request = takeLibraryRequest(state.problem, worker.worktree, access.libraryCatalog); } + catch (error) { + emit('library_request_rejected', { reason: error instanceof Error ? error.message : String(error) }); + fs.rmSync(path.join(worker.worktree, 'LIBRARY_REQUEST.json'), { force: true }); } - let candidate: ResearchCandidate | undefined; - let executedTurnId: string | undefined; - let executionError: string | undefined; - const turnSession = session!; - try { - try { - candidate = await modelTurn(started => modules.M1.execute(state.problem, currentContext, operation, worker, turnSession, signal, turnId => { - executedTurnId = turnId; - if (assignment?.kind === 'task' && cooperation!.current(assignment)) { - const record = research as SolverWorkerState; - record.sessionRouteId = assignment.assignment.routeId; - record.sessionTaskContextDigest = taskContextDigest; - if (!continuation && contextBasis) assignment.assignment.researchBasis = contextBasis.publishedBasis; - save(); - } - if (responsibility !== undefined) { - dispatchedContexts.delete(responsibility); - dispatchedContexts.set(responsibility, { threadId: turnSession.threadId, - researchInputDigest: contextBasis?.dispatchDigest }); - if (dispatchedContexts.size > 32) dispatchedContexts.delete(dispatchedContexts.keys().next().value!); - } else dispatchedContexts.clear(); - emit('context_dispatched', { mode: compacted ? 'compacted' : taskSwitch ? 'task-switch' : continuation ? 'continuation' : 'full', threadId: turnSession.threadId, - messageBytes: Buffer.byteLength(currentContext.message), messageDigest: mathDigest(currentContext.message), - compiledContentDigest: currentContext.manifest?.contentDigest }); - started(turnId); - }), assignment, onStarted, contextBasis?.publishedBasis ?? contextBasis?.basis); - } catch (error) { - signal.throwIfAborted(); - executionError = failureDetail(error, turnSession.lastError, turnSession.lastFailureDiagnostic); - if (!softSliceCheckpoint && !recoverableResearchFailure(executionError) && !locallyStopped(executionError)) throw error; - // The writer must stop before the ordinary saved-source checks and delivery run. - candidate = { status: 'failed', worktree: worker.worktree, problemReceiptDigest: state.problem.receiptDigest, - operation, provenance: { workerId: worker.id, threadId: turnSession.threadId } }; - } - if (candidate && (planningCheckpoint || cooperativeCheckpoint || softSliceCheckpoint)) - candidate = { ...candidate, status: 'checkpoint' }; - if (!candidate) { - if (assignment && dispatchAllowed() && budget().remainingMs > 0 && !signal.aborted) { - releaseUnstartedTurn(assignment); await rotateSession('context'); continue; - } - break; - } - await cooperation?.pulse(worker.id); - // The writer may publish its final control event and return before the polling timer fires. - if (candidate.status !== 'failed' && currentCheckpointNotesDigest()) { - contextSchedulingCheckpoint = true; - candidate = { ...candidate, status: 'checkpoint' }; + if (request) { + if (skillMode) { + await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, + close, save, deferred: reason => emit('proof_ready_freeze_deferred', { reason }) }); + if (team) { team.leadWriterStopped(); state.writerProcess = undefined; save(); } } - } finally { cooperation?.deactivate(worker); } - const lastInputTokens = session?.lastInputTokens; - sessionHasHistory = true; - const diagnostic = safeFailureDiagnostic(session?.lastFailureDiagnostic); - const turnError = executionError ?? failureDetail(session?.lastError, undefined, diagnostic); - if (access.libraryCatalog && candidate.status !== 'failed') { - let request: LibraryInstallationRequested | undefined; - try { - if (assignment?.kind === 'task' && (isFeasibilityReview(assignment.task) || isFinalCandidateReview(assignment.task)) && - fs.existsSync(path.join(worker.worktree, 'LIBRARY_REQUEST.json'))) throw new Error('math_library_request_fixed_review'); - request = takeLibraryRequest(state.problem, worker.worktree, access.libraryCatalog); - } - catch (error) { - emit('library_request_rejected', { reason: error instanceof Error ? error.message : String(error) }); - fs.rmSync(path.join(worker.worktree, 'LIBRARY_REQUEST.json'), { force: true }); - } - if (request) { - if (skillMode) { - await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, - close, save, deferred: reason => emit('proof_ready_freeze_deferred', { reason }) }); - if (team) { team.leadWriterStopped(); state.writerProcess = undefined; save(); } - } - else await close(); - access.assertHarnessCurrent?.(); - if (access.researchSkill) assertMathAgentSkillsCurrent([access.researchSkill]); - if (!sourceFeedback()) commitSolverSources(state.problem, worker.worktree); - emit('library_installation_requested', { names: request.request.names, catalogDigest: request.request.catalogDigest }); - throw request; - } - } - if (candidate.worktree !== worker.worktree || candidate.problemReceiptDigest !== state.problem.receiptDigest || - candidate.operation !== action.operation || candidate.provenance.workerId !== worker.id) - throw new Error('math_candidate_identity_changed'); - if (assignment && cooperation && candidate.provenance.threadId === turnSession.threadId) - await cooperation.deliverCompletedGuidance(worker, assignment, - completedGuidanceDecisions(turnSession, executedTurnId, candidate.status)); - if (await proofLifecycle?.settleTurn(assignment, candidate, operation, turnSession)) continue; - const singleSubmission = singleHandoff?.takeSubmission(); - if (singleSubmission || skillMode) { - // The runtime has settled the turn and stopped new requests. Reap all remaining - // writer processes before the ordinary source freeze and independent host check. - await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, close, save, - deferred: reason => emit('proof_ready_freeze_deferred', { ...singleSubmission, reason }) }); - if (team) { team.leadWriterStopped(); state.writerProcess = undefined; save(); } + else await close(); access.assertHarnessCurrent?.(); if (access.researchSkill) assertMathAgentSkillsCurrent([access.researchSkill]); - // submitted is a delivery status, never proof acceptance. The usual M2 check below - // fingerprints the stopped writer's actual sources and verifies every original target. - if (singleSubmission) candidate = { ...candidate, status: 'completed' }; + if (!sourceFeedback()) commitSolverSources(state.problem, worker.worktree); + emit('library_installation_requested', { names: request.request.names, catalogDigest: request.request.catalogDigest }); + throw request; } - // Closing can yield to a plan edit; check ownership after the writer has stopped. - if (candidate.status === 'failed' || planningCheckpoint) await close(); - if (assignment && cooperation && !cooperation.current(assignment)) { - const commit = sourceFeedback() ? git(worker.worktree, ['rev-parse', 'HEAD']) : commitSolverSources(state.problem, worker.worktree); - if (assignment.kind === 'task' || assignment.kind === 'lead') await cooperation.deliver(worker, assignment, commit); - else await exclusiveCheck(() => cooperation.deliver(worker, assignment, commit)); - emit('assignment_superseded', { commit }); - await rotateSession('context'); - continue; - } - research.lastInputTokens = lastInputTokens ?? research.lastInputTokens; - research.candidate = candidate; - const turn = cooperation && assignment && candidate.status === 'interrupted' ? 'checkpoint' : candidate.status; - if (!['completed', 'failed', 'checkpoint'].includes(turn)) break; - if (turn !== 'failed') { retries = 0; nativeContextRecovery = undefined; } - if (turn === 'checkpoint') emit('turn_checkpoint', { turn: research.turns, - ...(team?.leadCompletionCheckpoint ? { reason: 'math_team_completion_checkpoint' } : - team?.leadAdoptionCheckpoint ? { reason: 'math_team_adoption_checkpoint' } : - planningCheckpoint ? { reason: 'math_initial_planning_limit' } : - softSliceCheckpoint ? { reason: 'math_soft_slice_checkpoint' } : - contextSchedulingCheckpoint ? { reason: 'math_context_scheduling_checkpoint' } : - proofHandoffCheckpoint ? { reason: 'math_proof_handoff_checkpoint' } : - finalReviewHandoffCheckpoint ? { reason: 'math_final_review_handoff_checkpoint' } : - cooperativeCheckpoint ? { reason: 'math_cooperative_scheduling_checkpoint' } : {}) }); - if (turn === 'failed') emit('turn_failed', { reason: researchFailureReason(turnError), ...(diagnostic ? { diagnostic } : {}) }); - const sourceError = sourceFeedback(); - if (sourceError) { - if (team?.archive.completionRequested) { - emit('team_completion_rejected', { reason: sourceError, requestedAt: team.archive.completionRequested.at }); - team.archive.completionRequested = undefined; - } - research.check = undefined; - if (assignment) cooperation!.rejected(assignment, sourceError, undefined, turn !== 'completed'); - save(); emit('source_rejected', { reason: sourceError }); - if (turn === 'failed' && turnError && !locallyStopped(turnError)) { - if (!recoverableResearchFailure(turnError)) throw new Error(researchFailureReason(turnError), { cause: turnError }); - // Independent work has no task rejection to bound a corrective cycle after a request failure. - if (!cooperation) throw new Error(sourceError, { cause: turnError }); - } - // A deterministic saved-source rejection needs a corrective turn even when the native - // request failed or yielded. The next dispatch carries sourceFeedback; no invalid source - // is committed or checked, and no host repair modifies the writer's saved work. - continue; + } + if (candidate.worktree !== worker.worktree || candidate.problemReceiptDigest !== state.problem.receiptDigest || + candidate.operation !== action.operation || candidate.provenance.workerId !== worker.id) + throw new Error('math_candidate_identity_changed'); + const singleSubmission = singleHandoff.takeSubmission(); + if (singleSubmission || skillMode) { + // The runtime has settled the turn and stopped new requests. Reap all remaining + // writer processes before the ordinary source freeze and independent host check. + await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, close, save, + deferred: reason => emit('proof_ready_freeze_deferred', { ...singleSubmission, reason }) }); + if (team) { team.leadWriterStopped(); state.writerProcess = undefined; save(); } + access.assertHarnessCurrent?.(); + if (access.researchSkill) assertMathAgentSkillsCurrent([access.researchSkill]); + // submitted is a delivery status, never proof acceptance. The usual M2 check below + // fingerprints the stopped writer's actual sources and verifies every original target. + if (singleSubmission) candidate = { ...candidate, status: 'completed' }; + } + if (candidate.status === 'failed') await close(); + research.lastInputTokens = lastInputTokens ?? research.lastInputTokens; + research.candidate = candidate; + const turn = candidate.status; + if (!['completed', 'failed', 'checkpoint'].includes(turn)) break; + if (turn !== 'failed') { retries = 0; nativeContextRecovery = undefined; } + if (turn === 'checkpoint') emit('turn_checkpoint', { turn: research.turns, + ...(team?.leadCompletionCheckpoint ? { reason: 'math_team_completion_checkpoint' } : + team?.leadAdoptionCheckpoint ? { reason: 'math_team_adoption_checkpoint' } : + softSliceCheckpoint ? { reason: 'math_soft_slice_checkpoint' } : + contextSchedulingCheckpoint ? { reason: 'math_context_scheduling_checkpoint' } : {}) }); + if (turn === 'failed') emit('turn_failed', { reason: researchFailureReason(turnError), ...(diagnostic ? { diagnostic } : {}) }); + const sourceError = sourceFeedback(); + if (sourceError) { + if (team?.archive.completionRequested) { + emit('team_completion_rejected', { reason: sourceError, requestedAt: team.archive.completionRequested.at }); + team.archive.completionRequested = undefined; } - if (skillMode) { - await team?.flushAdoptions(); - const { commit, wholeProofReady } = await skillProofLifecycle!.freezeSources(); - if (team?.archive.completionRequested) { - const requested = team.archive.completionRequested; - team.archive.completionRequested = undefined; - emit('team_completion_frozen', { commit, wholeProofReady, requestedAt: requested.at }); save(); - } - // An unfinished research turn can publish useful helpers without repeatedly - // compiling every original hole. Ordinary diagnostics remain advisory. - if (!wholeProofReady) { - research.check = undefined; - save(); emit('research_saved', { commit, originalProblemAcceptance: 'not-assessed' }); - if (turn === 'failed') await retryFailedTurn(turnError, diagnostic); - continue; - } + research.check = undefined; + save(); emit('source_rejected', { reason: sourceError }); + if (turn === 'failed' && turnError && !locallyStopped(turnError)) { + if (!recoverableResearchFailure(turnError)) throw new Error(researchFailureReason(turnError), { cause: turnError }); + throw new Error(sourceError, { cause: turnError }); } - if (cooperation && assignment?.kind === 'task' && turn === 'checkpoint' && - !['research', 'sketch'].includes(assignment.task.kind) && (softSliceCheckpoint || contextSchedulingCheckpoint || - cooperativeCheckpoint && hasTaskConnectionCheck(assignment.task, assignment.assignment))) { - // A yielded connection or context handoff is not an unfinished proof submission. - // settleTurn above still handles a published ready record through the writer-freeze barrier first. - const commit = commitSolverSources(state.problem, worker.worktree); - const reason = softSliceCheckpoint || contextSchedulingCheckpoint ? 'context' : 'connection'; - recordAdvisoryOutput(true); - await cooperation.retainContextDraft(worker, assignment, commit, reason); - cooperation.interrupted(worker, assignment); - emit(reason === 'context' ? 'context_checkpoint_saved' : 'connection_checkpoint_saved', - { threadId: turnSession.threadId, taskId: assignment.task.id, commit }); - save(); continue; + // A deterministic saved-source rejection needs a corrective turn even when the native + // request failed or yielded. The next dispatch carries sourceFeedback; no invalid source + // is committed or checked, and no host repair modifies the writer's saved work. + continue; + } + if (skillMode) { + await team?.flushAdoptions(); + const { commit, wholeProofReady } = await skillProofLifecycle!.freezeSources(); + if (team?.archive.completionRequested) { + const requested = team.archive.completionRequested; + team.archive.completionRequested = undefined; + emit('team_completion_frozen', { commit, wholeProofReady, requestedAt: requested.at }); save(); } - if (cooperation && assignment && turn === 'failed' && - ((assignment.kind !== 'task' && assignment.kind !== 'lead') || - (assignment.kind === 'task' && ['research', 'sketch'].includes(assignment.task.kind)))) { - if (assignment.kind === 'task') { - const commit = commitSolverSources(state.problem, worker.worktree); - recordAdvisoryOutput(false); - await cooperation.deliver(worker, assignment, commit, true, 'request-failure'); - } else cooperation.interrupted(worker, assignment); - await retryFailedTurn(turnError, diagnostic); + // An unfinished research turn can publish useful helpers without repeatedly + // compiling every original hole. Ordinary diagnostics remain advisory. + if (!wholeProofReady) { + research.check = undefined; + save(); emit('research_saved', { commit, originalProblemAcceptance: 'not-assessed' }); + if (turn === 'failed') await retryFailedTurn(turnError, diagnostic); continue; } - setWorkerResearchPhase(state, research, 'checking'); save(); - const previousCheck = research.check; - const previousFailures = research.failures; - let checkWholeRequired = true; - let savedTaskProof = false; - let savedPlan = false; - try { - if (cooperation && assignment) { - const commit = commitSolverSources(state.problem, worker.worktree); - recordAdvisoryOutput(turn === 'checkpoint'); - const deliver = () => cooperation.deliver(worker, assignment, commit, turn !== 'completed', - turn === 'failed' ? 'request-failure' : proofHandoffCheckpoint ? 'proof-handoff' : - finalReviewHandoffCheckpoint ? 'final-review-handoff' : - cooperativeCheckpoint ? 'scheduling-checkpoint' : 'checkpoint'); - const delivery = assignment.kind === 'task' || assignment.kind === 'lead' ? await deliver() : await exclusiveCheck(deliver); - if (assignment.kind === 'lead' && turn === 'checkpoint') await cooperation.startInitialTasks(); - research.check = delivery.check; - savedTaskProof = delivery.check?.passed === true; - savedPlan = delivery.savedPlan === true; - checkWholeRequired = delivery.checkWhole; - if (!checkWholeRequired) save(); - } - if (checkWholeRequired) { - if (skillProofLifecycle) await skillProofLifecycle.checkFrozenWholeProof(candidate); - else await exclusiveCheck(() => checkWhole(candidate)); - } - } finally { setWorkerResearchPhase(state, research, 'running'); save(); } - feedbackCheck = previousCheck; feedbackFailures = previousFailures; - if (!winner && turn === 'failed') { - if ((!savedTaskProof && !savedPlan) || researchFailureReason(turnError) === 'math_model_context_window_exceeded') - await retryFailedTurn(turnError, diagnostic); - else if (recoverableResearchFailure(turnError)) { - // Accepted saved work can continue after repairing the session. - retries = 0; - await rotateSession('request'); - emit('worker_recovered', { reason: researchFailureReason(turnError), - ...(savedTaskProof ? { savedTaskProof: true } : {}), ...(savedPlan ? { savedPlan: true } : {}) }); - } else throw new Error(researchFailureReason(turnError), { cause: turnError }); - } } - } catch (error) { - if (!signal.aborted) { - errors.push(error); - if (error instanceof VerificationCheckpointError) emit('worker_checkpoint', { reason: error.message, key: error.checkpoint.key }); - else if (error instanceof LibraryInstallationRequested) emit('worker_checkpoint', { reason: error.message }); - else { - research.error = error instanceof Error ? error.message : 'math_worker_failed'; - const verification = verifierFailureDiagnostic(error) ?? (research.error === 'math_verifier_unavailable' - ? new VerifierFailureError({ stage: 'worker-boundary' }, error).diagnostic : undefined); - if (verification) { research.verifierFailure = verification; state.verifierFailure = verification; } - emit('worker_failed', { reason: research.error, ...(verification ? { verification } : {}), - ...(error instanceof MathGitError ? { git: error.diagnostic } : {}) }); - } - if (error instanceof LibraryInstallationRequested || !parallel || (cooperation && worker.id === input.workers[0].id && research.error !== 'math_model_context_capacity_blocked') || - (error instanceof VerificationCheckpointError || error instanceof Error && error.message === 'math_verifier_unavailable')) abort(); + research.phase = 'checking'; save(); + const previousCheck = research.check; + const previousFailures = research.failures; + try { + if (skillProofLifecycle) await skillProofLifecycle.checkFrozenWholeProof(candidate); + else await exclusiveCheck(() => checkWhole(candidate)); + } finally { research.phase = 'running'; save(); } + feedbackCheck = previousCheck; feedbackFailures = previousFailures; + if (!winner && turn === 'failed') await retryFailedTurn(turnError, diagnostic); + } + } catch (error) { + if (!signal.aborted) { + errors.push(error); + if (error instanceof VerificationCheckpointError) emit('worker_checkpoint', { reason: error.message, key: error.checkpoint.key }); + else if (error instanceof LibraryInstallationRequested) emit('worker_checkpoint', { reason: error.message }); + else { + research.error = error instanceof Error ? error.message : 'math_worker_failed'; + const verification = verifierFailureDiagnostic(error) ?? (research.error === 'math_verifier_unavailable' + ? new VerifierFailureError({ stage: 'worker-boundary' }, error).diagnostic : undefined); + if (verification) { research.verifierFailure = verification; state.verifierFailure = verification; } + emit('worker_failed', { reason: research.error, ...(verification ? { verification } : {}), + ...(error instanceof MathGitError ? { git: error.diagnostic } : {}) }); } - } finally { - signal.removeEventListener('abort', cancel); - try { await close(); } catch { /* close records each failure once, including cancellation. */ } - if (reservedTurn) { state.turns--; if (parallel) research.turns--; } - if (unstarted) cooperation?.release(worker, unstarted); - cooperation?.stopped(worker, (research as SolverWorkerState).error); - if (reservedTurn) cooperation?.settleTurn(worker); - if (parallel) research.phase = 'finished'; - updateUsage(); save(); + abort(); } - })); + } finally { + signal.removeEventListener('abort', cancel); + try { await close(); } catch { /* close records each failure once, including cancellation. */ } + if (reservedTurn) { state.turns--; } + updateUsage(); save(); + } input.signal.throwIfAborted(); // Quarantine is the actionable failure even if ordinary session cleanup also failed. const unconfirmedStop = errors.find(error => error instanceof Error && @@ -1928,6 +910,6 @@ export async function runResearchWorkers(input: { errors.find(error => error instanceof VerificationCheckpointError) ?? errors[0]; return winner; } finally { - try { await team?.close(); await cooperation?.stop(); } finally { input.signal.removeEventListener('abort', abort); } + try { await team?.close(); } finally { input.signal.removeEventListener('abort', abort); } } } diff --git a/src/solver/researchGuidance.ts b/src/solver/researchGuidance.ts index b7aa1ad0..72d04c4d 100644 --- a/src/solver/researchGuidance.ts +++ b/src/solver/researchGuidance.ts @@ -5,7 +5,7 @@ import { mathematicsRuntimeInstruction } from '../math/mathRuntimeEnvironment'; import { mathToolsInstruction } from '../math/mathTools'; import { assertMathAgentSkillsCurrent } from '../runtime/agentSkills'; import type { SolverRunState } from './archive'; -import { compileContextSections, compileTaskContext, portfolioContextSections, type ContextSection } from './contextCompiler'; +import { compileContextSections, compileTaskContext, type ContextSection } from './contextCompiler'; import { continuationContextSection, readContinuationSnapshot } from './continuationInput'; import { solverProofFeedback } from './feedback'; import type { ContextAccess, ContextBundle, ResearchDispatchOptions } from './modules/context'; @@ -59,7 +59,7 @@ export function buildCommonResearchContext(problem: SolverProblem, state: Readon const action = access.assignment, cooperation = state.cooperation; const readOnly = action?.kind === 'lead' || action?.kind === 'review' || action?.kind === 'task' && (isFeasibilityReview(action.task) || isFinalCandidateReview(action.task)); - const mandatory: ContextSection[] = [...(action?.kind === 'review' ? [] : portfolioContextSections(state)), + const mandatory: ContextSection[] = [ { id: 'common-guidance-identity', kind: 'assignment', text: 'Frozen shared mathematical skill:\n' + canonicalMathJson(state.commonResearchSkill) }, { id: 'saved-research', kind: 'sources', text: 'Read current owned sources and worktree-root RESEARCH.md before continuing. ' + diff --git a/src/solver/researchObservation.ts b/src/solver/researchObservation.ts deleted file mode 100644 index 9c3cf8c0..00000000 --- a/src/solver/researchObservation.ts +++ /dev/null @@ -1,60 +0,0 @@ -import path from 'node:path'; -import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; -import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; -import { appendDeliveryEvent, MAX_RESEARCH_NOTES_BYTES } from './deliveries'; -import { prepareResearchDelivery, ResearchAdmissionError, type ResearchAdmissionScope } from './researchAdmission'; -import { researchPublicationNotes } from './researchPublication'; -import { assignmentDeliveryFile, taskVersion, type TaskAssignment, type TaskRecord } from './tasks'; - -/** Shell-side preflight and one append; the host independently admits, snapshots and scopes the event. */ -export function queueResearchObservation(input: { - worktree: string; finding: unknown; probes?: readonly string[]; snapshotSources?: boolean; -}) { - const worktree = path.resolve(input.worktree); - assertMathCanonicalPath(worktree); - const local = (file: string) => { - const resolved = path.resolve(worktree, file); - if (!isMathPathWithin(worktree, resolved) || resolved === worktree) throw new Error('math_observation_path_outside_worktree'); - assertMathCanonicalPath(resolved); - return resolved; - }; - const context = JSON.parse(readMathText(local('COOPERATION.json'), 32_000_000)); - const delivery = context.researchDelivery as { - assignment: TaskAssignment; problemReceiptDigest: string; environmentDigest: string; - projectRelative: string; ownedFiles: string[]; - } | undefined; - if (!delivery?.assignment || !delivery.problemReceiptDigest || !delivery.environmentDigest || !Array.isArray(context.tasks)) - throw new Error('math_observation_no_current_assignment'); - const source = (context.tasks as TaskRecord[]).find(node => node.task.id === delivery.assignment.taskId); - if (!source || taskVersion(source.task) !== delivery.assignment.taskDigest) - throw new Error('math_observation_assignment_changed'); - const scope: ResearchAdmissionScope = { source: source.task, assignment: delivery.assignment, - identity: { problemReceiptDigest: delivery.problemReceiptDigest, environmentDigest: delivery.environmentDigest }, - tasks: context.tasks, deliveries: context.deliveries, ...(context.nextChecks ? { nextChecks: context.nextChecks } : {}), - ...(context.proofSearchRecords ? { proofSearchRecords: context.proofSearchRecords } : {}) }; - const object = typeof input.finding === 'object' && input.finding !== null && !Array.isArray(input.finding) - ? input.finding as Record : undefined; - const { guidanceDecisions, ...finding } = object ?? {}; - const admission = prepareResearchDelivery({ kind: 'event', value: object ? finding : input.finding }, scope); - if (admission.status === 'rejected') throw new ResearchAdmissionError(admission); - const probes = input.probes?.map(file => ({ source: path.relative(worktree, local(file)), - code: readMathText(local(file), MAX_RESEARCH_NOTES_BYTES) })); - researchPublicationNotes(admission.finding, probes); - let sources: Record | undefined; - if (input.snapshotSources) { - if (!Array.isArray(delivery.ownedFiles) || typeof delivery.projectRelative !== 'string') - throw new Error('math_observation_source_context_missing'); - sources = Object.fromEntries(delivery.ownedFiles.map(file => [file, - readMathText(local(path.join(delivery.projectRelative, file)), MAX_RESEARCH_NOTES_BYTES)])); - if (Object.values(sources).reduce((bytes, source) => bytes + Buffer.byteLength(source), 0) > MAX_RESEARCH_NOTES_BYTES) - throw new Error('math_observation_sources_too_large'); - } - const value = { kind: 'research', finding: admission.finding, guidanceDecisions, ...(probes ? { probes } : {}), ...(sources ? { sources } : {}) }; - const file = assignmentDeliveryFile(delivery.assignment); - appendDeliveryEvent(worktree, file, value); - return { status: 'queued', authority: 'advisory-unverified', - submissionId: mathDigest(canonicalMathJson({ file, value })), file, - taskId: delivery.assignment.taskId, taskDigest: delivery.assignment.taskDigest, - retainedProbes: probes?.length ?? 0, snapshotSources: Boolean(sources), - receipt: 'Read the host deliveryReceipts in COOPERATION.json; queued is not host acceptance.' }; -} diff --git a/src/solver/researchRetirement.ts b/src/solver/researchRetirement.ts new file mode 100644 index 00000000..159f26af --- /dev/null +++ b/src/solver/researchRetirement.ts @@ -0,0 +1,13 @@ +import type { SolverRunState } from './archive'; + +export const legacyCollaborationRetired = 'math_legacy_collaboration_retired: resume with the historical TheoremOS revision that created this run.'; + +/** Archive readers accept historical research state. A writer only accepts solo or native team state. */ +export function assertActiveResearchState(state: Pick) { + const nativeTeam = state.agentTeam?.transport === 'native-agent-control'; + if (state.portfolioExploration || (state.workerCount ?? 1) > 1 || state.workers?.length || + state.researchDelegation?.mode === 'read-only' || + (state.researchDelegation?.mode === 'team' || state.agentTeam || state.cooperation || state.planApproval) && !nativeTeam) + throw new Error(legacyCollaborationRetired); +} diff --git a/src/solver/researchToolGuide.ts b/src/solver/researchToolGuide.ts index 3f855d64..a2b0e9f8 100644 --- a/src/solver/researchToolGuide.ts +++ b/src/solver/researchToolGuide.ts @@ -1,5 +1,4 @@ import path from 'node:path'; -import type { AgentTeamTransport } from './agentTeamTool'; import { DECLARATION_INDEX_FILE } from './declarationIndex'; import type { ContextAccess } from './modules/context'; import type { SolverProblem } from './problem'; @@ -9,9 +8,6 @@ const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; export const researchToolCommand = (root: string, tools?: string) => `bun ${quote(tools ?? path.join(root, 'bin/math.ts'))}`; -export const checkpointCommand = (command: string, worktree: string, file: string, requestId: string) => - `${command} checkpoint --worktree ${quote(worktree)} --log ${quote(file)} --request-id ${quote(requestId)}`; - export const longCommandGuidance = 'For a long calculation, record the inputs, print progress and save completed batches in .scratch/tmp. Use unbuffered output for Python (python3 -u). ' + 'With native exec_command, keep the session ID returned after a short yield_time_ms. Poll with write_stdin and empty chars. ' + @@ -22,7 +18,7 @@ export const longCommandGuidance = export function buildResearchToolGuide(problem: Pick, access: Pick, environmentDigest: string, - teamTransport?: AgentTeamTransport) { + team = false) { const command = researchToolCommand(access.root, access.tools); const help = new ResearchToolHelpBuilder(); if (access.assignment?.kind === 'lead') help.section('Lead plan submission', @@ -33,8 +29,7 @@ export function buildResearchToolGuide(problem: Pick file.endsWith('.lean') && !Object.hasOwn(problem.frozenFiles ?? {}, file))); const file = problem.targets.find(target => editable.has(target.proofPath))?.proofPath ?? editable.values().next().value; const leanCheckCommand = file && `${command} check-lean --worktree ${quote(access.worktree)} --file ${quote(file)} --timeout-seconds 0`; - const report = teamTransport === 'native-agent-control' ? 'native send_message' : - teamTransport === 'host-tools' ? 'theoremos_team ' + (access.teamRole?.role === 'worker' ? 'progress' : 'message') : undefined; + const report = team ? 'native send_message' : undefined; const longCommandSummary = help.section('long-commands', longCommandGuidance + '\n\n' + 'Start a foreground calculation and get control back while it runs.\n' + 'exec_command ' + JSON.stringify({ cmd: 'python3 -u .scratch/tmp/experiment.py', workdir: access.worktree, @@ -47,7 +42,7 @@ export function buildResearchToolGuide(problem: Pick; -const assignmentTask = (assignment?: CooperativeAction) => - assignment?.kind === 'task' ? assignment.task.id : - assignment?.kind === 'backtranslate' || assignment?.kind === 'statement-review' ? assignment.taskId : undefined; - -type TurnUsageScope = { reported: boolean; incomplete: boolean; initialPlanning: boolean; +type TurnUsageScope = { reported: boolean; incomplete: boolean; taskId?: string; turnId?: string; upstreamRequests: boolean; nativeTurnTotals: boolean; finished: boolean; reportedUsage?: ModelRequestUsage }; @@ -29,16 +23,16 @@ export class ResearchUsage { constructor(private input: { state: SolverRunState; research: Pick; - maxTotalTokens: number; signal: AbortSignal; remainingMs: () => number; + signal: AbortSignal; remainingMs: () => number; changed: () => void; emit: (event: string, details: Record) => void; }) {} resetTurn() { this.stopReason = undefined; } /** Native compaction can make model requests between proof turns. It is maintenance, not a solver turn. */ - beginMaintenance(assignment?: CooperativeAction) { + beginMaintenance() { if (this.active) throw new Error('math_model_maintenance_during_turn'); - this.active = { reported: false, incomplete: false, initialPlanning: false, taskId: assignmentTask(assignment), + this.active = { reported: false, incomplete: false, upstreamRequests: this.requestSessionId === this.sessionId && this.sessionId !== undefined, nativeTurnTotals: Boolean(this.boundSession && this.boundSession.id === this.sessionId && this.boundSession.nativeTurnTotals), finished: false }; @@ -56,15 +50,14 @@ export class ResearchUsage { maintenance.finished = true; this.active = undefined; this.input.changed(); } - begin(assignment?: CooperativeAction, taskId = assignmentTask(assignment)) { - const { state, research, maxTotalTokens } = this.input; + begin(taskId?: string) { + const { research } = this.input; research.usageAccounting!.startedTurns++; research.usageAccounting!.pending = true; this.active = { reported: false, incomplete: false, taskId, upstreamRequests: this.requestSessionId === this.sessionId && this.sessionId !== undefined, nativeTurnTotals: Boolean(this.boundSession && this.boundSession.id === this.sessionId && this.boundSession.nativeTurnTotals), - finished: false, - initialPlanning: assignment?.kind === 'lead' && state.cooperation?.tasks.length === 0 && maxTotalTokens > 0 }; + finished: false }; if (!this.active.upstreamRequests) { this.nativeTurns.push(this.active); if (research.requestUsageAccounting) { @@ -183,40 +176,27 @@ export class ResearchUsage { } private rejectRequest(sessionId: string, reason: ModelRequestStopReason): ModelRequestAdmission { - if (this.sessionId === sessionId && this.active) { - const changed = this.stopReason !== reason; - this.stopReason = reason; - if (changed && reason === 'math_initial_planning_limit') this.input.emit('planning_budget_stopped', { - reason, maxPlanningTokens: Math.max(1, Math.floor(this.input.maxTotalTokens / 4)), maxRequests: 2, - reportedTotalTokens: reportedTotalTokens(this.input.research.usage), - startedRequests: this.input.research.requestUsageAccounting?.startedRequests ?? 0, - }); - } + if (this.sessionId === sessionId && this.active) this.stopReason = reason; return { allowed: false, reason }; } private admitRequest(sessionId: string, identity?: ModelRequestIdentity): ModelRequestAdmission { - const { state, research, signal, remainingMs, maxTotalTokens, changed } = this.input; + const { state, research, signal, remainingMs, changed } = this.input; if (!modelDispatchAllowed(state.tokenBudget!)) return this.rejectRequest(sessionId, state.tokenBudget!.reason!); if (this.sessionId !== sessionId || !this.active || signal.aborted || remainingMs() <= 0) return this.rejectRequest(sessionId, 'math_model_request_stopped'); - const requests = research.requestUsageAccounting; - if (this.active.initialPlanning && state.cooperation?.tasks.length === 0 && requests && (requests.startedRequests >= 2 || - (reportedTotalTokens(research.usage) ?? 0) >= Math.max(1, Math.floor(maxTotalTokens / 4)))) - // Only settled requests can yield a checkpoint with complete accounting. - return this.rejectRequest(sessionId, requests.pendingRequests ? 'math_model_request_stopped' : 'math_initial_planning_limit'); initializeRequestUsageAccounting(research); - const turn = this.active, taskId = turn.taskId, requestId = identity?.requestId ?? randomUUID(); - const settle = beginRequestUsage(research, { ...identity, requestId, runId: state.runId, sessionId, taskId }); + const turn = this.active, taskId = turn.taskId; + const settle = beginRequestUsage(research, { ...identity, runId: state.runId, sessionId, taskId }); let settled = false; changed(); return { allowed: true, settle: receipt => { if (settled) return; settled = true; const before = research.usage; - settle(receipt); + const status = settle(receipt); if (taskId) attributeTaskUsage(state, taskId, before, research.usage); - if (research.requestUsageAccounting!.receipts?.find(item => item.requestId === requestId)?.status !== 'reported') turn.incomplete = true; + if (status !== 'reported') turn.incomplete = true; changed(); } }; } diff --git a/src/solver/run.ts b/src/solver/run.ts index 0eb86253..e508318f 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -23,16 +23,14 @@ import { readSolverRunState, writeSolverRunState, type SolverRunState } from './ import { directSolverModules, configuredSolverModules, solverModuleConfiguration, solverMethodDigest, type SolverModules } from './modules'; import { configurableSolverModules } from './modules/custom'; import { researchModulePlanSchema, type ResearchModulePlan } from './modules/policy'; -import { MAX_RESEARCH_WORKERS, researchWorkers } from './modules/organization'; -import { runResearchWorkers, type WorkerAccess } from './research'; -import { validateNativeDelegation } from '../runtime/nativeDelegation'; +import { runResearchLead, type WorkerAccess } from './research'; import { MIN_TEAM_AGENTS, MAX_TEAM_AGENTS } from './teamCapacity'; import { getPreferredAgentTeamProfiles } from './agentTeamProfiles'; import { readPersonalExperts } from './personalExperts'; import { evaluateSolverProof } from './evaluation'; import { solverProofIsCurrent } from './modules/evidence'; import { checkCodexProviderConnectivity } from '../runtime/codexConnectivity'; -import { aggregateUsage, buildTokenBudget } from './usageBudget'; +import { buildTokenBudget } from './usageBudget'; import { selectedDeepSeekProfile } from '../runtime/deepseek'; import { WESTLAKE_NATIVE_TEAM_UNSUPPORTED, selectedWestlakeProfile } from '../runtime/westlake'; import { selectedSub2apiProfile } from '../runtime/sub2api'; @@ -46,8 +44,8 @@ import { readLibraryCatalog } from './libraryCatalog'; import { readLeanTaskReceipt } from '../math/leanTask'; import { copyContinuationSnapshot, freezeContinuationInput, readContinuationInput, readContinuationSnapshot, type ContinuationSnapshot } from './continuationInput'; -import { seedSolverContinuation, seedSingleSolverContinuation } from './continuationSeed'; -import type { TaskProof } from './cooperativeProof'; +import { seedSingleSolverContinuation } from './singleContinuationSeed'; +import { assertActiveResearchState, legacyCollaborationRetired } from './researchRetirement'; import { verifierFailureDiagnostic } from './verifierFailure'; import { generateSolverExplanations, type SolverExplanations } from './automaticExplanations'; import { readMathAgentSkill } from '../runtime/agentSkills'; @@ -60,21 +58,20 @@ import { planMathAgentSession } from '../runtime/agentSessionPlan'; import { SingleSolverProofHandoff } from './singleSolverProofHandoff'; import { assertAgentTeamProcessesStopped } from './agentTeam'; import { buildAgentTeamContributions } from './agentTeamContributions'; -import { configurePortfolioExploration, portfolioUsageRecords, PORTFOLIO_MAX_SECONDS, runPortfolioExploration } from './portfolioExploration'; const runSummary = (state: SolverRunState | undefined) => { - const workers = state?.workers ?? (state?.agentTeam ? [ + const workers = state?.agentTeam ? [ { ...state, id: 'lead', role: 'lead', turns: state.usageAccounting?.startedTurns ?? 0 }, ...state.agentTeam.workers, - ] : undefined); + ] : undefined; return { turns: state?.turns, dispatchCounts: state?.dispatchCounts, ...(state?.verifierFailure ? { verifierFailure: state.verifierFailure } : {}), - usage: state?.teamUsage ?? (state && portfolioUsageRecords(state).length - ? aggregateUsage([...(state.workers ?? [state]), ...portfolioUsageRecords(state)]) : state?.usage), tokenBudget: state?.tokenBudget, + usage: state?.teamUsage ?? state?.usage, tokenBudget: state?.tokenBudget, workers: workers?.map(worker => ({ id: worker.id, role: worker.role, turns: worker.turns, dispatchCounts: worker.dispatchCounts, usage: worker.usage, error: worker.error })) }; }; -export async function runSolver(args: string[], root: string, customModules?: SolverModules, hostSignal?: AbortSignal): Promise { +export async function runSolver(args: string[], root: string, customModules?: SolverModules, hostSignal?: AbortSignal, + entryPoint: 'internal' | 'cli' | 'historical-component' = 'internal'): Promise { const { values } = parseArgs({ args, options: { workspace: { type: 'string' }, 'receipt-file': { type: 'string' }, 'task-file': { type: 'string' }, output: { type: 'string' }, 'build-manifest': { type: 'string' }, model: { type: 'string', default: 'deepseek-flash' }, @@ -91,40 +88,55 @@ export async function runSolver(args: string[], root: string, customModules?: So 'knowledge-base': { type: 'string' }, 'continuation-manifest': { type: 'string' }, 'library-catalog': { type: 'string' }, 'library-catalog-sha256': { type: 'string' }, 'continuation-source-run': { type: 'string' }, - method: { type: 'string', default: 'direct' }, workers: { type: 'string', default: '4' }, + method: { type: 'string', default: 'direct' }, workers: { type: 'string' }, 'module-plan': { type: 'string' }, - scheduler: { type: 'string', default: 'plan' }, coordination: { type: 'string', default: 'cooperative' }, + scheduler: { type: 'string', default: 'plan' }, coordination: { type: 'string' }, 'plan-approval': { type: 'boolean' }, 'research-mode': { type: 'string' }, 'skill-loading': { type: 'string' }, 'common-research-skill': { type: 'string' }, 'skill-delegation': { type: 'string' }, 'skill-max-agents': { type: 'string' }, 'agent-team': { type: 'string' }, 'skill-preferred-profiles': { type: 'string' }, 'skill-expert-cards-file': { type: 'string' }, - 'portfolio-exploration': { type: 'boolean' }, 'skip-portfolio': { type: 'boolean' }, 'portfolio-seconds': { type: 'string' }, + 'portfolio-exploration': { type: 'boolean' }, 'portfolio-seconds': { type: 'string' }, } }); if (values.help) { - console.log(`Usage: theorem-os run --workspace DIR --task-file FILE --output FILE --build-manifest FILE [--receipt-file FILE] [--resume] [--method direct] [--scheduler plan|critical-path|continuation] [--module-plan FILE] [--coordination cooperative|independent] [--workers 1..${MAX_RESEARCH_WORKERS}] [--plan-approval] [--model MODEL --effort LEVEL] [--max-run-seconds N --max-turns N --max-turn-seconds N] [--max-total-tokens N] [--prepare-timeout-seconds N] [--proof-timeout-seconds N] [--evaluator-command CMD --evaluator-timeout-seconds N] [--proof-environment-cache-dir DIR] [--startup-only] [--check-statement]\n--module-plan loads the shared research-module plan JSON; use --scheduler plan.\nUse 0 for --prepare-timeout-seconds, --max-run-seconds, --max-turns, --max-turn-seconds, --proof-timeout-seconds or --evaluator-timeout-seconds to disable that limit. All time, turn and token limits default to 0 (unlimited). With an explicit proof-check timeout, an expired check saves a resumable checkpoint and the identical candidate gets more time on its next check.\n--max-total-tokens defaults to 0 (unlimited). A finite value stops new model turns after provider-reported consumption reaches it; in-flight turns finish and may exceed it. Resume retains cumulative usage and the saved allowance unless explicitly changed.`); + if (entryPoint === 'historical-component') { + console.log('Run host scheduling experiments with their pinned historical TheoremOS revision.'); + return 0; + } + console.log(`Usage: theorem-os run --workspace DIR --task-file FILE --output FILE --build-manifest FILE [--receipt-file FILE] [--resume] [--agent-team N | --workers 1] [--plan-approval] [--model MODEL --effort LEVEL] [--max-run-seconds N --max-turns N --max-turn-seconds N] [--max-total-tokens N] [--prepare-timeout-seconds N] [--proof-timeout-seconds N] [--evaluator-command CMD --evaluator-timeout-seconds N] [--proof-environment-cache-dir DIR] [--startup-only] [--check-statement]\nUse 0 for --prepare-timeout-seconds, --max-run-seconds, --max-turns, --max-turn-seconds, --proof-timeout-seconds or --evaluator-timeout-seconds to disable that limit. All time, turn and token limits default to 0 (unlimited). With an explicit proof-check timeout, an expired check saves a resumable checkpoint and the identical candidate gets more time on its next check.\n--max-total-tokens defaults to 0 (unlimited). A finite value stops new model turns after provider-reported consumption reaches it; in-flight turns finish and may exceed it. Resume retains cumulative usage and the saved allowance unless explicitly changed.`); console.log('--knowledge-base FILE attaches an immutable saved-theorem catalog. Resume requires the same catalog digest. Historical knowledge never grants proof acceptance.'); - console.log('--portfolio-exploration enables parallel route scouting before proof work. Use --portfolio-seconds N (default 1800) to bound it, or --skip-portfolio to bypass a pending stage.'); - console.log('--agent-team N selects one Codex Lead and a team of 2..8 agents including Lead. New teams start with native collaboration tools and can retry a failed initial native startup with host tools. The direct Westlake Chat profile uses host tools. Omit the preset to retain ordinary solver dispatch.'); + console.log('New Codex runs use a native team of 4 including Lead. Use --agent-team N to set 2..8 seats, or --workers 1 for a single researcher. Native teams require the pinned Codex team backend and a compatible provider profile.'); console.log('New proof runs default to --effort high. Resume retains the saved effort when --effort is omitted; an explicit effort must match the frozen run.'); console.log('Accepted proofs automatically generate audited explanations of every original target. --explanation-language zh|en selects the language (default zh; resume keeps the previous language). --no-explanations skips generation. The result.explanations field records progress and artifact/proof.md paths. Explanation failures preserve proof acceptance and exit code; --resume retries them without solving again. Explanation time and tokens are separate from solving limits.'); console.log('--library-catalog FILE --library-catalog-sha256 DIGEST enables agent search/get/request against one pinned release. Installation requests end this frozen run for host-controlled continuation.'); console.log('--continuation-manifest FILE attaches explicit historical sources and notes without changing the verbatim task file. Resume retains the frozen attachment identity; historical material remains advisory.'); - console.log('--continuation-source-run OLD_RESULT_OR_STATE initializes a new cooperative run from the old run, freshly checks its saved helpers, and starts solving in the same process. With --startup-only, the run freezes its continuation and checks saved helpers when resumed. Use --resume to retry an interrupted zero-turn initialization.'); + console.log('--continuation-source-run OLD_RESULT_OR_STATE initializes a new native team or solo Skill run from the old run, freshly checks its saved helpers, and starts solving in the same process. With --startup-only, the run freezes its continuation and checks saved helpers when resumed. Use --resume to retry an interrupted zero-turn initialization.'); console.log('--check-statement also elaborates the target files at startup (theorem bodies may still be sorry) and fails with math_statement_check_failed on a Lean error; statement-diagnostics.json keeps the messages.'); - console.log('--plan-approval holds every worker after the first accepted plan until a person approves that exact plan version (queuePlanApproval, the web workbench). The Lead takes a revision turn only for Lead guidance written while it waits. Waiting counts toward --max-run-seconds. Requires cooperative coordination and at least 2 workers; resume requires the same setting.'); - console.log('Lead planning and ordinary research first yield a resumable scheduling checkpoint after 120 seconds, with a reminder after 90 seconds. Lead planning keeps 120-second slices; ordinary research backs off to at most 960 seconds. Saved threads and drafts survive resume. Proof turns and total solving budgets are unchanged.'); - console.log('--research-mode skill loads pinned research methods in single, independent or cooperative workflows. New Skill runs default to one independent researcher; explicit --workers above 1 defaults to cooperative, and explicit --coordination cooperative defaults to 4 workers. Schedulers, module plans, plan approval and host acceptance retain their existing contracts. --skill-loading native|file selects native skill input or the same frozen file. Resume inherits saved mode, loading, workers and coordination; historical single-only Skill checkpoints retain their original semantics.'); - console.log('--harness codex|claude-code|opencode|cli selects the native agent independently of research method and --model. Additional harnesses default to Skill/file loading, require an explicit --model and dedicated --harness-profile DIR, and support host-managed single, independent and cooperative execution. Explicit legacy mode remains available. --harness-executable overrides the native binary; --codex remains a Codex-only alias. Resume retains the backend, model, executable, profile and session plan; changed executable/configuration bytes require a new run. New backends require Linux bubblewrap. Native turn usage stops subsequent dispatches; it does not enforce individual provider-request admission.'); + console.log('--plan-approval lets the native Lead publish an initial route for approval. Use inspect to read it and edit --approve-plan VERSION to approve it. Waiting pauses the solving clock.'); + console.log('--research-mode skill loads pinned research methods. --skill-loading native|file selects native Skill input or the same frozen file. Resume inherits the saved mode, loading, workers and coordination.'); + console.log('--harness codex|claude-code|opencode|cli selects the native agent independently of --model. Additional harnesses support one researcher and default to file-based Skill loading. They require Linux bubblewrap, an explicit --model and a dedicated --harness-profile DIR. --harness-executable overrides the native binary. Resume retains the frozen backend and session plan.'); console.log('--harness cli runs any configured headless command using DEDICATED_PROFILE/cli.json: argv, stdin/file/argument input, text/JSON/JSONL output, optional exact native session resume and usage fields. Use --harness-profile DIR and an explicit --model; --harness-executable optionally overrides the configured executable. CLIs without reasoning control require explicit --effort none. Commands without native resume receive full context on every turn and continue from saved sources/notes. Missing or partial usage blocks further finite-budget dispatches. See docs/generic-cli.md.'); - console.log('--common-research-skill native|file gives every research worker the same pinned mathematical skill and minimal host contracts for controlled strategy comparisons. Resume retains this identity. --research-mode skill --skill-delegation team --skill-max-agents 3 enables a Codex Lead to organize persistent proof writers with native spawn_agent, followup_task, send_message and wait_agent (single host Lead, --workers 1 --coordination independent). theoremos_team supplies only saved-result lookup and checked proof handoffs; collaboration uses the native tools. Historical host-tools runs retain their saved transport. --skill-delegation read-only retains bounded native investigations with built-in spawn/fork disabled. --skill-max-agents counts the Lead: 2..8 for team, 2..4 for read-only (default 4). Configured limits are shared; no research budget is imposed when limits are disabled.'); + console.log('Codex Lead delegates and communicates with native tools. theoremos_team handles route approval, saved-result lookup and checked proof handoffs. Configured limits are shared. Reproduce host scheduling experiments with their pinned historical revision.'); console.log('--skill-preferred-profiles engineer,D011 optionally suggests member work roles and domain specialties from the pinned Skill to the team Lead. The Lead chooses actual assignments and may use other profiles. Omit for no preference on a new run; resume retains the saved selection.'); console.log('--skill-expert-cards-file FILE freezes user-selected expert cards for a team run. Lead sees their catalogue and can select asset: in a member assignment. Resume reuses the saved cards.'); console.log('Team mode makes an early collaboration decision and exposes remaining run time and turn deadlines to every member. A finite --max-turn-seconds remains a hard ceiling; at 80% the host requests a checkpoint at the next model-request boundary, allowing the current response and tools to finish first. The overall deadline and cancellation remain hard stops; missing usage still blocks finite-budget continuation.'); return 0; } const specified = (key: string) => args.some(arg => arg === '--' + key || arg.startsWith('--' + key + '=')); + if (entryPoint === 'historical-component' || values['portfolio-exploration'] || values['portfolio-seconds'] !== undefined) + throw new Error(legacyCollaborationRetired); + const publicRun = entryPoint !== 'internal'; + if (publicRun && !values.resume) { + if ((values.workers !== undefined && values.workers !== '1') || values['skill-delegation'] === 'read-only' || + (values.coordination !== undefined && values.coordination !== 'independent') || + values['module-plan'] || values.scheduler !== 'plan' || + (values['common-research-skill'] && values.workers !== '1')) + throw new Error('math_native_team_required: use --agent-team N for collaboration or your pinned historical revision for host scheduling experiments.'); + const codex = (values.harness ?? 'codex') === 'codex'; + if (codex && values.workers === undefined && values['research-mode'] !== 'legacy' && !values['skill-delegation']) + values['agent-team'] ??= values['skill-max-agents'] ?? '4'; + } if (values['agent-team'] !== undefined) { if (values['research-mode'] !== undefined && values['research-mode'] !== 'skill' || values['skill-delegation'] !== undefined && values['skill-delegation'] !== 'team' || @@ -139,6 +151,12 @@ export async function runSolver(args: string[], root: string, customModules?: So try { savedConfiguration = readSolverRunState(`${path.resolve(values.output)}.runtime/state.json`); } catch { /* The authoritative read under the run lease reports invalid resume state. */ } } + if (savedConfiguration) assertActiveResearchState(savedConfiguration); + if (values['skill-delegation'] === 'read-only' || Number(values.workers) > 1 || + (!values.resume && values.coordination === 'cooperative' && !values['skill-delegation'])) + throw new Error(legacyCollaborationRetired); + if (values.workers !== undefined && values.workers !== '1') throw new Error('invalid --workers'); + const coordination = values.coordination ?? (savedConfiguration ? savedConfiguration.coordination ?? 'cooperative' : 'independent'); const harness = researchHarness(values.harness ?? savedConfiguration?.agentHarness?.id ?? 'codex'); if (harness.id !== 'codex' && values.codex) throw new Error('--codex requires --harness codex'); if (values.codex && values['harness-executable'] && values.codex !== values['harness-executable']) @@ -156,37 +174,29 @@ export async function runSolver(args: string[], root: string, customModules?: So if (commonLoading && (!['native', 'file'].includes(commonLoading) || skillMode && commonLoading !== skillLoading)) throw new Error('invalid --common-research-skill'); const delegationMode = values['skill-delegation'] ?? savedConfiguration?.researchDelegation?.mode; - if (delegationMode && (!skillMode || !['read-only', 'team'].includes(delegationMode)) || values['skill-max-agents'] && !delegationMode) + if (delegationMode && (!skillMode || delegationMode !== 'team') || values['skill-max-agents'] && !delegationMode) throw new Error('invalid --skill-delegation'); const maxAgents = Number(values['skill-max-agents'] ?? savedConfiguration?.researchDelegation?.maxAgents ?? 4); if (delegationMode && (!Number.isSafeInteger(maxAgents) || maxAgents < MIN_TEAM_AGENTS || - maxAgents > (delegationMode === 'team' ? MAX_TEAM_AGENTS : 4))) throw new Error('invalid --skill-max-agents'); - if (delegationMode === 'read-only') validateNativeDelegation({ mode: 'read-only', maxAgents }); + maxAgents > MAX_TEAM_AGENTS)) throw new Error('invalid --skill-max-agents'); if (delegationMode === 'team' && harness.id !== 'codex') throw new Error('math_team_requires_codex_dynamic_tools'); if (values['skill-preferred-profiles'] !== undefined && delegationMode !== 'team') throw new Error('invalid --skill-preferred-profiles: requires --skill-delegation team'); if (values['skill-expert-cards-file'] !== undefined && delegationMode !== 'team') throw new Error('invalid --skill-expert-cards-file: requires --skill-delegation team'); - if (skillMode) { - if (!specified('workers')) values.workers = String(savedConfiguration?.workerCount ?? - (specified('coordination') && values.coordination === 'cooperative' ? 4 : 1)); - if (!specified('coordination')) values.coordination = savedConfiguration?.coordination ?? - (Number(values.workers) > 1 ? 'cooperative' : 'independent'); - if (savedConfiguration && !savedConfiguration.researchSkillWorkflow && - (values.workers !== '1' || values.coordination !== 'independent' || values.method !== 'direct' || - values.scheduler !== 'plan' || values['module-plan'] || values['plan-approval'])) - throw new Error('math_skill_research_requires_single_independent_direct'); - } - if (delegationMode === 'team' && (values.workers !== '1' || values.coordination !== 'independent' || values['plan-approval'] || values['module-plan'])) + if (skillMode && savedConfiguration && !savedConfiguration.researchSkillWorkflow && + (coordination !== 'independent' || values.method !== 'direct' || + values.scheduler !== 'plan' || values['module-plan'] || values['plan-approval'])) + throw new Error('math_skill_research_requires_single_independent_direct'); + if (delegationMode === 'team' && (coordination !== 'independent' || values['module-plan'])) throw new Error('math_team_requires_single_lead'); const configured = configuredSolverModules(values.method!, values.scheduler!); if (customModules && values.scheduler !== 'plan') throw new Error('custom modules cannot combine with --scheduler'); - if (!['cooperative', 'independent'].includes(values.coordination!)) throw new Error('invalid --coordination'); - const coordination = values.coordination as 'cooperative' | 'independent'; + if (coordination !== 'independent' && coordination !== 'cooperative') throw new Error('invalid --coordination'); if (values['module-plan'] && (customModules || values.scheduler !== 'plan')) throw new Error('--module-plan requires --scheduler plan and no injected modules'); const baseModules = values['module-plan'] - ? configurableSolverModules(researchModulePlanSchema.parse(readMathJson(values['module-plan'])) as ResearchModulePlan, coordination, Number(values.workers)) + ? configurableSolverModules(researchModulePlanSchema.parse(readMathJson(values['module-plan'])) as ResearchModulePlan, coordination, 1) : customModules ?? configured; const modules: SolverModules = harness.id === 'codex' ? baseModules : { ...baseModules, M1: { ...baseModules.M1, version: baseModules.M1.version + ':' + harness.id + ':v1', @@ -213,16 +223,11 @@ export async function runSolver(args: string[], root: string, customModules?: So const evaluatorMs = limit('evaluator-timeout-seconds', true) * 1000; if (values['explanation-language'] !== undefined && !['zh', 'en'].includes(values['explanation-language'])) throw new Error('invalid --explanation-language'); - const workerCount = limit('workers'); - if (workerCount > MAX_RESEARCH_WORKERS) throw new Error('invalid --workers'); - const portfolioSeconds = values['portfolio-seconds'] === undefined ? undefined : limit('portfolio-seconds'); - if (portfolioSeconds !== undefined && portfolioSeconds > PORTFOLIO_MAX_SECONDS) throw new Error('invalid --portfolio-seconds'); - const singleSkill = skillMode && workerCount === 1; - if (values['continuation-source-run'] && !singleSkill && (coordination !== 'cooperative' || workerCount < 2)) - throw new Error('--continuation-source-run requires cooperative coordination and at least 2 workers'); - const planApproval = values['plan-approval'] === true; - if (planApproval && (coordination !== 'cooperative' || workerCount < 2)) - throw new Error('--plan-approval requires cooperative coordination and at least 2 workers'); + if (values['continuation-source-run'] && !skillMode) + throw new Error('--continuation-source-run requires Skill research'); + const planApproval = values['plan-approval'] ?? (savedConfiguration?.planApproval === true); + if (planApproval && delegationMode !== 'team') + throw new Error('--plan-approval requires a native team'); if (values['continuation-source-run'] && values['continuation-manifest']) throw new Error('--continuation-source-run cannot combine with --continuation-manifest'); const workspace = fs.realpathSync(required('workspace')); @@ -265,6 +270,8 @@ export async function runSolver(args: string[], root: string, customModules?: So const runWithLease = async (lease: MathLease): Promise => { const execute = async (): Promise => { const signal = lease.signal; + const resumedState = values.resume ? readSolverRunState(stateFile) : undefined; + if (resumedState) assertActiveResearchState(resumedState); const buildFile = fs.realpathSync(required('build-manifest')); const bundleRoot = path.join(root, 'out', 'main'); readMathBuildManifest(buildFile, root, bundleRoot); @@ -287,25 +294,18 @@ export async function runSolver(args: string[], root: string, customModules?: So const continuationInput = values['continuation-manifest'] ? readContinuationInput(values['continuation-manifest'], continuationIdentity) : undefined; let continuation: ContinuationSnapshot | undefined; - const slots = researchWorkers(path.join(directory, 'worktree'), problem.ownedFiles, workerCount); - const workers = modules.M5.workers(slots[0].worktree, [...problem.ownedFiles], workerCount); - if (workers.length !== workerCount || new Set(workers.map(worker => worker.id)).size !== workerCount || - workers.some((worker, index) => !/^[a-zA-Z0-9_-]{1,64}$/u.test(worker.id) || - worker.worktree !== slots[index].worktree || canonicalMathJson(worker.ownedFiles) !== canonicalMathJson(problem.ownedFiles) || - (index === 0 ? worker.id !== 'solver' || worker.role !== 'lead' : !['researcher', 'prover', 'engineer', 'reviewer'].includes(worker.role)))) - throw new Error('math_solver_worker_outside_ownership'); + const worktree = path.join(directory, 'worktree'); const profileArgument = values['harness-profile'] ?? savedConfiguration?.agentHarness?.profile; if (harness.id !== 'codex' && !profileArgument) throw new Error('--harness-profile is required for --harness ' + harness.id); const profile = profileArgument ? fs.realpathSync(profileArgument) : process.env.CODEX_HOME || path.join(os.homedir(), '.config/deepscientist/math-sol-codex'); const cli = harness.id === 'cli' ? readCliConfiguration(profile) : undefined; - const resumedState = values.resume ? readSolverRunState(stateFile) : undefined; const codexWestlake = harness.id === 'codex' ? selectedWestlakeProfile(profile) : undefined; - // The legacy Chat bridge does not carry native collaboration namespaces or attributed messages. - const newWestlakeTeam = delegationMode === 'team' && !values.resume && Boolean(codexWestlake); // Historical runs keep the transport frozen by their existing checkpoint. - const nativeTeamRun = delegationMode === 'team' && (resumedState - ? resumedState.agentTeam?.transport === 'native-agent-control' : !newWestlakeTeam); + const nativeTeamRun = delegationMode === 'team' && (!values.resume || + resumedState?.agentTeam?.transport === 'native-agent-control'); + const westlakeTeamError = WESTLAKE_NATIVE_TEAM_UNSUPPORTED + ': select a native-compatible Codex profile such as the Responses gateway.'; + if (!values.resume && codexWestlake && nativeTeamRun) throw new Error(westlakeTeamError); const sourceEnvironment = { ...process.env }; // Explicit CLI-only inputs, including unusually named credentials, never enter host Lean. for (const key of cli?.inheritEnvironment ?? []) delete sourceEnvironment[key]; @@ -317,7 +317,7 @@ export async function runSolver(args: string[], root: string, customModules?: So cli?.executable ?? (harness.id === 'codex' ? process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE || 'codex' : harness.id === 'claude-code' ? 'claude' : 'opencode')); // Historical Codex checkpoints retain their existing binding; explicit new flags opt into full launch identity. const pinHarness = harness.id !== 'codex' || specified('harness-executable') || specified('harness-profile') || - Boolean(savedConfiguration?.agentHarness) || nativeTeamRun || newWestlakeTeam; + Boolean(savedConfiguration?.agentHarness) || nativeTeamRun; const agentHarness = pinHarness ? bindResearchHarness(harness.id, executable, profile, process.env, values.model) : undefined; const harnessEnvironment = harness.id === 'codex' ? undefined : researchHarnessEnvironment(harness.id, process.env, { profile, model: values.model! }); @@ -328,12 +328,6 @@ export async function runSolver(args: string[], root: string, customModules?: So ? selectedDeepSeekProfile(profile) ?? sub2apiProfile ?? westlakeProfile : undefined; const knowledge = values['knowledge-base'] ? readAuthorizedKnowledgeCatalog(values['knowledge-base'], workspace, values['receipt-file'] || path.join(workspace, 'active-problem.json')) : undefined; - const portfolio = configurePortfolioExploration(resumedState?.portfolioExploration, { - enable: values['portfolio-exploration'], skip: values['skip-portfolio'], - durationMs: portfolioSeconds === undefined ? undefined : portfolioSeconds * 1000, - capacity: delegationMode === 'team' ? maxAgents : workerCount, - startedResearch: (resumedState?.turns ?? 0) > 0, - }); if (cli && !cli.efforts.includes(resumedState && !effortSpecified ? resumedState.effort : values.effort!)) throw new Error('math_cli_effort_unsupported'); const skillFile = path.join(root, 'skills/theoremos-research/SKILL.md'); @@ -350,11 +344,10 @@ export async function runSolver(args: string[], root: string, customModules?: So ? readPersonalExperts(values['skill-expert-cards-file']) : savedTeam?.mode === 'team' ? savedTeam.personalExperts : undefined; const researchDelegation: SolverRunState['researchDelegation'] = delegationMode === 'team' ? { mode: 'team', maxAgents, ...(preferredProfiles?.length ? { preferredProfiles } : {}), ...(personalExperts && { personalExperts }) } - : delegationMode === 'read-only' ? { mode: 'read-only', maxAgents } : undefined; + : undefined; const sessionSkill = loadedSkill ?? commonSkill; const plannedSession = planMathAgentSession(harness.id, { ...(sessionSkill ? { skills: [sessionSkill] } : {}), - ...(workerCount === 1 ? { completedOutput: new SingleSolverProofHandoff(problem, slots[0].worktree, () => {}).output } : {}), - ...(researchDelegation?.mode === 'read-only' ? { delegation: researchDelegation } : {}) }, cli); + completedOutput: new SingleSolverProofHandoff(problem, worktree, () => {}).output }, cli); const identity = { taskDigest: mathDigest(task), buildDigest: mathDigest(fs.readFileSync(buildFile)), providerProfile: providerProfile?.profile, providerProfileDigest: providerProfile?.digest, environmentDigest: preparedEnvironment.environmentDigest, @@ -402,6 +395,11 @@ export async function runSolver(args: string[], root: string, customModules?: So const moduleConfiguration = solverModuleConfiguration(modules); let state: SolverRunState; let sourceFeedback: string | undefined; + let leadSkill: WorkerAccess['researchSkill']; + const prepareSkill = (worktree: string) => { + const expected = state.researchSkill ?? state.commonResearchSkill; + return expected && prepareResearchSkill(root, worktree, expected, state.problem); + }; if (values.resume) { state = resumedState!; continuationSourceRun ??= state.pendingContinuationSource; @@ -417,17 +415,12 @@ export async function runSolver(args: string[], root: string, customModules?: So throw new Error('math_resume_session_plan_changed'); if (problem.libraryBinding?.hostConfiguration && state.continuationDigest) throw new Error('library_knowledge_history_unauthorized'); - if ([state, ...(state.workers ?? [])].some(record => record.writerStopUnconfirmed)) + if (state.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed: recover into a new isolated workspace before resuming.'); if (!tokenLimitSpecified) maxTotalTokens = state.tokenBudget?.maxTotalTokens ?? 0; if (!state.methodDigest && modules === directSolverModules && coordination === 'cooperative') state.methodDigest = identity.methodDigest; if ((state.coordination ?? 'cooperative') !== coordination) throw new Error('math_resume_coordination_changed'); - if ((state.workerCount ?? 1) !== workerCount) throw new Error('math_resume_worker_count_changed'); if (Boolean(state.planApproval) !== planApproval) throw new Error('math_resume_plan_approval_changed'); - if (workerCount > 1 && (!state.workers || state.workers.length !== workerCount || - state.workers.some((worker, index) => worker.id !== workers[index].id || - worker.role !== workers[index].role || worker.worktree !== workers[index].worktree))) - throw new Error('math_resume_worker_identity_changed'); if (state.schema !== 'deepscientist.math.solver.v1' || state.problem.workspace !== workspace || state.problem.receiptDigest !== problem.receiptDigest || (Object.keys(identity) as (keyof typeof identity)[]).some(key => state[key] !== identity[key]) || @@ -439,25 +432,21 @@ export async function runSolver(args: string[], root: string, customModules?: So } else if (continuationInput) throw new Error('math_resume_continuation_changed'); // Use the current authoritative receipt instead of trusting nested archived source policy. state.problem = problem; - if (state.researchSkill ?? state.commonResearchSkill) prepareResearchSkill(root, state.worktree, - (state.researchSkill ?? state.commonResearchSkill)!, problem); + leadSkill = prepareSkill(state.worktree); sourceFeedback = solverSourceFeedback(state.problem, state.worktree); assertSolverSources(state.problem, workspace); if (state.phase === 'finished' && fs.existsSync(output)) { const result = readMathJson(output) as Record & { status: string; runId: string; solution_commit: string }; if (result.status === 'evaluated_passed' || result.status === 'evaluated_failed') { - const winningWorktree = state.workers?.find(worker => worker.id === state.winningWorker)?.worktree ?? state.worktree; - assertSolverSources(state.problem, winningWorktree); + assertSolverSources(state.problem, state.worktree); if (!state.check?.passed || result.runId !== state.runId || result.solution_commit !== state.check.commit || - !solverProofIsCurrent(state.problem, winningWorktree, state.check) || + !solverProofIsCurrent(state.problem, state.worktree, state.check) || !solverProofIsCurrent(state.problem, workspace, state.check)) throw new Error('math_resume_completed_proof_changed'); - if (result.status === 'evaluated_passed') await explainAccepted(state, result, winningWorktree); + if (result.status === 'evaluated_passed') await explainAccepted(state, result, state.worktree); return result.status === 'evaluated_passed' ? 0 : 2; } } - if (codexWestlake && nativeTeamRun) - throw new Error(WESTLAKE_NATIVE_TEAM_UNSUPPORTED + - ': create a new team run with your saved artifacts. Direct Westlake uses host tools for new runs.'); + if (codexWestlake && nativeTeamRun) throw new Error(westlakeTeamError); } else { if (fs.existsSync(stateFile) || fs.existsSync(output)) throw new Error('math_run_exists_use_resume'); if (git(workspace, ['status', '--porcelain', '--untracked-files=no'])) throw new Error('math_workspace_has_uncommitted_sources'); @@ -468,31 +457,22 @@ export async function runSolver(args: string[], root: string, customModules?: So agentSessionPlan: plannedSession, ...(researchSkill ? { researchMode: 'skill', researchSkill, researchSkillWorkflow: 'full' } : {}), ...(commonResearchSkill ? { commonResearchSkill } : {}), ...(researchDelegation ? { researchDelegation } : {}), - ...(nativeTeamRun || newWestlakeTeam ? { agentTeam: { schema: 'theorem-os.agent-team.v1' as const, - transport: nativeTeamRun ? 'native-agent-control' as const : 'host-tools' as const, + ...(nativeTeamRun ? { agentTeam: { schema: 'theorem-os.agent-team.v1' as const, + transport: 'native-agent-control' as const, workers: [], events: [], deliveries: [], adoptions: [], operations: [] } } : {}), ...(continuation ? { continuationDigest: continuation.digest } : {}), - worktree: path.join(directory, 'worktree'), phase: 'prepared', turns: 0, dispatchCounts: {}, workerCount, + worktree, phase: 'prepared', turns: 0, dispatchCounts: {}, workerCount: 1, coordination, ...(planApproval ? { planApproval } : {}), moduleConfiguration, tokenBudget: buildTokenBudget(maxTotalTokens, [], westlakeProfile ? 'provider-observed-upstream-request-limit' : undefined) }; - if (workerCount > 1) state.workers = workers - .map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'prepared', turns: 0, dispatchCounts: {} })); git(workspace, ['worktree', 'add', '--detach', state.worktree, problem.baseCommit]); writeSolverRunState(stateFile, state); + leadSkill = prepareSkill(state.worktree); } - if (portfolio) state.portfolioExploration = portfolio; - if (state.researchSkill ?? state.commonResearchSkill) prepareResearchSkill(root, state.worktree, - (state.researchSkill ?? state.commonResearchSkill)!, problem); ownsRun = true; ownedState = state; state.tokenBudget = buildTokenBudget(maxTotalTokens, - [...(state.workers ?? [state]), ...(state.agentTeam?.workers ?? []), ...portfolioUsageRecords(state)], state.tokenBudget?.enforcement); + [state, ...(state.agentTeam?.workers ?? [])], state.tokenBudget?.enforcement); const save = () => { lease.assertOwned(); writeSolverRunState(stateFile, state); }; - if (portfolio) save(); - for (const worker of workers.slice(1)) { - signal.throwIfAborted(); - if (!fs.existsSync(worker.worktree)) git(workspace, ['worktree', 'add', '--detach', worker.worktree, problem.baseCommit]); - } const prepareProject = (worktree: string) => { const project = path.join(worktree, state.problem.projectRelative); fs.mkdirSync(path.join(project, '.lake'), { recursive: true }); @@ -613,10 +593,8 @@ export async function runSolver(args: string[], root: string, customModules?: So const installedLibrary = readInstalledLibrarySnapshot(problem, state.environmentDigest); const knowledgeSnapshot = knowledge && indexKnowledgeContextSnapshot({ digest: knowledge.digest, base: { entries: knowledge.base.entries, evidence: knowledge.base.evidence, contexts: knowledge.base.contexts, routeFindings: knowledge.base.routeFindings } }); - const workerAccess = new Map(); - const prepareAccess = (workerId: string, workerRoot: string, workerProject: string, workerCorpus?: string) => { - const pinnedSkill = (state.researchSkill ?? state.commonResearchSkill) && prepareResearchSkill(root, workerRoot, - (state.researchSkill ?? state.commonResearchSkill)!, state.problem); + const prepareAccess = (workerId: string, workerRoot: string, workerProject: string, + workerCorpus: string | undefined, pinnedSkill: WorkerAccess['researchSkill']): WorkerAccess => { const workerContinuation = continuation && copyContinuationSnapshot(continuation, workerProject); assertHostProblemCurrent(); let knowledgeFile: string | undefined; @@ -630,7 +608,7 @@ export async function runSolver(args: string[], root: string, customModules?: So const environment = { ...env, DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS: workerCorpus }; writeMathJsonDurable(environmentFile, projectMathematicsRuntimeEnvironment(environment), 0o400); - workerAccess.set(workerId, { environment: resolveMathematicsRuntimeEnvironment(environment), corpusFile: workerCorpus, + return { environment: resolveMathematicsRuntimeEnvironment(environment), corpusFile: workerCorpus, ...(harnessEnvironment ? { harnessEnvironment } : {}), ...(assertHarnessCurrent ? { assertHarnessCurrent } : {}), ...(cli ? { nativeContinuity: cli.session.mode !== 'fresh' } : {}), @@ -646,16 +624,15 @@ export async function runSolver(args: string[], root: string, customModules?: So else assertHostProblemCurrent(); } } : {}), ...(knowledge ? { knowledgeFile, knowledgeDigest: knowledge.digest, - knowledgeSnapshot } : {}) }); + knowledgeSnapshot } : {}) }; }; - prepareAccess('solver', state.worktree, project, corpusFile); + let leadAccess = prepareAccess('solver', state.worktree, project, corpusFile, leadSkill); const prepareTeamWorker = async (workerId: string, workerWorktree: string): Promise => { signal.throwIfAborted(); - const accessId = state.researchDelegation?.mode === 'team' ? 'team-' + workerId : workerId; + const accessId = 'team-' + workerId; const workerProject = prepareProject(workerWorktree); const lake = path.join(workerProject, '.lake'); - await checkDependencies(accessId, workerProject, preparing ? preparationMs - (Date.now() - preparationStarted) : - Math.min(preparationMs, executionClock!.remainingMs())); + await checkDependencies(accessId, workerProject, Math.min(preparationMs, executionClock!.remainingMs())); let workerCorpusFile: string | undefined; if (corpusFile) { workerCorpusFile = path.join(lake, 'retrieval-corpus.json'); @@ -665,28 +642,21 @@ export async function runSolver(args: string[], root: string, customModules?: So throw new Error('math_corpus_identity_changed'); } else fs.writeFileSync(workerCorpusFile, corpusBytes!, { mode: 0o400, flag: 'wx' }); } - prepareAccess(accessId, workerWorktree, workerProject, workerCorpusFile); - return workerAccess.get(accessId)!; + return prepareAccess(accessId, workerWorktree, workerProject, workerCorpusFile, prepareSkill(workerWorktree)); }; - const peerPreparation = await Promise.allSettled(workers.slice(1).map(worker => prepareTeamWorker(worker.id, worker.worktree))); - const failedPreparation = peerPreparation.find(result => result.status === 'rejected'); - if (failedPreparation?.status === 'rejected') throw failedPreparation.reason; - let freshContinuationChecks: readonly TaskProof[] | undefined; if (continuationSourceRun) { save(); continuationSeeding = true; - await (singleSkill ? seedSingleSolverContinuation : seedSolverContinuation)({ sourceRun: continuationSourceRun, run: stateFile, root, buildManifest: buildFile, + await seedSingleSolverContinuation({ sourceRun: continuationSourceRun, run: stateFile, root, buildManifest: buildFile, signal, lease, preparedEnvironment: env, timeoutMs: maxRunMs === Infinity ? Infinity : Math.max(1, preparationMs - (Date.now() - preparationStarted)), deferChecks: values['startup-only'], - onProgress: emit, onSeeded: (seeded, checks) => { state = ownedState = seeded; freshContinuationChecks = checks; } }); + onProgress: emit, onSeeded: seeded => { state = ownedState = seeded; } }); continuationSeeding = false; if (!state.continuationDigest) throw new Error('math_continuation_identity_missing'); continuation = readContinuationSnapshot(path.join(directory, 'continuation.json'), state.continuationDigest, continuationIdentity); - for (const worker of workers) { - const access = workerAccess.get(worker.id)!; - prepareAccess(worker.id, worker.worktree, path.join(worker.worktree, state.problem.projectRelative), access.corpusFile); - } + leadAccess = prepareAccess('solver', state.worktree, project, corpusFile, leadSkill); } - emit('ready', { runId: state.runId, worktree: state.worktree, workers }); + emit('ready', { runId: state.runId, worktree: state.worktree, + workers: [{ id: 'solver', role: 'lead', worktree: state.worktree, ownedFiles: state.problem.ownedFiles }] }); emit('preparation_finished', { durationMs: Date.now() - preparationStarted, dependencies: diagnostics.phases }); if (values['startup-only']) { writeMathJsonDurable(output, { schema: 'deepscientist.math.run.v2', runId: state.runId, @@ -712,19 +682,13 @@ export async function runSolver(args: string[], root: string, customModules?: So }, }; emit('solve_started', { budgetMs: maxRunMs, maxTurnMs }); - await runPortfolioExploration({ state, executable: agentHarness?.executable ?? executable, profile, signal, taskText: task, - open: modules.M1.open, remainingMs: executionBudget.remainingMs, maxTurnMs, maxTurns, maxTotalTokens, - assertCurrent: () => { assertHarnessCurrent?.(); assertHostProblemCurrent(); }, - prepareWorkspace: worktree => ({ project: prepareProject(worktree), - environment: { ...env, ...harnessEnvironment, DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS: undefined } }), - save, emit }); const winner = await withVerificationCheckpoints({ environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, checkpoints: state.verificationCheckpoints ??= [], save, emit }, - () => runResearchWorkers({ state, workers, access: workerAccess, modules, root, buildFile, taskText: task, + () => runResearchLead({ state, access: leadAccess, modules, root, buildFile, taskText: task, executable: agentHarness?.executable ?? executable, profile, signal, deadline, executionBudget, maxTurns, maxTurnMs, maxTotalTokens, proofTimeoutMs, - freshContinuationChecks, prepareTeamWorker, save, emit })); + prepareTeamWorker, save, emit })); executionClock.stop(); state.solveWaitingMs = executionClock.waitingMs(); state.solveFinishedAt = Date.now(); diff --git a/src/solver/singleContinuationSeed.ts b/src/solver/singleContinuationSeed.ts index 306ca5ed..03af849d 100644 --- a/src/solver/singleContinuationSeed.ts +++ b/src/solver/singleContinuationSeed.ts @@ -5,7 +5,7 @@ import { readMathBuildManifest } from '../math/mathBuildManifest'; import { bindLeanPackages } from '../math/leanDiagnostics'; import { MATH_PROOF_ENVIRONMENT_ENV, MATH_PROOF_ENVIRONMENT_SANDBOX_ENV, prepareMathProofEnvironment } from '../math/mathProofEnvironment'; import { DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT } from '../math/mathProofEnvironmentCache'; -import { canonicalMathJson, mathDigest, readMathFile, readMathJson, withMathRuntimeLease, writeMathJsonDurable } from '../math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest, readMathFile, readMathJson, withMathRuntimeLease, writeMathJsonDurable, type MathLease } from '../math/mathRuntimeIo'; import { resolveMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnvironment'; import { assertMathCanonicalPath } from '../math/paths'; import { resolveMathematicsLakePackagesCache } from '../math/verifier'; @@ -14,7 +14,7 @@ import { inheritedContinuationText, singleContinuationHistory } from './continua import { readAgentTeamContinuationNote, type AgentTeamResearchArtifactReference, type AgentTeamContinuationOrigin } from './agentTeamResearch'; import { freezeContinuationInput, MAX_CONTINUATION_ATTACHMENT_BYTES, readContinuationContents, type ContinuationManifest } from './continuationInput'; import { captureContinuationTaskDrafts, continuationOwnershipExtension, continuationSourcePolicyDigest, - type ContinuationSeedReport, type seedSolverContinuation } from './continuationSeed'; + type ContinuationSeedReport, type ContinuationSeedOptions } from './continuationSeed'; import { checkDeclarationArtifacts, readDeclarationArtifacts, writeDeclarationArtifacts } from './declarationArtifacts'; import { readRunInspection } from './inspection'; import { assertSolverSources, committedSource, commitSolverSources, git, pinSolverResearchSkill, readSolverProblem, withSolverWorktree } from './problem'; @@ -38,7 +38,6 @@ const sourceSchema = z.object({ schema: z.literal('theorem-os.single-continuatio description: z.string().optional(), premises: z.array(z.string()).optional() }).strict()), }).strict(); type SingleSource = z.infer; -type Options = Parameters[0]; type SingleSeedReport = ContinuationSeedReport & { declarationFailures?: { id: string; name: string; error: string }[] }; const configurationDigest = (state: SolverRunState) => mathDigest(canonicalMathJson({ runId: state.runId, @@ -230,13 +229,13 @@ function freezeSource(source: SingleSource, directory: string) { } /** Import artifacts into a new idle single run; historical scheduling state is never recreated. */ -export async function seedSingleSolverContinuation(options: Options): Promise { +export async function seedSingleSolverContinuation(options: ContinuationSeedOptions): Promise { const stateFile = readRunInspection(options.run).stateFile, directory = path.dirname(stateFile); const sourceStateFile = path.basename(path.resolve(options.sourceRun)) === 'state.json' ? path.resolve(options.sourceRun) : `${path.resolve(options.sourceRun)}.runtime/state.json`; assertMathCanonicalPath(sourceStateFile); if (sourceStateFile === stateFile) throw new Error('math_continuation_seed_identity_changed'); - const seed = async (lease: NonNullable) => { + const seed = async (lease: MathLease) => { const state = readSolverRunState(stateFile), sourceFile = path.join(directory, 'continuation-single-source.json'); const reportFile = path.join(directory, 'continuation-seed.json'), seeded = fs.existsSync(sourceFile); assertPrepared(state, stateFile, seeded); diff --git a/src/solver/skillResearchContext.ts b/src/solver/skillResearchContext.ts index 033929fd..51c9f0ce 100644 --- a/src/solver/skillResearchContext.ts +++ b/src/solver/skillResearchContext.ts @@ -5,7 +5,7 @@ import { mathToolGuide } from '../math/mathTools'; import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills'; import type { MathAgentOptions } from '../runtime/agentSession'; import type { SolverRunState } from './archive'; -import { compileContextSections, portfolioContextSections, type ContextSection } from './contextCompiler'; +import { compileContextSections, type ContextSection } from './contextCompiler'; import { continuationContextSection, readContinuationSnapshot } from './continuationInput'; import { DECLARATION_INDEX_FILE } from './declarationIndex'; import { solverProofFeedback } from './feedback'; @@ -45,20 +45,18 @@ export function skillResearchContinuationSection(problem: Pick): ContextSection { - const native = state.agentTeam?.transport === 'native-agent-control'; const overview = agentTeamOverview(state); return { id: 'agent-team', kind: 'feedback', - text: 'Team observations (advisory; ' + (native ? 'receive updates through native messages' : 'use theoremos_team poll for the durable inbox') + '):\n' + + text: 'Team observations (advisory; receive updates through native messages):\n' + JSON.stringify({ ...overview, recentEvents: agentTeamRecentEvents(state.agentTeam, 'lead'), latestSequence: state.agentTeam?.events.at(-1)?.sequence ?? 0, - inbox: native ? 'Native messages carry addressed updates. Use history for complete tasks and inspect or inspect-research for saved results. Native acceptance and latestSequence are not read acknowledgments.' : - 'Poll after your last received cursor (initially 0) for the full durable inbox. latestSequence is not an acknowledgment.' }) }; + inbox: 'Native messages carry addressed updates. Use history for complete tasks and inspect or inspect-research for saved results. Native acceptance and latestSequence are not read acknowledgments.' }) }; } /** Stable host contracts and current facts; research methods live in the pinned skill. */ export function buildSkillResearchContext(problem: SolverProblem, state: Readonly, - access: ContextAccess & { researchSkill: MathAgentSkill }): ContextBundle { + access: ContextAccess & { researchSkill: MathAgentSkill }): ContextBundle & { inboxThrough?: number } { const skill = access.researchSkill; assertMathAgentSkillsCurrent([skill]); if (!state.researchSkill || state.researchSkill.digest !== skill.digest || state.researchSkill.name !== skill.name || @@ -67,7 +65,7 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl if (!access.knowledgeDigest || access.knowledgeDigest !== state.knowledgeDigest) throw new Error('math_knowledge_identity_changed'); } else if (state.knowledgeDigest) throw new Error('math_knowledge_identity_missing'); const { command, help, leanCheckCommand, longCommandSummary } = buildResearchToolGuide(problem, access, state.environmentDigest, - state.researchDelegation?.mode === 'team' ? state.agentTeam?.transport ?? 'host-tools' : undefined); + state.researchDelegation?.mode === 'team'); const project = path.join(access.worktree, problem.projectRelative); const team = state.researchDelegation?.mode === 'team'; const teamWorker = state.researchDelegation?.mode === 'team' && access.teamRole?.role === 'worker'; @@ -106,8 +104,7 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl 'Consider these when they fit a concrete gap. You choose whether to delegate and may use any other catalogued specialty. ' + 'To give a member profile knowledge, put its ID on the Profiles: line of that assignment.\n\n' : ''; const instructions = (state.researchDelegation?.mode === 'team' - ? agentTeamInstructions(access.teamRole ?? { id: 'lead', role: 'lead' }, state.researchDelegation.maxAgents, - state.agentTeam?.transport) : '') + + ? agentTeamInstructions(access.teamRole ?? { id: 'lead', role: 'lead' }, state.researchDelegation.maxAgents) : '') + (leadProfile ? leadProfile.text + '\n\n' : '') + preferenceInstruction + cardCatalogue + (teamWorker ? 'Research the current Lead assignment in this isolated worktree using the pinned theoremos-research skill. ' + 'The frozen original problem is background and source constraints; the assignment defines the result you own.\n' @@ -123,12 +120,7 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl 'Do not read external candidate solutions. Do not edit the pinned skill, host help, configuration or receipts. ' + 'A message, local diagnostic or historical receipt is never acceptance. The host freezes sources after writer shutdown and checks every original target. ' + 'There is no host task graph in this mode. Execution-limit observations describe any stage and hard deadlines. ' + - (state.researchDelegation?.mode === 'team' ? '' : - state.researchDelegation?.mode === 'read-only' ? `The theoremos_investigate tool dispatches read-only native threads through the host, with at most ${state.researchDelegation.maxAgents} agents including you. ` + - 'Pass a questions array of bounded independent questions; the call waits for every result. Built-in spawn/fork is disabled. ' + - 'Delegate bounded questions only when parallel work helps. Children return advisory findings or candidates; you alone integrate formal sources. ' + - 'Each investigator is archived before its result returns; the host stops the entire session tree on delivery. All provider requests share your total allowance.\n' - : 'Native child delegation is disabled in this run.\n') + + (team ? '' : 'Native child delegation is disabled in this run.\n') + (leanCheckCommand ? `Lean check for an editable file (run from any directory):\n${leanCheckCommand}\n` : '') + toolSummary + longCommandSummary + help.instruction(access.worktree) + mathematicsRuntimeInstruction(access.environment.DEEPSCIENTIST_MATH_ENV_FILE); const originalProblem: ContextSection = { id: 'original-problem', kind: 'problem', @@ -137,7 +129,7 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl statement: problem.contract.informalStatement, formalStatement: problem.contract.formalStatement, assumptions: problem.contract.assumptions, targets: problem.targets, baselineCommit: problem.baseCommit, ownedFiles: problem.ownedFiles, frozenFiles: Object.keys(problem.frozenFiles ?? {}) }) }; - const mandatory: ContextSection[] = portfolioContextSections(state); + const mandatory: ContextSection[] = []; const feedback = [access.sourceFeedback, !teamWorker && state.check && !state.check.passed ? solverProofFeedback(state.check, access.previousCheck, access.previousFailures) : undefined].filter(Boolean).join('\n\n'); if (feedback) mandatory.push({ id: 'host-feedback', kind: 'feedback', text: feedback }); @@ -154,9 +146,11 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl mandatory.push({ id: 'saved-work', kind: 'sources', text: 'Read the current owned source files, relevant definitions and worktree-root RESEARCH.md before extending a remembered or inherited argument. ' + `The current owned declaration index is ${path.join(access.worktree, DECLARATION_INDEX_FILE)}. ` + 'Current files and complete references remain available even when their full text is not included in this message. Continue the original research from saved work.' }); + const workerContext = teamWorker ? agentTeamWorkerSection(state, access.teamRole!, access.teamAssignment!) : undefined; + const workerSections = workerContext + ? [workerContext.section, agentTeamProfileSection(skill, access.teamAssignment!.message, cards)] : []; const compile = (options: ResearchDispatchOptions = {}) => compileContextSections({ instructions, - mandatory: [...(teamWorker ? [agentTeamWorkerSection(state, access.teamRole!, access.teamAssignment!).section, - agentTeamProfileSection(skill, access.teamAssignment!.message, cards)] : []), + mandatory: [...workerSections, ...(access.executionLimits ? [executionLimitsSection(access.executionLimits)] : []), options.continuation ? skillResearchContinuationSection(problem, state) : originalProblem, ...mandatory, ...(options.checkpointInstruction ? [{ id: 'checkpoint', kind: 'checkpoint' as const, @@ -164,6 +158,6 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl maxOptionalContextBytes: access.maxOptionalContextBytes, inlineManifest: false }); const continued = compile({ continuation: true }); return { instructions, ...compile(), continuationMessage: continued.message, continuationManifest: continued.manifest, - compileDispatch: compile, + compileDispatch: compile, inboxThrough: workerContext?.inboxThrough, scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } }; } diff --git a/src/solver/usageBudget.ts b/src/solver/usageBudget.ts index 7b381291..a8d6f4e7 100644 --- a/src/solver/usageBudget.ts +++ b/src/solver/usageBudget.ts @@ -84,23 +84,36 @@ export function initializeRequestUsageAccounting(record: UsageRecord): void { (!record.usageAccounting && record.turns > 0)) }; } +// Keep the checkpoint array in append order and index it only while it is live. +const requestReceiptIndexes = new WeakMap>(); + /** Each lease represents exactly one attempted upstream request, independent of native thread counters. */ export function beginRequestUsage(record: UsageRecord, identity: Partial & { runId?: string; sessionId?: string; taskId?: string; startedAt?: number; -} = {}): (receipt: ModelRequestReceipt) => void { +} = {}): (receipt: ModelRequestReceipt) => Exclude { const accounting = record.requestUsageAccounting!; const requestId = identity.requestId ?? randomUUID(); const receipts = accounting.receipts ??= []; - let observation = receipts.find(item => item.requestId === requestId); + let byId = requestReceiptIndexes.get(receipts); + if (!byId) { + byId = new Map(); + for (const receipt of receipts) { + // Historical checkpoints use the first receipt if an ID is repeated. + if (!byId.has(receipt.requestId)) byId.set(receipt.requestId, receipt); + } + requestReceiptIndexes.set(receipts, byId); + } + let observation = byId.get(requestId); if (!observation) { observation = { ...identity, requestId, startedAt: identity.startedAt ?? Date.now(), status: 'pending' }; receipts.push(observation); + byId.set(requestId, observation); accounting.startedRequests++; accounting.pendingRequests++; } return receipt => { // The persisted identity also deduplicates settlement after checkpoint serialization/replay. - if (observation.status !== 'pending') return; + if (observation.status !== 'pending') return observation.status; accounting.pendingRequests--; const usage = normalizeModelRequestUsage(receipt.usage); let valid = usage !== undefined; @@ -120,6 +133,7 @@ export function beginRequestUsage(record: UsageRecord, identity: Partial; - -/** A completed check must not keep a waiting worker in the checking phase. */ -export function setWorkerResearchPhase(state: SolverRunState, research: Pick, - phase: 'running' | 'checking'): void { - research.phase = phase; - state.phase = state !== research && state.workers?.some(worker => worker.phase === 'checking') ? 'checking' : phase; -} - -/** Owns the writer-stop, immutable-snapshot, independent-check sequence for one worker. */ -export class WorkerProofLifecycle { - constructor(private readonly input: { - state: SolverRunState; - research: Pick; - worker: ResearchWorker; - cooperation: CooperativeResearch; - close: () => Promise; - save: () => void; - emit: (event: string, details?: Record) => void; - checked: () => void; - }) {} - - /** A durable frozen commit can be checked after restart without reopening its writer. */ - async resumeFrozen(assignment: CooperativeAction | undefined): Promise { - if (assignment?.kind !== 'task') return false; - const ready = this.input.cooperation.pendingProofReady(this.input.worker, assignment); - if (!ready?.snapshotCommit) return false; - await this.input.close(); - await this.checkSnapshot(assignment, ready); - return true; - } - - /** Only a settled turn's confirmed writer stop may authorize a new snapshot. */ - async settleTurn(assignment: CooperativeAction | undefined, candidate: ResearchCandidate, - operation: ResearchOperation, session: MathAgentSession): Promise { - if (assignment?.kind !== 'task') return false; - const { state, research, worker, cooperation, close, save, emit } = this.input; - const ready = cooperation.pendingProofReady(worker, assignment); - if (!ready) return false; - if (candidate.worktree !== worker.worktree || candidate.problemReceiptDigest !== state.problem.receiptDigest || - candidate.operation !== operation || candidate.provenance.workerId !== worker.id) - throw new Error('math_candidate_identity_changed'); - if (!ready.snapshotCommit) { - await stopProofWriter({ session, record: research, workerId: worker.id, close, save, deferred: reason => { - cooperation.proofReadyFailedFreeze(worker, assignment, reason); - cooperation.interrupted(worker, assignment); - emit('proof_ready_freeze_deferred', { receiptId: ready.id, reason }); - } }); - // The assignment and environment may have changed while the writer was stopping. - if (!cooperation.pendingProofReady(worker, assignment)) return true; - const sourceError = solverSourceFeedback(state.problem, worker.worktree, paths => - this.input.emit('source_quarantined', { paths: paths.slice(0, 32), count: paths.length })); - if (sourceError) { - research.check = undefined; - cooperation.proofReadyFailedFreeze(worker, assignment, sourceError); - cooperation.rejected(assignment, sourceError); - save(); emit('source_rejected'); - return true; - } - const commit = commitSolverSources(state.problem, worker.worktree); - if (!cooperation.proofReadyFrozen(worker, assignment, commit)) return true; - } else await close(); - await this.checkSnapshot(assignment, ready); - return true; - } - - private async checkSnapshot(assignment: TaskAction, ready: ProofReadyRecord): Promise { - const { state, research, worker, cooperation, save, emit, checked } = this.input; - if (!ready.snapshotCommit) throw new Error('math_proof_ready_snapshot_missing'); - setWorkerResearchPhase(state, research, 'checking'); save(); - try { - const delivery = await cooperation.deliver(worker, assignment, ready.snapshotCommit); - research.check = delivery.check; - cooperation.proofReadyCompleted(worker, assignment, delivery.check); - emit('proof_ready_checked', { receiptId: ready.id, readyId: ready.id, taskId: ready.taskId, taskDigest: ready.taskDigest, - workerId: ready.workerId, assignmentKey: ready.assignmentKey, seedCommit: ready.seedCommit, - commit: ready.snapshotCommit, sourceDigest: ready.sourceDigest, - receiptIds: delivery.check?.verification.results.map(result => result.receiptId), - passed: delivery.check?.passed === true, conditional: ready.evidence === 'conditional' }); - checked(); - } finally { setWorkerResearchPhase(state, research, 'running'); save(); } - } -} diff --git a/tests/agentResearchTeam.test.ts b/tests/agentResearchTeam.test.ts deleted file mode 100644 index bf0de4f9..00000000 --- a/tests/agentResearchTeam.test.ts +++ /dev/null @@ -1,1738 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; -import type { HarnessProcessIdentity } from '../src/runtime/harnessProcess'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; -import { DeclarationArtifactCheckError } from '../src/solver/declarationArtifacts'; -import type { AgentTeamState } from '../src/solver/agentTeamState'; -import { directSolverModules } from '../src/solver/modules'; -import { runResearchWorkers } from '../src/solver/research'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { RESEARCH_TOOL_HELP_FILE } from '../src/solver/researchToolHelp'; -import { deferred } from './helpers/async'; -import { temporaryDirectory } from './helpers/files'; -import { solverState } from './helpers/solver'; -import { currentWorkerProject } from '../src/solver/workerProject'; - -// Scheduling fixtures do not execute a backend bundle; Git sources, writer handoff -// and independent Lean verification below remain real. -vi.mock('../src/math/mathBuildManifest', async importOriginal => ({ - ...await importOriginal(), readMathBuildManifest: vi.fn(), -})); - -const original = 'namespace Team\ntheorem original : True := by sorry\n' + - 'theorem other : True := by sorry\nend Team\n'; -const helper = 'theorem reusable (n : Nat) : n = n := by rfl\n'; -const declarations = [{ file: 'Submission.lean', name: 'Team.reusable', type: '∀ n : Nat, n = n' }]; -const fixtures: ReturnType[] = []; -type InspectChangePage = { changeIndex: number; name: string; file: string; offset: number; source: string; - totalCharacters: number; truncated: boolean; nextOffset?: number }; -type ToolResult = { ok: boolean; error?: string; status?: string; delivery?: string; notification?: string; cursor: number; - taskId?: string; replacementTaskId?: string; - events: AgentTeamState['events']; adoption?: AgentTeamState['adoptions'][number]; - workers?: ({ id: string } & Record)[]; budget?: Record; - researchState?: { revision: number; summary: string; publishedAt: number; advisory: true }; - researchArtifacts?: { id: string; agentId: string; taskId: string; commit: string }[]; - id?: string; commit?: string; advisory?: boolean; originalProblemAcceptance?: string; - changes?: InspectChangePage[]; change?: InspectChangePage; sourceDigest?: string; - notes?: { file: string; sha256: string; bytes: number; text: string; offset: number; - nextOffset?: number; truncated: boolean; totalCharacters: number } | null }; -type StopReceipt = Awaited>>; - -/** A native session substitute with separately controlled turn settlement and writer shutdown. - * Tool cancellation waits for host callbacks, matching the native tool dispatcher's close contract. - * Git worktrees, source freezing, persistence, budgets and Lean checks remain real. */ -function controlledSession(options: MathAgentOptions, index: number) { - const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - const threadId = options.threadId ?? `native-${id}`; - const turnId = `${threadId}-turn-${index}`; - const started = deferred(), stopping = deferred(), outcome = deferred(); - const stopReceipt = deferred(); - const toolController = new AbortController(), pendingTools = new Set>(); - const notifications: string[] = []; - let message = '', messageId: string | undefined, runSettled = false, closed = false, calls = 0; - const abort = () => { - toolController.abort(new Error('fixture-tool-cancelled')); - void Promise.allSettled([...pendingTools]).then(() => outcome.resolve('interrupted')); - }; - options.signal?.addEventListener('abort', abort, { once: true }); - const session: MathAgentSession = { - threadId, usageSource: 'upstream-requests', - get lastCompletedResponse() { return runSettled ? { turnId, text: `Saved research by ${id}.` } : undefined; }, - run: async (input, inputMessageId, _workspace, onStarted) => { - message = input; messageId = inputMessageId; onStarted(turnId); started.resolve(); - try { return await outcome.promise; } finally { runSettled = true; } - }, - notify: async input => { notifications.push(input); }, - interrupt: async () => { abort(); }, - stopForFreeze: async () => { - stopping.resolve(); - const receipt = await stopReceipt.promise; - return runSettled && pendingTools.size === 0 ? receipt : { status: 'unconfirmed', reason: 'turn-not-settled' }; - }, - close: async () => { closed = true; options.signal?.removeEventListener('abort', abort); }, - }; - return { id, options, session, threadId, turnId, started, stopping, outcome, stopReceipt, notifications, - get message() { return message; }, get messageId() { return messageId; }, get closed() { return closed; }, - complete: () => { stopReceipt.resolve({ status: 'stopped' }); outcome.resolve('completed'); }, - call: (operation: Record) => { - const result = options.tools!.call('theoremos_team', operation, { - callId: `child-call-${++calls}`, turnId, threadId, signal: toolController.signal, - }).finally(() => { pendingTools.delete(result); }); - pendingTools.add(result); return result as Promise; - }, - }; -} - -function fixture({ maxTotalTokens = 0, maxAgents = 3, maxTurns = 16, maxTurnMs = 30_000, beforeOpen, beforeCheck }: { - maxTotalTokens?: number; maxAgents?: number; maxTurns?: number; maxTurnMs?: number; - beforeOpen?: (options: MathAgentOptions, attempt: number) => Promise; - beforeCheck?: (signal: AbortSignal) => Promise; -} = {}) { - const directory = temporaryDirectory('agent-research-team-'); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { source: original, task: 'Prove both frozen statements.' }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const root = path.resolve('.'); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, receipt.workspaceRoot, { runId: 'agent-team-integration', phase: 'running', - environmentDigest: mathDigest('real lean standard environment'), researchMode: 'skill', researchSkillWorkflow: 'full', - researchSkill: identity, researchDelegation: { mode: 'team', maxAgents }, workerCount: 1, coordination: 'independent', - // Global turns include children; this record accounts only for the Lead's requests. - usageAccounting: { startedTurns: 0, reportedTurns: 0, pending: false, incomplete: false }, - requestUsageAccounting: { startedRequests: 0, reportedRequests: 0, pendingRequests: 0, incomplete: false }, - }); - const skill = prepareResearchSkill(root, state.worktree, identity, problem); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); - const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - const controller = new AbortController(), sessions: ReturnType[] = [], teams: AgentResearchTeam[] = []; - const opened: MathAgentOptions[] = []; - const events: { event: string; details?: Record }[] = []; - const snapshots: SolverRunState[] = []; - const stateFile = path.join(directory, 'run-state.json'); - const modules = { ...directSolverModules, M1: { ...directSolverModules.M1, - open: async (options: MathAgentOptions) => { - const attempt = opened.push(options); await beforeOpen?.(options, attempt); - const current = controlledSession(options, sessions.length + 1); sessions.push(current); return current.session; - } } }; - const makeTeam = (currentState: SolverRunState) => { - const team = new AgentResearchTeam({ state: currentState, root, taskText: 'Prove both frozen statements.', - leadAccess: { environment, retrievalRoot: path.join(currentState.worktree, problem.projectRelative), researchSkill: skill }, - modules, executable: 'offline-no-model', profile: 'offline-no-credentials', signal: controller.signal, - maxAgents, maxTurns, maxTurnMs, maxTotalTokens, remainingMs: () => Infinity, - save: () => { writeSolverRunState(stateFile, currentState); snapshots.push(structuredClone(currentState)); }, - emit: (event, details) => { events.push({ event, details }); }, exclusiveCheck: async operation => { - await beforeCheck?.(controller.signal); return operation(); - }, - }); - teams.push(team); return team; - }; - const team = makeTeam(state); - let calls = 0; - const call = async (operation: Record, actor = 'lead', callId = `lead-call-${++calls}`, target = team) => - await target.tools(actor).call('theoremos_team', operation, { - callId, turnId: 'lead-turn', threadId: 'lead-thread', signal: controller.signal, - }) as ToolResult; - const current = { directory, root, environment, problem, state, stateFile, team, teams, sessions, opened, makeTeam, call, controller, events, snapshots, - source: (worktree: string) => path.join(worktree, problem.projectRelative, 'Submission.lean'), - session: async (id: string, occurrence = 0) => { - // A follow-up session may wait for an actual Lean check before dispatch. - await expect.poll(() => sessions.filter(item => item.id === id).length, { timeout: 10_000 }).toBeGreaterThan(occurrence); - const session = sessions.filter(item => item.id === id)[occurrence]!; await session.started.promise; return session; - }, - }; - fixtures.push(current); return current; -} - -afterEach(async () => { - for (const f of fixtures.splice(0)) { - f.controller.abort(); - for (const session of f.sessions) { - session.stopReceipt.resolve({ status: 'stopped' }); session.outcome.resolve('interrupted'); - } - await Promise.allSettled(f.teams.map(team => team.close())); - fs.rmSync(f.directory, { recursive: true, force: true }); - } -}); - -async function idle(team: AgentResearchTeam) { - await expect.poll(() => team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); -} - -/** Inspect the assignment actually sent to the native turn, independently of the context builder. */ -function dispatchedAssignment(message: string) { - const line = message.split('\n').find(line => line.startsWith('{"agentId":')); - expect(line, 'the native turn must receive its current structured assignment').toBeDefined(); - return JSON.parse(line!); -} - -describe('Agent-led sustained collaboration with real Git and Lean', () => { - it('automatically hands off a pending Lead adoption before more model work and resumes only after confirmed shutdown and integration', async () => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove the reusable equality helper.' }); - const producer = await f.session('producer'), worker = f.team.archive.workers[0]!; - const producerRequest = producer.options.requestGate!({ requestId: 'producer-proof', threadId: producer.threadId }); - if (!producerRequest.allowed) throw new Error(producerRequest.reason); - producerRequest.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 } }); - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - await producer.call({ operation: 'submit', summary: 'The reusable helper is proved.', declarations }); - producer.complete(); await idle(f.team); - const deliveryId = f.team.archive.deliveries[0]!.id; - await f.team.close(); - - const draft = original.replace('end Team', 'theorem leadDraft : True := by trivial\nend Team'); - const notes = 'The consumer draft is saved before requesting the checked helper.'; - const stopping = deferred(), stopReceipt = deferred(); - const opened: MathAgentOptions[] = []; - const modules = { ...directSolverModules, M1: { ...directSolverModules.M1, - open: async (options: MathAgentOptions): Promise => { - const turn = opened.push(options), threadId = options.threadId ?? 'adoption-persistent-lead'; - return { threadId, usageSource: 'upstream-requests', close: async () => {}, interrupt: async () => {}, - stopForFreeze: async () => { - if (turn !== 1) return { status: 'stopped' }; - stopping.resolve(); return stopReceipt.promise; - }, - run: async (_message, id, _workspace, started) => { - started(id); - expect(options.requestGate!.checkpoint!()).toBe(false); - const request = options.requestGate!({ requestId: `adoption-request-${turn}`, threadId }); - if (!request.allowed) throw new Error(request.reason); - if (turn === 1) { - fs.writeFileSync(f.source(f.state.worktree), draft); - fs.writeFileSync(path.join(f.state.worktree, 'RESEARCH.md'), notes); - const args = { operation: 'adopt', deliveryId }; - const context = { callId: 'adopt-helper', threadId, turnId: id, signal: f.controller.signal }; - const adoption = await options.tools!.call('theoremos_team', args, context); - expect(adoption).toMatchObject({ ok: true, adoption: { status: 'queued' } }); - expect(await options.tools!.call('theoremos_team', args, context)).toEqual(adoption); - // A pending response is never cancelled to obtain the writer. - expect(options.requestGate!.checkpoint!()).toBe(false); - request.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 } }); - // The model tries to continue after adopt; the next admission must yield. - expect(options.requestGate!.checkpoint!()).toBe(true); - expect(options.requestGate!.checkpoint!()).toBe(true); - expect(f.state.agentTeam!.adoptions).toHaveLength(1); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(draft); - return 'checkpoint'; - } - expect(turn).toBe(2); - expect(threadId).toBe('adoption-persistent-lead'); - expect(f.state.agentTeam!.adoptions[0]).toMatchObject({ status: 'completed', commit: expect.any(String) }); - const integrated = fs.readFileSync(f.source(f.state.worktree), 'utf8'); - expect(integrated).toContain(helper); - expect(integrated).toContain('theorem leadDraft : True := by trivial'); - expect(fs.readFileSync(path.join(f.state.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - request.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 } }); - fs.writeFileSync(f.source(f.state.worktree), integrated.replaceAll('by sorry', 'by trivial')); - return 'completed'; - } }; - } } }; - const running = runResearchWorkers({ state: f.state, root: f.root, taskText: 'Prove both frozen statements.', - workers: [{ id: 'solver', role: 'lead', worktree: f.state.worktree, ownedFiles: f.problem.ownedFiles }], - access: new Map([['solver', { environment: f.environment, - researchSkill: prepareResearchSkill(f.root, f.state.worktree, f.state.researchSkill!, f.problem), retrievalRoot: f.state.worktree }]]), - modules, buildFile: path.join(f.directory, 'unused-build.json'), executable: 'offline-no-model', profile: 'offline-no-credentials', - signal: f.controller.signal, deadline: Infinity, maxTurns: Infinity, maxTotalTokens: 0, maxTurnMs: Infinity, - save: () => writeSolverRunState(f.stateFile, f.state), emit: (event, details) => { f.events.push({ event, details }); } }); - void running.catch(() => {}); - await Promise.race([stopping.promise, running.then(() => { throw new Error('adoption-skipped-writer-shutdown'); })]); - try { - expect(opened).toHaveLength(1); - expect(f.state.agentTeam!.adoptions[0]!.status).toBe('queued'); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(draft); - } finally { stopReceipt.resolve({ status: 'stopped' }); } - const result = await running; - expect(result?.check.verification.status).toBe('kernel_verified'); - expect(opened.map(options => options.threadId)).toEqual([undefined, 'adoption-persistent-lead']); - expect(opened.every(options => options.turnCheckpointMs === undefined && options.turnTimeoutMs === undefined)).toBe(true); - expect(f.state.tokenBudget).toMatchObject({ status: 'unlimited', usageComplete: true, reportedTotalTokens: 9 }); - expect(f.state.requestUsageAccounting).toMatchObject({ startedRequests: 2, reportedRequests: 2, pendingRequests: 0 }); - expect(f.events.filter(event => event.event === 'team_adoption_checkpoint')).toHaveLength(1); - expect(f.events.filter(event => event.event === 'turn_checkpoint').map(event => event.details?.reason)) - .toEqual(['math_team_adoption_checkpoint']); - expect(f.state.agentTeam!.adoptions.map(adoption => adoption.status)).toEqual(['completed']); - }, 90_000); - - it('delivers a stopped fast writer while another researches, then freshly checks the Lead-selected adoption', async () => { - const f = fixture(); - expect(await f.call({ operation: 'spawn', agentId: 'fast', message: 'Prove a reusable equality helper.' })).toMatchObject({ ok: true }); - expect(await f.call({ operation: 'spawn', agentId: 'slow', message: 'Continue an independent investigation.' })).toMatchObject({ ok: true }); - const fast = await f.session('fast'), slow = await f.session('slow'); - const fastWorker = f.team.archive.workers.find(item => item.id === 'fast')!; - expect(fast.options).toMatchObject({ isolateProcess: true, threadId: undefined }); - expect(fast.options.hiddenRoots).toContain(f.state.worktree); - expect(fast.options.tools!.definitions.map(item => item.name)).toContain('theoremos_team'); - expect(fast.options.tools!.definitions.find(item => item.name === 'theoremos_team')!.inputSchema) - .toMatchObject({ properties: { operation: { enum: [ - 'progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', - 'route_summary'] } } }); - expect(fast.options.skills![0]!.digest).toBe(f.state.researchSkill!.digest); - const help = fs.readFileSync(path.join(fastWorker.worktree, RESEARCH_TOOL_HELP_FILE), 'utf8'); - expect(fast.options.instructions).toContain(path.join(fastWorker.worktree, RESEARCH_TOOL_HELP_FILE)); - expect(help).toMatch(/theoremos_team, operation submit/u); - expect(help).not.toContain('declaration-submission.json'); - expect(help).not.toMatch(/successful check-lean[^\n]*hands writing back automatically/u); - const deliveryWait = f.call({ operation: 'wait', after: 0, timeoutMs: 30_000 }); - fs.writeFileSync(f.source(fastWorker.worktree), original.replace('end Team', helper + 'end Team')); - expect(await fast.call({ operation: 'submit', summary: 'Equality helper proved.', declarations })) - .toMatchObject({ ok: true, status: 'pending-writer-stop' }); - fast.outcome.resolve('completed'); await fast.stopping.promise; - expect(f.team.archive.deliveries).toHaveLength(0); - expect(git(fastWorker.worktree, ['rev-parse', 'HEAD'])).toBe(fastWorker.seedCommit); - fast.stopReceipt.resolve({ status: 'stopped' }); - await expect.poll(() => f.team.archive.deliveries.length, { timeout: 60_000 }).toBe(1); - expect(fast.closed).toBe(true); expect(slow.closed).toBe(false); - expect(f.team.archive.workers.find(item => item.id === 'slow')!.status).toBe('running'); - const delivery = f.team.archive.deliveries[0]!; - const proof = readAgentTeamProofDelivery(delivery.path, f.state); - expect(proof.artifacts[0]!.proof.verification.results[0]).toMatchObject({ status: 'kernel_verified', sorryCount: 0 }); - expect((await deliveryWait).events).toContainEqual(expect.objectContaining({ kind: 'delivery', from: 'fast' })); - expect(await f.call({ operation: 'inspect', deliveryId: delivery.id })).toMatchObject({ ok: true, - id: delivery.id, declarations, changes: [expect.objectContaining({ name: 'reusable', source: expect.stringContaining('by rfl') })], - originalProblemAcceptance: 'not-assessed' }); - expect(await f.call({ operation: 'adopt', deliveryId: delivery.id, targetId: 'slow' })) - .toMatchObject({ ok: false, error: 'math_team_target_writing' }); - expect(await f.call({ operation: 'adopt', deliveryId: delivery.id })).toMatchObject({ ok: true, adoption: { status: 'queued' } }); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(original); - await f.team.flushAdoptions(); - const adopted = f.team.archive.adoptions[0]!; - expect(adopted).toMatchObject({ targetId: 'lead', status: 'completed', commit: expect.any(String) }); - const merged = fs.readFileSync(f.source(f.state.worktree), 'utf8'); - expect(merged).toContain(helper); expect(merged.match(/by sorry/gu)).toHaveLength(2); - expect(fs.readFileSync(f.source(f.team.archive.workers.find(item => item.id === 'slow')!.worktree), 'utf8')).toBe(original); - expect(f.state.phase).toBe('running'); expect(f.state.check).toBeUndefined(); - slow.complete(); await idle(f.team); - // An idle child can adopt a checked declaration and keep its independent source history. - expect(await f.call({ operation: 'adopt', deliveryId: delivery.id, targetId: 'slow' })) - .toMatchObject({ ok: true }); - await idle(f.team); - expect(f.team.archive.adoptions.at(-1)!.status).toBe('completed'); - expect(fs.readFileSync(f.source(f.team.archive.workers.find(item => item.id === 'slow')!.worktree), 'utf8')).toContain(helper); - await f.team.close(); - const saved = readSolverRunState(f.stateFile), restored = f.makeTeam(saved); - await restored.restore(); - expect(restored.archive.deliveries).toEqual(f.team.archive.deliveries); - expect(restored.archive.adoptions.map(adoption => adoption.status)).toEqual(['completed', 'completed']); - expect(f.sessions).toHaveLength(2); expect(restored.hasActiveWorkers).toBe(false); - expect(saved.check).toBeUndefined(); - }, 90_000); - - it('persists messages, resumes one native child thread, and does not replay completed tasks on restore', async () => { - const f = fixture(); - const spawn = { operation: 'spawn', agentId: 'researcher', message: 'Profiles: D006, researcher\nInvestigate the interface.' }; - const firstHandle = await f.call(spawn, 'lead', 'spawn-once'); - expect(await f.call(spawn, 'lead', 'spawn-once')).toEqual(firstHandle); - const first = await f.session('researcher'); - const profileRecord = (message: string) => JSON.parse(message.split('\n') - .find(line => line.startsWith('{"schema":"theorem-os.agent-team-profile-evidence.v1"'))!); - expect(profileRecord(first.message)).toMatchObject({ loaded: ['D006', 'researcher'], unresolved: [] }); - const firstWorker = f.team.archive.workers[0]!; - expect(currentWorkerProject(firstWorker.worktree)).toBe(path.join(firstWorker.worktree, f.state.problem.projectRelative)); - expect(fs.existsSync(path.join(firstWorker.worktree, 'COOPERATION.json'))).toBe(false); - expect(await f.call({ operation: 'message', agentId: 'researcher', message: 'Please keep the useful notes.' })) - .toMatchObject({ ok: true, delivery: 'saved-inbox', notification: 'queued' }); - expect(first.notifications[0]).toContain('Please keep the useful notes.'); - const leadMessages: string[] = []; - f.team.setLeadSession({ run: async () => 'completed', interrupt: async () => {}, close: async () => {}, - notify: async message => { leadMessages.push(message); } }); - expect(await first.call({ operation: 'message', agentId: 'lead', message: 'The interface needs a closed hypothesis.' })) - .toMatchObject({ ok: true, delivery: 'saved-inbox', notification: 'queued' }); - expect(leadMessages).toEqual([expect.stringContaining('The interface needs a closed hypothesis.')]); - f.team.setLeadSession({ run: async () => 'completed', interrupt: async () => {}, close: async () => {}, - notify: async () => { throw new Error('lead-turn-already-closed'); } }); - expect(await first.call({ operation: 'message', agentId: 'lead', message: 'Keep this message between turns.' })) - .toMatchObject({ ok: true, delivery: 'saved-inbox' }); - expect((await f.call({ operation: 'poll' })).events).toContainEqual(expect.objectContaining({ text: 'Keep this message between turns.' })); - expect((await first.call({ operation: 'poll' })).events).toContainEqual(expect.objectContaining({ text: 'Please keep the useful notes.' })); - const worktree = f.team.archive.workers[0]!.worktree; - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), 'A durable research note.'); - first.complete(); await idle(f.team); await f.team.close(); - const saved = readSolverRunState(f.stateFile); - expect(saved.agentTeam!.workers[0]).toMatchObject({ threadId: first.threadId, tasks: [{ status: 'completed' }] }); - const resumed = f.makeTeam(saved); await resumed.restore(); - expect(f.sessions).toHaveLength(1); expect(resumed.hasActiveWorkers).toBe(false); - expect(await f.call({ operation: 'message', agentId: 'researcher', message: 'New explicit assignment follows.' }, 'lead', undefined, resumed)) - .toMatchObject({ ok: true, delivery: 'saved-inbox' }); - expect(await f.call({ operation: 'assign', agentId: 'researcher', message: 'Profiles: D064, engineer\nUse your saved notes to continue.' }, 'lead', undefined, resumed)) - .toMatchObject({ ok: true }); - const second = await f.session('researcher', 1); - expect(second.options.threadId).toBe(first.threadId); expect(second.threadId).toBe(first.threadId); - expect(second.message).toContain('New explicit assignment follows.'); - expect(second.message).toContain('Use your saved notes to continue.'); - expect(profileRecord(second.message)).toMatchObject({ loaded: ['D064', 'engineer'], unresolved: [] }); - expect(second.message).not.toContain('Profile D006 ('); - expect(fs.readFileSync(path.join(worktree, 'RESEARCH.md'), 'utf8')).toBe('A durable research note.'); - second.complete(); await idle(resumed); - expect(resumed.archive.workers[0]!.tasks.map(task => task.status)).toEqual(['completed', 'completed']); - expect(resumed.archive.operations.filter(operation => operation.key.includes('spawn-once'))).toHaveLength(1); - }); - - it('publishes current research to new and resumed members and notifies a member already researching', async () => { - const f = fixture(); - const firstSummary = 'Route A: the consumer needs a closed equality helper; boundary assumptions remain open.'; - const firstPublication = await f.call({ operation: 'publish', summary: firstSummary }); - expect(firstPublication).toMatchObject({ ok: true, - researchState: { revision: 1, summary: firstSummary, publishedAt: expect.any(Number), advisory: true } }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Investigate the current shared route.' }); - const first = await f.session('child'); - expect(dispatchedAssignment(first.message).researchState).toMatchObject({ revision: 1, summary: firstSummary, advisory: true }); - - const revisedSummary = 'Route A is blocked at its boundary case. Route B reuses the same equality interface.'; - expect(await f.call({ operation: 'publish', summary: revisedSummary })).toMatchObject({ ok: true, - researchState: { revision: 2, summary: revisedSummary, advisory: true } }); - expect(first.notifications.some(message => message.includes('research-updated') && message.includes(revisedSummary))).toBe(true); - const inbox = await first.call({ operation: 'poll' }); - expect(inbox.researchState).toMatchObject({ revision: 2, summary: revisedSummary, advisory: true }); - expect(inbox.events).toContainEqual(expect.objectContaining({ from: 'lead', to: 'child', kind: 'research-updated' })); - first.complete(); await idle(f.team); await f.team.close(); - - const saved = readSolverRunState(f.stateFile), resumed = f.makeTeam(saved); - await resumed.restore(); - expect(f.sessions).toHaveLength(1); - await f.call({ operation: 'assign', agentId: 'child', message: 'Continue from the revised route.' }, 'lead', undefined, resumed); - const second = await f.session('child', 1); - expect(second.threadId).toBe(first.threadId); - expect(dispatchedAssignment(second.message).researchState).toMatchObject({ revision: 2, summary: revisedSummary, advisory: true }); - expect((await f.call({ operation: 'poll' }, 'lead', undefined, resumed)).researchState) - .toMatchObject({ revision: 2, summary: revisedSummary }); - second.complete(); await idle(resumed); - expect(saved.check).toBeUndefined(); - }); - - it('shares paged non-Lean research at its stopped source commit while later edits remain private', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'researcher', message: 'Save an advisory obstruction without a formal declaration.' }); - const first = await f.session('researcher'), worker = f.team.archive.workers[0]!; - const notes = '# Boundary calculation\n' + '同一假设下的计算仍需证明。\n'.repeat(25) + 'The missing premise is not established.\n'; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), notes); - first.outcome.resolve('completed'); await first.stopping.promise; - expect(worker.tasks[0]!.researchArtifactId).toBeUndefined(); - first.stopReceipt.resolve({ status: 'stopped' }); await idle(f.team); - const completed = worker.tasks[0]!; - expect(completed).toMatchObject({ status: 'completed', sourceCommit: expect.stringMatching(/^[a-f0-9]{40,64}$/u), - researchArtifactId: expect.stringMatching(/^[a-f0-9]{64}$/u) }); - const artifactId = completed.researchArtifactId!; - expect(git(worker.worktree, ['show', `${completed.sourceCommit}:RESEARCH.md`])).toBe(notes.trim()); - expect(f.team.archive.deliveries).toHaveLength(0); - const snapshot = await f.call({ operation: 'poll' }); - expect(snapshot.researchArtifacts).toContainEqual(expect.objectContaining({ id: artifactId, - agentId: 'researcher', taskId: completed.id, commit: completed.sourceCommit })); - expect(snapshot.researchArtifacts!.some(reference => Object.hasOwn(reference, 'path'))).toBe(false); - - const firstPage = await f.call({ operation: 'inspect-research', artifactId, offset: 0, limit: 31 }); - expect(firstPage).toMatchObject({ ok: true, id: artifactId, commit: completed.sourceCommit, - advisory: true, originalProblemAcceptance: 'not-assessed', - notes: { file: 'RESEARCH.md', text: notes.slice(0, 31), offset: 0, nextOffset: 31, truncated: true, - bytes: Buffer.byteLength(notes), totalCharacters: notes.length, sha256: mathDigest(notes) } }); - expect(JSON.stringify(firstPage)).not.toContain(f.directory); - await f.call({ operation: 'assign', agentId: 'researcher', message: 'Explore a revised assumption using the old note.' }); - const second = await f.session('researcher', 1); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'A private revision with a different conclusion.'); - await f.call({ operation: 'spawn', agentId: 'consumer', message: 'Read the other member\'s fixed research evidence.' }); - const consumer = await f.session('consumer'); - expect(dispatchedAssignment(consumer.message).researchArtifacts) - .toContainEqual(expect.objectContaining({ id: artifactId, commit: completed.sourceCommit })); - let recovered = firstPage.notes!.text, offset = firstPage.notes!.nextOffset; - while (offset !== undefined) { - const page = await consumer.call({ operation: 'inspect-research', artifactId, offset, limit: 31 }); - expect(page).toMatchObject({ ok: true, commit: completed.sourceCommit, advisory: true }); - recovered += page.notes!.text; offset = page.notes!.nextOffset; - } - expect(recovered).toBe(notes); - expect(await f.call({ operation: 'adopt', deliveryId: artifactId })).toMatchObject({ ok: false }); - expect(f.team.archive.adoptions).toHaveLength(0); expect(f.state.check).toBeUndefined(); - second.complete(); consumer.complete(); await idle(f.team); await f.team.close(); - const resumed = f.makeTeam(readSolverRunState(f.stateFile)); await resumed.restore(); - expect((await f.call({ operation: 'inspect-research', artifactId }, 'lead', undefined, resumed)).notes!.text).toBe(notes); - expect(f.sessions).toHaveLength(3); - }); - - it('yields a draft, adopts a checked peer into it and resumes the same task before freshly checking the combined delivery', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove the reusable equality helper.' }); - await f.call({ operation: 'spawn', agentId: 'consumer', message: 'Prove Team.consumer using the forthcoming reusable helper.' }); - const producer = await f.session('producer'), consumer = await f.session('consumer'); - const producerWorker = f.team.archive.workers.find(worker => worker.id === 'producer')!; - const consumerWorker = f.team.archive.workers.find(worker => worker.id === 'consumer')!; - const task = consumerWorker.tasks[0]!, deliveryBase = task.seedCommit; - const draft = 'theorem consumer (n : Nat) : n = n := by sorry\n'; - fs.writeFileSync(f.source(consumerWorker.worktree), original.replace('end Team', draft + 'end Team')); - fs.writeFileSync(path.join(consumerWorker.worktree, 'RESEARCH.md'), 'Paused draft: waiting for the reusable helper.'); - expect(await consumer.call({ operation: 'yield', reason: 'Adopt the peer helper before continuing this draft.' })) - .toMatchObject({ ok: true, taskId: task.id, status: 'pending-writer-stop' }); - consumer.outcome.resolve('completed'); await consumer.stopping.promise; - expect(task.status).toBe('running'); expect(task.researchArtifactId).toBeUndefined(); - consumer.stopReceipt.resolve({ status: 'stopped' }); - fs.writeFileSync(f.source(producerWorker.worktree), original.replace('end Team', helper + 'end Team')); - await producer.call({ operation: 'submit', summary: 'Reusable helper proved.', declarations }); - producer.complete(); await idle(f.team); - expect(task).toMatchObject({ status: 'paused', turns: 1, pauseRequested: { kind: 'handoff' }, - sourceCommit: expect.any(String), researchArtifactId: expect.any(String) }); - const pausedArtifactId = task.researchArtifactId!, pausedCommit = task.sourceCommit!; - expect((await f.call({ operation: 'poll' })).workers!.find(worker => worker.id === 'consumer')) - .toMatchObject({ status: 'paused', activity: 'paused' }); - const peerDelivery = f.team.archive.deliveries[0]!; - expect(await f.call({ operation: 'adopt', deliveryId: peerDelivery.id, targetId: 'consumer' })).toMatchObject({ ok: true }); - await idle(f.team); - expect(consumerWorker.pendingSourceBase).toBe(deliveryBase); - expect(consumerWorker.pendingPeerDeliveries).toEqual([peerDelivery.id]); - expect(fs.readFileSync(f.source(consumerWorker.worktree), 'utf8')).toContain(draft); - expect(fs.readFileSync(f.source(consumerWorker.worktree), 'utf8')).toContain(helper); - - expect(await f.call({ operation: 'resume', agentId: 'consumer', taskId: task.id })).toMatchObject({ ok: true, taskId: task.id }); - const resumed = await f.session('consumer', 1); - expect(resumed.threadId).toBe(consumer.threadId); expect(resumed.messageId).toBe(task.id); - expect(consumerWorker.tasks).toHaveLength(1); expect(task.turns).toBe(2); - expect(dispatchedAssignment(resumed.message)).toMatchObject({ taskId: task.id, - deliveryBaseCommit: deliveryBase, sourceCommit: git(consumerWorker.worktree, ['rev-parse', 'HEAD']) }); - // The proof author puts the adopted dependency before its consumer in Lean source order. - const connected = fs.readFileSync(f.source(consumerWorker.worktree), 'utf8').replace(helper, '').replace(draft, - helper + 'theorem consumer (n : Nat) : n = n := by exact reusable n\n'); - fs.writeFileSync(f.source(consumerWorker.worktree), connected); - fs.writeFileSync(path.join(consumerWorker.worktree, 'RESEARCH.md'), 'Resumed draft: consumer now applies the adopted reusable helper.'); - const ownDeclarations = [{ file: 'Submission.lean', name: 'Team.consumer', type: '∀ n : Nat, n = n' }]; - await resumed.call({ operation: 'submit', summary: 'Consumer connected to the peer helper.', declarations: ownDeclarations }); - resumed.complete(); await idle(f.team); - - expect(task.declarations).toEqual(ownDeclarations); - expect(task, JSON.stringify({ error: task.error, source: fs.readFileSync(f.source(consumerWorker.worktree), 'utf8') })) - .toMatchObject({ status: 'completed', turns: 2, deliveryId: expect.any(String) }); - const combined = f.team.archive.deliveries.find(delivery => delivery.agentId === 'consumer')!; - const checked = readAgentTeamProofDelivery(combined.path, f.state); - expect(checked.seedCommit).toBe(deliveryBase); - expect(checked.declarations).toEqual([...declarations, ...ownDeclarations]); - expect(checked.artifacts.map(artifact => artifact.declaration.name).toSorted()).toEqual(['Team.consumer', 'Team.reusable']); - expect(checked.artifacts.every(artifact => artifact.proof.passed && artifact.proof.verification.status === 'kernel_verified')).toBe(true); - expect(consumerWorker.pendingPeerDeliveries).toBeUndefined(); expect(consumerWorker.pendingSourceBase).toBeUndefined(); - expect(task.researchArtifactId).not.toBe(pausedArtifactId); expect(task.sourceCommit).not.toBe(pausedCommit); - expect(await f.call({ operation: 'inspect-research', artifactId: pausedArtifactId })) - .toMatchObject({ commit: pausedCommit, notes: { text: 'Paused draft: waiting for the reusable helper.' } }); - expect(await f.call({ operation: 'inspect-research', artifactId: task.researchArtifactId })) - .toMatchObject({ commit: task.sourceCommit, notes: { text: 'Resumed draft: consumer now applies the adopted reusable helper.' } }); - expect(f.team.archive.researchArtifacts!.filter(artifact => artifact.taskId === task.id)).toHaveLength(2); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it('pauses a settled turn checkpoint and resumes the same saved task and thread with cumulative usage', async () => { - const f = fixture({ maxTotalTokens: 100, maxTurns: 5 }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Develop a draft and retain useful partial work.', - budget: { tokens: 50, turns: 2 } }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - const deliveryBase = task.seedCommit; - const settle = (session: typeof first, requestId: string, totalTokens: number) => { - const admission = session.options.requestGate!({ requestId, threadId: session.threadId }); - expect(admission).toMatchObject({ allowed: true }); - if (!admission.allowed) throw new Error(admission.reason); - admission.settle({ complete: true, outcome: 'completed', usage: { inputTokens: totalTokens - 2, outputTokens: 2, totalTokens } }); - }; - settle(first, 'checkpoint-request', 20); - const draft = original.replace('end Team', 'theorem draft (n : Nat) : n = n := by sorry\nend Team'); - const notes = 'Saved partial work at the turn boundary; the same investigation remains open.'; - fs.writeFileSync(f.source(worker.worktree), draft); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), notes); - first.outcome.resolve('checkpoint'); await first.stopping.promise; - expect(task).toMatchObject({ status: 'running', pauseRequested: { kind: 'budget', reason: 'math_team_turn_checkpoint' } }); - expect(task.researchArtifactId).toBeUndefined(); - expect(await f.call({ operation: 'resume', agentId: 'child', taskId: task.id })) - .toMatchObject({ ok: false, error: 'math_team_task_not_paused' }); - - first.stopReceipt.resolve({ status: 'stopped' }); await idle(f.team); - expect(task).toMatchObject({ status: 'paused', turns: 1, budget: { tokens: 50, turns: 2 }, - sourceCommit: expect.any(String), researchArtifactId: expect.any(String) }); - expect(worker).toMatchObject({ status: 'paused', activity: 'paused', pendingSourceBase: deliveryBase }); - expect(worker.writerStopUnconfirmed).toBeUndefined(); expect(first.closed).toBe(true); - expect(git(worker.worktree, ['show', `${task.sourceCommit}:${f.problem.projectRelative}/Submission.lean`])).toBe(draft.trim()); - expect((await f.call({ operation: 'inspect-research', artifactId: task.researchArtifactId })).notes!.text).toBe(notes); - expect(readSolverRunState(f.stateFile).agentTeam!.workers[0]!.tasks[0]) - .toMatchObject({ id: task.id, status: 'paused', turns: 1, sourceCommit: task.sourceCommit }); - expect(f.state.taskUsage![task.id]!.totalTokens).toBe(20); expect(f.sessions).toHaveLength(1); - - expect(await f.call({ operation: 'resume', agentId: 'child', taskId: task.id })).toMatchObject({ ok: true, taskId: task.id }); - const second = await f.session('child', 1); - expect(second.threadId).toBe(first.threadId); expect(second.messageId).toBe(task.id); - expect(dispatchedAssignment(second.message)).toMatchObject({ taskId: task.id, deliveryBaseCommit: deliveryBase, - sourceCommit: task.sourceCommit }); - expect(fs.readFileSync(f.source(worker.worktree), 'utf8')).toBe(draft); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - expect(task).toMatchObject({ status: 'running', turns: 2, budget: { tokens: 50, turns: 2 } }); - expect(task.pauseRequested).toBeUndefined(); expect(f.state.taskUsage![task.id]!.totalTokens).toBe(20); - settle(second, 'resumed-request', 5); - second.complete(); await idle(f.team); - expect(worker.tasks).toHaveLength(1); expect(task).toMatchObject({ status: 'completed', turns: 2 }); - expect(f.state.taskUsage![task.id]!.totalTokens).toBe(25); - expect(f.state.tokenBudget).toMatchObject({ status: 'available', reportedTotalTokens: 25, usageComplete: true }); - }); - - it('keeps an unlimited team free of invented task budgets while accounting for large input requests', async () => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - const schema = f.team.tools().definitions[0]!.inputSchema; - const properties = schema.properties as Record; - expect(properties.operation!.enum).not.toContain('budget'); - expect(properties).not.toHaveProperty('budget'); expect(properties).not.toHaveProperty('leadReserve'); - const invalid = { ok: false, error: 'math_team_budget_not_configured' }; - expect(await f.call({ operation: 'spawn', agentId: 'child', message: 'Work without a quota.', budget: { tokens: 25000 } })) - .toMatchObject(invalid); - expect(f.team.archive.workers).toHaveLength(0); - expect(await f.call({ operation: 'budget', leadReserve: { tokens: 1000 } })).toMatchObject(invalid); - expect(f.team.archive.leadReserve).toBeUndefined(); - - expect(await f.call({ operation: 'spawn', agentId: 'child', message: 'Work without a quota.' })).toMatchObject({ ok: true }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - expect(first.options.turnTimeoutMs).toBeUndefined(); expect(first.options.turnCheckpointMs).toBeUndefined(); - expect(await f.call({ operation: 'assign', agentId: 'child', message: 'Do not queue a capped task.', budget: { turns: 1 } })) - .toMatchObject(invalid); - expect(worker.tasks).toHaveLength(1); expect(task.budget).toBeUndefined(); - expect(await f.call({ operation: 'budget', agentId: 'child', taskId: task.id, budget: { tokens: 25000 } })) - .toMatchObject(invalid); - for (let request = 0; request < 3; request++) { - const admission = first.options.requestGate!({ requestId: `large-input-${request}`, threadId: first.threadId }); - expect(admission.allowed).toBe(true); - if (!admission.allowed) throw new Error(admission.reason); - admission.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 49500, outputTokens: 500, totalTokens: 50000 } }); - } - expect(task).toMatchObject({ status: 'running', turns: 1 }); expect(task.pauseRequested).toBeUndefined(); - expect(f.state.tokenBudget).toMatchObject({ status: 'unlimited', maxTotalTokens: 0, - reportedTotalTokens: 150000, usageComplete: true }); - expect(worker.requestUsageAccounting).toMatchObject({ startedRequests: 3, reportedRequests: 3, pendingRequests: 0, incomplete: false }); - first.complete(); await idle(f.team); - expect(task.status).toBe('completed'); expect(task.budget).toBeUndefined(); - }); - - it('retains older saved task caps as history without enforcing them in an unlimited run', async () => { - const f = fixture({ maxTurns: Infinity }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Continue saved work.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - // Stand in for the optional local cap retained in a historical run archive. - task.budget = { tokens: 1, turns: 1 }; f.team.archive.leadReserve = { tokens: 100, turns: 1 }; - const admission = first.options.requestGate!({ requestId: 'saved-allowance' }); - if (!admission.allowed) throw new Error(admission.reason); - admission.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 8, outputTokens: 2, totalTokens: 10 } }); - expect(await first.call({ operation: 'yield', reason: 'Wait for a peer dependency.' })).toMatchObject({ ok: true }); - first.complete(); await idle(f.team); - expect(task.status).toBe('paused'); - const restoredState = readSolverRunState(f.stateFile); - const restored = f.makeTeam(restoredState); - expect(await f.call({ operation: 'resume', agentId: 'child', taskId: task.id }, 'lead', 'resume-unlimited', restored)) - .toMatchObject({ ok: true }); - const resumed = await f.session('child', 1), restoredTask = restored.archive.workers[0]!.tasks[0]!; - expect(resumed.threadId).toBe(first.threadId); - const next = resumed.options.requestGate!({ requestId: 'released-cap' }); - expect(next.allowed).toBe(true); - if (!next.allowed) throw new Error(next.reason); - next.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 30000, outputTokens: 100, totalTokens: 30100 } }); - expect(restoredTask.pauseRequested).toBeUndefined(); - expect(restoredTask.budget).toEqual({ tokens: 1, turns: 1 }); - expect(restored.archive.leadReserve).toEqual({ tokens: 100, turns: 1 }); - const overview = await f.call({ operation: 'poll' }, 'lead', 'poll-unlimited', restored); - expect(overview.budget).toMatchObject({ maxTurns: null, leadReserve: { tokens: 0, turns: 0 }, - remaining: { tokens: null, turns: null } }); - resumed.complete(); await idle(restored); - expect(restoredTask.status).toBe('completed'); - }); - - it('pauses at a cumulative task budget, resumes after Lead adjustment and retains the Lead turn reserve', async () => { - const f = fixture({ maxTotalTokens: 100, maxTurns: 5 }); - expect(await f.call({ operation: 'budget', leadReserve: { tokens: 40, turns: 2 } })).toMatchObject({ ok: true }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Investigate within the allocated allowance.', budget: { tokens: 20, turns: 1 } }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - const settle = (session: typeof first, requestId: string, totalTokens: number) => { - const admission = session.options.requestGate!({ requestId, threadId: session.threadId }); - expect(admission).toMatchObject({ allowed: true }); - if (!admission.allowed) throw new Error(admission.reason); - admission.settle({ complete: true, outcome: 'completed', usage: { inputTokens: totalTokens - 2, outputTokens: 2, totalTokens } }); - }; - settle(first, 'first-paid-request', 20); - expect(first.options.requestGate!({ requestId: 'over-task-limit' })).toEqual({ allowed: false, reason: 'math_model_request_stopped' }); - expect(task.pauseRequested).toMatchObject({ kind: 'budget', reason: 'math_team_task_token_limit' }); - first.stopReceipt.resolve({ status: 'stopped' }); first.outcome.resolve('interrupted'); await idle(f.team); - expect(task).toMatchObject({ status: 'paused', turns: 1, budget: { tokens: 20, turns: 1 } }); - expect(worker.requestUsageAccounting!.receipts).toHaveLength(1); - expect(worker.requestUsageAccounting!.reportedRequests).toBe(1); - expect(f.state.taskUsage![task.id]!.totalTokens).toBe(20); - expect(await f.call({ operation: 'resume', agentId: 'child', taskId: task.id })) - .toMatchObject({ ok: false, error: 'math_team_task_token_limit' }); - - await f.call({ operation: 'budget', agentId: 'child', taskId: task.id, budget: { tokens: 30, turns: 2 } }); - await f.call({ operation: 'resume', agentId: 'child', taskId: task.id }); - const second = await f.session('child', 1); - expect(second.threadId).toBe(first.threadId); expect(second.messageId).toBe(task.id); expect(task.turns).toBe(2); - // The current turn may issue requests even though reserving it reached its own turn cap. - settle(second, 'second-paid-request', 5); - await second.call({ operation: 'yield', reason: 'Save the current evidence for Lead review.' }); - second.complete(); await idle(f.team); - expect(await f.call({ operation: 'resume', agentId: 'child', taskId: task.id })) - .toMatchObject({ ok: false, error: 'math_team_task_turn_limit' }); - await f.call({ operation: 'budget', agentId: 'child', taskId: task.id, budget: { tokens: 40, turns: 3 } }); - await f.call({ operation: 'resume', agentId: 'child', taskId: task.id }); - const third = await f.session('child', 2); - expect(third.messageId).toBe(task.id); expect(task.turns).toBe(3); - third.complete(); await idle(f.team); - expect(worker.tasks).toHaveLength(1); expect(f.state.taskUsage![task.id]!.totalTokens).toBe(25); - const queued = await f.call({ operation: 'assign', agentId: 'child', message: 'This next task must preserve Lead integration turns.', - budget: { tokens: 10, turns: 1 } }); - await idle(f.team); - const followup = worker.tasks.find(task => task.id === queued.taskId)!; - expect(followup).toMatchObject({ status: 'paused', turns: 0, budget: { tokens: 10, turns: 1 }, - pauseRequested: { kind: 'budget', reason: 'math_team_lead_turn_reserve' } }); - expect(f.sessions).toHaveLength(3); expect(f.state.turns).toBe(3); - expect(f.state.tokenBudget).toMatchObject({ status: 'available', reportedTotalTokens: 25 }); - expect((await f.call({ operation: 'poll' })).budget).toMatchObject({ - leadReserve: { tokens: 40, turns: 2 }, remaining: { tokens: 75, turns: 2 }, childRemaining: { tokens: 35, turns: 0 } }); - }); - - it('pauses another child request at the Lead token reserve while preserving truthful provider receipts', async () => { - const f = fixture({ maxTotalTokens: 50 }); - await f.call({ operation: 'budget', leadReserve: { tokens: 20, turns: 1 } }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Use the child allowance without spending the integration reserve.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - const request = first.options.requestGate!({ requestId: 'observed-thirty' }); - expect(request.allowed).toBe(true); - if (!request.allowed) throw new Error(request.reason); - request.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 25, outputTokens: 5, totalTokens: 30 } }); - expect(first.options.requestGate!({ requestId: 'must-remain-unstarted' })).toEqual({ allowed: false, reason: 'math_model_request_stopped' }); - first.stopReceipt.resolve({ status: 'stopped' }); first.outcome.resolve('interrupted'); await idle(f.team); - expect(task).toMatchObject({ status: 'paused', turns: 1, - pauseRequested: { kind: 'budget', reason: 'math_team_lead_token_reserve' } }); - expect(f.state.tokenBudget).toMatchObject({ status: 'available', usageComplete: true, reportedTotalTokens: 30 }); - expect(worker.requestUsageAccounting!.receipts!.map(receipt => receipt.requestId)).toEqual(['observed-thirty']); - await f.call({ operation: 'budget', leadReserve: { tokens: 0, turns: 1 } }); - expect(await f.call({ operation: 'resume', agentId: 'child', taskId: task.id })).toMatchObject({ ok: true }); - const second = await f.session('child', 1); - expect(second.threadId).toBe(first.threadId); expect(task.turns).toBe(2); - second.complete(); await idle(f.team); - }); - - it('saves completed nominations with their pending delivery and recovers the earlier completion-before-pending format', async () => { - const checking = deferred(), release = deferred(); let checks = 0; - const f = fixture({ beforeCheck: async signal => { - if (++checks === 1) { - signal.addEventListener('abort', () => release.resolve(), { once: true }); - checking.resolve(); await release.promise; - } - } }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Prove the reusable helper and nominate it for checking.' }); - const child = await f.session('child'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'The nominated helper must be checked after recovery.'); - await child.call({ operation: 'submit', summary: 'Helper saved for independent checking.', declarations }); - child.complete(); await checking.promise; - const nominations = f.snapshots.filter(snapshot => { - const savedTask = snapshot.agentTeam?.workers[0]?.tasks[0]; - return savedTask?.status === 'completed' && savedTask.declarations?.length && !savedTask.deliveryId; - }); - expect(nominations.length).toBeGreaterThan(0); - for (const snapshot of nominations) { - const savedWorker = snapshot.agentTeam!.workers[0]!, savedTask = savedWorker.tasks[0]!; - expect(savedTask).toMatchObject({ sourceCommit: expect.any(String), researchArtifactId: expect.any(String) }); - expect(savedWorker.pendingDelivery).toMatchObject({ taskId: savedTask.id, seedCommit: savedTask.seedCommit, declarations }); - expect(snapshot.agentTeam!.researchArtifacts).toContainEqual(expect.objectContaining({ id: savedTask.researchArtifactId, - commit: savedTask.sourceCommit, taskId: savedTask.id })); - } - const legacy = readSolverRunState(f.stateFile), legacyWorker = legacy.agentTeam!.workers[0]!; - legacyWorker.pendingDelivery = undefined; - expect(legacyWorker.tasks[0]).toMatchObject({ status: 'completed', declarations, researchArtifactId: expect.any(String) }); - release.resolve(); await idle(f.team); await f.team.close(); - expect(task.deliveryId).toBeDefined(); - - const resumed = f.makeTeam(legacy); await resumed.restore(); - expect(f.sessions).toHaveLength(1); expect(resumed.hasActiveWorkers).toBe(false); - expect(legacyWorker.pendingDelivery).toBeUndefined(); expect(legacyWorker.tasks[0]!.deliveryId).toBeDefined(); - expect(resumed.archive.deliveries).toHaveLength(1); - const checked = readAgentTeamProofDelivery(resumed.archive.deliveries[0]!.path, legacy); - expect(checked.declarations).toEqual(declarations); - expect(checked.artifacts[0]!.proof.verification.status).toBe('kernel_verified'); - }, 90_000); - - it('reports checking, integrating and paused activity with request usage and recent execution evidence', async () => { - const started = [deferred(), deferred()], release = [deferred(), deferred()]; let checks = 0; - const f = fixture({ beforeCheck: async signal => { - const index = checks++; - if (index < 2) { - signal.addEventListener('abort', () => release[index]!.resolve(), { once: true }); - started[index]!.resolve(); await release[index]!.promise; - } - } }); - try { - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove a helper whose checking will wait.' }); - await f.call({ operation: 'spawn', agentId: 'consumer', message: 'Pause until the peer helper is checked.' }); - const producer = await f.session('producer'), consumer = await f.session('consumer'); - const producerWorker = f.team.archive.workers.find(worker => worker.id === 'producer')!; - const consumerWorker = f.team.archive.workers.find(worker => worker.id === 'consumer')!; - producer.options.onActivity!({ event: 'command_output', itemType: 'commandExecution' }); - const paid = producer.options.requestGate!({ requestId: 'producer-check-cost' }); - if (!paid.allowed) throw new Error(paid.reason); - paid.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 8, outputTokens: 2, totalTokens: 10 } }); - fs.writeFileSync(f.source(producerWorker.worktree), original.replace('end Team', helper + 'end Team')); - await producer.call({ operation: 'submit', summary: 'A helper awaiting its real Lean check.', declarations }); - producer.complete(); - await consumer.call({ operation: 'yield', reason: 'Use the checked peer result before further writing.' }); - consumer.complete(); await started[0]!.promise; - const waiting = (await f.call({ operation: 'poll' })).workers!; - expect(waiting.find(worker => worker.id === 'producer')).toMatchObject({ activity: 'checking', - pendingDelivery: { taskId: producerWorker.tasks[0]!.id, declarationCount: 1 }, - usage: { reportedTotalTokens: 10, usageComplete: true, reportedRequests: 1 }, - lastActivity: { event: 'command_output', itemType: 'commandExecution', at: expect.any(Number) } }); - await expect.poll(() => consumerWorker.status).toBe('paused'); - expect((await f.call({ operation: 'poll' })).workers!.find(worker => worker.id === 'consumer')) - .toMatchObject({ status: 'paused', activity: 'paused' }); - release[0]!.resolve(); await idle(f.team); - await f.call({ operation: 'adopt', deliveryId: f.team.archive.deliveries[0]!.id, targetId: 'consumer' }); - await started[1]!.promise; - expect((await f.call({ operation: 'poll' })).workers!.find(worker => worker.id === 'consumer')) - .toMatchObject({ status: 'paused', activity: 'integrating' }); - release[1]!.resolve(); await idle(f.team); - expect((await f.call({ operation: 'poll' })).workers!.find(worker => worker.id === 'consumer')) - .toMatchObject({ status: 'paused', activity: 'paused' }); - } finally { for (const gate of release) gate.resolve(); } - }, 90_000); - - it('checks a recovered running nomination without replaying a model turn or inventing task completion', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Save and submit a helper before the interrupted turn returns.' }); - const child = await f.session('child'), worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'A submit acknowledgment precedes turn completion.'); - await child.call({ operation: 'submit', summary: 'Nominated source before the interrupted response finishes.', declarations }); - const checkpoint = readSolverRunState(f.stateFile), recoveredWorker = checkpoint.agentTeam!.workers[0]!; - expect(recoveredWorker.tasks[0]).toMatchObject({ status: 'running', declarations, seedCommit: expect.any(String) }); - expect(recoveredWorker.pendingDelivery).toBeUndefined(); - const closing = f.team.close(); child.stopReceipt.resolve({ status: 'stopped' }); await closing; - const saveIndex = f.snapshots.length; - const resumed = f.makeTeam(checkpoint); await resumed.restore(); - - expect(f.sessions).toHaveLength(1); expect(resumed.hasActiveWorkers).toBe(false); - const task = recoveredWorker.tasks[0]!; - expect(task).toMatchObject({ status: 'interrupted', deliveryId: expect.any(String), - sourceCommit: expect.any(String), researchArtifactId: expect.any(String) }); - const firstInterrupted = f.snapshots.slice(saveIndex).find(snapshot => snapshot.agentTeam!.workers[0]!.tasks[0]!.status === 'interrupted')!; - expect(firstInterrupted).toBeDefined(); - expect(firstInterrupted.agentTeam!.workers[0]!.pendingDelivery).toMatchObject({ taskId: task.id, - seedCommit: task.seedCommit, declarations }); - expect(firstInterrupted.agentTeam!.workers[0]!.tasks[0]!.researchArtifactId).toBeDefined(); - expect(resumed.archive.deliveries).toHaveLength(1); - const proof = readAgentTeamProofDelivery(resumed.archive.deliveries[0]!.path, checkpoint); - expect(proof.declarations).toEqual(declarations); - expect(proof.artifacts[0]!.proof.verification.status).toBe('kernel_verified'); - expect(checkpoint.check).toBeUndefined(); - }, 90_000); - - it('cancels only the selected queued task and does not replay it after restoring the member', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Keep the current useful investigation.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!; - const obsolete = await f.call({ operation: 'assign', agentId: 'child', message: 'An obsolete follow-up.' }); - const useful = await f.call({ operation: 'assign', agentId: 'child', message: 'A complementary follow-up that remains useful.' }); - expect(await f.call({ operation: 'cancel', agentId: 'child', taskId: obsolete.taskId, reason: 'The interface changed.' })) - .toMatchObject({ ok: true }); - expect(worker.tasks.map(task => task.status)).toEqual(['running', 'cancelled', 'queued']); - expect(worker.tasks[1]!.cancelRequested).toMatchObject({ reason: 'The interface changed.' }); - expect(first.closed).toBe(false); expect(worker.status).toBe('running'); - first.complete(); - const second = await f.session('child', 1); - expect(second.threadId).toBe(first.threadId); expect(second.messageId).toBe(useful.taskId); - expect(second.messageId).not.toBe(obsolete.taskId); - second.complete(); await idle(f.team); await f.team.close(); - const resumed = f.makeTeam(readSolverRunState(f.stateFile)); await resumed.restore(); - expect(f.sessions).toHaveLength(2); expect(resumed.hasActiveWorkers).toBe(false); - expect(resumed.archive.workers[0]!.tasks.map(task => task.status)).toEqual(['completed', 'cancelled', 'completed']); - }); - - it('stops a cancelled task before replacing it in the same thread and retains its source draft and notes', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Develop a draft for the old route.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!, oldTask = worker.tasks[0]!; - const draft = original.replace('end Team', helper + 'end Team'); - fs.writeFileSync(f.source(worker.worktree), draft); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Old route: equality helper saved; the wider claim remains open.'); - expect(await f.call({ operation: 'cancel', agentId: 'child', taskId: oldTask.id, - reason: 'The consumer needs another route.', replacement: 'Continue the saved helper under the revised route.' })) - .toMatchObject({ ok: true }); - await first.stopping.promise; - expect(oldTask.cancelRequested).toMatchObject({ reason: 'The consumer needs another route.', replacementTaskId: expect.any(String) }); - const replacement = worker.tasks.find(task => task.id === oldTask.cancelRequested!.replacementTaskId)!; - expect(replacement).toMatchObject({ status: 'queued', message: 'Continue the saved helper under the revised route.' }); - expect(f.sessions).toHaveLength(1); expect(first.closed).toBe(false); - expect(oldTask.researchArtifactId).toBeUndefined(); - first.stopReceipt.resolve({ status: 'stopped' }); - const second = await f.session('child', 1); - expect(first.closed).toBe(true); expect(oldTask.status).toBe('cancelled'); - expect(second.threadId).toBe(first.threadId); expect(second.messageId).toBe(replacement.id); - expect(oldTask).toMatchObject({ sourceCommit: expect.any(String), researchArtifactId: expect.any(String) }); - expect(dispatchedAssignment(second.message).previousTask).toMatchObject({ id: oldTask.id, status: 'cancelled' }); - expect(fs.readFileSync(f.source(worker.worktree), 'utf8')).toBe(draft); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toContain('Old route: equality helper saved'); - expect(worker.status).toBe('running'); - second.complete(); await idle(f.team); await f.team.close(); - const resumed = f.makeTeam(readSolverRunState(f.stateFile)); await resumed.restore(); - expect(f.sessions).toHaveLength(2); expect(resumed.archive.workers[0]!.status).not.toBe('stopped'); - expect(resumed.archive.workers[0]!.tasks.map(task => task.status)).toEqual(['cancelled', 'completed']); - }); - - it('cancels a completed model response still awaiting writer shutdown without publishing its submitted proof', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Develop the helper on the old route.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!, oldTask = worker.tasks[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - await first.call({ operation: 'submit', summary: 'Candidate from the superseded route.', declarations }); - first.outcome.resolve('completed'); await first.stopping.promise; - const cancelled = await f.call({ operation: 'cancel', agentId: 'child', taskId: oldTask.id, - replacement: 'Continue with the revised route.' }); - expect(cancelled).toMatchObject({ ok: true, status: 'stopping', replacementTaskId: expect.any(String) }); - expect(await f.call({ operation: 'cancel', agentId: 'child', taskId: oldTask.id, - replacement: 'A retry must not create another task.' })) - .toMatchObject({ ok: true, replacementTaskId: cancelled.replacementTaskId }); - expect(worker.tasks).toHaveLength(2); expect(worker.tasks[1]!.status).toBe('queued'); - expect(f.sessions).toHaveLength(1); expect(f.team.archive.deliveries).toHaveLength(0); - first.stopReceipt.resolve({ status: 'stopped' }); - const second = await f.session('child', 1); - expect(oldTask.status).toBe('cancelled'); expect(second.messageId).toBe(cancelled.replacementTaskId); - expect(second.threadId).toBe(first.threadId); - expect(f.team.archive.deliveries).toHaveLength(0); expect(worker.pendingDelivery).toBeUndefined(); - expect((await f.call({ operation: 'inspect-research', artifactId: oldTask.researchArtifactId })).advisory).toBe(true); - second.complete(); await idle(f.team); - }); - - it('restores an in-flight cancellation without replaying the old task or duplicating its queued replacement', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Investigate the obsolete route.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!; - const draft = original.replace('end Team', helper + 'end Team'); - fs.writeFileSync(f.source(worker.worktree), draft); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'A saved draft survives the cancellation checkpoint.'); - await f.call({ operation: 'cancel', agentId: 'child', taskId: worker.tasks[0]!.id, - reason: 'Superseded route.', replacement: 'Use the saved draft on the replacement route.' }); - await first.stopping.promise; - // Capture the durable crash checkpoint while the writer still has to confirm shutdown. - const checkpoint = readSolverRunState(f.stateFile), checkpointWorker = checkpoint.agentTeam!.workers[0]!; - expect(checkpointWorker.tasks[0]).toMatchObject({ status: 'running', cancelRequested: { - replacementTaskId: checkpointWorker.tasks[1]!.id } }); - expect(checkpointWorker.tasks[1]!.status).toBe('queued'); - const closing = f.team.close(); first.stopReceipt.resolve({ status: 'stopped' }); await closing; - - const resumed = f.makeTeam(checkpoint); await resumed.restore(); - const replacement = await f.session('child', 1); - expect(replacement.threadId).toBe(first.threadId); - expect(replacement.messageId).toBe(checkpointWorker.tasks[1]!.id); - expect(checkpointWorker.tasks).toHaveLength(2); - expect(checkpointWorker.tasks[0]).toMatchObject({ status: 'cancelled', sourceCommit: expect.any(String), - researchArtifactId: expect.any(String) }); - expect(f.sessions.filter(session => session.messageId === checkpointWorker.tasks[0]!.id)).toHaveLength(1); - expect(fs.readFileSync(f.source(checkpointWorker.worktree), 'utf8')).toBe(draft); - expect((await f.call({ operation: 'inspect-research', artifactId: checkpointWorker.tasks[0]!.researchArtifactId }, - 'lead', undefined, resumed)).notes!.text).toBe('A saved draft survives the cancellation checkpoint.'); - replacement.complete(); await idle(resumed); - }); - - it('quarantines a cancelled writer with unconfirmed shutdown before publishing research or starting its replacement', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Develop a candidate helper.' }); - const child = await f.session('child'), worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'This draft still has a writer whose shutdown is unconfirmed.'); - await child.call({ operation: 'submit', summary: 'Candidate pending host checking.', declarations }); - await f.call({ operation: 'cancel', agentId: 'child', taskId: worker.tasks[0]!.id, - replacement: 'Continue only after the previous writer is proven stopped.' }); - await child.stopping.promise; - child.stopReceipt.resolve({ status: 'unconfirmed', reason: 'cancelled-writer-not-stopped' }); - await idle(f.team); - expect(worker.writerStopUnconfirmed).toMatchObject({ reason: 'cancelled-writer-not-stopped' }); - expect(worker.tasks[0]!.researchArtifactId).toBeUndefined(); - expect(worker.tasks[1]!.status).toBe('queued'); - expect(f.team.archive.deliveries).toHaveLength(0); expect(f.sessions).toHaveLength(1); - expect(git(worker.worktree, ['rev-parse', 'HEAD'])).toBe(worker.seedCommit); - await expect(f.team.close()).rejects.toThrow('math_writer_stop_unconfirmed:child'); - const resumed = f.makeTeam(readSolverRunState(f.stateFile)); - await expect(resumed.restore()).rejects.toThrow('math_writer_stop_unconfirmed:child'); - expect(f.sessions).toHaveLength(1); - }); - - it('keeps messages and stop responsive while an idle child adoption waits for Lean', async () => { - const checkStarted = deferred(), releaseCheck = deferred(); let checks = 0; - const f = fixture({ beforeCheck: async signal => { - if (++checks === 2) { - signal.addEventListener('abort', () => releaseCheck.resolve(), { once: true }); - checkStarted.resolve(); await releaseCheck.promise; - } - } }); - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove the reusable helper.' }); - await f.call({ operation: 'spawn', agentId: 'consumer', message: 'Investigate before receiving the helper.' }); - const producer = await f.session('producer'), consumer = await f.session('consumer'); - fs.writeFileSync(f.source(f.team.archive.workers.find(worker => worker.id === 'producer')!.worktree), - original.replace('end Team', helper + 'end Team')); - await producer.call({ operation: 'submit', summary: 'Reusable helper ready.', declarations }); - producer.complete(); consumer.complete(); await idle(f.team); - const deliveryId = f.team.archive.deliveries[0]!.id; - const adopting = f.call({ operation: 'adopt', deliveryId, targetId: 'consumer' }); - let timer: ReturnType | undefined; - try { - await checkStarted.promise; - const interactions = Promise.all([adopting, - f.call({ operation: 'message', agentId: 'consumer', message: 'This update must not wait for Lean.' }), - f.call({ operation: 'stop', agentId: 'consumer' })]); - const results = await Promise.race([interactions, new Promise(resolve => { timer = setTimeout(resolve, 1000); })]); - expect(results, 'slow Lean integration must release the team mutation queue').toBeDefined(); - expect(results?.map(result => result.ok)).toEqual([true, true, true]); - expect(f.team.archive.events).toContainEqual(expect.objectContaining({ to: 'consumer', text: 'This update must not wait for Lean.' })); - } finally { clearTimeout(timer); releaseCheck.resolve(); await adopting; } - await idle(f.team); - expect(f.team.archive.workers.find(worker => worker.id === 'consumer')!.status).toBe('stopped'); - expect(f.sessions.filter(session => session.id === 'consumer')).toHaveLength(1); - }, 90_000); - - it('rejects child scheduling and adoption, altered call replay, and delivery by the Lead', async () => { - const f = fixture(); - expect(f.team.tools('lead').definitions.find(item => item.name === 'theoremos_team')!.inputSchema) - .toMatchObject({ properties: { operation: { enum: [ - 'spawn', 'assign', 'amend', 'finish', 'budget', 'resume', 'history', 'publish', 'cancel', - 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'retire_route', 'route_summary'] } } }); - const spawn = { operation: 'spawn', agentId: 'child', message: 'Study independently.' }; - await f.call(spawn, 'lead', 'one-handle'); - const child = await f.session('child'); - await expect(f.call({ ...spawn, message: 'Different replay.' }, 'lead', 'one-handle')).rejects.toThrow('math_team_call_changed'); - expect(await child.call({ operation: 'spawn', agentId: 'intruder', message: 'Unauthorized assignment.' })) - .toMatchObject({ ok: false, error: 'math_team_lead_operation_required' }); - expect(await child.call({ operation: 'adopt', deliveryId: 'a'.repeat(64) })) - .toMatchObject({ ok: false, error: 'math_team_lead_operation_required' }); - expect(await child.call({ operation: 'publish', summary: 'A child cannot replace the shared route.' })) - .toMatchObject({ ok: false, error: 'math_team_lead_operation_required' }); - expect(await child.call({ operation: 'cancel', agentId: 'child', taskId: f.team.archive.workers[0]!.tasks[0]!.id })) - .toMatchObject({ ok: false, error: 'math_team_lead_operation_required' }); - expect(await f.call({ operation: 'submit', summary: 'Lead is not a child.', declarations })) - .toMatchObject({ ok: false, error: 'math_team_child_submission_required' }); - expect(f.team.archive.workers.map(worker => worker.id)).toEqual(['child']); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(original); - child.complete(); await idle(f.team); - }); - - it('restores an explicitly queued follow-up without replaying the completed turn ahead of it', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'First assignment.' }); - const first = await f.session('child'); - first.outcome.resolve('completed'); await first.stopping.promise; - await f.call({ operation: 'assign', agentId: 'child', message: 'The already authorized follow-up.' }); - const closing = f.team.close(); - first.stopReceipt.resolve({ status: 'stopped' }); await closing; - const saved = readSolverRunState(f.stateFile); - expect(saved.agentTeam!.workers[0]!.tasks.map(task => task.status)).toEqual(['completed', 'queued']); - const resumed = f.makeTeam(saved); await resumed.restore(); - const second = await f.session('child', 1); - expect(second.options.threadId).toBe(first.threadId); - expect(second.message).toContain('The already authorized follow-up.'); - expect(saved.agentTeam!.workers[0]!.tasks.map(task => task.status)).toEqual(['completed', 'running']); - second.complete(); await idle(resumed); - expect(f.sessions).toHaveLength(2); - expect(saved.agentTeam!.workers[0]!.tasks.map(task => task.status)).toEqual(['completed', 'completed']); - }); - - it.each(['invalid-proof', 'undeclared-helper', 'missing-name', 'outside-ownership'] as const)('reports %s as correctable feedback without publishing a delivery', async kind => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Prove a reusable helper.' }); - const child = await f.session('child'), worktree = f.team.archive.workers[0]!.worktree; - const addition = kind === 'invalid-proof' ? helper.replace('by rfl', 'by exact False.elim (by trivial)') - : kind === 'undeclared-helper' ? helper + 'theorem unlisted : True := by trivial\n' : helper; - fs.writeFileSync(f.source(worktree), original.replace('end Team', addition + 'end Team')); - const submission = await child.call({ operation: 'submit', summary: 'Candidate helper.', declarations: kind === 'missing-name' - ? [{ ...declarations[0], name: 'Team.missing' }] : kind === 'outside-ownership' - ? [{ ...declarations[0], file: 'NotOwned.lean' }] : declarations }); - if (kind === 'outside-ownership') { - expect(submission).toMatchObject({ ok: false, error: 'math_agent_team_proof_declaration_outside_ownership' }); - expect(f.team.archive.workers[0]!.tasks[0]!.declarations).toBeUndefined(); - } - child.complete(); await idle(f.team); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(f.team.archive.workers[0]!.pendingDelivery).toBeUndefined(); - if (kind !== 'outside-ownership') expect(f.team.archive.events).toContainEqual(expect.objectContaining({ from: 'child', to: 'lead', kind: 'failed', - text: expect.stringContaining({ 'invalid-proof': 'math_declaration_artifact_check_failed', - 'undeclared-helper': 'undeclared_source_change', 'missing-name': 'declaration_missing', - 'outside-ownership': 'declaration_outside_ownership' }[kind]) })); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(original); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it.each(['rejected', 'deferred'] as const)('transfers saved sources after a %s delivery is corrected in the same child thread', async kind => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Develop the reusable helper.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!; - const initial = kind === 'rejected' ? helper.replace('by rfl', 'by exact False.elim (by trivial)') : helper; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', initial + 'end Team')); - if (kind === 'rejected') await first.call({ operation: 'submit', summary: 'Candidate helper.', declarations }); - first.complete(); await idle(f.team); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(worker.pendingSourceBase).toBe(worker.tasks[0]!.seedCommit); - const previousTask = worker.tasks[0]!, leadDiagnostic = 'lead-only-failure-unrelated-to-this-child'; - if (kind === 'rejected') { - expect(previousTask.error).toContain('math_declaration_artifact_check_failed'); - const commit = git(f.state.worktree, ['rev-parse', 'HEAD']), checkedAt = Date.now(); - f.state.check = { commit, sourceDigest: mathDigest(original), passed: false, verification: { - schema: 'deepscientist.mathematics.verification-batch/v1', sessionId: 'lead-check', status: 'failed', targetCommit: commit, - results: [{ status: 'failed', targetCommit: commit, statementHash: mathDigest(f.problem.contract.formalStatement), - claim: 'statement', proofHash: mathDigest(original), proofPath: 'Submission.lean', theoremName: f.problem.targets[0]!.theoremName, - statementBinding: 'caller-bound-to-committed-declaration', toolchain: { lean: path.join(f.environment.PATH.split(':')[0]!, 'lean') }, - verifier: 'lean-kernel', goalsRemaining: 1, sorryCount: 1, admitCount: 0, axioms: [], checkedAt, - checkId: 'lead-check-1', receiptId: 'lead-failure-receipt', sessionId: 'lead-check', error: 'lean_compilation_failed', - stdoutPreview: `Submission.lean:2:1: error: ${leadDiagnostic}\n` }], - events: [], startedAt: checkedAt, checkedAt, durationMs: 0, - } }; - } - const objective = 'Finish the saved helper and submit its exact declaration.'; - await f.call({ operation: 'assign', agentId: 'child', message: objective }); - const second = await f.session('child', 1); - expect(second.options.threadId).toBe(first.threadId); - expect(worker.tasks[1]!.seedCommit).toBe(worker.tasks[0]!.seedCommit); - const assignment = dispatchedAssignment(second.message); - expect(assignment).toMatchObject({ agentId: 'child', coordinator: 'lead', taskId: worker.tasks[1]!.id, objective, - sourceCommit: git(worker.worktree, ['rev-parse', 'HEAD']), deliveryBaseCommit: worker.pendingSourceBase, - previousTask: { id: previousTask.id, status: kind === 'rejected' ? 'failed' : 'completed', summary: previousTask.summary } }); - expect(second.messageId).toBe(assignment.taskId); - expect(assignment.previousTask.error).toBe(previousTask.error); - expect(second.message).not.toContain(leadDiagnostic); - expect(fs.readFileSync(f.source(worker.worktree), 'utf8')).toContain(initial); - if (kind === 'rejected') expect(readSolverRunState(f.stateFile).check).toEqual(f.state.check); - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - await second.call({ operation: 'submit', summary: 'The equality helper is ready.', declarations }); - second.complete(); await idle(f.team); - expect(worker.pendingSourceBase).toBeUndefined(); expect(worker.pendingDelivery).toBeUndefined(); - expect(f.team.archive.deliveries).toHaveLength(1); - await f.call({ operation: 'adopt', deliveryId: f.team.archive.deliveries[0]!.id }); - await f.team.flushAdoptions(); - expect(f.team.archive.adoptions[0]).toMatchObject({ status: 'completed' }); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain(helper); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it('charges children to one request budget and refuses later dispatch once their receipts exhaust it', async () => { - const f = fixture({ maxTotalTokens: 50 }); - await f.call({ operation: 'spawn', agentId: 'first', message: 'First independent investigation.' }); - await f.call({ operation: 'spawn', agentId: 'second', message: 'Second independent investigation.' }); - const first = await f.session('first'), second = await f.session('second'); - for (const [index, session] of [first, second].entries()) { - const admission = session.options.requestGate!({ requestId: `request-${index}`, threadId: session.threadId }); - expect(admission).toMatchObject({ allowed: true }); - if (!admission.allowed) throw new Error(admission.reason); - const totalTokens = index === 0 ? 20 : 30; - const receipt = { usage: { inputTokens: totalTokens - 2, outputTokens: 2, totalTokens }, complete: true, outcome: 'completed' as const }; - admission.settle(receipt); admission.settle(receipt); - } - expect(f.state.teamUsage).toMatchObject({ totalTokens: 50, inputTokens: 46, outputTokens: 4 }); - expect(f.state.tokenBudget).toMatchObject({ status: 'exhausted', reportedTotalTokens: 50, reason: 'math_total_token_limit' }); - expect(first.options.requestGate!({ requestId: 'too-late' })).toEqual({ allowed: false, reason: 'math_total_token_limit' }); - first.complete(); second.complete(); await idle(f.team); - expect(f.team.archive.workers.map(worker => worker.requestUsageAccounting!.reportedRequests)).toEqual([1, 1]); - expect(f.state.tokenBudget!.usageComplete).toBe(true); - await f.call({ operation: 'assign', agentId: 'first', message: 'This assignment must await another authorized budget.' }); - await idle(f.team); expect(f.sessions).toHaveLength(2); - expect(f.team.archive.workers[0]!.tasks.at(-1)!.status).toBe('queued'); - }); - - it('retries an infrastructure-interrupted adoption with its original expected commit', async () => { - let checks = 0; - const f = fixture({ beforeCheck: async () => { - if (++checks === 2) throw new DeclarationArtifactCheckError(declarations[0], { - status: 'unavailable', results: [{ status: 'unavailable', error: 'offline-lean-infrastructure-unavailable' }], - } as never); - } }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Prove the equality helper.' }); - const child = await f.session('child'), worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - await child.call({ operation: 'submit', summary: 'Reusable equality proof.', declarations }); - child.complete(); await idle(f.team); - await f.call({ operation: 'adopt', deliveryId: f.team.archive.deliveries[0]!.id }); - await expect(f.team.flushAdoptions()).rejects.toThrow('offline-lean-infrastructure-unavailable'); - const adoption = f.team.archive.adoptions[0]!; - const expectedCommit = adoption.expectedCommit; - expect(adoption.status).toBe('integrating'); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(original); - await f.team.flushAdoptions(); - expect(adoption).toMatchObject({ status: 'completed', expectedCommit, error: undefined }); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain(helper); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it.each(['assign', 'adopt'] as const)('finishes a pending child adoption before %s may continue research', async operation => { - const checkStarted = deferred(), releaseCheck = deferred(); let checks = 0; - const f = fixture({ beforeCheck: async signal => { - if (++checks === 2) throw new Error('offline-integration-infrastructure-unavailable'); - if (checks === 3) { - signal.addEventListener('abort', () => releaseCheck.resolve(), { once: true }); - checkStarted.resolve(); await releaseCheck.promise; - } - } }); - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove a reusable helper.' }); - await f.call({ operation: 'spawn', agentId: 'consumer', message: 'Investigate before receiving the helper.' }); - const producer = await f.session('producer'), consumer = await f.session('consumer'); - const producerWorker = f.team.archive.workers.find(item => item.id === 'producer')!; - const consumerWorker = f.team.archive.workers.find(item => item.id === 'consumer')!; - fs.writeFileSync(f.source(producerWorker.worktree), original.replace('end Team', helper + 'end Team')); - await producer.call({ operation: 'submit', summary: 'Helper ready for another researcher.', declarations }); - producer.complete(); consumer.complete(); await idle(f.team); - const deliveryId = f.team.archive.deliveries[0]!.id; - expect(await f.call({ operation: 'adopt', deliveryId, targetId: 'consumer' })) - .toMatchObject({ ok: true }); - await idle(f.team); - const adoption = f.team.archive.adoptions[0]!; - const expectedCommit = adoption.expectedCommit; - expect(adoption.status).toBe('integrating'); - const assignment = { operation: 'assign', agentId: 'consumer', message: 'Continue using the checked helper.' }; - const continuation = f.call(operation === 'assign' ? assignment : { operation: 'adopt', deliveryId, targetId: 'consumer' }); - await checkStarted.promise; - expect(f.sessions).toHaveLength(2); - expect(adoption).toMatchObject({ status: 'integrating', expectedCommit }); - expect(fs.readFileSync(f.source(consumerWorker.worktree), 'utf8')).toBe(original); - if (operation === 'assign') expect(consumerWorker.tasks.at(-1)!.status).toBe('queued'); - releaseCheck.resolve(); - expect(await continuation).toMatchObject({ ok: true }); - if (operation === 'adopt') await f.call(assignment); - const resumed = await f.session('consumer', 1); - expect(adoption).toMatchObject({ status: 'completed', expectedCommit, error: undefined }); - expect(resumed.threadId).toBe(consumer.threadId); - expect(fs.readFileSync(f.source(consumerWorker.worktree), 'utf8')).toContain(helper); - expect(f.team.archive.adoptions).toHaveLength(1); - resumed.complete(); await idle(f.team); - }, 90_000); - - it('accepts a restored completed adoption before admitting another model turn', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Prove both original declarations.' }); - const child = await f.session('child'), worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replaceAll('by sorry', 'by trivial')); - await child.call({ operation: 'submit', summary: 'Both original declarations proved.', declarations: [ - { file: 'Submission.lean', name: 'Team.original', type: 'True' }, - { file: 'Submission.lean', name: 'Team.other', type: 'True' }, - ] }); - child.complete(); await idle(f.team); - await f.call({ operation: 'adopt', deliveryId: f.team.archive.deliveries[0]!.id }); - await f.team.flushAdoptions(); await f.team.close(); - const state = readSolverRunState(f.stateFile); - expect(state.check).toBeUndefined(); - expect(state.pendingResearchFreeze).toMatchObject({ commit: state.agentTeam!.adoptions[0]!.commit }); - let modelCalls = 0; - const resumedSkill = prepareResearchSkill(f.root, state.worktree, state.researchSkill!, f.problem); - const result = await runResearchWorkers({ state, root: f.root, taskText: 'Prove both frozen statements.', - workers: [{ id: 'solver', role: 'lead', worktree: state.worktree, ownedFiles: f.problem.ownedFiles }], - access: new Map([['solver', { environment: f.environment, researchSkill: resumedSkill, retrievalRoot: state.worktree }]]), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: async () => { - modelCalls++; throw new Error('unexpected-model-after-frozen-adoption'); - } } }, - buildFile: path.join(f.directory, 'unneeded-build.json'), executable: 'offline-no-model', profile: 'offline-no-credentials', - signal: f.controller.signal, deadline: Infinity, maxTurns: state.turns, maxTotalTokens: 0, maxTurnMs: Infinity, - save: () => writeSolverRunState(f.stateFile, state), emit: () => {}, - }); - expect(modelCalls).toBe(0); - expect(result?.check.verification.status).toBe('kernel_verified'); - expect(result?.check.verification.results).toHaveLength(2); - expect(state.pendingResearchFreeze).toBeUndefined(); expect(state.pendingProofCheck).toBeUndefined(); - expect(state.turns).toBe(1); - }, 90_000); - - it('releases a shared turn reservation after opening a child session fails', async () => { - const f = fixture({ maxTotalTokens: 50, beforeOpen: async (_options, attempt) => { - if (attempt === 1) throw new Error('offline-native-session-open-failed'); - } }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'First opening fails before any model turn.' }); - await idle(f.team); - expect(f.opened).toHaveLength(1); expect(f.sessions).toHaveLength(0); - expect(f.state.turns).toBe(0); expect(f.team.archive.workers[0]!.turns).toBe(0); - expect(f.team.archive.workers[0]!.tasks[0]).toMatchObject({ status: 'failed', error: 'offline-native-session-open-failed' }); - expect(f.state.tokenBudget).toMatchObject({ status: 'available', usageComplete: true, reportedTotalTokens: 0 }); - await f.call({ operation: 'assign', agentId: 'child', message: 'Explicitly retry after the opening failure.' }); - const child = await f.session('child'); - expect(f.state.turns).toBe(1); expect(f.team.archive.workers[0]!.turns).toBe(1); - child.complete(); await idle(f.team); - expect(f.opened).toHaveLength(2); - expect(f.team.archive.workers[0]!.tasks.map(task => task.status)).toEqual(['failed', 'completed']); - }); - - it('keeps an undelivered inbox cursor across failed session openings until a turn actually starts', async () => { - const opening = [deferred(), deferred(), deferred()], release = [deferred(), deferred(), deferred()]; - const f = fixture({ beforeOpen: async (_options, attempt) => { - opening[attempt - 1]!.resolve(); await release[attempt - 1]!.promise; - if (attempt < 3) throw new Error(`offline-open-failure-${attempt}`); - } }); - try { - await f.call({ operation: 'spawn', agentId: 'child', message: 'Initial assignment waits while opening.' }); - await opening[0]!.promise; - const worker = f.team.archive.workers[0]!; - const message = 'Retain this finding until a native turn actually receives it.'; - expect(await f.call({ operation: 'message', agentId: 'child', message })) - .toMatchObject({ ok: true, delivery: 'saved-inbox' }); - const event = f.team.archive.events.find(event => event.to === 'child' && event.text === message)!; - release[0]!.resolve(); await idle(f.team); - expect(worker.cursor).toBe(0); - - await f.call({ operation: 'assign', agentId: 'child', message: 'Retry with the saved inbox included.' }); - await opening[1]!.promise; - expect(worker.cursor).toBe(0); - release[1]!.resolve(); await idle(f.team); - expect(f.sessions).toHaveLength(0); - expect(readSolverRunState(f.stateFile).agentTeam!.workers[0]!.cursor).toBe(0); - - await f.call({ operation: 'assign', agentId: 'child', message: 'Start the assignment after recovery.' }); - await opening[2]!.promise; - expect(worker.cursor).toBe(0); - release[2]!.resolve(); - const child = await f.session('child'), assignment = dispatchedAssignment(child.message); - expect(assignment).toMatchObject({ taskId: worker.tasks[2]!.id, - previousTask: { id: worker.tasks[1]!.id, status: 'failed', error: 'offline-open-failure-2' }, - inbox: { after: 0, through: event.sequence, events: [expect.objectContaining({ sequence: event.sequence, - from: 'lead', to: 'child', kind: 'message', text: message })] } }); - expect(child.messageId).toBe(assignment.taskId); - expect(child.message).toContain(message); - expect(worker.cursor).toBe(event.sequence); - expect(readSolverRunState(f.stateFile).agentTeam!.workers[0]!.cursor).toBe(event.sequence); - child.complete(); await idle(f.team); - expect(worker.tasks.map(task => task.status)).toEqual(['failed', 'failed', 'completed']); - } finally { - for (const gate of release) gate.resolve(); - } - }); - - it('retains capacity until an asynchronously stopped writer has actually confirmed shutdown', async () => { - const f = fixture({ maxAgents: 2 }); - await f.call({ operation: 'spawn', agentId: 'old', message: 'Keep the only child writer slot.' }); - const old = await f.session('old'); - expect(await f.call({ operation: 'stop', agentId: 'old' })).toMatchObject({ ok: true, status: 'stopping' }); - await old.stopping.promise; - expect(await f.call({ operation: 'spawn', agentId: 'replacement', message: 'Must wait for the old writer to stop.' })) - .toMatchObject({ ok: false, error: 'math_team_capacity_exceeded' }); - expect(f.opened).toHaveLength(1); - old.stopReceipt.resolve({ status: 'stopped' }); await idle(f.team); - expect(await f.call({ operation: 'spawn', agentId: 'replacement', message: 'The writer slot is available now.' })).toMatchObject({ ok: true }); - const replacement = await f.session('replacement'); replacement.complete(); await idle(f.team); - expect(f.team.archive.workers.map(worker => worker.status)).toEqual(['stopped', 'idle']); - }); - - it('finishes a pending infrastructure-interrupted delivery before a queued follow-up may write', async () => { - const checkStarted = deferred(), releaseCheck = deferred(); let checks = 0; - const f = fixture({ beforeCheck: async signal => { - if (++checks === 1) throw new DeclarationArtifactCheckError(declarations[0], { - status: 'unavailable', results: [{ status: 'unavailable', error: 'offline-lean-infrastructure-unavailable' }], - } as never); - if (checks === 2) { - signal.addEventListener('abort', () => releaseCheck.resolve(), { once: true }); - checkStarted.resolve(); await releaseCheck.promise; - } - } }); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Prove a helper before continuing research.' }); - const first = await f.session('child'), worker = f.team.archive.workers[0]!; - const candidate = original.replace('end Team', helper + 'end Team'); - fs.writeFileSync(f.source(worker.worktree), candidate); - await first.call({ operation: 'submit', summary: 'Frozen helper awaiting its check.', declarations }); - first.complete(); await idle(f.team); - expect(worker.pendingDelivery).toMatchObject({ taskId: worker.tasks[0]!.id, commit: expect.any(String) }); - expect(f.team.archive.deliveries).toHaveLength(0); - await f.call({ operation: 'assign', agentId: 'child', message: 'Continue only after the previous delivery is checked.' }); - await checkStarted.promise; - expect(f.sessions).toHaveLength(1); - expect(fs.readFileSync(f.source(worker.worktree), 'utf8')).toBe(candidate); - expect(worker.tasks[1]!.status).toBe('queued'); - releaseCheck.resolve(); - const second = await f.session('child', 1); - expect(worker.pendingDelivery).toBeUndefined(); expect(f.team.archive.deliveries).toHaveLength(1); - expect(worker.tasks[0]!.deliveryId).toBe(f.team.archive.deliveries[0]!.id); - second.complete(); await idle(f.team); - expect(worker.tasks.map(task => task.status)).toEqual(['completed', 'completed']); - }, 90_000); - - it('quarantines unconfirmed writer shutdown and refuses recovery against a still-active persisted process', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Prove a helper.' }); - const child = await f.session('child'), worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - await child.call({ operation: 'submit', summary: 'A candidate requiring writer shutdown.', declarations }); - child.outcome.resolve('completed'); child.stopReceipt.resolve({ status: 'unconfirmed', reason: 'turn-not-settled' }); - await idle(f.team); - expect(worker.writerStopUnconfirmed).toMatchObject({ reason: 'turn-not-settled' }); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(git(worker.worktree, ['rev-parse', 'HEAD'])).toBe(worker.seedCommit); - await expect(f.team.close()).rejects.toThrow('math_writer_stop_unconfirmed:child'); - const saved = readSolverRunState(f.stateFile), resumed = f.makeTeam(saved); - await expect(resumed.restore()).rejects.toThrow('math_writer_stop_unconfirmed:child'); - expect(f.sessions).toHaveLength(1); - // A crash can leave a live writer identity even without an earlier shutdown failure. - saved.agentTeam!.workers[0]!.writerStopUnconfirmed = undefined; - const stat = fs.readFileSync(`/proc/${process.pid}/stat`, 'utf8'); - const processIdentity: HarnessProcessIdentity = { schema: 'theorem-os.harness-process-identity.v1', pid: process.pid, - startTime: stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/u)[19]!, - bootId: fs.readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim(), - pidNamespace: fs.readlinkSync(`/proc/${process.pid}/ns/pid`) }; - saved.agentTeam!.workers[0]!.writerProcess = processIdentity; - const crashResume = f.makeTeam(saved); - await expect(crashResume.restore()).rejects.toThrow('math_writer_stop_unconfirmed:child:previous-process-active'); - expect(f.sessions).toHaveLength(1); expect(f.team.archive.deliveries).toHaveLength(0); - }); - - it('returns every inbox event across bounded pages without advancing past unread messages', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'Read the full asynchronous inbox.' }); - const child = await f.session('child'); - const messages = [...Array.from({ length: 70 }, (_, index) => `Message ${index}`), - ...Array.from({ length: 6 }, (_, index) => `${index}:` + '界'.repeat(15_998))]; - for (const message of messages) await f.call({ operation: 'message', agentId: 'child', message }); - const received: AgentTeamState['events'] = []; - let cursor = 0, pages = 0, byteLimited = false; - while (received.length < messages.length) { - const page = await child.call({ operation: 'poll', after: cursor }); - expect(page.events.length).toBeGreaterThan(0); expect(page.events.length).toBeLessThanOrEqual(8); - expect(page.cursor).toBeGreaterThan(cursor); - const bytes = page.events.reduce((sum, event) => sum + Buffer.byteLength(JSON.stringify(event)), 0); - expect(bytes <= 128 * 1024 || page.events.length === 1).toBe(true); - if (pages === 0) expect(page.events).toHaveLength(8); - byteLimited ||= page.events.length < 8 && received.length + page.events.length < messages.length; - received.push(...page.events); cursor = page.cursor; pages++; - } - expect(byteLimited, 'large message bodies must stop a page before the item limit').toBe(true); - expect(received.map(event => event.text)).toEqual(messages); - expect(new Set(received.map(event => event.sequence)).size).toBe(messages.length); - child.complete(); await idle(f.team); - }); - - it('can stop a child while its cancellable host tool callback is queued without deadlocking dispatch', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'child', message: 'A writer with a pending host callback.' }); - const child = await f.session('child'); - child.stopReceipt.resolve({ status: 'stopped' }); - // Both calls enqueue in one tick: stop takes the mutation queue before submit; - // native run settles only once the cancelled tool callback has settled. - const stopping = f.call({ operation: 'stop', agentId: 'child' }); - const submitting = child.call({ operation: 'submit', summary: 'Racing shutdown.', declarations }); - const settledSubmit = submitting.catch(() => undefined); - let timer: ReturnType | undefined; - const result = await Promise.race([stopping, new Promise(resolve => { timer = setTimeout(resolve, 1000); })]); - clearTimeout(timer); - // Release the disposable stand-in even on regression so cleanup never hangs. - child.outcome.resolve('interrupted'); await Promise.allSettled([stopping, settledSubmit]); - expect(result).toMatchObject({ ok: true, agentId: 'child', status: 'stopping' }); - await idle(f.team); - expect(f.team.archive.workers[0]!.status).toBe('stopped'); - expect(f.team.archive.deliveries).toHaveLength(0); - }); -}); - -describe('Agent-owned unpaid handoff checkpoints', () => { - it('settles every paid request before a submit checkpoint and checks the nomination only after confirmed writer shutdown', async () => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove a reusable equality helper.' }); - await expect.poll(() => f.team.archive.workers[0]?.error ?? f.sessions.length).toBe(1); - const child = await f.session('producer'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - const gate = child.options.requestGate!; - expect(gate.checkpoint!()).toBe(false); - const first = gate({ requestId: 'nomination-paid-response', threadId: child.threadId }); - const second = gate({ requestId: 'nomination-parallel-response', threadId: child.threadId }); - if (!first.allowed || !second.allowed) throw new Error('fixture-request-refused'); - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', helper + 'end Team')); - expect(await child.call({ operation: 'submit', summary: 'The reusable helper is ready for independent checking.', declarations })) - .toMatchObject({ ok: true, status: 'pending-writer-stop' }); - expect(gate.checkpoint!()).toBe(false); - first.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 4, outputTokens: 2, totalTokens: 6 } }); - expect(gate.checkpoint!()).toBe(false); - // Other tools from the already paid response may still finish their output. - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'All tools finished before the unpaid handoff.'); - second.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 3, outputTokens: 1, totalTokens: 4 } }); - expect(gate.checkpoint!()).toBe(true); - expect(gate.checkpoint!()).toBe(true); - expect(child.closed).toBe(false); expect(child.options.signal?.aborted).toBe(false); - expect(worker.requestUsageAccounting).toMatchObject({ startedRequests: 2, reportedRequests: 2, pendingRequests: 0, incomplete: false }); - expect(f.team.archive.deliveries).toHaveLength(0); - - child.outcome.resolve('checkpoint'); await child.stopping.promise; - expect(task).toMatchObject({ status: 'running', declarations }); - expect(task.pauseRequested).toBeUndefined(); expect(task.researchArtifactId).toBeUndefined(); - expect(f.team.archive.deliveries).toHaveLength(0); - child.stopReceipt.resolve({ status: 'stopped' }); await idle(f.team); - expect(task).toMatchObject({ status: 'completed', turns: 1, deliveryId: expect.any(String), researchArtifactId: expect.any(String) }); - expect(task.pauseRequested).toBeUndefined(); - expect(f.sessions).toHaveLength(1); expect(child.closed).toBe(true); - expect(f.state.tokenBudget).toMatchObject({ status: 'unlimited' }); - expect(worker.usageAccounting).toMatchObject({ startedTurns: 1, reportedTurns: 1, pending: false, incomplete: false }); - const delivery = readAgentTeamProofDelivery(f.team.archive.deliveries[0]!.path, f.state); - expect(delivery.artifacts.every(artifact => artifact.proof.verification.status === 'kernel_verified')).toBe(true); - expect((await f.call({ operation: 'inspect-research', artifactId: task.researchArtifactId })).notes!.text) - .toBe('All tools finished before the unpaid handoff.'); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(original); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it('yields at the unpaid boundary and resumes the same task, thread and saved draft without a budget pause', async () => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - await f.call({ operation: 'spawn', agentId: 'consumer', message: 'Keep the current draft until a peer result is available.' }); - await expect.poll(() => f.team.archive.workers[0]?.error ?? f.sessions.length).toBe(1); - const first = await f.session('consumer'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - const draft = original.replace('end Team', 'theorem draft (n : Nat) : n = n := by sorry\nend Team'); - const gate = first.options.requestGate!; - const paid = gate({ requestId: 'yield-paid-response', threadId: first.threadId }); - if (!paid.allowed) throw new Error(paid.reason); - fs.writeFileSync(f.source(worker.worktree), draft); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Waiting for a checked peer interface.'); - expect(await first.call({ operation: 'yield', reason: 'Release the workspace so Lead can adopt the peer interface.' })) - .toMatchObject({ ok: true, taskId: task.id, status: 'pending-writer-stop' }); - expect(gate.checkpoint!()).toBe(false); - paid.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 4, outputTokens: 1, totalTokens: 5 } }); - expect(gate.checkpoint!()).toBe(true); - expect(first.options.signal?.aborted).toBe(false); - first.outcome.resolve('checkpoint'); await first.stopping.promise; - expect(task.status).toBe('running'); expect(task.sourceCommit).toBeUndefined(); - first.stopReceipt.resolve({ status: 'stopped' }); await idle(f.team); - expect(task).toMatchObject({ status: 'paused', turns: 1, pauseRequested: { kind: 'handoff' }, - sourceCommit: expect.any(String), researchArtifactId: expect.any(String) }); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(worker.requestUsageAccounting).toMatchObject({ startedRequests: 1, reportedRequests: 1, pendingRequests: 0, incomplete: false }); - expect(worker.usageAccounting).toMatchObject({ reportedTurns: 1, incomplete: false }); - const pausedArtifactId = task.researchArtifactId; - - expect(await f.call({ operation: 'resume', agentId: worker.id, taskId: task.id })).toMatchObject({ ok: true, taskId: task.id }); - const second = await f.session('consumer', 1); - expect(second.threadId).toBe(first.threadId); expect(second.messageId).toBe(task.id); - expect(worker.tasks).toHaveLength(1); expect(task.turns).toBe(2); - expect(task.pauseRequested).toBeUndefined(); expect(second.options.requestGate!.checkpoint!()).toBe(false); - expect(fs.readFileSync(f.source(worker.worktree), 'utf8')).toBe(draft); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe('Waiting for a checked peer interface.'); - const resumed = second.options.requestGate!({ requestId: 'resumed-paid-response', threadId: second.threadId }); - if (!resumed.allowed) throw new Error(resumed.reason); - resumed.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 3, outputTokens: 1, totalTokens: 4 } }); - second.complete(); await idle(f.team); - expect(task).toMatchObject({ status: 'completed', turns: 2 }); - expect(task.researchArtifactId).not.toBe(pausedArtifactId); - expect(f.state.tokenBudget).toMatchObject({ status: 'unlimited' }); - expect(worker.requestUsageAccounting).toMatchObject({ startedRequests: 2, reportedRequests: 2, pendingRequests: 0, incomplete: false }); - }, 90_000); - - it('persists Lead finish intent, waits for paid settlement and restores its checkpoint without another request', async () => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - let paidRequests = 0; - const gate = f.team.leadRequestGate(() => { - paidRequests++; f.state.requestUsageAccounting!.startedRequests++; f.state.requestUsageAccounting!.pendingRequests++; - return { allowed: true, settle: () => { - f.state.requestUsageAccounting!.reportedRequests++; f.state.requestUsageAccounting!.pendingRequests--; - } }; - }); - f.team.beginLeadTurn(); - const paid = gate({ requestId: 'finish-paid-response' }); - if (!paid.allowed) throw new Error(paid.reason); - const summary = 'The current source is ready for frozen independent acceptance.'; - expect(await f.call({ operation: 'finish', summary }, 'lead', 'finish-current-source')).toMatchObject({ ok: true }); - const persisted = readSolverRunState(f.stateFile); - expect(persisted.agentTeam!.completionRequested).toMatchObject({ summary, at: expect.any(Number) }); - expect(gate.checkpoint!()).toBe(false); expect(f.team.leadCompletionCheckpoint).toBe(false); - paid.settle({ complete: true, outcome: 'completed' }); - expect(gate.checkpoint!()).toBe(true); expect(gate.checkpoint!()).toBe(true); - expect(f.team.leadCompletionCheckpoint).toBe(true); - expect(f.events.filter(item => item.event === 'team_completion_checkpoint')).toHaveLength(1); - expect(f.events.filter(item => item.event === 'team_coordination_checkpoint')).toHaveLength(0); - expect(paidRequests).toBe(1); - // A crash after settlement preserves the intent and needs no paid rediscovery. - writeSolverRunState(f.stateFile, f.state); - const restored = f.makeTeam(readSolverRunState(f.stateFile)); - restored.beginLeadTurn(); - const recoveredGate = restored.leadRequestGate(() => { throw new Error('finish-must-stay-unpaid'); }); - expect(recoveredGate.checkpoint!()).toBe(true); expect(restored.leadCompletionCheckpoint).toBe(true); - expect(f.state.check).toBeUndefined(); expect(f.team.archive.deliveries).toHaveLength(0); - }); -}); - -describe('Task objectives, professional knowledge and source provenance', () => { - it('rejects unresolved new roles before a historical host-tool dispatch can change a running assignment', async () => { - const f = fixture(), agentId = 'specialist', message = 'Profiles: prover, uncatalogued\nCheck the interface.'; - const feedback = { ok: false, error: expect.stringContaining('math_team_profile_unresolved: ["uncatalogued"]') }; - expect(await f.call({ operation: 'spawn', agentId, message })).toMatchObject(feedback); - expect(f.team.archive.workers).toHaveLength(0); - await f.call({ operation: 'spawn', agentId, message: 'Profiles: graph-theory\nUse your custom expertise in the local encoding.' }); - const child = await f.session(agentId), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - const original = structuredClone(task), reason = 'Check the revised interface.'; - expect(task.profileEvidence?.loaded).toEqual(['D064']); - expect(await f.call({ operation: 'assign', agentId, message })).toMatchObject(feedback); - expect(await f.call({ operation: 'amend', agentId, taskId: task.id, message, reason })).toMatchObject(feedback); - expect(await f.call({ operation: 'cancel', agentId, taskId: task.id, replacement: message, reason })).toMatchObject(feedback); - expect(worker.tasks).toEqual([original]); - expect(child.notifications).toHaveLength(0); - }); - - it('amends a running objective without losing its draft, profile history or revision-bound progress', async () => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - await f.call({ operation: 'spawn', agentId: 'specialist', message: 'Profiles: D041, researcher\nInvestigate the stated assumptions.', workKind: 'independent-reconstruction' }); - const child = await f.session('specialist'), worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Retained draft.'); - const oldSource = task.profileEvidence!.sources[0]!; - const first = await child.call({ operation: 'progress', objectiveRevision: 1, kind: 'finding', summary: 'The assumption needs a precise boundary.', - nextStep: 'Check the boundary.', knowledgeUses: [{ anchor: oldSource.file + '#' + oldSource.anchor, application: 'Used the stated domain assumptions to identify the boundary.' }] }); - expect(first).toMatchObject({ ok: true, objectiveRevision: 1, advisory: true }); - const amendment = { operation: 'amend', agentId: worker.id, taskId: task.id, - message: 'Profiles: D006, engineer\nAssemble the specified checked interfaces.', reason: 'The useful output is now integration.', workKind: 'assembly' }; - expect(await f.call(amendment, 'lead', 'amendment-once')).toMatchObject({ ok: true, objectiveRevision: 2 }); - expect(await f.call(amendment, 'lead', 'amendment-once')).toMatchObject({ ok: true, objectiveRevision: 2 }); - expect(task.objectiveHistory).toHaveLength(1); - expect(task.objectiveHistory![0]).toMatchObject({ revision: 1, workKind: 'independent-reconstruction', - profileEvidence: { selected: ['D041', 'researcher'] } }); - expect(task.profileEvidence).toMatchObject({ selected: ['D006', 'engineer'], loaded: ['D006', 'engineer'] }); - expect(child.notifications.some(text => text.includes('"objectiveRevision":2') && text.includes('Assemble the specified checked interfaces.'))).toBe(true); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe('Retained draft.'); - expect(await child.call({ operation: 'progress', objectiveRevision: 1, kind: 'finding', summary: 'A finding from the earlier objective.' })) - .toMatchObject({ ok: false, error: 'math_team_objective_revision_changed' }); - expect(await child.call({ operation: 'submit', summary: 'A result without an amended objective version.', declarations })) - .toMatchObject({ ok: false, error: 'math_team_objective_revision_required' }); - expect(await child.call({ operation: 'progress', objectiveRevision: 2, kind: 'probe', summary: 'Use an obsolete source.', - knowledgeUses: [{ anchor: oldSource.file + '#' + oldSource.anchor, application: 'Obsolete knowledge is not the current assignment.' }] })) - .toMatchObject({ ok: false, error: expect.stringContaining('math_team_knowledge_anchor_not_loaded') }); - const nextSource = task.profileEvidence!.sources[0]!; - expect(await child.call({ operation: 'progress', objectiveRevision: 2, kind: 'blocker', summary: 'The supplied interface remains incomplete.', - evidenceRefs: ['RESEARCH.md'], knowledgeUses: [{ anchor: nextSource.file + '#' + nextSource.anchor, application: 'Checked the current interface assumptions.' }] })) - .toMatchObject({ ok: true, objectiveRevision: 2 }); - expect(task.progress!.map(item => item.objectiveRevision)).toEqual([1, 2]); - expect(task.progress![0]!.knowledgeUses![0]!.digest).toBe(oldSource.digest); - const full = await f.call({ operation: 'history', agentId: worker.id, limit: 1 }) as any; - expect(full.tasks[0]).toMatchObject({ objectiveRevision: 2, workKind: 'assembly', progressCount: 2 }); - expect(full.tasks[0].profileEvidence.sources[0]).toEqual(nextSource); - child.complete(); await idle(f.team); - expect(readSolverRunState(f.stateFile).agentTeam!.workers[0]!.tasks[0]!.objectiveHistory).toHaveLength(1); - expect(await f.call(amendment, 'lead', 'after-finish')).toMatchObject({ ok: false, error: 'math_team_task_not_amendable' }); - }); - - it('pages the exact stopped-writer sources of distinct checked declarations without adopting them', async () => { - const f = fixture(); - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove two helpers.' }); - const producer = await f.session('producer'), worker = f.team.archive.workers[0]!; - const prefix = 'theorem reusable (n : Nat) : n = n := by\n /- '; - const source = prefix + 'x'.repeat(15999 - prefix.length) + '𝔸β𝔹𝔸 / boundary / 𝔻 -/\n rfl\n'; - const other = 'theorem distinctEnd : True := by\n /- second 𝒳 -/\n trivial\n'; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Team', source + other + 'end Team')); - expect(await producer.call({ operation: 'submit', summary: 'Two helpers.', declarations: [...declarations, - { file: 'Submission.lean', name: 'Team.distinctEnd', type: 'True' }] })).toMatchObject({ ok: true }); - producer.complete(); await idle(f.team); - const ref = f.team.archive.deliveries[0]!, proof = readAgentTeamProofDelivery(ref.path, f.state); - await f.call({ operation: 'spawn', agentId: 'reader', message: 'Inspect the exact source of the submitted helpers.' }); - const reader = await f.session('reader'), readerWorktree = f.team.archive.workers[1]!.worktree; - const inspect = (options: Record = {}) => reader.call({ operation: 'inspect', deliveryId: ref.id, ...options }); - const overview = await inspect(); - expect(overview).toMatchObject({ ok: true, id: ref.id, commit: proof.commit, sourceDigest: proof.sourceDigest, - originalProblemAcceptance: 'not-assessed' }); - expect(overview.changes).toHaveLength(2); - for (const [index, change] of proof.changes.entries()) { - const expected = [...change.after], first = overview.changes![index]!; - expect(first).toMatchObject({ changeIndex: index, file: change.file, name: change.name, - totalCharacters: expected.length, offset: 0 }); - if (change.name === 'reusable') expect(first.truncated).toBe(true); - let page = first, joined = first.source; - for (;;) { - expect(page.source).toBe(expected.slice(page.offset, page.offset + [...page.source].length).join('')); - if (!page.truncated) { expect(page.nextOffset).toBeUndefined(); break; } - expect(page.nextOffset).toBeGreaterThan(page.offset); - expect(page.nextOffset).toBe([...joined].length); - const next = await inspect({ changeIndex: index, offset: page.nextOffset, limit: 4096 }); - expect(next).toMatchObject({ ok: true, id: ref.id, commit: proof.commit, sourceDigest: proof.sourceDigest, - originalProblemAcceptance: 'not-assessed', change: { changeIndex: index, file: change.file, name: change.name, - offset: page.nextOffset, totalCharacters: expected.length } }); - page = next.change!; joined += page.source; - } - expect(joined).toBe(change.name === 'reusable' ? source : other); - if (change.name === 'reusable') { - const request = { operation: 'inspect', deliveryId: ref.id, changeIndex: index, offset: 16000, limit: 24 }; - const firstRead = await f.call(request, 'reader', 'replay-frozen-page'); - expect(firstRead.change?.source).toContain('boundary'); - const recorded = readSolverRunState(f.stateFile).agentTeam!.operations; - expect(JSON.stringify(recorded)).not.toContain(firstRead.change!.source); - expect(await f.call(request, 'reader', 'replay-frozen-page')).toEqual(firstRead); - expect(readSolverRunState(f.stateFile).agentTeam!.operations).toEqual(recorded); - await expect(f.call({ ...request, offset: 16001 }, 'reader', 'replay-frozen-page')).rejects.toThrow('math_team_call_changed'); - const atSymbol = await inspect({ changeIndex: index, offset: 15999, limit: 1 }); - expect(atSymbol.change).toMatchObject({ source: '𝔸', nextOffset: 16000 }); - expect((await inspect({ changeIndex: index, offset: 16000, limit: 2 })).change) - .toMatchObject({ source: 'β𝔹', nextOffset: 16002 }); - } else { - expect((await inspect({ changeIndex: index, limit: 7 })).change) - .toMatchObject({ source: expected.slice(0, 7).join(''), offset: 0, nextOffset: 7 }); - } - } - for (const invalid of [{ changeIndex: 2 }, { changeIndex: -1 }, { changeIndex: 0.5 }, - { changeIndex: 0, offset: -1 }, { changeIndex: 0, limit: 0 }, { changeIndex: 0, limit: 16001 }, - { offset: 1 }, { limit: 10 }]) expect(await inspect(invalid)).toMatchObject({ ok: false }); - expect(f.team.archive.adoptions).toEqual([]); - expect(fs.readFileSync(f.source(readerWorktree), 'utf8')).toBe(original); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toBe(original); - reader.complete(); await idle(f.team); - }, 90_000); - - it('retains inspection and adoption exposure in a later checked assembled delivery', async () => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - await f.call({ operation: 'spawn', agentId: 'producer', message: 'Prove the reusable helper.', workKind: 'proof' }); - const producer = await f.session('producer'); - fs.writeFileSync(f.source(f.team.archive.workers[0]!.worktree), original.replace('end Team', helper + 'end Team')); - await producer.call({ operation: 'submit', summary: 'Reusable helper.', declarations }); producer.complete(); await idle(f.team); - const reference = f.team.archive.deliveries[0]!; - expect(reference).toBeDefined(); - await f.call({ operation: 'spawn', agentId: 'consumer', message: 'Reconstruct the interface independently.', workKind: 'independent-reconstruction' }); - const consumer = await f.session('consumer'), worker = f.team.archive.workers[1]!, task = worker.tasks[0]!; - expect(await consumer.call({ operation: 'inspect', deliveryId: reference.id })).toMatchObject({ ok: true, agentId: 'producer' }); - await consumer.call({ operation: 'yield', reason: 'Need the checked dependency.' }); consumer.complete(); await idle(f.team); - await f.call({ operation: 'adopt', deliveryId: reference.id, targetId: 'consumer' }); await idle(f.team); - expect(worker.exposures?.map(item => item.kind)).toEqual(['inspected', 'adopted']); - await f.call({ operation: 'amend', agentId: 'consumer', taskId: task.id, message: 'Assemble using the checked peer helper.', reason: 'The source has now been inspected and imported.', workKind: 'assembly' }); - await f.call({ operation: 'resume', agentId: 'consumer', taskId: task.id }); - const resumed = await f.session('consumer', 1); - expect(resumed.threadId).toBe(consumer.threadId); - fs.writeFileSync(f.source(worker.worktree), fs.readFileSync(f.source(worker.worktree), 'utf8') - .replace('end Team', 'theorem consumerReuse (n : Nat) : n = n := by exact reusable n\nend Team')); - await resumed.call({ operation: 'submit', objectiveRevision: 2, summary: 'Consumer assembled with the peer dependency.', - declarations: [{ file: 'Submission.lean', name: 'Team.consumerReuse', type: '∀ n : Nat, n = n' }] }); - resumed.complete(); await idle(f.team); - const own = f.team.archive.deliveries.find(item => item.agentId === 'consumer')!; - const delivery = readAgentTeamProofDelivery(own.path, f.state); - expect(delivery.provenance).toMatchObject({ objectiveRevision: 2, taskId: task.id, workKind: 'assembly', exposures: [ - { deliveryId: reference.id, agentId: 'producer', taskId: reference.taskId, kind: 'inspected' }, - { deliveryId: reference.id, agentId: 'producer', taskId: reference.taskId, kind: 'adopted' }, - ] }); - expect(delivery.declarations.map(item => item.name)).toContain('Team.consumerReuse'); - expect(readSolverRunState(f.stateFile).agentTeam!.workers[1]!.exposures).toHaveLength(2); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it.each(['holes', 'source-contract'] as const)('finishes only after every frozen original proof is ready and independently checked (%s)', async firstFailure => { - const f = fixture({ maxTurns: Infinity, maxTurnMs: Infinity }); - let opens = 0; - const modules = { ...directSolverModules, M1: { ...directSolverModules.M1, - open: async (options: MathAgentOptions): Promise => { - const turn = ++opens, threadId = options.threadId ?? 'finish-lead'; - return { threadId, usageSource: 'upstream-requests', close: async () => {}, interrupt: async () => {}, - stopForFreeze: async () => ({ status: 'stopped' }), run: async (_message, id, _workspace, started) => { - started(id); - const request = options.requestGate!({ requestId: 'finish-' + turn, threadId }); - if (request.allowed) request.settle({ complete: true, outcome: 'completed', usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } }); - if (turn === 1) { - expect(f.state.check?.passed).not.toBe(true); - if (firstFailure === 'source-contract') fs.writeFileSync(f.source(f.state.worktree), original.replace('theorem original : True', 'theorem original : False')); - } - else { - expect(turn).toBe(2); - expect(f.state.agentTeam!.completionRequested).toBeUndefined(); - fs.writeFileSync(f.source(f.state.worktree), original.replaceAll('by sorry', 'by trivial')); - } - expect(await options.tools!.call('theoremos_team', { operation: 'finish', summary: 'Saved candidate; request independent checking.' }, - { callId: 'finish-call-' + turn, threadId, turnId: id, signal: f.controller.signal })) - .toMatchObject({ ok: true, originalProblemAcceptance: 'not-assessed' }); - expect(options.requestGate!.checkpoint!()).toBe(true); - return 'checkpoint'; - } }; - } } }; - const result = await runResearchWorkers({ state: f.state, root: f.root, taskText: 'Prove both frozen statements.', - workers: [{ id: 'solver', role: 'lead', worktree: f.state.worktree, ownedFiles: f.problem.ownedFiles }], - access: new Map([['solver', { environment: f.environment, - researchSkill: prepareResearchSkill(f.root, f.state.worktree, f.state.researchSkill!, f.problem), retrievalRoot: f.state.worktree }]]), - modules, buildFile: path.join(f.directory, 'unused-build.json'), executable: 'offline-no-model', profile: 'offline-no-credentials', - signal: f.controller.signal, deadline: Infinity, maxTurns: Infinity, maxTotalTokens: 0, maxTurnMs: Infinity, - save: () => writeSolverRunState(f.stateFile, f.state), emit: (event, details) => { f.events.push({ event, details }); } }); - expect(opens).toBe(2); - expect(result?.check.verification.status).toBe('kernel_verified'); - expect(f.events.filter(item => item.event === 'team_completion_frozen').map(item => item.details?.wholeProofReady)) - .toEqual(firstFailure === 'holes' ? [false, true] : [true]); - expect(f.events.some(item => item.event === 'team_completion_rejected')).toBe(firstFailure === 'source-contract'); - expect(f.state.agentTeam!.completionRequested).toBeUndefined(); - }, 90_000); -}); diff --git a/tests/agentSessionPlan.test.ts b/tests/agentSessionPlan.test.ts index 57237f19..557f41f5 100644 --- a/tests/agentSessionPlan.test.ts +++ b/tests/agentSessionPlan.test.ts @@ -19,8 +19,6 @@ describe('workflow session requirements and selected execution contracts', () => }); it.each(['claude-code', 'opencode', 'cli'] as const)('retains %s native capability restrictions', harness => { - expect(() => planMathAgentSession(harness, { delegation: { mode: 'read-only', maxAgents: 2 } })) - .toThrow('delegation_unsupported'); expect(() => planMathAgentSession(harness, { skills: [skill('native')] })) .toThrow(harness === 'claude-code' ? 'native_skill_loading_unsupported' : 'requires_file_skill'); }); @@ -30,12 +28,6 @@ describe('workflow session requirements and selected execution contracts', () => .toMatchObject({ skillLoading: 'none', roleIsolation: 'sealed-role', structuredOutput: 'native-schema' }); expect(() => planMathAgentSession('codex', { readIsolation: { environment: 'standard' }, skills: [skill('file')] })) .toThrow('math_codex_skill_read_isolation_unsupported'); - expect(planMathAgentSession('codex', { delegation: { mode: 'read-only', maxAgents: 2 } })) - .toMatchObject({ roleIsolation: 'run-workspace' }); - expect(() => planMathAgentSession('codex', { delegation: { mode: 'read-only', maxAgents: 0 } })) - .toThrow('math_native_delegation_configuration_invalid'); - expect(() => planMathAgentSession('codex', { readIsolation: { environment: 'standard' }, - delegation: { mode: 'read-only', maxAgents: 2 } })).toThrow('math_native_delegation_read_isolation_unsupported'); expect(planMathAgentSession('codex', { skills: [skill('native'), skill('file')] }).skillLoading).toBe('mixed'); }); diff --git a/tests/agentTeamBudget.test.ts b/tests/agentTeamBudget.test.ts index e2bbfd74..e545e949 100644 --- a/tests/agentTeamBudget.test.ts +++ b/tests/agentTeamBudget.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { agentTeamChildAdmission, projectAgentTeamBudget, type AgentTeamBudgetInput } from '../src/solver/agentTeamBudget'; +import { projectAgentTeamBudget, type AgentTeamBudgetInput } from '../src/solver/agentTeamBudget'; import { attributeTaskUsage, beginRequestUsage, buildTokenBudget, initializeRequestUsageAccounting, - modelDispatchAllowed, type RequestUsageAccounting } from '../src/solver/usageBudget'; + type RequestUsageAccounting } from '../src/solver/usageBudget'; function observedBudget(tokens: number, limit = 1000) { return buildTokenBudget(limit, [{ turns: 1, usage: { totalTokens: tokens }, @@ -14,7 +14,7 @@ function input(overrides: Partial = {}): AgentTeamBudgetIn taskUsage: { helper: { totalTokens: 50 } }, ...overrides }; } -describe('Agent team child admission and Lead integration allowance', () => { +describe('Agent team historical budget inspection', () => { it('subtracts Lead reserves from the observed global remainder without charging them as consumption', () => { const source = input(), before = JSON.stringify(source); expect(projectAgentTeamBudget(source)).toMatchObject({ @@ -24,29 +24,9 @@ describe('Agent team child admission and Lead integration allowance', () => { task: { id: 'helper', budget: { tokens: 200, turns: 3 }, used: { tokens: 50, turns: 1 }, remaining: { tokens: 150, turns: 2 } }, }); - expect(agentTeamChildAdmission(source)).toEqual({ allowed: true }); expect(JSON.stringify(source)).toBe(before); }); - it('keeps the final observed token allowance usable by Lead while blocking another child request', () => { - const source = input({ tokenBudget: observedBudget(900) }); - expect(agentTeamChildAdmission(source, 'request')).toEqual({ allowed: false, reason: 'math_team_lead_token_reserve' }); - expect(projectAgentTeamBudget(source)).toMatchObject({ remaining: { tokens: 100 }, childRemaining: { tokens: 0 } }); - // Lead does not use child admission; its existing global gate still admits integration work. - expect(modelDispatchAllowed(source.tokenBudget)).toBe(true); - expect(source.turns).toBeLessThan(source.maxTurns); - }); - - it('protects a future Lead turn without blocking requests within an already reserved child turn', () => { - const source = input({ turns: 9, task: { id: 'helper', turns: 1, budget: { turns: 1 } } }); - expect(agentTeamChildAdmission(source, 'turn')).toEqual({ allowed: false, reason: 'math_team_task_turn_limit' }); - expect(agentTeamChildAdmission(source, 'request')).toEqual({ allowed: true }); - const anotherTask = { ...source, task: { id: 'other', turns: 0 } }; - expect(agentTeamChildAdmission(anotherTask, 'turn')).toEqual({ allowed: false, reason: 'math_team_lead_turn_reserve' }); - expect(agentTeamChildAdmission(anotherTask, 'request')).toEqual({ allowed: true }); - expect(source.maxTurns - source.turns).toBe(1); - }); - it('retains one task allowance and its real receipt usage across yield, save and resume', () => { const research = { turns: 0, usage: undefined as Record | undefined, requestUsageAccounting: undefined as RequestUsageAccounting | undefined }; @@ -62,11 +42,6 @@ describe('Agent team child admission and Lead integration allowance', () => { } const restored: AgentTeamBudgetInput = JSON.parse(JSON.stringify(input({ task, taskUsage: state.taskUsage }))); expect(projectAgentTeamBudget(restored).task).toMatchObject({ used: { tokens: 70, turns: 2 }, remaining: { tokens: 0, turns: 0 } }); - expect(agentTeamChildAdmission(restored, 'request')).toEqual({ allowed: false, reason: 'math_team_task_token_limit' }); - expect(agentTeamChildAdmission({ ...restored, task: { ...restored.task!, budget: { tokens: 71, turns: 2 } } }, 'turn')) - .toEqual({ allowed: false, reason: 'math_team_task_turn_limit' }); - expect(agentTeamChildAdmission({ ...restored, task: { ...restored.task!, budget: { tokens: 100, turns: 3 } } }, 'turn')) - .toEqual({ allowed: true }); expect(research.requestUsageAccounting!.receipts!.map(receipt => receipt.status)).toEqual(['reported', 'reported']); expect(state.taskUsage).toEqual({ helper: { inputTokens: 60, outputTokens: 10, totalTokens: 70 } }); }); @@ -75,7 +50,6 @@ describe('Agent team child admission and Lead integration allowance', () => { const source = input({ task: { id: 'helper', budget: { tokens: 100 }, turns: 1 }, taskUsage: { helper: { inputTokens: 80, outputTokens: 20, cachedInputTokens: 60, reasoningOutputTokens: 15 } } }); expect(projectAgentTeamBudget(source).task!.used.tokens).toBe(100); - expect(agentTeamChildAdmission(source, 'request')).toEqual({ allowed: false, reason: 'math_team_task_token_limit' }); expect(projectAgentTeamBudget({ ...source, taskUsage: { helper: { totalTokens: 90, inputTokens: 80, outputTokens: 20 } } }) .task!.used.tokens).toBe(90); }); @@ -87,11 +61,9 @@ describe('Agent team child admission and Lead integration allowance', () => { const pending = input({ tokenBudget: buildTokenBudget(0, [research]), task: { id: 'helper', budget: { tokens: 50 }, turns: 1 }, taskUsage: {} }); expect(pending.tokenBudget.usageComplete).toBe(false); - expect(agentTeamChildAdmission(pending, 'request')).toEqual({ allowed: true }); settle({ complete: false, outcome: 'interrupted', missingReason: 'resumed-without-receipt' }); const missing = { ...pending, tokenBudget: buildTokenBudget(0, [research]), taskUsageUnavailable: true }; expect(missing.tokenBudget.status).toBe('unlimited'); - expect(agentTeamChildAdmission(missing, 'request')).toEqual({ allowed: false, reason: 'math_model_usage_unavailable' }); expect(projectAgentTeamBudget(missing).task!.usageUnavailable).toBe(true); expect(research.requestUsageAccounting!.receipts).toHaveLength(1); expect(research.requestUsageAccounting!.receipts![0]!.status).toBe('missing'); @@ -100,16 +72,6 @@ describe('Agent team child admission and Lead integration allowance', () => { it('keeps malformed or incomplete task token totals unknown instead of resetting the task allowance', () => { const source = input({ taskUsage: { helper: { inputTokens: 20 } } }); expect(projectAgentTeamBudget(source).task).toMatchObject({ used: { tokens: null }, remaining: { tokens: null }, usageUnavailable: true }); - expect(agentTeamChildAdmission(source, 'request')).toEqual({ allowed: false, reason: 'math_model_usage_unavailable' }); - }); - - it.each([ - ['exhausted', 'math_total_token_limit'], - ['usage-unavailable', 'math_model_usage_unavailable'], - ] as const)('preserves the existing global %s refusal ahead of task and reserve limits', (status, reason) => { - const source = input({ tokenBudget: { ...observedBudget(1000), status, reason }, - task: { id: 'helper', budget: { tokens: 1, turns: 1 }, turns: 1 } }); - expect(agentTeamChildAdmission(source)).toEqual({ allowed: false, reason }); }); it('keeps saved local caps and reserves inactive when the run allowance is unlimited', () => { @@ -119,26 +81,5 @@ describe('Agent team child admission and Lead integration allowance', () => { expect(projectAgentTeamBudget(source)).toMatchObject({ maxTurns: null, remaining: { tokens: null, turns: null }, leadReserve: { tokens: 0, turns: 0 }, childRemaining: { tokens: null, turns: null }, task: { budget: {}, remaining: { tokens: null, turns: null } } }); - expect(agentTeamChildAdmission(source)).toEqual({ allowed: true }); - }); - - it('applies a finite task allowance even when the global run has no token cap', () => { - const source = input({ tokenBudget: observedBudget(5000, 0), task: { id: 'helper', budget: { tokens: 50 }, turns: 2 } }); - expect(agentTeamChildAdmission(source, 'request')).toEqual({ allowed: false, reason: 'math_team_task_token_limit' }); - }); - - it('reports an admitted request overrun and refuses the next request without fabricating a hard token cap', () => { - const before = input({ task: { id: 'helper', turns: 1, budget: { tokens: 60 } } }); - expect(agentTeamChildAdmission(before, 'request')).toEqual({ allowed: true }); - const settled = { ...before, taskUsage: { helper: { totalTokens: 80 } } }; - expect(projectAgentTeamBudget(settled).task).toMatchObject({ used: { tokens: 80 }, remaining: { tokens: 0 } }); - expect(agentTeamChildAdmission(settled, 'request')).toEqual({ allowed: false, reason: 'math_team_task_token_limit' }); - expect(before.taskUsage!.helper!.totalTokens).toBe(50); - }); - - it('blocks another child turn at the global turn limit while allowing requests in a turn already counted', () => { - const source = input({ turns: 10 }); - expect(agentTeamChildAdmission(source, 'turn')).toEqual({ allowed: false, reason: 'math_team_total_turn_limit' }); - expect(agentTeamChildAdmission(source, 'request')).toEqual({ allowed: true }); }); }); diff --git a/tests/agentTeamContextContract.test.ts b/tests/agentTeamContextContract.test.ts index d7d0a5c7..9e940e87 100644 --- a/tests/agentTeamContextContract.test.ts +++ b/tests/agentTeamContextContract.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { agentTeamOperationAllowed, agentTeamRequestSchema, type AgentTeamTransport } from '../src/solver/agentTeamTool'; +import { agentTeamOperationAllowed, agentTeamRequestSchema } from '../src/solver/agentTeamTool'; import { agentTeamTaskHistory } from '../src/solver/agentTeamViews'; import { agentTeamStateSchema } from '../src/solver/agentTeamState'; import { agentTeamContextSection, buildSkillResearchContext } from '../src/solver/skillResearchContext'; @@ -10,18 +10,19 @@ import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/mo import { resolveAgentTeamLeadProfile, resolveAgentTeamProfiles } from '../src/solver/agentTeamProfiles'; import { researchSkillIdentity } from '../src/solver/researchSkill'; import { readPersonalExperts } from '../src/solver/personalExperts'; +import { publishNativeApprovalPlan } from '../src/solver/planApproval'; import { localExample, solverState } from './helpers/solver'; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); -function fixture(transport: AgentTeamTransport) { +function fixture() { const base = localExample('team-context-contract-'); roots.push(base.directory); const skill = readMathAgentSkill(path.resolve('skills/theoremos-research/SKILL.md')); const objective = 'Profiles: D002, prover\nInvestigate the consumer hypothesis and report one useful result.'; const state = solverState(base.problem, base.workspace, { runId: 'context-contract', phase: 'prepared', researchMode: 'skill', researchSkill: researchSkillIdentity(skill), researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { schema: 'theorem-os.agent-team.v1', transport, events: [], deliveries: [], adoptions: [], operations: [], + agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', events: [], deliveries: [], adoptions: [], operations: [], workers: [{ id: 'member', role: 'researcher', worktree: base.workspace, phase: 'running', status: 'running', seedCommit: base.problem.baseCommit, turns: 1, cursor: 0, tasks: [{ id: 'current', message: objective, status: 'running', seedCommit: base.problem.baseCommit, profileEvidence: resolveAgentTeamProfiles(skill, objective).evidence }] }] } }); @@ -30,9 +31,22 @@ function fixture(transport: AgentTeamTransport) { return { ...base, state, access, objective }; } -describe.each(['host-tools', 'native-agent-control'] as const)('%s complete context contract', transport => { +describe('native team context contract', () => { + it('keeps the native Lead charter and continuation when a plan is saved for approval', () => { + const f = fixture(); + f.state.researchSkillWorkflow = 'full'; + f.state.planApproval = true; + publishNativeApprovalPlan(f.state, { operation: 'publish_plan', goals: f.problem.targets.map(target => + ({ theoremName: target.theoremName, objective: 'Check the local lemma first.' })) }, () => {}, () => {}); + const context = buildResearchContext(f.problem, f.state, f.access); + const dispatch = finalizeResearchDispatch(context, { continuation: true }); + expect(dispatch.instructions).toContain(resolveAgentTeamLeadProfile(f.access.researchSkill).section.text); + expect(dispatch.message).toContain('Continue the same original research in this saved thread'); + expect(dispatch.message).not.toContain('Check the local lemma first.'); + }); + it.each(['direct', 'full'] as const)('injects the pinned Lead charter once through the %s workflow, including continuation', workflow => { - const f = fixture(transport); + const f = fixture(); if (workflow === 'full') f.state.researchSkillWorkflow = 'full'; f.state.researchDelegation = { mode: 'team', maxAgents: 3, preferredProfiles: ['D011', 'engineer'] }; const profile = resolveAgentTeamLeadProfile(f.access.researchSkill); @@ -56,7 +70,7 @@ describe.each(['host-tools', 'native-agent-control'] as const)('%s complete cont }); it('gives Lead the actual member delivery interface while keeping its own standalone request separate', () => { - const f = fixture(transport); + const f = fixture(); f.state.researchDelegation = { mode: 'team', maxAgents: 3, preferredProfiles: ['D011', 'engineer'] }; const lead = buildSkillResearchContext(f.problem, f.state, { ...f.access, teamRole: { id: 'lead', role: 'lead' } }); const leadHelp = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); @@ -68,8 +82,8 @@ describe.each(['host-tools', 'native-agent-control'] as const)('%s complete cont const memberProfile = resolveAgentTeamProfiles(f.access.researchSkill, f.objective).section.text; const request = agentTeamRequestSchema.parse({ operation: 'submit', summary: 'One independent result.', declarations: [{ file: f.problem.ownedFiles[0], name: 'Fixture.helper', type: 'True' }] }); - expect(agentTeamOperationAllowed('member', false, transport, request.operation)).toBe(true); - expect(agentTeamOperationAllowed('lead', false, transport, request.operation)).toBe(false); + expect(agentTeamOperationAllowed('member', request.operation)).toBe(true); + expect(agentTeamOperationAllowed('lead', request.operation)).toBe(false); expect(leadHelp).toContain('operation submit'); expect(leadHelp).toContain('only for your own Lead worktree'); expect(memberHelp).toContain('operation submit'); @@ -93,30 +107,26 @@ describe.each(['host-tools', 'native-agent-control'] as const)('%s complete cont const editable = JSON.parse(/Editable Lean paths relative to it: (\[[^\n]*?\])\./u.exec(full.instructions)![1]!); expect(editable).toEqual(f.problem.ownedFiles.filter(file => !Object.hasOwn(f.problem.frozenFiles ?? {}, file))); expect(full.instructions).toContain('separate worktree'); - if (transport === 'native-agent-control') { - expect(full.instructions + full.message).not.toContain('theoremos_team poll'); - expect(full.instructions + full.message).not.toContain('Poll after'); - expect(full.instructions + full.message).not.toContain('After ordinary tools resume'); - expect(full.instructions + full.message).not.toContain('Built-in spawn/fork is disabled'); - if (context === member) { - expect(full.instructions).toContain('Only Lead dispatches and adopts.'); - expect(full.instructions).toContain('Do not spawn subteams or interrupt peers.'); - expect(full.message).not.toContain('"currentStage"'); - } else { - expect(full.instructions).toContain('Lead of a flat mathematical research team'); - expect(full.instructions).toContain('Call collaboration tools directly in their exposed namespace, not through functions.exec.'); - expect(full.instructions).toContain('A child\'s final answer is automatically delivered to its parent.'); - } - expect(agentTeamOperationAllowed('member', false, transport, 'poll')).toBe(false); + expect(full.instructions + full.message).not.toContain('theoremos_team poll'); + expect(full.instructions + full.message).not.toContain('Poll after'); + expect(full.instructions + full.message).not.toContain('After ordinary tools resume'); + expect(full.instructions + full.message).not.toContain('Built-in spawn/fork is disabled'); + if (context === member) { + expect(full.instructions).toContain('Only Lead dispatches and adopts.'); + expect(full.instructions).toContain('Do not spawn subteams or interrupt peers.'); + expect(full.message).not.toContain('"currentStage"'); } else { - expect(agentTeamOperationAllowed('member', false, transport, 'poll')).toBe(true); + expect(full.instructions).toContain('Lead of a flat mathematical research team'); + expect(full.instructions).toContain('Call collaboration tools directly in their exposed namespace, not through functions.exec.'); + expect(full.instructions).toContain('A child\'s final answer is automatically delivered to its parent.'); } + expect(agentTeamOperationAllowed('member', 'poll')).toBe(false); } } }); it('shows personal card descriptions to Lead and only assigned card knowledge to members', () => { - const f = fixture(transport); + const f = fixture(); const file = path.join(f.directory, 'expert-cards.json'); const card = { name: 'Chosen expert', assetId: 'chosen', version: 'v1', digest: 'a'.repeat(64), summary: 'Short catalogue entry', knowledge: 'Private chosen expert knowledge' }; @@ -137,11 +147,17 @@ describe.each(['host-tools', 'native-agent-control'] as const)('%s complete cont }); it('keeps one full current assignment and one evidence record, with complete history still readable', () => { - const f = fixture(transport); + const f = fixture(); + f.state.agentTeam!.events.push( + { sequence: 1, from: 'lead', to: 'member', kind: 'message', at: 1, text: 'Check the consumer hypothesis.' }, + { sequence: 2, from: 'lead', to: 'member', kind: 'message', at: 2, text: 'Long advisory. '.repeat(400) }, + ); const context = buildSkillResearchContext(f.problem, f.state, { ...f.access, teamRole: { id: 'member', role: 'worker' }, teamAssignment: { taskId: 'current', message: f.objective, sourceCommit: f.problem.baseCommit } }); const envelope = JSON.parse(context.message.split('\n')[1]!); + expect(envelope.inbox).toMatchObject({ through: 1, previewThrough: 2, more: true }); + expect(context.inboxThrough).toBe(1); expect(envelope.objective).toBe(f.objective); expect(envelope).not.toHaveProperty('profileEvidence'); expect(envelope.workers[0].tasks[0]).not.toHaveProperty('objective'); @@ -155,7 +171,7 @@ describe.each(['host-tools', 'native-agent-control'] as const)('%s complete cont it.each(['opening', 'saved presentation', 'failed probe', 'uncertain mail'] as const) ('keeps native %s evidence advisory after state recovery', scenario => { - const f = fixture('native-agent-control'), team = f.state.agentTeam!; + const f = fixture(), team = f.state.agentTeam!; team.workers = []; if (scenario !== 'opening') team.coordinationPresentation = { at: 1, reason: 'opening', decisionRevision: 0, eventSequence: 0, startedRequests: 0 }; @@ -189,7 +205,7 @@ it.each(['opening', 'saved presentation', 'failed probe', 'uncertain mail'] as c }); it('retains standalone declaration delivery without exposing a team contract', () => { - const f = fixture('native-agent-control'); + const f = fixture(); delete f.state.researchDelegation; delete f.state.agentTeam; const context = buildSkillResearchContext(f.problem, f.state, f.access); diff --git a/tests/agentTeamHandoffs.test.ts b/tests/agentTeamHandoffs.test.ts index 02fbccf2..b6db7313 100644 --- a/tests/agentTeamHandoffs.test.ts +++ b/tests/agentTeamHandoffs.test.ts @@ -19,7 +19,7 @@ afterEach(async () => { } }); -function fixture(transport: 'host-tools' | 'native-agent-control') { +function fixture() { const directory = temporaryDirectory('agent-team-handoffs-'); const receipt = bootstrapLeanTask(path.join(directory, 'lead'), { task: 'Disposable proof handoff fixture.', source: 'theorem original : True := by sorry\n', @@ -27,7 +27,7 @@ function fixture(transport: 'host-tools' | 'native-agent-control') { const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); const state = solverState(problem, receipt.workspaceRoot, { runId: 'proof-handoffs', phase: 'running', threadId: 'saved-lead-thread', researchMode: 'skill', researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { schema: 'theorem-os.agent-team.v1', transport, workers: [], events: [], deliveries: [], adoptions: [], operations: [], + agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [], coordination: { revision: 1, at: 1, decision: 'defer', reason: 'Historical optional note.', nextStep: 'Inspect one definition.', startedRequests: 0, eventSequence: 0 }, coordinationPresentation: { at: 2, reason: 'opening', decisionRevision: 1, eventSequence: 0 }, @@ -46,9 +46,9 @@ function fixture(transport: 'host-tools' | 'native-agent-control') { fixtures.push(f); return f; } -describe.each(['host-tools', 'native-agent-control'] as const)('%s minimal proof handoff adapter', transport => { +describe('native proof handoff adapter', () => { it('reads historical coordination fields without turning them or incoming messages into a research gate', () => { - const f = fixture(transport), notes = structuredClone(f.state.agentTeam); + const f = fixture(), notes = structuredClone(f.state.agentTeam); const source = fs.readFileSync(f.sourceFile, 'utf8'), head = git(f.state.worktree, ['rev-parse', 'HEAD']); const base: ModelRequestGate = identity => ({ allowed: true, settle: beginRequestUsage(f.state, identity) }); const gate = f.team.leadRequestGate(base); f.team.beginLeadTurn(); @@ -69,7 +69,7 @@ describe.each(['host-tools', 'native-agent-control'] as const)('%s minimal proof }); it.each(['adopt', 'finish', 'base'] as const)('retains the %s checkpoint and waits for paid response settlement', async kind => { - const f = fixture(transport); let baseCheckpoint = false; + const f = fixture(); let baseCheckpoint = false; const beforeRequest = vi.fn(async () => {}); const base: ModelRequestGate = identity => ({ allowed: true, settle: beginRequestUsage(f.state, identity) }); base.checkpoint = () => baseCheckpoint; base.beforeRequest = beforeRequest; @@ -91,7 +91,7 @@ describe.each(['host-tools', 'native-agent-control'] as const)('%s minimal proof }); it('honors a recovered adoption before admitting another paid response', () => { - const f = fixture(transport), base = vi.fn(() => ({ allowed: true as const, settle: () => {} })); + const f = fixture(), base = vi.fn(() => ({ allowed: true as const, settle: () => {} })); f.team.archive.adoptions.push({ id: 'recovered', deliveryId: 'b'.repeat(64), targetId: 'lead', status: 'queued' }); const gate = f.team.leadRequestGate(base); f.team.beginLeadTurn(); expect(gate.checkpoint!()).toBe(true); expect(base).not.toHaveBeenCalled(); expect(f.open).not.toHaveBeenCalled(); diff --git a/tests/agentTeamMessaging.test.ts b/tests/agentTeamMessaging.test.ts deleted file mode 100644 index b693ff92..00000000 --- a/tests/agentTeamMessaging.test.ts +++ /dev/null @@ -1,249 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; -import { createCodexMathSession } from '../src/runtime/codexSession'; -import { confirmHarnessProcessStopped } from '../src/runtime/harnessProcess'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { directSolverModules } from '../src/solver/modules'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { deferred } from './helpers/async'; -import { solverState } from './helpers/solver'; - -// This local protocol peer exercises the real tool dispatcher and native notification routing. -// It never contacts a model. The host writes a gate only after each turn has actually started. -const peer = String.raw` -const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'); -const workspace = process.cwd(), actor = process.env.DEEPSCIENTIST_MATH_WORKER_ID; -const scratch = path.join(workspace, '.scratch'); fs.mkdirSync(scratch, { recursive: true }); -const trace = value => fs.appendFileSync(path.join(scratch, 'native-messaging.jsonl'), JSON.stringify(value) + '\n'); -const send = value => { trace({ direction: 'peer', ...value }); process.stdout.write(JSON.stringify(value) + '\n'); }; -let threadId = 'messaging-' + actor, turnId, nextCall = 10000, gate, settled = true; -const finish = () => { - if (settled) return; settled = true; clearInterval(gate); - send({ method: 'item/completed', params: { threadId, turnId, - item: { type: 'agentMessage', id: 'final', text: 'Advisory messages saved; writer released.' } } }); - send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'interrupted' } } }); -}; -const stream = readline.createInterface({ input: process.stdin }); -stream.on('close', () => { clearInterval(gate); process.exit(0); }); -stream.on('line', line => { - const call = JSON.parse(line), params = call.params || {}; - trace({ direction: 'host', ...call }); - const reply = result => send({ id: call.id, result }); - if (call.method === 'initialize') return reply({}); - if (call.method === 'thread/start' || call.method === 'thread/resume') { - threadId = params.threadId || threadId; - return reply({ thread: { id: threadId }, model: params.model, reasoningEffort: params.config.model_reasoning_effort, - approvalPolicy: 'never', activePermissionProfile: { id: 'math-worker' } }); - } - if (call.method === 'skills/list') return reply({ data: [{ cwd: workspace, errors: [], skills: [{ - name: 'theoremos-research', enabled: true, path: path.join(workspace, '.agents/skills/theoremos-research/SKILL.md'), - }] }] }); - if (call.method === 'turn/start') { - turnId = params.clientUserMessageId; settled = false; reply({ turn: { id: turnId } }); - fs.writeFileSync(path.join(scratch, 'native-messaging-started.json'), JSON.stringify({ threadId, turnId })); - gate = setInterval(() => { - const file = path.join(scratch, 'native-messaging-commands.json'); - if (!fs.existsSync(file)) return; - clearInterval(gate); - for (const operation of JSON.parse(fs.readFileSync(file, 'utf8'))) { - const id = ++nextCall; - send({ id, method: 'item/tool/call', params: { threadId, turnId, callId: 'message-' + id, - namespace: null, tool: 'theoremos_team', arguments: operation } }); - } - }, 10); - return; - } - if (call.method === 'turn/steer') return reply({}); - if (call.method === 'turn/interrupt') { reply({}); finish(); return; } - if (call.id !== undefined && call.method) reply({}); -}); -`; - -async function bounded(operation: Promise, milliseconds: number, reason: string): Promise { - let timer: ReturnType; - try { - return await Promise.race([operation, new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error(reason)), milliseconds); - })]); - } finally { clearTimeout(timer!); } -} - -const fixtures: ReturnType[] = []; -function fixture(synchronizeMessages = false) { - const temporaryRoot = process.env.TMPDIR || '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - const directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-messaging-'))); - const root = path.resolve('.'), receipt = bootstrapLeanTask(path.join(directory, 'primary'), { - source: 'namespace Messaging\ntheorem original : True := by sorry\nend Messaging\n', - task: 'Exercise advisory messages while preserving independent proof acceptance.', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), worktree = path.join(directory, 'lead'); - git(receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, worktree, { runId: 'native-team-messaging', phase: 'running', model: 'fixture', effort: 'high', - environmentDigest: mathDigest('native-messaging-environment'), researchMode: 'skill', researchSkillWorkflow: 'full', - researchSkill: identity, researchDelegation: { mode: 'team', maxAgents: 3 }, workerCount: 1, coordination: 'independent' }); - const skill = prepareResearchSkill(root, worktree, identity, problem); - const profile = path.join(directory, 'profile'), executable = path.join(directory, 'peer'); - fs.mkdirSync(profile); fs.writeFileSync(path.join(profile, 'config.toml'), ''); - fs.writeFileSync(executable, '#!' + process.execPath + '\n' + peer, { mode: 0o700 }); - const controller = new AbortController(), sessions = new Map(); - const messageArrivals = new Set(), bothMessages = deferred(); - controller.signal.addEventListener('abort', () => bothMessages.resolve(), { once: true }); - const deadline = setTimeout(() => controller.abort(new Error('native-messaging-external-deadline')), 15000); - const modules = { ...directSolverModules, M1: { ...directSolverModules.M1, open: async (options: MathAgentOptions) => { - const actor = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - const tools = options.tools!; - const session = await createCodexMathSession({ ...options, tools: { ...tools, call: async (name, args, context) => { - // Both real dispatchers must be busy before either cross-member message reaches the - // manager. Only arrival is controlled; every response still comes from its real tools. - if (synchronizeMessages && (args as { operation?: string }).operation === 'message') { - messageArrivals.add(actor); if (messageArrivals.size === 2) bothMessages.resolve(); - await bothMessages.promise; - } - return tools.call(name, args, context); - } } }); - sessions.set(actor, session); return session; - } } }; - const environment = { PATH: `${path.dirname(process.execPath)}:/usr/bin:/bin` }; - const stateFile = path.join(directory, 'state.json'); - const team = new AgentResearchTeam({ state, root, taskText: 'Exercise message delivery without model calls.', - leadAccess: { environment, retrievalRoot: path.join(worktree, problem.projectRelative), researchSkill: skill }, - modules, executable, profile, signal: controller.signal, maxAgents: 3, maxTurns: 12, maxTurnMs: 10000, - maxTotalTokens: 0, remainingMs: () => Infinity, save: () => writeSolverRunState(stateFile, state), emit: () => {}, - exclusiveCheck: operation => operation(), - }); - let callId = 0; - const call = (operation: Record) => team.tools('lead').call('theoremos_team', operation, { - callId: `lead-${++callId}`, threadId: 'lead-thread', turnId: 'lead-turn', signal: controller.signal, - }) as Promise>; - const worker = (id: string) => team.archive.workers.find(item => item.id === id)!; - const trace = (id: string): Record[] => { - const file = path.join(worker(id).worktree, '.scratch/native-messaging.jsonl'); - return fs.existsSync(file) ? fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) : []; - }; - const start = async (id: string) => { - expect(await call({ operation: 'spawn', agentId: id, message: `Research independently as ${id}; messages remain advisory.` })) - .toMatchObject({ ok: true }); - await expect.poll(() => fs.existsSync(path.join(worker(id).worktree, '.scratch/native-messaging-started.json')), - { timeout: 5000 }).toBe(true); - expect(sessions.get(id)?.processIdentity).toMatchObject({ schema: 'theorem-os.harness-process-identity.v1' }); - expect(sessions.get(id)?.executionPlan?.harness).toBe('codex'); - }; - const send = (id: string, operations: Record[]) => - fs.writeFileSync(path.join(worker(id).worktree, '.scratch/native-messaging-commands.json'), JSON.stringify(operations)); - const current = { directory, team, state, stateFile, controller, sessions, deadline, call, worker, trace, start, send, messageArrivals }; - fixtures.push(current); return current; -} - -afterEach(async () => { - for (const f of fixtures.splice(0)) { - f.controller.abort(); - try { - await bounded(Promise.allSettled([...f.sessions.values()].map(session => session.close())), 6000, 'native-messaging-close-timeout'); - await bounded(f.team.close(), 6000, 'native-messaging-team-close-timeout'); - for (const session of f.sessions.values()) if (session.processIdentity) - expect(confirmHarnessProcessStopped(session.processIdentity).status).toBe('stopped'); - } finally { clearTimeout(f.deadline); fs.rmSync(f.directory, { recursive: true, force: true }); } - } -}); - -describe.skipIf(process.platform !== 'linux')('Agent team messaging through the real native adapter', () => { - it('rejects self-messages through the native dispatcher without a notification or blocked stop', async () => { - const f = fixture(); - await f.call({ operation: 'publish', summary: 'Revision one is the context dispatched to this member.' }); - await f.start('self'); - await f.call({ operation: 'publish', summary: 'Revision two arrives after the member started.' }); - const eventsBefore = [...f.team.archive.events]; - f.send('self', [{ operation: 'message', agentId: 'self', message: 'A self-message must not wait for its own callback.' }]); - await expect.poll(() => f.trace('self').some(item => item.direction === 'host' && item.id === 10001 && item.result), - { timeout: 2500 }).toBe(true); - const response = f.trace('self').find(item => item.direction === 'host' && item.id === 10001)!.result; - expect(response.success).toBe(true); - expect(JSON.parse(response.contentItems[0].text)).toMatchObject({ ok: false, - error: 'math_team_message_self_addressed', from: 'self', to: 'self', - hint: expect.stringContaining('Use agentId: "lead"') }); - expect(readSolverRunState(f.stateFile).agentTeam!.events).toEqual(eventsBefore); - expect(await bounded(f.call({ operation: 'stop', agentId: 'self' }), 2500, 'self-message-blocked-stop')) - .toMatchObject({ ok: true }); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 5000 }).toBe(false); - expect(f.worker('self').writerStopUnconfirmed).toBeUndefined(); - expect(f.trace('self').some(item => item.direction === 'host' && - ['turn/steer', 'thread/inject_items'].includes(item.method) && - JSON.stringify(item.params).includes('A self-message must not wait for its own callback.'))).toBe(false); - }, 20000); - - it('queues advisory messages in native history while amendments retain turn-bound steering', async () => { - const f = fixture(); await f.start('member'); - const task = f.worker('member').tasks[0]!; - await f.call({ operation: 'message', agentId: 'member', message: 'A complementary finding is available.' }); - await expect.poll(() => f.trace('member').filter(item => item.direction === 'host' && - item.method === 'thread/inject_items').length, { timeout: 2500 }).toBe(1); - const injected = f.trace('member').find(item => item.method === 'thread/inject_items')!.params; - expect(injected).toMatchObject({ threadId: f.worker('member').threadId, items: [{ - type: 'message', role: 'user', content: [{ type: 'input_text', text: expect.stringContaining('Team update (advisory)') }], - }] }); - expect(injected.items[0].content[0].text).toContain('A complementary finding is available.'); - expect(f.trace('member').filter(item => item.method === 'turn/steer')).toEqual([]); - - await f.call({ operation: 'amend', agentId: 'member', taskId: task.id, - message: 'Review the dependency interface before further work.', reason: 'The effective task objective changed.' }); - await expect.poll(() => f.trace('member').filter(item => item.direction === 'host' && - item.method === 'turn/steer').length, { timeout: 2500 }).toBe(1); - const steered = f.trace('member').find(item => item.method === 'turn/steer')!.params; - expect(steered).toMatchObject({ threadId: f.worker('member').threadId, expectedTurnId: task.id }); - expect(JSON.stringify(steered.input)).toContain('Lead assignment amendment (effective objective)'); - expect(JSON.stringify(steered.input)).toContain('Review the dependency interface before further work.'); - expect(f.trace('member').filter(item => item.method === 'turn/start')).toHaveLength(1); - expect(f.trace('member').filter(item => item.method === 'thread/inject_items')).toHaveLength(1); - }, 20000); - - it('keeps Lead cancel and stop responsive while two busy native members exchange concurrent messages', async () => { - const f = fixture(true); await f.start('alpha'); await f.start('beta'); - f.send('alpha', [{ operation: 'message', agentId: 'beta', message: 'Alpha shared its current interface.' }]); - f.send('beta', [{ operation: 'message', agentId: 'alpha', message: 'Beta shared a complementary observation.' }]); - await expect.poll(() => f.messageArrivals.size, { timeout: 2500 }).toBe(2); - await expect.poll(() => f.team.archive.events.some(event => event.kind === 'message'), { timeout: 2500 }).toBe(true); - const responses = await bounded(Promise.all([ - f.call({ operation: 'cancel', agentId: 'alpha', taskId: f.worker('alpha').tasks[0]!.id, reason: 'The dependency interface changed.' }), - f.call({ operation: 'stop', agentId: 'beta' }), - ]), 2500, 'cross-message-blocked-lead-mutations'); - expect(responses.map(response => response.ok)).toEqual([true, true]); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 5000 }).toBe(false); - expect(f.worker('alpha').tasks[0]!.status).toBe('cancelled'); expect(f.worker('beta').status).toBe('stopped'); - expect(f.team.archive.events.filter(event => event.kind === 'message').map(event => [event.from, event.to])) - .toEqual(expect.arrayContaining([['alpha', 'beta'], ['beta', 'alpha']])); - expect(f.team.archive.workers.every(worker => !worker.writerStopUnconfirmed && !worker.writerProcess)).toBe(true); - expect(f.state.check).toBeUndefined(); - }, 20000); - - it('retains a late message to an already closed native session and releases subsequent mutations', async () => { - const f = fixture(); await f.start('closed'); - await f.call({ operation: 'stop', agentId: 'closed' }); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 5000 }).toBe(false); - const closed = f.sessions.get('closed')!; - expect(await closed.stopForFreeze!()).toEqual({ status: 'stopped' }); - // Simulate a stale session reference during a close boundary, using its real notify method. - f.team.setLeadSession(closed); - const responses = await bounded(Promise.all([ - f.team.tools('closed').call('theoremos_team', { - operation: 'message', agentId: 'lead', message: 'Keep the late notification in the durable inbox.', - }, { callId: 'closed-late-message', threadId: closed.threadId, turnId: 'closed-turn', signal: f.controller.signal }), - f.call({ operation: 'publish', summary: 'A later mutation still progresses after native shutdown.' }), - ]), 2500, 'late-notification-blocked-serial'); - f.team.setLeadSession(undefined); - expect(responses[0]).toMatchObject({ ok: true, delivery: 'saved-inbox' }); - expect(responses[1]).toMatchObject({ ok: true }); - expect((await f.call({ operation: 'poll' })).events).toContainEqual(expect.objectContaining({ - from: 'closed', to: 'lead', kind: 'message', text: 'Keep the late notification in the durable inbox.', - })); - expect(f.trace('closed').some(item => ['turn/steer', 'thread/inject_items'].includes(item.method))).toBe(false); - }, 20000); -}); diff --git a/tests/agentTeamNativeControl.test.ts b/tests/agentTeamNativeControl.test.ts index 3c612dc7..9eb809ef 100644 --- a/tests/agentTeamNativeControl.test.ts +++ b/tests/agentTeamNativeControl.test.ts @@ -345,26 +345,31 @@ describe('native AgentControl mathematical-team host routing', () => { const accepted = await f.call('spawn', payload, 'lead', f.root, 'spawn-accepted'); expect(await f.call('spawn', payload, 'lead', f.root, 'spawn-accepted')).toEqual(accepted); // Recover the acceptance-before-parent-receipt save window from the fixed child binding. - f.archive.operations = f.archive.operations.filter(item => item.key !== 'native:spawn-accepted'); - await expect(f.call('spawn', { ...payload, startOptions: { parentTurnId: 'different-task-lineage' } }, 'lead', f.root, 'spawn-accepted')) + const archive = structuredClone(f.archive); + archive.operations = []; + const recovered = new AgentTeamNativeControl(archive, f.lifecycle, f.save), root = connection(); + const call = (operation: string, operationId: string, payload: Json) => recovered.options('lead').request({ + version: 1, sessionId: ROOT, threadId: ROOT, operation, operationId, payload, + }, root, { signal: new AbortController().signal }); + await call('attach', 'recovered-attach', { threadId: ROOT, sessionId: ROOT }); + await expect(call('spawn', 'spawn-accepted', { ...payload, startOptions: { parentTurnId: 'different-task-lineage' } })) .rejects.toThrow('call_changed'); - expect(await f.call('spawn', payload, 'lead', f.root, 'spawn-accepted')).toEqual(accepted); - await expect(f.call('spawn', payload)).rejects.toThrow('agent_exists'); + expect(await call('spawn', 'spawn-accepted', payload)).toEqual(accepted); + await expect(call('spawn', 'another-spawn', payload)).rejects.toThrow('agent_exists'); expect(f.lifecycle.spawn).toHaveBeenCalledTimes(1); }); it('makes native transport operations unavailable through the mathematical dynamic tool', () => { - const tool = agentTeamToolDefinition('lead', false, 'native-agent-control'); + const tool = agentTeamToolDefinition('lead'); const operations = (tool.inputSchema.properties as Json).operation.enum; for (const operation of ['spawn', 'assign', 'message', 'poll', 'wait', 'stop', 'resume', 'amend', 'cancel', 'coordinate', 'publish', 'budget', 'progress']) { expect(operations).not.toContain(operation); - expect(agentTeamOperationAllowed('lead', false, 'native-agent-control', operation)).toBe(false); + expect(agentTeamOperationAllowed('lead', operation)).toBe(false); } expect(operations).toEqual(['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary']); - const memberTool = agentTeamToolDefinition('analyst', false, 'native-agent-control'); + const memberTool = agentTeamToolDefinition('analyst'); expect((memberTool.inputSchema.properties as Json).operation.enum).toEqual(['yield', 'history', 'inspect', 'inspect-research', 'submit', 'route_summary']); - expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4, 'native-agent-control')).toContain('native collaboration tools'); - expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4, 'native-agent-control')).not.toContain('Built-in spawn/fork is disabled'); - expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4)).toContain('Built-in spawn/fork is disabled'); + expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4)).toContain('native collaboration tools'); + expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4)).not.toContain('Built-in spawn/fork is disabled'); }); }); diff --git a/tests/agentTeamNativeTools.test.ts b/tests/agentTeamNativeTools.test.ts index e92c478c..dcecbe6c 100644 --- a/tests/agentTeamNativeTools.test.ts +++ b/tests/agentTeamNativeTools.test.ts @@ -20,10 +20,6 @@ const executable = process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? 'codex'; const nativeAvailable = spawnSync(executable, ['--version'], { env: { PATH: process.env.PATH }, timeout: 5000, stdio: 'ignore', }).status === 0; -const operations = ['spawn', 'assign', 'amend', 'finish', 'budget', 'resume', 'history', 'publish', 'cancel', - 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'retire_route', 'route_summary']; -const memberOperations = ['progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', - 'route_summary']; const nativeLeadOperations = ['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary']; const nativeMemberOperations = ['yield', 'history', 'inspect', 'inspect-research', 'submit', 'route_summary']; @@ -96,15 +92,14 @@ function fixtureResponse(response: ServerResponse, id: string, items: Json[]) { // This checks the real native client's wire protocol. The upstream is local and // scripted, so passing this test says nothing about a model choosing to delegate. -describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport without a model', () => { - it.each([{ actor: 'lead', finiteBudget: true }, { actor: 'lead', finiteBudget: false }, { actor: 'member', finiteBudget: false }])( - 'advertises historical $actor operations for finite budget = $finiteBudget', async ({ actor, finiteBudget }) => { +describe.skipIf(!nativeAvailable || !process.env.THEOREMOS_TEST_CODEX_EXECUTABLE)('real Codex dynamic team tool transport without a model', () => { + it.each(['lead', 'member'])('round trips the %s mathematical tool contract', async actor => { const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; fs.mkdirSync(temporaryRoot, { recursive: true }); directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-native-tools-'))); const requests: Json[] = [], routes: string[] = [], errors: unknown[] = []; - const summary = 'Transport fixture: the host received this advisory publication.'; - const args = actor === 'lead' ? { operation: 'publish', summary } : { operation: 'message', agentId: 'lead', message: summary }; + const summary = 'Transport fixture: save Lead finish intent.'; + const args = actor === 'lead' ? { operation: 'finish', summary } : { operation: 'route_summary' }; const call = { type: 'function_call', id: 'fc_team_probe', call_id: 'call_team_probe', name: 'theoremos_team', arguments: JSON.stringify(args), status: 'completed' }; server = createServer(async (request, response) => { @@ -115,7 +110,7 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))); const index = requests.length; const final = { type: 'message', id: 'msg_team_probe', role: 'assistant', status: 'completed', - content: [{ type: 'output_text', text: 'The host publication was received.', annotations: [] }] }; + content: [{ type: 'output_text', text: 'The host result was received.', annotations: [] }] }; const item = index === 1 ? call : final; const isCall = item.type === 'function_call'; const base = { id: 'resp_team_probe_' + index, object: 'response', created_at: 1, @@ -154,12 +149,11 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou const state = solverState(readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), receipt.workspaceRoot, { runId: 'offline-native-tools', phase: 'running', researchMode: 'skill', researchDelegation: { mode: 'team', maxAgents: 3 } }); - if (actor === 'member') state.agentTeam = { schema: 'theorem-os.agent-team.v1', events: [], deliveries: [], adoptions: [], operations: [], - workers: [{ id: 'member', role: 'researcher', worktree: path.join(directory, 'member'), phase: 'prepared', turns: 0, - status: 'idle', seedCommit: state.problem.baseCommit, tasks: [], cursor: 0 }] }; + state.agentTeam = { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', + events: [], deliveries: [], adoptions: [], operations: [], workers: [] }; const team = new AgentResearchTeam({ state, root: process.cwd(), taskText: 'Offline transport fixture only.', leadAccess: { environment: {}, retrievalRoot: receipt.workspaceRoot }, modules: directSolverModules, - executable, profile, signal: new AbortController().signal, maxAgents: 3, maxTurns: finiteBudget ? 4 : Infinity, maxTurnMs: 10_000, + executable, profile, signal: new AbortController().signal, maxAgents: 3, maxTurns: 4, maxTurnMs: 10_000, maxTotalTokens: 0, remainingMs: () => 10_000, save: () => {}, emit: () => {}, exclusiveCheck: operation => operation() }); const tools = team.tools(actor), hostCalls: { name: string; arguments: unknown; threadId: string; turnId: string }[] = []; session = await createCodexMathSession({ executable, profile, workspace: receipt.workspaceRoot, @@ -174,55 +168,16 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou expect(errors).toEqual([]); expect(routes).toEqual(Array(2).fill('/v1/responses')); expect(requests).toHaveLength(2); const advertised = declaredTools(requests[0]).find(tool => tool.name === 'theoremos_team'); - // Codex normalizes provider schemas (for example, omitting numeric bounds). - // Capability names, required arguments and the host round trip are the contract. - expect(advertised?.parameters, JSON.stringify(advertised)).toMatchObject({ type: 'object', required: ['operation'], additionalProperties: false, - properties: { operation: { type: 'string' }, agentId: { type: 'string' }, message: { type: 'string' } } }); - const allowed = actor === 'member' ? memberOperations : - finiteBudget ? operations : operations.filter(name => name !== 'budget'); - expectAdvertisedOperations(advertised!, allowed, tools.definitions[0]!.inputSchema); - expect(advertised?.description).toContain('message: required agentId, message;'); - expect(advertised?.description).toContain(`the host fixes the sender as "${actor}"; agentId names the recipient`); - expect(advertised?.description).toContain('Self-addressed messages are rejected.'); - if (actor === 'member') { - const messageSchema = advertised?.parameters.oneOf.find((branch: Json) => branch.properties.operation.enum[0] === 'message'); - expect(messageSchema).toMatchObject({ required: ['operation', 'agentId', 'message'], additionalProperties: false }); - } - expect(advertised?.description).toContain('route_summary: required none; optional routeId, includeRetired; other fields forbidden.'); - expect(advertised?.parameters.properties.includeRetired).toMatchObject({ type: 'boolean' }); - expect(advertised?.parameters.properties.routeId).toMatchObject({ type: 'string' }); - if (actor === 'lead') { - expect(advertised?.description).not.toContain('coordinate'); - expect(advertised?.description).toContain('retire_route: required routeId, reason; optional evidenceRefs; other fields forbidden.'); - expect(advertised?.parameters.properties).not.toHaveProperty('decision'); - expect(advertised?.parameters.properties).toMatchObject({ reason: { type: 'string' }, - evidenceRefs: { type: 'array', items: { type: 'string' } } }); - } else { - expect(advertised?.description).toContain('submit: required summary, declarations; optional objectiveRevision, helpersOnly; other fields forbidden.'); - const submitSchema = advertised?.parameters.oneOf.find((branch: Json) => branch.properties.operation.enum[0] === 'submit'); - expect(submitSchema.required).toEqual(['operation', 'summary', 'declarations']); - expect(submitSchema.properties).not.toHaveProperty('agentId'); - expect(advertised?.parameters.properties).not.toHaveProperty('decision'); - } - if (finiteBudget) { - expect(advertised?.parameters.properties.budget).toMatchObject({ type: 'object', - properties: { tokens: { type: 'integer' }, turns: { type: 'integer' } } }); - expect(advertised?.parameters.properties.leadReserve).toMatchObject({ type: 'object', - properties: { tokens: { type: 'integer' }, turns: { type: 'integer' } } }); - expect(advertised?.description).toContain('message: required agentId, message;'); - expect(advertised?.description).toContain('budget: required none; optional leadReserve, agentId, taskId, budget;'); - } - else { - expect(advertised?.parameters.properties).not.toHaveProperty('budget'); - expect(advertised?.parameters.properties).not.toHaveProperty('leadReserve'); - } + expectAdvertisedOperations(advertised!, actor === 'member' ? nativeMemberOperations : nativeLeadOperations, + tools.definitions[0]!.inputSchema); + expect(advertised!.parameters.properties).not.toHaveProperty('budget'); + expect(advertised!.parameters.properties).not.toHaveProperty('leadReserve'); expect(hostCalls).toEqual([{ name: 'theoremos_team', arguments: args, threadId: session.threadId, turnId: expect.any(String) }]); - if (actor === 'lead') expect(state.agentTeam!.researchState).toMatchObject({ revision: 1, summary }); - else expect(state.agentTeam!.events).toContainEqual(expect.objectContaining({ from: 'member', to: 'lead', kind: 'message', text: summary })); + if (actor === 'lead') expect(state.agentTeam!.completionRequested).toMatchObject({ summary }); const returned = requests.at(-1)!.input.find((item: Json) => item.type === 'function_call_output' && item.call_id === call.call_id); - expect(JSON.stringify(returned?.output)).toContain(actor === 'lead' ? summary : 'saved-inbox'); - expect(session.lastCompletedResponse?.text).toBe('The host publication was received.'); + expect(JSON.stringify(returned?.output)).toContain(actor === 'lead' ? 'pending-writer-stop' : 'routes'); + expect(session.lastCompletedResponse?.text).toBe('The host result was received.'); expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); }, 20_000); @@ -458,7 +413,7 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou team.beginLeadTurn(); session = await createCodexMathSession({ executable, profile, workspace: state.worktree, environment, model: state.model, effort: state.effort, signal: controller.signal, skills: [researchSkill], - instructions: agentTeamInstructions({ id: 'lead', role: 'lead' }, 2, 'native-agent-control'), + instructions: agentTeamInstructions({ id: 'lead', role: 'lead' }, 2), nativeAgentControl: team.nativeAgentControlOptions(), requestGate: team.leadRequestGate(() => ({ allowed: true, settle: () => {} })), onUsage: () => {}, onItem: (phase, item) => { if (phase === 'started' && item.id === 'native_wait') waitStarted = true; @@ -568,7 +523,7 @@ child.on('close', code => process.exit(code ?? 0)); const state = solverState(readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), receipt.workspaceRoot, { runId: 'offline-native-adopt', phase: 'running', researchMode: 'skill', researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { schema: 'theorem-os.agent-team.v1', workers: [], events: [], adoptions: [], operations: [], + agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], adoptions: [], operations: [], deliveries: [{ id: deliveryId, agentId: 'producer', taskId: 'offline-delivery', path: path.join(directory, 'unused-delivery.json') }] } }); initializeRequestUsageAccounting(state); @@ -636,7 +591,7 @@ child.on('close', code => process.exit(code ?? 0)); }, 20_000); }); -describe.skipIf(!nativeAvailable)('native child decision checkpoints without a model', () => { +describe.skipIf(!nativeAvailable || !process.env.THEOREMOS_TEST_CODEX_EXECUTABLE)('native child decision checkpoints without a model', () => { it.each(['submit', 'yield'] as const)('finishes the paid tool group before %s releases the writer', async operation => { const [{ readMathAgentSkill }, { prepareResearchSkill, researchSkillIdentity }, { deferred }] = await Promise.all([ import('../src/runtime/agentSkills'), import('../src/solver/researchSkill'), import('./helpers/async'), @@ -651,39 +606,31 @@ describe.skipIf(!nativeAvailable)('native child decision checkpoints without a m const decision = operation === 'submit' ? { operation, summary: 'The fixture equality helper is ready.', declarations } : { operation, reason: 'The saved fixture draft needs a peer interface.' }; - const toolCalls = [decision, { operation: 'message', agentId: 'lead', message: 'The final paid tool has finished.' }] + const toolCalls = [decision, { operation: 'history' }] .map((arguments_, index) => ({ type: 'function_call', id: `fc_native_${operation}_${index}`, call_id: `call_native_${operation}_${index}`, name: 'theoremos_team', arguments: JSON.stringify(arguments_), status: 'completed' })); + let leadRequests = 0; server = createServer(async (request, response) => { try { const chunks: Buffer[] = []; for await (const chunk of request) chunks.push(Buffer.from(chunk)); - requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))); - const index = requests.length; - response.once('close', () => { if (!response.writableEnded) prematureCloses.push(index); }); - const final = { type: 'message', id: `msg_native_${operation}`, role: 'assistant', status: 'completed', - content: [{ type: 'output_text', text: 'Unexpected extra paid continuation.', annotations: [] }] }; - const items: Json[] = index === 1 ? toolCalls : [final]; - const base = { id: `resp_native_${operation}_${index}`, object: 'response', created_at: 1, - model: 'deepseek-flash', status: 'in_progress', output: [] }; - const events: Json[] = [{ type: 'response.created', response: base }]; - for (const [output_index, item] of items.entries()) { - events.push({ type: 'response.output_item.added', output_index, - item: item.type === 'function_call' ? { ...item, arguments: '', status: 'in_progress' } - : { ...item, content: [], status: 'in_progress' } }); - if (item.type === 'function_call') events.push( - { type: 'response.function_call_arguments.delta', item_id: item.id, output_index, delta: item.arguments }, - { type: 'response.function_call_arguments.done', item_id: item.id, output_index, arguments: item.arguments }); - else events.push( - { type: 'response.output_text.delta', item_id: item.id, output_index, content_index: 0, delta: final.content[0].text }, - { type: 'response.output_text.done', item_id: item.id, output_index, content_index: 0, text: final.content[0].text }); - events.push({ type: 'response.output_item.done', output_index, item }); + const body = JSON.parse(Buffer.concat(chunks).toString('utf8')); + const text = body.input.filter((item: Json) => ['message', 'agent_message'].includes(item.type)) + .flatMap((item: Json) => item.content ?? []).map((part: Json) => part.text ?? part.encrypted_content ?? '').join('\n'); + const final = (text: string) => ({ type: 'message', id: 'msg_fixture', role: 'assistant', status: 'completed', + content: [{ type: 'output_text', text, annotations: [] }] }); + if (!text.includes('NATIVE_CHILD_PAID_TOOLS')) { + const index = ++leadRequests; + const spawn = { type: 'function_call', id: 'spawn_child', call_id: 'spawn_child', name: 'spawn_agent', + namespace: 'collaboration', status: 'completed', arguments: JSON.stringify({ task_name: 'child', fork_turns: 'none', + message: 'NATIVE_CHILD_PAID_TOOLS Save the fixture handoff.' }) }; + fixtureResponse(response, 'resp_child_fixture_lead_' + index, [index === 1 ? spawn : final('Child dispatched.')]); + return; } - events.push({ type: 'response.completed', response: { ...base, status: 'completed', output: items, - usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 } } }); - response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); - response.end(events.map(event => 'event: ' + event.type + '\ndata: ' + JSON.stringify(event) + '\n\n').join('')); + const index = requests.push(body); + response.once('close', () => { if (!response.writableEnded) prematureCloses.push(index); }); + fixtureResponse(response, `resp_native_${operation}_${index}`, index === 1 ? toolCalls : [final('Unexpected extra paid continuation.')]); } catch (error) { errors.push(error); response.writeHead(500); response.end(); } }); await new Promise((resolve, reject) => { server!.once('error', reject); server!.listen(0, '127.0.0.1', resolve); }); @@ -703,7 +650,9 @@ describe.skipIf(!nativeAvailable)('native child decision checkpoints without a m const state = solverState(problem, receipt.workspaceRoot, { runId: `offline-native-${operation}`, phase: 'running', environmentDigest: 'e'.repeat(64), model: 'deepseek-flash', effort: 'high', researchMode: 'skill', researchSkill: identity, - researchDelegation: { mode: 'team', maxAgents: 2 } }); + researchDelegation: { mode: 'team', maxAgents: 2 }, + agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], + deliveries: [], adoptions: [], operations: [] } }); const researchSkill = prepareResearchSkill(root, state.worktree, identity, problem); const toolchain = path.join(process.env.HOME!, '.elan/toolchains/leanprover--lean4---v4.33.0'); const environment = { PATH: `${toolchain}/bin:${process.env.PATH}`, @@ -719,7 +668,7 @@ describe.skipIf(!nativeAvailable)('native child decision checkpoints without a m session = await createCodexMathSession({ ...options, tools: { definitions: options.tools!.definitions, call: async (name, value, context) => { const args = value as Json; hostCalls.push(args.operation); - if (args.operation === 'message') { + if (args.operation === 'history') { tailRunning = true; await releaseTail.promise; fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'The final paid tool output was preserved.'); tailFinished = true; @@ -733,9 +682,14 @@ describe.skipIf(!nativeAvailable)('native child decision checkpoints without a m leadAccess: { environment, researchSkill, retrievalRoot: receipt.workspaceRoot }, signal: controller.signal, maxAgents: 2, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens: 0, remainingMs: () => Infinity, save: () => {}, emit: () => {}, exclusiveCheck: check => check() }); + const lead = await createCodexMathSession({ executable, profile, workspace: state.worktree, environment, + model: state.model, effort: state.effort, signal: controller.signal, skills: [researchSkill], + instructions: 'Dispatch the disposable child fixture.', nativeAgentControl: team.nativeAgentControlOptions(), tools: team.tools(), + requestGate: team.leadRequestGate(() => ({ allowed: true, settle: () => {} })), onUsage: () => {} }); try { - expect(await team.tools().call('theoremos_team', { operation: 'spawn', agentId: 'child', message: 'Exercise the native fixture handoff.' }, - { callId: 'native-spawn', turnId: 'lead-turn', threadId: 'lead-thread', signal: controller.signal })).toMatchObject({ ok: true }); + team.setLeadSession(lead); + expect(await lead.run('Run the isolated child checkpoint fixture.', 'native-child-fixture', state.worktree, () => {})).toBe('completed'); + expect(leadRequests).toBe(2); const worker = team.archive.workers[0]!; await expect.poll(() => ({ tailRunning, error: worker.error ?? worker.tasks[0]?.error, requests: requests.length, opened: opened.length, activity: worker.activity, status: worker.tasks[0]?.status }), @@ -747,7 +701,7 @@ describe.skipIf(!nativeAvailable)('native child decision checkpoints without a m releaseTail.resolve(); await expect.poll(() => team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); expect(tailFinished).toBe(true); expect(requests).toHaveLength(1); - expect(hostCalls).toEqual([operation, 'message']); + expect(hostCalls).toEqual([operation, 'history']); expect(worker.error).toBeUndefined(); expect(worker.writerStopUnconfirmed).toBeUndefined(); expect(worker.requestUsageAccounting).toMatchObject({ startedRequests: 1, reportedRequests: 1, pendingRequests: 0, incomplete: false }); expect(worker.usageAccounting).toMatchObject({ reportedTurns: 1, pending: false, incomplete: false }); @@ -761,6 +715,6 @@ describe.skipIf(!nativeAvailable)('native child decision checkpoints without a m } expect(errors).toEqual([]); expect(prematureCloses).toEqual([]); expect(state.tokenBudget?.status).toBe('unlimited'); expect(state.check).toBeUndefined(); - } finally { releaseTail.resolve(); controller.abort(); await team.close(); } + } finally { releaseTail.resolve(); controller.abort(); await lead.close(); await team.close(); } }, 90_000); }); diff --git a/tests/agentTeamProof.test.ts b/tests/agentTeamProof.test.ts index 7279e458..a5db0068 100644 --- a/tests/agentTeamProof.test.ts +++ b/tests/agentTeamProof.test.ts @@ -407,7 +407,7 @@ describe('agent-owned declaration deliveries with real Lean', () => { const declarations = [...peer.declarations, ...own]; expect(declarationSubmissionSchema.safeParse({ declarations: own }).success).toBe(true); expect(declarationSubmissionSchema.safeParse({ declarations }).success).toBe(false); - // The duplicate is in the second checker batch; collection-wide delta checks still reject it. + // The last entry repeats the first and leaves a change unnamed. await expect(checkAgentTeamProofDelivery({ ...f.check, agentId: 'consumer', worktree: consumer.worktree, declarations: [...declarations.slice(0, 32), peer.declarations[0]] })) .rejects.toThrow('math_agent_team_proof_undeclared_source_change'); @@ -473,6 +473,22 @@ describe('agent-owned declaration deliveries with real Lean', () => { expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); }); + it('preserves the Git diagnostic when an existing seed commit is missing the owned source', async () => { + const f = fixture(), file = f.source(f.worktree), source = fs.readFileSync(file); + const relative = path.relative(f.worktree, file); + git(f.worktree, ['rm', '--force', '--quiet', '--', relative]); + git(f.worktree, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', + '--no-gpg-sign', '--quiet', '-m', 'Fixture without the owned source']); + const seedCommit = git(f.worktree, ['rev-parse', 'HEAD']); + fs.writeFileSync(file, source); + commitSolverSources(f.problem, f.worktree); + await expect(checkAgentTeamProofDelivery({ ...f.check, seedCommit })).rejects.toMatchObject({ + message: 'math_task_source_unavailable', + diagnostic: { command: 'show', commit: seedCommit, file: relative }, + }); + expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); + }); + it('rechecks changed dependencies instead of accepting the child\'s historical receipt', async () => { const f = fixture(); const established = original.replace('end Team', 'theorem established : True := by trivial\nend Team'); @@ -538,6 +554,21 @@ describe('agent-owned declaration deliveries with real Lean', () => { expect(fs.existsSync(path.join(f.common.evidenceDirectory, 'adoptions'))).toBe(false); }, 90_000); + it('rejects an edit to the staged adoption while Lean is checking', async () => { + const f = fixture(), delivery = await checkAgentTeamProofDelivery(f.check); + const verify = evidence.checkProjectedDeclarations; + vi.spyOn(evidence, 'checkProjectedDeclarations').mockImplementationOnce(async (...args) => { + const result = await verify(...args); + expect(result.passed).toBe(true); + fs.appendFileSync(f.source(args[2]), '\n-- staged source changed after Lean read it\n'); + return result; + }); + await expect(integrateAgentTeamProofDelivery({ ...f.common, delivery, worktree: f.receipt.workspaceRoot, + expectedCommit: f.problem.baseCommit })).rejects.toThrow('math_agent_team_proof_source_changed'); + expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit); + expect(fs.existsSync(path.join(f.common.evidenceDirectory, 'adoption-intents'))).toBe(false); + }, 90_000); + it('recovers the exact FF after publication failed and makes the same call idempotent', async () => { const f = fixture(), delivery = await checkAgentTeamProofDelivery(f.check); const input = { ...f.common, delivery, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; diff --git a/tests/agentTeamRouteSummary.test.ts b/tests/agentTeamRouteSummary.test.ts index 4d166d50..da844069 100644 --- a/tests/agentTeamRouteSummary.test.ts +++ b/tests/agentTeamRouteSummary.test.ts @@ -3,14 +3,14 @@ import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { AgentResearchTeam } from '../src/solver/agentTeam'; import type { AgentTeamTask } from '../src/solver/agentTeamState'; -import { agentTeamRequestSchema, agentTeamToolDefinition, type AgentTeamTransport } from '../src/solver/agentTeamTool'; +import { agentTeamRequestSchema, agentTeamToolDefinition } from '../src/solver/agentTeamTool'; import { directSolverModules } from '../src/solver/modules'; import { localExample, solverState } from './helpers/solver'; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); -function fixture(transport: AgentTeamTransport) { +function fixture() { const { directory, workspace, problem } = localExample('agent-team-route-summary-'); roots.push(directory); const commit = problem.baseCommit, deliveryId = 'a'.repeat(64); @@ -23,7 +23,7 @@ function fixture(transport: AgentTeamTransport) { { id: 'counterexample', status: 'completed', routeId: 'dead', message: 'Boundary fails.', sequence: 5 }, ]; const state = solverState(problem, workspace, { phase: 'running', runId: 'route-summary', researchMode: 'skill', - researchDelegation: { mode: 'team', maxAgents: 2 }, agentTeam: { schema: 'theorem-os.agent-team.v1', transport, canonicalCommit: commit, + researchDelegation: { mode: 'team', maxAgents: 2 }, agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', canonicalCommit: commit, workers: [{ id: 'member', role: 'researcher', worktree: path.join(directory, 'member'), phase: 'running', turns: 1, status: 'running', seedCommit: commit, tasks, cursor: 0 }], retiredRoutes: [{ routeId: 'dead', source: 'lead', reason: 'A boundary counterexample.\nSee probe.', evidenceRefs: ['probe'], retiredAt: 1 }], @@ -44,8 +44,8 @@ function fixture(transport: AgentTeamTransport) { } describe('route_summary through the team tool', () => { - it.each(['host-tools', 'native-agent-control'] as const)('serves Lead and member using %s', async transport => { - const { team, save, call, commit, deliveryId } = fixture(transport); + it('serves Lead and member', async () => { + const { team, save, call, commit, deliveryId } = fixture(); const full = await call('lead'); expect(await call('member')).toEqual(full); expect(full).toMatchObject({ ok: true, canonicalCommit: commit, @@ -66,7 +66,7 @@ describe('route_summary through the team tool', () => { }); it('keeps large Unicode archives under 8 KiB and preserves newest checked references', async () => { - const { team, call, commit } = fixture('host-tools'); + const { team, call, commit } = fixture(); const long = '♾️ 🧮 "\\ \n'.repeat(1_000); for (let i = 1; i <= 200; i++) { team.archive.workers[0]!.tasks.push({ id: 'task-' + i, routeId: 'route-' + i, status: 'running', message: long, sequence: i + 10 }); @@ -89,23 +89,13 @@ describe('route_summary through the team tool', () => { }); describe('Codex operation schema limit', () => { - it.each([false, true])('preserves a full flat host Lead schema for finite budget = %s', finite => { - const definition = agentTeamToolDefinition('lead', finite); - const schema = definition.inputSchema as Record; - expect(schema.properties.operation.enum).toHaveLength(finite ? 19 : 18); - expect(schema).toMatchObject({ type: 'object', required: ['operation'], additionalProperties: false, - properties: { routeId: { type: 'string' }, includeRetired: { type: 'boolean' }, evidenceRefs: { type: 'array' } } }); - expect(schema).not.toHaveProperty('oneOf'); - for (const operation of schema.properties.operation.enum) expect(definition.description).toContain(operation + ': required '); - expect(definition.description).toContain('route_summary: required none; optional routeId, includeRetired; other fields forbidden.'); - expect(agentTeamRequestSchema.safeParse({ operation: 'route_summary', routeId: 'a', reason: 'stray' }).success).toBe(false); - }); - - it.each([['member', 'host-tools', 11], ['lead', 'native-agent-control', 7], ['member', 'native-agent-control', 7]] as const)( - 'preserves exact branches for %s using %s', (actor, transport, count) => { - const schema = agentTeamToolDefinition(actor, false, transport).inputSchema as Record; + it.each([['lead', false, 7], ['member', true, 6], ['lead', true, 8]] as const)( + 'preserves exact branches for %s with approval = %s', (actor, approval, count) => { + const schema = agentTeamToolDefinition(actor, approval).inputSchema as Record; + expect(agentTeamRequestSchema.safeParse({ operation: 'route_summary', routeId: 'a', reason: 'stray' }).success).toBe(false); expect(schema.oneOf).toHaveLength(count); expect(schema.oneOf.map((branch: Record) => branch.properties.operation.enum[0])).toEqual(schema.properties.operation.enum); + expect(schema.properties.operation.enum.includes('publish_plan')).toBe(actor === 'lead' && approval); expect(schema.oneOf.at(-1)).toMatchObject({ type: 'object', required: ['operation'], additionalProperties: false, properties: { operation: { enum: ['route_summary'] }, includeRetired: { type: 'boolean' }, routeId: { type: 'string' } } }); }); diff --git a/tests/agentTeamSolver.test.ts b/tests/agentTeamSolver.test.ts index 888ba307..3ffd3da9 100644 --- a/tests/agentTeamSolver.test.ts +++ b/tests/agentTeamSolver.test.ts @@ -10,19 +10,9 @@ import { bootstrapLeanTask } from '../src/math/leanTask'; import { mathBuildFile, mathBuildSource, MATH_BUILD_INPUTS, MATH_RUNTIME_BUNDLES } from '../src/math/mathBuildManifest'; import { mathDigest, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import { projectMathematicsRuntimeEnvironment } from '../src/math/mathRuntimeEnvironment'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { confirmHarnessProcessStopped, type HarnessProcessIdentity } from '../src/runtime/harnessProcess'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; -import { evaluateSolverProof } from '../src/solver/evaluation'; -import { directSolverModules } from '../src/solver/modules'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { runSolver } from '../src/solver/run'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { solverState } from './helpers/solver'; import { tacticBatteryCacheTestDefines } from './helpers/tacticBatteryCache'; -import { nativeFileWatchFixture } from './helpers/nativeFileWatchFixture'; const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const task = 'Prove the frozen original target using independently checked team helpers.'; @@ -47,7 +37,7 @@ function freezeRuntime(root: string) { fs.cpSync(path.join(repository, relative), destination, { recursive: true }); } const bundleRoot = path.join(root, 'out/main'); - buildSync({ entryPoints: Object.fromEntries(['runMathProof', 'searchLean', 'checkLean', 'proofSearch'] + buildSync({ entryPoints: Object.fromEntries(['runMathProof', 'searchLean', 'checkLean'] .map((name, index) => [MATH_RUNTIME_BUNDLES[index].replace(/\.js$/u, ''), path.join(root, 'scripts/mathematics', name + '.ts')])), outdir: bundleRoot, bundle: true, platform: 'node', format: 'cjs', @@ -61,384 +51,8 @@ function freezeRuntime(root: string) { return manifest; } -const trace = (worktree: string): Record[] => fs.readFileSync( - path.join(worktree, '.scratch/agent-team-peer.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); - -describe.skipIf(process.platform !== 'linux')('Agent team through native tool RPC and independent Lean acceptance', () => { - it('delivers two isolated writers asynchronously, resumes Lead after each adoption and proves the original with both helpers', async () => { - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-solver-'))); - const root = path.join(directory, 'runtime'), buildFile = freezeRuntime(root); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { task, - source: 'namespace Team\ntheorem original (n : Nat) : n + 0 = 0 + n := by sorry\nend Team\n' }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const worktree = path.join(directory, 'lead'); - git(receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, worktree, { runId: 'native-agent-team-solver', phase: 'prepared', - model: 'fixture-model', effort: 'high', environmentDigest: mathDigest('native-team-real-Lean'), - workerCount: 1, coordination: 'independent', researchMode: 'skill', researchSkillWorkflow: 'full', - researchSkill: identity, researchDelegation: { mode: 'team', maxAgents: 3 } }); - const skill = prepareResearchSkill(root, worktree, identity, problem); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); - const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - const profile = path.join(directory, 'profile'), executable = path.join(directory, 'peer'); - fs.mkdirSync(profile); fs.writeFileSync(path.join(profile, 'config.toml'), ''); - fs.writeFileSync(executable, '#!' + process.execPath + '\n' + nativeFileWatchFixture + - fs.readFileSync(path.join(repository, 'tests/fixtures/agentTeamPeer.cjs'), 'utf8'), { mode: 0o700 }); - const processes = new Map(); - const open = vi.fn(directSolverModules.M1.open); - const events: { event: string; details?: Record }[] = []; - const snapshots: SolverRunState[] = []; - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(new Error('native-team-fixture-deadline')), 60_000); - let winner: Awaited>; - try { - winner = await runResearchWorkers({ state, root, buildFile, taskText: task, executable, profile, - workers: [{ id: 'solver', role: 'lead', worktree, ownedFiles: problem.ownedFiles }], - access: new Map([['solver', { environment, retrievalRoot: path.join(worktree, problem.projectRelative), researchSkill: skill }]]), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, - signal: controller.signal, deadline: Date.now() + 60_000, - maxTurns: 8, maxTurnMs: 45_000, maxTotalTokens: 1000, proofTimeoutMs: 30_000, - save: () => { - for (const current of [state.writerProcess, ...(state.agentTeam?.workers.map(worker => worker.writerProcess) ?? [])]) - if (current) processes.set(`${current.pid}:${current.startTime}`, current); - writeSolverRunState(path.join(directory!, 'state.json'), state); - }, emit: (event, details) => { - events.push({ event, details }); - if (event === 'team_event' && details?.kind === 'adopted') snapshots.push(structuredClone(state)); - } }); - } catch (error) { - throw new Error(JSON.stringify({ reason: String(error), leadStop: state.writerStopUnconfirmed, - workers: state.agentTeam?.workers.map(worker => ({ id: worker.id, stop: worker.writerStopUnconfirmed, - error: worker.error, process: worker.writerProcess && confirmHarnessProcessStopped(worker.writerProcess) })), - failures: events.filter(item => /failed|deferred/u.test(item.event)), - }), { cause: error }); - } finally { clearTimeout(timer); } - - expect(winner?.check.passed).toBe(true); - expect(winner?.check.verification.status).toBe('kernel_verified'); - expect(winner?.check.verification.results.map(result => result.theoremName)).toEqual(['Team.original']); - expect(state.turns).toBe(5); - expect(state.threadId).toBe('peer-lead'); - expect(state.teamUsage?.totalTokens).toBe(50); - expect(state.tokenBudget).toMatchObject({ usageComplete: true, reportedTotalTokens: 50 }); - expect(state.agentTeam?.workers).toHaveLength(2); - expect(open).toHaveBeenCalledTimes(5); - for (const [options] of open.mock.calls) { - expect(options).toMatchObject({ turnTimeoutMs: 45_000, turnCheckpointMs: 36_000 }); - } - expect(state.agentTeam?.deliveries).toHaveLength(2); - expect(state.agentTeam?.adoptions.map(adoption => adoption.status)).toEqual(['completed', 'completed']); - expect(state.writerStopUnconfirmed).toBeUndefined(); - expect(state.agentTeam?.workers.every(worker => !worker.writerStopUnconfirmed && !worker.writerProcess)).toBe(true); - expect(processes.size).toBe(5); - expect([...processes.values()].every(identity => confirmHarnessProcessStopped(identity).status === 'stopped')).toBe(true); - expect(snapshots).toHaveLength(2); - expect(snapshots.every(snapshot => snapshot.check?.passed !== true)).toBe(true); - - const leadTrace = trace(worktree), hostFrames = leadTrace.filter(frame => frame.direction === 'host'); - expect(hostFrames.filter(frame => frame.method === 'thread/start')).toHaveLength(1); - expect(hostFrames.filter(frame => frame.method === 'thread/resume').map(frame => frame.params.threadId)) - .toEqual(['peer-lead', 'peer-lead']); - expect(hostFrames.find(frame => frame.method === 'thread/start')?.params.dynamicTools[0].name).toBe('theoremos_team'); - expect(hostFrames.filter(frame => frame.method === 'thread/resume').every(frame => !frame.params.dynamicTools)).toBe(true); - expect(leadTrace).toContainEqual({ observation: 'fast-delivered-while-slow-running' }); - expect(leadTrace.some(frame => frame.observation === 'lead-resumed-with-fast')).toBe(true); - expect(leadTrace.some(frame => frame.observation === 'lead-resumed-with-both')).toBe(true); - expect(state.agentTeam!.researchState).toMatchObject({ revision: 2, - summary: 'The original target consumes fast then symmetric slow; check each exact helper before adoption.' }); - const inspectedResearch = leadTrace.find(frame => frame.observation === 'lead-inspected-research')!; - const fastTask = state.agentTeam!.workers.find(worker => worker.id === 'fast')!.tasks[0]!; - expect(inspectedResearch).toEqual({ observation: 'lead-inspected-research', artifactId: fastTask.researchArtifactId, - taskId: fastTask.id, commit: fastTask.sourceCommit }); - expect(state.agentTeam!.researchArtifacts).toContainEqual(expect.objectContaining({ id: fastTask.researchArtifactId, - taskId: fastTask.id, commit: fastTask.sourceCommit })); - expect(leadTrace.some(frame => frame.observation === 'peer-error')).toBe(false); - - for (const worker of state.agentTeam!.workers) { - expect(worker.worktree).not.toBe(worktree); expect(worker.threadId).toBe(`peer-${worker.id}`); - const childTrace = trace(worker.worktree); - expect(childTrace.some(frame => frame.observation === 'pinned-skill-read')).toBe(true); - expect(childTrace).toContainEqual({ observation: 'worker-received-research', actor: worker.id, revision: 1 }); - expect(childTrace).toContainEqual({ observation: 'worker-polled-current-research', actor: worker.id, revision: 2 }); - expect(childTrace.some(frame => frame.direction === 'peer' && frame.params?.arguments?.operation === 'submit')).toBe(true); - const reference = state.agentTeam!.deliveries.find(delivery => delivery.agentId === worker.id)!; - const delivery = readAgentTeamProofDelivery(reference.path, state); - expect(delivery.artifacts[0]!.proof.verification.status).toBe('kernel_verified'); - expect(delivery.artifacts[0]!.proof.passed).toBe(true); - } - const source = fs.readFileSync(path.join(worktree, problem.projectRelative, 'Submission.lean'), 'utf8'); - expect(source).toContain('exact Eq.trans (fast n) (Eq.symm (slow n))'); - expect(source).not.toContain('sorry'); - expect(events.filter(event => event.event === 'proof_checked')).toHaveLength(1); - expect(git(receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(problem.baseCommit); - }, 90_000); - - it('corrects a rejected child delivery in the same native thread with current task feedback before Lead adoption', async () => { - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-followup-'))); - const root = path.join(directory, 'runtime'), buildFile = freezeRuntime(root); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { task, - source: 'namespace Team\ntheorem original (n : Nat) : n + 0 = n := by sorry\nend Team\n' }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const worktree = path.join(directory, 'lead'); - git(receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, worktree, { runId: 'native-agent-team-followup', phase: 'prepared', - model: 'fixture-model', effort: 'high', environmentDigest: mathDigest('native-team-followup-real-Lean'), - workerCount: 1, coordination: 'independent', researchMode: 'skill', researchSkillWorkflow: 'full', - researchSkill: identity, researchDelegation: { mode: 'team', maxAgents: 2 } }); - const skill = prepareResearchSkill(root, worktree, identity, problem); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); - const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - const profile = path.join(directory, 'profile'), executable = path.join(directory, 'peer'); - fs.mkdirSync(profile); fs.writeFileSync(path.join(profile, 'config.toml'), ''); - fs.writeFileSync(executable, '#!' + process.execPath + '\n' + nativeFileWatchFixture + - fs.readFileSync(path.join(repository, 'tests/fixtures/agentTeamFollowupPeer.cjs'), 'utf8'), { mode: 0o700 }); - const processes = new Map(); - const events: { event: string; details?: Record }[] = []; - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(new Error('native-team-followup-deadline')), 60_000); - let winner: Awaited>; - try { - winner = await runResearchWorkers({ state, root, buildFile, taskText: task, executable, profile, - workers: [{ id: 'solver', role: 'lead', worktree, ownedFiles: problem.ownedFiles }], - access: new Map([['solver', { environment, retrievalRoot: path.join(worktree, problem.projectRelative), researchSkill: skill }]]), - modules: directSolverModules, signal: controller.signal, deadline: Date.now() + 60_000, - maxTurns: 6, maxTurnMs: 45_000, maxTotalTokens: 1000, proofTimeoutMs: 30_000, - save: () => { - for (const current of [state.writerProcess, ...(state.agentTeam?.workers.map(worker => worker.writerProcess) ?? [])]) - if (current) processes.set(`${current.pid}:${current.startTime}`, current); - writeSolverRunState(path.join(directory!, 'state.json'), state); - }, emit: (event, details) => { events.push({ event, details }); } }); - } finally { clearTimeout(timer); } - - expect(winner?.check.passed, JSON.stringify({ events, workers: state.agentTeam?.workers })).toBe(true); - expect(winner?.check.verification.status).toBe('kernel_verified'); - expect(winner?.check.verification.results.map(result => result.theoremName)).toEqual(['Team.original']); - expect(state.turns).toBe(4); expect(state.threadId).toBe('followup-lead'); - expect(state.teamUsage?.totalTokens).toBe(40); - expect(state.agentTeam?.workers).toHaveLength(1); - const worker = state.agentTeam!.workers[0]!, [first, second] = worker.tasks; - expect(worker.worktree).not.toBe(worktree); - expect(worker.threadId).toBe('followup-child'); expect(worker.turns).toBe(2); - expect(worker.tasks.map(task => task.status)).toEqual(['failed', 'completed']); - expect(first!.error).toContain('math_declaration_artifact_check_failed:Team.helper:'); - expect(first!.error).toMatch(/type mismatch/iu); - expect(second!.id).not.toBe(first!.id); - expect(second!.seedCommit).toBe(first!.seedCommit); - expect(worker.pendingSourceBase).toBeUndefined(); expect(worker.pendingDelivery).toBeUndefined(); - expect(state.agentTeam!.deliveries).toHaveLength(1); - expect(state.agentTeam!.adoptions.map(adoption => adoption.status)).toEqual(['completed']); - expect(events.filter(item => item.event === 'team_event' && item.details?.kind === 'failed')) - .toMatchObject([{ details: { from: 'child', to: 'lead', taskId: first!.id, text: expect.stringContaining(first!.error!) } }]); - - const childTrace = trace(worker.worktree), childFrames = childTrace.filter(frame => frame.direction === 'host'); - const childStart = childFrames.find(frame => frame.method === 'thread/start')!; - const childResumes = childFrames.filter(frame => frame.method === 'thread/resume'); - expect(childFrames.filter(frame => frame.method === 'thread/start')).toHaveLength(1); - expect(childResumes.map(frame => frame.params.threadId)).toEqual(['followup-child']); - expect(childResumes[0]!.params.dynamicTools).toBeUndefined(); - const childToolSchema = childStart.params.dynamicTools[0].inputSchema; - const childOperations = ['progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', - 'submit', 'route_summary']; - expect(childToolSchema.properties.operation.enum).toEqual(childOperations); - expect(childToolSchema.oneOf.map((branch: { properties: { operation: { enum: string[] } } }) => - branch.properties.operation.enum[0])).toEqual(childOperations); - expect([childStart, ...childResumes].every(frame => frame.params.developerInstructions.includes( - 'your agentId is "child", and your coordinator is lead.'))).toBe(true); - expect([childStart, ...childResumes].some(frame => frame.params.developerInstructions.includes('You are the Lead'))).toBe(false); - const childTurns = childFrames.filter(frame => frame.method === 'turn/start'); - const assignments = childTurns.map(frame => JSON.parse(frame.params.input.filter((item: { type: string }) => - item.type === 'text').map((item: { text: string }) => item.text).join('\n').split('\n') - .find((line: string) => line.startsWith('{"agentId":')))); - expect(childTurns.map(frame => frame.params.clientUserMessageId)).toEqual([first!.id, second!.id]); - expect(assignments[1]).toMatchObject({ agentId: 'child', coordinator: 'lead', taskId: second!.id, - deliveryBaseCommit: first!.seedCommit, previousTask: { id: first!.id, status: 'failed', error: first!.error } }); - expect(assignments[1].objective).toBe(second!.message); - expect(assignments[1].sourceCommit).not.toBe(assignments[1].deliveryBaseCommit); - expect(git(worker.worktree, ['show', `${assignments[1].sourceCommit}:${problem.projectRelative}/Submission.lean`])) - .toContain('by exact Nat.succ_ne_zero n'); - expect(childTrace.some(frame => frame.observation === 'worker-followup-context')).toBe(true); - - const leadTrace = trace(worktree), leadFrames = leadTrace.filter(frame => frame.direction === 'host'); - const leadToolSchema = leadFrames.find(frame => frame.method === 'thread/start')!.params.dynamicTools[0].inputSchema; - expect(leadToolSchema.properties.operation.enum).toEqual(['spawn', 'assign', 'amend', 'finish', 'budget', - 'resume', 'history', 'publish', 'cancel', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', - 'retire_route', 'route_summary']); - expect(leadToolSchema).not.toHaveProperty('oneOf'); - expect(leadFrames.filter(frame => frame.method === 'thread/resume').map(frame => frame.params.threadId)) - .toEqual(['followup-lead']); - expect(leadTrace).toContainEqual({ observation: 'lead-assigned-correction', - failedTaskId: first!.id, taskId: second!.id, error: first!.error }); - expect(leadTrace.some(frame => frame.observation === 'lead-inspected-corrected-helper')).toBe(true); - expect(leadTrace.some(frame => frame.observation === 'lead-resumed-with-corrected-helper')).toBe(true); - const roleGuideBytes = fs.statSync(path.join(repository, 'skills/theoremos-research/references/team-roles.md')).size; - for (const [frames, actor] of [[childTrace, 'child'], [leadTrace, 'lead']] as const) { - expect(frames.filter(frame => frame.observation === 'team-role-guide-read')) - .toEqual(Array.from({ length: 2 }, () => ({ observation: 'team-role-guide-read', actor, bytes: roleGuideBytes }))); - for (const resource of ['references/domain-experts.md', 'references/domain-experts/number-theory.md', - 'references/domain-materials.md', 'references/domain-materials/number-theory.md']) { - const content = fs.readFileSync(path.join(repository, 'skills/theoremos-research', resource)); - expect(frames.filter(frame => frame.observation === 'domain-expert-resource-read' && frame.resource === resource)) - .toEqual(Array.from({ length: 2 }, () => ({ observation: 'domain-expert-resource-read', actor, - expertId: 'D011', resource, sha256: crypto.createHash('sha256').update(content).digest('hex') }))); - } - } - expect([...childTrace, ...leadTrace].some(frame => frame.observation === 'peer-error')).toBe(false); - const reference = state.agentTeam!.deliveries[0]!, delivery = readAgentTeamProofDelivery(reference.path, state); - expect(reference.taskId).toBe(second!.id); expect(delivery.seedCommit).toBe(first!.seedCommit); - expect(delivery.artifacts[0]!.proof.verification.status).toBe('kernel_verified'); - const source = fs.readFileSync(path.join(worktree, problem.projectRelative, 'Submission.lean'), 'utf8'); - expect(source).toContain('exact helper n'); expect(source).not.toContain('sorry'); - expect(events.filter(item => item.event === 'proof_checked')).toHaveLength(1); - expect(processes.size).toBe(4); - expect([...processes.values()].every(identity => confirmHarnessProcessStopped(identity).status === 'stopped')).toBe(true); - expect(state.writerStopUnconfirmed).toBeUndefined(); expect(worker.writerStopUnconfirmed).toBeUndefined(); - expect(git(receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(problem.baseCommit); - }, 90_000); - - it('preserves one paused native task and its draft across peer adoption, cumulative budgeting and final independent S3 acceptance', async () => { - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-handoff-'))); - const root = path.join(directory, 'runtime'), buildFile = freezeRuntime(root); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { task, - source: 'namespace Team\ntheorem original (n : Nat) : n + 0 = n := by sorry\nend Team\n' }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const worktree = path.join(directory, 'lead'); - git(receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, worktree, { runId: 'native-agent-team-handoff', phase: 'prepared', - model: 'fixture-model', effort: 'high', environmentDigest: mathDigest('native-team-handoff-real-Lean'), - workerCount: 1, coordination: 'independent', researchMode: 'skill', researchSkillWorkflow: 'full', - researchSkill: identity, researchDelegation: { mode: 'team', maxAgents: 3 } }); - const skill = prepareResearchSkill(root, worktree, identity, problem); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); - const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - const profile = path.join(directory, 'profile'), executable = path.join(directory, 'peer'); - fs.mkdirSync(profile); fs.writeFileSync(path.join(profile, 'config.toml'), ''); - fs.writeFileSync(executable, '#!' + process.execPath + '\n' + nativeFileWatchFixture + - fs.readFileSync(path.join(repository, 'tests/fixtures/agentTeamHandoffPeer.cjs'), 'utf8'), { mode: 0o700 }); - const processes = new Map(); - const events: { event: string; details?: Record }[] = []; - const snapshots: { kind: unknown; to: unknown; state: SolverRunState }[] = []; - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(new Error('native-team-handoff-deadline')), 60_000); - let winner: Awaited>; - try { - winner = await runResearchWorkers({ state, root, buildFile, taskText: task, executable, profile, - workers: [{ id: 'solver', role: 'lead', worktree, ownedFiles: problem.ownedFiles }], - access: new Map([['solver', { environment, retrievalRoot: path.join(worktree, problem.projectRelative), researchSkill: skill }]]), - modules: directSolverModules, signal: controller.signal, deadline: Date.now() + 60_000, - maxTurns: 8, maxTurnMs: 45_000, maxTotalTokens: 1000, proofTimeoutMs: 30_000, - save: () => { - for (const current of [state.writerProcess, ...(state.agentTeam?.workers.map(worker => worker.writerProcess) ?? [])]) - if (current) processes.set(`${current.pid}:${current.startTime}`, current); - writeSolverRunState(path.join(directory!, 'state.json'), state); - }, emit: (event, details) => { - events.push({ event, details }); - if (event === 'team_event' && ['paused', 'adopted'].includes(String(details?.kind))) - snapshots.push({ kind: details?.kind, to: details?.to, state: structuredClone(state) }); - } }); - } finally { clearTimeout(timer); } - - const team = state.agentTeam!; - expect(winner?.check.passed, JSON.stringify({ events, workers: team.workers })).toBe(true); - expect(winner?.check.verification.status).toBe('kernel_verified'); - expect(winner?.check.verification.results.map(result => result.theoremName)).toEqual(['Team.original']); - expect(state.turns).toBe(5); expect(state.threadId).toBe('handoff-lead'); - expect(state.teamUsage?.totalTokens).toBe(50); - expect(state.tokenBudget).toMatchObject({ usageComplete: true, reportedTotalTokens: 50 }); - expect(team.workers).toHaveLength(2); expect(team.deliveries).toHaveLength(2); - expect(team.adoptions.map(adoption => ({ targetId: adoption.targetId, status: adoption.status }))) - .toEqual([{ targetId: 'consumer', status: 'completed' }, { targetId: 'lead', status: 'completed' }]); - expect(team.leadReserve).toEqual({ tokens: 50, turns: 2 }); - const consumer = team.workers.find(worker => worker.id === 'consumer')!, [consumerTask] = consumer.tasks; - expect(consumer.tasks).toHaveLength(1); - expect(consumerTask).toMatchObject({ status: 'completed', turns: 2, budget: { tokens: 100, turns: 2 } }); - expect(consumerTask!.pauseRequested).toBeUndefined(); - expect(consumerTask!.declarations?.map(declaration => declaration.name)).toEqual(['Team.combined']); - expect(consumer.pendingSourceBase).toBeUndefined(); expect(consumer.pendingPeerDeliveries).toBeUndefined(); - expect(consumer.pendingDelivery).toBeUndefined(); - const first = JSON.parse(fs.readFileSync(path.join(consumer.worktree, '.scratch/handoff-first-assignment.json'), 'utf8')); - expect(first.assignment.taskId).toBe(consumerTask!.id); - expect(consumerTask!.seedCommit).toBe(first.assignment.deliveryBaseCommit); - - const paused = snapshots.find(snapshot => snapshot.kind === 'paused')!.state.agentTeam!.workers - .find(worker => worker.id === 'consumer')!; - const adopted = snapshots.find(snapshot => snapshot.kind === 'adopted' && snapshot.to === 'consumer')!.state.agentTeam!.workers - .find(worker => worker.id === 'consumer')!; - expect(paused.tasks[0]).toMatchObject({ id: consumerTask!.id, status: 'paused', turns: 1, - seedCommit: first.assignment.deliveryBaseCommit, pauseRequested: { kind: 'handoff' } }); - expect(paused.writerProcess).toBeUndefined(); expect(paused.writerStopUnconfirmed).toBeUndefined(); - expect(paused.pendingSourceBase).toBe(first.assignment.deliveryBaseCommit); - expect(git(consumer.worktree, ['show', `${paused.tasks[0]!.sourceCommit}:${problem.projectRelative}/Submission.lean`])) - .toContain(first.draft.trim()); - expect(adopted.tasks[0]).toMatchObject({ id: consumerTask!.id, status: 'paused', turns: 1 }); - expect(adopted.pendingSourceBase).toBe(paused.pendingSourceBase); - expect(adopted.pendingPeerDeliveries).toEqual([team.deliveries.find(delivery => delivery.agentId === 'producer')!.id]); - const notes = team.researchArtifacts!.filter(artifact => artifact.taskId === consumerTask!.id) - .map(artifact => JSON.parse(fs.readFileSync(artifact.path, 'utf8'))); - expect(notes.map(note => note.status)).toEqual(['paused', 'completed']); - expect(notes[0]).toMatchObject({ commit: paused.tasks[0]!.sourceCommit, advisory: true, originalProblemAcceptance: 'not-assessed' }); - expect(notes[0].notes.text).toContain('awaits checked Team.dependency'); - expect(notes[1].notes.text).toContain('Resumed the same task after adoption'); - - const leadTrace = trace(worktree), consumerTrace = trace(consumer.worktree); - const consumerFrames = consumerTrace.filter(frame => frame.direction === 'host'); - expect(consumerFrames.filter(frame => frame.method === 'thread/start')).toHaveLength(1); - expect(consumerFrames.filter(frame => frame.method === 'thread/resume').map(frame => frame.params.threadId)) - .toEqual(['handoff-consumer']); - expect(consumerFrames.filter(frame => frame.method === 'turn/start').map(frame => frame.params.clientUserMessageId)) - .toEqual([consumerTask!.id, consumerTask!.id]); - const resumed = consumerTrace.find(frame => frame.observation === 'consumer-resumed-and-submitted-own-declaration')!; - expect(resumed).toMatchObject({ taskId: consumerTask!.id, threadId: first.threadId, - assignment: { deliveryBaseCommit: first.assignment.deliveryBaseCommit }, declarations: consumerTask!.declarations }); - expect(resumed.turnId).not.toBe(first.turnId); - expect(consumerTrace.filter(frame => frame.observation === 'handoff-worker-history')).toHaveLength(2); - expect(leadTrace.filter(frame => frame.observation === 'lead-observed-paused-draft')).toHaveLength(1); - expect(leadTrace.filter(frame => frame.observation === 'lead-resumed-same-consumer-task')).toHaveLength(1); - expect(leadTrace.filter(frame => frame.observation === 'lead-inspected-carried-peer')).toHaveLength(1); - expect(leadTrace.filter(frame => frame.observation === 'handoff-lead-proved-original')).toHaveLength(1); - expect(leadTrace.filter(frame => frame.direction === 'peer' && frame.params?.arguments?.operation === 'budget')).toHaveLength(2); - const reference = team.deliveries.find(delivery => delivery.agentId === 'consumer')!; - const delivery = readAgentTeamProofDelivery(reference.path, state); - expect(delivery.seedCommit).toBe(first.assignment.deliveryBaseCommit); - expect(delivery.declarations.map(declaration => declaration.name).toSorted()).toEqual(['Team.combined', 'Team.dependency']); - expect(delivery.artifacts.every(artifact => artifact.proof.passed && artifact.proof.commit === delivery.commit && - artifact.proof.verification.status === 'kernel_verified')).toBe(true); - for (const frames of [leadTrace, ...team.workers.map(worker => trace(worker.worktree))]) - expect(frames.some(frame => frame.observation === 'peer-error')).toBe(false); - expect(state.writerStopUnconfirmed).toBeUndefined(); - expect(team.workers.every(worker => !worker.writerProcess && !worker.writerStopUnconfirmed)).toBe(true); - expect(processes.size).toBe(5); - expect([...processes.values()].every(identity => confirmHarnessProcessStopped(identity).status === 'stopped')).toBe(true); - const source = fs.readFileSync(path.join(worktree, problem.projectRelative, 'Submission.lean'), 'utf8'); - expect(source).toContain('theorem dependency'); expect(source).toContain(first.draft); - expect(source).toContain('exact combined n'); expect(source).not.toContain('sorry'); - expect(git(receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(problem.baseCommit); - - const evaluation = await evaluateSolverProof(problem, winner!.check, - environment, controller.signal, { timeoutMs: 30_000 }); - expect(evaluation).toMatchObject({ status: 'passed', method: 'host-lean-kernel-all-targets', - verification: { passed: true, commit: winner!.check.commit, verification: { status: 'kernel_verified' } } }); - expect(git(receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(winner!.check.commit); - }, 120_000); - - it('freezes the new native transport and resumes historical host-tool runs through CLI preparation and independent S3 evaluation', async () => { +describe.skipIf(process.platform !== 'linux')('CLI native team startup and historical resume', () => { + it('freezes native transport at startup and directs a historical host-tool resume to its original revision', async () => { const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; fs.mkdirSync(temporaryRoot, { recursive: true }); directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-cli-'))); @@ -476,8 +90,7 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP fs.writeFileSync(path.join(profile, 'config.toml'), 'model_provider = "fixture"\n' + '[model_providers.fixture]\nname = "Local protocol fixture"\nwire_api = "responses"\n' + `base_url = "http://127.0.0.1:${address.port}/v1"\n`); - fs.writeFileSync(executable, '#!' + process.execPath + '\n' + nativeFileWatchFixture + - fs.readFileSync(path.join(repository, 'tests/fixtures/agentTeamPeer.cjs'), 'utf8'), { mode: 0o700 }); + fs.writeFileSync(executable, '#!' + process.execPath + '\nprocess.exitCode = 1;\n', { mode: 0o700 }); const events: Record[] = []; vi.spyOn(console, 'log').mockImplementation(line => { events.push(JSON.parse(String(line))); }); const args = ['--workspace', receipt.workspaceRoot, '--task-file', taskFile, @@ -491,60 +104,11 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP const historicalFile = path.join(output + '.runtime', 'state.json'); const historical = readSolverRunState(historicalFile); expect(historical.agentTeam?.transport).toBe('native-agent-control'); - // This fixture implements the historical dynamic tool protocol. Existing - // saved runs retain it even when the current default uses AgentControl. delete historical.agentTeam!.transport; writeSolverRunState(historicalFile, historical); - const code = await runSolver([...args, '--research-mode', 'skill', '--skill-delegation', 'team', '--skill-max-agents', '3', '--resume'], root); - const result = JSON.parse(fs.readFileSync(output, 'utf8')); - expect(code, JSON.stringify({ result, events })).toBe(0); - expect(result).toMatchObject({ status: 'evaluated_passed', solver_ready_receipt_valid: true, - completion_signal_valid: true, explanations: { status: 'disabled', targets: [] }, - evaluator: { status: 'passed', method: 'host-lean-kernel-all-targets', verification: { passed: true } } }); - const state = readSolverRunState(path.join(output + '.runtime', 'state.json')); - expect(state).toMatchObject({ phase: 'finished', researchMode: 'skill', - researchDelegation: { mode: 'team', maxAgents: 3 }, workerCount: 1, coordination: 'independent', - threadId: 'peer-lead', turns: 5, check: { passed: true } }); - expect(state.agentTeam?.workers.map(worker => worker.id).toSorted()).toEqual(['fast', 'slow']); - expect(state.agentTeam?.deliveries).toHaveLength(2); - expect(state.agentTeam?.adoptions.map(adoption => adoption.status)).toEqual(['completed', 'completed']); - expect(state.teamUsage?.totalTokens).toBe(50); - const runtime = output + '.runtime'; - expect(JSON.parse(fs.readFileSync(path.join(runtime, 'toolchain-readiness.json'), 'utf8')).status).toBe('ready'); - expect(JSON.parse(fs.readFileSync(path.join(runtime, 'provider-connectivity.json'), 'utf8')).status).toBe('reachable'); - expect(httpRequests).toEqual([{ method: 'HEAD', url: '/v1/models' }, { method: 'HEAD', url: '/v1/models' }]); - for (const id of ['solver', 'fast', 'slow']) { - const accessId = id === 'solver' ? id : 'team-' + id; - const diagnostics = JSON.parse(fs.readFileSync(path.join(runtime, - id === 'solver' ? 'preparation-diagnostics.json' : `preparation-${accessId}.json`), 'utf8')); - expect(diagnostics).toMatchObject({ exitCode: 0, timedOut: false }); - const projectedPath = path.join(runtime, `environment-${accessId}.json`); - const projected = JSON.parse(fs.readFileSync(projectedPath, 'utf8')); - expect(projected.DEEPSCIENTIST_MATH_SANDBOX_BACKEND).toBe('bwrap'); - expect(projected.DEEPSCIENTIST_MATH_ENV_FILE).toBe(projectedPath); - const writerWorktree = id === 'solver' ? state.worktree : state.agentTeam!.workers.find(worker => worker.id === id)!.worktree; - const started = trace(writerWorktree).find(frame => frame.direction === 'host' && frame.method === 'thread/start'); - expect(started?.params.cwd).toBe(writerWorktree); - expect(started?.params.developerInstructions).toContain(projectedPath); - expect(started?.params.developerInstructions).toContain(path.join(writerWorktree, state.problem.projectRelative)); - } - for (const worker of state.agentTeam!.workers) { - expect(worker.threadId).toBe(`peer-${worker.id}`); - expect(worker.writerProcess).toBeUndefined(); expect(worker.writerStopUnconfirmed).toBeUndefined(); - const reference = state.agentTeam!.deliveries.find(delivery => delivery.agentId === worker.id)!; - const delivery = readAgentTeamProofDelivery(reference.path, state); - expect(delivery.artifacts[0]!.proof.verification.status).toBe('kernel_verified'); - expect(delivery.artifacts[0]!.proof.passed).toBe(true); - expect(trace(worker.worktree).some(frame => frame.observation === 'pinned-skill-read')).toBe(true); - } - const finalCheck = result.evaluator.verification; - expect(finalCheck.commit).toBe(state.check!.commit); - expect(finalCheck.verification.status).toBe('kernel_verified'); - expect(finalCheck.verification.results.map((item: { theoremName: string }) => item.theoremName)).toEqual(['Team.original']); - expect(git(receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(state.check!.commit); - const source = fs.readFileSync(path.join(receipt.projectRoot, 'Submission.lean'), 'utf8'); - expect(source).toContain('exact Eq.trans (fast n) (Eq.symm (slow n))'); expect(source).not.toContain('sorry'); - expect(events.some(event => event.event === 'evaluation_finished' && event.status === 'passed')).toBe(true); - expect(trace(state.worktree).filter(frame => frame.direction === 'host' && frame.method === 'thread/resume')).toHaveLength(2); + const beforeResume = fs.readFileSync(historicalFile); + await expect(runSolver([...args, '--agent-team', '3', '--resume'], root)).rejects.toThrow('math_legacy_collaboration_retired'); + expect(fs.readFileSync(historicalFile)).toEqual(beforeResume); + expect(httpRequests).toEqual([{ method: 'HEAD', url: '/v1/models' }]); }, 150_000); }); diff --git a/tests/agentTeamSourceRecovery.test.ts b/tests/agentTeamSourceRecovery.test.ts index 7fef3dff..ddd0c137 100644 --- a/tests/agentTeamSourceRecovery.test.ts +++ b/tests/agentTeamSourceRecovery.test.ts @@ -3,14 +3,19 @@ import os from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { bootstrapLeanTask } from '../src/math/leanTask'; +import { LIBRARY_PACK_SCHEMA } from '../src/math/libraryPacks'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { readMathAgentSkill } from '../src/runtime/agentSkills'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; +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 { directSolverModules } from '../src/solver/modules'; +import { agentLibrary, LIBRARY_ACCESS_FILE, LIBRARY_REQUEST_FILE, type LibraryAccess, writeLibraryAccess } from '../src/solver/libraryAccess'; +import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; import { git, readSolverProblem } from '../src/solver/problem'; +import { RESEARCH_TOOL_HELP_FILE } from '../src/solver/researchToolHelp'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; import type { SoftSliceSettings } from '../src/solver/softSlice'; import { deferred } from './helpers/async'; @@ -25,16 +30,43 @@ const original = 'namespace Recovery\ntheorem goal : True := by sorry\nend Recov const helper = 'theorem helper : True := by trivial\n'; const declarations = [{ file: 'Submission.lean', name: 'Recovery.helper', type: 'True' }]; const fixtures: ReturnType[] = []; +const rootThreadId = '00000000-0000-4000-8000-000000000001'; -function fixture(maxAgents = 2, softSlice?: SoftSliceSettings, stallInterrupt = false) { +function nativeConnection(threadId: string, agentPath: string, cwd: string, notices: string[] = []): NativeAgentControlConnection { + return { info: { sessionId: rootThreadId, + agent: { threadId, metadata: { agentPath, agentId: threadId }, status: 'running' }, configSnapshot: { cwd } }, + request: vi.fn(async () => ({})), + input: vi.fn(async () => ({ accepted: true, threadId, submissionId: crypto.randomUUID() })), + update: vi.fn(async value => { + notices.push(...((value as { mailbox?: { message?: { text?: string } }[] }).mailbox ?? []).flatMap(item => item.message?.text ?? [])); + return { acceptedSequence: value.sequence }; + }), + }; +} + +function fixture({ maxAgents = 2, softSlice, stallInterrupt = false, librarySource, maxTotalTokens = 0 }: { + maxAgents?: number; softSlice?: SoftSliceSettings; stallInterrupt?: boolean; librarySource?: string; maxTotalTokens?: number; +} = {}) { const directory = temporaryDirectory('agent-team-source-recovery-'); const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { source: original, task: 'Prove True.' }); 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', environmentDigest: mathDigest('real Lean True recovery fixture'), researchMode: 'skill', researchSkillWorkflow: 'full', - researchSkill: identity, researchDelegation: { mode: 'team', maxAgents }, workerCount: 1, coordination: 'independent' }); + researchSkill: identity, researchDelegation: { mode: 'team', maxAgents }, workerCount: 1, coordination: 'independent', + requestUsageAccounting: { startedRequests: 0, reportedRequests: 0, pendingRequests: 0, incomplete: false }, + agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', + workers: [], events: [], deliveries: [], adoptions: [], operations: [] } }); const skill = prepareResearchSkill(root, state.worktree, identity, problem); + let libraryCatalog: LibraryAccess | undefined; + if (librarySource) { + const file = 'Submission/Library/TeamFixture.lean'; + const release = writeLibraryCatalog(path.join(directory, 'release'), { id: 'fixture/native-team-library', revision: 'v1', + environment: 'standard', packs: [{ schema: LIBRARY_PACK_SCHEMA, modules: [{ file, source: librarySource, + origin: { kind: 'upstream', repository: 'offline-native-fixture', commit: 'a'.repeat(40), file } }] }] }); + libraryCatalog = { file: release.file, digest: release.digest }; + writeLibraryAccess(problem, state.worktree, libraryCatalog); + } const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, @@ -46,11 +78,17 @@ function fixture(maxAgents = 2, softSlice?: SoftSliceSettings, stallInterrupt = const stateFile = path.join(directory, 'run-state.json'); const makeTeam = (current: SolverRunState) => { const team = new AgentResearchTeam({ state: current, root, taskText: 'Prove True.', - leadAccess: { environment, retrievalRoot: path.join(current.worktree, problem.projectRelative), researchSkill: skill }, + leadAccess: { environment, retrievalRoot: path.join(current.worktree, problem.projectRelative), researchSkill: skill, libraryCatalog }, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: async options => { const outcome = deferred(), record = { options, message: '', notices: [] as string[], complete: () => outcome.resolve('completed') }; sessions.push(record); - const session: MathAgentSession = { threadId: options.threadId ?? 'source-recovery-member', + const config = options.nativeAgentControl!; + const threadId = options.threadId ?? String(config.bootstrap!.threadId); + const connection = nativeConnection(threadId, '/root/' + options.environment!.DEEPSCIENTIST_MATH_WORKER_ID, options.workspace, record.notices); + await config.request({ version: 1, sessionId: rootThreadId, threadId, operation: 'attach', operationId: crypto.randomUUID(), + payload: { threadId, sessionId: rootThreadId } }, connection, { signal: controller.signal }); + await config.bound?.(connection); + const session: MathAgentSession = { threadId, nativeAgentControl: connection, usageSource: 'upstream-requests', run: async (message, _id, _workspace, started) => { record.message = message; started('source-recovery-turn-' + sessions.length); return outcome.promise; @@ -58,12 +96,15 @@ function fixture(maxAgents = 2, softSlice?: SoftSliceSettings, stallInterrupt = notify: async message => { record.notices.push(message); }, interrupt: async () => { if (!stallInterrupt) outcome.resolve('interrupted'); }, stopForFreeze: async () => ({ status: 'stopped' }), - close: async () => { if (stallInterrupt) outcome.resolve('interrupted'); }, + close: async () => { + if (stallInterrupt) outcome.resolve('interrupted'); + await config.disconnected?.(connection); + }, }; return session; } } }, executable: 'offline-no-model', profile: 'offline-no-credentials', signal: controller.signal, - maxAgents, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens: 0, remainingMs: () => Infinity, + maxAgents, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens, remainingMs: () => Infinity, softSlice, save: () => writeSolverRunState(stateFile, current), emit: (event, details) => { events.push({ event, details }); }, exclusiveCheck: operation => operation(), @@ -73,7 +114,26 @@ function fixture(maxAgents = 2, softSlice?: SoftSliceSettings, stallInterrupt = const team = makeTeam(state); let calls = 0; const call = (operation: Record, actor = 'lead', target = team) => target.tools(actor).call('theoremos_team', operation, { callId: 'source-recovery-call-' + ++calls, turnId: 'source-recovery-turn', threadId: 'source-recovery-thread', signal: controller.signal }) as Promise; - const current = { directory, state, stateFile, controller, sessions, teams, team, makeTeam, call, events, problem, + const native = async (operation: string, payload: Record, target = team) => { + const options = target.nativeAgentControlOptions(); + const connection = nativeConnection(rootThreadId, '/root', state.worktree); + const request = (method: string, args: Record) => options.request({ + version: 1, threadId: rootThreadId, sessionId: rootThreadId, operation: method, operationId: crypto.randomUUID(), payload: args, + }, connection, { signal: controller.signal }); + await request('attach', { threadId: rootThreadId, sessionId: rootThreadId }); + await options.bound?.(connection); + return request(operation, { caller: rootThreadId, ...payload }); + }; + const input = (text: string) => ({ kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } }); + const spawn = (name: string, message: string) => { + const source = { subagent: { thread_spawn: { parent_thread_id: rootThreadId, agent_path: '/root/' + name, depth: 1 } } }; + return native('spawn', { source, bootstrap: { source, config: { cwd: state.worktree, model: state.model, reasoningEffort: state.effort } }, + input: input(message), startOptions: { parentTurnId: 'root-turn' } }); + }; + 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, 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]!; @@ -94,10 +154,93 @@ async function idle(team: AgentResearchTeam) { await expect.poll(() => team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); } -describe('recoverable team source rejections', () => { +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'; + const f = fixture({ librarySource: source }); + await f.spawn('member', 'Find the exact declaration in the published library.'); + const child = await f.session(0), worktree = child.options.workspace; + const name = 'TeamFixture.library_helper', library = agentLibrary(worktree); + expect(library.search(name).hits[0]).toMatchObject({ name, installation: 'not-installed' }); + expect(library.get(name).source).toMatchObject({ complete: true, text: source }); + expect(fs.readFileSync(path.join(worktree, RESEARCH_TOOL_HELP_FILE), 'utf8')).toContain('Lead requests installation for the team'); + expect(() => library.request([name], 'Apply the checked helper.')).toThrow('math_library_request_lead_required'); + expect(fs.existsSync(path.join(worktree, LIBRARY_REQUEST_FILE))).toBe(false); + expect(agentLibrary(f.state.worktree).request([name], 'Apply the checked helper.')).toMatchObject({ status: 'queued' }); + expect(fs.existsSync(path.join(f.state.worktree, LIBRARY_REQUEST_FILE))).toBe(true); + }); + + it('prepares the math library on demand when an idle member resumes its saved thread', async () => { + const name = 'TeamFixture.library_helper'; + const f = fixture({ librarySource: `theorem ${name} : True := by trivial\n` }); + await f.spawn('member', 'Check the local identity.'); + const first = await f.session(0), worktree = first.options.workspace; + const threadId = f.team.archive.workers[0]!.native!.threadId; + first.complete(); await idle(f.team); await f.team.close(); + const catalog = path.join(worktree, LIBRARY_ACCESS_FILE); + fs.unlinkSync(catalog); + + const restored = f.makeTeam(readSolverRunState(f.stateFile)); + await restored.restore(); + expect(fs.existsSync(catalog)).toBe(false); + expect(f.sessions).toHaveLength(1); + + await f.followup('member', 'Look up the exact lemma for the next step.', restored); + const next = await f.session(1); + expect(next.options.threadId).toBe(threadId); + expect(next.options.workspace).toBe(worktree); + expect(agentLibrary(worktree).get(name).source.complete).toBe(true); + next.complete(); await idle(restored); + }); + + it('charges member receipts to the same run budget and blocks a subsequent request when exhausted', async () => { + const f = fixture({ maxAgents: 3, maxTotalTokens: 50 }); + await f.spawn('first', 'Check the local identity.'); + await f.spawn('second', 'Read the hypotheses.'); + const first = await f.session(0), second = await f.session(1); + for (const [index, session] of [first, second].entries()) { + const admission = session.options.requestGate!({ requestId: 'budget-' + index }); + if (admission.allowed === false) throw new Error(admission.reason); + const totalTokens = index === 0 ? 20 : 30; + const receipt = { usage: { inputTokens: totalTokens - 2, outputTokens: 2, totalTokens }, complete: true, + outcome: 'completed' as const }; + admission.settle(receipt); + admission.settle(receipt); + } + expect(f.state.teamUsage).toMatchObject({ totalTokens: 50, inputTokens: 46, outputTokens: 4 }); + expect(f.state.tokenBudget).toMatchObject({ status: 'exhausted', usageComplete: true }); + expect(first.options.requestGate!({ requestId: 'blocked' })).toEqual({ allowed: false, reason: 'math_total_token_limit' }); + first.complete(); second.complete(); await idle(f.team); + expect(f.team.archive.workers.map(worker => worker.requestUsageAccounting!.reportedRequests)).toEqual([1, 1]); + }); + + it('restores lost member receipts before admitting more work under a finite shared budget', async () => { + const f = fixture({ maxTotalTokens: 50 }); + await f.spawn('member', 'Check the local identity.'); + const child = await f.session(0); + const reported = child.options.requestGate!({ requestId: 'reported' }); + if (!reported.allowed) throw new Error(reported.reason); + reported.settle({ complete: true, usage: { inputTokens: 18, outputTokens: 2, totalTokens: 20 } }); + expect(child.options.requestGate!({ requestId: 'lost' }).allowed).toBe(true); + const saved = readSolverRunState(f.stateFile); + expect(saved.tokenBudget).toMatchObject({ status: 'available', reportedTotalTokens: 20, usageComplete: false }); + child.complete(); await idle(f.team); await f.team.close(); + + const restored = f.makeTeam(saved); await restored.restore(); + const recovered = readSolverRunState(f.stateFile); + expect(recovered.tokenBudget).toMatchObject({ status: 'usage-unavailable', reportedTotalTokens: 20, usageComplete: false }); + expect(recovered.teamUsage).toMatchObject({ totalTokens: 20 }); + expect(recovered.agentTeam!.workers[0]!.requestUsageAccounting).toMatchObject({ + pendingRequests: 0, incomplete: true, receipts: [expect.objectContaining({ status: 'reported' }), + expect.objectContaining({ requestId: 'lost', status: 'missing', missingReason: 'resumed-without-receipt' })], + }); + await expect(f.followup('member', 'Continue the investigation.', restored)).rejects.toThrow(); + expect(f.sessions).toHaveLength(1); + }); + it('preserves an unfinished child assignment that returns after a two-compaction milestone notice', async () => { - const f = fixture(2, { softSliceMs: 0, maxCompactionsPerSlice: 2 }); - await f.call({ operation: 'spawn', agentId: 'member', message: 'Investigate a partial proof.' }); + const f = fixture({ softSlice: { softSliceMs: 0, maxCompactionsPerSlice: 2 } }); + await f.spawn('member', 'Investigate a partial proof.'); const session = await f.session(0), worker = f.team.archive.workers[0]!; const activity = session.options.onActivity!; activity({ event: 'item_started', itemType: 'contextCompaction' }); @@ -117,8 +260,8 @@ describe('recoverable team source rejections', () => { }); it('closes an unsettled writer after the milestone checkpoint and preserves its draft', async () => { - const f = fixture(2, { softSliceMs: 0, maxCompactionsPerSlice: 1, softSliceGraceMs: 1 }, true); - await f.call({ operation: 'spawn', agentId: 'member', message: 'Investigate a partial proof.' }); + const f = fixture({ softSlice: { softSliceMs: 0, maxCompactionsPerSlice: 1, softSliceGraceMs: 1 }, stallInterrupt: true }); + await f.spawn('member', 'Investigate a partial proof.'); const session = await f.session(0), worker = f.team.archive.workers[0]!; fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'This draft belongs to the same task.\n'); vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); @@ -139,10 +282,10 @@ describe('recoverable team source rejections', () => { }); it('lands standalone helpers with the producer task open and installs them in a peer with unpublished work', async () => { - const f = fixture(3); - await f.call({ operation: 'spawn', agentId: 'member', message: 'Prove the goal and its helper lemmas.' }); + const f = fixture({ maxAgents: 3 }); + await f.spawn('member', 'Prove the goal and its helper lemmas.'); const a = await f.session(0), producer = f.team.archive.workers[0]!; - await f.call({ operation: 'spawn', agentId: 'peer', message: 'Draft another proof step.' }); + await f.spawn('peer', 'Draft another proof step.'); const b = await f.session(1), consumer = f.team.archive.workers[1]!; const helperProofs = helper + 'theorem second : True := helper\n'; const draft = 'theorem draft : True := by sorry\n'; @@ -168,24 +311,26 @@ describe('recoverable team source rejections', () => { expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).not.toContain('theorem second'); b.complete(); await idle(f.team); - await f.team.flushAdoptions(); + await f.team.close(); + const saved = readSolverRunState(f.stateFile), restored = f.makeTeam(saved); + await restored.restore(); expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain('theorem goal : True := by sorry'); - await f.call({ operation: 'assign', agentId: 'peer', message: 'Use the landed helpers to finish both proofs.' }); - const next = await f.session(2); - expect(next.message).toContain('landedHelpers'); - expect(next.message).toContain('Recovery.second'); const seeded = fs.readFileSync(f.source(consumer.worktree), 'utf8'); expect(seeded).toContain(helperProofs); expect(seeded).toContain(draft); + await f.followup('peer', 'Use the landed helpers to finish both proofs.', restored); + const next = await f.session(2); + 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: [ { ...declarations[0]!, name: 'Recovery.goal' }, { ...declarations[0]!, name: 'Recovery.draft' }, - ] }, 'peer'); - next.complete(); await idle(f.team); - const delivery = f.team.archive.deliveries.find(item => item.agentId === 'peer')!; - expect(readAgentTeamProofDelivery(delivery.path, f.state).artifacts.map(item => item.declaration.name)) + ] }, 'peer', restored); + 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']); - expect(f.state.check).toBeUndefined(); + expect(saved.check).toBeUndefined(); }, 60_000); it('replays a recorded submit_helpers call from an older member thread', async () => { @@ -193,17 +338,23 @@ describe('recoverable team source rejections', () => { const originalCall = { operation: 'submit_helpers', summary: 'Verified standalone facts.', declarations }; const context = { threadId: 'old-member-thread', turnId: 'old-turn', callId: 'old-submit', signal: f.controller.signal }; const result = { ok: true, status: 'pending-writer-stop', taskId: 'old-task' }; - f.team.archive.operations.push({ - key: canonicalMathJson(['member', context.threadId, context.turnId, context.callId]), - digest: mathDigest(canonicalMathJson(originalCall)), result, - }); - const tools = f.team.tools('member'); + const saved = structuredClone(f.state); + const key = canonicalMathJson(['member', context.threadId, context.turnId, context.callId]); + const changedCall = { ...originalCall, summary: 'Changed replay.' }; + saved.agentTeam!.operations.push( + { key, digest: mathDigest(canonicalMathJson(originalCall)), result }, + { key, digest: mathDigest(canonicalMathJson(changedCall)), result: { ok: false } }, + ); + writeSolverRunState(f.stateFile, saved); + const restored = f.makeTeam(readSolverRunState(f.stateFile)); + const tools = restored.tools('member'); await expect(tools.call('theoremos_team', originalCall, context)).resolves.toEqual(result); - expect(f.team.archive.operations).toHaveLength(1); + await expect(tools.call('theoremos_team', changedCall, context)).rejects.toThrow('math_team_call_changed'); + expect(restored.archive.operations).toEqual(saved.agentTeam!.operations); }); it('preserves the rejected Lean interface and check receipt for the producer, a repair peer and restored history', async () => { - const f = fixture(3); await f.call({ operation: 'spawn', agentId: 'member', message: 'Prove the helper.' }); + const f = fixture({ maxAgents: 3 }); 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('end Recovery', helper + 'end Recovery')); const wrong = [{ ...declarations[0]!, type: 'False' }]; @@ -220,18 +371,18 @@ describe('recoverable team source rejections', () => { expect(f.team.archive.events.find(event => event.kind === 'failed')?.text).toContain(JSON.stringify(locator)); expect(f.team.archive.deliveries).toHaveLength(0); expect(readSolverRunState(f.stateFile).agentTeam!.workers[0]!.tasks[0]!.failedCheck).toEqual(failure); - await f.call({ operation: 'assign', agentId: 'member', message: 'Repair the rejected declaration.' }); + await f.followup('member', 'Repair the rejected declaration.'); const next = await f.session(1); expect(next.message).toContain('failedCheck'); expect((await f.call(locator, 'member')).tasks[0]?.failedCheck).toEqual(failure); - await f.call({ operation: 'spawn', agentId: 'repair', message: 'Read the earlier failed interface: ' + JSON.stringify(locator) }); + await f.spawn('repair', 'Read the earlier failed interface: ' + JSON.stringify(locator)); await f.session(2); expect((await f.call(locator, 'repair')).tasks[0]?.failedCheck).toEqual(failure); expect(f.state.check).toBeUndefined(); }, 60_000); it('rejects a non-owned declaration file before nomination, and accepts a corrected submission on the same turn', async () => { - const f = fixture(); await f.call({ operation: 'spawn', agentId: 'member', message: 'Prove the helper.' }); + const f = fixture(); await f.spawn('member', 'Prove the helper.'); const session = await f.session(0), worker = f.team.archive.workers[0]!; expect(await f.call({ operation: 'submit', summary: 'Helper ready.', declarations: [ { ...declarations[0], file: `${f.problem.projectRelative}/Submission.lean` }] }, 'member')).toMatchObject({ @@ -251,7 +402,7 @@ describe('recoverable team source rejections', () => { it.each(['outside-ownership', 'original-declaration'] as const)( 'preserves a %s draft and notes, then permits an explicit same-member correction', async kind => { - const f = fixture(); await f.call({ operation: 'spawn', agentId: 'member', message: 'Prove the helper.' }); + const f = fixture(); await f.spawn('member', 'Prove the helper.'); const first = await f.session(0), worker = f.team.archive.workers[0]!, file = f.source(worker.worktree); const valid = original.replace('end Recovery', helper + 'end Recovery'); const invalid = kind === 'original-declaration' ? valid.replace('goal : True', 'goal : False') : valid; @@ -273,9 +424,9 @@ describe('recoverable team source rejections', () => { expect(git(worker.worktree, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit); if (kind === 'outside-ownership') expect(git(worker.worktree, ['diff', '--cached', '--name-only'])).toBe('Sketch.lean'); expect(f.team.archive.events.some(event => event.kind === 'failed' && event.text.includes('Lead can assign a correction'))).toBe(true); - await f.call({ operation: 'assign', agentId: 'member', message: 'Correct the rejected source and resubmit the helper.' }); + await f.followup('member', 'Correct the rejected source and resubmit the helper.'); const correction = await f.session(1); - expect(correction.options.threadId).toBe('source-recovery-member'); + expect(correction.options.threadId).toBe(worker.native!.threadId); expect(correction.message).toContain('Host rejected the edited source'); expect(correction.message).toContain(kind === 'outside-ownership' ? 'Sketch.lean' : 'math_original_declaration_changed'); expect(fs.readFileSync(file, 'utf8')).toBe(invalid); @@ -292,7 +443,7 @@ describe('recoverable team source rejections', () => { }, 60_000); it('clears a restored stopped-writer nomination without rewriting its invalid source or fabricating an artifact', async () => { - const f = fixture(); await f.call({ operation: 'spawn', agentId: 'member', message: 'Prove the helper.' }); + const f = fixture(); await f.spawn('member', 'Prove the helper.'); const first = await f.session(0), worker = f.team.archive.workers[0]!; first.complete(); await idle(f.team); await f.team.close(); fs.writeFileSync(f.source(worker.worktree), original.replace('goal : True', 'goal : False')); @@ -308,7 +459,7 @@ describe('recoverable team source rejections', () => { expect(saved.agentTeam!.researchArtifacts ?? []).toHaveLength(artifactCount); expect(saved.agentTeam!.deliveries).toHaveLength(0); expect(fs.readFileSync(f.source(recoveredWorker.worktree), 'utf8')).toContain('goal : False'); expect(fs.readFileSync(path.join(recoveredWorker.worktree, 'RESEARCH.md'), 'utf8')).toContain('previous process stopped'); - await f.call({ operation: 'assign', agentId: 'member', message: 'Repair the statement and prove the helper.' }, 'lead', restored); + await f.followup('member', 'Repair the statement and prove the helper.', restored); const correction = await f.session(1); expect(correction.message).toContain('math_original_declaration_changed'); fs.writeFileSync(f.source(recoveredWorker.worktree), original.replace('end Recovery', helper + 'end Recovery')); expect(await f.call({ operation: 'submit', summary: 'Recovered and repaired.', declarations }, 'member', restored)).toMatchObject({ ok: true }); @@ -317,7 +468,7 @@ describe('recoverable team source rejections', () => { }, 60_000); it('retains a nomination on an unrelated infrastructure failure', async () => { - const f = fixture(); await f.call({ operation: 'spawn', agentId: 'member', message: 'Prove the helper.' }); + 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('end Recovery', helper + 'end Recovery')); expect(await f.call({ operation: 'submit', summary: 'Helper ready.', declarations }, 'member')).toMatchObject({ ok: true }); @@ -332,17 +483,17 @@ describe('recoverable team source rejections', () => { }); it('resumes the exact acknowledged nomination after writer loss but honors an explicit cancellation', async () => { - const f = fixture(); await f.call({ operation: 'spawn', agentId: 'member', message: 'Investigate.' }); + const f = fixture(); await f.spawn('member', 'Route: test-route\nInvestigate.'); await f.session(0); const worker = f.team.archive.workers[0]!, task = worker.tasks[0]!; const message = 'Prove the helper.'; - expect(await f.call({ operation: 'amend', agentId: worker.id, taskId: task.id, message, - workKind: 'proof', reason: 'The interface is ready.' })).toMatchObject({ ok: true }); + await f.followup(worker.id, message); fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery')); const reply = await f.call({ operation: 'submit', summary: 'Ready to check.', objectiveRevision: 2, declarations }, 'member'); expect(reply).toMatchObject({ status: 'pending-writer-stop' }); const beforeCancel = readSolverRunState(f.stateFile); - expect(await f.call({ operation: 'cancel', agentId: worker.id, taskId: task.id })).toMatchObject({ ok: true }); + expect(await f.call({ operation: 'retire_route', routeId: 'test-route', reason: 'This route is ruled out.', + evidenceRefs: ['RESEARCH.md'] })).toMatchObject({ ok: true, cancelledTaskIds: [task.id] }); await idle(f.team); expect(f.team.archive.deliveries).toHaveLength(0); const cancelled = f.makeTeam(readSolverRunState(f.stateFile)); @@ -363,10 +514,11 @@ describe('recoverable team source rejections', () => { expect(readAgentTeamProofDelivery(exact.archive.deliveries[0]!.path, legacy).provenance).not.toHaveProperty('objectiveRevision'); const recovered = f.makeTeam(beforeCancel); await recovered.restore(); - expect(recovered.archive.workers[0]!.tasks[0]!.status).toBe('interrupted'); + const recoveredTask = recovered.archive.workers[0]!.tasks[0]!; + expect(recoveredTask.status, recoveredTask.error).toBe('interrupted'); expect(recovered.archive.deliveries).toHaveLength(1); expect(readAgentTeamProofDelivery(recovered.archive.deliveries[0]!.path, beforeCancel).provenance) - .toMatchObject({ taskId: task.id, objectiveRevision: 2, objectiveDigest: mathDigest(message), workKind: 'proof' }); + .toMatchObject({ taskId: task.id, objectiveRevision: 2, objectiveDigest: mathDigest(message) }); expect(f.sessions).toHaveLength(1); }, 60_000); }); diff --git a/tests/agentTeamTool.test.ts b/tests/agentTeamTool.test.ts index 3cbb8d48..c1cc9aa7 100644 --- a/tests/agentTeamTool.test.ts +++ b/tests/agentTeamTool.test.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { bootstrapLeanTask } from '../src/math/leanTask'; import { MathAgentToolDispatcher } from '../src/runtime/agentTeamTools'; import { AgentResearchTeam } from '../src/solver/agentTeam'; @@ -27,9 +27,8 @@ function fixture(actor = 'member') { const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); const state = solverState(problem, receipt.workspaceRoot, { runId: 'tool-contract', phase: 'running', researchMode: 'skill', researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { schema: 'theorem-os.agent-team.v1', workers: ['member', 'peer'].map(id => ({ id, role: 'researcher' as const, - worktree: path.join(directory, id), phase: 'prepared' as const, status: 'idle' as const, turns: 0, - seedCommit: problem.baseCommit, tasks: [], cursor: 0 })), events: [], deliveries: [], adoptions: [], operations: [] } }); + agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', + workers: [], events: [], deliveries: [], adoptions: [], operations: [] } }); const team = new AgentResearchTeam({ state, root: process.cwd(), taskText: 'Offline tool contract fixture.', leadAccess: { environment: {}, retrievalRoot: receipt.workspaceRoot }, modules: directSolverModules, executable: 'offline-no-model', profile: 'offline-no-credentials', signal: new AbortController().signal, @@ -49,139 +48,68 @@ function fixture(actor = 'member') { return { team, ...client(actor), client, state }; } -function branch(actor: string, finite: boolean, operation: string): Json { - const definition = agentTeamToolDefinition(actor, finite); +function branch(actor: string, operation: string): Json { + const definition = agentTeamToolDefinition(actor); const schema = (definition.inputSchema.oneOf as Json[]).find(item => item.properties.operation.enum[0] === operation); if (!schema) throw new Error('Missing advertised operation: ' + operation); return schema; } -describe('operation-specific team tool contracts', () => { - it('advertises message recipients and submit identity binding separately', () => { - expect(branch('member', false, 'message')).toMatchObject({ - required: ['operation', 'agentId', 'message'], additionalProperties: false, +describe('mathematical team tool contracts', () => { + it('advertises role-specific math operations and the optional Lead plan gate', () => { + const child = agentTeamToolDefinition('member'); + const lead = agentTeamToolDefinition('lead'); + const approval = agentTeamToolDefinition('lead', true); + expect((child.inputSchema.properties.operation as Json).enum).toEqual([ + 'yield', 'history', 'inspect', 'inspect-research', 'submit', 'route_summary', + ]); + expect((lead.inputSchema.properties.operation as Json).enum).toEqual([ + 'finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary', + ]); + expect((approval.inputSchema.properties.operation as Json).enum).toContain('publish_plan'); + expect((agentTeamToolDefinition('member', true).inputSchema.properties.operation as Json).enum).not.toContain('publish_plan'); + expect(branch('member', 'submit')).toMatchObject({ required: ['operation', 'summary', 'declarations'], additionalProperties: false, + properties: { declarations: { items: { required: ['file', 'name', 'type'], additionalProperties: false } } }, }); - const submit = branch('member', false, 'submit'); - expect(submit.required).toEqual(['operation', 'summary', 'declarations']); - expect(submit.properties).not.toHaveProperty('agentId'); - expect(submit.properties.declarations.items).toMatchObject({ - required: ['file', 'name', 'type'], additionalProperties: false, - }); - expect(branch('member', false, 'wait').required).toEqual(['operation', 'after']); - expect(branch('member', false, 'history').properties.limit.maximum).toBe(8); - expect(branch('member', false, 'inspect-research').properties.limit.maximum).toBe(16000); - for (const actor of ['lead', 'member']) { - const description = agentTeamToolDefinition(actor, false).description; - expect(description).toContain(`the host fixes the sender as "${actor}"; agentId names the recipient`); - expect(description).toContain('Self-addressed messages are rejected.'); - } - expect(agentTeamToolDefinition('member', false).description).toContain('To report to Lead use agentId: "lead"'); - }); - - it('keeps role and configured allowance capabilities out of unavailable operation branches', () => { - const member = agentTeamToolDefinition('member', false).inputSchema as Json; - expect(member.properties.operation.enum).not.toContain('coordinate'); - expect(member.properties.operation.enum).not.toContain('spawn'); - expect(member.properties).not.toHaveProperty('decision'); - expect(member.properties).not.toHaveProperty('budget'); - const unlimited = agentTeamToolDefinition('lead', false).inputSchema as Json; - expect(unlimited.properties.operation.enum).not.toContain('budget'); - expect(unlimited.properties).not.toHaveProperty('budget'); - expect(unlimited.properties).not.toHaveProperty('leadReserve'); - expect(unlimited).not.toHaveProperty('oneOf'); - const finite = agentTeamToolDefinition('lead', true); - expect(finite.inputSchema).not.toHaveProperty('oneOf'); - expect(finite.inputSchema.properties).toHaveProperty('budget'); + expect(branch('member', 'submit').properties).not.toHaveProperty('agentId'); + expect(branch('member', 'submit').properties).not.toHaveProperty('objectiveRevision'); + expect(branch('member', 'history').properties.limit.maximum).toBe(8); }); - it.each([false, true])('keeps coordinate off the Lead menu with finite budget = %s while accepting explicit legacy calls', async finite => { - const tool = agentTeamToolDefinition('lead', finite); - expect((tool.inputSchema as Json).properties.operation.enum).not.toContain('coordinate'); - expect(tool.inputSchema.properties).not.toHaveProperty('decision'); - expect(tool.description).not.toContain('coordinate'); - const invalid = agentTeamRequestSchema.safeParse({ operation: 'coordinate', decision: 'continue' }); - if (invalid.success) throw new Error('Incomplete legacy operation must remain invalid.'); - expect(agentTeamArgumentFeedback('lead', finite, { operation: 'coordinate' }, invalid.error).allowedOperations) - .not.toContain('coordinate'); - const f = fixture('lead'), note = { decision: 'continue', reason: 'Checked the interface.', nextStep: 'Explore the bound.' }; - const result = await f.call({ operation: 'coordinate', ...note }, 'legacy-coordinate'); - expect(result.value).toMatchObject({ ok: true, advisory: true }); - expect(f.state.agentTeam?.coordination).toMatchObject({ ...note, revision: 1 }); - }); - - it('returns the exact selected operation contract for a missing recipient or extra identity', () => { - for (const args of [{ operation: 'message', message: 'A useful finding.' }, - { operation: 'submit', agentId: 'member', summary: 'Saved helper.', - declarations: [{ file: 'Submission.lean', name: 'helper', type: 'True' }] }]) { - const parsed = agentTeamRequestSchema.safeParse(args); - expect(parsed.success).toBe(false); - if (parsed.success) throw new Error('The malformed request must be rejected.'); - const feedback = agentTeamArgumentFeedback('member', false, args, parsed.error); - expect(feedback).toMatchObject({ ok: false, error: 'math_team_arguments_invalid' }); - expect(feedback.contract).toEqual(branch('member', false, args.operation)); - expect(feedback.hint).toContain('other fields forbidden'); - } + it('returns the selected operation contract when a caller supplies another member identity', () => { + const args = { operation: 'submit', agentId: 'peer', summary: 'Saved helper.', + declarations: [{ file: 'Submission.lean', name: 'helper', type: 'True' }] }; + const parsed = agentTeamRequestSchema.safeParse(args); + if (parsed.success) throw new Error('The malformed request must be rejected.'); + expect(agentTeamArgumentFeedback('member', args, parsed.error)).toMatchObject({ + ok: false, error: 'math_team_arguments_invalid', contract: branch('member', 'submit'), + hint: expect.stringContaining('other fields forbidden'), + }); }); - it('delivers repair feedback through the real host dispatcher without performing a malformed call', async () => { + it('rejects removed collaboration commands and unauthorized math commands without mutating the journal', async () => { const f = fixture(); - const missingRecipient = await f.call({ operation: 'message', message: 'A useful finding.' }, 'missing-recipient'); - expect(missingRecipient.response.success).toBe(true); - expect(missingRecipient.value).toMatchObject({ ok: false, error: 'math_team_arguments_invalid', - contract: { required: ['operation', 'agentId', 'message'] } }); - const extraIdentity = await f.call({ operation: 'submit', agentId: 'member', summary: 'Saved helper.', - declarations: [{ file: 'Submission.lean', name: 'helper', type: 'True' }] }, 'extra-identity'); - expect(extraIdentity.value.contract.properties).not.toHaveProperty('agentId'); + for (const operation of ['spawn', 'assign', 'amend', 'cancel', 'coordinate', 'message', 'poll', 'wait', 'budget']) { + const result = await f.client('lead').call({ operation }, 'removed-' + operation); + expect(result.value).toMatchObject({ ok: false, error: 'math_team_arguments_invalid' }); + expect(result.value.allowedOperations).not.toContain(operation); + } + const adopt = await f.call({ operation: 'adopt', deliveryId: '0'.repeat(64) }, 'child-adopt'); + expect(adopt.value).toMatchObject({ ok: false, error: 'math_team_native_operation_required' }); expect(f.team.archive.events).toHaveLength(0); expect(f.team.archive.operations).toHaveLength(0); - expect(f.team.archive.workers[0]!.pendingDelivery).toBeUndefined(); }); - it('preserves bound caller identity and idempotent delivery after correcting the recipient', async () => { - const f = fixture(), args = { operation: 'message', agentId: 'lead', message: 'A useful finding.' }; - const first = await f.call(args, 'corrected-message'), duplicate = await f.call(args, 'corrected-message'); - expect(first.value).toMatchObject({ ok: true, from: 'member', to: 'lead', delivery: 'saved-inbox' }); + it('makes Lead finish replay-safe through the host dispatcher', async () => { + const f = fixture('lead'), args = { operation: 'finish', summary: 'The candidate is ready for checking.' }; + const first = await f.call(args, 'finish'), duplicate = await f.client('lead').call(args, 'finish'); + expect(first.value).toMatchObject({ ok: true, status: 'pending-writer-stop', originalProblemAcceptance: 'not-assessed' }); expect(duplicate.response).toEqual(first.response); - expect(f.team.archive.events).toHaveLength(1); - expect(f.team.archive.events[0]).toMatchObject({ from: 'member', to: 'lead', text: args.message }); + expect(f.team.archive.completionRequested?.summary).toBe(args.summary); expect(f.team.archive.operations).toHaveLength(1); - const changed = await f.dispatcher.call({ threadId: 'thread', turnId: 'turn', callId: 'corrected-message', - tool: 'theoremos_team', arguments: { ...args, message: 'Changed replay.' } }); + const changed = await f.client('lead').dispatcher.call({ threadId: 'thread', turnId: 'turn', callId: 'finish', + tool: 'theoremos_team', arguments: { ...args, summary: 'Changed replay.' } }); expect(changed).toMatchObject({ success: false }); - expect(f.team.archive.events).toHaveLength(1); - const unauthorized = await f.call({ operation: 'coordinate', decision: 'defer', reason: 'Not allowed.', nextStep: 'Research.' }, 'child-coordinate'); - expect(unauthorized.value).toMatchObject({ ok: false, error: 'math_team_lead_operation_required' }); + expect(f.team.archive.completionRequested?.summary).toBe(args.summary); }); - - it.each(['member', 'lead'])('rejects self-addressed messages from %s without saving or notifying an inbox', async actor => { - const f = fixture(actor), notify = vi.spyOn(f.team as any, 'notify'); - const args = { operation: 'message', agentId: actor, message: 'A useful finding.' }; - const rejected = await f.call(args, 'self-addressed'); - expect(rejected.response.success).toBe(true); - expect(rejected.value).toMatchObject({ ok: false, error: 'math_team_message_self_addressed', from: actor, to: actor }); - expect(rejected.value.hint).toContain('agentId names the recipient, not the sender'); - expect(rejected.value.hint).toContain(actor === 'lead' ? 'Use the intended team member ID.' : 'Use agentId: "lead"'); - const replay = await f.call(args, 'self-addressed'); - expect(replay.response).toEqual(rejected.response); - expect(f.team.archive.events).toHaveLength(0); - expect(notify).not.toHaveBeenCalled(); - expect(f.team.archive.operations).toHaveLength(1); - const recipient = actor === 'lead' ? 'member' : 'lead'; - const corrected = await f.call({ ...args, agentId: recipient }, 'corrected-recipient'); - expect(corrected.value).toMatchObject({ ok: true, from: actor, to: recipient, delivery: 'saved-inbox' }); - expect(f.team.archive.events).toHaveLength(1); - expect(notify).toHaveBeenCalledOnce(); - }); - - it.each([{ actor: 'member', recipient: 'peer' }, { actor: 'lead', recipient: 'member' }])( - 'delivers $actor messages only to the chosen $recipient inbox', async ({ actor, recipient }) => { - const f = fixture(actor), args = { operation: 'message', agentId: recipient, message: 'A usable interface.' }; - const sent = await f.call(args, 'routed-message'); - expect(sent.value).toMatchObject({ ok: true, from: actor, to: recipient, delivery: 'saved-inbox' }); - const received = await f.client(recipient).call({ operation: 'poll', after: 0 }, 'recipient-poll'); - expect(received.value.events).toEqual([expect.objectContaining({ from: actor, to: recipient, text: args.message })]); - const senderInbox = await f.call({ operation: 'poll', after: 0 }, 'sender-poll'); - expect(senderInbox.value.events).toEqual([]); - expect(f.team.archive.events).toHaveLength(1); - }); }); diff --git a/tests/agentTeamTransportFallback.test.ts b/tests/agentTeamTransportFallback.test.ts index fbbdb595..f4a00951 100644 --- a/tests/agentTeamTransportFallback.test.ts +++ b/tests/agentTeamTransportFallback.test.ts @@ -1,13 +1,17 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { LOCAL_EXAMPLE_PROOF } from '../src/math/localExample'; import { readMathAgentSkill } from '../src/runtime/codexSkills'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; +import { buildRunInspection, exportRunPlan } from '../src/solver/inspection'; +import { queuePlanApproval } from '../src/solver/humanEdit'; import { directSolverModules } from '../src/solver/modules'; -import { runResearchWorkers } from '../src/solver/research'; +import { publishNativeApprovalPlan } from '../src/solver/planApproval'; +import { runResearchLead } from '../src/solver/research'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { leadWorker, localExample, solverState } from './helpers/solver'; +import { localExample, solverState } from './helpers/solver'; vi.mock(import('../src/math/mathBuildManifest'), async original => ({ ...await original(), readMathBuildManifest: vi.fn() })); @@ -16,7 +20,9 @@ const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); function fixture(open: (options: MathAgentOptions, signal: AbortController) => Promise, - previous?: { turns: number; threadId: string }, maxTurns = (previous?.turns ?? 0) + 1) { + previous?: { turns: number; threadId: string }, maxTurns = (previous?.turns ?? 0) + 1, + settings?: { review?: true; setWaiting?: (waiting: boolean) => void; + remainingMs?: () => number; maxTotalTokens?: number }) { const { problem, workspace, directory } = localExample('agent-team-transport-'); roots.push(directory); const root = path.resolve('.'); @@ -26,10 +32,10 @@ function fixture(open: (options: MathAgentOptions, signal: AbortController) => P coordination: 'independent', workerCount: 1, researchDelegation: { mode: 'team', maxAgents: 3 }, agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [] }, - ...previous, + ...(settings?.review ? { planApproval: true } : {}), ...previous, }); const researchSkill = prepareResearchSkill(root, workspace, identity, problem); - const worker = leadWorker(problem, workspace), controller = new AbortController(); + const controller = new AbortController(); const stateFile = path.join(directory, 'state.json'); const emit = vi.fn(); const start = vi.fn((options: MathAgentOptions) => open(options, controller)); @@ -38,57 +44,43 @@ function fixture(open: (options: MathAgentOptions, signal: AbortController) => P verification: { schema: 'deepscientist.mathematics.verification-batch/v1' as const, status: 'failed' as const, sessionId: 'fixture', targetCommit: problem.baseCommit, results: [], events: [], startedAt: 0, checkedAt: 1, durationMs: 1 }, })); - const run = () => runResearchWorkers({ state, workers: [worker], - access: new Map([[worker.id, { environment: {}, researchSkill, retrievalRoot: directory }]]), + const run = () => runResearchLead({ state, + access: { environment: {}, researchSkill, retrievalRoot: directory }, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: start }, M2: { ...directSolverModules.M2, check }, M3: { ...directSolverModules.M3, retry: (...args) => { const retry = directSolverModules.M3.retry(...args); return retry && { ...retry, delayMs: 0 }; } } }, root, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the frozen targets.', executable: 'offline', profile: 'offline', signal: controller.signal, - deadline: Infinity, maxTurns, maxTurnMs: Infinity, maxTotalTokens: 0, + deadline: Infinity, maxTurns, maxTurnMs: Infinity, maxTotalTokens: settings?.maxTotalTokens ?? 0, + ...(settings?.setWaiting ? { executionBudget: { + remainingMs: settings.remainingMs ?? (() => Infinity), setWaiting: settings.setWaiting, + } } : {}), save: () => writeSolverRunState(stateFile, state), emit }); - return { run, state, stateFile, start, emit, controller }; + return { run, state, stateFile, start, emit, controller, check }; } const startupError = 'math_codex_rpc_failed:-32603:thread/start'; -describe('AgentResearchTeam startup transport fallback', () => { - it('keeps one turn, rebuilds Lead context, and persists the successful host-tools retry', async () => { - const close = vi.fn(async () => {}); - const repaired = vi.fn(async (_message, _id, _workspace, started) => { started('host-turn'); return 'completed'; }); +describe('AgentResearchTeam startup transport', () => { + it('surfaces a native startup failure without creating a host-tools team', async () => { const f = fixture(async options => { - if (options.nativeAgentControl) { - // A launch can fail after binding a partial native control record. - f.state.agentTeam!.nativeControl = { sessionId: 'failed', rootThreadId: 'partial', sequence: 0, mailbox: [] }; - throw new Error(startupError); - } - expect(readSolverRunState(f.stateFile).agentTeam).toMatchObject({ transport: 'host-tools' }); - return { threadId: 'host-lead', run: repaired, close, interrupt: async () => {}, - stopForFreeze: async () => ({ status: 'stopped' }) }; - }); - f.emit.mockImplementation((event) => { - if (event === 'team_transport_fallback') expect(readSolverRunState(f.stateFile)).toMatchObject({ - turns: 0, agentTeam: { transport: 'host-tools' }, - }); + expect(options.nativeAgentControl).toBeDefined(); + throw new Error(startupError); }); - await f.run(); - expect(f.start).toHaveBeenCalledTimes(2); - const [native, host] = f.start.mock.calls.map(([options]) => options); - expect(native.nativeAgentControl).toBeDefined(); - expect(native.instructions).toContain('native AgentControl'); - expect(host.nativeAgentControl).toBeUndefined(); - expect(host.instructions).toContain('Built-in spawn/fork is disabled'); - expect(JSON.stringify(host.tools!.definitions)).toContain('"spawn"'); - expect(repaired).toHaveBeenCalledOnce(); - expect(close).toHaveBeenCalled(); - const saved = readSolverRunState(f.stateFile); - expect(saved).toMatchObject({ turns: 1, threadId: 'host-lead', agentTeam: { transport: 'host-tools' } }); - expect(saved.agentTeam?.nativeControl).toBeUndefined(); - expect(f.emit.mock.calls.filter(([event]) => event === 'team_transport_fallback')).toEqual([ - ['team_transport_fallback', { from: 'native-agent-control', to: 'host-tools', - reason: 'math_codex_rpc_failed', error: startupError }], - ]); + await expect(f.run()).rejects.toThrow(startupError); + expect(f.start).toHaveBeenCalledOnce(); + expect(readSolverRunState(f.stateFile)).toMatchObject({ turns: 0, agentTeam: { transport: 'native-agent-control' } }); + expect(f.emit.mock.calls.map(([event]) => event)).not.toContain('team_transport_fallback'); + }); + + it('leaves saved host-tools teams readable without starting their writers', async () => { + const f = fixture(async () => { throw new Error('Historical teams must use their pinned revision.'); }); + f.state.agentTeam!.transport = 'host-tools'; + writeSolverRunState(f.stateFile, f.state); + await expect(f.run()).rejects.toThrow('math_legacy_collaboration_retired'); + expect(f.start).not.toHaveBeenCalled(); + expect(readSolverRunState(f.stateFile)).toMatchObject({ turns: 0, agentTeam: { transport: 'host-tools' } }); }); it.each(['abort', 'auth', 'auth-wrapped', 'prior-turn', 'shutdown-unconfirmed'] as const)('preserves transport on %s', async mode => { @@ -137,3 +129,149 @@ describe('native Lead recovery', () => { agentTeam: { nativeControl: { sessionId: threadId, rootThreadId: threadId } } }); }); }); + +describe('native Lead plan approval', () => { + it('stops the planning writer, waits for the exact version, then resumes the same thread', async () => { + const setWaiting = vi.fn(); + const retiredRoute = { routeId: 'structural-symmetry', retiredAt: 1, source: 'lead' as const, + reason: 'Counterexample in the member report.' }; + const close = vi.fn(async () => {}); + const stopForFreeze = vi.fn(async () => ({ status: 'stopped' as const })); + const f = fixture(async options => { + const planning = f.start.mock.calls.length === 1; + expect(options.threadId).toBe(planning ? undefined : 'native-plan-lead'); + expect(Boolean(options.readOnlyWorkspace)).toBe(planning); + expect(JSON.stringify(options.tools!.definitions)).toContain('publish_plan'); + return { threadId: 'native-plan-lead', close, interrupt: async () => {}, + stopForFreeze, + run: async (message, _id, workspace, started) => { + const turnId = planning ? 'plan-turn' : 'proof-turn'; + started(turnId); + if (!planning) { + expect(message).toContain('The human approved plan version'); + expect(message).toContain('Verify the available identity lemma.'); + expect(message).toContain('Check the identity.'); + const control = options.nativeAgentControl!; + const threadId = 'native-plan-lead'; + const connection = { request: vi.fn(), update: vi.fn(), input: vi.fn() }; + const callNative = (operation: string, payload: Record) => + control.request({ version: 1, sessionId: threadId, threadId, operation, operationId: operation, payload }, + connection, { signal: f.controller.signal }); + await callNative('attach', { threadId, sessionId: threadId }); + await expect(callNative('spawn', { + caller: threadId, + source: { subagent: { thread_spawn: { parent_thread_id: threadId, agent_path: '/root/prover' } } }, + bootstrap: { config: { model: f.state.model, reasoningEffort: f.state.effort } }, + input: { kind: 'message', mode: 'triggerTurn', + message: { kind: 'plaintext', text: 'Route: structural-symmetry\nCheck the remaining lemma.' } }, + })).rejects.toThrow('math_team_route_retired:structural-symmetry'); + expect(readSolverRunState(f.stateFile).agentTeam).toMatchObject({ retiredRoutes: [retiredRoute], workers: [] }); + fs.writeFileSync(path.join(workspace, f.state.problem.projectRelative, f.state.problem.ownedFiles[0]!), LOCAL_EXAMPLE_PROOF); + return 'completed'; + } + expect(message).toContain('This turn is for planning only'); + const context = { threadId: 'native-plan-lead', turnId, signal: f.controller.signal }; + const call = (callId: string, args: unknown) => options.tools!.call('theoremos_team', args, { ...context, callId }); + const goal = { theoremName: f.state.problem.targets[0]!.theoremName, objective: 'Use the left identity.' }; + expect(await call('incomplete', { operation: 'publish_plan', goals: [goal] })).toMatchObject({ + ok: false, error: expect.stringContaining('math_team_plan_targets_mismatch'), + }); + const goals = f.state.problem.targets.map(target => ({ theoremName: target.theoremName, objective: 'Check the identity.' })); + expect(await call('publish', { operation: 'publish_plan', goals, investigations: ['Verify the available identity lemma.'] })) + .toMatchObject({ ok: true, status: 'pending', planVersion: expect.any(String) }); + expect(options.requestGate?.checkpoint?.()).toBe(true); + expect(await call('finish-blocked', { operation: 'finish', summary: 'done' })).toMatchObject({ + ok: false, error: expect.stringContaining('math_team_plan_approval_required'), + }); + return 'checkpoint'; + } }; + }, undefined, 2, { review: true, setWaiting }); + f.state.agentTeam!.retiredRoutes = [retiredRoute]; + const running = f.run(); + await vi.waitFor(() => expect(setWaiting).toHaveBeenCalledWith(true)); + expect(stopForFreeze).toHaveBeenCalledOnce(); + expect(stopForFreeze.mock.invocationCallOrder[0]).toBeLessThan(setWaiting.mock.invocationCallOrder[0]!); + expect(close).toHaveBeenCalledOnce(); + expect(f.start).toHaveBeenCalledOnce(); + expect(f.check).not.toHaveBeenCalled(); + const pending = readSolverRunState(f.stateFile); + const plan = exportRunPlan(pending); + expect(plan.tasks.map(task => task.kind)).toEqual(['goal', 'goal', 'research']); + expect(buildRunInspection(pending).planApproval).toMatchObject({ status: 'pending', planVersion: plan.baseVersion }); + await expect(queuePlanApproval(f.stateFile, { id: 'stale', planVersion: 'other-version' })) + .rejects.toThrow('math_plan_approval_version_conflict'); + expect(f.start).toHaveBeenCalledOnce(); + await queuePlanApproval(f.stateFile, { id: 'approval', planVersion: plan.baseVersion }); + await running; + expect(setWaiting.mock.calls).toEqual([[true], [false]]); + expect(f.start).toHaveBeenCalledTimes(2); + expect(stopForFreeze).toHaveBeenCalledTimes(2); + expect(f.check).toHaveBeenCalledOnce(); + expect(stopForFreeze.mock.invocationCallOrder[1]).toBeLessThan(f.check.mock.invocationCallOrder[0]!); + expect(buildRunInspection(readSolverRunState(f.stateFile)).planApproval).toMatchObject({ + status: 'approved', approvedId: 'approval', approvedVersion: plan.baseVersion, + }); + }); + + function saveStoppedPlan(f: ReturnType) { + f.state.phase = 'finished'; + const goals = f.state.problem.targets.map(target => ({ theoremName: target.theoremName, objective: 'Check the identity.' })); + const { planVersion } = publishNativeApprovalPlan(f.state, { operation: 'publish_plan', goals }, + () => writeSolverRunState(f.stateFile, f.state), f.emit); + return planVersion; + } + + it('reopens a stopped approval wait without starting a second planning turn', async () => { + const stoppedThread = 'saved-planning-thread'; + const setWaiting = vi.fn(); + const f = fixture(async options => { + expect(options.threadId).toBe(stoppedThread); + expect(options.readOnlyWorkspace).toBeUndefined(); + return { threadId: stoppedThread, close: async () => {}, interrupt: async () => {}, + stopForFreeze: async () => ({ status: 'stopped' }), + run: async (message, _id, _workspace, started) => { + expect(message).toContain('The human approved plan version'); + started('proof-turn'); return 'completed'; + } }; + }, { turns: 1, threadId: stoppedThread }, 2, { review: true, setWaiting }); + const planVersion = saveStoppedPlan(f); + await expect(queuePlanApproval(f.stateFile, { id: 'before-resume', planVersion })) + .rejects.toThrow('math_plan_approval_run_inactive'); + const running = f.run(); + let approvalQueued = false; + try { + await vi.waitFor(() => expect(setWaiting).toHaveBeenCalledWith(true)); + expect(f.start).not.toHaveBeenCalled(); + const receipt = await queuePlanApproval(f.stateFile, { id: 'after-resume', planVersion }); + approvalQueued = true; + expect(receipt).toMatchObject({ status: 'queued' }); + } finally { + if (!approvalQueued) { + f.controller.abort(); + await running.catch(() => {}); + } + } + await running; + expect(f.start).toHaveBeenCalledOnce(); + expect(buildRunInspection(readSolverRunState(f.stateFile)).planApproval) + .toMatchObject({ status: 'approved', approvedVersion: planVersion }); + }); + + it.each(['turns', 'tokens', 'time'])('settles a pending plan with no %s allowance', async limit => { + const setWaiting = vi.fn(() => f.controller.abort(new Error('unexpected wait behind exhausted budget'))); + const f = fixture(async () => { throw new Error('unexpected model dispatch'); }, + { turns: 1, threadId: 'saved-planning-thread' }, limit === 'turns' ? 1 : 2, { + review: true, setWaiting, maxTotalTokens: limit === 'tokens' ? 100 : undefined, + remainingMs: () => limit === 'time' ? 0 : Infinity, + }); + if (limit === 'tokens') { + f.state.usage = { totalTokens: 100 }; + f.state.usageAccounting = { startedTurns: 1, reportedTurns: 1, pending: false, incomplete: false }; + } + const planVersion = saveStoppedPlan(f); + await expect(f.run()).resolves.toBeUndefined(); + expect(f.emit).toHaveBeenCalledWith('plan_approval_unanswered', expect.objectContaining({ planVersion })); + expect(setWaiting).not.toHaveBeenCalled(); + expect(f.start).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/agentTools.test.ts b/tests/agentTools.test.ts index f010cbea..2c0efaa2 100644 --- a/tests/agentTools.test.ts +++ b/tests/agentTools.test.ts @@ -11,7 +11,7 @@ import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; import { readSolverProblem } from '../src/solver/problem'; const commands = ['check-finite', 'check-lean', 'continuation', 'declarations', 'hub', 'kernel-certificate', 'knowledge', 'library', - 'checkpoint', 'plan-apply', 'plan-validate', 'proof-search', 'research-observe', 'search-lean']; + 'checkpoint', 'plan-validate', 'search-lean']; const fixture = path.resolve('examples/finite/old-b1-nine-constraints.json'); let directory = ''; let tools = ''; diff --git a/tests/campaignLibraryNative.test.ts b/tests/campaignLibraryNative.test.ts index 2fe3c539..48c80f1e 100644 --- a/tests/campaignLibraryNative.test.ts +++ b/tests/campaignLibraryNative.test.ts @@ -16,12 +16,12 @@ import { newestLeanBinary } from './helpers/lean'; import { solverState } from './helpers/solver'; // The release build independently verifies the build manifest; this test keeps real preparation, library checks and continuation revalidation. -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); +vi.mock(import('../src/math/mathBuildManifest'), async original => ({ ...await original(), readMathBuildManifest: vi.fn() })); const lean = newestLeanBinary(), roots: string[] = []; afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); roots.splice(0).forEach(root => fs.rmSync(root, { recursive: true, force: true })); }); describe('campaign library native continuation', () => { - it.skipIf(!lean)('prepares the requested closure and replays the old graph through the real frozen solver initialization', async () => { + it.skipIf(!lean)('prepares the requested closure and continues from an archived graph without restoring the old scheduler', async () => { // An explicit output directory retains this disposable fixture for cross-language controller checks. const artifacts = process.env.THEOREMOS_CAMPAIGN_LIBRARY_NATIVE_ARTIFACTS; if (artifacts) fs.mkdirSync(artifacts, { recursive: true, mode: 0o700 }); @@ -31,7 +31,7 @@ describe('campaign library native continuation', () => { fs.writeFileSync(envFile, `ELAN_HOME=${path.join(os.homedir(), '.elan')}\nPATH=${path.dirname(lean!)}:/usr/bin:/bin:/usr/sbin\n`); vi.stubEnv('DEEPSCIENTIST_MATH_ENV_FILE', envFile); vi.stubEnv('ELAN_HOME', path.join(os.homedir(), '.elan')); vi.stubEnv('DEEPSCIENTIST_MATH_SANDBOX_BACKEND', 'bwrap'); vi.stubEnv('DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS', ''); - vi.stubEnv('CODEX_HOME', path.join(root, 'unused-profile')); vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.stubEnv('CODEX_HOME', path.join(root, 'unused-profile')); const logs = vi.spyOn(console, 'log').mockImplementation(() => {}); const taskDirectory = path.join(root, 'tasks/Native'); fs.mkdirSync(taskDirectory, { recursive: true, mode: 0o700 }); const source = 'namespace Original\ntheorem goal (n : Nat) : n + 0 = n := by sorry\nend Original\n'; const receipt = bootstrapLeanTask(path.join(taskDirectory, 'workspace'), { source, task: 'Prove the unchanged target.' }); @@ -66,15 +66,15 @@ describe('campaign library native continuation', () => { sourceTaskFile: taskFile, catalog: access, prepared: next }); const open = vi.fn(async () => { throw new Error('A startup-only library transition must not contact a model'); }); const exit = await runSolver(['--workspace', next.workspace, '--receipt-file', next.activeProblemPath, '--task-file', next.taskFile, - '--output', next.output, '--build-manifest', build, '--workers', '2', '--coordination', 'cooperative', + '--output', next.output, '--build-manifest', build, '--workers', '1', '--research-mode', 'skill', '--library-catalog', access.file, '--library-catalog-sha256', access.digest, '--continuation-source-run', oldOutput, '--startup-only', '--no-explanations', '--prepare-timeout-seconds', '60', - '--evaluator-timeout-seconds', '30', '--proof-timeout-seconds', '30'], root, + '--evaluator-timeout-seconds', '30', '--proof-timeout-seconds', '30'], path.resolve('.'), { ...directSolverModules, M1: { ...directSolverModules.M1, open } }); - expect(exit, JSON.stringify(readMathJson(next.output), null, 2)).toBe(0); expect(open).not.toHaveBeenCalled(); + expect(exit, logs.mock.calls.flat().join("\n")).toBe(0); expect(open).not.toHaveBeenCalled(); const newState = readSolverRunState(next.output + '.runtime/state.json'); expect(newState.phase).toBe('prepared'); expect(newState.turns).toBe(0); - expect(newState.cooperation?.tasks.find(node => node.task.id === 'goal')?.task).toMatchObject(task); + expect(newState.cooperation).toBeUndefined(); expect(newState.problem.targets).toEqual(problem.targets); expect(newState.problem.frozenFiles?.[file]).toBe(mathDigest(moduleSource)); const seedReport = readMathJson(next.output + '.runtime/continuation-seed.json') as { stage: string }; diff --git a/tests/certificateSlots.test.ts b/tests/certificateSlots.test.ts index 2582113a..d129d055 100644 --- a/tests/certificateSlots.test.ts +++ b/tests/certificateSlots.test.ts @@ -16,7 +16,7 @@ import { buildResearchContext } from '../src/solver/modules/context'; import { taskVersion } from '../src/solver/tasks'; import { assertSolverSources, commitSolverSources, committedSource, git, readSolverProblem, solverProofImports, type SolverProblem } from '../src/solver/problem'; -import type { CooperativeTask } from '../src/solver/cooperation'; +import type { CooperativeTask } from '../src/solver/tasks'; import { temporaryDirectory } from './helpers/files'; import { newestLeanBinary } from './helpers/lean'; diff --git a/tests/chatSessionWorkspace.test.ts b/tests/chatSessionWorkspace.test.ts index 1053c9ad..e5c0cda2 100644 --- a/tests/chatSessionWorkspace.test.ts +++ b/tests/chatSessionWorkspace.test.ts @@ -25,6 +25,7 @@ function fixture(state: 'formalizing' | 'proving' = 'proving', wide = true) { conversation: { messages: [] }, currentId: 'chat-a', draft: '', references: [], formalizations: [], summaries: [], unsavedDrafts: new Set(), liveShown: new Set(), liveSelected: new Map(), submissionIdentity: { unresolved: false }, guidanceFeedback: { runId: '', records: [] }, + withdrawing: new Set(), withdrawalNotes: new Map(), options: { session: () => undefined, runs: () => [], keyRequired: () => false, onArtifact }, answers: { sync: vi.fn() }, reading: { rendered: vi.fn(), capture }, refreshGuidanceFeedback: vi.fn(), solve: () => ({ process, wide }), diff --git a/tests/claudeCodeSession.test.ts b/tests/claudeCodeSession.test.ts index 09a242e5..5171a891 100644 --- a/tests/claudeCodeSession.test.ts +++ b/tests/claudeCodeSession.test.ts @@ -223,7 +223,6 @@ describe('Claude Code stream-json adapter without provider calls', () => { }); it('rejects unsupported responsibility contracts before starting a native process', async () => { - await expect(open({ ...options, delegation: { mode: 'read-only', maxAgents: 2 } })).rejects.toThrow('math_claude_delegation_unsupported'); await expect(open({ ...options, readIsolation: { environment: 'standard' } })).rejects.toThrow('math_sealed_provider_credential_unavailable'); await expect(open({ ...options, skills: [{ name: 'fixture', path: '/never/SKILL.md', digest: 'a'.repeat(64), loading: 'native' }] })) .rejects.toThrow('math_claude_native_skill_loading_unsupported'); diff --git a/tests/cliSession.test.ts b/tests/cliSession.test.ts index 7bc092b6..cb88c705 100644 --- a/tests/cliSession.test.ts +++ b/tests/cliSession.test.ts @@ -319,7 +319,6 @@ describe('configured headless CLI sessions with isolated local children', () => it('rejects unsupported responsibility contracts and effort before launching a process', async () => { await expect(open({ ...options, readIsolation: { environment: 'standard' } })).rejects.toThrow('math_cli_sealed_role_configuration_required'); - await expect(open({ ...options, delegation: { mode: 'read-only', maxAgents: 2 } })).rejects.toThrow('math_cli_delegation_unsupported'); await expect(open({ ...options, outputSchema: {} })).rejects.toThrow('math_cli_output_schema_unsupported'); await expect(open({ ...options, skills: [{ name: 'fixture', path: '/never/SKILL.md', digest: 'a'.repeat(64), loading: 'native' }] })) .rejects.toThrow('math_cli_requires_file_skill'); diff --git a/tests/codexSession.test.ts b/tests/codexSession.test.ts index e28a1ae9..bfc04115 100644 --- a/tests/codexSession.test.ts +++ b/tests/codexSession.test.ts @@ -401,6 +401,8 @@ readline.createInterface({ input: process.stdin }).on('line', line => { }); const start = calls.find(call => call.method === 'thread/start').params; expect(start.config.allow_login_shell).toBe(false); + expect(start).not.toHaveProperty('dynamicTools'); + expect(calls.some(call => call.method.startsWith('theoremos/agentControl/'))).toBe(false); expect(start.developerInstructions).toContain(options.instructions); expect(start.developerInstructions).toContain('"login": false'); expect(start.config.mcp_servers.unrelated).toEqual({ enabled: false }); diff --git a/tests/codexSessionAgentControl.test.ts b/tests/codexSessionAgentControl.test.ts index 6c3bbeb7..1af6450c 100644 --- a/tests/codexSessionAgentControl.test.ts +++ b/tests/codexSessionAgentControl.test.ts @@ -13,13 +13,24 @@ const fixture = String.raw` const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'); const directory = process.env.CODEX_HOME; const send = value => process.stdout.write(JSON.stringify(value) + '\n'); -let start, settings, threadId, counter = 0; +let start, settings, threadId, counter = 0, planningTurn; const host = (operation, id, extra = {}) => send({id,method:'theoremos/agentControl/request',params:{version:1, sessionId:'root-id',threadId,operationId:'operation-'+id,operation,payload:{threadId,sessionId:'root-id',...extra}}}); readline.createInterface({input:process.stdin}).on('line', line => { const call = JSON.parse(line); fs.appendFileSync(path.join(directory,'calls.jsonl'), JSON.stringify(call)+'\n'); const reply = result => send({id:call.id,result}); + if (call.id === 'invalid-plan-tool') { + send({method:'item/completed',params:{threadId,turnId:planningTurn.id,item:{id:'invalid',type:'dynamicToolCall', + tool:'theoremos_team',arguments:null,success:call.result.success}}}); + return send({id:'plan-tool',method:'item/tool/call',params:{threadId,turnId:planningTurn.id, + tool:'theoremos_team',callId:'publish',arguments:{operation:'publish_plan'}}}); + } + if (call.id === 'plan-tool') { + send({method:'item/completed',params:{threadId,turnId:planningTurn.id,item:{id:'publish',type:'dynamicToolCall', + tool:'theoremos_team',arguments:{operation:'publish_plan'},success:call.result.success}}}); + return; + } if (call.id === 'attach') { fs.writeFileSync(path.join(directory,'attach.json'), JSON.stringify(call)); const turns = process.env.LONG_RESUME_HISTORY && !settings.excludeTurns @@ -57,6 +68,12 @@ readline.createInterface({input:process.stdin}).on('line', line => { const turn = {id:'native-turn-'+ ++counter,status:'inProgress'}; const native = process.env.THEOREMOS_HOST_AGENT_CONTROL === '1'; if (native) host('admitTurn','admit-'+counter,{turnId:turn.id}); + if (process.env.PLAN_TOOL_FIXTURE) { + planningTurn = turn; + reply({threadId,submissionId:turn.id,turn,accepted:true}); + return send({id:'invalid-plan-tool',method:'item/tool/call',params:{threadId,turnId:turn.id, + tool:'theoremos_team',callId:'invalid',arguments:null}}); + } if (process.env.HOLD_HOST_CALLBACK) host('recordUsage','usage'); send({method:'item/completed',params:{threadId,turnId:turn.id,item:{id:'answer',type:'agentMessage',text:'Research saved.'}}}); send({method:'turn/completed',params:{threadId,turn:{...turn,status:'completed'}}}); @@ -66,6 +83,11 @@ readline.createInterface({input:process.stdin}).on('line', line => { }); return reply({threadId,submissionId:turn.id,turn,accepted:true}); } + if (call.method === 'turn/interrupt' && planningTurn) { + reply({}); + send({method:'turn/completed',params:{threadId,turn:{...planningTurn,status:'interrupted'}}}); + return host('releaseTurn','release-plan',{turnId:planningTurn.id}); + } if (call.method === 'theoremos/agentControl/update') return reply({acceptedSequence:call.params.sequence}); }); `; @@ -90,6 +112,29 @@ describe('native AgentControl stdio integration without model calls', () => { fs.rmSync(directory, { recursive: true, force: true }); }); + it('allows a direct provider to correct invalid plan arguments before the successful checkpoint', async () => { + const workspace = path.join(directory, 'workspace'), profile = path.join(directory, 'profile'); + fs.mkdirSync(workspace); fs.mkdirSync(profile); + let published = false; + const requestGate: NonNullable = () => ({ allowed: true, settle: () => {} }); + requestGate.checkpoint = () => published; + session = await createCodexMathSession({ ...options, workspace, profile, isolateProcess: true, readOnlyWorkspace: true, + nativeAgentControl: host, requestGate, turnTimeoutMs: 5000, tools: { + definitions: [{ name: 'theoremos_team', description: 'Publish initial route', inputSchema: { type: 'object' } }], + call: async (_tool, args) => { + if (args === null) return { ok: false, error: 'Expected a plan object' }; + published = true; return { ok: true }; + }, + }, environment: { ...options.environment, PLAN_TOOL_FIXTURE: '1' } }); + expect(session.usageSource).toBe('native-thread-totals'); + expect(await session.run('Publish a plan.', 'task', workspace, () => {})).toBe('checkpoint'); + expect(published).toBe(true); + expect(await session.stopForFreeze!()).toMatchObject({ status: 'stopped' }); + const rpc = fs.readFileSync(path.join(profile, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + expect(rpc.find(call => call.id === 'invalid-plan-tool')?.result.success).toBe(true); + expect(rpc.findIndex(call => call.id === 'plan-tool')).toBeLessThan(rpc.findIndex(call => call.method === 'turn/interrupt')); + }); + it('dispatches factory attach before thread startup returns and enables actual native tools explicitly', async () => { session = await createCodexMathSession({ ...options, nativeAgentControl: host }); expect(host.request).toHaveBeenCalledWith(expect.objectContaining({ operation: 'attach', threadId: 'root-id', diff --git a/tests/commonResearchGuidance.test.ts b/tests/commonResearchGuidance.test.ts index b75b3154..d418c578 100644 --- a/tests/commonResearchGuidance.test.ts +++ b/tests/commonResearchGuidance.test.ts @@ -30,11 +30,6 @@ describe('common mathematical guidance across research strategies', () => { { mode: 'native default Lead', transport: 'native-agent-control', role: undefined, channel: 'native send_message' }, { mode: 'native Lead', transport: 'native-agent-control', role: 'lead', channel: 'native send_message' }, { mode: 'native member', transport: 'native-agent-control', role: 'worker', channel: 'native send_message' }, - { mode: 'historical default Lead', transport: 'host-tools', role: undefined, channel: 'theoremos_team message' }, - { mode: 'historical Lead', transport: 'host-tools', role: 'lead', channel: 'theoremos_team message' }, - { mode: 'historical member', transport: 'host-tools', role: 'worker', channel: 'theoremos_team progress' }, - { mode: 'saved Lead without transport', transport: undefined, role: undefined, channel: 'theoremos_team message' }, - { mode: 'saved member without transport', transport: undefined, role: 'worker', channel: 'theoremos_team progress' }, ] as const)('materializes a permitted result-sharing channel for $mode', ({ transport, role, channel }) => { const f = fixture(), objective = 'Profiles: prover\nInspect one saved Lean probe.'; f.state.researchMode = 'skill'; f.state.researchSkill = researchSkillIdentity(f.skill); @@ -50,16 +45,9 @@ describe('common mathematical guidance across research strategies', () => { const help = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); expect(help).toContain(`Share a useful probe result or blocker through ${channel}, with its saved source path and exact diagnostic`); expect(help).not.toContain('research-observe'); - if (transport === 'native-agent-control') { - expect(help).not.toContain('theoremos_team progress'); - expect(help).not.toContain('theoremos_team message'); - expect(agentTeamOperationAllowed(role === 'worker' ? 'member' : 'lead', false, transport, 'progress')).toBe(false); - } else { - const operation = role === 'worker' ? 'progress' : 'message'; - expect(agentTeamOperationAllowed(role === 'worker' ? 'member' : 'lead', false, transport ?? 'host-tools', operation)).toBe(true); - expect(help).not.toContain('native send_message'); - if (role !== 'worker') expect(help).not.toContain('theoremos_team progress'); - } + expect(help).not.toContain('theoremos_team progress'); + expect(help).not.toContain('theoremos_team message'); + expect(agentTeamOperationAllowed(role === 'worker' ? 'member' : 'lead', 'progress')).toBe(false); }); it('keeps standalone result retention independent of team-only tools', () => { diff --git a/tests/componentTemplate.test.ts b/tests/componentTemplate.test.ts index 7a3ea1ff..3382ff68 100644 --- a/tests/componentTemplate.test.ts +++ b/tests/componentTemplate.test.ts @@ -21,7 +21,17 @@ describe('search component starter', () => { expect(JSON.parse(probe.stdout).readyTasks).toEqual(['goal', 'research']); const help = spawnSync('bun', [files.entry, '--help'], { encoding: 'utf8', timeout: 20_000, maxBuffer: 8_000 }); expect(help.status, help.stderr).toBe(0); - expect(help.stdout).toContain('--workspace'); + expect(help.stdout).toContain("pinned historical TheoremOS revision"); + }); + it('keeps the generated and bundled component scripts from creating fresh host scheduling runs', () => { + const root = temp(), files = createSearchComponent(root, 'my-search'); + fs.symlinkSync(path.resolve('src/solver'), path.join(root, 'src/solver'), 'dir'); + for (const entry of [files.entry, path.resolve('scripts/mathematics/runGoalsFirst.ts')]) { + const result = spawnSync('bun', [entry, '--workers', '4', '--startup-only'], + { encoding: 'utf8', timeout: 20_000, maxBuffer: 8_000 }); + expect(result.status, result.stderr).toBe(1); + expect(result.stderr).toContain('math_legacy_collaboration_retired'); + } }); it('preserves an existing component or entry', () => { const root = temp(), files = createSearchComponent(root, 'my-search'); diff --git a/tests/consumerConnections.test.ts b/tests/consumerConnections.test.ts index 4eea7661..fa6a39af 100644 --- a/tests/consumerConnections.test.ts +++ b/tests/consumerConnections.test.ts @@ -5,7 +5,7 @@ import type { MathematicsVerifierBatchRequest, MathematicsVerifierBatchResult } import { maskLeanCommentsAndStrings } from '../src/math/leanSyntax'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; +import { parseCooperationPlan } from '../src/solver/tasks'; import { buildResearchContext } from '../src/solver/modules/context'; import type { ResearchWorker } from '../src/solver/modules/organization'; import { readyResearchTasks, taskCanStart } from '../src/solver/modules/search'; @@ -13,7 +13,6 @@ import { committedSource, commitSolverSources, git, readSolverProblem, type Solv import { automaticTaskConnection, createTaskConnectionCheck, freshTaskConnection, hasTaskConnectionCheck, taskConnectionCheckCurrent } from '../src/solver/taskConnections'; import { assignmentDeliveryFile, freshlyAccepted, taskVersion, type CooperativeAction, type CooperativeTask, type TaskAssignment, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; import { verifiedBatch } from './helpers/verifier'; import { conditionalPayloads } from './helpers/conditionalProjection'; @@ -158,339 +157,3 @@ describe('consumer connection dispatch', () => { expect(taskConnectionCheckCurrent(tasks[1].task, assignment, tasks, identity)).toBe(false); }); }); - -describe('host consumer connection lifecycle', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[], checkedSources: string[]; - type TaskAction = Extract; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - const sourcePath = (worker: ResearchWorker) => path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - const create = () => { - const controller = new AbortController(), cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, - signal: controller.signal }); - instances.push({ cooperative, controller }); return cooperative; - }; - const assigned = async (worker: ResearchWorker) => { - const action = await cooperative.next(worker, budget); - if (action?.kind !== 'task') throw new Error('fixture_missing_task'); - expect(cooperative.started(worker, action)).toBe(true); return action; - }; - const deliverConsumer = async () => { - const action = await assigned(workers[2]); expect(action.task.id).toBe('goal_0'); - fs.writeFileSync(sourcePath(workers[2]), fs.readFileSync(sourcePath(workers[2]), 'utf8') - .replace('n + 0 = n := by sorry', 'n + 0 = n := by\n have h : True := Tutorial.helper\n rfl')); - await cooperative.deliver(workers[2], action, commitSolverSources(problem, workers[2].worktree)); - return action; - }; - const deliverInput = async (action: TaskAction) => { - fs.writeFileSync(sourcePath(workers[1]), fs.readFileSync(sourcePath(workers[1]), 'utf8') - .replace('theorem add_zero', 'lemma helper : True := by trivial\ntheorem add_zero')); - await cooperative.deliver(workers[1], action, commitSolverSources(problem, workers[1].worktree)); - }; - - beforeEach(async () => { - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest): Promise => { - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); checkedSources.push(source); - const batch = verifiedBatch(request, { sessionId: 'connection-fixture' }); - return !/\b(?:sorry|admit)\b/u.test(source) ? batch - : { ...batch, status: 'failed', results: batch.results.map(item => ({ ...item, status: 'failed' })) }; - }); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('consumer-connection-'); - ({ directory, workspace, problem } = example); - workers = [leadWorker(problem, workspace, 'lead'), ...['researcher', 'engineer', 'observer'] - .map(id => peerWorker(example, id, { role: id === 'engineer' ? 'engineer' : 'researcher' }))]; - const tasks: CooperativeTask[] = [{ id: 'helper', kind: 'lemma', objective: 'Core input', type: 'True', - theoremName: 'Tutorial.helper', proofPath: 'Submission.lean', dependsOn: [], revision: 0, ownerId: 'researcher' }, - { id: 'independent', kind: 'research', objective: 'Independent useful investigation', dependsOn: [], revision: 0, ownerId: 'observer' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal' as const, objective: 'Prove the original goal', - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: index ? [] : ['helper'], revision: 0, - ownerId: 'engineer', status: index ? 'paused' as const : 'active' as const }))]; - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ tasks }) + '\n```'); - state = solverState(problem, workspace, { runId: 'connection-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, tasks: [] } }); - instances = []; checkedSources = []; cooperative = create(); await cooperative.restore(); - }); - afterEach(async () => { - for (const instance of instances) { instance.controller.abort(); await instance.cooperative.stop(); } - expect(host.createSession).not.toHaveBeenCalled(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('dispatches the consumer before any input proof, keeps independent work executable, and integrates only after the input closes', async () => { - const digest = taskVersion(node('goal_0').task), parent = await deliverConsumer(); - expect(parent.assignment.connectionCheck).toMatchObject({ consumer: { taskId: 'goal_0', taskDigest: digest }, - problemReceiptDigest: problem.receiptDigest, environmentDigest: 'environment' }); - expect(node('goal_0')).toMatchObject({ status: 'conditional', attempts: 1, proof: { passed: true, - conditions: [{ taskId: 'helper', taskDigest: taskVersion(node('helper').task) }] } }); - expect(node('goal_0').integratedCheck).toBeUndefined(); expect(state.cooperation!.review).toBeUndefined(); - expect(taskVersion(node('goal_0').task)).toBe(digest); expect(node('goal_0').task.conditional).toBeUndefined(); - expect(checkedSources.some(source => conditionalPayloads(source).some(payload => - payload.declaration.startsWith('theorem add_zero ') && payload.dependencies.some(dependency => - dependency.theoremName === 'Tutorial.helper' && dependency.type === 'True')))).toBe(true); - const independent = await assigned(workers[3]); expect(independent.task.id).toBe('independent'); - const context = buildResearchContext(problem, state, { root: directory, worktree: workers[2].worktree, taskText: 'Problem', - environment: {}, retrievalRoot: directory, assignment: parent, maxOptionalContextBytes: 0 }); - expect(context.instructions).toContain('host-dispatched consumer connection check'); - expect(context.workContract?.input).toHaveProperty('connectionCheck.basisDigest', parent.assignment.connectionCheck!.basisDigest); - await deliverInput(await assigned(workers[1])); - expect(node('goal_0')).toMatchObject({ status: 'integrated', attempts: 1, integratedCheck: { passed: true } }); - expect(node('goal_0').integratedCheck!.conditions).toBeUndefined(); - const canonical = committedSource(workspace, state.cooperation!.canonicalCommit!, `${problem.projectRelative}/Submission.lean`); - expect(canonical).toContain('lemma helper : True := by trivial'); expect(canonical).not.toContain('(helper : True)'); - }); - - const rejectForwardInputReferences = () => { - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); - // Host conditional payloads quote source and premise names; only unquoted Lean references can be forward references. - const code = maskLeanCommentsAndStrings(source); - const reference = code.indexOf('Tutorial.helper'), declaration = code.indexOf('lemma helper : True'); - const result = await verify(request); - return reference >= 0 && (declaration < 0 || declaration > reference) - ? { ...result, status: 'failed', results: result.results.map(item => ({ ...item, status: 'failed', - error: 'Lean exited with status 1.', - stdoutPreview: 'Submission.lean:5:4: error(lean.unknownIdentifier): Unknown identifier `Tutorial.helper`' })) } - : result; - }); - }; - - it.each(['snapshot', 'legacy', 'explicit'] as const)('keeps %s dispatch assumptions when the input integrates before the worker delivers its old source', async mode => { - rejectForwardInputReferences(); - const parentWorker = mode === 'explicit' ? workers[3] : workers[2]; - if (mode === 'explicit') { - const tasks = state.cooperation!.tasks.map(item => item.task.id === 'goal_0' ? { ...item.task, status: 'paused' as const } : item.task); - tasks.splice(tasks.findIndex(task => task.id === 'independent'), 1, { id: 'consumer', kind: 'lemma', conditional: true, - objective: 'An explicitly conditional helper without an active downstream consumer', type: 'True', - theoremName: 'Tutorial.consumer', proofPath: 'Submission.lean', dependsOn: ['helper'], revision: 0, ownerId: 'observer' }); - await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); - } - const parent = await assigned(parentWorker); - expect(parent.task.id).toBe(mode === 'explicit' ? 'consumer' : 'goal_0'); - if (mode === 'explicit') expect(parent.assignment.connectionCheck).toBeUndefined(); - if (mode === 'legacy') { - const { assumedInputs: _inputs, workerId: _worker, assignmentId: _assignment, basisDigest: _basis, ...legacy } = parent.assignment.connectionCheck!; - parent.assignment.connectionCheck = { ...legacy, basisDigest: mathDigest(canonicalMathJson(legacy)) }; - } - const source = fs.readFileSync(sourcePath(parentWorker), 'utf8'); - fs.writeFileSync(sourcePath(parentWorker), mode === 'explicit' - ? source.replace('theorem add_zero', 'lemma consumer : True := by exact Tutorial.helper\ntheorem add_zero') - : source.replace('n + 0 = n := by sorry', 'n + 0 = n := by\n have h : True := Tutorial.helper\n rfl')); - const commit = commitSolverSources(problem, parentWorker.worktree); - expect(committedSource(workspace, commit, `${problem.projectRelative}/Submission.lean`)).not.toContain('lemma helper'); - await deliverInput(await assigned(workers[1])); - expect(node('helper').status).toBe('integrated'); - await cooperative.deliver(parentWorker, parent, commit); - const consumer = node(parent.task.id); - expect(consumer.status).toBe('integrated'); - expect(consumer.proof!.conditions).toEqual([{ taskId: 'helper', taskDigest: taskVersion(node('helper').task) }]); - expect(consumer.integratedCheck!.conditions ?? []).toEqual([]); - expect(freshlyAccepted(consumer, taskVersion(consumer.task))).toBe(true); - expect(checkedSources.some(source => conditionalPayloads(source).some(payload => - payload.declaration.startsWith(mode === 'explicit' ? 'lemma consumer ' : 'theorem add_zero ') && - payload.dependencies.some(dependency => dependency.theoremName === 'Tutorial.helper' && dependency.type === 'True')))).toBe(true); - expect(checkedSources.at(-1)).toContain('lemma helper : True := by trivial'); - expect(checkedSources.at(-1)).not.toContain('(helper : True)'); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('checks an ordinary dispatch using its already integrated source without assumption binders', async () => { - rejectForwardInputReferences(); - await deliverInput(await assigned(workers[1])); - const parent = await deliverConsumer(); - expect(parent.assignment.connectionCheck).toBeUndefined(); - expect(node('goal_0').proof!.conditions).toBeUndefined(); - expect(node('goal_0').integratedCheck!.conditions).toBeUndefined(); - expect(checkedSources.every(source => conditionalPayloads(source).length === 0)).toBe(true); - }); - - it.each([ - ['automatic', 'compatible'], - ['explicit', 'compatible'], - ['automatic', 'conflicting'], - ] as const)('refreshes a saved %s connection with a %s draft when its exact input integrates', async (mode, draftKind) => { - const worker = mode === 'automatic' ? workers[2] : workers[3]; - if (mode === 'explicit') { - const tasks = state.cooperation!.tasks.map(item => item.task.id === 'goal_0' - ? { ...item.task, status: 'paused' as const } : item.task); - tasks.splice(tasks.findIndex(task => task.id === 'independent'), 1, { id: 'consumer', kind: 'lemma', conditional: true, - objective: 'Use the exact integrated prerequisite.', type: 'True', theoremName: 'Tutorial.consumer', - proofPath: 'Submission.lean', dependsOn: ['helper'], revision: 0, ownerId: worker.id }); - await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); - } - const parent = await assigned(worker), consumer = node(parent.task.id); - expect(consumer.task.id).toBe(mode === 'automatic' ? 'goal_0' : 'consumer'); - expect(Boolean(parent.assignment.connectionCheck)).toBe(mode === 'automatic'); - const threadId = 'saved-connection-thread'; - const record = { ...worker, phase: 'running' as const, turns: 1, threadId, sessionTaskId: parent.task.id, - sessionTaskVersion: parent.assignment.taskDigest, sessionAssignmentId: parent.assignment.assignmentId }; - state.workers = [...(state.workers ?? []).filter(item => item.id !== worker.id), record]; - const notes = 'Saved connection draft before the exact input integrated.\n'; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), notes); - const conflicting = draftKind === 'conflicting'; - const draftAnchor = conflicting ? 'theorem add_zero' : 'end Tutorial'; - const draftLemma = conflicting ? 'lemma helper : True := by exact True.intro' : 'lemma old_draft_support : True := by trivial'; - fs.writeFileSync(sourcePath(worker), fs.readFileSync(sourcePath(worker), 'utf8') - .replace(draftAnchor, `${draftLemma}\n${draftAnchor}`)); - const previousCommit = commitSolverSources(problem, worker.worktree); - await cooperative.retainContextDraft(worker, parent, previousCommit, 'connection'); - cooperative.interrupted(worker, parent); - const unchanged = await assigned(worker); - expect(unchanged.assignment).toBe(parent.assignment); - cooperative.interrupted(worker, unchanged); - - await deliverInput(await assigned(workers[1])); - expect(node('helper').status).toBe('integrated'); - expect(cooperative.current(parent)).toBe(true); - const current = await assigned(worker); - expect(current.assignment).toMatchObject({ workerId: worker.id, taskDigest: parent.assignment.taskDigest, - canonicalCommit: state.cooperation!.canonicalCommit }); - expect(current.assignment.connectionCheck).toBeUndefined(); - expect(assignmentDeliveryFile(current.assignment)).not.toBe(assignmentDeliveryFile(parent.assignment)); - expect(committedSource(workspace, current.assignment.seedCommit, 'RESEARCH.md')).toBe(notes); - const proofPath = `${problem.projectRelative}/Submission.lean`; - const seedSource = committedSource(workspace, current.assignment.seedCommit, proofPath); - expect(seedSource).toContain('lemma helper : True := by trivial'); - expect(seedSource).not.toContain(draftLemma); - const resumedSource = conflicting ? seedSource : seedSource.replace(draftAnchor, `${draftLemma}\n${draftAnchor}`); - expect(fs.readFileSync(sourcePath(worker), 'utf8')).toBe(resumedSource); - const restored = state.cooperation!.researchDrafts![parent.task.id]; - expect(restored).toMatchObject({ assignmentId: current.assignment.assignmentId, - seedCommit: current.assignment.seedCommit, workerId: worker.id }); - expect(committedSource(workspace, restored.commit, proofPath)).toBe(resumedSource); - if (conflicting) { - expect(committedSource(workspace, previousCommit, proofPath)).toContain(draftLemma); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ commit: previousCommit, status: 'advisory', - artifacts: expect.objectContaining({ artifacts: expect.arrayContaining([expect.objectContaining({ kind: 'owned-source' })]) }) })); - } - expect(state.workers.find(item => item.id === worker.id)?.threadId).toBe(threadId); - expect(cooperative.current(parent)).toBe(false); - const checkedBefore = checkedSources.length; - await cooperative.deliver(worker, parent, previousCommit); - expect(checkedSources).toHaveLength(checkedBefore); - expect(consumer).toMatchObject({ status: 'running', assignment: current.assignment }); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ commit: previousCommit, status: 'superseded' })); - - const source = fs.readFileSync(sourcePath(worker), 'utf8'); - fs.writeFileSync(sourcePath(worker), mode === 'automatic' - ? source.replace('n + 0 = n := by sorry', 'n + 0 = n := by\n have h : True := Tutorial.helper\n rfl') - : source.replace('theorem add_zero', 'lemma consumer : True := by exact Tutorial.helper\ntheorem add_zero')); - await cooperative.deliver(worker, current, commitSolverSources(problem, worker.worktree)); - expect(consumer.status).toBe('integrated'); - expect(consumer.proof!.conditions).toBeUndefined(); - expect(checkedSources.slice(checkedBefore).every(source => conditionalPayloads(source).length === 0)).toBe(true); - }); - - it('rebuilds a connection receipt with only the input still unproved', async () => { - const tasks = state.cooperation!.tasks.map(item => item.task.id === 'goal_0' - ? { ...item.task, dependsOn: ['helper', 'remaining_input'] } : item.task); - tasks.push({ id: 'remaining_input', kind: 'lemma', objective: 'Prove the other premise.', type: 'True', - theoremName: 'Tutorial.remaining_input', proofPath: 'Submission.lean', dependsOn: [], revision: 0, ownerId: 'observer' }); - await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); - const worker = workers[2], first = await assigned(worker); - expect(first.assignment.connectionCheck?.assumedInputs?.map(input => input.taskId)).toEqual(['helper', 'remaining_input']); - cooperative.interrupted(worker, first); - await deliverInput(await assigned(workers[1])); - const current = await assigned(worker); - expect(current.assignment.connectionCheck?.assumedInputs).toEqual([ - { taskId: 'remaining_input', taskDigest: taskVersion(node('remaining_input').task) }, - ]); - expect(current.assignment.assignmentId).not.toBe(first.assignment.assignmentId); - expect(cooperative.current(current)).toBe(true); - }); - - it.each(['goal', 'lemma'] as const)('discharges a conditional %s after a later input declaration and preserves added helper order', async kind => { - rejectForwardInputReferences(); - const tasks = state.cooperation!.tasks.map(item => item.task); - const parentWorker = kind === 'lemma' ? workers[3] : workers[2]; - if (kind === 'lemma') { - const goal = tasks.findIndex(task => task.id === 'goal_0'); - tasks[goal] = { ...tasks[goal], dependsOn: ['consumer'], conditional: false }; - tasks.splice(tasks.findIndex(task => task.id === 'independent'), 1, { id: 'consumer', kind: 'lemma', objective: 'Combine the input', type: 'True', - theoremName: 'Tutorial.consumer', proofPath: 'Submission.lean', dependsOn: ['helper'], revision: 0, ownerId: 'observer' }); - await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); - } - const parent = await assigned(parentWorker); - expect(parent.task.id).toBe(kind === 'goal' ? 'goal_0' : 'consumer'); - let source = fs.readFileSync(sourcePath(parentWorker), 'utf8'); - source = kind === 'goal' ? source.replace('n + 0 = n := by sorry', - 'n + 0 = n := by\n have h : True := Tutorial.helper\n rfl') : source.replace('theorem add_zero', - 'lemma support_a : True := by exact Tutorial.helper\nlemma support_b : True := by exact Tutorial.helper\n' + - 'lemma consumer : True := by exact Tutorial.helper\ntheorem add_zero'); - fs.writeFileSync(sourcePath(parentWorker), source); - await cooperative.deliver(parentWorker, parent, commitSolverSources(problem, parentWorker.worktree)); - expect(node(parent.task.id).status).toBe('conditional'); - const input = await assigned(workers[1]); - fs.writeFileSync(sourcePath(workers[1]), fs.readFileSync(sourcePath(workers[1]), 'utf8') - .replace('theorem zero_add', 'lemma helper : True := by trivial\ntheorem zero_add')); - await cooperative.deliver(workers[1], input, commitSolverSources(problem, workers[1].worktree)); - const consumer = node(parent.task.id); - expect(consumer.status).toBe('integrated'); - expect(consumer.integratedCheck!.conditions ?? []).toEqual([]); - expect(freshlyAccepted(consumer, taskVersion(consumer.task))).toBe(true); - const canonical = committedSource(workspace, state.cooperation!.canonicalCommit!, `${problem.projectRelative}/Submission.lean`); - const consumerName = kind === 'goal' ? 'theorem add_zero' : 'lemma consumer'; - expect(canonical.indexOf('lemma helper')).toBeLessThan(canonical.indexOf(consumerName)); - if (kind === 'lemma') { - expect(canonical.indexOf('lemma helper')).toBeLessThan(canonical.indexOf('lemma support_a')); - expect(canonical.indexOf('lemma support_a')).toBeLessThan(canonical.indexOf('lemma support_b')); - expect(canonical.indexOf('lemma support_b')).toBeLessThan(canonical.indexOf('lemma consumer')); - } - expect(canonical).not.toContain('(helper : True)'); - }); - - it('blocks a conditional reorder across a frozen option command without advancing canonical acceptance', async () => { - for (const instance of instances) { instance.controller.abort(); await instance.cooperative.stop(); } - const file = sourcePath(workers[0]); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem zero_add', 'set_option maxRecDepth 1000\ntheorem zero_add')); - git(workspace, ['add', '--', `${problem.projectRelative}/Submission.lean`]); - git(workspace, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--quiet', '--no-gpg-sign', '-m', 'Freeze a context barrier']); - problem = readSolverProblem(workspace, problem.activeProblemPath); - for (const worker of workers.slice(1)) git(worker.worktree, ['reset', '--hard', problem.baseCommit]); - state = solverState(problem, workspace, { runId: 'connection-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, tasks: [] } }); - instances = []; cooperative = create(); await cooperative.restore(); - rejectForwardInputReferences(); - await deliverConsumer(); - const input = await assigned(workers[1]); - fs.writeFileSync(sourcePath(workers[1]), fs.readFileSync(sourcePath(workers[1]), 'utf8') - .replace('theorem zero_add', 'lemma helper : True := by trivial\ntheorem zero_add')); - await cooperative.deliver(workers[1], input, commitSolverSources(problem, workers[1].worktree)); - expect(node('helper').status).toBe('integrated'); - expect(node('goal_0').status).toBe('blocked'); - expect(node('goal_0').feedback).toContain('math_task_integration_missing_context'); - expect(node('goal_0').feedback).not.toContain('math_verifier_unavailable'); - expect(state.cooperation!.canonicalCommit).toBe(node('helper').integratedCheck!.commit); - expect(freshlyAccepted(node('goal_0'), taskVersion(node('goal_0').task))).toBe(false); - const canonical = committedSource(workspace, state.cooperation!.canonicalCommit!, `${problem.projectRelative}/Submission.lean`); - expect(canonical).toContain('n + 0 = n := by sorry'); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('rechecks restored conditional receipts without another consumer dispatch or granting unproved inputs acceptance', async () => { - await deliverConsumer(); const proof = node('goal_0').proof!, previous = host.verify.mock.calls.length; - const snapshot = path.join(directory, 'state.json'); writeSolverRunState(snapshot, state); - for (const instance of instances) { instance.controller.abort(); await instance.cooperative.stop(); } - state = readSolverRunState(snapshot); cooperative = create(); await cooperative.restore(); - expect(node('goal_0').assignment!.connectionCheck!.assumedInputs).toEqual(node('goal_0').proof!.conditions); - expect(host.verify.mock.calls.length).toBeGreaterThan(previous); - expect(node('goal_0')).toMatchObject({ status: 'conditional', attempts: 1, proof: { commit: proof.commit } }); - expect(node('goal_0').integratedCheck).toBeUndefined(); - await deliverInput(await assigned(workers[1])); - expect(node('goal_0')).toMatchObject({ status: 'integrated', attempts: 1 }); - }); - - it('offers a fresh connection when the core contract changes and excludes the old late delivery', async () => { - const old = await deliverConsumer(), oldBasis = old.assignment.connectionCheck!.basisDigest; - const tasks = state.cooperation!.tasks.map(node => node.task.id === 'helper' ? { ...node.task, type: 'True ∧ True' } : node.task); - await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); - expect(cooperative.current(old)).toBe(false); - expect(node('goal_0')).toMatchObject({ status: 'pending', attempts: 1 }); expect(node('goal_0').proof).toBeUndefined(); - const next = await assigned(workers[2]); - expect(next.task.id).toBe('goal_0'); expect(next.assignment.connectionCheck!.basisDigest).not.toBe(oldBasis); - expect(next.assignment.connectionCheck!.inputs).toEqual([{ taskId: 'helper', taskDigest: taskVersion(node('helper').task) }]); - expect(node('goal_0').task.conditional).toBeUndefined(); - }); -}); diff --git a/tests/contextCheckpoint.test.ts b/tests/contextCheckpoint.test.ts index 7607fea1..29200217 100644 --- a/tests/contextCheckpoint.test.ts +++ b/tests/contextCheckpoint.test.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; + import { acceptContextCheckpoint, readCheckpointNotesDigest, savedContextCheckpoint } from '../src/solver/contextCheckpoint'; import { MAX_RESEARCH_NOTES_BYTES } from '../src/solver/deliveries'; import { git } from '../src/solver/problem'; @@ -92,66 +92,3 @@ describe('explicit context checkpoint publication', () => { } finally { fs.rmSync(example.directory, { recursive: true, force: true }); } }); }); - -describe('task checkpoint event intake', () => { - const reader = (commit = 'a'.repeat(40)) => { - const task: CooperativeTask = { id: 'a', kind: 'lemma', objective: 'Prove a.', dependsOn: [], revision: 0, - theoremName: 'a', proofPath: 'Submission.lean', type: 'True' }; - const action: Extract = { kind: 'task', task, assignment: { - taskId: task.id, taskDigest: taskVersion(task), workerId: 'peer', seedCommit: commit, assignmentId: 'dispatch', - } }; - const worker = { id: 'peer', role: 'prover' as const, worktree: directory, ownedFiles: [] }; - const session = { id: worker.id, ...research }; - const main = { threadId: 'other-thread', workers: [session], problem: { baseCommit: commit }, environmentDigest: 'environment' }; - const sequence: string[] = [], save = vi.fn(); - const cooperative = Object.create(CooperativeResearch.prototype); - Object.assign(cooperative, { - archive: { tasks: [{ task, status: 'running', attempts: 1, assignment: action.assignment }], deliveries: [] }, - input: { state: main, signal: new AbortController().signal, save, - emit: (name: string) => { sequence.push(name); } }, - current: () => true, record: vi.fn(), - }); - return { cooperative, action, worker, session, main, sequence, save }; - }; - - it('publishes the checkpoint only after the preceding research event finishes intake', async () => { - git(directory, ['init', '--quiet']); - git(directory, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--quiet', '--allow-empty', '-m', 'Fixture']); - const commit = git(directory, ['rev-parse', 'HEAD']); - const { cooperative, action, worker, session, main, sequence, save } = reader(commit); - const entered = deferred(), release = deferred(); - cooperative.publishResearchFinding = vi.fn(async () => { - entered.resolve(); await release.promise; sequence.push('research-recorded'); - }); - const file = path.join(directory, assignmentDeliveryFile(action.assignment)); - fs.writeFileSync(file, JSON.stringify({ kind: 'research', finding: { summary: 'The exact unresolved gap.' } }) + '\n' + - JSON.stringify(event) + '\n'); - const cursors = {}; - const pending = cooperative.readWorkerDeliveries(worker, action, cursors); - await entered.promise; - expect(savedContextCheckpoint(session, directory)).toBeUndefined(); - expect(sequence).toEqual([]); - release.resolve(); await pending; - expect(sequence).toEqual(['research-recorded', 'context_checkpoint_published']); - expect(savedContextCheckpoint(session, directory)).toBe(digest); - expect(main).not.toHaveProperty('contextCheckpoint'); - expect(cooperative.record).not.toHaveBeenCalled(); - expect(cooperative.archive.deliveries).toEqual([]); - expect(cooperative.archive.tasks[0].status).toBe('running'); - expect(cursors).toHaveProperty(`peer/${assignmentDeliveryFile(action.assignment)}`, fs.statSync(file).size); - expect(save).toHaveBeenCalled(); - }); - - it.each(['legacy-log', 'wrong-task', 'wrong-digest', 'superseded', 'wrong-worker'] as const)( - 'rejects checkpoint intake from %s', async scope => { - const { cooperative, action, worker, session } = reader(); - const value = { ...event, id: 'checkpoint', taskId: action.task.id, taskDigest: action.assignment.taskDigest }; - if (scope === 'wrong-task') value.taskId = 'other'; - if (scope === 'wrong-digest') value.taskDigest = 'other'; - if (scope === 'superseded') cooperative.current = () => false; - if (scope === 'wrong-worker') action.assignment.workerId = 'other'; - await expect(cooperative.receive(worker, action, value, scope !== 'legacy-log')).rejects.toThrow('math_delivery_invalid'); - expect(savedContextCheckpoint(session, directory)).toBeUndefined(); - expect(cooperative.record).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/contextCompiler.test.ts b/tests/contextCompiler.test.ts index b570a51c..b71a2014 100644 --- a/tests/contextCompiler.test.ts +++ b/tests/contextCompiler.test.ts @@ -13,7 +13,6 @@ import type { DeliveryRecord } from '../src/solver/deliveries'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { buildProofContinuation } from '../src/solver/progress'; import { createCapacityExploration } from '../src/solver/capacityExploration'; -import { cooperativeResearch } from './helpers/cooperation'; import { localExample, leadWorker, peerWorker, solverState } from './helpers/solver'; const baseCommit = 'a'.repeat(40), proofCommit = 'b'.repeat(40); @@ -1175,43 +1174,6 @@ it.each(['proposal', 'refutation'] as const)('loads a current %s source and its expect(taskRecordIndex(context.message).map(row => row.id)).toEqual([staleSource.id, staleInput.id]); }); -it('writes exact digest-retrievable task records and failed inputs to each worker archive within its visibility scope', async () => { - const example = localExample('context-record-retrieval-', 'lead'), controller = new AbortController(), - workers = [leadWorker(example.problem, example.workspace, 'lead'), peerWorker(example, 'peer')], - sameGroup = node({ ...lemma('peer_task'), groupId: 'first', sharing: 'group' }), - privateOther = node({ ...lemma('private_task'), groupId: 'other', sharing: 'group' }), - publicHelper = { ...node({ ...lemma('public_helper'), groupId: 'other', sharing: 'problem' }), status: 'completed' as const }; - sameGroup.status = 'running'; - sameGroup.assignment = { ...assign(sameGroup.task).assignment, workerId: workers[1].id, seedCommit: example.problem.baseCommit }; - const failedInputs = [sameGroup, privateOther].map(record => ({ id: `failure-${record.task.id}`, taskId: record.task.id, - taskDigest: taskVersion(record.task), inputDigest: `input-${record.task.id}`, feedback: `Exact feedback for ${record.task.id}`, - basis: { contractDigest: 'contract', environmentDigest: 'environment', dependencies: {} } })), - state = solverState(example.problem, example.workspace, { runId: 'context-record-retrieval', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, tasks: [sameGroup, privateOther, publicHelper], failedTaskInputs: failedInputs } }), - cooperative = cooperativeResearch({ state, workers, retrievalRoot: example.directory, signal: controller.signal }); - try { - cooperative.activate(workers[1], { kind: 'task', task: sameGroup.task, assignment: sameGroup.assignment }, async () => {}, async () => {}); - for (const worker of workers) { - const archive = JSON.parse(fs.readFileSync(path.join(worker.worktree, 'COOPERATION.json'), 'utf8')), - action = worker.id === 'lead' ? undefined : { kind: 'task' as const, task: sameGroup.task, assignment: sameGroup.assignment! }, - scoped = cooperative.contextState(action, worker); - expect(archive.tasks).toEqual(JSON.parse(canonicalMathJson(scoped.tasks))); - expect(archive.failedTaskInputs).toEqual(JSON.parse(canonicalMathJson(scoped.failedTaskInputs))); - for (const record of scoped.tasks) { - const archived = archive.tasks.find((item: TaskRecord) => item.task.id === record.task.id); - expect(mathDigest(canonicalMathJson(archived))).toBe(mathDigest(canonicalMathJson(record))); - expect(archive.peers.find((peer: { id: string }) => peer.id === record.task.id).taskDigest).toBe(taskVersion(record.task)); - } - if (worker.id === 'peer') { - expect(archive.tasks.map((record: TaskRecord) => record.task.id)).toEqual(['peer_task', 'public_helper']); - expect(archive.failedTaskInputs.map((record: { taskId: string }) => record.taskId)).toEqual(['peer_task']); - } else expect(archive.tasks.map((record: TaskRecord) => record.task.id)).toContain('private_task'); - } - } finally { - controller.abort(); await cooperative.stop(); fs.rmSync(example.directory, { recursive: true, force: true }); - } -}); - function unusedPlannedDependency() { const a = lemma('a'), b = lemma('b'), first = lemma('first', [a.id, b.id]), second = lemma('second', [first.id]); const oldProof = checked(a); diff --git a/tests/continuationSeed.test.ts b/tests/continuationSeed.test.ts deleted file mode 100644 index 5f895065..00000000 --- a/tests/continuationSeed.test.ts +++ /dev/null @@ -1,3082 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LEAN_EVAL_BENCHMARK_COMMIT } from '../src/math/leanEvalCatalogAdapter'; -import { canonicalMathProblemStatementPayloads, type MathProblemContract } from '../src/math/contracts'; -import { hashMathFormalSourceDeclaration } from '../src/math/leanSource'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import { projectMathematicsRuntimeEnvironment, resolveMathematicsRuntimeEnvironment } from '../src/math/mathRuntimeEnvironment'; -import { MATH_PROOF_ENVIRONMENT_ENV, MATH_PROOF_ENVIRONMENT_SANDBOX_ENV } from '../src/math/mathProofEnvironment'; -import { DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT } from '../src/math/mathProofEnvironmentCache'; -import { withMathRuntimeLease } from '../src/math/mathRuntimeIo'; -import type { MathematicsVerifierBatchRequest, MathematicsVerifierExecutionOptions } from '../src/math/verifier'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { captureSolverContinuationSource, seedSolverContinuation } from '../src/solver/continuationSeed'; -import { acceptContextCheckpoint } from '../src/solver/contextCheckpoint'; -import { MAX_CONTINUATION_ATTACHMENT_BYTES, readContinuationPage, readContinuationSnapshot } from '../src/solver/continuationInput'; -import { committedSource, commitSolverSources, git, readSolverProblem } from '../src/solver/problem'; -import { theoryModuleSource } from '../src/math/theoryModules'; -import { freshlyAccepted, taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { setTaskStatus } from '../src/solver/taskLifecycle'; -import { expandTaskFamilies } from '../src/solver/taskFamilies'; -import type { TaskProof } from '../src/solver/cooperativeProof'; -import * as taskProofs from '../src/solver/cooperativeProof'; -import { conditionalExpectedType } from '../src/solver/conditionalProjection'; -import { hasTaskConnectionCheck, taskConnectionCheckCurrent } from '../src/solver/taskConnections'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { captureResearchBasis, researchSourceDigest, settleResearch } from '../src/solver/researchRecords'; -import { researchSourceTasks, scopedResearchSources } from '../src/solver/researchSources'; -import { bindMathematicalGap } from '../src/solver/mathematicalGaps'; -import { currentNextCheck, proposedNextChecks } from '../src/solver/nextChecks'; -import { emptyProofSearchCheckpoint } from '../src/math/leanProofSearch'; -import { localProofSearchPath } from '../src/math/proofSearchCheckpointPath'; -import { proofSearchRecordForAssignment, projectProofSearchRecord, retainProofSearchCheckpoint } from '../src/solver/proofSearchRecords'; -import { proposedDefinitionContractChecks } from '../src/solver/definitionContractChecks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { WorkerProofLifecycle } from '../src/solver/workerProofLifecycle'; -import { VerificationCheckpointError, withVerificationCheckpoints } from '../src/solver/verificationCheckpoint'; -import { failedBatch, receiptBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), build: vi.fn(), prepare: vi.fn(), dispose: vi.fn(), - resolvePackages: vi.fn(), packages: undefined as string | undefined })); -vi.mock('../src/math/mathBuildManifest', async importOriginal => ({ ...await importOriginal(), - readMathBuildManifest: host.build })); -vi.mock('../src/math/verifier', async importOriginal => ({ ...await importOriginal(), - checkManyFormalVerifications: host.verify, resolveMathematicsLakePackagesCache: host.resolvePackages })); -vi.mock('../src/math/mathProofEnvironment', async importOriginal => ({ ...await importOriginal(), - prepareMathProofEnvironment: host.prepare })); - -const roots: string[] = []; -const original = 'import Submission.Helpers\nnamespace Submission\ntheorem original : True := by sorry\nend Submission\n'; -const emptyHelpers = 'namespace Submission.Helpers\nend Submission.Helpers\n'; -const helpers = 'namespace Submission.Helpers\nlemma first_helper : True := by trivial\nlemma second_helper : True := by trivial\nend Submission.Helpers\n'; -const commit = (root: string, message: string) => { - git(root, ['add', '--', '.']); - git(root, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--quiet', '--no-gpg-sign', '-m', message]); - return git(root, ['rev-parse', 'HEAD']); -}; - -function fixture(statement = original, goalNames = ['Submission.original'], manifestPackages?: readonly unknown[]) { - const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'continuation-seed-test-'))); roots.push(root); - const workspace = path.join(root, 'workspace'), projectRelative = 'generated/fixture', project = path.join(workspace, projectRelative); - fs.mkdirSync(path.join(project, 'Submission'), { recursive: true }); - const trusted = { 'Challenge.lean': 'theorem challenge : True := by trivial\n', - 'config.json': '{"theorem_names":["original"]}\n', 'holes.json': '{"id":"fixture","holes":[{"name":"original"}]}\n', - 'lean-toolchain': 'leanprover/lean4:v4.31.0\n', 'lakefile.toml': 'name = "fixture"\n[[lean_lib]]\nname = "Submission"\n', - ...(manifestPackages === undefined ? {} : { 'lake-manifest.json': JSON.stringify({ packages: manifestPackages }) }) }; - for (const [file, text] of Object.entries(trusted)) fs.writeFileSync(path.join(project, file), text); - fs.writeFileSync(path.join(project, 'Submission.lean'), statement); - fs.writeFileSync(path.join(project, 'Submission/Helpers.lean'), emptyHelpers); - git(workspace, ['init', '--quiet']); const base = commit(workspace, 'Public solver baseline'); - fs.appendFileSync(path.join(workspace, '.git/info/exclude'), `\n/${projectRelative}/.lake/\n/active-problem.json\n`); - const payloads = canonicalMathProblemStatementPayloads({ informalStatement: 'Prove the original claim.', formalStatement: statement, assumptions: [] }); - const contract: MathProblemContract = { problemId: 'fixture', informalStatement: 'Prove the original claim.', formalStatement: statement, - assumptions: [], knownTraps: [], acceptanceCriteria: ['Prove original'], officialVerificationCommand: 'lake test', - statementHash: mathDigest(payloads.informal), leanStatementHash: mathDigest(payloads.lean) }; - const receiptFile = path.join(workspace, 'active-problem.json'); - fs.writeFileSync(receiptFile, JSON.stringify({ schema: 'deepscientist.mathematics.lean-eval-bootstrap-receipt.v1', - receiptId: 'fixture', problemId: 'fixture', benchmarkCommit: LEAN_EVAL_BENCHMARK_COMMIT, catalogHash: 'a'.repeat(64), - leaderboardSource: 'disabled', contract, workspaceRoot: workspace, projectRoot: project, activeProblemPath: receiptFile, - createdAt: 1, trustedFiles: Object.keys(trusted), solverOwnedFiles: ['Submission.lean', 'Submission/Helpers.lean'], - publicObligations: goalNames.map(name => ({ name, declarationHash: hashMathFormalSourceDeclaration(statement, name) })) })); - const problem = readSolverProblem(workspace, receiptFile); - const oldDirectory = path.join(root, 'old.json.runtime'), directory = path.join(root, 'new.json.runtime'); - for (const parent of [oldDirectory, directory]) { - fs.mkdirSync(parent, { mode: 0o700 }); - for (const name of ['worktree', 'worktree-2']) git(workspace, ['worktree', 'add', '--quiet', '--detach', path.join(parent, name), base]); - } - const sourceWorktree = path.join(oldDirectory, 'worktree'), worktree = path.join(directory, 'worktree'); - fs.writeFileSync(path.join(sourceWorktree, projectRelative, 'Submission/Helpers.lean'), helpers); - const canonical = commit(sourceWorktree, 'Historical helpers'); - const notes = '\ufeffunfinished λ notes\r\n'; - fs.writeFileSync(path.join(oldDirectory, 'worktree-2', projectRelative, 'Submission/Helpers.lean'), helpers.replace('by trivial', 'by sorry')); - fs.writeFileSync(path.join(oldDirectory, 'worktree-2', 'RESEARCH.md'), notes); - fs.writeFileSync(path.join(sourceWorktree, 'RESEARCH.md'), 'Old Lead findings, still advisory.\n'); - const tasks: CooperativeTask[] = ['first', 'second'].map(name => ({ id: name, kind: 'lemma', objective: `Prove ${name}`, - dependsOn: [], revision: 0, ownerId: 'prover-1', proofPath: 'Submission/Helpers.lean', - theoremName: `Submission.Helpers.${name}_helper`, type: 'True' })); - tasks.push({ id: 'goal', kind: 'goal', objective: 'Prove original', dependsOn: ['first', 'second'], revision: 0, - proofPath: 'Submission.lean', theoremName: 'Submission.original' }); - const archivedProof = (task: CooperativeTask): TaskProof => ({ commit: canonical, sourceDigest: 'old-source', passed: true, - taskDigest: taskVersion(task), seedCommit: base, changes: [], verification: { status: 'kernel_verified', targetCommit: canonical, - results: [{ status: 'kernel_verified', targetCommit: canonical, receiptId: `old-${task.id}` }] } as TaskProof['verification'] }); - const buildFile = path.join(root, 'manifest.json'); fs.writeFileSync(buildFile, '{"fixture":"new-build"}', { mode: 0o400 }); - const skeleton = { schema: 'deepscientist.math.solver.v1' as const, problem, taskDigest: mathDigest('Original unchanged task.\n'), - environmentDigest: mathDigest('new-environment'), evaluatorDigest: mathDigest('host-default'), model: 'fixture', effort: 'max', - coordination: 'cooperative' as const, turns: 0, dispatchCounts: {}, workerCount: 2 }; - const newState: SolverRunState = { ...skeleton, runId: 'new-run', buildDigest: mathDigest(fs.readFileSync(buildFile)), - methodDigest: 'new-method', phase: 'prepared', worktree, workers: [ - { id: 'solver', role: 'lead', worktree, phase: 'prepared', turns: 0, dispatchCounts: {} }, - { id: 'prover-1', role: 'prover', worktree: path.join(directory, 'worktree-2'), phase: 'prepared', turns: 0, dispatchCounts: {} }] }; - const oldState: SolverRunState = { ...skeleton, runId: 'old-run', buildDigest: 'historical-build', methodDigest: 'old-method', - phase: 'running', turns: 8, worktree: sourceWorktree, workers: [ - { id: 'solver', role: 'lead', worktree: sourceWorktree, phase: 'running', turns: 3, threadId: 'old-lead-thread' }, - { id: 'prover-1', role: 'prover', worktree: path.join(oldDirectory, 'worktree-2'), phase: 'running', turns: 5, threadId: 'old-prover-thread' }], - cooperation: { canonicalCommit: canonical, planVersion: 'historical-plan', groups: [{ group: { - id: 'main', objective: 'Original route', status: 'active', revision: 0 }, turns: 8 }], - tasks: tasks.map(task => ({ task, status: task.kind === 'goal' ? 'running' : 'integrated', attempts: 2, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'prover-1', seedCommit: base, assignmentId: `old-${task.id}` }, - ...(task.kind === 'lemma' ? { integratedCheck: archivedProof(task) } : {}) })), - deliveries: [{ id: 'old-delivery', producer: 'prover-1', kind: 'proof', status: 'verified', statement: 'True', premises: [], - dependencies: [], remainingObligations: [], summary: 'Historical check', evidenceRefs: [], createdAt: 1 }] } }; - const stateFile = path.join(directory, 'state.json'), sourceStateFile = path.join(oldDirectory, 'state.json'); - writeSolverRunState(stateFile, newState); writeSolverRunState(sourceStateFile, oldState); - const environmentFile = path.join(directory, 'environment-solver.json'); - host.packages = path.join(root, 'packages'); fs.mkdirSync(host.packages); - fs.writeFileSync(environmentFile, canonicalMathJson(projectMathematicsRuntimeEnvironment({ PATH: '/usr/bin:/bin', - DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages, - [MATH_PROOF_ENVIRONMENT_ENV]: 'disposed-startup-only-fixture' })), { mode: 0o400 }); - const controller = new AbortController(); - const options = { sourceRun: sourceStateFile, run: stateFile, root, buildManifest: buildFile, signal: controller.signal }; - return { root, directory, oldDirectory, workspace, worktree, sourceWorktree, projectRelative, stateFile, sourceStateFile, - newState, oldState, tasks, notes, base, environmentFile, options, controller, seed: () => seedSolverContinuation(options) }; -} - -function conditionalFixture() { - const f = fixture(), worker = f.oldState.workers![1]!.worktree; - git(worker, ['reset', '--hard', f.oldState.cooperation!.canonicalCommit!]); - fs.writeFileSync(path.join(worker, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('end Submission.Helpers', 'lemma bridge_helper : True := by exact second_helper\nend Submission.Helpers')); - const proofCommit = commit(worker, 'Historical conditional bridge'); - fs.writeFileSync(path.join(worker, 'RESEARCH.md'), f.notes); - const task: CooperativeTask = { id: 'bridge', kind: 'lemma', objective: 'Reuse the missing typed lemma', - dependsOn: ['second'], revision: 0, ownerId: 'prover-1', proofPath: 'Submission/Helpers.lean', - theoremName: 'Submission.Helpers.bridge_helper', type: 'True' }; - const condition = { taskId: 'second', taskDigest: taskVersion(f.tasks[1]!) }; - f.oldState.cooperation!.tasks.push({ task, status: 'conditional', attempts: 1, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'prover-1', seedCommit: f.oldState.cooperation!.canonicalCommit!, - dependencies: [condition] }, - proof: { commit: proofCommit, sourceDigest: 'old-conditional-source', passed: true, taskDigest: taskVersion(task), - seedCommit: f.oldState.cooperation!.canonicalCommit!, changes: [], conditions: [condition], - verification: { status: 'kernel_verified', targetCommit: proofCommit, - results: [{ status: 'kernel_verified', targetCommit: proofCommit, receiptId: 'old-bridge' }] } as TaskProof['verification'] } }); - f.oldState.workers![1]!.sessionTaskId = task.id; - writeSolverRunState(f.sourceStateFile, f.oldState); - return { ...f, task, condition, proofCommit }; -} - -function frozenGoalFixture() { - const f = fixture(), node = f.oldState.cooperation!.tasks.find(node => node.task.id === 'goal')!; - const worker = f.oldState.workers![1]!; - worker.role = 'engineer'; f.newState.workers![1]!.role = 'engineer'; - node.assignment = { taskId: node.task.id, taskDigest: taskVersion(node.task), workerId: worker.id, - seedCommit: f.oldState.cooperation!.canonicalCommit!, assignmentId: 'old-frozen-goal', - dependencies: node.task.dependsOn.map(id => ({ taskId: id, taskDigest: taskVersion(f.tasks.find(task => task.id === id)!) })) }; - git(worker.worktree, ['reset', '--hard', node.assignment.seedCommit]); - fs.writeFileSync(path.join(worker.worktree, f.projectRelative, 'Submission.lean'), original.replace('by sorry', 'by trivial')); - const snapshotCommit = commit(worker.worktree, 'Frozen goal candidate'); - const cooperation = cooperationFor(f, f.oldState), descriptor = { id: worker.id, role: worker.role, - worktree: worker.worktree, ownedFiles: f.oldState.problem.ownedFiles }; - const ready = cooperation.freezeImportedProof(descriptor, { kind: 'task', task: node.task, assignment: node.assignment }, - 'host-frozen-goal-input', snapshotCommit)!; - if (!ready) throw new Error('fixture_frozen_goal_missing'); - writeSolverRunState(f.sourceStateFile, f.oldState); writeSolverRunState(f.stateFile, f.newState); - return { ...f, snapshotCommit, ready }; -} - -function initialPlanningFixture() { - const f = fixture(); - git(f.sourceWorktree, ['reset', '--hard', f.base]); - f.oldState.phase = 'finished'; f.oldState.turns = 0; - f.oldState.solveStartedAt = 10; f.oldState.solveFinishedAt = 11; - for (const worker of f.oldState.workers!) { worker.turns = 0; delete worker.threadId; } - f.oldState.cooperation = { canonicalCommit: f.base, leadSeedCommit: f.base, tasks: [], proofRoutes: [], - // Cooperation establishes an empty-graph version before its first context is compiled. - planVersion: mathDigest(canonicalMathJson({ tasks: [], groups: undefined })), - leadWakes: { requested: 1, consumed: 1, settled: 0, recent: [{ at: 10, reason: 'initial-plan', seq: 1 }] } }; - writeSolverRunState(f.sourceStateFile, f.oldState); - return f; -} - -function startedInitialPlanningFixture() { - const f = initialPlanningFixture(); - for (const [index, id, role] of [[1, 'researcher-1', 'researcher'], [2, 'researcher-2', 'researcher'], - [3, 'engineer', 'engineer']] as const) { - for (const [directory, state] of [[f.oldDirectory, f.oldState], [f.directory, f.newState]] as const) { - const worktree = path.join(directory, `worktree-${index + 1}`); - if (index > 1) git(f.workspace, ['worktree', 'add', '--quiet', '--detach', worktree, f.base]); - state.workers![index] = { id, role, worktree, phase: directory === f.oldDirectory ? 'finished' : 'prepared', - turns: 0, dispatchCounts: {} }; - state.workerCount = 4; - } - } - const usage = { inputTokens: 1200, outputTokens: 300, totalTokens: 1500 }; - const accounting = { startedTurns: 3, reportedTurns: 0, pending: false, incomplete: true }; - const requests = { startedRequests: 2, reportedRequests: 1, pendingRequests: 0, incomplete: true, - receipts: [{ source: 'responses-relay' as const, requestId: 'initial-request', runId: f.oldState.runId, - sessionId: 'initial-session', startedAt: 1, status: 'reported' as const, settledAt: 2, - outcome: 'completed' as const, usage }] }; - f.oldState.phase = 'finished'; f.oldState.turns = 3; f.oldState.dispatchCounts = { planning: 3 }; - f.oldState.usage = usage; - const lead = f.oldState.workers![0]; - Object.assign(lead, { turns: 3, threadId: 'initial-thread', previousThreadIds: ['earlier-initial-thread'], - sessionRole: 'lead', sessionStatementReview: false, dispatchCounts: { planning: 3 }, usage, - usageBeforeThread: { inputTokens: 1000, outputTokens: 200, totalTokens: 1200 }, - usageAccounting: accounting, requestUsageAccounting: requests, - candidate: { status: 'failed', operation: 'direct', worktree: lead.worktree, - problemReceiptDigest: f.oldState.problem.receiptDigest } }); - const leadNotes = 'Initial-plan draft and unresolved obligations.\n'; - const leadDraft = emptyHelpers.replace('end Submission.Helpers', 'lemma initial_draft : True := by sorry\nend Submission.Helpers'); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), leadNotes); - fs.writeFileSync(path.join(lead.worktree, f.projectRelative, 'Submission/Helpers.lean'), leadDraft); - const savedDraft = { id: 'saved-initial-lead-draft', producer: lead.id, kind: 'progress' as const, - status: 'advisory' as const, statement: f.oldState.problem.contract.formalStatement, - premises: f.oldState.problem.contract.assumptions, dependencies: [], remainingObligations: [], evidenceRefs: [], - createdAt: 11, commit: f.base, - summary: 'Saved Lead draft pending integration: math_math-plan_missing_or_too_large. ' + - `Inspect git show ${f.base}:PROJECT_RELATIVE_PATH and reapply the useful declarations against the current canonical sources. ` + - 'This draft has no proof acceptance.' }; - f.oldState.cooperation!.deliveries = [savedDraft]; - writeSolverRunState(f.sourceStateFile, f.oldState); writeSolverRunState(f.stateFile, f.newState); - return { ...f, usage, accounting, requests, leadNotes, leadDraft, savedDraft }; -} - -function freshReceipts(request: MathematicsVerifierBatchRequest) { - return receiptBatch(request, { sessionId: 'fresh-seed', receiptId: (_, name) => `fresh-seed-${request.targetCommit}-${name}` }); -} - -function originalDependencyFixture(declared = false, hidden = false) { - const statement = 'import Submission.Helpers\nnamespace Submission\n' + - 'theorem premise : True := by sorry\ndef witness : True := premise\n' + - 'theorem original : True := by sorry\nend Submission\n'; - const f = fixture(statement, ['Submission.original', 'Submission.premise']); - const source = statement.replace('premise : True := by sorry', 'premise : True := by trivial') - .replace('original : True := by sorry', `original : True := by ${hidden ? 'trivial' : 'exact witness'}`); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), source); - const canonical = commit(f.sourceWorktree, 'Frozen original goal chain'); - const oldProof = f.oldState.cooperation!.tasks[0]!.integratedCheck!; - const goal = { ...f.tasks[2]!, dependsOn: declared ? ['premise'] : [] }; - const premise = { ...goal, id: 'premise', theoremName: 'Submission.premise', objective: 'Prove premise', dependsOn: [] }; - f.oldState.cooperation!.canonicalCommit = canonical; - // Consumers deliberately precede their original prerequisite in the saved graph. - f.oldState.cooperation!.tasks = [goal, premise].map(task => ({ task, status: 'integrated', attempts: 1, - integratedCheck: { ...oldProof, commit: canonical, taskDigest: taskVersion(task) } })); - writeSolverRunState(f.sourceStateFile, f.oldState); - return f; -} - -function conditionalOriginalContextFixture(canonicalBridge = false) { - const statement = 'import Submission.Helpers\nnamespace Submission\n' + - 'theorem premise : True := by sorry\ntheorem extra : True := by sorry\n' + - 'theorem unused : True := by sorry\ndef witness : True := premise\n' + - 'def nestedWitness : True := witness\ndef combinedWitness : True := by\n' + - ' have h : True := extra\n exact nestedWitness\n' + - 'theorem original : True := by sorry\nend Submission\n'; - const f = fixture(statement, ['Submission.original', 'Submission.premise', 'Submission.extra', 'Submission.unused']); - const source = statement.replaceAll(': True := by sorry', ': True := by trivial'); - const canonicalSource = canonicalBridge ? source.replace('end Submission', - 'lemma bridge : True := by exact unused\nend Submission') : source; - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), canonicalSource); - const canonical = commit(f.sourceWorktree, 'Historical original context'); - const previous = f.oldState.cooperation!.tasks, historical = previous[0]!.integratedCheck!; - const originals = ['premise', 'extra', 'unused'].map(id => { - const task = { ...f.tasks[2]!, id, objective: `Prove ${id}`, theoremName: `Submission.${id}`, dependsOn: [] }; - return { task, status: 'integrated' as const, attempts: 1, - integratedCheck: { ...historical, commit: canonical, taskDigest: taskVersion(task) } }; - }); - const worker = f.oldState.workers![1]!.worktree; - git(worker, ['reset', '--hard', canonical]); - const bridgeDeclaration = 'lemma bridge : True := by\n' + - ' have h : True := Submission.Helpers.second_helper\n exact combinedWitness\n'; - fs.writeFileSync(path.join(worker, f.projectRelative, 'Submission.lean'), canonicalBridge ? - canonicalSource.replace('lemma bridge : True := by exact unused\n', bridgeDeclaration) : - source.replace('end Submission', bridgeDeclaration + 'end Submission')); - const proofCommit = commit(worker, 'Conditional bridge using original definitions'); - const task: CooperativeTask = { id: 'bridge', kind: 'lemma', objective: 'Apply the typed input with original context', - dependsOn: ['second'], revision: 0, ownerId: 'prover-1', proofPath: 'Submission.lean', - theoremName: 'Submission.bridge', type: 'True' }; - const condition = { taskId: 'second', taskDigest: taskVersion(f.tasks[1]!) }; - const bridge = { task, status: 'conditional' as const, attempts: 1, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'prover-1', seedCommit: canonical, - dependencies: [condition] }, - proof: { ...historical, commit: proofCommit, seedCommit: canonical, taskDigest: taskVersion(task), conditions: [condition] } }; - f.oldState.cooperation!.canonicalCommit = canonical; - f.oldState.cooperation!.tasks = [bridge, ...originals, ...previous.slice(0, 2), - { task: { ...f.tasks[2]!, dependsOn: ['bridge'] }, status: 'pending', attempts: 0 }]; - f.oldState.workers![1]!.sessionTaskId = task.id; - writeSolverRunState(f.sourceStateFile, f.oldState); - return { ...f, task, condition, proofCommit, bridge, canonicalSource }; -} - -function replaceHelperCandidates(f: ReturnType, count: number) { - const tasks: CooperativeTask[] = Array.from({ length: count }, (_, index) => ({ ...f.tasks[0]!, - id: `helper_${index}`, objective: `Prove helper ${index}`, theoremName: `Submission.Helpers.helper_${index}` })); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), - `namespace Submission.Helpers\n${tasks.map(task => `lemma ${task.id} : True := by trivial\n`).join('')}end Submission.Helpers\n`); - const canonical = commit(f.sourceWorktree, 'Historical helper batch'); - const historical = f.oldState.cooperation!.tasks[0]!.integratedCheck!; - f.oldState.cooperation!.canonicalCommit = canonical; - f.oldState.cooperation!.tasks = [...tasks.map(task => ({ task, status: 'integrated' as const, attempts: 1, - integratedCheck: { ...historical, commit: canonical, taskDigest: taskVersion(task) } })), - { task: { ...f.tasks.at(-1)!, dependsOn: tasks.map(task => task.id) }, status: 'pending', attempts: 0 }]; - writeSolverRunState(f.sourceStateFile, f.oldState); - return tasks; -} - -function cooperationFor(f: ReturnType, state: SolverRunState, freshContinuationChecks: readonly TaskProof[] = [], - options: { timeoutMs?: number; save?: () => void; environment?: NodeJS.ProcessEnv; - emit?: (event: string, details?: Record) => void } = {}) { - const workers = state.workers!.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, - ownedFiles: state.problem.ownedFiles })); - const { environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages, - [MATH_PROOF_ENVIRONMENT_ENV]: 'live-host-proof-environment' }, ...runtimeOptions } = options; - return cooperativeResearch({ state, workers, retrievalRoot: f.root, signal: f.controller.signal, - freshContinuationChecks, access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: f.root }])), ...runtimeOptions }); -} - -async function freshConditionalFixture(explicit = true, prepared = true) { - const f = conditionalFixture(), input = f.oldState.cooperation!.tasks.find(node => node.task.id === 'second')!; - if (explicit) { - f.task.conditional = true; - const bridge = f.oldState.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - bridge.proof!.taskDigest = bridge.assignment!.taskDigest = taskVersion(f.task); - } - // Its input stays unresolved, so receipt reuse cannot turn into normal integration. - setTaskStatus(input, 'pending', 'reconstructed'); input.integratedCheck = undefined; - writeSolverRunState(f.sourceStateFile, f.oldState); - const environment: NodeJS.ProcessEnv = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages, - [MATH_PROOF_ENVIRONMENT_ENV]: 'live-host-proof-environment' }; - let state!: SolverRunState, proofs!: TaskProof[]; - await seedSolverContinuation({ ...f.options, ...(prepared ? { preparedEnvironment: environment } : {}), - onSeeded: (next, checked) => { state = next; proofs = checked; } }); - const bridge = state.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - return { ...f, state, proofs, bridge, environment }; -} - -async function suspendedTaskDraftFixture(kind: 'research' | 'sketch' | 'goal' | 'lemma' | 'feasibility' = 'research', - notes: string | null = '\ufeffSUSPENDED_ROUTE_FINDING λ\r\n```math\n' + - '{"conclusion":"inconclusive","summary":"SUSPENDED_ROUTE_FINDING"}\n```\r\n', sourceDraft = true, scopedReview = false) { - const f = fixture(), state = f.oldState, peer = state.workers![1]!; - peer.role = 'engineer'; f.newState.workers![1]!.role = 'engineer'; - const tasks = state.cooperation!.tasks, goal = tasks.find(node => node.task.id === 'goal')!; - setTaskStatus(goal, 'pending', 'reconstructed'); goal.assignment = undefined; - let task: CooperativeTask; - if (kind === 'goal' || kind === 'lemma') { - for (const [directory, current] of [[f.oldDirectory, state], [f.directory, f.newState]] as const) { - const worktree = path.join(directory, 'worktree-3'); - git(f.workspace, ['worktree', 'add', '--quiet', '--detach', worktree, f.base]); - current.workers!.push({ id: 'input-prover', role: 'prover', worktree, phase: 'prepared', turns: 0, dispatchCounts: {} }); - current.workerCount = current.workers!.length; - } - const input = tasks.find(node => node.task.id === 'first')!; - input.task = { ...input.task, ownerId: 'input-prover' }; setTaskStatus(input, 'pending', 'reconstructed'); - input.assignment = undefined; input.integratedCheck = undefined; - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('first_helper : True := by trivial', 'first_helper : True := by sorry')); - state.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Unfinished typed connection input'); - task = kind === 'goal' ? { ...goal.task, ownerId: peer.id } : { id: 'saved_route', kind: 'lemma', - objective: 'Apply the unfinished typed input', dependsOn: ['first'], revision: 0, ownerId: peer.id, - theoremName: 'Submission.Helpers.saved_route', type: 'True', proofPath: 'Submission/Helpers.lean' }; - if (kind === 'lemma') { - goal.task = { ...goal.task, dependsOn: [task.id], conditional: false }; - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ - result: { status: 'unavailable', taskDigest: taskVersion(input.task), inputDigest: mathDigest('fixture-no-lean'), - reason: 'fixture-no-lean', evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' }, current: () => true })); - } - } else { - if (scopedReview) tasks.push({ task: { id: 'inspected_input', kind: 'research', - objective: 'Check the local finite input.', status: 'paused', dependsOn: [], revision: 0 }, status: 'pending', attempts: 0 }); - task = { id: 'saved_route', kind: kind === 'feasibility' ? 'research' : kind, - objective: 'Investigate the first route', dependsOn: kind === 'feasibility' ? scopedReview ? ['inspected_input'] : [] : ['first'], revision: 0, - ownerId: peer.id, ...(kind === 'feasibility' ? { reviewScope: 'feasibility' as const } : {}) }; - goal.task = { ...goal.task, dependsOn: [...goal.task.dependsOn, task.id] }; - } - if (kind === 'goal') goal.task = task; - else tasks.push({ task, status: 'pending', attempts: 0 }); - const other: CooperativeTask = { id: 'current_route', kind: 'research', objective: 'Investigate a different route', - dependsOn: [], revision: 0, ownerId: peer.id, status: 'paused' }; - const otherNode = { task: other, status: 'pending' as const, attempts: 0 }; tasks.push(otherNode); - const cooperative = cooperationFor(f, state), descriptor = { ...peer, ownedFiles: state.problem.ownedFiles }; - try { - const action = await cooperative.next(descriptor, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task' || action.task.id !== task.id) throw new Error('fixture_expected_saved_task'); - Object.assign(peer, { sessionRole: 'researcher', sessionTaskId: task.id, sessionTaskVersion: taskVersion(task), - sessionAssignmentId: action.assignment.assignmentId }); - const file = path.join(peer.worktree, f.projectRelative, 'Submission/Helpers.lean'); - if (sourceDraft) fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('end Submission.Helpers', - 'lemma suspended_support : True := by\r\n sorry\r\nend Submission.Helpers')); - if (notes === null) fs.rmSync(path.join(peer.worktree, 'RESEARCH.md'), { force: true }); - else fs.writeFileSync(path.join(peer.worktree, 'RESEARCH.md'), notes); - const draftCommit = commitSolverSources(state.problem, peer.worktree), draftSource = fs.readFileSync(file, 'utf8'); - cooperative.retainContextDraft(descriptor, action, draftCommit, kind === 'goal' || kind === 'lemma' ? 'connection' : 'context'); - cooperative.interrupted(descriptor, action); - const node = tasks.find(node => node.task.id === task.id)!; - node.task = { ...node.task, status: 'paused' }; otherNode.task = { ...other, status: 'active' }; - const current = await cooperative.next(descriptor, { maxTurns: Infinity, remainingMs: Infinity }); - if (current?.kind !== 'task' || current.task.id !== other.id) throw new Error('fixture_expected_other_task'); - fs.writeFileSync(path.join(peer.worktree, 'RESEARCH.md'), 'CURRENT_ROUTE_FINDING\n'); - const currentCommit = commitSolverSources(state.problem, peer.worktree); - cooperative.retainContextDraft(descriptor, current, currentCommit); - cooperative.interrupted(descriptor, current); - Object.assign(peer, { sessionTaskId: other.id, sessionTaskVersion: taskVersion(other), - sessionAssignmentId: current.assignment.assignmentId }); - node.task = { ...node.task, status: 'active' }; otherNode.task = { ...otherNode.task, status: 'paused' }; - writeSolverRunState(f.sourceStateFile, state); writeSolverRunState(f.stateFile, f.newState); - return { ...f, task: node.task, draftCommit, draftSource, draftNotes: notes, draftAssignment: action.assignment, - currentCommit }; - } finally { await cooperative.stop(); } -} - -function taskDraftAttachments(stateFile: string) { - const state = readSolverRunState(stateFile), directory = path.dirname(stateFile); - const snapshot = readContinuationSnapshot(path.join(directory, 'continuation.json'), state.continuationDigest!); - return snapshot.manifest.attachments.filter(item => /^seed-task-drafts(?:-[1-9][0-9]*)?$/u.test(item.id)) - .flatMap(item => JSON.parse(fs.readFileSync(path.join(directory, item.contentPath), 'utf8'))) as - NonNullable['taskDrafts']>; -} - -async function researchCheckpointFixture(kind: 'research' | 'sketch' = 'research', count = 3, - notes: string | null = 'Unchanged investigation.\n', dependency = false, sourceMetadata = false, acknowledge = false) { - const f = fixture(), state = f.oldState, peer = state.workers![1]!; - peer.role = 'engineer'; f.newState.workers![1]!.role = 'engineer'; - const task: CooperativeTask = { id: 'investigate', kind, objective: 'Investigate the original problem', - dependsOn: dependency ? ['input_research'] : [], revision: 0, ownerId: peer.id }; - state.cooperation!.tasks = [{ task, status: 'pending', attempts: 0 }, - { task: { ...f.tasks.at(-1)!, dependsOn: [task.id] }, status: 'pending', attempts: 0 }]; - state.cooperation!.deliveries = []; - if (dependency) { - state.cooperation!.tasks.push({ task: { id: 'input_research', kind: 'research', objective: 'Find the input condition', - dependsOn: [], revision: 0 }, status: 'completed', attempts: 1, finding: 'The saved input condition.' }); - publishCompletedResearch(state, 'input_research', 'original-input-finding'); - if (sourceMetadata) Object.assign(state.cooperation!.deliveries![0]!, { - sourceUses: [{ kind: 'mathlib', reference: 'Mathlib.Logic.Basic', locator: 'True.intro', - assumptions: [], adaptation: 'Check the exact consumer in Lean.', - consumer: { taskId: 'goal', taskDigest: taskVersion(state.cooperation!.tasks[1]!.task) }, - lemmaRequestIds: [], remaining: ['The original goal still requires independent verification.'] }], - searchCheckpoint: { path: 'retained-advisory-search.json', digest: mathDigest('retained-advisory-search') }, - }); - } - const cooperation = cooperationFor(f, state), worker = { ...peer, ownedFiles: state.problem.ownedFiles }; - try { - for (let index = 0; index < count; index++) { - const action = await cooperation.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task' || action.task.id !== task.id) throw new Error('fixture_expected_checkpoint_task'); - Object.assign(peer, { sessionTaskId: task.id, sessionTaskVersion: taskVersion(task), - sessionAssignmentId: action.assignment.assignmentId, sessionRole: 'researcher' }); - if (notes === null) fs.rmSync(path.join(peer.worktree, 'RESEARCH.md'), { force: true }); - else fs.writeFileSync(path.join(peer.worktree, 'RESEARCH.md'), notes); - if (index === 0 && acknowledge && notes !== null) { - peer.contextCheckpoint = { threadId: peer.threadId!, requestedAt: Date.now(), requestId: 'confirm-accurate-notes' }; - acceptContextCheckpoint(peer, peer.worktree, { kind: 'checkpoint', requestId: 'confirm-accurate-notes', - notesDigest: mathDigest(notes) }); - } - await cooperation.deliver(worker, action, commitSolverSources(state.problem, peer.worktree), true); - } - const checkpoint = structuredClone(state.cooperation!.researchCheckpoints![task.id]); - writeSolverRunState(f.sourceStateFile, state); writeSolverRunState(f.stateFile, f.newState); - return { ...f, task, checkpoint }; - } finally { await cooperation.stop(); } -} - -function publishCompletedResearch(state: SolverRunState, taskId: string, id: string) { - const node = state.cooperation!.tasks.find(node => node.task.id === taskId)!; - const sources = Object.fromEntries(state.problem.ownedFiles.map(file => [file, - committedSource(state.worktree, state.cooperation!.canonicalCommit!, `${state.problem.projectRelative}/${file}`)])); - const basis = captureResearchBasis(node.task, { problemReceiptDigest: state.problem.receiptDigest, - environmentDigest: state.environmentDigest, retrievalDigest: state.retrievalDigest, knowledgeDigest: state.knowledgeDigest, - sourceDigest: researchSourceDigest(scopedResearchSources(state.problem, node.task, sources, researchSourceTasks(state.cooperation!.tasks))), - tasks: state.cooperation!.tasks, deliveries: state.cooperation!.deliveries }); - node.assignment = { taskId, taskDigest: taskVersion(node.task), workerId: 'solver', assignmentId: id, - seedCommit: state.cooperation!.canonicalCommit!, researchBasis: basis, - dependencies: node.task.dependsOn.map(id => ({ taskId: id, - taskDigest: taskVersion(state.cooperation!.tasks.find(node => node.task.id === id)!.task) })) }; - const record = settleResearch({ id, assignment: node.assignment, basis, commit: state.cooperation!.canonicalCommit!, - finding: node.finding!, complete: true })!; - node.status = 'completed'; node.researchCompletion = record; - state.cooperation!.deliveries!.push({ id, producer: 'solver', taskId, taskDigest: taskVersion(node.task), - kind: 'research', status: 'advisory', statement: node.task.objective, premises: [], - dependencies: node.assignment.dependencies!, remainingObligations: [], summary: node.finding!, evidenceRefs: [], - createdAt: state.cooperation!.deliveries!.length + 1, commit: state.cooperation!.canonicalCommit!, - finding: node.finding, findingDigest: mathDigest(node.finding!), researchRecord: record }); - return record; -} - -function completedResearchFixture(kind: 'research' | 'sketch' = 'research') { - const f = fixture(), task: CooperativeTask = { id: 'route_research', kind, - objective: 'Locate an exact route from the current helper to the original goal', dependsOn: ['first'], revision: 0 }; - const finding = JSON.stringify({ taskId: task.id, taskDigest: taskVersion(task), conclusion: 'inconclusive', - summary: 'The helper does not close the original goal; the stated arithmetic gap remains.' }); - f.oldState.cooperation!.tasks.push({ task, status: 'completed', attempts: 16, finding, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'solver', assignmentId: 'old-research', - seedCommit: f.oldState.cooperation!.canonicalCommit!, - dependencies: [{ taskId: 'first', taskDigest: taskVersion(f.tasks[0]!) }] } }); - const completion = publishCompletedResearch(f.oldState, task.id, 'old-research-completion'); - writeSolverRunState(f.sourceStateFile, f.oldState); - return { ...f, task, finding, completion }; -} - -function nextContinuation(f: ReturnType, sourceStateFile: string, name: string) { - const directory = path.join(f.root, `${name}.json.runtime`); fs.mkdirSync(directory, { mode: 0o700 }); - for (let index = 0; index < f.newState.workers!.length; index++) - git(f.workspace, ['worktree', 'add', '--quiet', '--detach', path.join(directory, index ? `worktree-${index + 1}` : 'worktree'), f.base]); - const stateFile = path.join(directory, 'state.json'); - writeSolverRunState(stateFile, { ...f.newState, runId: name, worktree: path.join(directory, 'worktree'), - workers: f.newState.workers!.map((worker, index) => ({ ...worker, - worktree: path.join(directory, index ? `worktree-${index + 1}` : 'worktree') })) }); - const environmentFile = path.join(directory, 'environment-solver.json'); - fs.writeFileSync(environmentFile, canonicalMathJson(projectMathematicsRuntimeEnvironment({ PATH: '/usr/bin:/bin', - DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages })), { mode: 0o400 }); - return { stateFile, directory, seed: () => seedSolverContinuation({ ...f.options, sourceRun: sourceStateFile, run: stateFile }) }; -} - -/** A new bootstrap workspace (its own repository) for the same problem, adding an owned theory module unless `change` alters it. */ -function rebootstrapped(f: ReturnType, change?: 'trusted' | 'frozen' | 'dropped' | 'unchanged') { - const workspace = path.join(f.root, 'workspace-extended'), project = path.join(workspace, f.projectRelative); - const added = change === 'unchanged' ? [] : ['Submission/Theory/T01.lean']; - fs.mkdirSync(path.join(project, 'Submission', 'Theory'), { recursive: true }); - for (const file of [...Object.keys(f.newState.problem.trustedFiles), ...f.newState.problem.ownedFiles]) - fs.writeFileSync(path.join(project, file), committedSource(f.workspace, f.base, `${f.projectRelative}/${file}`)); - for (const file of added) fs.writeFileSync(path.join(project, file), theoryModuleSource()); - if (change === 'trusted') fs.writeFileSync(path.join(project, 'Challenge.lean'), 'theorem challenge : 1 = 1 := rfl\n'); - if (change === 'frozen') fs.writeFileSync(path.join(project, 'Submission/Helpers.lean'), - 'namespace Submission.Helpers\nlemma frozen_seed : True := by trivial\nend Submission.Helpers\n'); - git(workspace, ['init', '--quiet']); const base = commit(workspace, 'Public solver baseline with theory modules'); - fs.appendFileSync(path.join(workspace, '.git/info/exclude'), `\n/${f.projectRelative}/.lake/\n/active-problem.json\n`); - const receipt = JSON.parse(fs.readFileSync(path.join(f.workspace, 'active-problem.json'), 'utf8')); - const receiptFile = path.join(workspace, 'active-problem.json'); - fs.writeFileSync(receiptFile, JSON.stringify({ ...receipt, workspaceRoot: workspace, projectRoot: project, activeProblemPath: receiptFile, - createdAt: 2, solverOwnedFiles: [...receipt.solverOwnedFiles.filter((file: string) => change !== 'dropped' || file !== 'Submission/Helpers.lean'), - ...added], ...(added.length ? { theoryModules: added.length } : {}) })); - const problem = readSolverProblem(workspace, receiptFile); - const directory = path.join(f.root, 'extended.json.runtime'); fs.mkdirSync(directory, { mode: 0o700 }); - for (const part of ['worktree', 'worktree-2']) git(workspace, ['worktree', 'add', '--quiet', '--detach', path.join(directory, part), base]); - const stateFile = path.join(directory, 'state.json'), worktree = path.join(directory, 'worktree'); - writeSolverRunState(stateFile, { ...f.newState, runId: 'extended-run', problem, worktree, - workers: f.newState.workers!.map((worker, index) => ({ ...worker, worktree: path.join(directory, index ? 'worktree-2' : 'worktree') })) }); - const environmentFile = path.join(directory, 'environment-solver.json'); - fs.writeFileSync(environmentFile, canonicalMathJson(projectMathematicsRuntimeEnvironment({ PATH: '/usr/bin:/bin', - DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages })), { mode: 0o400 }); - return { workspace, project, base, problem, directory, stateFile, worktree, - seed: () => seedSolverContinuation({ ...f.options, run: stateFile }) }; -} - -beforeEach(() => { - host.build.mockReset(); host.verify.mockReset(); host.prepare.mockReset(); host.dispose.mockReset(); host.resolvePackages.mockReset(); - host.resolvePackages.mockImplementation(() => host.packages); - host.dispose.mockResolvedValue(undefined); - host.prepare.mockResolvedValue({ environmentValue: 'fresh-seed-proof-environment', dispose: host.dispose, - stats: { files: 0, bytes: 0, publications: 1 } }); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => verifiedBatch(request, - { sessionId: 'fresh-seed', receipt: 'fresh-seed', checks: true })); -}); -describe('continuation of ordinary research no-progress checkpoints', () => { - it.each([false, true])('preserves seed-equal note attribution through two continuations without inventing it (acknowledged: %s)', async acknowledged => { - const notes = '\ufeffunfinished λ notes\r\n'; - const f = await researchCheckpointFixture('research', 1, notes, false, false, acknowledged); - const originalDraft = f.oldState.cooperation!.researchDrafts![f.task.id]; - expect(committedSource(f.oldState.worktree, originalDraft.seedCommit, 'RESEARCH.md')).toBe(notes); - const expected = acknowledged ? mathDigest(notes) : undefined; - expect(originalDraft.handoffNotesDigest).toBe(expected); - await f.seed(); await f.seed(); - const second = nextContinuation(f, f.stateFile, `notes-attribution-${acknowledged}-second`); await second.seed(); - for (const stateFile of [f.stateFile, second.stateFile]) { - const state = readSolverRunState(stateFile), cooperation = cooperationFor(f, state); - const worker = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }; - expect(state.cooperation!.researchDrafts![f.task.id].handoffNotesDigest).toBe(expected); - expect(taskDraftAttachments(stateFile).find(draft => draft.taskId === f.task.id)!.handoffNotesDigest).toBe(expected); - try { - await cooperation.restore(); - const action = await cooperation.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task' || action.task.id !== f.task.id) throw new Error('fixture_expected_notes_attribution_resume'); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - expect(state.cooperation!.researchDrafts![f.task.id].handoffNotesDigest).toBe(expected); - await cooperation.deliver(worker, action, commitSolverSources(state.problem, worker.worktree), true); - expect(state.cooperation!.researchDrafts![f.task.id].handoffNotesDigest).toBe(expected); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.proof).toBeUndefined(); - } finally { await cooperation.stop(); } - } - }); - - it('recovers changed legacy notes whose saved checkpoint has no attribution field', async () => { - const f = await researchCheckpointFixture('research', 1); - const draft = f.oldState.cooperation!.researchDrafts![f.task.id]; - delete draft.handoffNotesDigest; - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); - const state = readSolverRunState(f.stateFile), cooperation = cooperationFor(f, state); - const worker = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }; - expect(state.cooperation!.researchDrafts![f.task.id].handoffNotesDigest).toBeUndefined(); - try { - const action = await cooperation.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task' || action.task.id !== f.task.id) throw new Error('fixture_expected_legacy_notes_resume'); - expect(state.cooperation!.researchDrafts![f.task.id].handoffNotesDigest).toBe(mathDigest('Unchanged investigation.\n')); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.proof).toBeUndefined(); - } finally { await cooperation.stop(); } - }); - - it('retains task scheduling backoff through cold continuation when the worker slot is reset', async () => { - const f = await researchCheckpointFixture('research', 2); - const advisoryCheckpoint = { scope: mathDigest(canonicalMathJson({ kind: 'task', taskDigest: taskVersion(f.task) })), - noProgressStreak: 2, contentDigest: mathDigest('saved-source-notes-and-scratch') }; - f.oldState.cooperation!.researchCheckpoints![f.task.id].advisoryCheckpoint = advisoryCheckpoint; - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); await f.seed(); - const second = nextContinuation(f, f.stateFile, 'task-backoff-second'); await second.seed(); - for (const stateFile of [f.stateFile, second.stateFile]) { - const state = readSolverRunState(stateFile); - expect(state.cooperation!.researchCheckpoints![f.task.id].advisoryCheckpoint).toEqual(advisoryCheckpoint); - expect(state.workers![1]!.advisoryCheckpoint).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.proof).toBeUndefined(); - } - }); - - it.each(['research', 'sketch'] as const)('keeps a paused %s parked through repeated seeding and two more generations', async kind => { - const f = await researchCheckpointFixture(kind), historical = fs.readFileSync(f.sourceStateFile); - expect(f.checkpoint).toMatchObject({ count: 3, unchangedEvidenceCount: 3, paused: true }); - await f.seed(); await f.seed(); - const second = nextContinuation(f, f.stateFile, `paused-${kind}-second`); await second.seed(); await second.seed(); - const third = nextContinuation(f, second.stateFile, `paused-${kind}-third`); await third.seed(); await third.seed(); - for (const stateFile of [f.stateFile, second.stateFile, third.stateFile]) { - const state = readSolverRunState(stateFile), node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(state.cooperation!.researchCheckpoints![f.task.id]).toMatchObject(f.checkpoint); - expect(node).toMatchObject({ status: 'blocked', feedback: expect.stringContaining('math_research_checkpoint_unchanged'), attempts: 0 }); - expect(node.assignment!.workerId).toBe('prover-1'); - expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); expect(node.researchCompletion).toBeUndefined(); - expect(state.cooperation!.blockers!.find(blocker => blocker.id === state.cooperation!.researchCheckpoints![f.task.id].blockerId)) - .toMatchObject({ status: 'parked', evidenceStatus: 'advisory', mechanism: 'unchanged-research-checkpoint' }); - expect(state.workers![1]!.threadId).toBeUndefined(); expect(state.workers![1]!.advisoryCheckpoint).toBeUndefined(); - expect(state.cooperation!.researchDrafts![f.task.id]).toMatchObject({ suspended: true, - outputDigest: f.checkpoint.outputDigest, assignmentId: node.assignment!.assignmentId }); - expect(taskDraftAttachments(stateFile).find(draft => draft.taskId === f.task.id)!.archived).toBeUndefined(); - // Cold worker initialization is another workspace's output and must not revive the saved task. - fs.writeFileSync(path.join(state.workers![1]!.worktree, 'RESEARCH.md'), 'A different responsibility was initialized.'); - commitSolverSources(state.problem, state.workers![1]!.worktree); - const cooperation = cooperationFor(f, state); - try { (cooperation as any).refreshResearchCheckpoints(); } - finally { await cooperation.stop(); } - expect(node.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints![f.task.id]).toMatchObject(f.checkpoint); - } - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - }); - - it.each([null, ''] as const)('retains a two-checkpoint streak and %s notes so the next unchanged slice pauses', async notes => { - const f = await researchCheckpointFixture('research', 2, notes); - await f.seed(); await f.seed(); - const state = readSolverRunState(f.stateFile), cooperation = cooperationFor(f, state); - const worker = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }; - try { - expect(state.cooperation!.researchCheckpoints![f.task.id]).toMatchObject({ count: 2, paused: false }); - const action = await cooperation.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task' || action.task.id !== f.task.id) throw new Error('fixture_expected_checkpoint_resume'); - expect(fs.existsSync(path.join(worker.worktree, 'RESEARCH.md'))).toBe(notes !== null); - await cooperation.deliver(worker, action, commitSolverSources(state.problem, worker.worktree), true); - expect(state.cooperation!.researchCheckpoints![f.task.id]).toMatchObject({ count: 3, paused: true, - unchangedEvidenceCount: 3, outputDigest: f.checkpoint.outputDigest }); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.status).toBe('blocked'); - } finally { await cooperation.stop(); } - }); - - it.each(['task-version', 'environment', 'saved-output', 'relevant-delivery'] as const) - ('reopens a prior pause when %s changes before cold capture', async change => { - const f = await researchCheckpointFixture(), state = f.oldState; - const node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - if (change === 'task-version') node.task = { ...node.task, revision: 1 }; - if (change === 'environment') state.environmentDigest = mathDigest('prior-different-environment'); - if (change === 'saved-output') { - const worker = state.workers![1]!; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'A new saved task draft.'); - const commit = commitSolverSources(state.problem, worker.worktree), cooperation = cooperationFor(f, state); - try { cooperation.retainContextDraft({ ...worker, ownedFiles: state.problem.ownedFiles }, - { kind: 'task', task: node.task, assignment: node.assignment! }, commit); } - finally { await cooperation.stop(); } - } - if (change === 'relevant-delivery') state.cooperation!.deliveries!.push({ id: 'new-advice', producer: 'solver', - taskId: node.task.id, taskDigest: taskVersion(node.task), kind: 'research', status: 'advisory', - statement: '', premises: [], dependencies: [], remainingObligations: [node.task.id], - summary: 'New evidence from an independent worker', findingDigest: mathDigest('new-evidence'), evidenceRefs: [], createdAt: 5 }); - writeSolverRunState(f.sourceStateFile, state); - await f.seed(); await f.seed(); - const seeded = readSolverRunState(f.stateFile); - expect(seeded.cooperation!.tasks.find(node => node.task.id === f.task.id)!.status).toBe('pending'); - expect(seeded.cooperation!.researchCheckpoints?.[f.task.id]).toBeUndefined(); - }); - - it('ignores unrelated advisory deliveries and reopens on a new relevant delivery during live recovery', async () => { - const f = await researchCheckpointFixture(), other: CooperativeTask = { id: 'unrelated', kind: 'research', - objective: 'A separate investigation', dependsOn: [], revision: 0, status: 'paused' }; - f.oldState.cooperation!.tasks.push({ task: other, status: 'pending', attempts: 0 }); - f.oldState.cooperation!.deliveries!.push({ id: 'unrelated-advice', producer: 'solver', taskId: other.id, - taskDigest: taskVersion(other), kind: 'research', status: 'advisory', statement: '', premises: [], dependencies: [], - remainingObligations: [], summary: 'Unrelated notes changed', findingDigest: mathDigest('unrelated'), evidenceRefs: [], createdAt: 5 }); - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); await f.seed(); - const state = readSolverRunState(f.stateFile), cooperation = cooperationFor(f, state); - try { - expect(state.cooperation!.researchCheckpoints![f.task.id]).toMatchObject(f.checkpoint); - state.cooperation!.deliveries!.push({ ...state.cooperation!.deliveries![0]!, id: 'related-advice', - taskId: f.task.id, taskDigest: taskVersion(f.task), findingDigest: mathDigest('new-local-evidence') }); - (cooperation as any).refreshResearchCheckpoints(); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints![f.task.id]).toBeUndefined(); - } finally { await cooperation.stop(); } - }); - - it.each([false, true])('compares effective dependency findings after reconstruction (changed=%s)', async changed => { - const f = await researchCheckpointFixture('research', 3, 'Unchanged investigation.', true); - if (changed) { - f.oldState.cooperation!.tasks.find(node => node.task.id === 'input_research')!.finding = 'A different input condition.'; - publishCompletedResearch(f.oldState, 'input_research', 'new-input-finding'); - writeSolverRunState(f.sourceStateFile, f.oldState); - } - await f.seed(); await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.status).toBe(changed ? 'pending' : 'blocked'); - if (changed) expect(state.cooperation!.researchCheckpoints?.[f.task.id]).toBeUndefined(); - else expect(state.cooperation!.researchCheckpoints![f.task.id]).toMatchObject(f.checkpoint); - }); - - it('retains advisory source metadata without changing a paused task input across continuations', async () => { - const f = await researchCheckpointFixture('research', 3, 'Unchanged investigation.', true, true); - const metadata = f.oldState.cooperation!.deliveries![0]!; - await f.seed(); await f.seed(); - const second = nextContinuation(f, f.stateFile, 'source-metadata-checkpoint'); await second.seed(); await second.seed(); - for (const stateFile of [f.stateFile, second.stateFile]) { - const state = readSolverRunState(stateFile), input = state.cooperation!.deliveries!.find(delivery => delivery.id === metadata.id)!; - expect(input.sourceUses).toEqual(metadata.sourceUses); expect(input.searchCheckpoint).toEqual(metadata.searchCheckpoint); - expect(input.status).toBe('advisory'); expect(input.evidence).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints![f.task.id]).toMatchObject(f.checkpoint); - expect(state.cooperation!.proofSearchRecords).toBeUndefined(); - } - }); - - it('loads an older frozen source with no checkpoint field without inventing a pause', async () => { - const f = await researchCheckpointFixture(), rename = fs.renameSync; - const fail = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (String(to) === path.join(f.directory, 'continuation.json')) throw new Error('freeze legacy checkpoint fixture'); - return rename(from, to); - }); - await expect(f.seed()).rejects.toThrow('freeze legacy checkpoint fixture'); fail.mockRestore(); - const sourceFile = path.join(f.directory, 'continuation-seed-source.json'); - const source = JSON.parse(fs.readFileSync(sourceFile, 'utf8')); delete source.researchCheckpoints; - fs.chmodSync(sourceFile, 0o600); fs.writeFileSync(sourceFile, canonicalMathJson(source)); fs.chmodSync(sourceFile, 0o400); - await f.seed(); await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)!.status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints).toBeUndefined(); - expect(state.cooperation!.researchDrafts![f.task.id].outputDigest).toBe(f.checkpoint.outputDigest); - }); -}); - -describe('continuation of per-task saved drafts', () => { - it('restores the same reviewer\'s notes and complete probe across cold continuation without inheriting a verdict', async () => { - const notes = '\ufeffReview only: searched the finite case, no uniform estimate found.\r\n' + - 'Saved .scratch/tmp/Probe1.lean; command: lake env lean .scratch/tmp/Probe1.lean\r\n' + - '```lean\r\nexample : True := by trivial\r\n```\r\nObserved: local check succeeds; the main gap remains.\r\n'; - const f = await suspendedTaskDraftFixture('feasibility', notes, false); - await f.seed(); - const second = nextContinuation(f, f.stateFile, 'feasibility-next'); await second.seed(); - const state = readSolverRunState(second.stateFile), node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(node.status).toBe('pending'); expect(node.researchCompletion).toBeUndefined(); - expect(node.assignment?.feasibilityInputDigest).toBe(f.draftAssignment.feasibilityInputDigest); - expect(taskDraftAttachments(second.stateFile)).toContainEqual(expect.objectContaining({ taskId: f.task.id, - notes, commit: f.draftCommit, feasibilityInputDigest: f.draftAssignment.feasibilityInputDigest })); - const cooperative = cooperationFor(f, state), peer = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }; - try { - await cooperative.restore(); - const action = await cooperative.next(peer, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_expected_feasibility_review'); - expect(action.task.id).toBe(f.task.id); - expect(fs.readFileSync(path.join(peer.worktree, 'RESEARCH.md'))).toEqual(Buffer.from(notes)); - expect(node.finding).toBeUndefined(); expect(node.proof).toBeUndefined(); expect(state.check).toBeUndefined(); - } finally { await cooperative.stop(); } - }); - - it('archives feasibility handoff notes when the canonical input changes before cold continuation', async () => { - const f = await suspendedTaskDraftFixture('feasibility', 'OLD_REVIEW_NOTES\n', false); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('end Submission.Helpers', 'lemma newer : True := by trivial\nend Submission.Helpers')); - f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Advance canonical review input'); - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); - const state = readSolverRunState(f.stateFile), node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(node.assignment).toBeUndefined(); expect(node.status).toBe('pending'); - expect(state.cooperation!.researchDrafts?.[f.task.id]).toBeUndefined(); - expect(taskDraftAttachments(f.stateFile)).toContainEqual(expect.objectContaining({ taskId: f.task.id, - notes: 'OLD_REVIEW_NOTES\n', commit: f.draftCommit })); - expect(node.researchCompletion).toBeUndefined(); expect(node.finding).toBeUndefined(); - }); - - it('resumes a scoped feasibility draft after unrelated canonical additions in cold continuation', async () => { - const notes = 'RETAINED_REVIEW_NOTES\n'; - const f = await suspendedTaskDraftFixture('feasibility', notes, false, true); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('end Submission.Helpers', 'lemma unrelated : True := by trivial\nend Submission.Helpers')); - f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Add unrelated helper'); - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); - - const state = readSolverRunState(f.stateFile), node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(node.assignment).toBeDefined(); - expect(state.cooperation!.researchDrafts?.[f.task.id]).toMatchObject({ commit: f.draftCommit, suspended: true }); - const cooperative = cooperationFor(f, state), peer = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }; - try { - await cooperative.restore(); - const action = await cooperative.next(peer, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_expected_feasibility_review'); - expect(action.task.id).toBe(f.task.id); - expect(action.assignment.feasibilityInputDigest).not.toBe(f.draftAssignment.feasibilityInputDigest); - expect(fs.readFileSync(path.join(peer.worktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8')).toContain('lemma unrelated'); - expect(fs.readFileSync(path.join(peer.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - expect(node.finding).toBeUndefined(); expect(node.proof).toBeUndefined(); - } finally { await cooperative.stop(); } - }); - - it('preserves all 17 UTF-8 drafts above 16 MB through bounded attachments and another ordinary continuation', async () => { - const f = fixture(), peer = f.oldState.workers![1]!; - peer.role = 'engineer'; f.newState.workers![1]!.role = 'engineer'; - const drafts: CooperativeTask[] = Array.from({ length: 17 }, (_, index) => ({ id: `large_draft_${index}`, - kind: 'research', objective: `Investigate saved route ${index}`, dependsOn: [], revision: 0, ownerId: peer.id })); - const goal = f.oldState.cooperation!.tasks.find(node => node.task.id === 'goal')!; - goal.task = { ...goal.task, dependsOn: [...goal.task.dependsOn, ...drafts.map(task => task.id)] }; - setTaskStatus(goal, 'pending', 'reconstructed'); goal.assignment = undefined; - git(peer.worktree, ['reset', '--hard', f.oldState.cooperation!.canonicalCommit!]); - const file = path.join(peer.worktree, f.projectRelative, 'Submission/Helpers.lean'); - fs.appendFileSync(file, `\n/- ${'草'.repeat(320_000)} -/\n`); - const notes = 'Retained UTF-8 draft λ\r\n'; fs.writeFileSync(path.join(peer.worktree, 'RESEARCH.md'), notes); - const draftSource = fs.readFileSync(file, 'utf8'), version = commitSolverSources(f.oldState.problem, peer.worktree); - const retainer = cooperationFor(f, f.oldState), descriptor = { ...peer, ownedFiles: f.oldState.problem.ownedFiles }; - try { - for (const task of drafts) { - const assignment = { taskId: task.id, taskDigest: taskVersion(task), workerId: peer.id, - seedCommit: f.oldState.cooperation!.canonicalCommit!, canonicalCommit: f.oldState.cooperation!.canonicalCommit!, - assignmentId: `saved-${task.id}` }; - f.oldState.cooperation!.tasks.push({ task, assignment, status: 'running', attempts: 1 }); - const action = { kind: 'task' as const, task, assignment }; - retainer.retainContextDraft(descriptor, action, version); retainer.interrupted(descriptor, action); - } - } finally { await retainer.stop(); } - writeSolverRunState(f.sourceStateFile, f.oldState); writeSolverRunState(f.stateFile, f.newState); - const historicalState = fs.readFileSync(f.sourceStateFile); - const first = await f.seed(), state = readSolverRunState(f.stateFile); - const snapshot = readContinuationSnapshot(path.join(f.directory, 'continuation.json'), state.continuationDigest!); - const chunks = snapshot.manifest.attachments.filter(item => item.id.startsWith('seed-task-drafts')); - expect(chunks.map(item => item.id)).toEqual(['seed-task-drafts', 'seed-task-drafts-2']); - expect(chunks.every(item => item.bytes <= MAX_CONTINUATION_ATTACHMENT_BYTES)).toBe(true); - const saved = taskDraftAttachments(f.stateFile), text = canonicalMathJson(saved); - expect(saved.map(draft => draft.taskId).sort()).toEqual(drafts.map(task => task.id).sort()); - expect(text.length).toBeLessThan(MAX_CONTINUATION_ATTACHMENT_BYTES); - expect(Buffer.byteLength(text)).toBeGreaterThan(MAX_CONTINUATION_ATTACHMENT_BYTES); - for (const draft of saved) { - expect(draft).toMatchObject({ commit: version, notes, source: { runId: f.oldState.runId, stateFile: f.sourceStateFile } }); - expect(mathDigest(draft.sources['Submission/Helpers.lean'])).toBe(mathDigest(draftSource)); - } - expect(Object.keys(state.cooperation!.researchDrafts!)).toHaveLength(17); - expect((await f.seed()).snapshotDigest).toBe(first.snapshotDigest); - const next = nextContinuation(f, f.stateFile, 'large-drafts-next'); await next.seed(); - const restored = readSolverRunState(next.stateFile), cooperative = cooperationFor(f, restored); - const worker = { ...restored.workers![1]!, ownedFiles: restored.problem.ownedFiles }; - const identities = (items: typeof saved) => items.map(({ suspended: _suspended, ...draft }) => mathDigest(canonicalMathJson(draft))); - expect(identities(taskDraftAttachments(next.stateFile))).toEqual(identities(saved)); - try { - await cooperative.restore(); - const action = await cooperative.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_expected_recovered_large_draft'); - expect(drafts.map(task => task.id)).toContain(action.task.id); - expect(mathDigest(fs.readFileSync(path.join(worker.worktree, f.projectRelative, 'Submission/Helpers.lean')))).toBe(mathDigest(draftSource)); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - const node = restored.cooperation!.tasks.find(node => node.task.id === action.task.id)!; - expect(node.status).toBe('running'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - expect(node.researchCompletion).toBeUndefined(); - } finally { await cooperative.stop(); } - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historicalState); - }, 90_000); - - it.each(['research', 'sketch'] as const)('restores suspended %s work through successive continuations and normal delivery', async kind => { - const f = await suspendedTaskDraftFixture(kind), historicalState = fs.readFileSync(f.sourceStateFile); - expect(f.oldState.cooperation!.researchDrafts![f.task.id].suspended).toBe(true); - expect(fs.readFileSync(path.join(f.oldState.workers![1]!.worktree, 'RESEARCH.md'), 'utf8')).toBe('CURRENT_ROUTE_FINDING\n'); - const first = await f.seed(), seeded = readSolverRunState(f.stateFile); - const assignment = seeded.cooperation!.tasks.find(node => node.task.id === f.task.id)!.assignment!; - expect(assignment.assignmentId).not.toBe(f.draftAssignment.assignmentId); - expect(seeded.cooperation!.researchDrafts![f.task.id]).toMatchObject({ commit: f.draftCommit, suspended: true, - assignmentId: assignment.assignmentId, seedCommit: f.draftAssignment.seedCommit }); - expect(Object.keys(seeded.cooperation!.researchDrafts!)).toHaveLength(2); - expect(taskDraftAttachments(f.stateFile)).toContainEqual(expect.objectContaining({ taskId: f.task.id, - taskDigest: taskVersion(f.task), notes: f.draftNotes, commit: f.draftCommit, - seedCommit: f.draftAssignment.seedCommit, canonicalCommit: f.draftAssignment.canonicalCommit, - source: expect.objectContaining({ runId: f.oldState.runId, stateFile: f.sourceStateFile }), - sources: expect.objectContaining({ 'Submission/Helpers.lean': f.draftSource }) })); - expect((await f.seed()).snapshotDigest).toBe(first.snapshotDigest); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.find(node => node.task.id === f.task.id)!.assignment).toEqual(assignment); - const second = nextContinuation(f, f.stateFile, `saved-${kind}-second`); await second.seed(); await second.seed(); - const secondState = readSolverRunState(second.stateFile), cooperative = cooperationFor(f, secondState); - const worker = secondState.workers![1]!, descriptor = { ...worker, ownedFiles: secondState.problem.ownedFiles }; - try { - await cooperative.restore(); - const action = await cooperative.next(descriptor, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_expected_recovered_task'); - expect(action.task.id).toBe(f.task.id); - expect(fs.readFileSync(path.join(worker.worktree, f.projectRelative, 'Submission/Helpers.lean'))) - .toEqual(Buffer.from(f.draftSource)); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'))).toEqual(Buffer.from(f.draftNotes!)); - expect(secondState.cooperation!.tasks.find(node => node.task.id === f.task.id)).toMatchObject({ status: 'running' }); - expect(secondState.cooperation!.tasks.find(node => node.task.id === f.task.id)!.proof).toBeUndefined(); - expect(secondState.cooperation!.tasks.find(node => node.task.id === f.task.id)!.researchCompletion).toBeUndefined(); - cooperative.interrupted(descriptor, action); - writeSolverRunState(second.stateFile, secondState); - } finally { await cooperative.stop(); } - const third = nextContinuation(f, second.stateFile, `saved-${kind}-third`); await third.seed(); - const thirdState = readSolverRunState(third.stateFile), resumed = cooperationFor(f, thirdState); - const peer = { ...thirdState.workers![1]!, ownedFiles: thirdState.problem.ownedFiles }; - try { - await resumed.restore(); - const action = await resumed.next(peer, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_expected_recovered_task'); - expect(action.task.id).toBe(f.task.id); - expect(fs.readFileSync(path.join(peer.worktree, 'RESEARCH.md'))).toEqual(Buffer.from(f.draftNotes!)); - const context = resumed.contextState(action, peer); - action.assignment.researchBasis = captureResearchBasis(action.task, { problemReceiptDigest: thirdState.problem.receiptDigest, - environmentDigest: thirdState.environmentDigest, retrievalDigest: thirdState.retrievalDigest, knowledgeDigest: thirdState.knowledgeDigest, - sourceDigest: researchSourceDigest(Object.fromEntries(thirdState.problem.ownedFiles.map(file => [file, - committedSource(peer.worktree, action.assignment.seedCommit, `${f.projectRelative}/${file}`)]))), - tasks: context.tasks, deliveries: context.deliveries }); - // Finish the advisory report within its ordinary source scope. The unfinished - // supporting code remains independently recoverable in the frozen task draft. - for (const file of thirdState.problem.ownedFiles) fs.writeFileSync(path.join(peer.worktree, f.projectRelative, file), - committedSource(peer.worktree, action.assignment.seedCommit, `${f.projectRelative}/${file}`)); - await resumed.deliver(peer, action, commitSolverSources(thirdState.problem, peer.worktree)); - const completed = thirdState.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(completed.status, completed.feedback).toBe('completed'); expect(completed.researchCompletion).toBeDefined(); - expect(completed.integratedCheck).toBeUndefined(); expect(thirdState.check).toBeUndefined(); - } finally { await resumed.stop(); } - expect(taskDraftAttachments(third.stateFile).filter(draft => draft.taskId === f.task.id)).toHaveLength(1); - expect(taskDraftAttachments(third.stateFile).find(draft => draft.taskId === f.task.id)!.source.runId).toBe(f.oldState.runId); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historicalState); - }, 45_000); - - it.each(['goal', 'lemma'] as const)('recomputes a %s connection assignment and retains its draft across two generations', async kind => { - const f = await suspendedTaskDraftFixture(kind); await f.seed(); - const state = readSolverRunState(f.stateFile), node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(node.status).toBe('pending'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - expect(taskConnectionCheckCurrent(node.task, node.assignment!, state.cooperation!.tasks, - { environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest })).toBe(true); - expect(node.assignment!.connectionCheck!.assignmentId).not.toBe(f.draftAssignment.assignmentId); - await f.seed(); - const second = nextContinuation(f, f.stateFile, `saved-${kind}-connection`); await second.seed(); - const restored = readSolverRunState(second.stateFile), cooperative = cooperationFor(f, restored); - const worker = { ...restored.workers![1]!, ownedFiles: restored.problem.ownedFiles }; - try { - await cooperative.restore(); - const action = await cooperative.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_expected_recovered_task'); - expect(action.task.id).toBe(f.task.id); - expect(taskConnectionCheckCurrent(action.task, action.assignment, restored.cooperation!.tasks, - { environmentDigest: restored.environmentDigest, problemReceiptDigest: restored.problem.receiptDigest })).toBe(true); - expect(restored.cooperation!.researchDrafts![f.task.id].assignmentId).toBe(action.assignment.assignmentId); - expect(fs.readFileSync(path.join(worker.worktree, f.projectRelative, 'Submission/Helpers.lean'))) - .toEqual(Buffer.from(f.draftSource)); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'))).toEqual(Buffer.from(f.draftNotes!)); - expect(restored.cooperation!.tasks.find(node => node.task.id === f.task.id)!.proof).toBeUndefined(); - cooperative.interrupted(worker, action); writeSolverRunState(second.stateFile, restored); - } finally { await cooperative.stop(); } - const third = nextContinuation(f, second.stateFile, `saved-${kind}-connection-again`); await third.seed(); - expect(readSolverRunState(third.stateFile).cooperation!.researchDrafts![f.task.id]).toMatchObject({ commit: f.draftCommit, suspended: true }); - expect(taskDraftAttachments(third.stateFile).find(draft => draft.taskId === f.task.id)!.source.runId).toBe(f.oldState.runId); - }, 45_000); - - it.each([null, ''])('preserves a notes-only snapshot with notes %j instead of another task workspace', async notes => { - const f = await suspendedTaskDraftFixture('research', notes, false); await f.seed(); - expect(f.oldState.cooperation!.researchDrafts![f.task.id].artifacts.artifacts).toEqual([]); - const second = nextContinuation(f, f.stateFile, notes === null ? 'missing-draft-notes' : 'empty-draft-notes'); await second.seed(); - const state = readSolverRunState(second.stateFile), cooperative = cooperationFor(f, state); - const worker = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }, noteFile = path.join(worker.worktree, 'RESEARCH.md'); - fs.writeFileSync(noteFile, 'UNRELATED_WORKSPACE_NOTES'); commitSolverSources(state.problem, worker.worktree); - try { - await cooperative.restore(); - const action = await cooperative.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind === 'task' && action.task.id).toBe(f.task.id); - expect(fs.existsSync(noteFile)).toBe(notes !== null); - if (notes !== null) expect(fs.readFileSync(noteFile)).toEqual(Buffer.from(notes)); - expect(taskDraftAttachments(second.stateFile).find(draft => draft.taskId === f.task.id)!.notes).toBe(notes); - } finally { await cooperative.stop(); } - }); - - it.each(['environment', 'task-version'] as const)('keeps a changed %s snapshot advisory through subsequent continuations', async change => { - const f = await suspendedTaskDraftFixture(), originalEnvironment = f.newState.environmentDigest; - if (change === 'environment') { - f.newState.environmentDigest = mathDigest('changed-draft-environment'); writeSolverRunState(f.stateFile, f.newState); - } else { - const node = f.oldState.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - node.task = { ...node.task, revision: node.task.revision + 1 }; writeSolverRunState(f.sourceStateFile, f.oldState); - } - await f.seed(); - const state = readSolverRunState(f.stateFile), node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(node.status).toBe('pending'); expect(node.assignment).toBeUndefined(); - expect(state.cooperation!.researchDrafts?.[f.task.id]).toBeUndefined(); - expect(taskDraftAttachments(f.stateFile)).toContainEqual(expect.objectContaining({ taskId: f.task.id, notes: f.draftNotes, - commit: f.draftCommit, taskDigest: taskVersion(f.task), sources: expect.objectContaining({ 'Submission/Helpers.lean': f.draftSource }) })); - f.newState.environmentDigest = originalEnvironment; - const second = nextContinuation(f, f.stateFile, `advisory-draft-${change}`); await second.seed(); - expect(readSolverRunState(second.stateFile).cooperation!.researchDrafts?.[f.task.id]).toBeUndefined(); - expect(taskDraftAttachments(second.stateFile)).toContainEqual(expect.objectContaining({ taskId: f.task.id, - archived: true, notes: f.draftNotes, commit: f.draftCommit })); - }); - - it('keeps newer canonical proofs while recovering old notes and retaining source evidence', async () => { - const f = await suspendedTaskDraftFixture(); - const canonicalSource = helpers.replace('end Submission.Helpers', 'lemma newer_canonical : True := by trivial\nend Submission.Helpers'); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), canonicalSource); - f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Advance canonical after saved draft'); - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - const state = readSolverRunState(f.stateFile), cooperative = cooperationFor(f, state); - const worker = { ...state.workers![1]!, ownedFiles: state.problem.ownedFiles }; - try { - await cooperative.restore(); - const action = await cooperative.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_expected_recovered_task'); - expect(action.task.id).toBe(f.task.id); - const source = fs.readFileSync(path.join(worker.worktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8'); - expect(source).toContain('newer_canonical'); expect(source).not.toContain('suspended_support'); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'))).toEqual(Buffer.from(f.draftNotes!)); - expect(fs.readFileSync(path.join(state.worktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8')).toBe(canonicalSource); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ taskId: f.task.id, commit: f.draftCommit, - kind: 'progress', status: 'advisory', artifacts: expect.objectContaining({ scope: 'advisory-unverified' }) })); - expect(action.assignment.canonicalCommit).toBe(state.cooperation!.canonicalCommit); - cooperative.interrupted(worker, action); writeSolverRunState(f.stateFile, state); - } finally { await cooperative.stop(); } - const second = nextContinuation(f, f.stateFile, 'newer-canonical-draft'); await second.seed(); - expect(fs.readFileSync(path.join(second.directory, 'worktree', f.projectRelative, 'Submission/Helpers.lean'), 'utf8')).toBe(canonicalSource); - expect(taskDraftAttachments(second.stateFile)).toContainEqual(expect.objectContaining({ taskId: f.task.id, - commit: f.draftCommit, archived: true, notes: f.draftNotes })); - expect(readSolverRunState(second.stateFile).cooperation!.researchDrafts![f.task.id].commit).not.toBe(f.draftCommit); - }); -}); -afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); - -describe('explicit prepared-run continuation initialization', () => { - it('preserves a source that failed before its first plan and resumes ordinary initial planning', async () => { - const f = initialPlanningFixture(), before = fs.readFileSync(f.sourceStateFile); - const first = await f.seed(), state = readSolverRunState(f.stateFile); - expect(first).toMatchObject({ stage: 'complete', candidates: [], checked: [], failed: [] }); - expect(host.verify).not.toHaveBeenCalled(); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(before); - expect(state.turns).toBe(0); - expect(state.solveStartedAt).toBeUndefined(); - expect(state.check).toBeUndefined(); - expect(state.cooperation).toMatchObject({ tasks: [], history: [], deliveries: [], planEdited: false }); - expect(state.cooperation!.planVersion).toBeUndefined(); - expect(fs.readFileSync(path.join(f.worktree, f.projectRelative, 'Submission.lean'), 'utf8')).toBe(original); - const source = JSON.parse(fs.readFileSync(path.join(f.directory, 'continuation-seed-source.json'), 'utf8')); - expect(source).toMatchObject({ initialPlanning: true, plan: { tasks: [], groups: [] } }); - expect(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, 'seed-recovery-guide').text) - .toContain('Lead still owes the first plan covering every original target'); - const draft = JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, 'draft-prover-1').text); - expect(draft.notes).toBe(f.notes); - expect(draft.sources['Submission/Helpers.lean']).toContain('by sorry'); - const again = await f.seed(); - expect(again.snapshotDigest).toBe(first.snapshotDigest); - const resumed = readSolverRunState(f.stateFile), cooperative = cooperationFor(f, resumed); - try { - await cooperative.restore(); - const action = await cooperative.next(resumed.workers![0], { maxTurns: 10, remainingMs: 60_000 }); - expect(action).toMatchObject({ kind: 'lead', initialPlanNonce: expect.any(String) }); - expect(resumed.cooperation!.initialPlanPublication).toBeUndefined(); - expect(resumed.cooperation!.tasks).toEqual([]); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it('preserves a started initial-planning source with three Lead turns and idle peers', async () => { - const f = startedInitialPlanningFixture(), historical = fs.readFileSync(f.sourceStateFile); - const originalSources = f.oldState.workers!.flatMap(worker => ['RESEARCH.md', - ...f.oldState.problem.ownedFiles.map(file => path.join(f.projectRelative, file))] - .map(file => path.join(worker.worktree, file)).filter(file => fs.existsSync(file))) - .map(file => [file, fs.readFileSync(file)] as const); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report).toMatchObject({ stage: 'complete', candidates: [], checked: [], failed: [] }); - expect(host.verify).not.toHaveBeenCalled(); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - for (const [file, bytes] of originalSources) expect(fs.readFileSync(file)).toEqual(bytes); - expect(state.turns).toBe(0); expect(state.usage).toBeUndefined(); - expect(state.workers!.every(worker => worker.turns === 0 && !worker.threadId && !worker.usage)).toBe(true); - expect(state.cooperation).toMatchObject({ tasks: [], planEdited: false }); - expect(state.cooperation!.planVersion).toBeUndefined(); - expect(fs.readFileSync(path.join(f.worktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8')).toBe(emptyHelpers); - const source = JSON.parse(fs.readFileSync(path.join(f.directory, 'continuation-seed-source.json'), 'utf8')); - const { receipts: _receipts, ...requestCounts } = f.requests; - expect(source).toMatchObject({ initialPlanning: true, source: { runId: 'old-run' }, plan: { tasks: [], groups: [] }, - history: { activity: { turns: 3, dispatchCounts: { planning: 3 }, usage: f.usage, - workers: [expect.objectContaining({ id: 'solver', turns: 3, usage: f.usage, - usageAccounting: f.accounting, requestUsageAccounting: requestCounts }), - expect.objectContaining({ id: 'researcher-1', turns: 0 }), expect.objectContaining({ id: 'researcher-2', turns: 0 }), - expect.objectContaining({ id: 'engineer', turns: 0 })] } } }); - expect(source.history.deliveries).toContainEqual(expect.objectContaining(f.savedDraft)); - const snapshot = path.join(f.directory, 'continuation.json'); - const history = JSON.parse(readContinuationPage(snapshot, state.continuationDigest, 'seed-history').text); - expect(history.history.activity.turns).toBe(3); - expect(history.history.activity.workers[0].requestUsageAccounting).toEqual(requestCounts); - expect(history.history.activity.workers[0]).not.toHaveProperty('threadId'); - expect(history.history.activity.workers[0]).not.toHaveProperty('previousThreadIds'); - const draft = JSON.parse(readContinuationPage(snapshot, state.continuationDigest, 'draft-solver').text); - expect(draft.notes).toBe(f.leadNotes); expect(draft.sources['Submission/Helpers.lean']).toBe(f.leadDraft); - const firstDigest = report.snapshotDigest; - expect((await f.seed()).snapshotDigest).toBe(firstDigest); - const resumed = readSolverRunState(f.stateFile), cooperative = cooperationFor(f, resumed); - try { - await cooperative.restore(); - expect(await cooperative.next(resumed.workers![0], { maxTurns: 10, remainingMs: 60_000 })) - .toMatchObject({ kind: 'lead', initialPlanNonce: expect.any(String) }); - expect(resumed.cooperation!.tasks).toEqual([]); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it('captures a preserved initial Lead draft read-only without initializing or checking the destination', () => { - const f = startedInitialPlanningFixture(), historical = fs.readFileSync(f.sourceStateFile); - const prepared = fs.readFileSync(f.stateFile); - const source = captureSolverContinuationSource(f.sourceStateFile, f.stateFile, f.newState); - expect(source).toMatchObject({ initialPlanning: true, candidateIds: [], plan: { tasks: [], groups: [] }, - history: { deliveries: [f.savedDraft], activity: { turns: 3 } } }); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - expect(fs.readFileSync(f.stateFile)).toEqual(prepared); - expect(fs.existsSync(path.join(f.directory, 'continuation-seed-source.json'))).toBe(false); - expect(host.verify).not.toHaveBeenCalled(); expect(host.prepare).not.toHaveBeenCalled(); - }); - - it.each(['proof', 'verified', 'accepted', 'conditional', 'external-producer', 'task-bound', 'dependency', - 'remaining-obligation', 'evidence', 'evidence-reference', 'artifact', 'foreign-commit', 'ordinary-progress', - 'different-statement', 'different-premises'] as const) - ('refuses a delivery with graph or proof authority in initial planning: %s', async kind => { - const f = startedInitialPlanningFixture(), delivery = f.oldState.cooperation!.deliveries![0]; - if (kind === 'proof') delivery.kind = 'proof'; - if (kind === 'verified' || kind === 'accepted' || kind === 'conditional') delivery.status = kind; - if (kind === 'external-producer') delivery.producer = 'researcher-1'; - if (kind === 'task-bound') { delivery.taskId = 'removed-task'; delivery.taskDigest = 'a'.repeat(64); } - if (kind === 'dependency') delivery.dependencies = [{ taskId: 'removed-task', taskDigest: 'a'.repeat(64) }]; - if (kind === 'remaining-obligation') delivery.remainingObligations = ['removed-task']; - if (kind === 'evidence') delivery.evidence = { passed: true, verification: { status: 'kernel_verified', - targetCommit: f.base, results: [{ receiptId: 'historical-proof' }] } }; - if (kind === 'evidence-reference') delivery.evidenceRefs = ['historical-proof']; - if (kind === 'artifact') delivery.artifacts = { commit: f.base, artifacts: [] } as typeof delivery.artifacts; - if (kind === 'foreign-commit') delivery.commit = f.base[0] === 'a' ? 'b'.repeat(40) : 'a'.repeat(40); - if (kind === 'ordinary-progress') delivery.summary = 'Accepted work from a previous task.'; - if (kind === 'different-statement') delivery.statement = 'A prior typed task, not the initial problem.'; - if (kind === 'different-premises') delivery.premises = ['A prior dependency.']; - writeSolverRunState(f.sourceStateFile, f.oldState); - const historical = fs.readFileSync(f.sourceStateFile); - await expect(f.seed()).rejects.toThrow('math_plan_invalid'); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - expect(fs.existsSync(path.join(f.directory, 'continuation-seed-source.json'))).toBe(false); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it.each(['turns', 'worker-turns', 'started-request', 'publication', 'history', 'partial-plan']) - ('does not treat a previously active or incomplete graph as unstarted planning: %s', async kind => { - const f = initialPlanningFixture(); - if (kind === 'turns') f.oldState.turns = 1; - if (kind === 'worker-turns') f.oldState.workers![0].turns = 1; - if (kind === 'started-request') f.oldState.workers![0].usageAccounting = - { startedTurns: 1, reportedTurns: 0, pending: true, incomplete: true }; - if (kind === 'publication') f.oldState.cooperation!.initialPlanPublication = { nonce: 'old-publication', - file: `DELIVERIES-${mathDigest('old-publication')}.jsonl`, offset: 0, - eventDigest: mathDigest('old-event'), baseVersion: 'old-base', planVersion: 'old-plan', acceptedAt: 1 }; - if (kind === 'history') f.oldState.cooperation!.history = [{ task: f.tasks[0] }]; - if (kind === 'partial-plan') f.oldState.cooperation!.tasks = [{ task: f.tasks[0], status: 'pending', attempts: 0 }]; - writeSolverRunState(f.sourceStateFile, f.oldState); - await expect(f.seed()).rejects.toThrow(kind === 'partial-plan' ? 'math_plan_incomplete_original_coverage' : 'math_plan_invalid'); - expect(host.verify).not.toHaveBeenCalled(); - expect(fs.existsSync(path.join(f.directory, 'continuation-seed-source.json'))).toBe(false); - }); - - it.each(['publication', 'edited', 'edit-history', 'history', 'partial-plan', 'nonempty-version', - 'missing-version', 'peer-turn', 'peer-request', 'lead-task', 'nonplanning-turn', 'accepted-candidate', - 'proof-receipt', 'changed-canonical'] as const) - ('does not reinterpret a started accepted, incomplete or inconsistent graph as initial planning: %s', async kind => { - const f = startedInitialPlanningFixture(), cooperation = f.oldState.cooperation!; - if (kind === 'publication') cooperation.initialPlanPublication = { nonce: 'old-publication', - file: `DELIVERIES-${mathDigest('old-publication')}.jsonl`, offset: 0, - eventDigest: mathDigest('old-event'), baseVersion: 'old-base', planVersion: 'old-plan', acceptedAt: 1 }; - if (kind === 'edited') cooperation.planEdited = true; - if (kind === 'edit-history') cooperation.edits = [{ id: 'old-edit', status: 'applied' }] as typeof cooperation.edits; - if (kind === 'history') cooperation.history = [{ task: f.tasks[0] }]; - if (kind === 'partial-plan') cooperation.tasks = [{ task: f.tasks[0], status: 'pending', attempts: 0 }]; - if (kind === 'nonempty-version') cooperation.planVersion = mathDigest('accepted-but-cleared-graph'); - if (kind === 'missing-version') delete cooperation.planVersion; - if (kind === 'peer-turn') f.oldState.workers![1].turns = 1; - if (kind === 'peer-request') f.oldState.workers![1].usageAccounting = - { startedTurns: 1, reportedTurns: 0, pending: true, incomplete: true }; - if (kind === 'lead-task') f.oldState.workers![0].sessionTaskId = 'removed-task'; - if (kind === 'nonplanning-turn') f.oldState.dispatchCounts = { planning: 2, proving: 1 }; - if (kind === 'accepted-candidate') f.oldState.workers![0].candidate!.status = 'passed'; - if (kind === 'proof-receipt') cooperation.proofReadyRecords = [{ status: 'consumed' }] as typeof cooperation.proofReadyRecords; - if (kind === 'changed-canonical') cooperation.canonicalCommit = f.base[0] === 'a' ? 'b'.repeat(40) : 'a'.repeat(40); - writeSolverRunState(f.sourceStateFile, f.oldState); - const historical = fs.readFileSync(f.sourceStateFile); - await expect(f.seed()).rejects.toThrow(); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - expect(host.verify).not.toHaveBeenCalled(); - expect(fs.existsSync(path.join(f.directory, 'continuation-seed-source.json'))).toBe(false); - }); - - it('rejects a missing external package cache before replay checks', async () => { - const f = fixture(original, ['Submission.original'], [{ name: 'required-package' }]); - host.resolvePackages.mockReturnValue(undefined); - await expect(f.seed()).rejects.toThrow('math_lake_packages_unavailable'); - expect(host.verify).not.toHaveBeenCalled(); - expect(host.prepare).not.toHaveBeenCalled(); - }); - - it('owns a fresh proof environment without changing frozen settings or the static run identity', async () => { - const f = fixture(), savedEnvironment = fs.readFileSync(f.environmentFile); - const lifecycle: string[] = []; - host.resolvePackages.mockImplementation((_project: string, env: NodeJS.ProcessEnv) => { - expect(env[MATH_PROOF_ENVIRONMENT_ENV]).toBeUndefined(); - expect(env[MATH_PROOF_ENVIRONMENT_SANDBOX_ENV]).toBeUndefined(); - expect(env.DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS).toBe(host.packages); - lifecycle.push('resolve-packages'); - return host.packages; - }); - host.prepare.mockImplementation(async () => { - lifecycle.push('prepare'); - return { environmentValue: 'fresh-seed-proof-environment', dispose: host.dispose, - stats: { files: 0, bytes: 0, publications: 1 } }; - }); - host.dispose.mockImplementation(async () => { lifecycle.push('dispose'); }); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest, options: MathematicsVerifierExecutionOptions) => { - expect(host.dispose).not.toHaveBeenCalled(); - expect(options.env![MATH_PROOF_ENVIRONMENT_ENV]).toBe('fresh-seed-proof-environment'); - expect(options.env![MATH_PROOF_ENVIRONMENT_SANDBOX_ENV]).toBeUndefined(); - // The verifier resolves the environment again. The resolved marker must - // survive the host-side replacement or it would reload the disposed lease. - expect(resolveMathematicsRuntimeEnvironment(options.env)[MATH_PROOF_ENVIRONMENT_ENV]).toBe('fresh-seed-proof-environment'); - lifecycle.push('verify'); - return verifiedBatch(request, { sessionId: 'fresh-seed', receipt: 'fresh-seed', checks: true }); - }); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual([]); - expect(lifecycle).toEqual(['resolve-packages', 'prepare', 'verify', 'dispose']); - expect(host.prepare).toHaveBeenCalledExactlyOnceWith(path.join(f.worktree, f.projectRelative), host.packages, - expect.objectContaining({ env: expect.objectContaining({ DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages }), - signal: expect.any(AbortSignal), cacheRoot: DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT, - deadlineAt: expect.any(Number) })); - expect(host.prepare.mock.calls[0][2].env[MATH_PROOF_ENVIRONMENT_ENV]).toBeUndefined(); - expect(host.prepare.mock.calls[0][2].env[MATH_PROOF_ENVIRONMENT_SANDBOX_ENV]).toBeUndefined(); - expect(host.dispose).toHaveBeenCalledOnce(); - expect(state.environmentDigest).toBe(f.newState.environmentDigest); - expect(state.buildDigest).toBe(f.newState.buildDigest); - expect(state.methodDigest).toBe(f.newState.methodDigest); - expect(fs.readFileSync(f.environmentFile)).toEqual(savedEnvironment); - expect(fs.statSync(f.environmentFile).mode & 0o777).toBe(0o400); - const reportText = fs.readFileSync(path.join(f.directory, 'continuation-seed.json'), 'utf8'); - expect(reportText).not.toContain('fresh-seed-proof-environment'); - expect(fs.readFileSync(path.join(f.directory, 'continuation-seed-source.json'), 'utf8')).not.toContain('fresh-seed-proof-environment'); - }); - - it('disposes the proof environment after verifier exceptions', async () => { - const f = fixture(); - host.verify.mockRejectedValue(new Error('simulated verifier exception')); - const report = await f.seed(); - expect(report.stage).toBe('complete'); - expect(report.failed).toEqual(['first', 'second']); - expect(host.dispose).toHaveBeenCalledOnce(); - expect(readSolverRunState(f.stateFile).cooperation.tasks.some(node => node.status === 'integrated')).toBe(false); - }); - - it('disposes the proof environment after an outer initialization failure', async () => { - const f = fixture(); - await expect(seedSolverContinuation({ ...f.options, onProgress: event => { - if (event === 'continuation_seed_check') throw new Error('simulated check callback failure'); - } })).rejects.toThrow('simulated check callback failure'); - expect(host.dispose).toHaveBeenCalledOnce(); - expect(host.verify).not.toHaveBeenCalled(); - expect(readSolverRunState(f.stateFile).cooperation.tasks.every(node => node.status === 'pending')).toBe(true); - }); - - it('leaves tasks pending when proof environment preparation fails', async () => { - const f = fixture(), savedEnvironment = fs.readFileSync(f.environmentFile); - host.prepare.mockRejectedValue(new Error('simulated proof environment preparation failure')); - await expect(f.seed()).rejects.toThrow('simulated proof environment preparation failure'); - expect(host.dispose).not.toHaveBeenCalled(); - expect(host.verify).not.toHaveBeenCalled(); - expect(readSolverRunState(f.stateFile).cooperation.tasks.every(node => node.status === 'pending')).toBe(true); - expect(fs.readFileSync(f.environmentFile)).toEqual(savedEnvironment); - expect(readSolverRunState(f.stateFile).environmentDigest).toBe(f.newState.environmentDigest); - }); - - it('keeps proof environment preparation and verification unlimited when requested', async () => { - const f = fixture(); - await seedSolverContinuation({ ...f.options, timeoutMs: Infinity }); - expect(host.prepare.mock.calls[0][2].deadlineAt).toBeUndefined(); - expect(host.verify.mock.calls.every(([request]) => request.timeoutMs === Infinity && request.batchTimeoutMs === Infinity)).toBe(true); - expect(host.dispose).toHaveBeenCalledOnce(); - }); - - it('retains exact task identities and source drafts, but only fresh receipts authorize imported helpers', async () => { - const f = fixture(); - f.oldState.workers[1].sessionTaskId = 'second'; - writeSolverRunState(f.sourceStateFile, f.oldState); - const originalState = fs.readFileSync(f.sourceStateFile), oldSource = fs.readFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean')); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.stage).toBe('complete'); expect(report.failed).toEqual([]); expect(host.verify).toHaveBeenCalledOnce(); - expect(state.buildDigest).toBe(f.newState.buildDigest); expect(state.methodDigest).toBe('new-method'); - expect(state.workers).toEqual(f.newState.workers); expect(state.turns).toBe(0); expect(state.phase).toBe('prepared'); - expect(state.cooperation.tasks.map(node => taskVersion(node.task))).toEqual(f.tasks.map(taskVersion)); - expect(state.cooperation.tasks.map(node => node.status)).toEqual(['integrated', 'integrated', 'pending']); - expect(state.cooperation.tasks.every(node => !node.assignment && !node.proof)).toBe(true); - expect(state.cooperation.groups[0].turns).toBe(0); expect(state.cooperation.deliveries).toEqual([]); - for (const node of state.cooperation.tasks.slice(0, 2)) { - expect(node.integratedCheck.verification.results[0].receiptId).toContain('fresh-seed-'); - expect(git(f.worktree, ['rev-parse', `refs/math/${state.runId}/evidence/${node.integratedCheck.verification.targetCommit}`])) - .toBe(node.integratedCheck.verification.targetCommit); - } - expect(fs.readFileSync(path.join(f.worktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8')).toBe(helpers); - expect(fs.existsSync(path.join(f.worktree, 'RESEARCH.md'))).toBe(false); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(originalState); - expect(fs.readFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'))).toEqual(oldSource); - const snapshotFile = path.join(f.directory, 'continuation.json'); - const snapshot = readContinuationSnapshot(snapshotFile, state.continuationDigest); - expect(snapshot.manifest.attachments.every(item => item.provenance.evidence === 'recorded-not-replayed')).toBe(true); - const draft = JSON.parse(readContinuationPage(snapshotFile, state.continuationDigest, 'draft-prover-1').text); - expect(draft.notes).toBe(f.notes); expect(draft.sources['Submission/Helpers.lean']).toContain('by sorry'); - expect(draft.assignment.taskId).toBe('second'); - expect(fs.statSync(path.join(f.directory, 'continuation-seed-source.json')).mode & 0o777).toBe(0o400); - }); - - it('releases only task owners that a smaller destination team cannot staff', async () => { - const f = fixture(); - f.oldState.cooperation!.tasks[0]!.task = { ...f.oldState.cooperation!.tasks[0]!.task, ownerId: 'engineer' }; - f.oldState.workers[1].sessionTaskId = 'second'; - writeSolverRunState(f.sourceStateFile, f.oldState); - const engineer = { ...f.newState.workers![1]!, id: 'engineer', role: 'engineer' as const }; - writeSolverRunState(f.stateFile, { ...f.newState, workers: [f.newState.workers![0]!, engineer] }); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.stage).toBe('complete'); expect(report.failed).toEqual([]); - expect(state.cooperation.tasks.map(node => taskVersion(node.task))) - .toEqual(f.oldState.cooperation!.tasks.map(node => taskVersion(node.task))); - expect(state.cooperation.tasks.map(node => node.task.ownerId)).toEqual(['engineer', undefined, undefined]); - expect(state.cooperation.tasks.map(node => node.status)).toEqual(['integrated', 'integrated', 'pending']); - const draft = JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, 'draft-prover-1').text); - expect(draft.assignment.taskId).toBe('second'); - await expect(f.seed()).resolves.toMatchObject({ stage: 'complete', failed: [] }); - }); - - it('hands off definition and family tasks with their exact identities', async () => { - const f = fixture(), lemma = { kind: 'lemma' as const, revision: 0, dependsOn: [], proofPath: 'Submission/Helpers.lean' }; - const tasks = expandTaskFamilies([ - { ...lemma, id: 'colouring', objective: 'Define the colouring', declaration: 'definition', - theoremName: 'Submission.Helpers.Colouring', type: 'Type' }, - { ...lemma, id: 'cases', objective: 'Check each case', theoremName: 'Submission.Helpers.cases', - family: { lo: 0, hi: 4, chunk: 2, predicate: 'Submission.Helpers.Good' } }], code => new Error(code)) - .map(task => ({ revision: 0, ...task as CooperativeTask })); - expect(tasks.map(task => task.familyMember)).toEqual([undefined, undefined, 'cases', 'cases']); - f.oldState.cooperation!.tasks.splice(2, 0, ...tasks.map(task => ({ task, status: 'pending' as const, attempts: 0 }))); - writeSolverRunState(f.sourceStateFile, f.oldState); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.stage).toBe('complete'); expect(report.failed).toEqual([]); - expect(state.cooperation.tasks.slice(2, 6).map(node => node.task)).toEqual(tasks); - expect(state.cooperation.tasks.map(node => taskVersion(node.task))) - .toEqual(f.oldState.cooperation!.tasks.map(node => taskVersion(node.task))); - }); - - it('rechecks a conditional declaration absent from canonical source with its exact typed obligation', async () => { - const f = conditionalFixture(), oldState = fs.readFileSync(f.sourceStateFile); - expect(fs.readFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8')) - .not.toContain('bridge_helper'); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual([]); - expect(report.candidates).toEqual(['first', 'second', 'bridge']); - expect(host.verify).toHaveBeenCalledTimes(2); - const bridge = state.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - expect(bridge.status).toBe('conditional'); - expect(bridge.integratedCheck).toBeUndefined(); - expect(bridge.proof?.passed).toBe(true); - expect(bridge.proof?.conditions).toEqual([f.condition]); - expect(bridge.proof?.commit).not.toBe(f.proofCommit); - expect(bridge.proof?.verification.results[0]?.receiptId).toContain('fresh-seed-'); - expect(bridge.proof?.changes.some(change => change.name === 'bridge_helper')).toBe(true); - expect(bridge.assignment?.seedCommit).not.toBe(f.oldState.cooperation!.canonicalCommit); - expect(hasTaskConnectionCheck(bridge.task, bridge.assignment!)).toBe(true); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(oldState); - const snapshot = readContinuationSnapshot(path.join(f.directory, 'continuation.json'), state.continuationDigest); - const draft = JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, 'draft-prover-1').text); - expect(snapshot.manifest.attachments.some(item => item.id === 'seed-history')).toBe(true); - expect(draft.notes).toBe(f.notes); - expect(draft.sources['Submission/Helpers.lean']).toContain('bridge_helper'); - }); - - it('reuses a held lease and proof environment and hands off fresh receipts without integrating conditional tasks', async () => { - const f = conditionalFixture(), seeded = vi.fn(); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages, - [MATH_PROOF_ENVIRONMENT_ENV]: 'live-host-proof-environment' }; - await withMathRuntimeLease({ lockPath: path.join(f.directory, 'run.lock'), flockExecutable: '/usr/bin/flock' }, async lease => { - const report = await seedSolverContinuation({ ...f.options, signal: lease.signal, lease, - preparedEnvironment: environment, onSeeded: seeded }); - expect(report.stage).toBe('complete'); - }); - expect(host.prepare).not.toHaveBeenCalled(); - expect(host.dispose).not.toHaveBeenCalled(); - expect(host.verify.mock.calls.every(([, options]) => options.env[MATH_PROOF_ENVIRONMENT_ENV] === 'live-host-proof-environment')).toBe(true); - expect(seeded).toHaveBeenCalledOnce(); - const [state, proofs] = seeded.mock.calls[0]!; - expect(proofs).toHaveLength(3); - expect(proofs).toContain(state.cooperation.tasks[0].integratedCheck); - expect(proofs).toContain(state.cooperation.tasks[1].integratedCheck); - expect(proofs).toContain(state.cooperation.tasks[3].proof); - expect(state.cooperation.tasks[3].status).toBe('conditional'); - }); - - it.each([false, true])('restores an unchanged fresh conditional receipt once and keeps its input unresolved (explicit=%s)', async explicit => { - const f = await freshConditionalFixture(explicit), events: string[] = []; - const saved = f.bridge.proof, cooperative = cooperationFor(f, f.state, f.proofs, - { environment: f.environment, emit: event => events.push(event) }); - const checks = () => host.verify.mock.calls.filter(([request]) => request.items.some(item => item.theoremName === f.task.theoremName)); - expect(checks()).toHaveLength(1); - expect(f.proofs).toContain(saved); - try { - await cooperative.restore(); - expect(checks()).toHaveLength(1); - expect(events).toContain('task_conditional_check_reused'); - expect(f.bridge).toMatchObject({ status: 'conditional', proof: { passed: true, conditions: [f.condition] } }); - expect(f.bridge.proof).toBe(saved); expect(f.bridge.integratedCheck).toBeUndefined(); - expect(freshlyAccepted(f.bridge, taskVersion(f.bridge.task))).toBe(false); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'second')!.status).toBe('pending'); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'goal')!.status).toBe('pending'); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it('matches the effective prepared environment after copying its settings into a frozen solver projection', async () => { - const f = await freshConditionalFixture(), file = path.join(f.directory, 'environment-restored.json'); - fs.writeFileSync(file, canonicalMathJson(projectMathematicsRuntimeEnvironment({ - ...resolveMathematicsRuntimeEnvironment(f.environment), DEEPSCIENTIST_MATH_ENV_FILE: file })), { mode: 0o400 }); - const environment = resolveMathematicsRuntimeEnvironment({ DEEPSCIENTIST_MATH_ENV_FILE: file }); - const cooperative = cooperationFor(f, f.state, f.proofs, { environment }); - try { - await cooperative.restore(); - expect(host.verify.mock.calls.filter(([request]) => request.items.some(item => item.theoremName === f.task.theoremName))).toHaveLength(1); - expect(f.bridge.status).toBe('conditional'); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it.each([false, true])('reuses a conditional original context only while its retained goals are unchanged (changed=%s)', async changed => { - const f = conditionalOriginalContextFixture(), input = f.oldState.cooperation!.tasks.find(node => node.task.id === 'second')!; - setTaskStatus(input, 'pending', 'reconstructed'); input.integratedCheck = undefined; - writeSolverRunState(f.sourceStateFile, f.oldState); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages, - [MATH_PROOF_ENVIRONMENT_ENV]: 'live-host-proof-environment' }; - let state!: SolverRunState, proofs!: TaskProof[]; - host.verify.mockImplementation(freshReceipts); - await seedSolverContinuation({ ...f.options, preparedEnvironment: environment, - onSeeded: (next, checked) => { state = next; proofs = checked; } }); - const bridge = state.cooperation!.tasks.find(node => node.task.id === 'bridge')!, saved = bridge.proof; - if (changed) setTaskStatus(state.cooperation!.tasks.find(node => node.task.id === 'premise')!, 'pending', 'reconstructed'); - const events: string[] = [], cooperative = cooperationFor(f, state, proofs, - { environment, emit: event => events.push(event) }); - host.verify.mockClear(); - try { - await (cooperative as any).recheckConditional(); - expect(host.verify).toHaveBeenCalledTimes(changed ? 1 : 0); - expect(events.includes('task_conditional_check_reused')).toBe(!changed); - expect(bridge.status).toBe('conditional'); expect(bridge.proof === saved).toBe(!changed); - expect(bridge.integratedCheck).toBeUndefined(); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it.each(['proof-content', 'source', 'projection', 'assignment', 'environment', 'runtime-environment', 'problem', - 'deserialized-proof', 'deserialized-state', 'no-handoff', 'standalone-seed', 'checker'] as const) - ('rechecks conditional proof after %s instead of trusting its seed receipt', async change => { - const f = await freshConditionalFixture(true, change !== 'standalone-seed'); - let state = f.state, proofs = f.proofs; - if (change === 'proof-content') f.bridge.proof!.verification.results[0]!.receiptId += '-edited'; - if (change === 'projection') f.bridge.proof!.verification.targetCommit = f.base; - if (change === 'source') { - const worker = state.workers![1]!.worktree; - git(worker, ['reset', '--hard', f.bridge.proof!.commit]); - fs.appendFileSync(path.join(worker, f.projectRelative, 'Submission/Helpers.lean'), '\n-- A changed source snapshot.\n'); - f.bridge.proof!.commit = commit(worker, 'Changed conditional source'); - } - if (change === 'assignment') f.bridge.assignment!.assignmentId = 'changed-live-assignment'; - if (change === 'environment') state.environmentDigest = mathDigest('changed-environment'); - if (change === 'runtime-environment') f.environment[MATH_PROOF_ENVIRONMENT_ENV] = 'changed-proof-environment'; - if (change === 'problem') state.problem.receiptDigest = mathDigest('changed-problem-receipt'); - if (change === 'deserialized-proof') { - f.bridge.proof = JSON.parse(JSON.stringify(f.bridge.proof)); proofs = [f.bridge.proof!]; - } - if (change === 'deserialized-state') state = JSON.parse(JSON.stringify(state)); - if (change === 'no-handoff') proofs = []; - const events: string[] = [], cooperative = cooperationFor(f, state, proofs, - { environment: f.environment, emit: event => events.push(event) }); - if (change === 'checker') { - const input = (cooperative as any).input; - input.modules = { ...input.modules, M2: { ...input.modules.M2, - checkTask: vi.fn((...args: Parameters) => taskProofs.checkTaskProof(...args)) } }; - } - host.verify.mockClear(); - try { - await (cooperative as any).recheckConditional(); - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][0].items.map(item => item.theoremName)).toEqual([f.task.theoremName]); - expect(events).not.toContain('task_conditional_check_reused'); - const bridge = state.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - expect(bridge.status).toBe('conditional'); expect(bridge.integratedCheck).toBeUndefined(); - expect(freshlyAccepted(bridge, taskVersion(bridge.task))).toBe(false); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it.each(['task', 'condition'] as const)('invalidates a changed %s contract without reusing conditional acceptance', async change => { - const f = await freshConditionalFixture(); - const node = change === 'task' ? f.bridge : f.state.cooperation!.tasks.find(node => node.task.id === 'second')!; - node.task.revision++; - const events: string[] = [], cooperative = cooperationFor(f, f.state, f.proofs, - { environment: f.environment, emit: event => events.push(event) }); - try { - await (cooperative as any).recheckConditional(); - expect(events).not.toContain('task_conditional_check_reused'); - expect(f.bridge).toMatchObject({ status: 'blocked', feedback: 'math_task_condition_version_invalid' }); - expect(f.bridge.integratedCheck).toBeUndefined(); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it('reuses fresh seed receipts through cooperation restore in the same process', async () => { - const f = fixture(); host.verify.mockImplementation(freshReceipts); - let state!: SolverRunState, proofs!: TaskProof[]; - await seedSolverContinuation({ ...f.options, onSeeded: (next, checks) => { state = next; proofs = checks; } }); - expect(host.verify).toHaveBeenCalledOnce(); - const cooperative = cooperationFor(f, state, proofs); - try { - await cooperative.restore(); - expect(host.verify).toHaveBeenCalledOnce(); - expect(state.cooperation!.tasks.slice(0, 2).map(node => node.integratedCheck)).toEqual(proofs); - expect(state.cooperation!.tasks.slice(0, 2).every(node => node.status === 'integrated' && !node.pendingValidation)).toBe(true); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it('checks JSON-restored seed receipts again even when the original fresh objects are supplied', async () => { - const f = fixture(); host.verify.mockImplementation(freshReceipts); - let proofs!: TaskProof[]; - await seedSolverContinuation({ ...f.options, onSeeded: (_next, checks) => { proofs = checks; } }); - const state = readSolverRunState(f.stateFile), cooperative = cooperationFor(f, state, proofs); - try { - await cooperative.restore(); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(host.verify.mock.calls[1][0].items.map(item => item.theoremName)) - .toEqual(['Submission.Helpers.first_helper', 'Submission.Helpers.second_helper']); - expect(state.cooperation!.tasks.slice(0, 2).every(node => node.status === 'integrated' && !node.pendingValidation)).toBe(true); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it('discharges a freshly restored conditional proof through normal cooperation integration', async () => { - const f = conditionalFixture(); host.verify.mockImplementation(freshReceipts); - let state!: SolverRunState, proofs!: TaskProof[]; - await seedSolverContinuation({ ...f.options, onSeeded: (next, checks) => { state = next; proofs = checks; } }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')!.status).toBe('conditional'); - const cooperative = cooperationFor(f, state, proofs); - try { - await cooperative.restore(); - const bridge = state.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - expect(bridge).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(bridge.integratedCheck!.conditions).toBeUndefined(); - expect(bridge.proof!.projection).toMatchObject({ environmentDigest: state.environmentDigest, - problemReceiptDigest: state.problem.receiptDigest }); - expect(committedSource(f.worktree, state.cooperation!.canonicalCommit!, `${f.projectRelative}/Submission/Helpers.lean`)) - .toContain('lemma bridge_helper : True := by exact second_helper'); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it('prefers an unconditional integrated check after an old conditional proof has been discharged', async () => { - const f = conditionalFixture(), bridge = f.oldState.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - git(f.sourceWorktree, ['reset', '--hard', f.proofCommit]); - f.oldState.cooperation!.canonicalCommit = f.proofCommit; - bridge.status = 'integrated'; - bridge.integratedCheck = { ...bridge.proof!, conditions: undefined }; - writeSolverRunState(f.sourceStateFile, f.oldState); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual([]); expect(report.candidates).toEqual(['first', 'second', 'bridge']); - expect(host.verify).toHaveBeenCalledTimes(2); // Its typed predecessor is checked in an earlier wave. - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')).toMatchObject({ status: 'integrated', - integratedCheck: { passed: true } }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')!.proof).toBeUndefined(); - }); - - it('blocks only a conditional candidate whose saved assignment lost its dependencies', async () => { - const f = conditionalFixture(), bridge = f.oldState.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - delete bridge.assignment!.dependencies; - writeSolverRunState(f.sourceStateFile, f.oldState); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual(['bridge']); expect(host.verify).toHaveBeenCalledOnce(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')).toMatchObject({ status: 'blocked', - feedback: 'math_task_condition_version_invalid' }); - expect(state.cooperation!.tasks.slice(0, 2).every(node => node.status === 'integrated')).toBe(true); - }); - - it('keeps a conditional candidate blocked and its draft intact when the historical proof commit is unavailable', async () => { - const f = conditionalFixture(), bridge = f.oldState.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - bridge.proof!.commit = 'f'.repeat(40); - writeSolverRunState(f.sourceStateFile, f.oldState); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual(['bridge']); - expect(host.verify).toHaveBeenCalledOnce(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')).toMatchObject({ - status: 'blocked', feedback: expect.stringContaining('math_task_source_unavailable') }); - const draft = JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, 'draft-prover-1').text); - expect(draft.sources['Submission/Helpers.lean']).toContain('bridge_helper'); - }); - - it('rejects a changed conditional dependency contract without promoting its old receipt', async () => { - const f = conditionalFixture(), bridge = f.oldState.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - bridge.proof!.conditions![0] = { taskId: 'second', taskDigest: mathDigest('changed condition') }; - writeSolverRunState(f.sourceStateFile, f.oldState); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual(['bridge']); - expect(host.verify).toHaveBeenCalledOnce(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')).toMatchObject({ - status: 'blocked', feedback: 'math_task_condition_version_invalid' }); - }); - - it('rechecks the same frozen conditional source after later old-run edits', async () => { - const f = conditionalFixture(), first = await f.seed(); - expect(first.failed).toEqual([]); - const snapshotDigest = readSolverRunState(f.stateFile).continuationDigest; - fs.writeFileSync(path.join(f.oldState.workers![1]!.worktree, f.projectRelative, 'Submission/Helpers.lean'), emptyHelpers); - fs.writeFileSync(path.join(f.oldState.workers![1]!.worktree, 'RESEARCH.md'), 'Late historical edit'); - const second = await f.seed(), state = readSolverRunState(f.stateFile); - expect(second.failed).toEqual([]); - expect(state.continuationDigest).toBe(snapshotDigest); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')?.status).toBe('conditional'); - expect(host.verify).toHaveBeenCalledTimes(4); - const frozen = JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), snapshotDigest, 'conditional-bridge').text); - expect(frozen.sources['Submission/Helpers.lean']).toContain('bridge_helper'); - }); - - it.each(['phase', 'turns', 'thread', 'worker-turns', 'worker-session', 'existing-plan'])('rejects nonfresh target state: %s', async kind => { - const f = fixture(); - if (kind === 'phase') f.newState.phase = 'running'; - if (kind === 'turns') f.newState.turns = 1; - if (kind === 'thread') f.newState.threadId = 'some-thread'; - if (kind === 'worker-turns') f.newState.workers[1].turns = 1; - if (kind === 'worker-session') f.newState.workers[1].sessionAssignmentId = 'some-assignment'; - if (kind === 'existing-plan') f.newState.cooperation = { tasks: [] }; - writeSolverRunState(f.stateFile, f.newState); - await expect(f.seed()).rejects.toThrow('math_continuation_seed_requires_fresh_prepared_run'); - expect(host.verify).not.toHaveBeenCalled(); - expect(fs.existsSync(path.join(f.directory, 'continuation-seed-source.json'))).toBe(false); - }); - - it('refuses an active target lease even when the on-disk phase still says prepared', async () => { - const f = fixture(); - await withMathRuntimeLease({ lockPath: path.join(f.directory, 'run.lock'), flockExecutable: '/usr/bin/flock' }, async () => { - await expect(f.seed()).rejects.toThrow('math_runtime_lease_busy'); - }); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it.each(['task', 'receipt', 'source-policy', 'build'])('rejects mismatched identities: %s', async changed => { - const f = fixture(); - if (changed === 'task') f.oldState.taskDigest = mathDigest('different task'); - if (changed === 'receipt') f.oldState.problem = { ...f.oldState.problem, receiptDigest: mathDigest('different receipt') }; - if (changed === 'source-policy') f.oldState.problem = { ...f.oldState.problem, sourceStructure: {} }; - if (changed === 'build') f.newState.buildDigest = mathDigest('different build'); - writeSolverRunState(f.sourceStateFile, f.oldState); writeSolverRunState(f.stateFile, f.newState); - await expect(f.seed()).rejects.toThrow(changed === 'build' ? 'math_continuation_seed_build_changed' : 'math_continuation_seed_identity_changed'); - expect(host.verify).not.toHaveBeenCalled(); expect(git(f.worktree, ['rev-parse', 'HEAD'])).toBe(f.base); - }); - - it('seeds a re-bootstrapped workspace that only adds owned modules, with fresh receipts in its own repository', async () => { - const f = conditionalFixture(), e = rebootstrapped(f), oldState = fs.readFileSync(f.sourceStateFile); - const report = await e.seed(), state = readSolverRunState(e.stateFile); - expect(report).toMatchObject({ stage: 'complete', failed: [], candidates: ['first', 'second', 'bridge'], evidence: 'fresh-helper-receipts' }); - expect(state.problem.ownedFiles).toEqual(['Submission.lean', 'Submission/Helpers.lean', 'Submission/Theory/T01.lean']); - expect(state.cooperation.tasks.map(node => [node.task.id, node.status])).toEqual([['first', 'integrated'], ['second', 'integrated'], - ['goal', 'pending'], ['bridge', 'conditional']]); - for (const node of state.cooperation.tasks.slice(0, 2)) { - expect(node.integratedCheck!.verification.results[0]!.receiptId).toContain('fresh-seed'); - expect(git(e.worktree, ['rev-parse', `refs/math/${state.runId}/evidence/${node.integratedCheck!.verification.targetCommit}`])) - .toBe(node.integratedCheck!.verification.targetCommit); - } - expect(fs.readFileSync(path.join(e.worktree, f.projectRelative, 'Submission/Helpers.lean'), 'utf8')).toBe(helpers); - expect(fs.readFileSync(path.join(e.worktree, f.projectRelative, 'Submission/Theory/T01.lean'), 'utf8')).toBe(theoryModuleSource()); - const source = JSON.parse(fs.readFileSync(path.join(e.directory, 'continuation-seed-source.json'), 'utf8')); - expect(source.ownershipExtension).toEqual({ sourceReceiptDigest: f.oldState.problem.receiptDigest, - sourcePolicyDigest: expect.stringMatching(/^[a-f0-9]{64}$/u), addedFiles: ['Submission/Theory/T01.lean'] }); - expect(Object.keys(source.canonicalSources)).toEqual(state.problem.ownedFiles); - expect(source.conditionalCandidates[0].seedSources['Submission/Theory/T01.lean']).toBe(theoryModuleSource()); - const snapshot = path.join(e.directory, 'continuation.json'); - const draft = JSON.parse(readContinuationPage(snapshot, state.continuationDigest, 'draft-prover-1').text); - expect(Object.keys(draft.sources)).toEqual(['Submission.lean', 'Submission/Helpers.lean']); - expect(readContinuationPage(snapshot, state.continuationDigest, 'seed-recovery-guide').text) - .toContain('added owned files ["Submission/Theory/T01.lean"]'); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(oldState); - await expect(e.seed()).resolves.toMatchObject({ stage: 'complete', failed: [] }); - }); - - it('reopens completed research bound to the former problem receipt after an ownership extension', async () => { - const f = completedResearchFixture(), e = rebootstrapped(f); - expect(await e.seed()).toMatchObject({ stage: 'complete', failed: [] }); - const state = readSolverRunState(e.stateFile), research = state.cooperation.tasks.find(node => node.task.id === f.task.id)!; - expect(research.status).toBe('pending'); - expect(state.cooperation.history!.some(record => record.task.id === f.task.id && record.finding === f.finding)).toBe(true); - expect(state.cooperation.deliveries!.map(delivery => [delivery.id, delivery.status])).toEqual([['old-research-completion', 'superseded']]); - }); - - it.each(['trusted', 'frozen', 'dropped', 'unchanged'] as const)('rejects a re-bootstrapped workspace with %s ownership', async change => { - const f = fixture(), e = rebootstrapped(f, change); - await expect(e.seed()).rejects.toThrow('math_continuation_seed_identity_changed'); - expect(host.verify).not.toHaveBeenCalled(); expect(git(e.worktree, ['rev-parse', 'HEAD'])).toBe(e.base); - expect(fs.existsSync(path.join(e.directory, 'continuation-seed-source.json'))).toBe(false); - }); - - it('does not promote historical acceptance when the fresh helper check fails', async () => { - const f = fixture(); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const verified = verifiedBatch(request, { sessionId: 'fresh-seed', receipt: 'fresh-seed', checks: true }); - return request.items.some(item => item.theoremName.endsWith('second_helper')) - ? failedBatch(verified, { stdoutPreview: () => 'error: unsolved goals', - selected: result => result.theoremName === 'Submission.Helpers.second_helper' }) : verified; - }); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual(['second']); - expect(state.cooperation.tasks.map(node => node.status)).toEqual(['integrated', 'blocked', 'pending']); - expect(state.cooperation.tasks[1].integratedCheck.passed).toBe(false); - }); - - it('requires new receipt identities even when a verifier reports kernel_verified', async () => { - const f = fixture(); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const verified = verifiedBatch(request, { sessionId: 'fresh-seed', receipt: 'fresh-seed', checks: true }); - return { ...verified, results: verified.results.map(({ receiptId: _receipt, ...result }) => result) }; - }); - const report = await f.seed(); - expect(report.failed).toEqual(['first', 'second']); - expect(readSolverRunState(f.stateFile).cooperation.tasks.some(node => node.status === 'integrated')).toBe(false); - }); - - it('rejects changed trusted canonical sources before freezing or checking them', async () => { - const f = fixture(); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Challenge.lean'), 'theorem changed : False := by sorry\n'); - f.oldState.cooperation.canonicalCommit = commit(f.sourceWorktree, 'Invalid trusted change'); - writeSolverRunState(f.sourceStateFile, f.oldState); - await expect(f.seed()).rejects.toThrow('math_continuation_seed_source_policy_changed'); - expect(readSolverRunState(f.stateFile).cooperation).toBeUndefined(); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('rejects frozen-original declaration changes in historical owned sources', async () => { - const f = fixture(); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), original.replace(': True', ': False')); - f.oldState.cooperation.canonicalCommit = commit(f.sourceWorktree, 'Invalid original change'); - writeSolverRunState(f.sourceStateFile, f.oldState); - await expect(f.seed()).rejects.toThrow('math_original_declaration_changed'); - expect(readSolverRunState(f.stateFile).cooperation).toBeUndefined(); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('does not overwrite new source work during a repeated initialization', async () => { - const f = fixture(); await f.seed(); - const target = path.join(f.worktree, f.projectRelative, 'Submission/Helpers.lean'); - fs.appendFileSync(target, '\n-- New local proof work\n'); const edited = fs.readFileSync(target); - await expect(f.seed()).rejects.toThrow('math_continuation_seed_destination_changed'); - expect(fs.readFileSync(target)).toEqual(edited); - }); - - it('leaves unfinished obligations pending on cancellation and retries the frozen capture', async () => { - const f = fixture(); - await expect(seedSolverContinuation({ ...f.options, onProgress: event => { - if (event === 'continuation_seed_checked') f.controller.abort(); - } })).rejects.toThrow(); - expect(host.dispose).toHaveBeenCalledOnce(); - const interrupted = readSolverRunState(f.stateFile); - expect(interrupted.cooperation.tasks.map(node => node.status)).toEqual(['integrated', 'pending', 'pending']); - fs.writeFileSync(path.join(f.oldDirectory, 'worktree-2', 'RESEARCH.md'), 'Newer old-run notes must not replace the frozen capture.'); - const report = await seedSolverContinuation({ ...f.options, signal: new AbortController().signal }); - expect(host.prepare).toHaveBeenCalledTimes(2); - expect(host.dispose).toHaveBeenCalledTimes(2); - expect(report.stage).toBe('complete'); - const state = readSolverRunState(f.stateFile), draft = JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), - state.continuationDigest, 'draft-prover-1').text); - expect(draft.notes).toBe(f.notes); - }); - - it('recovers interrupted multi-file snapshot publication without importing any acceptance early', async () => { - const f = fixture(), rename = fs.renameSync; - const fail = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (String(to) === path.join(f.directory, 'continuation.json')) throw new Error('simulated snapshot publication failure'); - return rename(from, to); - }); - await expect(f.seed()).rejects.toThrow('simulated snapshot publication failure'); - expect(readSolverRunState(f.stateFile).cooperation).toBeUndefined(); - expect(host.verify).not.toHaveBeenCalled(); fail.mockRestore(); - expect((await f.seed()).stage).toBe('complete'); - }); - - it('rejects redirected worker draft files before reading or importing them', async () => { - const f = fixture(), notes = path.join(f.oldDirectory, 'worktree-2', 'RESEARCH.md'); - fs.renameSync(notes, `${notes}.saved`); fs.symlinkSync(`${notes}.saved`, notes); - await expect(f.seed()).rejects.toThrow('math_path_invalid'); - expect(readSolverRunState(f.stateFile).cooperation).toBeUndefined(); expect(host.verify).not.toHaveBeenCalled(); - }); -}); - -describe('completed advisory research continuation', () => { - it.each(['research', 'sketch'] as const)('retains unchanged completed %s and finding without replaying proof or session authority', async kind => { - const f = completedResearchFixture(kind), prior = f.oldState.cooperation!.tasks.at(-1)!; - prior.proof = prior.integratedCheck = f.oldState.cooperation!.tasks[0]!.integratedCheck; - writeSolverRunState(f.sourceStateFile, f.oldState); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - const retained = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(retained).toMatchObject({ status: 'completed', attempts: 0, finding: f.finding }); - expect(retained.researchCompletion).toEqual(f.completion); - expect(retained.assignment).toBeUndefined(); expect(retained.proof).toBeUndefined(); expect(retained.integratedCheck).toBeUndefined(); - expect(state.workers!.every(worker => !worker.threadId && !worker.sessionTaskId && !worker.sessionAssignmentId)).toBe(true); - expect(report.checked).toEqual(['first', 'second']); - expect(state.cooperation!.tasks[0]!.integratedCheck!.verification.results[0]!.receiptId).not.toBe('old-first'); - expect(state.cooperation!.tasks.find(node => node.task.id === 'goal')?.status).toBe('pending'); - expect(JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, - 'seed-completed-research').text)[0]).toMatchObject({ task: { id: f.task.id }, finding: f.finding }); - await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.find(node => node.task.id === f.task.id)?.researchCompletion).toEqual(f.completion); - }); - - it('hands off blueprint prose on completed research without changing its retained identity', async () => { - const f = completedResearchFixture(), prior = f.oldState.cooperation!.tasks.at(-1)!; - const blueprint = { informalProof: 'Reduce to the escalator tree and bound each leaf.', citations: ['Rouse 2014, §3'] }; - prior.task = { ...prior.task, ...blueprint }; - expect(taskVersion(prior.task)).toBe(taskVersion(f.task)); - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); const state = readSolverRunState(f.stateFile); - const retained = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(retained).toMatchObject({ status: 'completed', finding: f.finding, task: blueprint }); - expect(retained.researchCompletion).toEqual(f.completion); - expect(JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, - 'seed-completed-research').text)[0]).toMatchObject({ task: { id: f.task.id, ...blueprint } }); - }); - - it.each(['mathlib', 'verified-library', 'public-literature'] as const)( - 'preserves preferred owners and %s research identities throughout continuation metadata', async researchSource => { - const f = completedResearchFixture(), prior = f.oldState.cooperation!.tasks.at(-1)!; - const goal = f.oldState.cooperation!.tasks.find(node => node.task.id === 'goal')!; - goal.task = { ...goal.task, preferredOwnerId: 'prover-1' }; - prior.task = { ...prior.task, researchSource, consumerGoalIds: [goal.task.id] }; - prior.finding = JSON.stringify({ ...JSON.parse(f.finding), taskDigest: taskVersion(prior.task) }); - const completion = publishCompletedResearch(f.oldState, prior.task.id, 'source-focused-completion'); - f.oldState.cooperation!.goalProgress = { schema: 'theoremos.goal-progress.v1', - problemReceiptDigest: f.oldState.problem.receiptDigest, sequence: 1, - goals: [{ key: 'goal-key', proofPath: goal.task.proofPath!, theoremName: goal.task.theoremName!, taskId: goal.task.id, - activeMs: 900, coreActiveMs: 1200, lastReviewedCoreMs: 900, observedAt: 1000, active: true, - seenEvidence: [], coreSeenEvidence: [], closed: false }], - decisions: [{ id: 'review', at: 900, reason: 'Inspect the next mathematical step.', goalKeys: ['goal-key'], - nextChecks: [{ action: 'construction-check', objective: 'Test the retained construction.', expectedEvidence: 'An exact witness.', - targetTaskId: prior.task.id, taskDigest: taskVersion(prior.task) }] }] }; - const gapScope = { problemReceiptDigest: f.oldState.problem.receiptDigest, - environmentDigest: f.oldState.environmentDigest, source: goal.task, consumer: goal.task, dependencies: [] }; - f.oldState.cooperation!.deliveries!.push({ id: 'preferred-owner-gap', producer: 'prover-1', - taskId: goal.task.id, taskDigest: taskVersion(goal.task), kind: 'research', status: 'advisory', - statement: goal.task.objective, premises: [], dependencies: [], remainingObligations: [], - summary: 'An advisory gap on the unchanged original target.', evidenceRefs: [], createdAt: 50, - mathematicalGap: { consumer: { taskId: goal.task.id, taskDigest: taskVersion(goal.task) }, - previousGap: 'The original target is open.', reduced: 'The helper has been proved.', - remaining: 'Connect the helper to the target.', evidenceScope: 'Current original target.', reconsiderWhen: [] }, - mathematicalGapScope: gapScope }); - writeSolverRunState(f.sourceStateFile, f.oldState); - - expect((await f.seed()).stage).toBe('complete'); - await f.seed(); - const state = readSolverRunState(f.stateFile), retained = state.cooperation!.tasks.find(node => node.task.id === prior.task.id)!; - expect(retained).toMatchObject({ status: 'completed', task: { researchSource, consumerGoalIds: [goal.task.id] } }); - expect(retained.researchCompletion).toEqual(completion); - expect(taskVersion(retained.task)).toBe(taskVersion(prior.task)); - expect(state.cooperation!.tasks.find(node => node.task.id === goal.task.id)?.task).toEqual(goal.task); - expect(state.cooperation!.goalProgress!.decisions).toEqual(f.oldState.cooperation!.goalProgress.decisions); - expect(state.cooperation!.goalProgress!.goals[0]).toMatchObject({ active: false, activeMs: 900, coreActiveMs: 1200 }); - expect(state.cooperation!.deliveries!.find(delivery => delivery.id === 'preferred-owner-gap')?.mathematicalGapScope).toEqual(gapScope); - const source = JSON.parse(fs.readFileSync(path.join(f.directory, 'continuation-seed-source.json'), 'utf8')); - expect(source.completedResearch.find(record => record.task.id === prior.task.id).task).toEqual(prior.task); - expect(source.researchContext.tasks.find(node => node.task.id === goal.task.id).task).toEqual(goal.task); - expect(source.researchContext.tasks.find(node => node.task.id === prior.task.id).task).toEqual(prior.task); - }); - - it.each([ - { preferredOwnerId: 'invalid owner' }, - { researchSource: 'unsupported-source' }, - { unexpectedMigrationField: true }, - ])('rejects invalid or unknown nested handoff metadata %j before importing sources', async metadata => { - const f = completedResearchFixture(), goal = f.oldState.cooperation!.tasks.find(node => node.task.id === 'goal')!.task; - f.oldState.cooperation!.deliveries!.push({ id: 'invalid-handoff-gap', producer: 'prover-1', - taskId: goal.id, taskDigest: taskVersion(goal), kind: 'research', status: 'advisory', - statement: goal.objective, premises: [], dependencies: [], remainingObligations: [], summary: 'Invalid scope.', - evidenceRefs: [], createdAt: 50, mathematicalGapScope: { problemReceiptDigest: f.oldState.problem.receiptDigest, - environmentDigest: f.oldState.environmentDigest, source: { ...goal, ...metadata } as CooperativeTask, - consumer: goal, dependencies: [] } }); - writeSolverRunState(f.sourceStateFile, f.oldState); - await expect(f.seed()).rejects.toThrow(); - expect(fs.existsSync(path.join(f.directory, 'continuation-seed-source.json'))).toBe(false); - expect(readSolverRunState(f.stateFile).cooperation).toBeUndefined(); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('does not bind research completed on A to canonical sources B before the first continuation', async () => { - const f = completedResearchFixture(); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('end Submission.Helpers', 'lemma later_input : True := by trivial\nend Submission.Helpers')); - f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Canonical B after research completed on A'); - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)).toMatchObject({ status: 'pending' }); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ finding: f.finding, researchCompletion: f.completion })); - const frozen = JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, - 'seed-completed-research').text); - expect(frozen[0].record).toEqual(f.completion); - }); - - it('compares the same scoped source bytes that were supplied to the research assignment', async () => { - const f = completedResearchFixture(); - for (const node of f.oldState.cooperation!.tasks) { - node.task = { ...node.task, sharing: 'problem' }; - if (node.integratedCheck) node.integratedCheck = { ...node.integratedCheck, taskDigest: taskVersion(node.task) }; - } - const privateTask: CooperativeTask = { ...f.tasks[0]!, id: 'private_helper', groupId: 'private', sharing: 'group', - theoremName: 'Submission.Helpers.private_helper', ownerId: undefined }; - f.oldState.cooperation!.groups!.push({ group: { id: 'private', objective: 'Independent private route', - status: 'active', revision: 0 }, turns: 0 }); - f.oldState.cooperation!.tasks.push({ task: privateTask, status: 'pending', attempts: 0 }); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('end Submission.Helpers', 'lemma private_helper : True := by trivial\nend Submission.Helpers')); - f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Unrelated private canonical helper'); - const completion = publishCompletedResearch(f.oldState, f.task.id, 'scoped-research-completion'); - expect(completion.basis.sourceDigest).not.toBe(researchSourceDigest(Object.fromEntries(f.oldState.problem.ownedFiles.map(file => [file, - committedSource(f.sourceWorktree, f.oldState.cooperation!.canonicalCommit!, `${f.projectRelative}/${file}`)])))); - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - const retained = readSolverRunState(f.stateFile).cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(retained).toMatchObject({ status: 'completed', finding: f.finding }); - expect(retained.researchCompletion).toEqual(completion); - }); - - it('reopens research when a dependency publishes a new finding without changing its task version', async () => { - const f = completedResearchFixture(), node = f.oldState.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - const input: CooperativeTask = { id: 'input_research', kind: 'research', objective: 'Find the missing arithmetic condition', - revision: 0, dependsOn: [] }; - f.oldState.cooperation!.tasks.push({ task: input, status: 'completed', attempts: 1, finding: 'Old arithmetic condition.' }); - publishCompletedResearch(f.oldState, input.id, 'input-old'); - node.task = { ...node.task, dependsOn: [input.id] }; - const completion = publishCompletedResearch(f.oldState, node.task.id, 'route-before-new-input'); - const dependency = f.oldState.cooperation!.tasks.find(node => node.task.id === input.id)!; - dependency.finding = 'A new counterexample refutes the old arithmetic condition.'; - publishCompletedResearch(f.oldState, input.id, 'input-new'); - expect(taskVersion(dependency.task)).toBe(taskVersion(input)); - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(record => record.task.id === node.task.id)?.status).toBe('pending'); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ finding: f.finding, researchCompletion: completion })); - expect(state.cooperation!.deliveries!.some(delivery => delivery.id === 'input-new' && delivery.finding === dependency.finding)).toBe(true); - }); - - it('preserves a fresh same-text completion at B by its own publication identity across generations', async () => { - const f = completedResearchFixture(); await f.seed(); - const source = readSolverRunState(f.stateFile), node = source.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - fs.writeFileSync(path.join(source.worktree, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('end Submission.Helpers', 'lemma recompletion_input : True := by trivial\nend Submission.Helpers')); - source.cooperation!.canonicalCommit = commit(source.worktree, 'Canonical B before fresh completion'); - const completion = publishCompletedResearch(source, node.task.id, 'fresh-completion-at-B'); - expect(node.finding).toBe(f.finding); expect(completion.basis.sourceDigest).not.toBe(f.completion.basis.sourceDigest); - writeSolverRunState(f.stateFile, source); - const second = nextContinuation(f, f.stateFile, 'same-text-at-B'); await second.seed(); - const third = nextContinuation(f, second.stateFile, 'same-text-at-B-again'); await third.seed(); - const state = readSolverRunState(third.stateFile), retained = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(retained).toMatchObject({ status: 'completed', finding: f.finding }); - expect(retained.researchCompletion).toEqual(completion); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ researchCompletion: f.completion })); - }); - - it('retains a dependency research event without lemma proposals and reopens for a changed event', async () => { - const f = completedResearchFixture(); - const event = { id: 'dependency-event', producer: 'prover-1', taskId: 'first', taskDigest: taskVersion(f.tasks[0]!), - kind: 'research' as const, status: 'advisory' as const, statement: 'Arithmetic obstruction', premises: [], dependencies: [], - remainingObligations: [], summary: 'The event supplies an independent local obstruction.', evidenceRefs: [], createdAt: 10, - finding: 'Complete dependency-event finding', findingDigest: mathDigest('Complete dependency-event finding') }; - f.oldState.cooperation!.deliveries!.push(event); - const completion = publishCompletedResearch(f.oldState, f.task.id, 'completion-using-event'); - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - const second = nextContinuation(f, f.stateFile, 'event-generation'); await second.seed(); - const source = readSolverRunState(second.stateFile); - expect(source.cooperation!.tasks.find(node => node.task.id === f.task.id)?.researchCompletion).toEqual(completion); - expect(source.cooperation!.deliveries).toContainEqual(expect.objectContaining(event)); - source.cooperation!.deliveries!.push({ ...event, id: 'new-dependency-event', summary: 'New contradictory evidence.', - finding: 'New complete finding', findingDigest: mathDigest('New complete finding'), createdAt: 11 }); - writeSolverRunState(second.stateFile, source); - const third = nextContinuation(f, second.stateFile, 'changed-event-generation'); await third.seed(); - expect(readSolverRunState(third.stateFile).cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - }); - - it('reopens research when its former proof input fails the independent seed recheck', async () => { - const f = completedResearchFixture(); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => failedBatch(request)); - await f.seed(); const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ researchCompletion: f.completion })); - await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - }); - - it('keeps legacy completed research without a publication basis as history', async () => { - const f = completedResearchFixture(); delete f.oldState.cooperation!.tasks.at(-1)!.researchCompletion; - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ task: f.task, finding: f.finding })); - }); - - it('retains legacy completed research without a finding as history through successive continuations', async () => { - const f = completedResearchFixture(), prior = f.oldState.cooperation!.tasks.at(-1)!; - delete prior.researchCompletion; delete prior.finding; - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); - const next = nextContinuation(f, f.stateFile, 'legacy-without-finding'); - await next.seed(); - for (const file of [f.stateFile, next.stateFile]) { - const state = readSolverRunState(file); - const task = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(task).toMatchObject({ status: 'pending', attempts: 0 }); - expect(task.finding).toBeUndefined(); expect(task.researchCompletion).toBeUndefined(); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ task: f.task })); - } - }); - - it.each(['environmentDigest', 'retrievalDigest', 'knowledgeDigest'] as const)('reopens research for a changed %s and retains the finding as history', async field => { - const f = completedResearchFixture(); - f.newState[field] = mathDigest(`changed-${field}`); writeSolverRunState(f.stateFile, f.newState); - await f.seed(); const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)).toMatchObject({ status: 'pending', attempts: 0 }); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)?.finding).toBeUndefined(); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ task: f.task, finding: f.finding })); - }); - - it('retains completed research across generations, but reopens it when its dependency or canonical sources change', async () => { - const f = completedResearchFixture(); await f.seed(); - const second = nextContinuation(f, f.stateFile, 'second-generation'); await second.seed(); - let state = readSolverRunState(second.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)).toMatchObject({ status: 'completed', finding: f.finding }); - const dependency = state.cooperation!.tasks.find(node => node.task.id === 'first')!; - dependency.task = { ...dependency.task, revision: dependency.task.revision + 1 }; - writeSolverRunState(second.stateFile, state); - const third = nextContinuation(f, second.stateFile, 'third-generation'); await third.seed(); - state = readSolverRunState(third.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ task: f.task, finding: f.finding })); - - state = readSolverRunState(f.stateFile); - fs.writeFileSync(path.join(state.worktree, f.projectRelative, 'Submission/Helpers.lean'), - helpers.replace('end Submission.Helpers', 'lemma new_input : True := by trivial\nend Submission.Helpers')); - state.cooperation!.canonicalCommit = commit(state.worktree, 'New canonical research input'); - writeSolverRunState(f.stateFile, state); - const changedSources = nextContinuation(f, f.stateFile, 'changed-sources'); await changedSources.seed(); - expect(readSolverRunState(changedSources.stateFile).cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - }); - - it('does not revive an archived completion after a later explicit reopen', async () => { - const f = completedResearchFixture(); await f.seed(); - const source = readSolverRunState(f.stateFile), node = source.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - node.task = { ...node.task, revision: 1 }; node.status = 'pending'; node.finding = undefined; - writeSolverRunState(f.stateFile, source); - const second = nextContinuation(f, f.stateFile, 'reopened-generation'); await second.seed(); - const third = nextContinuation(f, second.stateFile, 'still-reopened-generation'); await third.seed(); - const state = readSolverRunState(third.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)).toMatchObject({ task: { revision: 1 }, status: 'pending' }); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ task: f.task, finding: f.finding })); - }); - - it.each(['pending', 'running', 'blocked'] as const)('does not preserve a %s research attempt as completed', async status => { - const f = completedResearchFixture(); f.oldState.cooperation!.tasks.at(-1)!.status = status; - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.find(node => node.task.id === f.task.id)) - .toMatchObject({ status: 'pending', attempts: 0 }); - }); - - it.each(['task', 'dependency'] as const)('reopens a stale completed research assignment after a changed %s contract', async changed => { - const f = completedResearchFixture(), node = f.oldState.cooperation!.tasks.find(node => node.task.id === - (changed === 'task' ? f.task.id : 'first'))!; - node.task = { ...node.task, revision: 1 }; - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ finding: f.finding })); - }); - - it.each(['final-candidate', 'feasibility', 'legacy-final-candidate'] as const)('requires a new %s review', async scope => { - const f = completedResearchFixture(), node = f.oldState.cooperation!.tasks.at(-1)!; - node.task = scope === 'legacy-final-candidate' ? { ...node.task, id: 'independent_candidate_review' } : - { ...node.task, reviewScope: scope }; - writeSolverRunState(f.sourceStateFile, f.oldState); await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.find(task => task.task.id === node.task.id)?.status).toBe('pending'); - }); - - it('loads a legacy frozen source without completion identity conservatively', async () => { - const f = completedResearchFixture(), rename = fs.renameSync; - const fail = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (String(to) === path.join(f.directory, 'continuation.json')) throw new Error('stop before snapshot publication'); - return rename(from, to); - }); - await expect(f.seed()).rejects.toThrow('stop before snapshot publication'); fail.mockRestore(); - const sourceFile = path.join(f.directory, 'continuation-seed-source.json'); - const source = JSON.parse(fs.readFileSync(sourceFile, 'utf8')); delete source.completedResearch; - fs.chmodSync(sourceFile, 0o600); fs.writeFileSync(sourceFile, canonicalMathJson(source)); fs.chmodSync(sourceFile, 0o400); - await f.seed(); const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - expect(state.cooperation!.tasks[0]!.status).toBe('integrated'); - expect(readContinuationPage(path.join(f.directory, 'continuation.json'), state.continuationDigest, 'seed-history').text).toContain(f.finding.replaceAll('"', '\\"')); - }); - - it('reads a legacy snapshot inputDigest as historical evidence without rebinding it to current inputs', async () => { - const f = completedResearchFixture(), rename = fs.renameSync; - const fail = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (String(to) === path.join(f.directory, 'continuation.json')) throw new Error('freeze legacy completion fixture'); - return rename(from, to); - }); - await expect(f.seed()).rejects.toThrow('freeze legacy completion fixture'); fail.mockRestore(); - const sourceFile = path.join(f.directory, 'continuation-seed-source.json'); - const source = JSON.parse(fs.readFileSync(sourceFile, 'utf8')); - source.completedResearch = [{ task: f.task, finding: f.finding, inputDigest: mathDigest('legacy guessed binding') }]; - delete source.researchContext; - fs.chmodSync(sourceFile, 0o600); fs.writeFileSync(sourceFile, canonicalMathJson(source)); fs.chmodSync(sourceFile, 0o400); - await f.seed(); const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.find(node => node.task.id === f.task.id)?.status).toBe('pending'); - expect(state.cooperation!.history).toContainEqual(expect.objectContaining({ task: f.task, finding: f.finding })); - expect(state.cooperation!.history!.every(item => !item.researchCompletion)).toBe(true); - }); -}); - -describe('bounded continuation verification batches', () => { - it('resumes an expired cold-seed check with its destination budget and the same frozen inputs', async () => { - const f = fixture(); - const inherited = { key: mathDigest('unrelated historical verification'), timeoutMs: 7000, attempts: 1, - at: 1, targetCommit: f.base, receiptIds: ['old-timeout'] }; - f.oldState.verificationCheckpoints = [inherited]; - writeSolverRunState(f.sourceStateFile, f.oldState); - const historical = fs.readFileSync(f.sourceStateFile), limits: number[] = []; - const seed = () => seedSolverContinuation({ ...f.options, timeoutMs: 1000 }); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - limits.push(request.timeoutMs!); - const batch = freshReceipts(request); - return limits.length <= 2 ? { ...batch, status: 'blocked', results: batch.results.map(result => ({ ...result, - status: 'blocked', error: 'Lean verification timed out.' })) } : batch; - }); - for (const timeoutMs of [1000, 2000]) { - await expect(seed()).rejects.toBeInstanceOf(VerificationCheckpointError); - const state = readSolverRunState(f.stateFile); - expect(state.phase).toBe('prepared'); - expect(state.verificationCheckpoints).toHaveLength(2); - expect(state.verificationCheckpoints![0]).toEqual(inherited); - expect(state.verificationCheckpoints![1]).toMatchObject({ timeoutMs, attempts: timeoutMs === 1000 ? 1 : 2 }); - expect(state.cooperation!.recheck).toMatchObject({ total: 2, completed: 0 }); - for (const node of state.cooperation!.tasks) { - expect(node.status).toBe('pending'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - } - const report = JSON.parse(fs.readFileSync(path.join(f.directory, 'continuation-seed.json'), 'utf8')); - expect(report).toMatchObject({ stage: 'interrupted', checked: [], failed: [], evidence: 'advisory-sources-require-recheck' }); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - } - const report = await seed(), state = readSolverRunState(f.stateFile); - expect(limits).toEqual([1000, 2000, 4000]); - expect(report).toMatchObject({ stage: 'complete', checked: ['first', 'second'], failed: [] }); - expect(state.cooperation!.tasks.slice(0, 2).every(node => node.status === 'integrated' && node.integratedCheck?.passed)).toBe(true); - expect(state.cooperation!.tasks.at(-1)!.status).toBe('pending'); - expect(state.check).toBeUndefined(); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - expect(host.dispose).toHaveBeenCalledTimes(3); - }); - - it('preserves a cold-seed timeout after cancellation and rejects late successful receipts', async () => { - const f = fixture(), seed = (signal = f.controller.signal) => seedSolverContinuation({ ...f.options, signal, timeoutMs: 1000 }); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const batch = freshReceipts(request); - return { ...batch, status: 'blocked', results: batch.results.map(result => ({ ...result, - status: 'blocked', error: 'Formal verification batch deadline exceeded.' })) }; - }); - await expect(seed()).rejects.toBeInstanceOf(VerificationCheckpointError); - const checkpoint = readSolverRunState(f.stateFile).verificationCheckpoints!; - const controller = new AbortController(); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { controller.abort(); return freshReceipts(request); }); - await expect(seed(controller.signal)).rejects.toMatchObject({ name: 'AbortError' }); - const cancelled = readSolverRunState(f.stateFile); - expect(cancelled.verificationCheckpoints).toEqual(checkpoint); - for (const node of cancelled.cooperation!.tasks) { - expect(node.status).toBe('pending'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - } - host.verify.mockImplementation(freshReceipts); - expect((await seed()).failed).toEqual([]); - expect(host.verify.mock.calls.map(([request]) => request.timeoutMs)).toEqual([1000, 2000, 2000]); - }); - - it('owns cold-seed checkpoints even when called within another run verification context', async () => { - const f = fixture(), outer = { environmentDigest: mathDigest('outer-environment'), problemReceiptDigest: mathDigest('outer-problem'), - checkpoints: [], save: vi.fn(), emit: vi.fn() }; - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const batch = freshReceipts(request); - return { ...batch, status: 'blocked', results: batch.results.map(result => ({ ...result, - status: 'blocked', error: 'Lean verification timed out.' })) }; - }); - await expect(withVerificationCheckpoints(outer, - () => seedSolverContinuation({ ...f.options, timeoutMs: 1000 }))).rejects.toBeInstanceOf(VerificationCheckpointError); - expect(outer.checkpoints).toEqual([]); expect(outer.save).not.toHaveBeenCalled(); expect(outer.emit).not.toHaveBeenCalled(); - expect(readSolverRunState(f.stateFile).verificationCheckpoints).toMatchObject([{ timeoutMs: 1000, attempts: 1 }]); - }); - - it('reconsiders a failed old continuation check against canonical source with fresh receipts', async () => { - const f = fixture(), node = f.oldState.cooperation!.tasks[0]!; - node.status = 'blocked'; node.feedback = 'math_continuation_seed_helper_not_verified'; - node.integratedCheck = { ...node.integratedCheck!, passed: false, verification: { - ...node.integratedCheck!.verification, status: 'failed', results: [{ - ...node.integratedCheck!.verification.results[0], status: 'failed', - error: 'Lean exited with status 1.', stdoutPreview: 'Submission/Helpers.lean:2:1: error: unknown identifier removed_context', - }] } }; - writeSolverRunState(f.sourceStateFile, f.oldState); - host.verify.mockImplementation(freshReceipts); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.candidates).toEqual(['first', 'second']); expect(report.failed).toEqual([]); - expect(state.cooperation!.tasks[0]).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(state.cooperation!.tasks[0].integratedCheck!.verification.results[0].receiptId).toMatch(/^fresh-seed-/u); - }); - - it.each(['changed-contract', 'environment-failure'] as const)('does not select an obsolete failed check (%s)', async kind => { - const f = fixture(), node = f.oldState.cooperation!.tasks[0]!; - node.status = 'blocked'; node.integratedCheck = { ...node.integratedCheck!, passed: false, - taskDigest: kind === 'changed-contract' ? 'f'.repeat(64) : taskVersion(node.task), verification: { - ...node.integratedCheck!.verification, status: kind === 'environment-failure' ? 'unavailable' : 'failed', - results: [{ ...node.integratedCheck!.verification.results[0], status: kind === 'environment-failure' ? 'unavailable' : 'failed', - error: kind === 'environment-failure' ? 'No Lean toolchain' : 'Lean exited with status 1.', - stdoutPreview: 'Submission/Helpers.lean:2:1: error: unknown identifier removed_context' }] } }; - writeSolverRunState(f.sourceStateFile, f.oldState); host.verify.mockImplementation(freshReceipts); - const report = await f.seed(); - expect(report.candidates).toEqual(['second']); - expect(readSolverRunState(f.stateFile).cooperation!.tasks[0].status).toBe('pending'); - }); - - it.each([false, true])('rechecks an original prerequisite before its def consumer (declared=%s)', async declared => { - const f = originalDependencyFixture(declared), check = vi.spyOn(taskProofs, 'checkTaskProofs'); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const source = committedSource(f.worktree, request.targetCommit!, `${f.projectRelative}/Submission.lean`); - if (request.items.some(item => item.theoremName === 'Submission.original')) { - expect(source).toContain('theorem premise : True := by trivial'); - expect(source).toContain('def witness'); - } - return freshReceipts(request); - }); - let state!: SolverRunState, proofs!: TaskProof[]; - const report = await seedSolverContinuation({ ...f.options, onSeeded: (next, checked) => { state = next; proofs = checked; } }); - expect(report.checked).toEqual(['premise', 'goal']); expect(report.failed).toEqual([]); - expect(check.mock.calls.map(call => call[3].map(request => [request.task.id, request.retainedGoals]))) - .toEqual([[['premise', []]], [['goal', ['Submission.premise']]]]); - const cooperative = cooperationFor(f, state, proofs); - try { - await cooperative.restore(); - expect(state.cooperation!.tasks.every(node => node.status === 'integrated')).toBe(true); - } finally { f.controller.abort(); await cooperative.stop(); } - }); - - it.each([false, true])('restores conditional original inputs from the frozen candidate through definitions (canonical bridge=%s)', async canonicalBridge => { - const f = conditionalOriginalContextFixture(canonicalBridge), check = vi.spyOn(taskProofs, 'checkTaskProofs'); - let fresh: TaskProof[] = []; - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - if (request.items.some(item => item.theoremName === 'Submission.bridge')) { - const source = committedSource(f.worktree, request.targetCommit!, `${f.projectRelative}/Submission.lean`); - expect(source).toContain('theorem premise : True := by trivial'); - expect(source).toContain('theorem extra : True := by trivial'); - expect(source).toContain('def witness'); expect(source).toContain('def nestedWitness'); - expect(source).toContain('def combinedWitness'); - expect(source).not.toContain('theorem unused'); - expect(source).toContain('lemma bridge : theorem_os_conditional_type%'); - expect(source).toContain('Submission.Helpers.second_helper'); - } - return freshReceipts(request); - }); - const report = await seedSolverContinuation({ ...f.options, onSeeded: (_state, proofs) => { fresh = proofs; } }); - const requests = check.mock.calls.flatMap(call => call[3]), bridgeRequest = requests.find(request => request.task.id === 'bridge')!; - expect(bridgeRequest.retainedGoals).toEqual(['Submission.premise', 'Submission.extra']); - expect(bridgeRequest.conditions).toEqual([f.tasks[1]]); - expect(check.mock.calls.findIndex(call => call[3].some(request => request.task.id === 'bridge'))) - .toBeGreaterThan(check.mock.calls.findIndex(call => call[3].some(request => request.task.id === 'premise'))); - const state = readSolverRunState(f.stateFile), bridge = state.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - expect(report.failed).toEqual([]); - expect(bridge).toMatchObject({ status: 'conditional', proof: { passed: true, conditions: [f.condition] } }); - expect(bridge.integratedCheck).toBeUndefined(); - expect(fresh.map(proof => proof.taskDigest)).toContain(taskVersion(f.task)); - expect(state.cooperation!.tasks.find(node => node.task.id === 'goal')?.status).toBe('pending'); - }); - - it('keeps an unverified original out of a frozen conditional context', async () => { - const f = conditionalOriginalContextFixture(), check = vi.spyOn(taskProofs, 'checkTaskProofs'); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - if (request.items.some(item => ['Submission.premise', 'Submission.bridge'].includes(item.theoremName!))) { - if (request.items.some(item => item.theoremName === 'Submission.bridge')) { - const source = committedSource(f.worktree, request.targetCommit!, `${f.projectRelative}/Submission.lean`); - expect(source).not.toContain('theorem premise'); expect(source).not.toContain('def combinedWitness'); - } - return failedBatch(freshReceipts(request), { stdoutPreview: file => `${file}:3:1: error: unsolved goals` }); - } - return freshReceipts(request); - }); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed.toSorted()).toEqual(['bridge', 'premise']); - const bridgeRequests = check.mock.calls.flatMap(call => call[3]).filter(request => request.task.id === 'bridge'); - expect(bridgeRequests).toHaveLength(1); - expect(bridgeRequests[0].retainedGoals).toEqual(['Submission.extra']); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')).toMatchObject({ - status: 'blocked', proof: { passed: false, conditions: [f.condition] } }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')!.integratedCheck).toBeUndefined(); - }); - - it('rejects a frozen conditional dependency after its original task version changes', async () => { - const f = conditionalOriginalContextFixture(), premise = f.oldState.cooperation!.tasks.find(node => node.task.id === 'premise')!; - f.bridge.assignment.dependencies.push({ taskId: premise.task.id, taskDigest: taskVersion(premise.task) }); - premise.task = { ...premise.task, revision: premise.task.revision + 1 }; - writeSolverRunState(f.sourceStateFile, f.oldState); - const check = vi.spyOn(taskProofs, 'checkTaskProofs'); host.verify.mockImplementation(freshReceipts); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual(['bridge']); - expect(check.mock.calls.flatMap(call => call[3]).some(request => request.task.id === 'bridge')).toBe(false); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')).toMatchObject({ - status: 'blocked', feedback: 'math_task_condition_version_invalid' }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')!.proof).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'premise')!.status).toBe('integrated'); - }); - - it('does not restore a conditional candidate through a cycle of original inputs', async () => { - const f = conditionalOriginalContextFixture(); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), f.canonicalSource - .replace('premise : True := by trivial', 'premise : True := by exact extra') - .replace('extra : True := by trivial', 'extra : True := by exact premise')); - f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Cyclic historical originals'); - writeSolverRunState(f.sourceStateFile, f.oldState); - const check = vi.spyOn(taskProofs, 'checkTaskProofs'); host.verify.mockImplementation(freshReceipts); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed.toSorted()).toEqual(['bridge', 'extra', 'premise']); - expect(check.mock.calls.flatMap(call => call[3]).every(request => !['bridge', 'extra', 'premise'].includes(request.task.id))).toBe(true); - for (const id of ['bridge', 'extra', 'premise']) { - const node = state.cooperation!.tasks.find(node => node.task.id === id)!; - expect(node.status).toBe('blocked'); expect(node.feedback).toContain('dependency_cycle'); - expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - } - }); - - it('restores original context referenced only by a conditional input type', async () => { - const f = conditionalOriginalContextFixture(), worker = f.oldState.workers![1]!.worktree; - const source = f.canonicalSource.replace('end Submission', 'def conditionType : Prop := by\n' + - ' have h : True := premise\n exact True\nlemma missing : conditionType := by sorry\nend Submission'); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), source); - const canonical = commit(f.sourceWorktree, 'Conditional type context'); - git(worker, ['reset', '--hard', canonical]); - fs.writeFileSync(path.join(worker, f.projectRelative, 'Submission.lean'), source.replace('end Submission', - 'lemma bridge : True := by exact missing\nend Submission')); - const proofCommit = commit(worker, 'Conditional type-only original input'); - const missing: CooperativeTask = { id: 'missing', kind: 'lemma', objective: 'Prove the typed input', - dependsOn: [], revision: 0, ownerId: 'prover-1', proofPath: 'Submission.lean', - theoremName: 'Submission.missing', type: 'Submission.conditionType' }; - const condition = { taskId: missing.id, taskDigest: taskVersion(missing) }; - f.bridge.task = { ...f.task, dependsOn: ['missing'] }; - f.bridge.assignment = { ...f.bridge.assignment, taskDigest: taskVersion(f.bridge.task), seedCommit: canonical, dependencies: [condition] }; - f.bridge.proof = { ...f.bridge.proof, taskDigest: taskVersion(f.bridge.task), commit: proofCommit, seedCommit: canonical, conditions: [condition] }; - f.oldState.cooperation!.canonicalCommit = canonical; - f.oldState.cooperation!.tasks.splice(1, 0, { task: missing, status: 'pending', attempts: 0 }); - writeSolverRunState(f.sourceStateFile, f.oldState); - const check = vi.spyOn(taskProofs, 'checkTaskProofs'); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - if (request.items.some(item => item.theoremName === 'Submission.bridge')) { - const projected = committedSource(f.worktree, request.targetCommit!, `${f.projectRelative}/Submission.lean`); - expect(projected).toContain('theorem premise : True := by trivial'); - expect(projected).toContain('def conditionType'); - expect(projected).toContain('lemma bridge : theorem_os_conditional_type%'); - expect(projected).toContain('Submission.conditionType'); - expect(projected).not.toContain('lemma missing'); - } - return freshReceipts(request); - }); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - const request = check.mock.calls.flatMap(call => call[3]).find(request => request.task.id === 'bridge')!; - expect(request.retainedGoals).toEqual(['Submission.premise']); - expect(request.conditions).toEqual([missing]); - expect(report.failed).toEqual([]); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')).toMatchObject({ - status: 'conditional', proof: { passed: true, conditions: [condition] } }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'bridge')!.integratedCheck).toBeUndefined(); - }); - - it('recovers an unknown source dependency once only after a new original receipt', async () => { - const f = originalDependencyFixture(false, true), attempts: { target: string; retained: boolean }[] = []; - const check = vi.spyOn(taskProofs, 'checkTaskProofs'); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const source = committedSource(f.worktree, request.targetCommit!, `${f.projectRelative}/Submission.lean`); - const target = request.items[0].theoremName!, retained = source.includes('theorem premise'); - attempts.push({ target, retained }); - if (target === 'Submission.original' && !retained) return failedBatch(freshReceipts(request), { - stdoutPreview: file => `${file}:4:1: error: unknown identifier selected by tactic` }); - return freshReceipts(request); - }); - const report = await f.seed(); - // Existing single-target compact/full fallback is separate from one context recovery. - expect(attempts).toEqual([{ target: 'Submission.original', retained: false }, { target: 'Submission.original', retained: false }, - { target: 'Submission.premise', retained: true }, { target: 'Submission.original', retained: true }]); - expect(check.mock.calls.filter(call => call[3][0].task.id === 'goal')).toHaveLength(2); - expect(report.checked).toEqual(['goal', 'premise']); expect(report.failed).toEqual([]); - expect(readSolverRunState(f.stateFile).cooperation!.recheck!.completed).toBe(2); - }); - - it('does not restore an unverified original or retry unchanged context', async () => { - const f = originalDependencyFixture(false, true); - const check = vi.spyOn(taskProofs, 'checkTaskProofs'); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => failedBatch(freshReceipts(request), { - stdoutPreview: file => `${file}:3:1: error: unsolved goals` })); - const report = await f.seed(); - expect(report.failed.toSorted()).toEqual(['goal', 'premise']); - expect(check.mock.calls).toHaveLength(2); - expect(check.mock.calls.every(call => call[3].every(request => !request.retainedGoals.length))).toBe(true); - }); - - it('blocks a cycle inferred through definitions without accepting either original', async () => { - const f = originalDependencyFixture(); - const source = fs.readFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), 'utf8') - .replace('premise : True := by trivial', 'premise : True := by exact original'); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), source); - f.oldState.cooperation!.canonicalCommit = commit(f.sourceWorktree, 'Invalid cyclic source'); - writeSolverRunState(f.sourceStateFile, f.oldState); host.verify.mockImplementation(freshReceipts); - const report = await f.seed(); - expect(report.failed.toSorted()).toEqual(['goal', 'premise']); expect(host.verify).not.toHaveBeenCalled(); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.every(node => node.feedback?.includes('dependency_cycle'))).toBe(true); - }); - - it('independently checks members after a shared Lean compilation fails', async () => { - const f = fixture(); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => request.items.length > 1 || - request.items.some(item => item.theoremName?.includes('second_helper')) ? failedBatch(freshReceipts(request), { - stdoutPreview: file => `${file}:3:1: error: unsolved goals` }) : freshReceipts(request)); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual(['second']); expect(report.checked).toEqual(['first', 'second']); - expect(host.verify.mock.calls[0][0].items).toHaveLength(2); - expect(host.verify.mock.calls.slice(1).every(([request]) => request.items.length === 1)).toBe(true); - expect(state.cooperation!.tasks[0].status).toBe('integrated'); expect(state.cooperation!.tasks[1].status).toBe('blocked'); - }); - - it('checks identical helper projections once and preserves each target receipt and type', async () => { - const f = fixture(); host.verify.mockImplementation(freshReceipts); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual([]); expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][0].items.map(item => item.theoremName)) - .toEqual(['Submission.Helpers.first_helper', 'Submission.Helpers.second_helper']); - expect(host.verify.mock.calls[0][1].expectedDeclarationTypes).toEqual({ - 'Submission.Helpers.first_helper': 'True', 'Submission.Helpers.second_helper': 'True' }); - const proofs = state.cooperation!.tasks.slice(0, 2).map(node => node.integratedCheck!); - expect(proofs.map(proof => proof.verification.results.map(result => result.theoremName))) - .toEqual([['Submission.Helpers.first_helper'], ['Submission.Helpers.second_helper']]); - expect(proofs.map(proof => proof.taskDigest)).toEqual(f.tasks.slice(0, 2).map(taskVersion)); - expect(new Set(proofs.map(proof => proof.verification.results[0]!.receiptId)).size).toBe(2); - expect(state.cooperation!.tasks.slice(0, 2).every(node => node.status === 'integrated')).toBe(true); - }); - - it('keeps different full projections separate even when candidates share the canonical commit', async () => { - const f = fixture(); - fs.writeFileSync(path.join(f.sourceWorktree, f.projectRelative, 'Submission.lean'), original.replace('by sorry', 'by trivial')); - const canonical = commit(f.sourceWorktree, 'Historical original proof'); - f.oldState.cooperation!.canonicalCommit = canonical; - const goal = f.oldState.cooperation!.tasks.find(node => node.task.kind === 'goal')!; - goal.status = 'integrated'; goal.integratedCheck = { ...f.oldState.cooperation!.tasks[0]!.integratedCheck!, - commit: canonical, taskDigest: taskVersion(goal.task) }; - writeSolverRunState(f.sourceStateFile, f.oldState); - const check = vi.spyOn(taskProofs, 'checkTaskProofs'); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const source = committedSource(f.worktree, request.targetCommit!, `${f.projectRelative}/Submission.lean`); - if (request.items.some(item => item.theoremName === 'Submission.original')) expect(source).toContain('theorem original'); - else expect(source).not.toContain('theorem original'); - return freshReceipts(request); - }); - const report = await f.seed(); - expect(report.failed).toEqual([]); - expect(check.mock.calls.map(call => call[3].map(request => request.task.id))).toEqual([['first', 'second'], ['goal']]); - expect(new Set(check.mock.calls.map(call => call[2])).size).toBe(1); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.every(node => node.status === 'integrated')).toBe(true); - }); - - it('includes each conditional target and typed assumptions in the grouping projection', async () => { - // Reconstructed copies of identical saved sources must have the same commit - // identity, so this exercises projection grouping beyond the source commit. - vi.stubEnv('GIT_AUTHOR_DATE', '2000-01-01T00:00:00Z'); vi.stubEnv('GIT_COMMITTER_DATE', '2000-01-01T00:00:00Z'); - const f = conditionalFixture(), worker = f.oldState.workers![1]!.worktree; - const file = path.join(worker, f.projectRelative, 'Submission/Helpers.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('end Submission.Helpers', - 'lemma bridge_first_helper : True := by exact first_helper\nend Submission.Helpers')); - const proofCommit = commit(worker, 'Historical bridges with different assumptions'); - const bridge = f.oldState.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - bridge.proof!.commit = proofCommit; - const task = { ...f.task, id: 'bridge_first', theoremName: 'Submission.Helpers.bridge_first_helper', dependsOn: ['first'] }; - const condition = { taskId: 'first', taskDigest: taskVersion(f.tasks[0]!) }; - f.oldState.cooperation!.tasks.push({ task, status: 'conditional', attempts: 1, - assignment: { ...bridge.assignment!, taskId: task.id, taskDigest: taskVersion(task), dependencies: [condition] }, - proof: { ...bridge.proof!, taskDigest: taskVersion(task), conditions: [condition] } }); - writeSolverRunState(f.sourceStateFile, f.oldState); - const check = vi.spyOn(taskProofs, 'checkTaskProofs'); host.verify.mockImplementation(freshReceipts); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual([]); - expect(check.mock.calls.map(call => call[3].map(request => request.task.id))) - .toEqual([['first', 'second'], ['bridge'], ['bridge_first']]); - const conditionalGroups = check.mock.calls.filter(call => call[3].some(request => request.conditions?.length)); - expect(conditionalGroups).toHaveLength(2); expect(new Set(conditionalGroups.map(call => call[2])).size).toBe(1); - expect(host.verify.mock.calls.slice(1).map(([, options]) => options.expectedDeclarationType)) - .toEqual([ - conditionalExpectedType(f.task.theoremName!, 'True', [{ theoremName: 'Submission.Helpers.second_helper', type: 'True' }]), - conditionalExpectedType(task.theoremName!, 'True', [{ theoremName: 'Submission.Helpers.first_helper', type: 'True' }]), - ]); - expect(state.cooperation!.tasks.filter(node => node.task.id.startsWith('bridge')).map(node => node.status)) - .toEqual(['conditional', 'conditional']); - }); - - it('limits identical projections to batches of 32 and executes only one group at a time', async () => { - const f = fixture(), tasks = replaceHelperCandidates(f, 33), check = taskProofs.checkTaskProofs; - let active = 0, peak = 0; - vi.spyOn(taskProofs, 'checkTaskProofs').mockImplementation(async (...args) => { - active++; peak = Math.max(peak, active); - try { return await check(...args); } finally { active--; } - }); - host.verify.mockImplementation(freshReceipts); - const report = await f.seed(); - expect(report.failed).toEqual([]); - expect(host.verify.mock.calls.map(([request]) => request.items.length)).toEqual([32, 1]); - expect(host.verify.mock.calls.flatMap(([request]) => request.items.map(item => item.theoremName))) - .toEqual(tasks.map(task => task.theoremName)); - expect(peak).toBe(1); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.filter(node => node.status === 'integrated')).toHaveLength(33); - }); - - it('isolates a candidate that fails projection preflight while batching healthy helpers', async () => { - const f = fixture(), task = { ...f.tasks[0]!, id: 'missing', theoremName: 'Submission.Helpers.missing_helper' }; - f.oldState.cooperation!.tasks.splice(1, 0, { task, status: 'integrated', attempts: 1, - integratedCheck: { ...f.oldState.cooperation!.tasks[0]!.integratedCheck!, taskDigest: taskVersion(task) } }); - writeSolverRunState(f.sourceStateFile, f.oldState); - host.verify.mockImplementation(freshReceipts); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.failed).toEqual(['missing']); expect(report.checked).toHaveLength(3); - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][0].items.map(item => item.theoremName)) - .toEqual(['Submission.Helpers.first_helper', 'Submission.Helpers.second_helper']); - expect(state.cooperation!.tasks.find(node => node.task.id === 'missing')).toMatchObject({ status: 'blocked', - feedback: expect.stringContaining('math_task_missing_declaration') }); - expect(state.cooperation!.tasks.filter(node => ['first', 'second'].includes(node.task.id)) - .every(node => node.status === 'integrated')).toBe(true); - }); - - it('falls back to isolated checks when a planned batch rejects its projection match', async () => { - const f = fixture(), check = taskProofs.checkTaskProofs; - const attempts = vi.spyOn(taskProofs, 'checkTaskProofs').mockImplementation(async (...args) => { - if (args[3].length > 1) throw new Error('math_task_batch_projection_mismatch'); - return check(...args); - }); - host.verify.mockImplementation(freshReceipts); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(attempts.mock.calls.map(call => call[3].length)).toEqual([2, 1, 1]); - expect(host.verify.mock.calls.map(([request]) => request.items.length)).toEqual([1, 1]); - expect(report.failed).toEqual([]); expect(report.checked).toEqual(['first', 'second']); - expect(state.cooperation!.tasks.slice(0, 2).every(node => node.status === 'integrated')).toBe(true); - }); - - it('verifies every target again on initialization retry even when the saved report checked them all', async () => { - const f = fixture(); let verification = 0; - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const sessionId = `seed-attempt-${++verification}`; - return receiptBatch(request, { sessionId, receiptId: (_, name) => `${sessionId}-${name}` }); - }); - expect((await f.seed()).checked).toEqual(['first', 'second']); - const before = readSolverRunState(f.stateFile), frozenFile = path.join(f.directory, 'continuation-seed-source.json'); - const frozen = fs.readFileSync(frozenFile), oldReceipt = before.cooperation!.tasks[0]!.integratedCheck!.verification.results[0]!.receiptId; - host.verify.mockClear(); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - expect(report.checked).toEqual(['first', 'second']); expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][0].items.map(item => item.theoremName)) - .toEqual(['Submission.Helpers.first_helper', 'Submission.Helpers.second_helper']); - expect(state.cooperation!.tasks[0]!.integratedCheck!.verification.results[0]!.receiptId).not.toBe(oldReceipt); - expect(state.continuationDigest).toBe(before.continuationDigest); expect(fs.readFileSync(frozenFile)).toEqual(frozen); - }); - - it('retains the run lease and proof environment until an aborted batch verification settles', async () => { - const f = fixture(); - let entered!: () => void, release!: () => void; - const checking = new Promise(resolve => { entered = resolve; }); - const gate = new Promise(resolve => { release = resolve; }); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - entered(); await gate; return freshReceipts(request); - }); - const running = f.seed(), settled = running.then(() => 'fulfilled', () => 'rejected'); - try { - await Promise.race([checking, settled.then(status => { throw new Error(`seed_${status}_before_batch_verification`); })]); - expect(host.verify).toHaveBeenCalledOnce(); expect(host.verify.mock.calls[0][0].items).toHaveLength(2); - f.controller.abort(); - await expect(withMathRuntimeLease({ lockPath: path.join(f.directory, 'run.lock'), - flockExecutable: '/usr/bin/flock' }, async () => undefined)).rejects.toThrow('math_runtime_lease_busy'); - expect(host.dispose).not.toHaveBeenCalled(); - expect(readSolverRunState(f.stateFile).cooperation!.tasks.every(node => node.status === 'pending')).toBe(true); - } finally { - release(); await settled; - } - await expect(running).rejects.toThrow(); - expect(host.dispose).toHaveBeenCalledOnce(); - const state = readSolverRunState(f.stateFile); - expect(state.phase).toBe('prepared'); - expect(state.cooperation!.tasks.every(node => node.status === 'pending' && !node.integratedCheck && !node.proof)).toBe(true); - expect(JSON.parse(fs.readFileSync(path.join(f.directory, 'continuation-seed.json'), 'utf8')).checked).toEqual([]); - await withMathRuntimeLease({ lockPath: path.join(f.directory, 'run.lock'), - flockExecutable: '/usr/bin/flock' }, async () => undefined); - }); -}); - -describe('continuation of a host-frozen unfinished delivery', () => { - async function resumeFrozen(f: ReturnType, stateFile: string, - emit: (event: string, details?: Record) => void = () => {}) { - const state = readSolverRunState(stateFile), save = () => writeSolverRunState(stateFile, state); - const cooperation = cooperationFor(f, state, [], { timeoutMs: 1000, save }), worker = state.workers![1]!; - const descriptor = { id: worker.id, role: worker.role, worktree: worker.worktree, ownedFiles: state.problem.ownedFiles }; - let action: Awaited>; - try { - await cooperation.restore(); - action = await cooperation.next(descriptor, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind).toBe('task'); - const lifecycle = new WorkerProofLifecycle({ state, research: worker, worker: descriptor, cooperation, - close: async () => {}, save, emit, checked: () => {} }); - return await withVerificationCheckpoints({ environmentDigest: state.environmentDigest, - problemReceiptDigest: state.problem.receiptDigest, checkpoints: state.verificationCheckpoints ??= [], save, emit }, - () => lifecycle.resumeFrozen(action)); - } finally { - if (action?.kind === 'task' && state.cooperation!.proofReadyRecords?.some(ready => ready.status === 'frozen')) - cooperation.release(descriptor, action); - cooperation.stopped(descriptor); - await cooperation.stop(); - state.phase = 'finished'; - for (const worker of state.workers!) worker.phase = 'finished'; - save(); - } - } - - function timeOutVerification() { - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const batch = freshReceipts(request); - if (!request.items.some(item => item.theoremName === 'Submission.original')) return batch; - return { ...batch, status: 'blocked', results: batch.results.map(result => ({ ...result, - status: 'blocked', error: 'Lean verification timed out.' })) }; - }); - } - - it('carries the verification deadline through two continuations of the same frozen proof', async () => { - const f = frozenGoalFixture(); await f.seed(); - const started: { key: unknown; timeoutMs: unknown }[] = []; - const emit = (event: string, details?: Record) => { - if (event === 'verification_started') started.push({ key: details!.key, timeoutMs: details!.timeoutMs }); - }; - timeOutVerification(); - await expect(resumeFrozen(f, f.stateFile, emit)).rejects.toBeInstanceOf(VerificationCheckpointError); - const first = readSolverRunState(f.stateFile), key = first.verificationCheckpoints![0]!.key; - const firstGoal = first.cooperation!.tasks.find(node => node.task.id === 'goal')!; - expect(firstGoal.status).toBe('pending'); expect(firstGoal.assignment).toBeUndefined(); - const historical = fs.readFileSync(f.stateFile); - host.verify.mockImplementation(freshReceipts); - const second = nextContinuation(f, f.stateFile, 'deadline-second'); await second.seed(); await second.seed(); - expect(fs.readFileSync(f.stateFile)).toEqual(historical); - timeOutVerification(); - await expect(resumeFrozen(f, second.stateFile, emit)).rejects.toBeInstanceOf(VerificationCheckpointError); - host.verify.mockImplementation(freshReceipts); - const third = nextContinuation(f, second.stateFile, 'deadline-third'); await third.seed(); await third.seed(); - const pending = readSolverRunState(third.stateFile); - expect(pending.cooperation!.proofReadyRecords).toHaveLength(1); - expect(pending.cooperation!.proofReadyRecords![0]).toMatchObject({ status: 'frozen', snapshotCommit: f.snapshotCommit }); - expect(pending.cooperation!.proofReadyRecords![0]!.receiptIds).toBeUndefined(); - expect(await resumeFrozen(f, third.stateFile, emit)).toBe(true); - expect(started.filter(item => item.key === key).map(item => item.timeoutMs).slice(0, 3)).toEqual([1000, 2000, 4000]); - const checked = readSolverRunState(third.stateFile).cooperation!.proofReadyRecords!; - expect(checked).toHaveLength(1); expect(checked[0]!.status).toBe('checked'); - expect(checked[0]!.receiptIds?.length).toBeGreaterThan(0); - }); - - it.each(['cancellation', 'environment preparation failure'] as const)( - 'retries a continuation after %s without multiplying its inherited verification budget', async failure => { - const f = frozenGoalFixture(); await f.seed(); timeOutVerification(); - await expect(resumeFrozen(f, f.stateFile)).rejects.toBeInstanceOf(VerificationCheckpointError); - const checkpoints = readSolverRunState(f.stateFile).verificationCheckpoints!; - const next = nextContinuation(f, f.stateFile, `retry-${failure === 'cancellation' ? 'cancel' : 'failure'}`); - host.verify.mockImplementation(freshReceipts); - const controller = new AbortController(); - if (failure === 'environment preparation failure') host.prepare.mockRejectedValueOnce(new Error('fixture_environment_failure')); - const interrupted = seedSolverContinuation({ ...f.options, sourceRun: f.stateFile, run: next.stateFile, - signal: controller.signal, onProgress: event => { - if (failure === 'cancellation' && event === 'continuation_seed_checked') controller.abort(); - } }); - if (failure === 'cancellation') await expect(interrupted).rejects.toMatchObject({ name: 'AbortError' }); - else await expect(interrupted).rejects.toThrow('fixture_environment_failure'); - const changedSource = readSolverRunState(f.stateFile); - changedSource.verificationCheckpoints![0]!.timeoutMs *= 16; - writeSolverRunState(f.stateFile, changedSource); - await next.seed(); await next.seed(); - const state = readSolverRunState(next.stateFile); - expect(state.verificationCheckpoints).toEqual(checkpoints); - expect(state.cooperation!.proofReadyRecords).toHaveLength(1); - expect(state.cooperation!.proofReadyRecords![0]!.status).toBe('frozen'); - expect(state.cooperation!.proofReadyRecords![0]!.receiptIds).toBeUndefined(); - }); - - it.each(['environment', 'problem receipt'] as const)('does not carry verification budgets into a different %s', async change => { - const f = frozenGoalFixture(); await f.seed(); timeOutVerification(); - await expect(resumeFrozen(f, f.stateFile)).rejects.toBeInstanceOf(VerificationCheckpointError); - host.verify.mockImplementation(freshReceipts); - const next = change === 'problem receipt' ? rebootstrapped(f) : nextContinuation(f, f.stateFile, 'changed-environment'); - if (change === 'environment') { - const state = readSolverRunState(next.stateFile); - state.environmentDigest = mathDigest('different-runtime-environment'); writeSolverRunState(next.stateFile, state); - } - await seedSolverContinuation({ ...f.options, sourceRun: f.stateFile, run: next.stateFile }); - const state = readSolverRunState(next.stateFile); - expect(state.verificationCheckpoints ?? []).toEqual([]); - expect(state.cooperation!.proofReadyRecords).toBeUndefined(); - }); - - async function lostFrozenAssignmentFixture() { - const f = frozenGoalFixture(); await f.seed(); - const source = readSolverRunState(f.stateFile), node = source.cooperation!.tasks.find(node => node.task.id === 'goal')!; - const assignment = node.assignment!, ready = source.cooperation!.proofReadyRecords![0]!; - source.phase = 'finished'; source.turns = 3; - source.verificationCheckpoints = [{ key: mathDigest('timed-out-projected-goal'), timeoutMs: 1_800_000, - attempts: 1, at: ready.requestedAt + 1, targetCommit: source.cooperation!.canonicalCommit!, receiptIds: ['timeout-only'] }]; - delete node.assignment; - for (const worker of source.workers!) { - worker.phase = 'finished'; - delete worker.sessionTaskId; delete worker.sessionTaskVersion; delete worker.sessionAssignmentId; - } - writeSolverRunState(f.stateFile, source); host.verify.mockClear(); - return { ...f, source, assignment, frozenReady: ready }; - } - - it('recovers a frozen continuation after its timed-out assignment and worker session were dropped', async () => { - const f = await lostFrozenAssignmentFixture(), historical = fs.readFileSync(f.stateFile); - expect(f.source.verificationCheckpoints![0]!.targetCommit).not.toBe(f.snapshotCommit); - const next = nextContinuation(f, f.stateFile, 'recovered-frozen-goal'), report = await next.seed(); - await next.seed(); - const state = readSolverRunState(next.stateFile), node = state.cooperation!.tasks.find(node => node.task.id === 'goal')!; - const ready = state.cooperation!.proofReadyRecords![0]!; - expect(report.checked).not.toContain('goal'); - expect(state.cooperation!.proofReadyRecords).toHaveLength(1); - expect(node.status).toBe('pending'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - expect(node.assignment!.dependencies).toEqual(f.assignment.dependencies); - expect(node.assignment!.assignmentId).not.toBe(f.assignment.assignmentId); - expect(ready).toMatchObject({ status: 'frozen', snapshotCommit: f.snapshotCommit, sourceDigest: f.frozenReady.sourceDigest }); - expect(ready.id).not.toBe(f.frozenReady.id); expect(ready.receiptIds).toBeUndefined(); - expect(host.verify.mock.calls.some(call => call[0].items.some(item => item.theoremName === 'Submission.original'))).toBe(false); - const cooperation = cooperationFor(f, state), worker = state.workers![1]!; - await cooperation.restore(); - const descriptor = { id: worker.id, role: worker.role, worktree: worker.worktree, ownedFiles: state.problem.ownedFiles }; - const action = await cooperation.next(descriptor, { maxTurns: Infinity, remainingMs: Infinity }); - const checked = vi.fn(); - const lifecycle = new WorkerProofLifecycle({ state, research: worker, worker: descriptor, cooperation, - close: async () => {}, save: () => {}, emit: () => {}, checked }); - try { - expect(await lifecycle.resumeFrozen(action)).toBe(true); - expect(checked).toHaveBeenCalledOnce(); - expect(ready.status).toBe('checked'); expect(ready.receiptIds?.length).toBeGreaterThan(0); - expect(host.verify.mock.calls.some(call => call[0].items.some(item => item.theoremName === 'Submission.original'))).toBe(true); - } finally { await cooperation.stop(); } - expect(fs.readFileSync(f.stateFile)).toEqual(historical); - }); - - it.each(['assignment', 'submission', 'ready-id', 'snapshot', 'digest', 'seed', 'task-version', 'environment'] as const)( - 'rejects a missing-assignment continuation with changed %s identity', async kind => { - const f = await lostFrozenAssignmentFixture(), ready = f.source.cooperation!.proofReadyRecords![0]!; - if (kind === 'assignment') ready.assignmentKey = 'DELIVERIES-wrong.jsonl'; - else if (kind === 'submission') ready.submissionId = mathDigest('different-submission'); - else if (kind === 'ready-id') ready.id = mathDigest('different-ready'); - else if (kind === 'snapshot') { - const worker = f.source.workers![1]!; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Different commit with identical owned proof sources.\n'); - ready.snapshotCommit = commit(worker.worktree, 'Different frozen identity'); - } else if (kind === 'digest') ready.sourceDigest = '0'.repeat(64); - else if (kind === 'seed') ready.seedCommit = f.base; - else if (kind === 'task-version') ready.taskDigest = '0'.repeat(64); - else ready.environmentDigest = '0'.repeat(64); - writeSolverRunState(f.stateFile, f.source); - const next = nextContinuation(f, f.stateFile, `changed-frozen-${kind}`); - await expect(next.seed()).rejects.toThrow('math_continuation_seed_frozen_identity_changed'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('requires an intact digest-bound frozen attachment to recover a missing assignment', async () => { - const f = await lostFrozenAssignmentFixture(); - const snapshot = readContinuationSnapshot(path.join(f.directory, 'continuation.json'), f.source.continuationDigest!); - const attachment = snapshot.manifest.attachments.find(item => item.id === 'frozen-goal')!; - const file = path.join(f.directory, attachment.contentPath); - fs.chmodSync(file, 0o600); fs.writeFileSync(file, 'x'.repeat(attachment.bytes)); fs.chmodSync(file, 0o400); - const next = nextContinuation(f, f.stateFile, 'corrupted-frozen-attachment'); - await expect(next.seed()).rejects.toThrow('math_continuation_content_changed'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('rejects a missing assignment without trusted continuation metadata', async () => { - const f = frozenGoalFixture(); - delete f.oldState.cooperation!.tasks.find(node => node.task.id === 'goal')!.assignment; - writeSolverRunState(f.sourceStateFile, f.oldState); - await expect(f.seed()).rejects.toThrow('math_continuation_seed_frozen_identity_changed'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('defers its exact goal snapshot to the ordinary lifecycle without a new model writer', async () => { - const f = frozenGoalFixture(), historical = fs.readFileSync(f.sourceStateFile); - const report = await f.seed(), state = readSolverRunState(f.stateFile); - const node = state.cooperation!.tasks.find(node => node.task.id === 'goal')!; - const ready = state.cooperation!.proofReadyRecords![0]!; - expect(report.checked).not.toContain('goal'); - expect(host.verify.mock.calls.flatMap(call => call[0].items).some(item => item.theoremName === 'Submission.original')).toBe(false); - expect(node.status).toBe('pending'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - expect(ready.status).toBe('frozen'); expect(ready.snapshotCommit).toBe(f.snapshotCommit); - expect(ready.sourceDigest).toBe(f.ready.sourceDigest); expect(ready.id).not.toBe(f.ready.id); - expect(ready.receiptIds).toBeUndefined(); expect(node.assignment!.assignmentId).not.toBe('old-frozen-goal'); - const cooperation = cooperationFor(f, state), worker = state.workers![1]!; - await cooperation.restore(); - const descriptor = { id: worker.id, role: worker.role, worktree: worker.worktree, ownedFiles: state.problem.ownedFiles }; - const action = await cooperation.next(descriptor, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind).toBe('task'); - const close = vi.fn(async () => {}), checked = vi.fn(), emit = vi.fn(); - const lifecycle = new WorkerProofLifecycle({ state, research: worker, worker: descriptor, cooperation, close, - save: () => {}, emit, checked }); - try { - expect(await lifecycle.resumeFrozen(action)).toBe(true); - expect(close).toHaveBeenCalledOnce(); expect(checked).toHaveBeenCalledOnce(); - expect(emit).toHaveBeenCalledWith('proof_ready_checked', expect.objectContaining({ commit: f.snapshotCommit, passed: true })); - expect(ready.status).toBe('checked'); expect(ready.receiptIds?.length).toBeGreaterThan(0); - expect(host.verify.mock.calls.some(call => call[0].items.some(item => item.theoremName === 'Submission.original'))).toBe(true); - } finally { await cooperation.stop(); } - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - }); - - it.each(['digest', 'assignment', 'receipt', 'environment', 'task-version', 'seed'] as const)('rejects a frozen record with changed %s identity', async kind => { - const f = frozenGoalFixture(), ready = f.oldState.cooperation!.proofReadyRecords![0]!; - if (kind === 'digest') ready.sourceDigest = '0'.repeat(64); - else if (kind === 'assignment') ready.assignmentKey = 'DELIVERIES-wrong.jsonl'; - else if (kind === 'receipt') ready.problemReceiptDigest = '0'.repeat(64); - else if (kind === 'environment') ready.environmentDigest = '0'.repeat(64); - else if (kind === 'task-version') ready.taskDigest = '0'.repeat(64); - else ready.seedCommit = f.base; - writeSolverRunState(f.sourceStateFile, f.oldState); - await expect(f.seed()).rejects.toThrow('math_continuation_seed_frozen_identity_changed'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('requires the source run lease and refuses a quarantined writer', async () => { - const f = frozenGoalFixture(); - await withMathRuntimeLease({ lockPath: path.join(f.oldDirectory, 'run.lock'), flockExecutable: '/usr/bin/flock' }, - async () => { await expect(f.seed()).rejects.toThrow('math_runtime_lease_busy'); }); - f.oldState.workers![1]!.writerStopUnconfirmed = { at: 1, reason: 'unconfirmed-fixture' }; - writeSolverRunState(f.sourceStateFile, f.oldState); - await expect(f.seed()).rejects.toThrow('math_continuation_seed_frozen_writer_unconfirmed'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('keeps a candidate with a changed destination environment advisory', async () => { - const f = frozenGoalFixture(); - f.newState.environmentDigest = mathDigest('different-runtime-environment'); writeSolverRunState(f.stateFile, f.newState); - await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.proofReadyRecords).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'goal')!.assignment).toBeUndefined(); - }); - - it('repeats prepared seeding with the same frozen source without duplicating execution records', async () => { - const f = frozenGoalFixture(), worker = f.newState.workers![1]!.worktree; - const local = [path.join(worker, '.scratch', 'new-proof.lean'), - path.join(worker, f.projectRelative, '.lake', 'build', 'cached.olean')]; - for (const file of local) { - fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, 'Preserved local work\n'); - } - await f.seed(); - const first = readSolverRunState(f.stateFile).cooperation!.proofReadyRecords; - await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.proofReadyRecords).toEqual(first); - for (const file of local) expect(fs.readFileSync(file, 'utf8')).toBe('Preserved local work\n'); - }); - - it.each([ - { initialization: 'first', kind: 'uncommitted' }, - { initialization: 'first', kind: 'committed' }, - { initialization: 'repeated', kind: 'uncommitted' }, - { initialization: 'repeated', kind: 'committed' }, - ] as const)( - 'does not overwrite $kind destination worker proof work during $initialization frozen initialization', async ({ initialization, kind }) => { - const f = frozenGoalFixture(); - if (initialization === 'repeated') await f.seed(); - const worker = readSolverRunState(f.stateFile).workers![1]!.worktree; - const proof = path.join(worker, f.projectRelative, 'Submission.lean'); - fs.appendFileSync(proof, '\n-- New destination worker proof work\n'); - if (kind === 'committed') commit(worker, 'New destination worker proof work'); - const before = fs.readFileSync(proof), head = git(worker, ['rev-parse', 'HEAD']); - const state = fs.readFileSync(f.stateFile), historical = fs.readFileSync(f.sourceStateFile); - host.verify.mockClear(); host.prepare.mockClear(); - const error = await f.seed().then(() => undefined, (error: unknown) => error); - expect(fs.readFileSync(proof)).toEqual(before); - expect(error).toMatchObject({ message: 'math_continuation_seed_destination_changed' }); - expect(git(worker, ['rev-parse', 'HEAD'])).toBe(head); - expect(fs.readFileSync(f.stateFile)).toEqual(state); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - expect(host.verify).not.toHaveBeenCalled(); expect(host.prepare).not.toHaveBeenCalled(); - }); - - it.each(['first', 'repeated'] as const)( - 'does not overwrite untracked destination proof notes during %s frozen initialization', async initialization => { - const f = frozenGoalFixture(), worker = f.newState.workers![1]!.worktree; - if (initialization === 'repeated') { - await f.seed(); - git(worker, ['reset', '--hard', f.base]); - } - const notes = path.join(worker, 'RESEARCH.md'), before = 'New destination proof notes\n'; - fs.writeFileSync(notes, before); - expect(git(worker, ['status', '--porcelain', '--untracked-files=no'])).toBe(''); - const state = fs.readFileSync(f.stateFile), historical = fs.readFileSync(f.sourceStateFile); - host.verify.mockClear(); host.prepare.mockClear(); - const error = await f.seed().then(() => undefined, (error: unknown) => error); - expect(fs.readFileSync(notes, 'utf8')).toBe(before); - expect(error).toMatchObject({ message: 'math_continuation_seed_destination_changed' }); - expect(git(worker, ['rev-parse', 'HEAD'])).toBe(f.base); - expect(fs.readFileSync(f.stateFile)).toEqual(state); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - expect(host.verify).not.toHaveBeenCalled(); expect(host.prepare).not.toHaveBeenCalled(); - }); - - it('keeps a frozen goal advisory when the destination worker can no longer prove goals', async () => { - const f = frozenGoalFixture(); - f.newState.workers![1]!.role = 'prover'; writeSolverRunState(f.stateFile, f.newState); - await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.proofReadyRecords).toBeUndefined(); - }); - - it('does not replace a freshly rechecked canonical goal with a pending snapshot', async () => { - const f = frozenGoalFixture(), node = f.oldState.cooperation!.tasks.find(node => node.task.id === 'goal')!; - f.oldState.cooperation!.canonicalCommit = f.snapshotCommit; - node.integratedCheck = { ...f.oldState.cooperation!.tasks[0]!.integratedCheck!, commit: f.snapshotCommit, - taskDigest: taskVersion(node.task) }; - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); - const state = readSolverRunState(f.stateFile), goal = state.cooperation!.tasks.find(node => node.task.id === 'goal')!; - expect(goal.status).toBe('integrated'); expect(goal.integratedCheck?.passed).toBe(true); - expect(state.cooperation!.proofReadyRecords).toBeUndefined(); - }); - - it('migrates a host definition check without a fabricated gap delivery or proof acceptance', async () => { - const f = fixture(), cooperation = f.oldState.cooperation!; - const witness: CooperativeTask = { id: 'witness', kind: 'lemma', declaration: 'definition', revision: 0, - objective: 'Construct the shared witness.', theoremName: 'Submission.Helpers.witness', - proofPath: 'Submission/Helpers.lean', type: 'Nat', dependsOn: [] }; - cooperation.tasks.push({ task: witness, status: 'pending', attempts: 0 }); - for (const node of cooperation.tasks.filter(node => ['first', 'second'].includes(node.task.id))) { - node.task = { ...node.task, dependsOn: ['witness'] }; - setTaskStatus(node, 'pending', 'reconstructed'); - delete node.integratedCheck; delete node.assignment; - } - const identity = { problemReceiptDigest: f.oldState.problem.receiptDigest, environmentDigest: f.oldState.environmentDigest }; - const [proposed] = proposedDefinitionContractChecks(cooperation, identity, 11); - expect(proposed).toBeDefined(); - cooperation.nextChecks = [proposed.record]; cooperation.tasks.push(proposed.node); - writeSolverRunState(f.sourceStateFile, f.oldState); - const historical = fs.readFileSync(f.sourceStateFile); - await f.seed(); - const restored = readSolverRunState(f.stateFile).cooperation!; - expect(restored.nextChecks).toEqual([proposed.record]); - const check = restored.tasks.find(node => node.nextCheckId === proposed.record.id)!; - expect(check).toMatchObject({ task: proposed.node.task, status: 'pending' }); - expect(check.proof).toBeUndefined(); expect(check.integratedCheck).toBeUndefined(); - expect(restored.nextChecks![0].gapDeliveryId).toBeUndefined(); - expect(restored.deliveries!.some(delivery => delivery.mathematicalGap)).toBe(false); - await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.nextChecks).toHaveLength(1); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - }); - - it.each(['pending', 'decided'] as const)('migrates a scoped %s check and its parent evidence without reopening it', async status => { - const f = fixture(), cooperation = f.oldState.cooperation!, goal = cooperation.tasks.find(node => node.task.id === 'goal')!.task; - const source: CooperativeTask = { id: 'membership_audit', kind: 'research', objective: 'Inspect the missing membership inference.', - revision: 0, dependsOn: ['goal'] }; - cooperation.tasks.push({ task: source, status: 'completed', attempts: 1 }); - const identity = { problemReceiptDigest: f.oldState.problem.receiptDigest, environmentDigest: f.oldState.environmentDigest }; - const gap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, previousGap: 'Membership was assumed.', - reduced: 'The candidate is specified.', remaining: 'Its membership remains unknown.', evidenceScope: 'Original assumptions.', - reconsiderWhen: [], nextCheck: { action: 'construction-check' as const, objective: 'Check membership.', expectedEvidence: 'A valid application or exact missing premise.' } }; - const finding = JSON.stringify({ taskId: source.id, taskDigest: taskVersion(source), conclusion: 'inconclusive', - summary: 'Check membership next.', mathematicalGap: gap }); - cooperation.deliveries!.push({ id: 'membership-gap', taskId: source.id, taskDigest: taskVersion(source), producer: 'prover-1', - kind: 'research', status: 'advisory', statement: source.objective, premises: [], dependencies: [], remainingObligations: [gap.remaining], - summary: 'Check membership next.', evidenceRefs: [], createdAt: 10, commit: cooperation.canonicalCommit, - finding, findingDigest: mathDigest(finding), mathematicalGap: gap, - mathematicalGapScope: bindMathematicalGap(gap, source, cooperation, identity) }); - const proposed = proposedNextChecks(cooperation, identity, 11)[0]!; - const checkFinding = 'The attempted application still requires membership.'; - if (status === 'decided') { - const { id, taskId, taskDigest, scope } = proposed.record; - const outcome = { checkId: id, conclusion: 'inconclusive' as const, summary: checkFinding, evidenceRefs: [] }; - proposed.record.status = status; - proposed.record.outcome = { ...outcome, deliveryId: 'membership-outcome' }; - proposed.record.decision = { checkId: id, outcomeDeliveryId: 'membership-outcome', action: 'stop', reason: checkFinding, at: 13 }; - cooperation.deliveries!.push({ id: 'membership-outcome', taskId, taskDigest, producer: 'prover-1', kind: 'research', - status: 'advisory', statement: proposed.node.task.objective, premises: [], dependencies: [], remainingObligations: [], - summary: checkFinding, evidenceRefs: [], createdAt: 12, checkOutcome: outcome, checkOutcomeScope: scope }); - } - cooperation.nextChecks = [proposed.record]; - cooperation.tasks.push(status === 'decided' ? { ...proposed.node, status: 'completed', finding: checkFinding } : proposed.node); - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); - const restored = readSolverRunState(f.stateFile).cooperation!; - expect(restored.nextChecks).toEqual([proposed.record]); - expect(restored.tasks.find(node => node.nextCheckId === proposed.record.id)).toMatchObject({ task: proposed.node.task, - ...(status === 'decided' ? { status: 'completed', finding: checkFinding } : { status: 'pending' }) }); - expect(restored.deliveries!.find(delivery => delivery.id === 'membership-gap')?.mathematicalGap?.nextCheck).toEqual(gap.nextCheck); - expect(restored.tasks.find(node => node.nextCheckId)?.proof).toBeUndefined(); - await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation!.nextChecks).toHaveLength(1); - }); - - it.each(['pinned', 'legacy', 'missing'] as const)('restores a progress-origin proof search with a %s checkpoint', async mode => { - const f = fixture(), cooperation = f.oldState.cooperation!, goal = f.tasks[2]!, helper = f.tasks[0]!; - const identity = { problemReceiptDigest: f.oldState.problem.receiptDigest, environmentDigest: f.oldState.environmentDigest }; - const scope = { ...identity, taskId: helper.id, taskDigest: taskVersion(helper) }; - const saved = emptyProofSearchCheckpoint({ scope, sourceDigest: mathDigest('source'), projectionDigest: mathDigest('projection'), - backendDigest: mathDigest('backend'), target: { file: helper.proofPath!, theoremName: helper.theoremName!, type: helper.type! }, - environment: { environmentDigest: mathDigest('diagnostic env') }, sourceFiles: [] }); - saved.replaySources = [{ file: helper.proofPath!, source: helpers }]; - const basisDigest = mathDigest(canonicalMathJson(saved.basis)), sourceProject = path.join(f.sourceWorktree, f.projectRelative); - const retain = (generation: number, history?: string) => { - const file = localProofSearchPath(sourceProject, basisDigest, generation, history); - const bytes = canonicalMathJson({ ...saved, generation }); - fs.mkdirSync(path.dirname(file), { recursive: true }); - fs.writeFileSync(file, bytes, { mode: 0o400 }); - return retainProofSearchCheckpoint({ projectRoot: sourceProject, runDirectory: f.oldDirectory, - reference: { path: file, digest: mathDigest(bytes) }, scope, history, workerId: 'prover-1', assignmentKey: 'fixture' }); - }; - const owner = retain(0); - cooperation.proofSearchRecords = { [helper.id]: owner }; - const gap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, previousGap: 'Membership was assumed.', - reduced: 'The candidate is specified.', remaining: 'Membership remains unknown.', evidenceScope: 'Original assumptions.', - reconsiderWhen: [], nextCheck: { action: 'construction-check' as const, objective: 'Check one branch.', - expectedEvidence: 'A candidate or an open goal.', execution: { kind: 'proof-search' as const, - taskId: helper.id, taskDigest: scope.taskDigest, basis: basisDigest, - ...(mode === 'legacy' ? {} : { checkpoint: owner.checkpoint }), node: saved.nodes[0]!.id } } }; - cooperation.deliveries!.push({ id: 'search-gap', taskId: helper.id, taskDigest: taskVersion(helper), producer: 'prover-1', - kind: 'progress', status: 'conditional', statement: helper.objective, premises: [], dependencies: [], remainingObligations: [gap.remaining], - summary: 'Check the branch.', evidenceRefs: [], createdAt: 10, mathematicalGap: gap, - mathematicalGapScope: bindMathematicalGap(gap, helper, cooperation, identity) }); - const proposed = proposedNextChecks(cooperation, identity, 11)[0]!; - if (mode === 'legacy') delete proposed.record.proofSearchSeed; - cooperation.nextChecks = [proposed.record]; cooperation.tasks.push(proposed.node); - const working = mode === 'pinned' ? retain(1, proposed.record.id) : undefined; - if (working) cooperation.proofSearchRecords[proposed.record.taskId] = working; - if (mode === 'missing') fs.unlinkSync(owner.checkpoint.path); - expect(currentNextCheck(proposed.record, cooperation, identity)).toBe(true); - writeSolverRunState(f.sourceStateFile, f.oldState); - await f.seed(); - const restored = readSolverRunState(f.stateFile).cooperation!, check = restored.nextChecks![0]!; - expect(restored.deliveries!.find(delivery => delivery.id === 'search-gap')).toMatchObject({ kind: 'progress', status: 'conditional' }); - if (mode === 'missing') { - expect(currentNextCheck(check, restored, identity)).toBe(false); - expect(check.status).toBe('stale'); - expect(restored.tasks.find(node => node.nextCheckId === check.id)).toMatchObject({ status: 'blocked' }); - } else { - expect(currentNextCheck(check, restored, identity)).toBe(true); - const selected = proofSearchRecordForAssignment(restored.proofSearchRecords, scope, check); - expect(selected?.checkpoint.digest).toBe((working ?? owner).checkpoint.digest); - expect(Boolean(restored.proofSearchRecords?.[helper.id])).toBe(mode === 'legacy'); - const projected = projectProofSearchRecord({ record: selected, scope, runDirectory: f.directory, history: check.id, - projectRoot: path.join(f.newState.workers![1]!.worktree, f.projectRelative) }); - expect(projected?.checkpoint.digest).toBe(selected!.checkpoint.digest); - expect(fs.readFileSync(projected!.checkpoint.path)).toEqual(fs.readFileSync((working ?? owner).checkpoint.path)); - if (mode === 'pinned') { - expect(check.proofSearchSeed?.checkpoint.digest).toBe(owner.checkpoint.digest); - expect(check.proofSearchSeed?.checkpoint.path).toContain(f.directory); - } - for (const record of [owner, working]) if (record) fs.unlinkSync(record.checkpoint.path); - } - await f.seed(); - expect(readSolverRunState(f.stateFile).cooperation?.nextChecks).toEqual(restored.nextChecks); - }); -}); diff --git a/tests/cooperativeReplay.test.ts b/tests/cooperativeReplay.test.ts deleted file mode 100644 index 0a0da664..00000000 --- a/tests/cooperativeReplay.test.ts +++ /dev/null @@ -1,170 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { COOPERATIVE_REPLAY_SOURCE, cooperativeReplay, cooperativeReplayAccepted, cooperativeReplayActors, - cooperativeReplayAssignment, replayCooperative } from '../scripts/mathematics/cooperativeReplay'; -import type { MathAgentOptions } from '../src/runtime/codexSession'; -import type { SolverRunState } from '../src/solver/archive'; -import { directSolverModules } from '../src/solver/modules'; -import { taskCanStart } from '../src/solver/modules/search'; -import { leadResearchInputSection, type TaskContextInput } from '../src/solver/contextCompiler'; -import type { DeliveryRecord } from '../src/solver/deliveries'; -import { answerResearchInputs } from '../src/solver/researchDecisions'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { leadPlanDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; - -const directories: string[] = []; -const temporary = () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cooperative-replay-')); directories.push(directory); return directory; }; -const read = (file: string) => JSON.parse(fs.readFileSync(file, 'utf8')); -const researchDelivery = (id: string, task: CooperativeTask, - finding: { summary: string; lemmaRequests?: CooperativeTask[] } & Record): DeliveryRecord => ({ - id, producer: task.ownerId!, taskId: task.id, taskDigest: taskVersion(task), findingDigest: mathDigest(JSON.stringify(finding)), - kind: 'research', status: 'advisory', statement: '', premises: [], dependencies: [], remainingObligations: [], - summary: finding.summary, evidenceRefs: [], createdAt: 1, finding: JSON.stringify(finding), lemmaRequests: finding.lemmaRequests, -}); -const researchContext = (tasks: TaskRecord[], deliveries: DeliveryRecord[], leadResearchInputIds?: string[]) => - leadResearchInputSection({ cooperation: { tasks, deliveries, leadResearchInputIds } as TaskContextInput['cooperation'] })?.text ?? ''; -afterEach(() => { vi.restoreAllMocks(); for (const directory of directories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }); }); - -describe('scripted cooperative replay', () => { - it('reads current initial and continuation assignments and rejects non-model assembly', () => { - const first = { kind: 'lead', seedCommit: 'first' }, current = { kind: 'lead', seedCommit: 'current', planNonce: 'new' }; - expect(cooperativeReplayAssignment('Cooperative assignment:\n' + JSON.stringify(first))).toEqual(first); - expect(cooperativeReplayAssignment('Cooperative assignment:\n' + JSON.stringify(first) + - '\nCurrent cooperative assignment (replaces every previous dispatch nonce and receipt):\n' + JSON.stringify(current))).toEqual(current); - expect(() => cooperativeReplayAssignment('No assignment was dispatched.')).toThrow('assignment_missing'); - expect(() => cooperativeReplayAssignment('Cooperative assignment:\n{"kind":"assemble"}')).toThrow('unexpected_assignment'); - }); - - it('publishes a nonce-bound research-to-proof handoff and retains the failed draft and independent review', async () => { - const directory = temporary(), trace = path.join(directory, 'trace'); - fs.mkdirSync(path.join(directory, 'generated/problem'), { recursive: true }); - const source = path.join(directory, 'generated/problem/Submission.lean'); - fs.writeFileSync(source, COOPERATIVE_REPLAY_SOURCE); - const actors = cooperativeReplayActors('repair-once', trace); - expect(actors.modules.M1.execute).toBe(directSolverModules.M1.execute); - expect(actors.modules.M2).toBe(directSolverModules.M2); - expect(actors.modules.M3).toBe(directSolverModules.M3); - expect(actors.modules.M4).toBe(directSolverModules.M4); - expect(actors.modules.M5).toBe(directSolverModules.M5); - const usage = vi.fn(), started = vi.fn(); - const run = async (workerId: string, action: CooperativeAction) => { - const session = await actors.modules.M1.open({ workspace: directory, executable: 'must-not-start-a-process', profile: directory, - model: 'scripted-zero-model', effort: 'none', instructions: 'Frozen fixture instructions.', onUsage: usage, - environment: { DEEPSCIENTIST_MATH_WORKER_ID: workerId } } as MathAgentOptions); - const viewFile = path.join(directory, 'COOPERATION.json'), view = fs.existsSync(viewFile) ? read(viewFile) : undefined; - const context = action.kind === 'lead' && view ? researchContext(view.tasks, view.deliveries) : ''; - expect(await session.run('Cooperative assignment:\n' + JSON.stringify(action) + '\n' + context, 'message', directory, started)).toBe('completed'); - await session.close(); - return fs.readFileSync(path.join(directory, 'RESEARCH.md'), 'utf8'); - }; - const initial: CooperativeAction = { kind: 'lead', seedCommit: 'seed', initialPlanNonce: 'initial', planVersion: 'base' }; - await run('solver', initial); - const first = read(path.join(directory, leadPlanDeliveryFile(initial)!)); - expect(first).toMatchObject({ kind: 'plan', dispatchNonce: 'initial', baseVersion: 'base' }); - const tasks: CooperativeTask[] = first.tasks; - const question = tasks.find(task => task.kind === 'research')!, goal = tasks.find(task => task.kind === 'goal')!; - expect(goal).toMatchObject({ status: 'paused', conditional: false }); - const writeView = (nodes: unknown[], deliveries: unknown[] = []) => fs.writeFileSync(path.join(directory, 'COOPERATION.json'), - JSON.stringify({ tasks: nodes, deliveries })); - const assignment = (task: CooperativeTask) => ({ kind: 'task' as const, task, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: task.ownerId!, seedCommit: 'seed', assignmentId: task.id } }); - writeView(tasks.map(task => ({ task, status: 'pending', attempts: 0 }))); - const finding = JSON.parse(await run('researcher-2', assignment(question))); - expect(finding).toMatchObject({ conclusion: 'supporting', needsDecision: true, lemmaRequests: [{ theoremName: 'Replay.climb_eq' }] }); - // Host-published proposals carry their normalized group in the actual prompt. - const helper = { ...finding.lemmaRequests[0], groupId: 'main' } as CooperativeTask; - const deliveries = [researchDelivery('published-helper', question, { ...finding, lemmaRequests: [helper] })]; - writeView([{ task: question, status: 'completed', attempts: 1 }, { task: goal, status: 'pending', attempts: 0 }], deliveries); - const adoption: CooperativeAction = { kind: 'lead', seedCommit: 'seed', planNonce: 'adopt', planVersion: 'v1' }; - await run('solver', adoption); - const adopted = read(path.join(directory, leadPlanDeliveryFile(adoption)!)); - expect(adopted).toMatchObject({ baseVersion: 'v1', upsert: [helper, - { id: goal.id, status: 'active', dependsOn: [helper.id] } ] }); - const activeGoal = { ...goal, status: 'active' as const, dependsOn: [helper.id] }; - expect(answerResearchInputs(adopted, deliveries, tasks, [question, helper, activeGoal], [], 'v1')) - .toMatchObject([{ deliveryId: 'published-helper', outcome: 'adopt', taskIds: [helper.id] }]); - const dependencies = [{ task: helper, status: 'pending' as const, attempts: 0 }, - { task: activeGoal, status: 'pending' as const, attempts: 0 }]; - expect(taskCanStart(activeGoal, dependencies)).toBe(false); - expect(taskCanStart(activeGoal, [{ ...dependencies[0], status: 'integrated' }, dependencies[1]])).toBe(true); - expect(fs.readFileSync(source, 'utf8')).toBe(COOPERATIVE_REPLAY_SOURCE); - - await run('engineer', assignment(helper)); - expect(fs.readFileSync(source, 'utf8')).toContain('exact Nat.zero_ne_one'); - await run('engineer', assignment(helper)); - expect(fs.readFileSync(source, 'utf8')).toContain('induction n with'); - expect(fs.readFileSync(source, 'utf8')).not.toContain('exact Nat.zero_ne_one'); - expect(actors.turns.filter(turn => turn.injectedFailure)).toHaveLength(1); - expect(fs.readFileSync(actors.turns[3].source, 'utf8')).toContain('exact Nat.zero_ne_one'); - - writeView([{ task: question, status: 'completed', attempts: 1 }, { task: helper, status: 'integrated', attempts: 2 }, - { task: goal, status: 'pending', attempts: 0 }], deliveries); - await run('engineer', assignment(activeGoal)); - const solved = fs.readFileSync(source, 'utf8'); - expect(solved).toContain('rw [climb_eq n]'); expect(solved).not.toContain('sorry'); - await run('researcher-1', { kind: 'review', seedCommit: 'checked-original', sourceDigest: 'exact-source' }); - expect(fs.readFileSync(source, 'utf8')).toBe(solved); - expect(fs.readFileSync(path.join(directory, 'RESEARCH.md'), 'utf8')).toContain('"commit":"checked-original","verdict":"accepted"'); - expect(new Set(actors.turns.map(turn => turn.role))).toEqual(new Set(['lead', 'researcher', 'engineer', 'reviewer'])); - expect(read(path.join(trace, 'turns.json'))).toHaveLength(7); - for (const turn of actors.turns) for (const file of [turn.context, turn.output, turn.source]) expect(fs.existsSync(file)).toBe(true); - expect(usage).toHaveBeenCalledTimes(7); expect(started).toHaveBeenCalledTimes(7); - }); - - it('answers the current research page and leaves an inconclusive gap to its next-check', async () => { - const directory = temporary(); - fs.mkdirSync(path.join(directory, 'generated/problem'), { recursive: true }); - fs.writeFileSync(path.join(directory, 'generated/problem/Submission.lean'), COOPERATIVE_REPLAY_SOURCE); - const question: CooperativeTask = { id: 'research_bridge', kind: 'research', ownerId: 'researcher-2', - objective: 'Check the recursion.', dependsOn: [], revision: 0 }; - const goal: CooperativeTask = { id: 'original', kind: 'goal', objective: 'Prove Replay.target.', status: 'paused', - proofPath: 'Submission.lean', theoremName: 'Replay.target', dependsOn: [], revision: 0 }; - const helper: CooperativeTask = { id: 'climb_identity', kind: 'lemma', ownerId: 'engineer', - objective: 'Induct on n to prove climb is the identity; Replay.target consumes two instances at n.', - proofPath: 'Submission.lean', theoremName: 'Replay.climb_eq', type: '∀ n : Nat, Replay.climb n = n', - dependsOn: [], revision: 0, groupId: 'main' }; - const tasks: TaskRecord[] = [{ task: question, status: 'completed', attempts: 1 }, { task: goal, status: 'pending', attempts: 0 }]; - const gap = researchDelivery('gap', question, { summary: 'The induction invariant needs a construction check.', - conclusion: 'inconclusive', needsDecision: true, mathematicalGap: { nextCheck: { action: 'construction-check' } } }); - const wrong = researchDelivery('wrong-interface', question, { summary: 'A pointwise instance is insufficient.', - conclusion: 'supporting', lemmaRequests: [{ ...helper, type: 'Replay.climb 0 = 0' }] }); - const late = researchDelivery('not-shown', question, { summary: 'A later helper publication.', - conclusion: 'supporting', lemmaRequests: [helper] }); - const deliveries = [gap, wrong, late]; - fs.writeFileSync(path.join(directory, 'COOPERATION.json'), JSON.stringify({ tasks, deliveries })); - const actors = cooperativeReplayActors('next-check', path.join(directory, 'trace')); - const session = await actors.modules.M1.open({ workspace: directory, executable: 'must-not-start-a-process', profile: directory, - model: 'scripted-zero-model', effort: 'none', instructions: 'Frozen fixture instructions.', onUsage: vi.fn(), - environment: { DEEPSCIENTIST_MATH_WORKER_ID: 'solver' } } as MathAgentOptions); - const action: CooperativeAction = { kind: 'lead', seedCommit: 'seed', planNonce: 'current-page', planVersion: 'v1' }; - await session.run('Cooperative assignment:\n' + JSON.stringify(action) + '\n' + - researchContext(tasks, deliveries, [late.id]) + '\n' + researchContext(tasks, deliveries, [gap.id, wrong.id]), - 'message', directory, vi.fn()); - await session.close(); - const plan = read(path.join(directory, leadPlanDeliveryFile(action)!)); - expect(plan.upsert).toEqual([]); - const decisions = answerResearchInputs(plan, [wrong, gap], [question, goal], [question, goal], [], 'v1'); - expect(decisions).toMatchObject([{ deliveryId: wrong.id, outcome: 'decline' }, { deliveryId: gap.id, outcome: 'decline' }]); - expect(plan.researchDecisions).toHaveLength(2); - expect(decisions.find(decision => decision.deliveryId === gap.id)?.reason).toContain('next-check'); - }); - - it('does not treat scripted completion or an accepted review as independent final acceptance', () => { - const result = { status: 'evaluated_passed', completion_signal_valid: true, solver_ready_receipt_valid: true, - solution_commit: 'claimed', evaluator: { status: 'passed', method: 'host-lean-kernel-all-targets' } }; - const state = { phase: 'finished', check: { passed: true, commit: 'claimed' }, problem: { targets: [] } } as unknown as SolverRunState; - expect(cooperativeReplayAccepted(state, result)).toBe(false); - expect(cooperativeReplayAccepted({ ...state, check: { ...state.check!, passed: false } }, result)).toBe(false); - expect(cooperativeReplayAccepted({ ...state, phase: 'running' }, result)).toBe(false); - }); - - it('requires an existing build manifest and preserves an existing replay directory', async () => { - const directory = temporary(); - fs.writeFileSync(path.join(directory, 'evidence'), 'retained'); - await expect(replayCooperative(directory, '/unused', '/unused')).rejects.toThrow('Replay directory already exists'); - expect(fs.readFileSync(path.join(directory, 'evidence'), 'utf8')).toBe('retained'); - await expect(cooperativeReplay(['--directory', directory])).rejects.toThrow('--build-manifest is required'); - }); -}); diff --git a/tests/coordinationSimulation.test.ts b/tests/coordinationSimulation.test.ts deleted file mode 100644 index ebc95835..00000000 --- a/tests/coordinationSimulation.test.ts +++ /dev/null @@ -1,223 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch, parseCooperationPlan } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { checkSolverRunState, restoreResidue } from '../src/solver/stateInvariants'; -import { leadPlanDeliveryFile, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn(), failing: false })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -/** mulberry32: small, seedable and stable across platforms. */ -function random(seed: number) { - return () => { - seed = (seed + 0x6d2b79f5) | 0; - let value = Math.imul(seed ^ (seed >>> 15), 1 | seed); - value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value; - return ((value ^ (value >>> 14)) >>> 0) / 4294967296; - }; -} - -const PROOFS: Record = { - 'Tutorial.add_zero': ['n + 0 = n := ', 'by rfl'], - 'Tutorial.zero_add': ['0 + n = n := ', 'by exact Nat.zero_add n'], -}; -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -const settle = () => new Promise(resolve => setTimeout(resolve, 5)); - -type Slot = { promise: Promise; done?: { action: CooperativeAction | undefined } }; -type Outcome = { status: 'assembled' | 'deadlock' | 'violation' | 'exhausted'; steps: number; trace: string[]; - detail?: unknown }; - -/** - * Drives the real cooperation layer the way research.ts does (next → started → activate → deliver/interrupted/ - * stopped → deactivate) with scripted writers. Faults are drawn from a seeded stream, so any failure replays. - */ -async function simulate(seed: number, cleanup: (() => Promise)[], maxSteps = 120): Promise { - const draw = random(seed), trace: string[] = []; - const example = localExample(`coordination-simulation-${seed}-`); - const { directory, workspace } = example; - const problem: SolverProblem = example.problem; - const lead = leadWorker(problem, workspace); - // The smallest realistic roster: goals belong to the engineer role, lemmas to provers, research to researchers. - const peers = [peerWorker(example, 'engineer', { role: 'engineer' }), peerWorker(example, 'prover-1', { role: 'prover' }), - peerWorker(example, 'researcher-1', { role: 'researcher' })]; - const workers = [lead, ...peers]; - const goals: CooperativeTask[] = problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}.`, theoremName: target.theoremName, proofPath: target.proofPath, - dependsOn: [], revision: 0 })); - const plan = parseCooperationPlan(problem, { tasks: goals }); - const planGraph = () => parseCooperationPlan(problem, { - tasks: state.cooperation!.tasks.map(node => node.task), groups: state.cooperation!.groups?.map(route => route.group) }); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(plan) + '\n```'); - let state: SolverRunState = solverState(problem, workspace, { runId: `simulation-${seed}`, phase: 'running', failures: [], - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const events: string[] = []; - let controller = new AbortController(); - const create = () => cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => { events.push(event); if (process.env.THEOREM_OS_SIMULATION_DEBUG && /wait|refill/u.test(event)) - trace.push(`event ${event} ${JSON.stringify(details).slice(0, 600)}`); } }); - let cooperative: CooperativeResearch = create(); - cleanup.push(async () => { controller.abort(); await cooperative.stop().catch(() => {}); fs.rmSync(directory, { recursive: true, force: true }); }); - await cooperative.restore(); - const live = new Set(workers.map(worker => worker.id)); - let slots = new Map(), crashes = 0, helpers = 0; - const request = (worker: ResearchWorker) => { - const slot: Slot = { promise: cooperative.next(worker, budget) }; - slot.promise.then(action => { slot.done = { action }; }, error => { slot.done = { action: undefined }; trace.push(`next-error ${worker.id} ${error}`); }); - slots.set(worker.id, slot); - }; - const source = (worker: ResearchWorker) => path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - const prove = (worker: ResearchWorker, theorem: string, wrong: boolean) => { - // Repairs continue from the failed source, so replace whatever body the seed carries. - const text = fs.readFileSync(source(worker), 'utf8'); - if (!PROOFS[theorem]) { - const name = theorem.split('.').at(-1)!, index = name.split('_').at(-1)!; - const line = `theorem ${name} : ${index} = ${index} := ${wrong ? 'by simp' : 'rfl'}`; - fs.writeFileSync(source(worker), new RegExp(`^theorem ${name} .*$`, 'mu').test(text) - ? text.replace(new RegExp(`^theorem ${name} .*$`, 'mu'), line) : text.replace('end Tutorial', `${line}\n\nend Tutorial`)); - return commitSolverSources(problem, worker.worktree); - } - const [statement, body] = PROOFS[theorem]!; - fs.writeFileSync(source(worker), text.replace(new RegExp(`${statement.replace(/[+]/gu, '\\+')}.*$`, 'mu'), - statement + (wrong ? 'by simp' : body))); - return commitSolverSources(problem, worker.worktree); - }; - // Scheduling fields belong to research.ts; here liveness is judged by the dispatch loop itself. - const violations = () => checkSolverRunState(state).filter(item => !item.code.startsWith('quiescent_') && - item.severity === 'error'); - - for (let step = 0; step < maxSteps; step++) { - for (const worker of workers) if (live.has(worker.id) && !slots.has(worker.id)) request(worker); - // Real-time grace for host timers; a dispatch that never resolves is the lost wake-up being searched for. - for (let wait = 0; wait < 40 && ![...slots.values()].some(slot => slot.done); wait++) await settle(); - const ready = workers.filter(worker => slots.get(worker.id)?.done); - if (!ready.length) return { status: 'deadlock', steps: step, trace, detail: { - tasks: state.cooperation!.tasks.map(node => [node.task.id, node.status, node.assignment?.workerId]), - live: [...live], events: events.slice(-15) } }; - const broken = violations(); - if (broken.length) return { status: 'violation', steps: step, trace, detail: broken }; - if (draw() < 0.06) { - // Whole-process restart: unsaved slots are dropped exactly as a killed host drops them. - trace.push(`${step} restart`); - controller.abort(); await cooperative.stop(); - const file = path.join(directory, 'state.json'); - writeSolverRunState(file, state); state = readSolverRunState(file); - controller = new AbortController(); cooperative = create(); slots = new Map(); - // A new process starts every worker again, including one that crashed before the restart. - for (const item of workers) live.add(item.id); - await cooperative.restore(); - const residue = restoreResidue(state.cooperation!); - if (residue.length) return { status: 'violation', steps: step, trace, detail: { residue } }; - continue; - } - const worker = ready[Math.floor(draw() * ready.length)]!; - const action = slots.get(worker.id)!.done!.action; - slots.delete(worker.id); - if (!action) { - trace.push(`${step} ${worker.id} no-work`); - cooperative.stopped(worker); live.delete(worker.id); - if (worker.id === lead.id) return { status: 'deadlock', steps: step, trace, detail: { reason: 'lead stopped before assembly', - tasks: state.cooperation!.tasks.map(node => [node.task.id, node.status, node.assignment?.workerId, node.attempts]), - live: [...live], waits: state.workers!.map(item => [item.id, item.scheduling?.wait?.stage, - item.scheduling?.wait?.candidates.map(candidate => candidate.reason)]), events: events.slice(-10) } }; - continue; - } - if (action.kind === 'assemble') { trace.push(`${step} assemble`); return { status: 'assembled', steps: step, trace }; } - if (!cooperative.started(worker, action)) { trace.push(`${step} ${worker.id} ${action.kind} stale`); cooperative.release(worker, action); continue; } - cooperative.activate(worker, action, async () => {}, async () => {}); - const roll = draw(); - try { - if (action.kind === 'task') { - const label = `${step} ${worker.id} ${action.task.id}`; - // Losing the only engineer leaves goals unownable by design; crash only spare capacity. - if (roll < 0.12 && worker.role !== 'engineer' && worker.id !== lead.id && crashes < 1) { - trace.push(`${label} crash`); crashes++; - cooperative.deactivate(worker); cooperative.stopped(worker, 'math_worker_failed'); live.delete(worker.id); - continue; - } - if (roll < 0.3) { trace.push(`${label} interrupted`); cooperative.interrupted(worker, action); continue; } - const wrong = roll < 0.5; - const before = fs.readFileSync(source(worker), 'utf8'); - trace.push(`${label} ${wrong ? 'wrong' : 'proof'}` + (process.env.THEOREM_OS_SIMULATION_DEBUG - ? ` seeded=${JSON.stringify(before.split('\n').filter(line => line.includes(':=')))}` : '')); - host.failing = wrong; - try { - const result = await cooperative.deliver(worker, action, prove(worker, action.task.theoremName!, wrong)); - if (process.env.THEOREM_OS_SIMULATION_DEBUG) trace.push(` -> passed=${result.check?.passed} status=${ - state.cooperation!.tasks.find(node => node.task.id === action.task.id)?.status} feedback=${ - (state.cooperation!.tasks.find(node => node.task.id === action.task.id)?.feedback ?? '').slice(0, 300)}`); - } - catch (error) { - return { status: 'violation', steps: step, trace, detail: { thrown: String(error), events: events.slice(-12), - tasks: state.cooperation!.tasks.map(node => [node.task.id, node.status, node.assignment?.workerId, - Boolean(node.proof), Boolean(node.pendingValidation)]) } }; - } - } else if (action.kind === 'lead') { - // A failed original route is reconsidered in an ordinary plan turn; there is no separate recovery dispatch. - const failed = state.cooperation!.tasks.filter(node => node.status === 'blocked' && node.attempts > 0).map(node => node.task.id); - const mode = roll < 0.15 ? 'interrupted' : failed.length ? 'replan' : 'plan'; - trace.push(`${step} lead ${mode}${action.coordination ? ' coordination' : ''}`); - if (mode === 'interrupted') { cooperative.interrupted(worker, action); continue; } - // The bounded protocol: one complete event in the dispatch's delivery log, then the turn ends. - let graph = planGraph(); - if (mode === 'replan') { - // A new typed input for the failed tasks: the answer a real Lead gives after a failed route. - const helper: CooperativeTask = { id: `helper_${++helpers}`, kind: 'lemma', objective: 'Prove the auxiliary fact.', - // Lemma inputs are compared by type, not name: each new input must state a different fact. - theoremName: `Tutorial.helper_${helpers}`, proofPath: 'Submission.lean', type: `${helpers} = ${helpers}`, - dependsOn: [], revision: 0 }; - graph = parseCooperationPlan(problem, { ...graph, tasks: [...graph.tasks.map(item => failed.includes(item.id) - ? { ...item, dependsOn: [...item.dependsOn, helper.id] } : item), helper] }); - } - const file = leadPlanDeliveryFile(action); - if (file) fs.appendFileSync(path.join(worker.worktree, file), JSON.stringify({ kind: 'plan', - dispatchNonce: action.planNonce ?? action.initialPlanNonce, baseVersion: action.planVersion, - summary: mode === 'replan' ? 'Split the failed inference through a new helper.' - : 'The current graph remains the complete next step.', ...graph }) + '\n'); - else fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(graph) + '\n```\n'); - await cooperative.pulse(worker.id); - await cooperative.deliver(worker, action, commitSolverSources(problem, worker.worktree)); - } else { - trace.push(`${step} ${worker.id} ${action.kind} released`); - cooperative.release(worker, action); - } - } finally { host.failing = false; cooperative.deactivate(worker); } - } - return { status: 'exhausted', steps: maxSteps, trace, detail: state.cooperation!.tasks.map(node => [node.task.id, node.status]) }; -} - -describe('seeded coordination simulation with fault injection', () => { - const cleanup: (() => Promise)[] = []; - afterEach(async () => { - for (const run of cleanup.splice(0)) await run(); - expect(host.createSession).not.toHaveBeenCalled(); - }); - host.verify.mockImplementation(async request => { - const batch = verifiedBatch(request, { sessionId: 'simulation', checks: true }); - return host.failing ? failedBatch(batch, { stdoutPreview: file => `${file}:3:1: error: unsolved goals`, goalsRemaining: 1 }) : batch; - }); - host.createSession.mockImplementation(() => { throw new Error('real_models_are_not_used_in_simulation'); }); - - const seeds = Number(process.env.THEOREM_OS_SIMULATION_SEEDS ?? 12); - const first = Number(process.env.THEOREM_OS_SIMULATION_FIRST_SEED ?? 1); - it.each(Array.from({ length: seeds }, (_, index) => first + index))('seed %i reaches assembly without lost work', async seed => { - // Throws outside a task delivery (restore, Lead delivery) are failures too; the seed replays them. - const outcome = await simulate(seed, cleanup).catch(error => ({ status: 'thrown', detail: String(error) })); - if (outcome.status !== 'assembled') console.error(JSON.stringify({ seed, ...outcome }, null, 1)); - expect(outcome.status).toBe('assembled'); - }, 60_000); -}); diff --git a/tests/definitionStatementReview.test.ts b/tests/definitionStatementReview.test.ts deleted file mode 100644 index 307bae1a..00000000 --- a/tests/definitionStatementReview.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import fs from 'node:fs'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { LeanStatementContext } from '../src/math/leanStatementContext'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { SolverProblem } from '../src/solver/problem'; -import type { CooperativeTask, TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ capture: vi.fn(), sessions: vi.fn() })); -vi.mock('../src/solver/statementReview', async importOriginal => ({ - ...await importOriginal(), captureStatementContexts: host.capture, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.sessions })); - -describe('statement review of a lemma that names a planned definition', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, cooperative: CooperativeResearch, controller: AbortController; - let nodes: TaskRecord[]; - const context = (task: CooperativeTask): LeanStatementContext => ({ type: task.type!, constants: [], omitted: [] }); - - beforeEach(() => { - host.capture.mockReset().mockImplementation(async (_problem: SolverProblem, requested: CooperativeTask[]) => - new Map(requested.map(task => [task.id, context(task)]))); - host.sessions.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - let workspace: string; - ({ directory, workspace, problem } = localExample('definition-statement-review-')); - const tasks: CooperativeTask[] = [ - { id: 'double', kind: 'lemma', declaration: 'definition', objective: 'Twice a natural number.', type: 'Nat → Nat', - theoremName: 'Tutorial.double', proofPath: 'Submission.lean', dependsOn: [], revision: 0 }, - { id: 'double_zero', kind: 'lemma', objective: 'double vanishes at zero.', type: 'double 0 = 0', - theoremName: 'Tutorial.double_zero', proofPath: 'Submission.lean', dependsOn: ['double'], revision: 0, - statementReview: true, informalStatement: 'Twice zero is zero.' }, - { id: 'plain', kind: 'lemma', objective: 'An unrelated helper.', type: 'True', - theoremName: 'Tutorial.plain', proofPath: 'Submission.lean', dependsOn: [], revision: 0, - statementReview: true, informalStatement: 'Truth holds.' }, - ]; - nodes = tasks.map(task => ({ task, status: 'pending', attempts: 0 })); - state = solverState(problem, workspace, { runId: 'definition-statement-review', phase: 'running', environmentDigest: 'environment', - cooperation: { canonicalCommit: problem.baseCommit, tasks: nodes } }); - controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers: [leadWorker(problem, workspace, 'lead')], retrievalRoot: directory, - signal: controller.signal, exclusiveCheck: operation => operation() }); - }); - afterEach(async () => { - controller?.abort(); await cooperative?.stop(); expect(host.sessions).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('elaborates and requests its review only after the definition is integrated', async () => { - await (cooperative as any).prepareStatementContexts(); - expect(host.capture).toHaveBeenCalledOnce(); - expect(host.capture.mock.calls[0][1].map((task: CooperativeTask) => task.id)).toEqual(['plain']); - (cooperative as any).syncStatementReviews(); - expect(state.cooperation!.statementReviews!.map(review => review.taskId)).toEqual(['plain']); - - nodes[0].status = 'integrated'; - await (cooperative as any).prepareStatementContexts(); - expect(host.capture).toHaveBeenCalledTimes(2); - expect(host.capture.mock.calls[1][1].map((task: CooperativeTask) => task.id)).toEqual(['double_zero']); - (cooperative as any).syncStatementReviews(); - expect(state.cooperation!.statementReviews!.filter(review => review.status !== 'superseded').map(review => review.taskId).sort()) - .toEqual(['double_zero', 'plain']); - }); - - it('supersedes the review when the definition leaves the canonical graph', async () => { - nodes[0].status = 'integrated'; - await (cooperative as any).prepareStatementContexts(); - (cooperative as any).syncStatementReviews(); - const review = state.cooperation!.statementReviews!.find(item => item.taskId === 'double_zero')!; - expect(review.status).toBe('pending'); - nodes[0].status = 'pending'; - (cooperative as any).syncStatementReviews(); - expect(review.status).toBe('superseded'); - expect(state.cooperation!.statementReviews!.filter(item => item.taskId === 'double_zero' && item.status !== 'superseded')).toEqual([]); - }); -}); diff --git a/tests/deliveryReceipts.test.ts b/tests/deliveryReceipts.test.ts index a769247b..ccca5b3c 100644 --- a/tests/deliveryReceipts.test.ts +++ b/tests/deliveryReceipts.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { CooperativeResearch } from '../src/solver/cooperation'; + import { deliveryReceiptFeedback, deliveryReceiptSchema, rejectedDeliveryReceipt, type DeliveryReceipt } from '../src/solver/deliveryReceipts'; import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; @@ -39,32 +39,4 @@ describe('delivery receipt correction chains', () => { .replacesReceipt).toBeUndefined(); }); - it('resolves only a verified correction chain and leaves independent or foreign rejections pending', () => { - const first = reject({ summary: 'Original rejection' }); - const second = reject({ kind: 'research', finding: { summary: 'Rejected correction', replacesReceipt: first.id } }, [first]); - const independent = reject({ summary: 'Independent rejection' }); - const foreign = { ...reject({ summary: 'Foreign rejection' }), workerId: 'other-writer' }; - const stale = { ...reject({ summary: 'Wrong seed rejection' }), seedCommit: 'b'.repeat(40) }; - // A restored link outside the dispatch must never be followed by the resolver. - first.replacesReceipt = foreign.id; - const node = { task, feedback: deliveryReceiptFeedback(second) }; - const receipts = JSON.parse(JSON.stringify([first, second, independent, foreign, stale])) as DeliveryReceipt[]; - const cooperative = Object.create(CooperativeResearch.prototype) as any; - Object.assign(cooperative, { archive: { tasks: [node], deliveryReceipts: receipts }, - input: { state: { environmentDigest: 'environment' } } }); - cooperative.resolveDeliveryReceipts({ id: 'writer' }, action, second.id); - expect(receipts.map(receipt => receipt.status)).toEqual(['recorded', 'recorded', 'needs-correction', 'needs-correction', 'needs-correction']); - expect(node.feedback).toBe(deliveryReceiptFeedback(independent)); - expect(receipts[0].assignmentKey).toBe(assignmentDeliveryFile(action.assignment)); - }); - - it('tells a gap correction to retain required fields and select only a scoped original goal', () => { - const receipt = reject({ summary: 'Gap rejection' }); - receipt.issues = [{ path: 'mathematicalGap.previousDeliveryId', message: 'Invalid prior gap' }]; - const feedback = deliveryReceiptFeedback(receipt); - expect(feedback).toContain('keeping required consumer, previousGap, reduced, remaining, evidenceScope and reconsiderWhen'); - expect(feedback).toContain('kind:"goal"'); - expect(feedback).toContain('mathematicalGaps[].deliveryId'); - expect(feedback).toContain('omit only previousDeliveryId'); - }); }); diff --git a/tests/evaluatorRun.test.ts b/tests/evaluatorRun.test.ts index abd63977..cdd27e78 100644 --- a/tests/evaluatorRun.test.ts +++ b/tests/evaluatorRun.test.ts @@ -18,7 +18,7 @@ vi.mock('../src/runtime/codexConnectivity', () => ({ checkCodexProviderConnectiv vi.mock('../src/math/verifier', async original => ({ ...await original(), resolveMathematicsLakePackagesCache: () => undefined, })); -vi.mock('../src/solver/research', () => ({ runResearchWorkers: host.research })); +vi.mock('../src/solver/research', () => ({ runResearchLead: host.research })); vi.mock('../src/solver/evaluation', () => ({ evaluateSolverProof: host.evaluate })); describe('evaluator failure attribution in persisted run results', () => { diff --git a/tests/exactSourceIntegration.test.ts b/tests/exactSourceIntegration.test.ts index 4f0c52c3..56bdb6f6 100644 --- a/tests/exactSourceIntegration.test.ts +++ b/tests/exactSourceIntegration.test.ts @@ -4,7 +4,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { applyTaskChanges, taskChanges } from '../src/solver/cooperativeProof'; import { committedSource, commitSolverSources, git, withSolverWorktree, type SolverProblem } from '../src/solver/problem'; import { taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState, type LocalExample } from './helpers/solver'; import { failedBatch, receiptBatch } from './helpers/verifier'; @@ -134,163 +133,5 @@ describe('exact source task integration', () => { }); }); - it('preserves the delivery projection and receipt through the actual single-task integration caller', async () => { - host.environment.mockReturnValue({ identity: 'sealed-fixture' }); - const worker = peerWorker(example, 'engineer'), lead = leadWorker(problem, workspace); - const env = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - // Distinct histories require the host's content-equivalent receipt rebind even - // when both projection commits are created within the same timestamp second. - git(worker.worktree, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', - '--allow-empty', '--quiet', '--no-gpg-sign', '-m', 'Distinct worker history']); - fs.writeFileSync(path.join(worker.worktree, problem.projectRelative, 'Submission.lean'), candidate); - const lake = path.join(worker.worktree, problem.projectRelative, '.lake'); - fs.mkdirSync(lake, { recursive: true }); - fs.writeFileSync(path.join(lake, 'package-overrides.json'), '{"path":"/engineer/packages"}\n'); - delivery = commitSolverSources(problem, worker.worktree); - const assignment = { taskId: task.id, taskDigest: taskVersion(task), workerId: worker.id, seedCommit: problem.baseCommit }; - const node = { task, assignment, status: 'running' as const, attempts: 1 }; - const state = solverState(problem, workspace, { runId: 'exact-source-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, tasks: [node] } }); - const controller = new AbortController(); - const cooperative = cooperativeResearch({ state, workers: [lead, worker], retrievalRoot: directory, - signal: controller.signal, access: new Map([lead, worker].map(item => [item.id, { environment: env, retrievalRoot: directory }])) }); - const cacheChecks = vi.spyOn((cooperative as any).taskProofCache, 'check'); - try { - const proof = await (cooperative as any).check(task, assignment, worker.worktree, delivery); - Object.assign(node, { status: 'delivered', proof }); - await (cooperative as any).integrateNow(node); - const integrated = state.cooperation!.tasks[0]!; - expect(integrated.status).toBe('integrated'); - expect(committedSource(workspace, state.cooperation!.canonicalCommit!, `${problem.projectRelative}/Submission.lean`)).toBe(candidate); - expect(host.verify).toHaveBeenCalledOnce(); - expect(integrated.integratedCheck!.verification).toEqual(proof.verification); - expect(cacheChecks).toHaveBeenCalledTimes(2); - expect(cacheChecks.mock.calls[1]![0]).toBe(cacheChecks.mock.calls[0]![0]); - expect(integrated.integratedCheck!.projectionReuse).toMatchObject({ checkedProjectionCommit: proof.verification.targetCommit }); - } finally { controller.abort(); await cooperative.stop(); } - }); - - const conflictingDelivery = async (declaration = 'lemma shared : True := by exact True.intro') => { - task = { id: 'shared', kind: 'lemma', objective: 'Prove the shared statement.', type: 'True', - proofPath: 'Submission.lean', theoremName: 'Tutorial.shared', dependsOn: [], revision: 0 }; - const worker = peerWorker(example, 'engineer'), lead = leadWorker(problem, workspace); - const submittedSource = seed.replace('theorem add_zero', - 'lemma shared : True := by trivial\nlemma deliveryOnly : True := by trivial\ntheorem add_zero'); - fs.writeFileSync(path.join(worker.worktree, problem.projectRelative, 'Submission.lean'), submittedSource); - const submittedCommit = commitSolverSources(problem, worker.worktree); - const canonicalSource = seed.replace('theorem add_zero', - `${declaration}\nlemma peerKept : True := by trivial\ntheorem add_zero`); - fs.writeFileSync(path.join(project, 'Submission.lean'), canonicalSource); - const canonical = commitSolverSources(problem, workspace); - const assignment = { taskId: task.id, taskDigest: taskVersion(task), workerId: worker.id, seedCommit: problem.baseCommit }; - const node: TaskRecord = { task, assignment, status: 'running', attempts: 1 }; - const state = solverState(problem, workspace, { runId: 'canonical-conflict-fixture', phase: 'running', - cooperation: { canonicalCommit: canonical, tasks: [node] } }); - const controller = new AbortController(), events: { event: string; [key: string]: unknown }[] = []; - const cooperative = cooperativeResearch({ state, workers: [lead, worker], retrievalRoot: directory, - signal: controller.signal, emit: (event, detail) => events.push({ event, ...detail }) }); - const proof = await (cooperative as any).check(task, assignment, worker.worktree, submittedCommit); - Object.assign(node, { status: 'delivered', proof }); - host.verify.mockClear(); - return { node, state, cooperative, controller, proof, canonical, canonicalSource, events, - finish: async () => { controller.abort(); await cooperative.stop(); } }; - }; - - it('accepts a different canonical proof only after checking the exact task without overwriting peer work', async () => { - const f = await conflictingDelivery(); - try { - await (f.cooperative as any).integrateNow(f.node); - expect(f.node.status).toBe('integrated'); - expect(f.state.cooperation!.canonicalCommit).toBe(f.canonical); - expect(committedSource(workspace, f.canonical, `${problem.projectRelative}/Submission.lean`)).toBe(f.canonicalSource); - expect(f.node.proof).toBe(f.proof); - expect(f.node.integratedCheck).toMatchObject({ passed: true, commit: f.canonical, seedCommit: f.canonical, - taskDigest: taskVersion(task), changes: [] }); - expect(f.node.integratedCheck!.conditions).toBeUndefined(); - expect(host.verify).toHaveBeenCalledOnce(); - const [request, options] = host.verify.mock.calls[0]!; - expect(options.expectedDeclarationType).toBe('True'); - const checked = committedSource(workspace, request.targetCommit, `${problem.projectRelative}/Submission.lean`); - expect(checked).toContain('lemma shared : True := by exact True.intro'); - expect(checked).not.toContain('deliveryOnly'); - } finally { await f.finish(); } - }); - - it.each([ - ['unproved', 'lemma shared : True := by sorry'], - ['wrong type', 'lemma shared : False := by sorry'], - ['extra premise', 'lemma shared (h : True) : True := by exact h'], - ])('keeps the original conflict when the canonical declaration is %s', async (_kind, declaration) => { - const f = await conflictingDelivery(declaration); - host.verify.mockImplementation(async request => failedBatch(receiptBatch(request, - { sessionId: 'canonical-rejected', receiptId: () => 'canonical-rejected' }), - { stdoutPreview: () => 'Submission.lean:1:1: error: exact task is not proved', goalsRemaining: 1 })); - try { - await (f.cooperative as any).integrateNow(f.node); - expect(host.verify).toHaveBeenCalled(); - for (const [, options] of host.verify.mock.calls) expect(options.expectedDeclarationType).toBe('True'); - expect(f.node.status).toBe('blocked'); - expect(f.node.feedback).toMatch(/^math_task_integration_conflict/u); - expect(f.node.proof).toBe(f.proof); - expect(f.node.integratedCheck?.passed).not.toBe(true); - expect(f.state.cooperation!.canonicalCommit).toBe(f.canonical); - expect(committedSource(workspace, f.canonical, `${problem.projectRelative}/Submission.lean`)).toBe(f.canonicalSource); - } finally { await f.finish(); } - }); - it('does not accept a missing canonical target when a different supporting declaration conflicts', async () => { - const f = await conflictingDelivery('lemma deliveryOnly : True := by exact True.intro'); - try { - await (f.cooperative as any).integrateNow(f.node); - expect(f.node.status).toBe('blocked'); - expect(f.node.feedback).toMatch(/^math_task_integration_conflict/u); - expect(f.node.integratedCheck?.passed).not.toBe(true); - expect(f.node.proof).toBe(f.proof); - expect(f.state.cooperation!.canonicalCommit).toBe(f.canonical); - expect(committedSource(workspace, f.canonical, `${problem.projectRelative}/Submission.lean`)).not.toContain('lemma shared'); - } finally { await f.finish(); } - }); - - it('rechecks the new canonical when peer integration advances during conflict recovery', async () => { - const f = await conflictingDelivery(); - let newer: string | undefined; - host.verify.mockImplementationOnce(async request => { - fs.writeFileSync(path.join(project, 'Submission.lean'), f.canonicalSource.replace('theorem add_zero', - 'lemma newestPeer : True := by trivial\ntheorem add_zero')); - newer = commitSolverSources(problem, workspace); - f.state.cooperation!.canonicalCommit = newer; - return receiptBatch(request, { sessionId: 'superseded-canonical', receiptId: () => 'superseded-canonical' }); - }); - try { - await (f.cooperative as any).integrateNow(f.node); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(f.events).toContainEqual(expect.objectContaining({ event: 'task_integration_rebased', - taskId: task.id, from: f.canonical, to: newer })); - expect(f.node.status).toBe('integrated'); - expect(f.node.integratedCheck).toMatchObject({ passed: true, commit: newer, seedCommit: newer }); - expect(f.node.integratedCheck!.verification.results[0]!.receiptId).not.toBe('superseded-canonical'); - expect(f.state.cooperation!.canonicalCommit).toBe(newer); - expect(committedSource(workspace, newer!, `${problem.projectRelative}/Submission.lean`)).toContain('newestPeer'); - expect(f.node.proof).toBe(f.proof); - } finally { await f.finish(); } - }); - - it.each(['unavailable', 'abort'] as const)('propagates %s during canonical conflict verification', async outcome => { - const f = await conflictingDelivery(); - host.verify.mockImplementationOnce(async request => { - const batch = receiptBatch(request, { sessionId: 'canonical-interrupted', receiptId: () => 'canonical-interrupted' }); - if (outcome === 'abort') f.controller.abort(); - else { batch.status = 'unavailable'; for (const result of batch.results) result.status = 'unavailable'; } - return batch; - }); - try { - const integration = (f.cooperative as any).integrateNow(f.node); - if (outcome === 'abort') await expect(integration).rejects.toMatchObject({ name: 'AbortError' }); - else await expect(integration).rejects.toThrow('math_verifier_unavailable'); - expect(f.node.status).not.toBe('integrated'); - expect(f.node.integratedCheck?.passed).not.toBe(true); - expect(f.state.cooperation!.canonicalCommit).toBe(f.canonical); - expect(f.node.proof).toBe(f.proof); - } finally { await f.finish(); } - }); }); diff --git a/tests/fixtures/agentTeamFollowupPeer.cjs b/tests/fixtures/agentTeamFollowupPeer.cjs deleted file mode 100644 index a89738a3..00000000 --- a/tests/fixtures/agentTeamFollowupPeer.cjs +++ /dev/null @@ -1,205 +0,0 @@ -// Deterministic app-server peer for a rejected declaration followed by a new -// assignment in the same native thread. All checks and integration stay real. -const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'), crypto = require('node:crypto'); -const actor = process.env.DEEPSCIENTIST_MATH_WORKER_ID === 'solver' - ? 'lead' : process.env.DEEPSCIENTIST_MATH_WORKER_ID; -const workspace = process.env.DEEPSCIENTIST_MATH_WORKER_WORKTREE; -const traceFile = path.join(workspace, '.scratch/agent-team-peer.jsonl'); -fs.mkdirSync(path.dirname(traceFile), { recursive: true }); -const trace = value => fs.appendFileSync(traceFile, JSON.stringify(value) + '\n'); -const send = value => { trace({ direction: 'peer', ...value }); process.stdout.write(JSON.stringify(value) + '\n'); }; -const pending = new Map(); -let threadId = `followup-${actor}`, turnId, nextCall = 10000, cursor = 0; -const initialObjective = 'Use domain expert D011 (elementary-number-theory), references/domain-experts/number-theory.md#elementary-number-theory. Act as Lean Prover (prover). Prove Team.helper : ∀ n : Nat, n + 0 = n and submit the exact declaration.'; -const correctionObjective = 'Use domain expert D011 (elementary-number-theory), references/domain-experts/number-theory.md#elementary-number-theory. Act as Lean Debugger (lean-debugger) and Lean Prover (prover). Correct the rejected Team.helper proof using its host Lean feedback; preserve its statement and submit the saved helper.'; - -function assert(condition, reason) { if (!condition) throw new Error(reason); } - -async function team(operation) { - const requestId = ++nextCall; - const result = new Promise((resolve, reject) => pending.set(requestId, { resolve, reject, operation })); - send({ id: requestId, method: 'item/tool/call', params: { - threadId, turnId, callId: `call-${requestId}`, namespace: null, tool: 'theoremos_team', arguments: operation, - } }); - return result; -} - -async function until(predicate) { - let snapshot = await team({ operation: 'poll', after: cursor }); - for (;;) { - cursor = snapshot.cursor; - if (predicate(snapshot)) return snapshot; - const failed = snapshot.workers.find(worker => worker.status === 'failed'); - if (failed) throw new Error('child-infrastructure-failed:' + JSON.stringify(failed)); - snapshot = await team({ operation: 'wait', after: cursor, timeoutMs: 5000 }); - } -} - -function complete(stage, text, status = 'completed') { - const factor = stage + 1; - send({ method: 'thread/tokenUsage/updated', params: { threadId, turnId, tokenUsage: { - total: { inputTokens: 7 * factor, outputTokens: 3 * factor, totalTokens: 10 * factor }, - last: { inputTokens: 7, outputTokens: 3, totalTokens: 10 }, - } } }); - send({ method: 'item/completed', params: { threadId, turnId, - item: { type: 'agentMessage', id: 'final', text } } }); - send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status } } }); -} - -function checkRole(method, params) { - const lead = actor === 'lead'; - const expected = lead ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'retire_route', 'route_summary'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress', 'route_summary']; - const identity = lead ? 'You are the Lead of an Agent-organized research team; your agentId is lead.' - : `You are a mathematical researcher and Lean proof writer; your agentId is ${JSON.stringify(actor)}, and your coordinator is lead.`; - assert(params.developerInstructions.includes(identity), 'current-developer-identity-missing'); - if (!lead) assert(!params.developerInstructions.includes('You are the Lead'), 'worker-received-lead-identity'); - assert(params.config['features.multi_agent'] === false && params.config['features.multi_agent_v2'] === false, - 'native-unmanaged-delegation-enabled'); - if (method === 'thread/start') { - const tool = params.dynamicTools.find(tool => tool.name === 'theoremos_team'); - assert(tool && JSON.stringify(tool.inputSchema.properties.operation.enum.toSorted()) === JSON.stringify(expected.toSorted()), - 'role-operation-schema-mismatch'); - assert(lead ? tool.inputSchema.properties.summary && !tool.inputSchema.properties.declarations - : !tool.inputSchema.properties.targetId && tool.inputSchema.properties.summary && tool.inputSchema.properties.declarations, - 'role-parameter-schema-mismatch'); - } else assert(!params.dynamicTools, 'resume-redeclared-native-tools'); - trace({ observation: 'native-role-bound', actor, method, threadId, operations: expected }); -} - -async function research(params) { - const sourceFile = path.join(workspace, 'generated/problem/Submission.lean'); - const source = fs.readFileSync(sourceFile, 'utf8'); - const skillRoot = path.join(workspace, '.agents/skills/theoremos-research'); - assert(fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8').includes('theoremos_team') && - fs.readFileSync(path.join(skillRoot, 'references/parallel-work.md'), 'utf8').includes('`inspect`'), - 'pinned-team-skill-missing'); - const roleGuide = fs.readFileSync(path.join(skillRoot, 'references/team-roles.md')); - trace({ observation: 'team-role-guide-read', actor, bytes: roleGuide.length }); - for (const resource of ['references/domain-experts.md', 'references/domain-experts/number-theory.md', - 'references/domain-materials.md', 'references/domain-materials/number-theory.md']) { - const content = fs.readFileSync(path.join(skillRoot, resource)); - trace({ observation: 'domain-expert-resource-read', actor, expertId: 'D011', resource, - sha256: crypto.createHash('sha256').update(content).digest('hex') }); - } - trace({ observation: 'pinned-skill-read', actor }); - - if (actor !== 'lead') { - const text = params.input.filter(item => item.type === 'text').map(item => item.text).join('\n'); - const line = text.split('\n').find(line => line.startsWith('{"agentId":')); - assert(line, 'current-worker-assignment-missing'); - const assignment = JSON.parse(line); - assert(assignment.agentId === actor && assignment.coordinator === 'lead' && assignment.taskId === turnId, - 'current-worker-assignment-binding-mismatch'); - const checkpoint = path.join(workspace, '.scratch/first-followup-assignment.json'); - let stage = 0, updated; - if (!assignment.previousTask) { - assert(assignment.objective === initialObjective && !source.includes('theorem helper'), 'initial-assignment-mismatch'); - assert(assignment.deliveryBaseCommit === assignment.sourceCommit, 'initial-delivery-base-mismatch'); - fs.writeFileSync(checkpoint, JSON.stringify(assignment)); - updated = source.replace('theorem original', - 'theorem helper (n : Nat) : n + 0 = n := by exact Nat.succ_ne_zero n\ntheorem original'); - } else { - stage = 1; - const previous = JSON.parse(fs.readFileSync(checkpoint, 'utf8')); - assert(assignment.objective === correctionObjective && assignment.taskId !== previous.taskId, - 'followup-did-not-replace-task'); - assert(assignment.previousTask.id === previous.taskId && assignment.previousTask.status === 'failed' && - assignment.previousTask.error.includes('math_declaration_artifact_check_failed:Team.helper:') && - /type mismatch/iu.test(assignment.previousTask.error), 'own-lean-rejection-feedback-missing'); - assert(assignment.deliveryBaseCommit === previous.deliveryBaseCommit && - assignment.sourceCommit !== assignment.deliveryBaseCommit && source.includes('by exact Nat.succ_ne_zero n'), - 'followup-lost-rejected-draft-or-delivery-base'); - updated = source.replace('by exact Nat.succ_ne_zero n', 'by rfl'); - trace({ observation: 'worker-followup-context', threadId, assignment }); - } - trace({ observation: 'worker-current-task', threadId, stage, assignment }); - fs.writeFileSync(sourceFile, updated); - fs.appendFileSync(path.join(workspace, 'RESEARCH.md'), `${stage ? 'Corrected' : 'Candidate'} Team.helper source saved.\n`); - const submitted = await team({ operation: 'submit', summary: stage ? 'Corrected helper proved.' : 'Candidate helper submitted.', - declarations: [{ file: 'Submission.lean', name: 'Team.helper', type: '∀ n : Nat, n + 0 = n' }] }); - assert(submitted.status === 'pending-writer-stop' && submitted.taskId === assignment.taskId, - 'submission-not-bound-to-current-task'); - complete(stage, stage ? 'Corrected helper ready for independent checking.' : 'Candidate helper ready for host checking.'); - return; - } - - if (!source.includes('theorem helper')) { - const spawned = await team({ operation: 'spawn', agentId: 'child', message: initialObjective }); - const rejected = await until(snapshot => snapshot.workers.some(worker => - worker.id === 'child' && worker.tasks.some(task => task.id === spawned.taskId && task.status === 'failed'))); - const failure = rejected.workers.find(worker => worker.id === 'child').tasks.find(task => task.id === spawned.taskId); - assert(rejected.deliveries.length === 0 && failure.error.includes('math_declaration_artifact_check_failed:Team.helper:') && - /type mismatch/iu.test(failure.error), 'candidate-not-rejected-by-real-lean'); - const assigned = await team({ operation: 'assign', agentId: 'child', message: correctionObjective }); - assert(assigned.taskId !== spawned.taskId, 'followup-reused-task-id'); - trace({ observation: 'lead-assigned-correction', failedTaskId: spawned.taskId, taskId: assigned.taskId, error: failure.error }); - const corrected = await until(snapshot => snapshot.deliveries.some(delivery => - delivery.agentId === 'child' && delivery.taskId === assigned.taskId)); - const delivery = corrected.deliveries.find(delivery => delivery.taskId === assigned.taskId); - const inspected = await team({ operation: 'inspect', deliveryId: delivery.id }); - assert(inspected.taskId === assigned.taskId && inspected.declarations[0].name === 'Team.helper' && - inspected.artifacts[0].proof.verification.status === 'kernel_verified' && - inspected.originalProblemAcceptance === 'not-assessed', 'corrected-delivery-not-independently-checked'); - trace({ observation: 'lead-inspected-corrected-helper', deliveryId: inspected.id, taskId: inspected.taskId }); - await team({ operation: 'adopt', deliveryId: delivery.id }); - complete(0, 'Adopt corrected helper and return to release the Lead writer.'); - return; - } - - assert(source.includes('theorem helper (n : Nat) : n + 0 = n := by rfl'), 'lead-resumed-with-wrong-helper'); - trace({ observation: 'lead-resumed-with-corrected-helper', threadId }); - fs.writeFileSync(sourceFile, source.replace('by sorry', 'by\n exact helper n')); - fs.appendFileSync(path.join(workspace, 'RESEARCH.md'), 'Original target uses the corrected, checked and adopted helper.\n'); - complete(1, 'Original proof saved using the corrected team helper.'); -} - -const stream = readline.createInterface({ input: process.stdin }); -stream.on('close', () => process.exit(0)); -stream.on('line', line => { - const call = JSON.parse(line), params = call.params || {}; - trace({ direction: 'host', ...call }); - if (!call.method && pending.has(call.id)) { - const waiter = pending.get(call.id); pending.delete(call.id); - try { - assert(call.result?.success, 'tool-transport-failed:' + JSON.stringify(call)); - const value = JSON.parse(call.result.contentItems[0].text); - assert(value.ok, 'team-operation-failed:' + JSON.stringify(value)); - if (waiter.operation.operation === 'message') assert(value.delivery === 'saved-inbox' && - ['queued', 'unavailable'].includes(value.notification), 'message-acknowledgment-invalid'); - waiter.resolve(value); - } catch (error) { waiter.reject(error); } - return; - } - const reply = result => send({ id: call.id, result }); - // The injected nativeFileWatchFixture owns these connection-scoped calls. - if (call.method === 'fs/watch' || call.method === 'fs/unwatch') return; - try { - if (call.method === 'initialize') return reply({}); - if (call.method === 'thread/start' || call.method === 'thread/resume') { - threadId = params.threadId || threadId; - checkRole(call.method, params); - return reply({ thread: { id: threadId }, model: params.model, modelProvider: params.config.model_provider, - reasoningEffort: params.config.model_reasoning_effort, approvalPolicy: 'never', - activePermissionProfile: { id: 'math-worker' } }); - } - if (call.method === 'skills/list') return reply({ data: [{ cwd: workspace, errors: [], skills: [{ - name: 'theoremos-research', enabled: true, - path: path.join(workspace, '.agents/skills/theoremos-research/SKILL.md'), - }] }] }); - if (call.method === 'turn/start') { - turnId = params.clientUserMessageId; reply({ turn: { id: turnId } }); - send({ method: 'item/started', params: { threadId, turnId, item: { type: 'reasoning', id: 'research' } } }); - void research(params).catch(error => { - process.stderr.write(String(error.stack || error) + '\n'); - trace({ observation: 'peer-error', error: String(error) }); complete(0, String(error), 'failed'); - }); - return; - } - if (call.method === 'turn/interrupt') { reply({}); complete(0, 'Interrupted by host.', 'interrupted'); return; } - if (call.id !== undefined) reply({}); - } catch (error) { - trace({ observation: 'peer-error', error: String(error) }); - if (call.id !== undefined) send({ id: call.id, error: { code: -32000, message: String(error) } }); - } -}); diff --git a/tests/fixtures/agentTeamHandoffPeer.cjs b/tests/fixtures/agentTeamHandoffPeer.cjs deleted file mode 100644 index 733b63eb..00000000 --- a/tests/fixtures/agentTeamHandoffPeer.cjs +++ /dev/null @@ -1,213 +0,0 @@ -// Local deterministic app-server: native RPC, process isolation, source freezing, -// declaration checks and final acceptance all remain in the actual runtime. -const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'), crypto = require('node:crypto'); -const actor = process.env.DEEPSCIENTIST_MATH_WORKER_ID === 'solver' ? 'lead' : process.env.DEEPSCIENTIST_MATH_WORKER_ID; -const workspace = process.env.DEEPSCIENTIST_MATH_WORKER_WORKTREE; -const traceFile = path.join(workspace, '.scratch/agent-team-peer.jsonl'); -fs.mkdirSync(path.dirname(traceFile), { recursive: true }); -const trace = value => fs.appendFileSync(traceFile, JSON.stringify(value) + '\n'); -const send = value => { trace({ direction: 'peer', ...value }); process.stdout.write(JSON.stringify(value) + '\n'); }; -const pending = new Map(); -let threadId = `handoff-${actor}`, turnId, nextCall = 10000, cursor = 0; -const helper = 'theorem dependency (n : Nat) : n + 0 = n := by rfl\n'; -const draft = 'theorem combined (n : Nat) : n + 0 = n := by\n exact dependency n\n'; -const consumerObjective = 'Retain a draft of Team.combined using Team.dependency, yield for its checked adoption, then resume this same task and submit only your own declaration.'; -const resumeMessage = 'The peer dependency has been checked and adopted; continue the same saved task.'; -const assert = (condition, reason) => { if (!condition) throw new Error(reason); }; - -async function team(operation) { - const requestId = ++nextCall; - const result = new Promise((resolve, reject) => pending.set(requestId, { resolve, reject, operation })); - send({ id: requestId, method: 'item/tool/call', params: { - threadId, turnId, callId: `call-${requestId}`, namespace: null, tool: 'theoremos_team', arguments: operation, - } }); - return result; -} - -async function until(predicate) { - let snapshot = await team({ operation: 'poll', after: cursor }); - for (;;) { - cursor = snapshot.cursor; - if (predicate(snapshot)) return snapshot; - const failed = snapshot.workers.find(worker => worker.status === 'failed' || worker.tasks.some(task => task.status === 'failed')); - if (failed) throw new Error('unexpected-handoff-worker-failure:' + JSON.stringify(failed)); - snapshot = await team({ operation: 'wait', after: cursor, timeoutMs: 5000 }); - } -} - -function complete(stage, text, status = 'completed') { - const factor = stage + 1; - send({ method: 'thread/tokenUsage/updated', params: { threadId, turnId, tokenUsage: { - total: { inputTokens: 7 * factor, outputTokens: 3 * factor, totalTokens: 10 * factor }, - last: { inputTokens: 7, outputTokens: 3, totalTokens: 10 }, - } } }); - send({ method: 'item/completed', params: { threadId, turnId, item: { type: 'agentMessage', id: 'final', text } } }); - send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status } } }); -} - -function checkRole(method, params) { - const expected = actor === 'lead' - ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'retire_route', 'route_summary'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress', 'route_summary']; - assert(params.config['features.multi_agent'] === false && params.config['features.multi_agent_v2'] === false, - 'native-unmanaged-delegation-enabled'); - if (method === 'thread/start') { - const tool = params.dynamicTools.find(tool => tool.name === 'theoremos_team'); - assert(tool && JSON.stringify(tool.inputSchema.properties.operation.enum.toSorted()) === JSON.stringify(expected.toSorted()), - 'handoff-role-operation-schema-mismatch'); - } else assert(!params.dynamicTools, 'handoff-resume-redeclared-native-tools'); - trace({ observation: 'handoff-native-role-bound', actor, method, threadId, operations: expected }); -} - -async function research(params) { - const sourceFile = path.join(workspace, 'generated/problem/Submission.lean'); - const source = fs.readFileSync(sourceFile, 'utf8'); - const skillRoot = path.join(workspace, '.agents/skills/theoremos-research'); - const reference = fs.readFileSync(path.join(skillRoot, 'references/parallel-work.md'), 'utf8'); - assert(reference.includes('`yield`') && reference.includes('`resume`') && reference.includes('`history`'), 'handoff-skill-interface-missing'); - - if (actor !== 'lead') { - const input = params.input.filter(item => item.type === 'text').map(item => item.text).join('\n'); - const assignment = JSON.parse(input.split('\n').find(line => line.startsWith('{"agentId":'))); - assert(assignment.taskId === params.clientUserMessageId && assignment.agentId === actor, 'handoff-assignment-binding-changed'); - const history = await team({ operation: 'history', agentId: actor, offset: 0, limit: 1 }); - assert(history.total === 1 && history.nextOffset === null && history.tasks[0].id === assignment.taskId && - history.tasks[0].objective === assignment.objective, 'handoff-worker-history-incomplete'); - trace({ observation: 'handoff-worker-history', actor, taskId: assignment.taskId, history }); - - if (actor === 'producer') { - fs.writeFileSync(sourceFile, source.replace('theorem original', helper + 'theorem original')); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), 'The dependency declaration is ready for fresh host checking.\n'); - await team({ operation: 'submit', summary: 'Peer dependency proved.', declarations: [ - { file: 'Submission.lean', name: 'Team.dependency', type: '∀ n : Nat, n + 0 = n' }, - ] }); - complete(0, 'Peer helper saved and submitted.'); return; - } - - const checkpointFile = path.join(workspace, '.scratch/handoff-first-assignment.json'); - if (!fs.existsSync(checkpointFile)) { - assert(assignment.objective === consumerObjective && !source.includes('theorem dependency'), 'handoff-initial-consumer-context-invalid'); - fs.writeFileSync(sourceFile, source.replace('end Team', draft + 'end Team')); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), 'The retained combined draft awaits checked Team.dependency.\n'); - fs.writeFileSync(checkpointFile, JSON.stringify({ assignment, threadId, turnId, draft })); - await team({ operation: 'message', agentId: 'lead', message: 'My saved draft needs the peer dependency before I can finish.' }); - const yielded = await team({ operation: 'yield', reason: 'Need the checked peer dependency while preserving this draft and task.' }); - assert(yielded.status === 'pending-writer-stop' && yielded.taskId === assignment.taskId, 'handoff-yield-did-not-await-writer-stop'); - trace({ observation: 'consumer-yield-requested', taskId: assignment.taskId, threadId, turnId, - deliveryBaseCommit: assignment.deliveryBaseCommit }); - complete(0, 'Saved the blocked draft and yielded for peer adoption.'); return; - } - - const first = JSON.parse(fs.readFileSync(checkpointFile, 'utf8')); - assert(assignment.taskId === first.assignment.taskId && threadId === first.threadId && turnId !== first.turnId, - 'handoff-resume-lost-task-or-thread-identity'); - assert(assignment.deliveryBaseCommit === first.assignment.deliveryBaseCommit && source.includes(first.draft) && source.includes(helper), - 'handoff-resume-lost-draft-peer-or-source-baseline'); - assert(assignment.inbox.events.some(event => event.kind === 'message' && event.text === resumeMessage), - 'handoff-resume-missed-saved-inbox'); - assert(history.tasks[0].turns === 2 && history.tasks[0].budget.turns === 2, 'handoff-task-allowance-was-reset'); - fs.appendFileSync(path.join(workspace, 'RESEARCH.md'), 'Resumed the same task after adoption; the retained combined draft now uses its checked dependency.\n'); - const declarations = [{ file: 'Submission.lean', name: 'Team.combined', type: '∀ n : Nat, n + 0 = n' }]; - const submitted = await team({ operation: 'submit', summary: 'The retained combined draft is complete.', declarations }); - assert(submitted.taskId === assignment.taskId && submitted.status === 'pending-writer-stop', 'handoff-resumed-submission-unbound'); - trace({ observation: 'consumer-resumed-and-submitted-own-declaration', taskId: assignment.taskId, - threadId, turnId, assignment, declarations }); - complete(1, 'The same task submitted only its own combined declaration.'); return; - } - - if (!source.includes('theorem combined')) { - await team({ operation: 'publish', summary: 'Producer checks the dependency while consumer retains its dependent draft across an explicit handoff.' }); - const reserve = await team({ operation: 'budget', leadReserve: { tokens: 50, turns: 2 } }); - assert(reserve.budget.leadReserve.tokens === 50 && reserve.budget.leadReserve.turns === 2, 'handoff-lead-reserve-not-projected'); - const consumer = await team({ operation: 'spawn', agentId: 'consumer', message: consumerObjective, budget: { tokens: 100, turns: 1 } }); - await team({ operation: 'spawn', agentId: 'producer', message: 'Prove and submit Team.dependency as a checked equality helper.', - budget: { tokens: 100, turns: 1 } }); - const paused = await until(snapshot => snapshot.workers.find(worker => worker.id === 'consumer')?.tasks - .some(task => task.id === consumer.taskId && task.status === 'paused') && snapshot.deliveries.some(delivery => delivery.agentId === 'producer')); - const history = await team({ operation: 'history', agentId: 'consumer', offset: 0, limit: 1 }); - assert(history.tasks[0].id === consumer.taskId && history.tasks[0].status === 'paused' && - history.tasks[0].objective === consumerObjective && history.tasks[0].sourceCommit, 'handoff-paused-history-invalid'); - trace({ observation: 'lead-observed-paused-draft', taskId: consumer.taskId, history }); - const peer = paused.deliveries.find(delivery => delivery.agentId === 'producer'); - await team({ operation: 'inspect', deliveryId: peer.id }); - await team({ operation: 'adopt', deliveryId: peer.id, targetId: 'consumer' }); - const integrated = await until(snapshot => snapshot.adoptions.some(adoption => - adoption.deliveryId === peer.id && adoption.targetId === 'consumer' && adoption.status === 'completed')); - assert(integrated.workers.find(worker => worker.id === 'consumer').tasks[0].status === 'paused', 'handoff-adoption-resumed-without-lead'); - const allowance = await team({ operation: 'budget', agentId: 'consumer', taskId: consumer.taskId, budget: { tokens: 100, turns: 2 } }); - assert(allowance.budget.task.id === consumer.taskId && allowance.budget.task.used.turns === 1 && - allowance.budget.task.remaining.turns === 1, 'handoff-budget-update-reset-task-use'); - await team({ operation: 'message', agentId: 'consumer', message: resumeMessage, relatedTaskId: consumer.taskId }); - const resumed = await team({ operation: 'resume', agentId: 'consumer', taskId: consumer.taskId }); - assert(resumed.taskId === consumer.taskId, 'handoff-resume-created-another-task'); - trace({ observation: 'lead-resumed-same-consumer-task', taskId: consumer.taskId, budget: allowance.budget }); - const completed = await until(snapshot => snapshot.deliveries.some(delivery => delivery.agentId === 'consumer')); - const delivery = completed.deliveries.find(delivery => delivery.agentId === 'consumer'); - const inspected = await team({ operation: 'inspect', deliveryId: delivery.id }); - assert(JSON.stringify(inspected.declarations.map(item => item.name).toSorted()) === JSON.stringify(['Team.combined', 'Team.dependency']), - 'handoff-host-did-not-carry-peer-declarations'); - assert(inspected.artifacts.every(artifact => artifact.proof.verification.status === 'kernel_verified') && - inspected.originalProblemAcceptance === 'not-assessed', 'handoff-combined-delivery-not-freshly-checked'); - trace({ observation: 'lead-inspected-carried-peer', taskId: consumer.taskId, deliveryId: delivery.id, - declarations: inspected.declarations }); - await team({ operation: 'adopt', deliveryId: delivery.id }); - complete(0, 'Adopt the checked combined delivery and release the Lead writer.'); return; - } - - assert(source.includes(helper) && source.includes(draft), 'handoff-lead-adoption-lost-either-declaration'); - const original = 'theorem original (n : Nat) : n + 0 = n := by sorry\n'; - assert(source.includes(original), 'handoff-frozen-original-missing'); - // The retained draft follows the original target; put its consumer after the - // adopted declaration before asking the independent checker to accept it. - fs.writeFileSync(sourceFile, source.replace(original, '').replace('end Team', - original.replace('by sorry', 'by\n exact combined n') + 'end Team')); - fs.appendFileSync(path.join(workspace, 'RESEARCH.md'), 'Original target completed using the resumed consumer declaration.\n'); - trace({ observation: 'handoff-lead-proved-original', threadId }); - complete(1, 'Original proof uses the adopted consumer declaration.'); -} - -const stream = readline.createInterface({ input: process.stdin }); -stream.on('close', () => process.exit(0)); -stream.on('line', line => { - const call = JSON.parse(line), params = call.params || {}; - trace({ direction: 'host', ...call }); - if (!call.method && pending.has(call.id)) { - const waiter = pending.get(call.id); pending.delete(call.id); - try { - assert(call.result?.success, 'handoff-tool-transport-failed:' + JSON.stringify(call)); - const value = JSON.parse(call.result.contentItems[0].text); - assert(value.ok, 'handoff-team-operation-failed:' + JSON.stringify(value)); - if (waiter.operation.operation === 'message') assert(value.delivery === 'saved-inbox' && - ['queued', 'unavailable'].includes(value.notification), 'handoff-message-acknowledgment-invalid'); - waiter.resolve(value); - } catch (error) { waiter.reject(error); } - return; - } - const reply = result => send({ id: call.id, result }); - // The injected nativeFileWatchFixture owns these connection-scoped calls. - if (call.method === 'fs/watch' || call.method === 'fs/unwatch') return; - try { - if (call.method === 'initialize') return reply({}); - if (call.method === 'thread/start' || call.method === 'thread/resume') { - threadId = params.threadId || threadId; checkRole(call.method, params); - return reply({ thread: { id: threadId }, model: params.model, modelProvider: params.config.model_provider, - reasoningEffort: params.config.model_reasoning_effort, approvalPolicy: 'never', activePermissionProfile: { id: 'math-worker' } }); - } - if (call.method === 'skills/list') return reply({ data: [{ cwd: workspace, errors: [], skills: [{ - name: 'theoremos-research', enabled: true, path: path.join(workspace, '.agents/skills/theoremos-research/SKILL.md'), - }] }] }); - if (call.method === 'turn/start') { - turnId = `handoff-${actor}-${crypto.randomUUID()}`; reply({ turn: { id: turnId } }); - send({ method: 'item/started', params: { threadId, turnId, item: { type: 'reasoning', id: 'research' } } }); - void research(params).catch(error => { - process.stderr.write(String(error.stack || error) + '\n'); trace({ observation: 'peer-error', error: String(error) }); - complete(0, String(error), 'failed'); - }); return; - } - if (call.method === 'turn/interrupt') { reply({}); complete(0, 'Interrupted by host.', 'interrupted'); return; } - if (call.id !== undefined) reply({}); - } catch (error) { - trace({ observation: 'peer-error', error: String(error) }); - if (call.id !== undefined) send({ id: call.id, error: { code: -32000, message: String(error) } }); - } -}); diff --git a/tests/fixtures/agentTeamPeer.cjs b/tests/fixtures/agentTeamPeer.cjs deleted file mode 100644 index bfb87c67..00000000 --- a/tests/fixtures/agentTeamPeer.cjs +++ /dev/null @@ -1,188 +0,0 @@ -// Deterministic app-server peer: all tool requests go through the real adapter and -// host. It writes only its own worktree and never contacts a model or provider. -const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'); -const actor = process.env.DEEPSCIENTIST_MATH_WORKER_ID === 'solver' - ? 'lead' : process.env.DEEPSCIENTIST_MATH_WORKER_ID; -const workspace = process.env.DEEPSCIENTIST_MATH_WORKER_WORKTREE; -const traceFile = path.join(workspace, '.scratch/agent-team-peer.jsonl'); -fs.mkdirSync(path.dirname(traceFile), { recursive: true }); -const trace = value => fs.appendFileSync(traceFile, JSON.stringify(value) + '\n'); -const send = value => { trace({ direction: 'peer', ...value }); process.stdout.write(JSON.stringify(value) + '\n'); }; -const pending = new Map(); -let threadId = `peer-${actor}`, turnId, nextCall = 10000, cursor = 0; -const seen = []; -const initialResearch = 'Two complementary equality helpers supply the original equality; both helper claims remain unproved.'; -const revisedResearch = 'The original target consumes fast then symmetric slow; check each exact helper before adoption.'; - -async function team(operation) { - const requestId = ++nextCall; - const result = new Promise((resolve, reject) => { pending.set(requestId, { resolve, reject, operation }); }); - send({ id: requestId, method: 'item/tool/call', params: { - threadId, turnId, callId: `call-${requestId}`, namespace: null, tool: 'theoremos_team', arguments: operation, - } }); - return result; -} - -async function until(predicate) { - let snapshot = await team({ operation: 'poll', after: cursor }); - for (;;) { - cursor = snapshot.cursor; seen.push(...snapshot.events); - if (predicate(snapshot)) return snapshot; - const failed = snapshot.workers.find(worker => worker.status === 'failed'); - if (failed) throw new Error('child-failed:' + JSON.stringify(failed)); - snapshot = await team({ operation: 'wait', after: cursor, timeoutMs: 5000 }); - } -} - -function complete(stage, text, status = 'completed') { - const factor = actor === 'lead' ? stage + 1 : 1; - send({ method: 'thread/tokenUsage/updated', params: { threadId, turnId, tokenUsage: { - total: { inputTokens: 7 * factor, outputTokens: 3 * factor, totalTokens: 10 * factor }, - last: { inputTokens: 7, outputTokens: 3, totalTokens: 10 }, - } } }); - send({ method: 'item/completed', params: { threadId, turnId, - item: { type: 'agentMessage', id: 'final', text } } }); - send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status } } }); -} - -async function research(params) { - const sourceFile = path.join(workspace, 'generated/problem/Submission.lean'); - const source = fs.readFileSync(sourceFile, 'utf8'); - // Read the actual pinned method and collaboration reference in every process. - const skillRoot = path.join(workspace, '.agents/skills/theoremos-research'); - const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8'); - const reference = fs.readFileSync(path.join(skillRoot, 'references/parallel-work.md'), 'utf8'); - if (!skill.includes('theoremos_team') || !reference.includes('`inspect`')) throw new Error('pinned-team-skill-missing'); - trace({ observation: 'pinned-skill-read', actor }); - - if (actor !== 'lead') { - const input = params.input.filter(item => item.type === 'text').map(item => item.text).join('\n'); - const assignment = JSON.parse(input.split('\n').find(line => line.startsWith('{"agentId":'))); - if (assignment.researchState?.revision !== 1 || assignment.researchState.summary !== initialResearch || - assignment.researchState.advisory !== true) throw new Error('published-research-missing-from-worker-assignment'); - trace({ observation: 'worker-received-research', actor, revision: assignment.researchState.revision }); - await team({ operation: 'message', agentId: 'lead', message: 'ready' }); - const current = await until(() => seen.some(event => event.kind === 'message' && event.text === 'prove-now')); - if (current.researchState?.revision !== 2 || current.researchState.summary !== revisedResearch || - !seen.some(event => event.kind === 'research-updated' && event.to === actor)) - throw new Error('published-research-update-missing-from-worker-inbox'); - trace({ observation: 'worker-polled-current-research', actor, revision: current.researchState.revision }); - const name = actor === 'fast' ? 'fast' : 'slow'; - const type = actor === 'fast' ? '∀ n : Nat, n + 0 = n' : '∀ n : Nat, 0 + n = n'; - const helper = actor === 'fast' - ? 'theorem fast (n : Nat) : n + 0 = n := by rfl\n' - : 'theorem slow (n : Nat) : 0 + n = n := by exact Nat.zero_add n\n'; - fs.writeFileSync(sourceFile, source.replace('theorem original', helper + 'theorem original')); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), `${actor}: exact helper source saved.\n`); - const submitted = await team({ operation: 'submit', summary: `${name} helper proved.`, - declarations: [{ file: 'Submission.lean', name: `Team.${name}`, type }] }); - if (submitted.status !== 'pending-writer-stop') throw new Error('submission-did-not-wait-for-stop'); - complete(0, `${name} source and declaration saved.`); - return; - } - - if (!source.includes('theorem fast')) { - const publication = await team({ operation: 'publish', summary: initialResearch }); - if (publication.researchState?.revision !== 1 || publication.researchState.advisory !== true) - throw new Error('research-publication-not-saved'); - await team({ operation: 'spawn', agentId: 'fast', message: 'Prove Team.fast; wait for prove-now.' }); - await team({ operation: 'spawn', agentId: 'slow', message: 'Prove Team.slow; wait for prove-now.' }); - await until(() => ['fast', 'slow'].every(id => seen.some(event => event.from === id && event.text === 'ready'))); - await team({ operation: 'publish', summary: revisedResearch }); - await team({ operation: 'message', agentId: 'fast', message: 'prove-now' }); - const snapshot = await until(state => state.deliveries.some(delivery => delivery.agentId === 'fast') && - state.workers.find(worker => worker.id === 'fast').tasks.some(task => task.researchArtifactId)); - if (snapshot.workers.find(worker => worker.id === 'slow').status !== 'running') - throw new Error('slow-writer-did-not-overlap-fast-delivery'); - trace({ observation: 'fast-delivered-while-slow-running' }); - const delivery = snapshot.deliveries.find(item => item.agentId === 'fast'); - const inspected = await team({ operation: 'inspect', deliveryId: delivery.id }); - if (inspected.declarations[0].name !== 'Team.fast' || inspected.originalProblemAcceptance !== 'not-assessed') - throw new Error('fast-delivery-interface-invalid'); - const task = snapshot.workers.find(worker => worker.id === 'fast').tasks.find(task => task.id === delivery.taskId); - const reference = snapshot.researchArtifacts.find(artifact => artifact.id === task.researchArtifactId); - if (!reference || reference.commit !== task.sourceCommit || Object.hasOwn(reference, 'path')) - throw new Error('research-reference-not-bound-to-stopped-source'); - const firstPage = await team({ operation: 'inspect-research', artifactId: reference.id, offset: 0, limit: 9 }); - const secondPage = await team({ operation: 'inspect-research', artifactId: reference.id, offset: firstPage.notes.nextOffset }); - if (firstPage.commit !== task.sourceCommit || firstPage.advisory !== true || secondPage.advisory !== true || - firstPage.originalProblemAcceptance !== 'not-assessed' || firstPage.notes.nextOffset !== 9 || - firstPage.notes.text + secondPage.notes.text !== 'fast: exact helper source saved.\n') - throw new Error('research-notes-pagination-invalid'); - trace({ observation: 'lead-inspected-research', artifactId: reference.id, taskId: task.id, commit: task.sourceCommit }); - await team({ operation: 'message', agentId: 'slow', message: 'prove-now' }); - await team({ operation: 'adopt', deliveryId: delivery.id }); - complete(0, 'Adopt fast and return to release the Lead writer.'); - return; - } - - if (!source.includes('theorem slow')) { - trace({ observation: 'lead-resumed-with-fast', threadId }); - const snapshot = await until(state => state.deliveries.some(delivery => delivery.agentId === 'slow')); - const delivery = snapshot.deliveries.find(item => item.agentId === 'slow'); - const inspected = await team({ operation: 'inspect', deliveryId: delivery.id }); - if (inspected.declarations[0].name !== 'Team.slow') throw new Error('slow-delivery-interface-invalid'); - await team({ operation: 'adopt', deliveryId: delivery.id }); - complete(1, 'Adopt slow and return to release the Lead writer.'); - return; - } - - trace({ observation: 'lead-resumed-with-both', threadId }); - fs.writeFileSync(sourceFile, source.replace('by sorry', 'by\n exact Eq.trans (fast n) (Eq.symm (slow n))')); - fs.appendFileSync(path.join(workspace, 'RESEARCH.md'), 'Original target consumes both checked child declarations.\n'); - complete(2, 'Original proof saved using both team helpers.'); -} - -const stream = readline.createInterface({ input: process.stdin }); -stream.on('close', () => process.exit(0)); -stream.on('line', line => { - const call = JSON.parse(line), params = call.params || {}; - trace({ direction: 'host', ...call }); - if (!call.method && pending.has(call.id)) { - const waiter = pending.get(call.id); pending.delete(call.id); - try { - if (!call.result?.success) throw new Error('tool-transport-failed:' + JSON.stringify(call)); - const value = JSON.parse(call.result.contentItems[0].text); - if (!value.ok) throw new Error('team-operation-failed:' + JSON.stringify(value)); - if (waiter.operation.operation === 'message' && (value.delivery !== 'saved-inbox' || - !['queued', 'unavailable'].includes(value.notification))) throw new Error('message-acknowledgment-invalid'); - waiter.resolve(value); - } catch (error) { waiter.reject(error); } - return; - } - const reply = result => send({ id: call.id, result }); - // The injected nativeFileWatchFixture owns these connection-scoped calls. - if (call.method === 'fs/watch' || call.method === 'fs/unwatch') return; - if (call.method === 'initialize') return reply({}); - if (call.method === 'thread/start' || call.method === 'thread/resume') { - threadId = params.threadId || threadId; - if (call.method === 'thread/start') { - const expected = actor === 'lead' - ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'retire_route', 'route_summary'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress', 'route_summary']; - const tool = params.dynamicTools.find(tool => tool.name === 'theoremos_team'); - if (!tool || JSON.stringify(tool.inputSchema.properties.operation.enum.toSorted()) !== JSON.stringify(expected.toSorted())) - throw new Error('role-operation-schema-mismatch'); - } - return reply({ thread: { id: threadId }, model: params.model, modelProvider: params.config.model_provider, - reasoningEffort: params.config.model_reasoning_effort, approvalPolicy: 'never', - activePermissionProfile: { id: 'math-worker' } }); - } - if (call.method === 'skills/list') return reply({ data: [{ cwd: workspace, errors: [], skills: [{ - name: 'theoremos-research', enabled: true, - path: path.join(workspace, '.agents/skills/theoremos-research/SKILL.md'), - }] }] }); - if (call.method === 'turn/start') { - turnId = params.clientUserMessageId; reply({ turn: { id: turnId } }); - send({ method: 'item/started', params: { threadId, turnId, item: { type: 'reasoning', id: 'research' } } }); - void research(params).catch(error => { - process.stderr.write(String(error.stack || error) + '\n'); - trace({ observation: 'peer-error', error: String(error) }); complete(0, String(error), 'failed'); - }); - return; - } - if (call.method === 'turn/interrupt') { - reply({}); complete(0, 'Interrupted by host.', 'interrupted'); return; - } - if (call.id !== undefined) reply({}); -}); diff --git a/tests/formalizationRelay.test.ts b/tests/formalizationRelay.test.ts index 80bf1f85..3d326bc6 100644 --- a/tests/formalizationRelay.test.ts +++ b/tests/formalizationRelay.test.ts @@ -506,7 +506,7 @@ describe('host credential relay for isolated formalization roles', () => { const changed = () => { lead.tokenBudget = buildTokenBudget(0, [lead, member]); }; changed(); const track = (record: SolverRunState, sessionId: string) => { - const usage = new ResearchUsage({ state: lead, research: record, maxTotalTokens: 0, + const usage = new ResearchUsage({ state: lead, research: record, signal: new AbortController().signal, remainingMs: () => Infinity, changed, emit: () => {} }); const callbacks = usage.bindSession(sessionId, () => undefined); usage.sessionOpened({ threadId: sessionId, usageSource: 'upstream-requests', diff --git a/tests/frontierPriorityContext.test.ts b/tests/frontierPriorityContext.test.ts index 8c5a2439..488209f8 100644 --- a/tests/frontierPriorityContext.test.ts +++ b/tests/frontierPriorityContext.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, it, vi } from 'vitest'; import * as contextCompiler from '../src/solver/contextCompiler'; -import type { CooperationState } from '../src/solver/cooperation'; +import type { CooperationState } from '../src/solver/cooperationShared'; import type { SolverRunState } from '../src/solver/archive'; import type { SolverProblem } from '../src/solver/problem'; import { buildResearchContext } from '../src/solver/modules/context'; @@ -60,8 +60,6 @@ it.each(['lemma', 'goal', 'research', 'sketch'] as const)( expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'assignment-policy', required: true })); expect(context.message).toContain('Current delivery log: ' + assignmentDeliveryFile(action.assignment)); expect(context.instructions).toContain('"kind":"helpers","declarations":'); - expect(context.instructions).toContain('Use research-observe from .scratch/theoremos-help.md'); - expect(context.toolHelp?.text).toContain("--finding '.scratch/finding.json'"); if (kind === 'lemma' || kind === 'goal') { expect(context.instructions).toContain('save the assigned declaration and return for host checking'); } else { diff --git a/tests/fullSkillWorkflow.test.ts b/tests/fullSkillWorkflow.test.ts index 8b4f549d..6e6e624c 100644 --- a/tests/fullSkillWorkflow.test.ts +++ b/tests/fullSkillWorkflow.test.ts @@ -109,7 +109,6 @@ describe('Skill methods with complete host workflows', () => { expect(context.workContract?.input).toMatchObject({ taskId: 'helper', taskDigest: assignment.taskDigest }); const help = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); expect(help).not.toContain('Lead plan submission'); - expect(help).toContain("bun '" + tools.replaceAll("'", "'\\''") + "' research-observe"); const continued = finalizeResearchDispatch(context, { continuation: true }); expect(continued.message).toContain('CURRENT_EXACT_TYPE_ERROR'); expect(continued.message).toContain(assignmentDeliveryFile(assignment)); diff --git a/tests/goalProgressCooperation.test.ts b/tests/goalProgressCooperation.test.ts deleted file mode 100644 index 5795826e..00000000 --- a/tests/goalProgressCooperation.test.ts +++ /dev/null @@ -1,308 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { commitSolverSources } from '../src/solver/problem'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const interval = 60_000; -const budget = { maxTurns: Infinity, remainingMs: Infinity }; - -describe('goal progress controls the cooperative planning loop', () => { - const directories: string[] = [], controls: AbortController[] = [], runs: CooperativeResearch[] = []; - const waiting: Promise[] = []; - - beforeEach(() => { - vi.useFakeTimers(); vi.setSystemTime(new Date('2026-11-02T00:00:00Z')); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ current: () => true, - result: { status: 'unavailable', reason: 'offline fixture does not open Lean', inputDigest: 'fixture-input', - taskDigest: taskVersion(input.task), evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } })); - }); - afterEach(async () => { - controls.splice(0).forEach(controller => controller.abort()); - await Promise.allSettled(runs.splice(0).map(run => run.stop())); - await Promise.allSettled(waiting.splice(0)); - vi.useRealTimers(); vi.restoreAllMocks(); - directories.splice(0).forEach(directory => fs.rmSync(directory, { recursive: true, force: true })); - }); - - const tracked = (promise: Promise) => { - waiting.push(promise); void promise.catch(() => {}); - let finished = false; - void promise.then(() => { finished = true; }, () => { finished = true; }); - return { promise, finished: () => finished }; - }; - const flush = async () => { for (let index = 0; index < 12; index++) await Promise.resolve(); }; - - function fixture() { - const example = localExample('goal-progress-cooperation-', 'lead'); directories.push(example.directory); - const { directory, workspace, problem } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'engineer', { role: 'engineer' }), - peerWorker(example, 'prover', { role: 'prover' }), peerWorker(example, 'researcher')]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: `goal_${index + 1}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, - conditional: false, ownerId: 'engineer', ...(index ? { status: 'paused' } : {}), - })) }); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(plan) + '\n```\n'); - let state = solverState(problem, workspace, { runId: 'goal-progress-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - let allowed = true; - const events: { event: string; details?: Record }[] = []; - const check = vi.fn(async () => { throw new Error('fixture_unexpected_proof_or_model_call'); }); - const modules: SolverModules = { ...directSolverModules, - M1: { ...directSolverModules.M1, open: check }, - M2: { version: directSolverModules.M2.version, check, checkTask: check } }; - const create = () => { - const controller = new AbortController(); controls.push(controller); - const run = cooperativeResearch({ state, workers, modules, retrievalRoot: directory, signal: controller.signal, - modelDispatchAllowed: () => allowed, goalProgressReviewMs: interval, - emit: (event, details) => events.push({ event, details }) }); - runs.push(run); return run; - }; - let cooperation = create(); - const startGoal = async () => { - const action = await cooperation.next(workers[1], budget); - expect(action).toMatchObject({ kind: 'task', task: { id: 'goal_1' } }); - if (action?.kind !== 'task') throw new Error('fixture_expected_original_goal'); - expect(cooperation.started(workers[1], action)).toBe(true); - const interrupt = vi.fn(async () => {}); - cooperation.activate(workers[1], action, interrupt, async () => {}); - return { action, interrupt }; - }; - const leadAction = async (notify: (message: string) => Promise = async () => {}) => { - const action = await cooperation.next(workers[0], budget); - expect(action).toMatchObject({ kind: 'lead' }); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead_review'); - expect(cooperation.started(workers[0], action)).toBe(true); - cooperation.activate(workers[0], action, async () => {}, notify); - return action; - }; - const commitPlan = (value: unknown) => { - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(value) + '\n```\n'); - return commitSolverSources(problem, workspace); - }; - return { workers, problem, events, check, create, startGoal, leadAction, commitPlan, - get state() { return state; }, get cooperation() { return cooperation; }, - setAllowed: (value: boolean) => { allowed = value; }, - async restart() { - await cooperation.stop(); - const file = path.join(directory, 'state.json'); writeSolverRunState(file, state); - state = readSolverRunState(file); cooperation = create(); await cooperation.restore(); - } }; - } - - const requested = (events: ReturnType['events']) => - events.filter(item => item.event === 'goal_progress_review_requested'); - - it('wakes Lead for an active unproductive goal and turns its accepted revision into prover work', async () => { - const run = fixture(), { cooperation, workers, state } = run; - const engineer = await run.startGoal(); - state.cooperation!.lastLeadInputDigest = (cooperation as any).planningInputDigest(); - const lead = tracked(cooperation.next(workers[0], budget)); - await flush(); expect(lead.finished()).toBe(false); - await vi.advanceTimersByTimeAsync(interval - 1); - expect(lead.finished()).toBe(false); expect(requested(run.events)).toHaveLength(0); - await vi.advanceTimersByTimeAsync(1); - const action = await lead.promise; - expect(action).toMatchObject({ kind: 'lead' }); - if (action?.kind !== 'lead') throw new Error('fixture_expected_progress_review'); - const pending = state.cooperation!.goalProgress!.pending!; - expect(pending.goalIds).toEqual(['goal_1']); expect(requested(run.events)).toHaveLength(1); - expect(cooperation.current(engineer.action)).toBe(true); expect(engineer.interrupt).not.toHaveBeenCalled(); - expect(cooperation.started(workers[0], action)).toBe(true); - cooperation.activate(workers[0], action, async () => {}, async () => {}); - await vi.advanceTimersByTimeAsync(interval * 2); - expect(requested(run.events)).toHaveLength(1); - const file = leadPlanDeliveryFile(action)!; - fs.appendFileSync(path.join(workers[0].worktree, file), JSON.stringify({ kind: 'plan', dispatchNonce: action.planNonce, - baseVersion: action.planVersion, summary: 'Replace the unsupported direct argument with a typed estimate.', - upsert: [{ id: 'goal_1', dependsOn: ['estimate'] }, { id: 'estimate', kind: 'lemma', - objective: 'Prove the estimate consumed by the original goal.', proofPath: 'Submission.lean', - theoremName: 'Tutorial.progress_estimate', type: '1 = 1', dependsOn: [], ownerId: 'prover' }], - progressReview: { id: pending.id, reason: 'The original proof has no checked intermediate fact; prove this estimate next.', - nextChecks: [{ action: 'construction-check', targetTaskId: 'estimate', objective: 'Prove the exact estimate.', - expectedEvidence: 'A kernel-checked estimate available to the original goal.' }] }, - }) + '\n'); - await cooperation.pulse(workers[0].id); - await cooperation.deliver(workers[0], action, commitSolverSources(run.problem, workers[0].worktree)); - cooperation.deactivate(workers[0]); cooperation.deactivate(workers[1]); - expect(state.cooperation!.goalProgress!.pending).toBeUndefined(); - expect(state.cooperation!.goalProgress!.decisions).toContainEqual(expect.objectContaining({ id: pending.id })); - expect(engineer.interrupt).toHaveBeenCalledOnce(); - expect(cooperation.current(engineer.action)).toBe(false); - const next = await cooperation.next(workers[2], budget); - expect(next).toMatchObject({ kind: 'task', task: { id: 'estimate' } }); - expect(cooperation.started(workers[2], next!)).toBe(true); - expect(run.check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - }); - - it.each(['checkpoint', 'invalid-plan', 'missing-answer', 'wrong-review-id'] as const)( - 'keeps an unanswered progress review after %s', async kind => { - const run = fixture(); await run.startGoal(); await vi.advanceTimersByTimeAsync(interval); - const action = await run.leadAction(), pending = structuredClone(run.state.cooperation!.goalProgress!.pending!); - const patch = { baseVersion: action.planVersion, upsert: kind === 'invalid-plan' - ? [{ id: 'goal_1', theoremName: 'Tutorial.changed_original' }] : [], - ...(kind === 'missing-answer' || kind === 'checkpoint' ? {} : { - progressReview: { id: kind === 'wrong-review-id' ? 'unpresented-review' : pending.id, - reason: 'This response must only settle the exact presented valid decision.', - nextChecks: [{ action: 'construction-check', targetTaskId: 'goal_1', objective: 'Check the original goal proof.', - expectedEvidence: 'A checked proof or an exact residual goal.' }] }, - }) }; - const commit = kind === 'checkpoint' ? action.seedCommit : run.commitPlan(patch); - await run.cooperation.deliver(run.workers[0], action, commit, kind === 'checkpoint', 'scheduling-checkpoint'); - run.cooperation.deactivate(run.workers[0]); - expect(run.state.cooperation!.goalProgress!.pending?.id).toBe(pending.id); - expect(run.events.filter(item => item.event === 'goal_progress_review_answered')).toHaveLength(0); - expect(run.state.cooperation!.planRejection).toBeDefined(); - expect(run.state.cooperation!.lastLeadPauseInputDigest).toBeUndefined(); - if (kind === 'checkpoint' || kind === 'missing-answer') - expect(run.state.cooperation!.error).toContain('math_plan_progress_review_missing'); - if (kind === 'wrong-review-id') - expect(run.state.cooperation!.error).toContain('math_plan_progress_review_stale'); - expect(run.check).not.toHaveBeenCalled(); - }); - - it('settles a progress decision saved in a checkpoint even when the accepted graph stays identical', async () => { - const run = fixture(); await run.startGoal(); await vi.advanceTimersByTimeAsync(interval); - const action = await run.leadAction(), archive = run.state.cooperation!, id = archive.goalProgress!.pending!.id; - const planVersion = archive.planVersion; - const commit = run.commitPlan({ baseVersion: action.planVersion, upsert: [], progressReview: { id, - reason: 'Check the exact original construction before selecting a different route.', - nextChecks: [{ action: 'construction-check', targetTaskId: 'goal_1', objective: 'Check the original construction.', - expectedEvidence: 'A checked construction or its exact residual gap.' }] } }); - await run.cooperation.deliver(run.workers[0], action, commit, true, 'scheduling-checkpoint'); - run.cooperation.deactivate(run.workers[0]); - expect(archive.planVersion).toBe(planVersion); - expect(archive.goalProgress!.pending).toBeUndefined(); - expect(archive.goalProgress!.decisions?.filter(decision => decision.id === id)).toHaveLength(1); - expect(run.events.filter(item => item.event === 'goal_progress_review_answered')).toHaveLength(1); - expect(archive.lastLeadPauseInputDigest).toBeUndefined(); - expect(archive.error).toBeUndefined(); - expect(run.check).not.toHaveBeenCalled(); - }); - - it('accepts the exact presented progress decision from a nested live revision without changing the graph', async () => { - const run = fixture(); await run.startGoal(); await vi.advanceTimersByTimeAsync(interval); - const action = await run.leadAction(), archive = run.state.cooperation!, id = archive.goalProgress!.pending!.id; - const planVersion = archive.planVersion; - const event = { kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, - tasks: { baseVersion: action.planVersion, upsert: [], progressReview: { id, - reason: 'Preserve the exact proof obligation and check its missing construction.', - nextChecks: [{ action: 'construction-check', targetTaskId: 'goal_1', objective: 'Check the original construction.', - expectedEvidence: 'A checked construction or its exact missing premise.' }] } } }; - fs.appendFileSync(path.join(run.workers[0].worktree, leadPlanDeliveryFile(action)!), JSON.stringify(event) + '\n'); - await run.cooperation.pulse(); - expect(archive.planVersion).toBe(planVersion); - expect(archive.planPublication).toMatchObject({ nonce: action.planNonce }); - expect(archive.goalProgress!.pending).toBeUndefined(); - expect(archive.goalProgress!.decisions?.filter(decision => decision.id === id)).toHaveLength(1); - expect(run.events.filter(item => item.event === 'plan_publication_rejected')).toHaveLength(0); - expect(archive.error).toBeUndefined(); - expect(run.check).not.toHaveBeenCalled(); - }); - - it('reports an omitted progress review while the draft is still editable and accepts the same-turn correction', async () => { - const run = fixture(); await run.startGoal(); await vi.advanceTimersByTimeAsync(interval); - const notify = vi.fn(async (_message: string) => {}), action = await run.leadAction(notify); - const pending = structuredClone(run.state.cooperation!.goalProgress!.pending!); - const patch = { baseVersion: action.planVersion, upsert: [] }; - fs.writeFileSync(path.join(run.workers[0].worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(patch) + '\n```\n'); - await run.cooperation.pulse(); - expect(notify).toHaveBeenCalledOnce(); - expect(notify.mock.calls[0][0]).toContain('math_plan_progress_review_missing'); - expect(notify.mock.calls[0][0]).toContain(pending.id); - expect(notify.mock.calls[0][0]).toContain('goal_1'); - expect(run.state.cooperation!.goalProgress!.pending?.id).toBe(pending.id); - expect(run.state.cooperation!.planPublication).toBeUndefined(); - await run.cooperation.pulse(); - expect(notify).toHaveBeenCalledOnce(); - const commit = run.commitPlan({ ...patch, progressReview: { id: pending.id, - reason: 'Check the exact original construction and preserve its proof obligation.', - nextChecks: [{ action: 'construction-check', targetTaskId: 'goal_1', objective: 'Check the original construction.', - expectedEvidence: 'A checked construction or its exact residual gap.' }] } }); - await run.cooperation.pulse(); - expect(notify).toHaveBeenCalledOnce(); - await run.cooperation.deliver(run.workers[0], action, commit, true, 'scheduling-checkpoint'); - run.cooperation.deactivate(run.workers[0]); - expect(run.state.cooperation!.goalProgress!.pending).toBeUndefined(); - expect(run.state.cooperation!.goalProgress!.decisions).toContainEqual(expect.objectContaining({ id: pending.id })); - expect(run.state.cooperation!.error).toBeUndefined(); - expect(run.check).not.toHaveBeenCalled(); - }); - - it.each(['model-disabled', 'plan-approval', 'provider-cooldown'] as const)( - 'excludes %s waiting from active execution and resumes the remaining interval', async gate => { - const run = fixture(); await run.startGoal(); await vi.advanceTimersByTimeAsync(interval / 3); - if (gate === 'model-disabled') run.setAllowed(false); - if (gate === 'plan-approval') run.state.planApproval = true; - if (gate === 'provider-cooldown') run.state.workers![1].recovery = { phase: 'cooling-down', reason: 'provider unavailable', - cycles: 1, startedAt: Date.now(), nextRetryAt: Date.now() + interval * 10, waitedMs: 0 }; - run.cooperation.modelBudgetChanged(); - // A dispatch refresh observes the gate; no private host implementation is called by the fixture. - const gated = tracked(run.cooperation.next(run.workers[0], budget)); - await flush(); await vi.advanceTimersByTimeAsync(interval * 4); - expect(requested(run.events)).toHaveLength(0); - expect(run.state.cooperation!.goalProgress!.goals[0].activeMs).toBe(interval / 3); - run.setAllowed(true); run.state.planApproval = false; delete run.state.workers![1].recovery; - run.cooperation.modelBudgetChanged(); - await flush(); await vi.advanceTimersByTimeAsync(interval * 2 / 3 - 1); - expect(requested(run.events)).toHaveLength(0); - await vi.advanceTimersByTimeAsync(1); - expect(requested(run.events)).toHaveLength(1); - expect(await gated.promise).toMatchObject({ kind: 'lead' }); - }); - - it.each(['model-disabled', 'plan-approval'] as const)('retains an already owed review behind the %s gate', async gate => { - const run = fixture(); await run.startGoal(); await vi.advanceTimersByTimeAsync(interval); - const id = run.state.cooperation!.goalProgress!.pending!.id; - if (gate === 'model-disabled') run.setAllowed(false); else run.state.planApproval = true; - run.cooperation.modelBudgetChanged(); - const next = tracked(run.cooperation.next(run.workers[0], budget)); - await flush(); await vi.advanceTimersByTimeAsync(interval * 2); - expect(next.finished()).toBe(false); - expect(run.state.cooperation!.goalProgress!.pending!.id).toBe(id); - expect(run.events.filter(item => item.event === 'goal_progress_review_dispatched')).toHaveLength(0); - run.setAllowed(true); run.state.planApproval = false; run.cooperation.modelBudgetChanged(); - expect(await next.promise).toMatchObject({ kind: 'lead' }); - expect(run.state.cooperation!.goalProgress!.pending!.id).toBe(id); - expect(run.events.filter(item => item.event === 'goal_progress_review_dispatched')).toHaveLength(1); - }); - - it('preserves execution spent before stop while excluding a saved run\'s offline interval', async () => { - const run = fixture(); await run.startGoal(); await vi.advanceTimersByTimeAsync(interval / 3); - await run.cooperation.stop(); - const saved = run.state.cooperation!.goalProgress!.goals[0].activeMs; - expect(saved).toBe(interval / 3); - vi.setSystemTime(Date.now() + 24 * 60 * 60_000); - await run.restart(); - expect(run.state.cooperation!.goalProgress!.goals[0].activeMs).toBe(saved); - expect(run.state.cooperation!.goalProgress!.goals[0].active).toBe(false); - await run.startGoal(); - await vi.advanceTimersByTimeAsync(interval - saved - 1); - expect(requested(run.events)).toHaveLength(0); - await vi.advanceTimersByTimeAsync(1); - expect(await run.cooperation.next(run.workers[0], budget)).toMatchObject({ kind: 'lead' }); - expect(requested(run.events)).toHaveLength(1); - }); - - it('keeps the global progress review in Lead context and out of every peer projection', async () => { - const run = fixture(), engineer = await run.startGoal(); await vi.advanceTimersByTimeAsync(interval); - const action = await run.leadAction(); - expect(run.cooperation.contextState(action, run.workers[0]).goalProgress?.pending).toBeDefined(); - for (const worker of run.workers.slice(1)) { - expect(run.cooperation.contextState(worker.id === 'engineer' ? engineer.action : undefined, worker).goalProgress).toBeUndefined(); - const context = JSON.parse(fs.readFileSync(path.join(worker.worktree, 'COOPERATION.json'), 'utf8')); - expect(context).not.toHaveProperty('goalProgress'); - } - expect(JSON.parse(fs.readFileSync(path.join(run.workers[0].worktree, 'COOPERATION.json'), 'utf8')).goalProgress.pending) - .toMatchObject({ id: run.state.cooperation!.goalProgress!.pending!.id }); - }); -}); diff --git a/tests/goalProgressResearch.test.ts b/tests/goalProgressResearch.test.ts index af283434..73add86b 100644 --- a/tests/goalProgressResearch.test.ts +++ b/tests/goalProgressResearch.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { type CooperativeResearch } from '../src/solver/cooperation'; + import { parseLeadPlan } from '../src/solver/cooperationShared'; import type { TaskProof } from '../src/solver/cooperativeProof'; import { answerGoalProgress, GOAL_PROGRESS_REVIEW_MS as interval, goalProgressForTask, goalProgressStateSchema, @@ -13,16 +13,13 @@ import type { NextCheckRecord } from '../src/solver/nextCheckContract'; import { captureObligationSnapshot } from '../src/solver/obligationProgress'; import { leadPlanningEvidence, leadPlanningEvidenceText } from '../src/solver/planningEvidence'; import { leadPlanDeliveryFile, markTaskAcceptance, parseCooperationPlan, taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; import { receiptBatch } from './helpers/verifier'; const host = vi.hoisted(() => ({ createSession: vi.fn() })); vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); const roots: string[] = []; -const running: { cooperation: CooperativeResearch; controller: AbortController }[] = []; afterEach(async () => { - for (const item of running.splice(0)) { item.controller.abort(); await item.cooperation.stop(); } expect(host.createSession).not.toHaveBeenCalled(); host.createSession.mockReset(); vi.restoreAllMocks(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); @@ -135,235 +132,3 @@ describe('goal effort and unresolved frontier', () => { expect(clock.state.goals[0]).toMatchObject({ activeMs: 100, coreActiveMs: 0, coreSeenEvidence: [] }); }); }); - -describe('executable goal reviews', () => { - it.each(['typed-lemma', 'advisory-research'])('binds a review to a connected new %s target in the same revision', kind => { - const example = localExample('goal-review-new-target-'); roots.push(example.directory); - const originals = example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal' as const, - objective: `Prove ${target.theoremName}.`, dependsOn: [], revision: 0, - ...(index ? { status: 'paused' as const } : {}) })); - const basePlan = parseCooperationPlan(example.problem, { tasks: originals }); - const current = basePlan.tasks.map(node), clock = observer(current, [originals[0].id]); - clock.observe(0); clock.observe(interval); - const target = kind === 'typed-lemma' ? { ...lemma('bridge'), theoremName: 'Tutorial.bridge' } - : research('investigation', [originals[0].id]); - const base = { ...basePlan, version: 'accepted-plan' }; - const revision = { baseVersion: base.version, upsert: [target, - ...(kind === 'typed-lemma' ? [{ id: originals[0].id, dependsOn: [target.id] }] : [])], - progressReview: { id: clock.state.pending!.id, reason: 'Test the exact missing input.', nextChecks: [check(target)] } }; - const plan = parseLeadPlan(example.problem, revision, base); - expect(prepareGoalProgressDecision(plan.goalProgressDecision!, clock.state, plan, [], current).nextChecks[0]) - .toMatchObject({ targetTaskId: target.id, taskDigest: taskVersion(plan.tasks.find(task => task.id === target.id)!) }); - - const disconnected = parseLeadPlan(example.problem, { ...revision, - upsert: [kind === 'typed-lemma' ? target : { ...target, consumerGoalIds: [] }] }, base); - expect(() => prepareGoalProgressDecision(disconnected.goalProgressDecision!, clock.state, disconnected, [], current)) - .toThrow('math_plan_progress_review_task_unavailable: ' + target.id); - if (kind === 'typed-lemma') { - expect(() => parseLeadPlan(example.problem, { ...revision, - upsert: [{ ...target, consumerGoalIds: [originals[0].id] }, revision.upsert[1]] }, base)) - .toThrow('consumerGoalIds'); - const wrongDeclaration = { ...plan.goalProgressDecision!, nextChecks: [{ ...check(target), execution: { - kind: 'application' as const, expectedType: 'True', expression: 'by trivial', - context: { file: target.proofPath!, declaration: 'Tutorial.other' }, - } }] }; - expect(() => prepareGoalProgressDecision(wrongDeclaration, clock.state, plan, [], current)) - .toThrow('math_plan_progress_review_task_unavailable: ' + target.id); - } - }); - - it.each([false, true])('accepts a live Lead plan after peer proof progress supersedes its review (new review: %s)', async replacement => { - const example = localExample('goal-review-race-'); roots.push(example.directory); - const lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'peer'); - const originals = example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal' as const, - objective: `Prove ${target.theoremName}`, dependsOn: index === 0 ? ['core'] : [], revision: 0, - ...(index ? { status: 'paused' as const } : {}) })); - const core = { ...lemma('core'), theoremName: 'Tutorial.core', status: 'paused' as const }; - const work = { ...research('research', [originals[0]!.id]), ownerId: peer.id }; - const plan = parseCooperationPlan(example.problem, { tasks: [...originals, core, work] }); - const state = solverState(example.problem, example.workspace, { runId: 'review-race', phase: 'running', - cooperation: { tasks: plan.tasks.map(node), canonicalCommit: example.problem.baseCommit, - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const events: string[] = [], controller = new AbortController(); - let now = 0; vi.spyOn(Date, 'now').mockImplementation(() => now); - const cooperation = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: example.directory, - signal: controller.signal, emit: event => events.push(event) }); running.push({ cooperation, controller }); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const workAction = await cooperation.next(peer, budget); - if (workAction?.kind !== 'task' || workAction.task.id !== work.id) throw new Error('missing research assignment'); - expect(cooperation.started(peer, workAction)).toBe(true); - cooperation.activate(peer, workAction, async () => {}, async () => {}); - (cooperation as any).changed(); now = interval; (cooperation as any).changed(); - const oldReview = state.cooperation!.goalProgress!.pending!.id; - const leadAction = await cooperation.next(lead, budget); - if (leadAction?.kind !== 'lead') throw new Error('missing Lead review'); - expect(cooperation.contextState(leadAction, lead).goalProgress!.pending!.id).toBe(oldReview); - expect(cooperation.started(lead, leadAction)).toBe(true); - cooperation.activate(lead, leadAction, async () => {}, async () => {}); - const reminder = cooperation.leadCheckpointInstruction(leadAction); - expect(reminder).toContain('Include progressReview with id ' + JSON.stringify(oldReview)); - expect(reminder).toContain('nextChecks covering every reviewed goal: ["goal_0"]'); - expect(reminder).not.toContain('return without a revision'); - expect(cooperation.contextState(leadAction, lead).leadDecisionInstruction).toBe(reminder); - - // Another worker's checked receipt reaches the archive while the Lead is still composing this plan. - const checked = proof(core); - checked.projection = { environmentDigest: state.environmentDigest, problemReceiptDigest: example.problem.receiptDigest, - sourceDigest: 'fixture-source' }; - checked.references = { root: { file: core.proofPath!, name: core.theoremName! }, sourceCommit: example.problem.baseCommit, - environmentDigest: state.environmentDigest, contextDigest: 'fixture-context', inputs: [], tasks: [], statement: [], proof: [] }; - const index = state.cooperation!.tasks.findIndex(item => item.task.id === core.id); - state.cooperation!.tasks[index] = { ...node(core), status: 'integrated', proof: checked, integratedCheck: checked }; - now++; (cooperation as any).changed(); - expect(state.cooperation!.goalProgress!.pending).toBeUndefined(); - expect(state.cooperation!.goalProgress!.goals[0]!.coreSeenEvidence).toHaveLength(1); - if (replacement) { now += interval; (cooperation as any).changed(); } - const nextReview = state.cooperation!.goalProgress!.pending?.id; - if (replacement) expect(nextReview).not.toBe(oldReview); - const settledReminder = cooperation.leadCheckpointInstruction(leadAction); - expect(settledReminder).toContain('return without a revision'); - expect(settledReminder).not.toContain('Include progressReview'); - expect(settledReminder).not.toContain(oldReview); - if (nextReview) expect(settledReminder).not.toContain(nextReview); - - fs.appendFileSync(path.join(lead.worktree, leadPlanDeliveryFile(leadAction)!), JSON.stringify({ kind: 'plan', - dispatchNonce: leadAction.planNonce, baseVersion: leadAction.planVersion, - upsert: [{ id: work.id, informalProof: 'Use the newly checked input in the next construction.' }], - progressReview: { id: oldReview, reason: 'Continue with the planned check.', nextChecks: [check(core)] } }) + '\n'); - await cooperation.pulse(lead.id); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(events).toContain('plan_published'); - expect(state.cooperation!.tasks.find(item => item.task.id === work.id)!.task.informalProof) - .toBe('Use the newly checked input in the next construction.'); - expect(state.cooperation!.goalProgress!.pending?.id).toBe(nextReview); - expect(state.cooperation!.goalProgress!.decisions ?? []).toEqual([]); - expect(events).not.toContain('goal_progress_review_answered'); - }); - - it('requires concrete active tasks serving every reviewed goal and records guidance without resetting core stagnation', () => { - const tasks = [node(lemma('core')), node(goal()), node(research())], clock = observer(tasks); - clock.observe(0); clock.observe(interval); - const request = { progressReview: { id: clock.state.pending!.id, reason: 'Test the unresolved construction.', nextChecks: [check(tasks[0]!.task)] } }; - expect(() => parseGoalProgressDecision({ progressReview: { id: request.progressReview.id, reason: 'Keep going.' } })).toThrow('nextChecks'); - expect(parseGoalProgressDecision({ progressReview: { id: request.progressReview.id, reason: 'Keep going.' } }, true)).toBeUndefined(); - const parsed = parseGoalProgressDecision(request)!; - const plan = { tasks: tasks.map(item => item.task), groups: [] }; - const prepared = prepareGoalProgressDecision(parsed, clock.state, plan); - expect(prepared.nextChecks[0]!.taskDigest).toBe(taskVersion(tasks[0]!.task)); - expect(() => prepareGoalProgressDecision({ ...parsed, nextChecks: [check(lemma('unrelated'))] }, clock.state, - { ...plan, tasks: [...plan.tasks, lemma('unrelated')] })).toThrow('task_unavailable'); - expect(() => prepareGoalProgressDecision(parsed, clock.state, { ...plan, - tasks: plan.tasks.map(task => task.id === 'core' ? { ...task, status: 'paused' } : task) })).toThrow('task_unavailable'); - expect(() => prepareGoalProgressDecision(parsed, clock.state, plan, [], - tasks.map(item => item.task.id === 'core' ? { ...item, status: 'integrated' } : item))).toThrow('task_unavailable'); - const evidence = structuredClone(clock.state.goals[0]!.seenEvidence); - expect(answerGoalProgress(clock.state, prepared, interval)).toBe(true); - expect(clock.state.goals[0]).toMatchObject({ coreActiveMs: interval, lastReviewedCoreMs: interval, seenEvidence: evidence }); - expect(clock.observe(interval).requested).toBe(false); - expect(clock.observe(2 * interval - 1).requested).toBe(false); - expect(clock.observe(2 * interval).requested).toBe(true); - expect(goalProgressTaskContext(clock.state, tasks[0]!.task)).toContain(prepared.nextChecks[0]!.expectedEvidence); - expect(goalProgressTaskContext(clock.state, { ...tasks[0]!.task, type: 'False', revision: 1 })).toBe(''); - }); - - it('reports the uncovered independent goal while allowing one shared check to cover multiple goals', () => { - const shared = lemma('shared'), independent = goal('independent', []); - const tasks = [node(shared), node(goal('left', [shared.id])), node(goal('right', [shared.id])), node(independent)]; - const clock = observer(tasks, [shared.id, independent.id]); - clock.observe(0); clock.observe(interval); - expect(clock.state.pending!.goalIds).toEqual(['left', 'right', 'independent']); - const plan = { tasks: tasks.map(item => item.task), groups: [] }; - const decision = { id: clock.state.pending!.id, reason: 'Check the shared estimate and retain the independent proof.', - nextChecks: [check(shared)] }; - expect(() => prepareGoalProgressDecision(decision, clock.state, plan)) - .toThrow('math_plan_progress_review_goal_unanswered: independent'); - const prepared = prepareGoalProgressDecision({ ...decision, nextChecks: [...decision.nextChecks, check(independent)] }, - clock.state, plan); - expect(prepared.nextChecks.map(item => item.targetTaskId)).toEqual(['shared', 'independent']); - expect(plan.tasks.map(task => task.dependsOn)).toEqual([[], ['shared'], ['shared'], []]); - const prompt = leadPlanningEvidenceText(leadPlanningEvidence({ tasks, goalProgress: clock.state })); - expect(prompt).toContain('nextChecks must cover every reviewed goal'); - expect(prompt).toContain('One check may cover multiple goals through recorded dependencies'); - expect(prompt).toContain('do not invent connections merely to satisfy coverage'); - expect(prompt).toContain('A new target may be created in upsert in this same revision'); - expect(prompt).toContain('An unchanged completed or integrated target is unavailable'); - }); - - it('preserves old reason-only records but exposes only exact bound directions to each worker', () => { - const tasks = [node(lemma('core')), node(goal()), node(research())], clock = observer(tasks); - clock.observe(0); clock.observe(interval); - const pending = clock.state.pending!; - clock.state.decisions = [{ id: 'legacy', at: 0, reason: 'Keep going.', goalKeys: pending.goalKeys }]; - const bound = prepareGoalProgressDecision({ id: pending.id, reason: 'Check the next inference.', nextChecks: [check(tasks[0]!.task)] }, - clock.state, { tasks: tasks.map(item => item.task), groups: [] }); - answerGoalProgress(clock.state, bound, interval); - const restored = goalProgressStateSchema.parse(JSON.parse(JSON.stringify(clock.state))); - expect(restored).toEqual(clock.state); - const scoped = goalProgressForTask(restored, tasks[0]!.task)!; - expect(scoped.goals).toEqual([]); expect(scoped.pending).toBeUndefined(); expect(scoped.decisions).toHaveLength(1); - expect(goalProgressForTask(restored, research())).toBeUndefined(); - }); - - it('assigns fallback research to its covered original goals and notifies an active task of an accepted check', async () => { - const example = localExample('goal-review-fallback-'); roots.push(example.directory); - const lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'peer'); - const state = solverState(example.problem, example.workspace, { runId: 'review-fallback', phase: 'running' }); - const controller = new AbortController(), cooperation = cooperativeResearch({ state, workers: [lead, peer], - retrievalRoot: example.directory, signal: controller.signal }); running.push({ cooperation, controller }); - await cooperation.startInitialTasks(); - const work = state.cooperation!.tasks.find(item => item.task.kind === 'research')!.task; - expect(work.consumerGoalIds).toEqual(state.cooperation!.tasks.filter(item => item.task.kind === 'goal').map(item => item.task.id)); - const target = state.cooperation!.tasks.find(item => item.task.kind === 'goal')!.task; - expect(target.dependsOn).not.toContain(work.id); - const clock = observer(state.cooperation!.tasks, [work.id]); clock.observe(0); clock.observe(interval); - state.cooperation!.goalProgress = clock.state; - const action = { kind: 'task' as const, task: work, assignment: { taskId: work.id, taskDigest: taskVersion(work), - workerId: peer.id, seedCommit: example.problem.baseCommit, dependencies: [] } }; - const record = state.cooperation!.tasks.find(item => item.task.id === work.id)!; - record.assignment = action.assignment; - const notify = vi.fn(async () => {}); - (cooperation as any).active.set(peer.id, { action, notify, interrupt: async () => {} }); - const decision = prepareGoalProgressDecision({ id: clock.state.pending!.id, reason: 'Use the recorded finite input.', nextChecks: [check(work)] }, - clock.state, { tasks: state.cooperation!.tasks.map(item => item.task), groups: state.cooperation!.groups!.map(item => item.group) }); - const leadAction = { kind: 'lead' as const, seedCommit: example.problem.baseCommit }; - (cooperation as any).presentedGoalProgress.set(leadAction, decision.id); - (cooperation as any).goalProgressDecisions.set(leadAction, decision); - (cooperation as any).answerGoalProgressReview(leadAction); - expect(notify).toHaveBeenCalledOnce(); - expect(notify.mock.calls[0]![0]).toContain(decision.nextChecks[0]!.expectedEvidence); - (cooperation as any).active.delete(peer.id); - }); - - it('preserves attribution as metadata, validates original-goal references, and delivers saved checks in mandatory context', async () => { - const example = localExample('goal-progress-review-'); roots.push(example.directory); - const originals = example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal' as const, - objective: `Prove ${target.theoremName}`, dependsOn: [], revision: 0 })); - const work = research('research', [originals[0]!.id]); - const plan = parseCooperationPlan(example.problem, { tasks: [...originals, work] }); - expect(taskVersion(work)).toBe(taskVersion({ ...work, consumerGoalIds: [] })); - expect(plan.tasks.at(-1)!.consumerGoalIds).toEqual([originals[0]!.id]); - expect(() => parseCooperationPlan(example.problem, { tasks: [...originals, { ...work, consumerGoalIds: ['research'] }] })).toThrow('consumerGoalIds'); - const records = plan.tasks.map(node), clock = observer(records); clock.observe(0); clock.observe(interval); - const bound = prepareGoalProgressDecision({ id: clock.state.pending!.id, reason: 'Investigate the boundary case.', nextChecks: [check(work)] }, clock.state, plan); - answerGoalProgress(clock.state, bound, interval); - const lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'peer'); - const state = solverState(example.problem, example.workspace, { runId: 'review-context', phase: 'running', - cooperation: { tasks: records, canonicalCommit: example.problem.baseCommit, goalProgress: clock.state, - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - // Persist and re-read through the real checkpoint schema before constructing the next dispatch. - const file = path.join(example.directory, 'state.json'); writeSolverRunState(file, state); - const restored = readSolverRunState(file); - const controller = new AbortController(), cooperation = cooperativeResearch({ state: restored, workers: [lead, peer], - retrievalRoot: example.directory, signal: controller.signal }); running.push({ cooperation, controller }); - const action = { kind: 'task' as const, task: work, assignment: { taskId: work.id, taskDigest: taskVersion(work), - workerId: peer.id, seedCommit: example.problem.baseCommit, dependencies: [] } }; - const scoped = cooperation.contextState(action, peer); - expect(scoped.goalProgress?.decisions?.[0]?.nextChecks?.[0]?.targetTaskId).toBe(work.id); - const context = buildResearchContext(example.problem, { ...restored, cooperation: scoped }, { root: example.directory, - worktree: peer.worktree, environment: {}, taskText: 'Prove the frozen goal.', retrievalRoot: example.directory, - assignment: action, maxOptionalContextBytes: 0 }); - expect(context.manifest?.included).toContainEqual(expect.objectContaining({ id: 'goal-review-next-checks', required: true })); - expect(context.message).toContain(bound.nextChecks[0]!.expectedEvidence); - expect(context.continuationMessage).toContain(bound.nextChecks[0]!.expectedEvidence); - }); -}); diff --git a/tests/harnessProcess.test.ts b/tests/harnessProcess.test.ts index 87c9cf48..b17a85e3 100644 --- a/tests/harnessProcess.test.ts +++ b/tests/harnessProcess.test.ts @@ -52,6 +52,26 @@ describe('shared native harness process isolation', () => { expect(fs.readFileSync(secret, 'utf8')).toBe('hidden file'); }); + it('allows planning notes while the proof workspace and repository metadata are read-only', () => { + const proof = path.join(workspace, 'proof.lean'); + const gitDirectory = path.join(workspace, '.git'); + fs.writeFileSync(proof, 'theorem proposed : True := by sorry'); + fs.mkdirSync(gitDirectory); + const launch = prepareHarnessProcess({ workspace, profile, readOnlyWorkspace: true }, + process.execPath, ['-e', ` + const fs = require('fs'), path = require('path'); + for (const file of ['proof.lean', 'new.lean', '.git/HEAD']) { + try { fs.writeFileSync(file, 'bad'); process.exit(9); } + catch (error) { if (error.code !== 'EROFS' && error.code !== 'EACCES') throw error; } + } + fs.writeFileSync(path.join(path.dirname(process.env.TMPDIR), 'plan.md'), 'route notes'); + `]); + const result = spawnSync(launch.command, launch.args, { env: launch.env, encoding: 'utf8', timeout: 10_000 }); + expect(result.status, result.stderr).toBe(0); + expect(fs.readFileSync(proof, 'utf8')).toContain('sorry'); + expect(fs.readFileSync(path.join(workspace, '.scratch', 'plan.md'), 'utf8')).toBe('route notes'); + }); + it('lets a Mathlib writer start a nested sandbox without exposing its hidden roots', () => { const canary = path.join(outside, 'canary'); fs.writeFileSync(canary, 'private'); diff --git a/tests/harnessProofAcceptance.test.ts b/tests/harnessProofAcceptance.test.ts index 3f4a2903..52600298 100644 --- a/tests/harnessProofAcceptance.test.ts +++ b/tests/harnessProofAcceptance.test.ts @@ -9,8 +9,8 @@ import { readMathAgentSkill } from '../src/runtime/agentSkills'; import { researchHarness } from '../src/runtime/researchHarness'; import { directSolverModules } from '../src/solver/modules'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { runResearchWorkers } from '../src/solver/research'; -import { leadWorker, localExample, solverState } from './helpers/solver'; +import { runResearchLead } from '../src/solver/research'; +import { localExample, solverState } from './helpers/solver'; // Only the unrelated build receipt is a double. Native processes, filesystem isolation, // writer shutdown, source freezing, helper checks and all original-target checks are real. @@ -57,9 +57,9 @@ describe('portable native research retains independent real Lean acceptance', () LEAN_PATH: '', LEAN_SYSROOT: '', DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'absent.env') }; const events: string[] = []; - const winner = await runResearchWorkers({ state, workers: [leadWorker(problem, workspace)], - access: new Map([['solver', { environment, researchSkill: skill, retrievalRoot: workspace, - ...(harnessId === 'cli' ? { nativeContinuity: false } : {}) }]]), + const winner = await runResearchLead({ state, + access: { environment, researchSkill: skill, retrievalRoot: workspace, + ...(harnessId === 'cli' ? { nativeContinuity: false } : {}) }, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: researchHarness(harnessId).open } }, root: repository, buildFile: path.join(directory, 'unused-build.json'), taskText: 'Check the frozen tutorial statements.', executable, profile, signal: new AbortController().signal, deadline: Infinity, diff --git a/tests/helpers/cooperation.ts b/tests/helpers/cooperation.ts deleted file mode 100644 index c07f1cd9..00000000 --- a/tests/helpers/cooperation.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { CooperativeResearch } from '../../src/solver/cooperation'; -import { reviewGoalPaths } from '../../src/solver/goalPathReview'; -import { directSolverModules } from '../../src/solver/modules'; -import type { ResearchWorker } from '../../src/solver/modules/organization'; -import type { WorkerAccess } from '../../src/solver/research'; -import type { SolverRunState } from '../../src/solver/archive'; - -type Input = ConstructorParameters[0]; - -// Worker-delivery fixtures must keep their helper open even when real Lean can solve it at dispatch. -export const workerDeliveryModules: Input['modules'] = { - ...directSolverModules, M2: { ...directSolverModules.M2, closeTask: undefined }, -}; - -/** Access for every worker with an empty environment and a shared retrieval root. */ -export function workerAccess(workers: readonly ResearchWorker[], retrievalRoot: string): Map { - return new Map(workers.map(worker => [worker.id, { environment: {}, retrievalRoot }])); -} - -/** - * Record the current goal-path stall, if any, as already answered by a Lead turn that saw it, as a live - * decision on unchanged input would have. Fixtures that only simulate such a decision use this. - */ -export function answeredGoalPathStall(state: SolverRunState) { - const cooperation = state.cooperation!; - const review = reviewGoalPaths(cooperation.tasks, { groups: cooperation.groups, proofRoutes: cooperation.proofRoutes, - environmentDigest: state.environmentDigest, candidates: false }); - if (review.stallDigest) cooperation.goalPathStall = { digest: review.stallDigest, active: true, at: 0, - goalIds: review.stalledGoalIds, taskIds: review.stalledTaskIds.slice(0, 16), answeredAt: 0 }; - return review.stallDigest; -} - -/** - * CooperativeResearch with fixture defaults: shared-root access, a fresh signal, no-op save and emit, - * the direct modules and an inline exclusive check. Any field in `input` replaces its default. - */ -export function cooperativeResearch(input: Pick & Partial & { retrievalRoot: string }): CooperativeResearch { - const { retrievalRoot, ...rest } = input; - return new CooperativeResearch({ access: workerAccess(input.workers, retrievalRoot), - signal: new AbortController().signal, save: () => {}, emit: () => {}, modules: directSolverModules, - exclusiveCheck: async check => check(), ...rest }); -} diff --git a/tests/helpers/solver.ts b/tests/helpers/solver.ts index f5265bc0..6db42b9c 100644 --- a/tests/helpers/solver.ts +++ b/tests/helpers/solver.ts @@ -36,3 +36,7 @@ export function solverState(problem: SolverProblem, worktree: string, fields: St taskDigest: 'task', buildDigest: 'build', environmentDigest: 'environment', evaluatorDigest: 'evaluator', model: 'unused', effort: 'unused', worktree, turns: 0, ...rest }; } + +export function workerAccess(workers: readonly ResearchWorker[], retrievalRoot: string): Map { + return new Map(workers.map(worker => [worker.id, { environment: {}, retrievalRoot }])); +} diff --git a/tests/helpers/solverAtomicPlanRejection.ts b/tests/helpers/solverAtomicPlanRejection.ts deleted file mode 100644 index f687a0de..00000000 --- a/tests/helpers/solverAtomicPlanRejection.ts +++ /dev/null @@ -1,91 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { describe, expect, it, vi } from 'vitest'; -import { commitSolverSources, committedSource } from '../../src/solver/problem'; -import { parseCooperationPlan } from '../../src/solver/tasks'; -import { cooperativeResearch } from './cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './solver'; - -describe('CooperativeResearch malformed plans', () => { - const fence = (value: unknown) => '```math-plan\n' + JSON.stringify(value) + '\n```'; - const malformedFence = fence({ tasks: [] }) + '\n' + fence({ tasks: [] }); - - function fixture() { - const example = localExample('solver-atomic-plan-rejection-', 'lead'); - const { directory, workspace, problem } = example; - const lead = leadWorker(problem, workspace); - const peer = peerWorker(example, 'engineer', { role: 'engineer' }); - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - ...target, id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, status: 'paused', - })) }); - const archive = { tasks: plan.tasks.map(task => ({ task, status: 'blocked' as const, attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })), error: 'fixture_request_new_plan' }; - const state = solverState(problem, workspace, { runId: 'atomic-plan-rejection', phase: 'running', cooperation: archive }); - const controller = new AbortController(); - const emit = vi.fn(); - const research = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: directory, signal: controller.signal, emit }); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const inbox = (worktree: string) => JSON.parse(fs.readFileSync(path.join(worktree, 'COOPERATION.json'), 'utf8')); - async function checkpoint(notes: string, editLean?: () => void) { - const action = await research.next(lead, budget); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead'); - expect(research.started(lead, action)).toBe(true); - research.activate(lead, action, async () => {}, async () => {}); - expect(research.leadCheckpointInstruction(action)).toContain('plan-apply'); - const file = path.join(lead.worktree, 'RESEARCH.md'); - fs.writeFileSync(file, notes); - editLean?.(); - research.deactivate(lead); - const commit = commitSolverSources(problem, lead.worktree); - await research.deliver(lead, action, commit, true, 'scheduling-checkpoint'); - return commit; - } - return { state, research, lead, peer, problem, emit, inbox, budget, checkpoint, async close() { - controller.abort(); - await research.stop(); - fs.rmSync(directory, { recursive: true, force: true }); - } }; - } - - it('keeps a repair turn private and stops retrying different malformed drafts on unchanged inputs', async () => { - const f = fixture(); - try { - const archive = f.state.cooperation!; - const first = await f.checkpoint(malformedFence); - expect(f.inbox(f.lead.worktree)).toMatchObject({ error: 'math_math-plan_requires_one_block' }); - expect(f.inbox(f.peer.worktree)).not.toHaveProperty('planRejection'); - expect(archive.planRejection).toMatchObject({ stalled: false }); - expect(committedSource(f.lead.worktree, first, 'RESEARCH.md')).toBe(malformedFence); - - // A distinct schema error receives accurate feedback, but neither a different bad - // response nor changing its explanatory prose is new mathematical evidence. - const second = '# Still drafting\n\n' + fence({ tasks: 'bad task array' }); - await f.checkpoint(second); - expect(archive.planRejection).toMatchObject({ stalled: true, - error: expect.stringContaining('math_plan_invalid: {"field":"tasks"}') }); - expect(f.inbox(f.peer.worktree)).not.toHaveProperty('error'); - expect(archive.deliveries ?? []).toEqual([]); - expect(archive.leadWakes?.recent?.filter(wake => wake.reason === 'plan-rejected') ?? []).toEqual([]); - expect(await f.research.next(f.lead, f.budget)).toBeUndefined(); - expect(f.emit).toHaveBeenCalledWith('plan_stalled', expect.objectContaining({ stalled: true })); - } finally { await f.close(); } - }); - - it('retains a checkpoint containing genuine Lean changes as an advisory source draft', async () => { - const f = fixture(); - try { - const file = path.join(f.lead.worktree, f.problem.projectRelative, 'Submission.lean'); - const commit = await f.checkpoint(malformedFence, () => { - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', 'lemma atomic_plan_draft : True := by trivial\ntheorem add_zero')); - }); - const archive = f.state.cooperation!; - expect(archive.deliveries).toContainEqual(expect.objectContaining({ - commit, kind: 'progress', status: 'advisory', - summary: expect.stringContaining('owned Lean source changes'), - })); - expect(archive.deliveries?.find(delivery => delivery.commit === commit)?.summary).not.toContain('math_math-plan_requires_one_block'); - expect(committedSource(f.lead.worktree, commit, `${f.problem.projectRelative}/Submission.lean`)).toContain('lemma atomic_plan_draft'); - expect(archive.tasks.every(node => !node.integratedCheck)).toBe(true); - } finally { await f.close(); } - }); -}); diff --git a/tests/helpers/solverTeamRouteRetirement.ts b/tests/helpers/solverTeamRouteRetirement.ts deleted file mode 100644 index 5026b7a2..00000000 --- a/tests/helpers/solverTeamRouteRetirement.ts +++ /dev/null @@ -1,176 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../../src/math/leanTask'; -import { mathDigest } from '../../src/math/mathRuntimeIo'; -import { readMathAgentSkill } from '../../src/runtime/agentSkills'; -import type { MathAgentOptions, MathAgentSession } from '../../src/runtime/agentSession'; -import type { NativeAgentControlConnection } from '../../src/runtime/nativeAgentControl'; -import { AgentResearchTeam } from '../../src/solver/agentTeam'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../../src/solver/archive'; -import { directSolverModules } from '../../src/solver/modules'; -import { readSolverProblem } from '../../src/solver/problem'; -import { prepareResearchSkill, researchSkillIdentity } from '../../src/solver/researchSkill'; -import { deferred } from './async'; -import { temporaryDirectory } from './files'; -import { solverState } from './solver'; - -const goal = 'Show True.'; -const rootThreadId = '00000000-0000-4000-8000-000000000001'; -const cleanup: Array<() => Promise> = []; -afterEach(async () => { - for (const close of cleanup.splice(0)) await close(); -}); - -function nativeConnection(threadId: string, agentPath: string, cwd: string): NativeAgentControlConnection { - return { - info: { sessionId: rootThreadId, agent: { threadId, metadata: { threadId, agentPath }, status: 'running' }, - configSnapshot: { cwd } }, - request: vi.fn(async () => ({})), - input: vi.fn(async () => ({ accepted: true, threadId, submissionId: 'followup' })), - update: vi.fn(async request => ({ acceptedSequence: request.sequence })), - }; -} - -function fixture(transport: 'host-tools' | 'native-agent-control') { - const directory = temporaryDirectory('team-route-retirement-'); - const task = bootstrapLeanTask(path.join(directory, 'lead'), { source: 'theorem target : True := by sorry\n', task: goal }); - const problem = readSolverProblem(task.workspaceRoot, task.activeProblemPath); - const root = process.cwd(); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, task.workspaceRoot, { runId: 'team-route-retirement', phase: 'running', - environmentDigest: mathDigest('offline route retirement fixture'), - researchMode: 'skill', researchSkillWorkflow: 'full', researchSkill: identity, workerCount: 1, - researchDelegation: { mode: 'team', maxAgents: 2 }, - agentTeam: { schema: 'theorem-os.agent-team.v1', transport, workers: [], events: [], deliveries: [], adoptions: [], operations: [] } }); - const skill = prepareResearchSkill(root, state.worktree, identity, problem); - const controller = new AbortController(), stateFile = path.join(directory, 'state.json'); - const current = new Map; stopped: ReturnType; - interrupt: () => Promise; finish: () => void; context?: string }>(); - const teams: AgentResearchTeam[] = []; - const open = async (options: MathAgentOptions): Promise => { - const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - const threadId = options.threadId ?? (options.nativeAgentControl?.bootstrap?.threadId as string | undefined) ?? id; - const started = deferred(), stopped = deferred(), outcome = deferred(); - const record = { started, stopped, interrupt: vi.fn(async () => { outcome.resolve('interrupted'); }), - finish: () => { stopped.resolve(); outcome.resolve('completed'); }, context: undefined as string | undefined }; - current.set(id, record); - return { threadId, usageSource: 'upstream-requests', - ...(options.nativeAgentControl ? { nativeAgentControl: nativeConnection(threadId, '/root/' + id, options.workspace) } : {}), - run: async (message, _id, _workspace, onStarted) => { - record.context = message; onStarted('turn-' + id); started.resolve(); return outcome.promise; - }, - interrupt: record.interrupt, stopForFreeze: async () => { await stopped.promise; return { status: 'stopped' }; }, - close: async () => {} }; - }; - const create = (saved: SolverRunState) => { - const team = new AgentResearchTeam({ state: saved, root, taskText: goal, - leadAccess: { researchSkill: skill, environment: {}, retrievalRoot: saved.worktree }, - executable: 'offline', profile: 'offline', signal: controller.signal, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, - maxAgents: 2, maxTurns: Infinity, maxTotalTokens: 0, maxTurnMs: Infinity, remainingMs: () => Infinity, - save: () => writeSolverRunState(stateFile, saved), emit: () => {}, exclusiveCheck: operation => operation() }); - teams.push(team); return team; - }; - const team = create(state); - let sequence = 0; - const call = (args: Record, actor = 'lead', instance = team) => instance.tools(actor).call('theoremos_team', args, { - threadId: 'fixture', turnId: 'fixture', callId: 'tool-' + ++sequence, signal: controller.signal, - }); - const session = async (id: string) => { - await expect.poll(() => current.get(id)).toBeDefined(); - const worker = current.get(id)!; - await worker.started.promise; return worker; - }; - cleanup.push(async () => { - for (const session of current.values()) session.finish(); - controller.abort(); - await Promise.all(teams.map(team => team.close())); - fs.rmSync(directory, { recursive: true, force: true }); - }); - return { team, state, stateFile, create, call, session, signal: controller.signal }; -} - -const retirement = { operation: 'retire_route', routeId: 'counterexample', - reason: 'The symmetric reduction fails at the boundary.', evidenceRefs: ['RESEARCH.md#boundary-witness'] }; - -describe('atomic AgentResearchTeam route retirement', () => { - it('cancels the running and queued tasks together, releases capacity, and refuses the route after resume', async () => { - const f = fixture('host-tools'); - expect(await f.call({ operation: 'spawn', agentId: 'old', routeId: 'counterexample', message: 'Check the route.' })) - .toMatchObject({ ok: true, routeId: 'counterexample' }); - const old = await f.session('old'); - await f.call({ operation: 'assign', agentId: 'old', routeId: 'counterexample', message: 'Try the next case.' }); - expect(await f.call(retirement, 'old')).toMatchObject({ ok: false, error: 'math_team_lead_operation_required' }); - const worker = f.team.archive.workers[0]!; - const ids = worker.tasks.map(task => task.id); - expect(await f.call(retirement)).toMatchObject({ ok: true, cancelledTaskIds: ids, releasedAgentIds: ['old'] }); - expect(old.interrupt).toHaveBeenCalled(); - expect(await f.call(retirement)).toMatchObject({ ok: true, cancelledTaskIds: [], releasedAgentIds: [] }); - const durable = readSolverRunState(f.stateFile); - expect(durable.agentTeam?.retiredRoutes).toMatchObject([{ routeId: 'counterexample', source: 'lead', evidenceRefs: retirement.evidenceRefs }]); - expect(durable.agentTeam!.workers[0]!.tasks.map(task => Boolean(task.cancelRequested))).toEqual([true, true]); - expect(await f.call({ operation: 'spawn', agentId: 'new', routeId: 'counterexample', message: 'Repeat the refuted route.' })) - .toMatchObject({ ok: false, error: expect.stringContaining('math_team_route_retired:counterexample') }); - // A different isolated workspace can start while the old writer is still stopping. - expect(await f.call({ operation: 'spawn', agentId: 'new', routeId: 'replacement', message: 'Use the new construction.' })) - .toMatchObject({ ok: true }); - const replacement = await f.session('new'); - expect(replacement.context).toContain('The symmetric reduction fails at the boundary.'); - expect(worker.tasks[0]!.researchArtifactId).toBeUndefined(); - old.finish(); replacement.finish(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(worker.tasks.map(task => task.status)).toEqual(['cancelled', 'cancelled']); - expect(worker.tasks.map(task => task.turns)).toEqual([1, 0]); - expect(worker.tasks[0]!.researchArtifactId).toEqual(expect.any(String)); - await f.team.close(); - const saved = readSolverRunState(f.stateFile), resumed = f.create(saved); - await resumed.restore(); - expect(await f.call({ operation: 'assign', agentId: 'new', routeId: 'counterexample', message: 'Reopen without different evidence.' }, 'lead', resumed)) - .toMatchObject({ ok: false, error: expect.stringContaining('math_team_route_retired:counterexample') }); - }); - - it('prunes queued work without interrupting a different route on the same member', async () => { - const f = fixture('host-tools'); - await f.call({ operation: 'spawn', agentId: 'mixed', routeId: 'live-route', message: 'Check the construction.' }); - const live = await f.session('mixed'); - const queued = await f.call({ operation: 'assign', agentId: 'mixed', routeId: 'counterexample', message: 'Check a different route.' }); - expect(await f.call(retirement)).toMatchObject({ ok: true, cancelledTaskIds: [(queued as { taskId: string }).taskId], releasedAgentIds: [] }); - expect(live.interrupt).not.toHaveBeenCalled(); - live.finish(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(f.team.archive.workers[0]!.tasks.map(task => task.status)).toEqual(['completed', 'cancelled']); - }); - - it('tags native spawn work, exposes the Lead operation, and blocks retired native requests', async () => { - const f = fixture('native-agent-control'); - const options = f.team.nativeAgentControlOptions('lead')!; - const connection = nativeConnection(rootThreadId, '/root', f.state.worktree); - let sequence = 0; - const native = (operation: string, payload: Record) => options.request({ - version: 1, operation, operationId: 'native-' + ++sequence, threadId: rootThreadId, sessionId: rootThreadId, payload, - }, connection, { signal: f.signal }); - await native('attach', { threadId: rootThreadId, sessionId: rootThreadId }); - const spawn = (id: string, route: string) => native('spawn', { caller: rootThreadId, - source: { subagent: { thread_spawn: { agent_path: '/root/' + id, parent_thread_id: rootThreadId, depth: 1 } } }, - bootstrap: { config: { cwd: f.state.worktree } }, - input: { kind: 'message', mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Route: ' + route + '\nExplore a local reduction.' } }, - }); - await spawn('old', 'counterexample'); - const old = await f.session('old'); - expect(f.team.archive.workers[0]!.tasks[0]).toMatchObject({ routeId: 'counterexample', message: 'Explore a local reduction.' }); - expect(await f.call(retirement, 'old')).toMatchObject({ ok: false, error: 'math_team_native_operation_required' }); - expect(await f.call(retirement)).toMatchObject({ ok: true, releasedAgentIds: ['old'] }); - await expect(spawn('new', 'counterexample')).rejects.toThrow('math_team_route_retired:counterexample'); - await spawn('new', 'replacement'); - const replacement = await f.session('new'); - expect(replacement.context).toContain('"routeId":"replacement"'); - await expect(native('send', { target: { kind: 'path', reference: '/root/new' }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Route: counterexample\nRepeat the route.' } }, - })).rejects.toThrow('math_team_route_retired:counterexample'); - old.finish(); replacement.finish(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(f.team.archive.workers[0]!.tasks[0]!.status).toBe('cancelled'); - }); -}); diff --git a/tests/hostProofPublication.test.ts b/tests/hostProofPublication.test.ts deleted file mode 100644 index 665cbb15..00000000 --- a/tests/hostProofPublication.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { RETRY_DISPATCH } from '../src/solver/cooperationShared'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, committedSource, readSolverProblem } from '../src/solver/problem'; -import { hasTaskAcceptance, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => 'host-publication-fixture-tools', - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -// Thorp has a complete canonical helper inside a section with universes, and its -// advisory type projection defers that scope. Two other workers occupy its group. -const original = 'namespace OAI\nnoncomputable section\nuniverse u\nnamespace Thorp.Current\n' + - 'theorem first_reciprocal_main : True := by sorry\nend Thorp.Current\nend\nend OAI\n'; -const helper = 'theorem exceptionalFirst_le_reciprocalFirst : (∀ n : Nat, n = n) ∧ (∀ n : Nat, n = n) := by\n' + - ' constructor <;> intro n <;> rfl\n'; -const fixtures: ReturnType[] = []; -const verified = (request: MathematicsVerifierBatchRequest) => verifiedBatch(request, { sessionId: 'host-publication-fixture' }); - -function fixture(maxConcurrent = 3) { - const directory = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'host-proof-publication-'))); - const receipt = bootstrapLeanTask(path.join(directory, 'workspace'), { source: original, task: 'Prove the original target.' }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const project = path.join(receipt.workspaceRoot, problem.projectRelative); - fs.writeFileSync(path.join(project, 'Submission.lean'), original.replace('theorem first_reciprocal_main', helper + 'theorem first_reciprocal_main')); - const canonical = commitSolverSources(problem, receipt.workspaceRoot); - const example = { directory, workspace: receipt.workspaceRoot, receipt: undefined!, problem }; - const lead = leadWorker(problem, receipt.workspaceRoot); - const prover = peerWorker(example, 'researcher-2', { commit: canonical }); - const other = Array.from({ length: maxConcurrent - 1 }, (_, index) => - peerWorker(example, `busy-${index}`, { commit: canonical })); - const workers: ResearchWorker[] = [lead, prover, ...other]; - const tasks = [{ id: 'exceptional_le', kind: 'lemma', objective: 'Prove the canonical conjunct helper.', - dependsOn: [], revision: 0, proofPath: 'Submission.lean', - theoremName: 'OAI.Thorp.Current.exceptionalFirst_le_reciprocalFirst', type: '(∀ n : Nat, n = n) ∧ (∀ n : Nat, n = n)' }, - { id: 'goal', kind: 'goal', objective: 'Assemble the original theorem.', dependsOn: ['exceptional_le'], revision: 0, - proofPath: 'Submission.lean', theoremName: 'OAI.Thorp.Current.first_reciprocal_main', ownerId: 'missing-engineer' }, - ...other.map(worker => ({ id: worker.id, kind: 'research', objective: `Independent ${worker.id} work.`, - dependsOn: [], revision: 0 }))] as const; - const state = solverState(problem, receipt.workspaceRoot, { runId: 'host-publication-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: canonical, tasks: tasks.map(task => ({ task, - status: task.kind === 'research' ? 'running' : 'pending', attempts: task.kind === 'research' ? 1 : 0, - ...(task.kind === 'research' ? { assignment: { taskId: task.id, taskDigest: taskVersion(task), - workerId: task.id, seedCommit: canonical } } : {}) })), - groups: [{ group: { id: 'main', objective: 'Close the original target.', status: 'active', revision: 0, maxConcurrent }, turns: 0 }] } }); - const environmentFile = path.join(directory, 'environment.json'); fs.writeFileSync(environmentFile, ''); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: environmentFile }; - const controller = new AbortController(), events: { event: string; details: Record }[] = []; - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, - signal: controller.signal, access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory }])), - emit: (event, details) => events.push({ event, details }), - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, closeTask: undefined } } }); - const node = state.cooperation!.tasks[0]!; - (cooperative as any).changed(); - const f = { directory, problem, state, cooperative, controller, prover, lead, node, events, canonical, - dispatch: () => (cooperative as any).nextPeer(prover, budget, true) as Promise }; - fixtures.push(f); return f; -} - -afterEach(async () => { - for (const f of fixtures.splice(0)) { - f.controller.abort(); await f.cooperative.stop(); fs.rmSync(f.directory, { recursive: true, force: true }); - } - expect(host.createSession).not.toHaveBeenCalled(); vi.restoreAllMocks(); -}); - -describe('host proof publication in the final group slot', () => { - it.each([1, 3])('integrates a checked canonical helper despite deferred type scope at capacity %i', async capacity => { - const f = fixture(capacity); - expect(f.state.cooperation!.groups![0].busy).toBe(capacity - 1); - expect(await f.dispatch()).toBe(RETRY_DISPATCH); - expect(f.node.typePreflight).toMatchObject({ status: 'deferred', reason: 'declaration-scope-not-reproducible' }); - expect(f.node.status).toBe('integrated'); - expect(f.node.integratedCheck?.passed).toBe(true); - expect(hasTaskAcceptance(f.node.integratedCheck!)).toBe(true); - expect(f.node.attempts).toBe(0); - expect(f.events.filter(item => item.event === 'task_canonical_probe')).toHaveLength(1); - expect(f.events.filter(item => item.event === 'task_type_preflight')).toHaveLength(1); - expect(f.state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ taskId: 'exceptional_le', kind: 'proof', status: 'verified' })); - expect(committedSource(f.lead.worktree, f.state.cooperation!.canonicalCommit!, - `${f.problem.projectRelative}/Submission.lean`)).toContain(helper); - expect(f.state.workers!.find(worker => worker.id === f.prover.id)?.scheduling?.status).toBe('idle'); - expect(f.state.cooperation!.groups![0].busy).toBe(capacity - 1); - }); - - it('continues to an ordinary task when the deferred-scope canonical proof fails its independent check', async () => { - const f = fixture(); - host.verify.mockImplementation(async request => failedBatch(verified(request), { - stdoutPreview: () => 'Submission.lean:1:1: error: unsolved goals', goalsRemaining: 1 })); - const action = await f.dispatch(); - expect(action).toMatchObject({ kind: 'task', task: { id: 'exceptional_le' }, - assignment: { canonicalProbe: { proofAcceptance: 'not-accepted', verificationStatus: 'failed' } } }); - expect(f.node.status).toBe('running'); - expect(f.node.proof).toBeUndefined(); expect(f.node.integratedCheck).toBeUndefined(); - expect(f.state.cooperation!.failedTaskInputs ?? []).toEqual([]); - }); - - it.each(['paused-group', 'changed-task'] as const)('still rejects a prepared proof for a %s at publication', async invalidation => { - const f = fixture(), exclusive = (f.cooperative as any).input.exclusiveCheck; - (f.cooperative as any).input.exclusiveCheck = async (operation: () => Promise) => { - if ((f.cooperative as any).proofPublications.size) { - if (invalidation === 'paused-group') f.state.cooperation!.groups![0].group = { - ...f.state.cooperation!.groups![0].group, status: 'paused' }; - else f.node.task = { ...f.node.task, revision: 1 }; - (f.cooperative as any).changed(); - } - return exclusive(operation); - }; - expect(await f.dispatch()).toBe(RETRY_DISPATCH); - expect(f.node.status).toBe('pending'); - expect(f.node.proof).toBeUndefined(); expect(f.node.assignment).toBeUndefined(); - expect(f.state.cooperation!.canonicalCommit).toBe(f.canonical); - }); - - it('drains a preparing canonical proof on stop without retrying or claiming a stale assignment', async () => { - const f = fixture(), entered = deferred(), release = deferred(); - host.verify.mockImplementationOnce(async request => { entered.resolve(); await release.promise; return verified(request); }); - const dispatch = f.dispatch(); await entered.promise; - const stop = f.cooperative.stop(); release.resolve(); - expect(await dispatch).toBe(RETRY_DISPATCH); await stop; - expect(f.node.status).toBe('pending'); - expect(f.node.assignment).toBeUndefined(); expect(f.node.proof).toBeUndefined(); - expect((f.cooperative as any).preparingTaskTypes.size).toBe(0); - expect((f.cooperative as any).proofPublications.size).toBe(0); - }); -}); diff --git a/tests/humanGuidance.test.ts b/tests/humanGuidance.test.ts index de59d221..bd133406 100644 --- a/tests/humanGuidance.test.ts +++ b/tests/humanGuidance.test.ts @@ -9,7 +9,6 @@ import { mathDigest } from '../src/math/mathRuntimeIo'; import { runInspectionSnapshot } from '../src/solver/inspection'; import { buildResearchContext } from '../src/solver/modules/context'; import { assignmentDeliveryFile, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; import { webWorkerFixture } from './helpers/webWorkerBridge'; const roots: string[] = []; @@ -106,76 +105,6 @@ describe('independent host guidance input', () => { expect(readHumanGuidance(f.stateFile, f.state.runId)[0]).toMatchObject({ status: 'failed', reason: 'fixture_transport_failed' }); }); - it('uses the cooperative host checkpoint and preserves role/task ownership', async () => { - const f = fixture(), input = guidanceFor(f); await queueHumanGuidance(f.output, input); - const workerWorktree = path.join(path.dirname(f.stateFile), 'engineer'); - execFileSync('git', ['-C', f.worktree, 'worktree', 'add', '--detach', '--quiet', workerWorktree, f.currentCommit]); - const worker = { id: 'engineer', role: 'engineer' as const, worktree: workerWorktree, ownedFiles: f.state.problem.ownedFiles }; - const lead = { ...worker, id: 'solver', role: 'lead' as const, worktree: f.worktree }; - const node = f.state.cooperation!.tasks[1]; - const assignment = { taskId: 'goal', taskDigest: taskVersion(f.goal), workerId: worker.id, seedCommit: f.currentCommit }; - node.assignment = assignment; node.status = 'running'; - const host = cooperativeResearch({ state: f.state, workers: [lead, worker], retrievalRoot: f.directory }); - const notify = vi.fn(async (_message: string) => {}); - const action: CooperativeAction = { kind: 'task', task: node.task, assignment }; - host.activate(worker, action, async () => {}, notify); - await host.pulse(worker.id); - expect(notify).toHaveBeenCalledOnce(); - expect(readHumanGuidance(f.stateFile, f.state.runId)[0]).toMatchObject({ status: 'delivered', deliveredTo: ['engineer'] }); - host.deactivate(worker); - expect(node.assignment).toBe(assignment); expect(node.task).toEqual(f.goal); - - const scoped = host.contextState(action, worker); - const problem = { ...f.state.problem, declarations: { 'Submission.lean': [{ name: 'goal', header: 'goal : True' }] } }; - const context = buildResearchContext(problem, { ...f.state, problem, cooperation: scoped }, { root: f.directory, - worktree: workerWorktree, retrievalRoot: f.directory, environment: {}, taskText: 'Prove the original goal.', assignment: action }); - for (const message of [context.message, context.continuationMessage]) { - expect(message).toContain('COOPERATION.json.humanGuidance'); - expect(message).toContain(input.id); - expect(message).toContain('guidanceDecisions'); - expect(message).not.toContain(input.text); - } - host.activate(worker, action, async () => {}, notify); - const readView = (worktree: string) => JSON.parse(fs.readFileSync(path.join(worktree, 'COOPERATION.json'), 'utf8')); - expect(readView(workerWorktree).humanGuidance).toEqual([expect.objectContaining({ id: input.id, text: input.text, taskRef: input.taskRef })]); - expect(readView(f.worktree).humanGuidance).toBeUndefined(); - host.deactivate(worker); - }); - - it('delivers a complete 128 KiB advisory candidate to the actual assigned agent without executing or writing it', async () => { - const f = fixture(), sentinel = path.join(f.directory, 'candidate-must-never-execute'); - const prefix = f.source.replace('by sorry', 'by trivial') + '\n/-'; - const suffix = `-/\n-- $(touch ${sentinel})\n-- COMPLETE-CANDIDATE-END\n`; - const source = prefix + 'x'.repeat(128 * 1024 - Buffer.byteLength(prefix + suffix)) + suffix; - const input: HumanGuidanceInput = { ...guidanceFor(f), candidate: candidateFor(f, source) }; - expect(Buffer.byteLength(source)).toBe(128 * 1024); - expect(webGuidanceSchema.parse(input).candidate?.source).toBe(source); - const before = fs.readFileSync(path.join(f.project, 'Submission.lean')), checkpoint = fs.readFileSync(f.stateFile); - expect((await queueHumanGuidance(f.output, input)).candidate).toEqual(input.candidate); - expect((await queueHumanGuidance(f.output, input)).candidate).toEqual(input.candidate); - const worker = { id: 'engineer', role: 'engineer' as const, worktree: f.worktree, ownedFiles: f.state.problem.ownedFiles }; - const lead = { ...worker, id: 'solver', role: 'lead' as const }, node = f.state.cooperation!.tasks[1]; - const assignment = { taskId: 'goal', taskDigest: taskVersion(f.goal), workerId: worker.id, seedCommit: f.currentCommit }; - node.assignment = assignment; node.status = 'running'; - const host = cooperativeResearch({ state: f.state, workers: [lead, worker], retrievalRoot: f.directory }); - const notify = vi.fn(async (_message: string) => {}); - host.activate(worker, { kind: 'task', task: node.task, assignment }, async () => {}, notify); - await host.pulse(worker.id); await host.pulse(worker.id); - expect(notify).toHaveBeenCalledOnce(); - const message = notify.mock.calls[0][0]; - expect(message).toContain(source); expect(message).toContain(input.candidate!.sourceDigest); - expect(message).toContain(input.candidate!.baseSourceDigest); - expect(message).toContain('ordinary task delivery and declaration integration'); - expect(message).toContain('independent S3 acceptance'); - expect(readHumanGuidance(f.stateFile, f.state.runId)[0]).toMatchObject({ status: 'delivered', deliveredTo: ['engineer'], candidate: input.candidate }); - expect(fs.readFileSync(path.join(f.project, 'Submission.lean'))).toEqual(before); - expect(fs.readFileSync(f.stateFile)).toEqual(checkpoint); - expect(fs.existsSync(sentinel)).toBe(false); - expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'))).toBe(false); - expect(node.status).toBe('running'); expect(node.proof).toBeUndefined(); - host.deactivate(worker); - }); - it('rejects malformed candidate bytes, paths, digests, task bindings and executable fields in both entry schemas', () => { const f = fixture(), candidate = candidateFor(f), input = { ...guidanceFor(f), candidate }; const invalid = [ @@ -314,64 +243,4 @@ describe('independent host guidance input', () => { expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toBeUndefined(); }); - it('accepts structured decisions from the actual worker delivery log and scopes recovery context to that worker', async () => { - const f = fixture(), input = guidanceFor(f); await queueHumanGuidance(f.output, input); - const worker = { id: 'engineer', role: 'engineer' as const, worktree: f.worktree, ownedFiles: f.state.problem.ownedFiles }; - const lead = { ...worker, id: 'solver', role: 'lead' as const }, node = f.state.cooperation!.tasks[1]; - const assignment = { taskId: 'goal', taskDigest: taskVersion(f.goal), workerId: worker.id, seedCommit: f.currentCommit }; - const action: CooperativeAction = { kind: 'task', task: node.task, assignment }; - node.assignment = assignment; node.status = 'running'; - const emit = vi.fn(); - const host = cooperativeResearch({ state: f.state, workers: [lead, worker], retrievalRoot: f.directory, emit }); - host.activate(worker, action, async () => {}, async () => {}); - await host.pulse(worker.id); - fs.appendFileSync(path.join(f.worktree, assignmentDeliveryFile(assignment)), JSON.stringify({ - summary: 'I accepted this guidance in prose.', - }) + '\n'); - await host.pulse(worker.id); - expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toBeUndefined(); - fs.appendFileSync(path.join(f.worktree, assignmentDeliveryFile(assignment)), JSON.stringify({ - summary: 'I have read the exact human premise.', guidanceDecisions: [decisionFor(input)], - }) + '\n'); - await host.pulse(worker.id); await host.pulse(worker.id); - const record = readHumanGuidance(f.stateFile, f.state.runId)[0]; - expect(record.decision).toMatchObject({ status: 'accepted', workerId: worker.id, sourceTaskRef: input.taskRef }); - expect(emit.mock.calls.filter(call => call[0] === 'human_guidance_decided')).toHaveLength(1); - fs.appendFileSync(path.join(f.worktree, assignmentDeliveryFile(assignment)), JSON.stringify({ - summary: 'The relevant task reference is now recorded.', - guidanceDecisions: [{ ...decisionFor(input), evidenceRefs: [{ kind: 'task', ...input.taskRef! }] }], - }) + '\n'); - await host.pulse(worker.id); - const supplemented = readHumanGuidance(f.stateFile, f.state.runId)[0]; - expect(supplemented.decision?.evidenceRefs).toEqual([{ kind: 'task', ...input.taskRef! }]); - expect(supplemented.decision?.decidedAt).toBe(record.decision?.decidedAt); - expect(emit.mock.calls.filter(call => call[0] === 'human_guidance_decided')).toHaveLength(2); - expect(host.contextState(action, worker).humanGuidance?.[0].decision).toEqual(supplemented.decision); - expect(host.contextState(undefined, lead).humanGuidance).toEqual([]); - expect(node.status).toBe('running'); expect(node.proof).toBeUndefined(); - expect(f.state.cooperation!.deliveries!.filter(item => item.producer === worker.id).every(item => item.kind === 'progress')).toBe(true); - host.deactivate(worker); - }); - - it('reads a Lead handling decision from the real final role response after delivery', async () => { - const f = fixture(), input = { ...guidanceFor(f), recipient: { kind: 'lead' as const }, taskRef: undefined }; - await queueHumanGuidance(f.output, input); - const lead = { id: 'solver', role: 'lead' as const, worktree: f.worktree, ownedFiles: f.state.problem.ownedFiles }; - const worker = { ...lead, id: 'engineer', role: 'engineer' as const }; - const host = cooperativeResearch({ state: f.state, workers: [lead, worker], retrievalRoot: f.directory }); - const action: CooperativeAction = { kind: 'lead', seedCommit: f.currentCommit, planVersion: 'plan-v1' }; - host.activate(lead, action, async () => {}, async () => {}); await host.pulse(lead.id); - expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toBeUndefined(); - fs.writeFileSync(path.join(f.worktree, 'RESEARCH.md'), JSON.stringify({ - tasks: f.state.cooperation!.tasks.map(node => node.task), summary: 'I accepted the human direction in prose.', - guidanceDecisions: [{ ...decisionFor(input), status: 'declined', reason: 'This premise does not apply to the fixed target.' }], - })); - const commit = f.commit(); - await host.deliver(lead, action, commit); - expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toMatchObject({ - status: 'declined', workerId: lead.id, sourcePlanVersion: 'plan-v1', evidenceRefs: [], - }); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'goal')?.proof).toBeUndefined(); - host.deactivate(lead); - }); }); diff --git a/tests/installedLibraryContext.test.ts b/tests/installedLibraryContext.test.ts index 79ceb5cf..e168a6a0 100644 --- a/tests/installedLibraryContext.test.ts +++ b/tests/installedLibraryContext.test.ts @@ -7,7 +7,7 @@ import { mathDigest } from '../src/math/mathRuntimeIo'; import * as residualReader from '../src/math/leanResidualGoals'; import * as knowledgeContext from '../src/solver/knowledgeContext'; import type { SolverRunState } from '../src/solver/archive'; -import type { CooperationState } from '../src/solver/cooperation'; +import type { CooperationState } from '../src/solver/cooperationShared'; import { installedLibraryContextSections, installedLibraryRetrievals, readInstalledLibrarySnapshot } from '../src/solver/installedLibraryContext'; import * as knowledgeApplications from '../src/solver/knowledgeApplications'; import { buildResearchContext, finalizeResearchDispatch, type ContextAccess } from '../src/solver/modules/context'; @@ -450,7 +450,7 @@ describe('installed library retrieval in actual task context', () => { 'you may add import Mathlib or any pinned Mathlib.* import', 'Add helpers in owned modules', 'check-lean --workspace', 'add application:{expression:']) expect(context.instructions).not.toContain(writableAdvice); expect(context.instructions.split('\n').find(line => line.startsWith('Edit only '))) - .toBe(`Edit only ${path.join(f.receipt.workspaceRoot, 'RESEARCH.md')}, ${path.join(f.receipt.workspaceRoot, leadPlanDeliveryFile(assignment)!)}.`); + .toBe(`Edit only ${path.join(f.receipt.workspaceRoot, 'RESEARCH.md')}, ${path.join(f.receipt.workspaceRoot, '.scratch/plan.json')}.`); expect(packets(context.message)).toHaveLength(1); expect(packets(context.message)[0].candidates[0]).toMatchObject({ name: 'Frozen.Arithmetic.add_comm', import: 'import Submission.Library.Arithmetic.Commutativity', check: '#check Frozen.Arithmetic.add_comm' }); diff --git a/tests/installedLibraryUsage.test.ts b/tests/installedLibraryUsage.test.ts deleted file mode 100644 index 913b8b25..00000000 --- a/tests/installedLibraryUsage.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { LIBRARY_PACK_SCHEMA } from '../src/math/libraryPacks'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { readInstalledLibrarySnapshot } from '../src/solver/installedLibraryContext'; -import { commitSolverSources, git, readSolverProblem } from '../src/solver/problem'; -import { taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { leadWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => undefined, resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -it('retains installed-only proof use in a cooperative delivery and its persisted state', async () => { - const directory = temporaryDirectory('installed-library-use-'), workspace = path.join(directory, 'workspace'); - const file = 'Submission/Library/Fixture/Facts.lean'; - const reference = { name: 'Frozen.fact', file }; - const source = 'namespace Current\ntheorem goal : True := by sorry\nend Current\n'; - const receipt = bootstrapLeanTask(workspace, { source, task: 'Prove the goal using the installed library.', libraryPack: { - schema: LIBRARY_PACK_SCHEMA, modules: [{ file, source: 'namespace Frozen\ntheorem fact : True := True.intro\nend Frozen\n', - origin: { kind: 'upstream', repository: 'offline-fixture', commit: 'a'.repeat(40), file: 'Facts.lean' } }], - } }); - const problem = readSolverProblem(workspace, receipt.activeProblemPath); - const authorWorktree = path.join(directory, 'author'); - git(workspace, ['worktree', 'add', '--quiet', '--detach', authorWorktree, problem.baseCommit]); - const workers = [leadWorker(problem, workspace), { ...leadWorker(problem, authorWorktree, 'author'), role: 'researcher' as const }]; - const task: CooperativeTask = { id: 'helper', kind: 'lemma', theoremName: 'Current.helper', proofPath: 'Submission.lean', - type: 'True', objective: 'Use the installed fact.', dependsOn: [], revision: 0 }; - const action: Extract = { kind: 'task', task, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: workers[1].id, - seedCommit: problem.baseCommit, assignmentId: 'installed-use', dependencies: [] } }; - const state = solverState(problem, workspace, { runId: 'installed-use', phase: 'running', cooperation: { - canonicalCommit: problem.baseCommit, - groups: [{ group: { id: 'main', objective: 'Prove the original.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [{ task, assignment: action.assignment, status: 'running', attempts: 1 }, { - task: { ...problem.targets[0], id: 'goal', kind: 'goal', objective: 'Prove the original.', revision: 0, - dependsOn: [], status: 'paused' }, status: 'pending', attempts: 0, - }], - } }); - const access = workerAccess(workers, directory); - for (const value of access.values()) value.installedLibrary = readInstalledLibrarySnapshot(problem, state.environmentDigest); - const events: { event: string; details?: Record }[] = []; - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verifiedBatch(request, { sessionId: 'installed-use', checks: true }); - return { ...batch, results: batch.results.map(result => ({ ...result, - declarationReferences: { statement: [], proof: result.theoremName === task.theoremName ? [reference] : [] } })) }; - }); - const cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, access, - emit: (event, details) => events.push({ event, details }) }); - try { - state.cooperation!.planVersion = (cooperative as any).planVersion(); - fs.writeFileSync(path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'), - 'import Submission.Library.Fixture.Facts\n' + source.replace('theorem goal', - 'theorem helper : True := by exact Frozen.fact\ntheorem goal')); - const commit = commitSolverSources(problem, workers[1].worktree); - - await cooperative.deliver(workers[1], action, commit); - - const delivery = state.cooperation!.deliveries?.find(delivery => delivery.kind === 'proof'); - expect(delivery).toMatchObject({ status: 'verified', taskId: task.id, knowledgeUses: [{ source: 'installed-library', - declaration: reference, attribution: 'host-observed-reference', status: 'checked-reference', - catalogDigest: access.get(workers[1].id)!.installedLibrary!.digest }] }); - expect(events.filter(item => item.event === 'knowledge_use_observed')).toHaveLength(1); - const saved = path.join(directory, 'state.json'); - writeSolverRunState(saved, state); - expect(readSolverRunState(saved).cooperation!.deliveries![0].knowledgeUses).toEqual(delivery!.knowledgeUses); - expect(state.knowledgeDigest).toBeUndefined(); - expect(host.createSession).not.toHaveBeenCalled(); - } finally { - await cooperative.stop(); - fs.rmSync(directory, { recursive: true, force: true }); - } -}); diff --git a/tests/knowledgeContext.test.ts b/tests/knowledgeContext.test.ts index a52c34e6..ac0fe246 100644 --- a/tests/knowledgeContext.test.ts +++ b/tests/knowledgeContext.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { mathDigest } from '../src/math/mathRuntimeIo'; import type { SolverRunState } from '../src/solver/archive'; import * as contextCompiler from '../src/solver/contextCompiler'; -import type { CooperationState } from '../src/solver/cooperation'; +import type { CooperationState } from '../src/solver/cooperationShared'; import { knowledgeContextConsumers, knowledgeContextSections, type KnowledgeContextSnapshot } from '../src/solver/knowledgeContext'; import { buildResearchContext, buildStatementReviewContext, type ContextAccess } from '../src/solver/modules/context'; import type { SolverProblem } from '../src/solver/problem'; diff --git a/tests/leadCheckpointHandoff.test.ts b/tests/leadCheckpointHandoff.test.ts deleted file mode 100644 index 091fdc3c..00000000 --- a/tests/leadCheckpointHandoff.test.ts +++ /dev/null @@ -1,384 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentActivity, MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { runResearchWorkers } from '../src/solver/research'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -const SLICE_MS = 10 * 60_000; -const WAIT_MS = 10 * 60_000; - -describe('Lead checkpoint waits for its required decision handoff', () => { - let directory: string; - let controller: AbortController; - let completion: Promise | undefined; - - beforeEach(() => { - vi.useFakeTimers(); - // Use explicit intake, avoiding an unrelated 200 ms cooperative poll in fake time. - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - }); - afterEach(async () => { - controller?.abort(new Error('fixture_complete')); - if (completion) await Promise.allSettled([completion]); - completion = undefined; - vi.useRealTimers(); vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - }); - - async function fixture(options: { pendingNotice?: boolean; noNotify?: boolean } = {}) { - let cooperation: CooperativeResearch | undefined; - const activate = CooperativeResearch.prototype.activate; - vi.spyOn(CooperativeResearch.prototype, 'activate').mockImplementation(function (this: CooperativeResearch, ...args) { - cooperation = this; - return activate.apply(this, args); - }); - const example = localExample('lead-checkpoint-handoff-', 'lead'); - directory = example.directory; - const { problem, workspace } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'researcher')]; - const question: CooperativeTask = { id: 'question', kind: 'research', objective: 'Find the missing bridge.', - status: 'paused', dependsOn: [], revision: 0 }; - const bridge: CooperativeTask = { id: 'bridge', kind: 'lemma', objective: 'Prove the smaller bridge.', - proofPath: 'Submission.lean', theoremName: 'Tutorial.bridge', type: 'True', dependsOn: [], revision: 0 }; - const plan = parseCooperationPlan(problem, { tasks: [question, ...problem.targets.map((target, index) => ({ - id: `goal_${index + 1}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, status: 'paused', - }))] }); - const state = solverState(problem, workspace, { runId: 'lead-checkpoint-handoff', phase: 'prepared', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: task.id === question.id ? 'completed' : 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })), - deliveries: [{ id: 'bridge-delivery', producer: workers[1].id, taskId: question.id, - taskDigest: taskVersion(question), kind: 'research', status: 'advisory', - summary: 'This typed bridge needs a Lead decision.', statement: '', premises: [], dependencies: [], - remainingObligations: [], evidenceRefs: [], createdAt: 1, lemmaRequests: [bridge] }] } }); - const started = deferred(), stopped = deferred(); - let activity: ((activity: MathAgentActivity) => void) | undefined; - let action: Extract | undefined; - const interrupt = vi.fn(async () => { stopped.resolve('interrupted'); }); - const notice = deferred(); - const notify = vi.fn(async (_message: string) => { if (options.pendingNotice) await notice.promise; }); - const omitNotify = options.noNotify; - const open = vi.fn(async (options: MathAgentOptions): Promise => ({ - threadId: 'offline-lead-handoff-thread', interrupt, ...(!omitNotify ? { notify } : {}), - close: async () => { stopped.resolve('closed'); }, - run: async (message, _messageId, _workspace, onStarted) => { - const assigned = JSON.parse(message) as CooperativeAction; - if (assigned.kind !== 'lead' || !assigned.planNonce || action) throw new Error('fixture_unexpected_assignment'); - action = assigned; activity = options.onActivity; - onStarted('offline-lead-handoff-turn'); - activity?.({ event: 'reasoning' }); started.resolve(); - return stopped.promise; - }, - })); - const check = vi.fn(async () => { throw new Error('fixture_unexpected_proof_acceptance'); }); - const modules: SolverModules = { ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M2: { ...directSolverModules.M2, check, checkTask: check }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Offline required-decision fixture.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }) } }; - const events: { event: string; details?: Record }[] = []; - controller = new AbortController(); - completion = runResearchWorkers({ state, workers, modules, access: workerAccess(workers, directory), - root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the frozen original targets.', - executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, - deadline: Infinity, maxTurnMs: Infinity, maxTurns: 1, maxTotalTokens: 0, goalProgressReviewMs: 24 * 3_600_000, - save: () => {}, emit: (event, details) => events.push({ event, details }) }); - void completion.catch(() => {}); - await Promise.race([started.promise, completion.then(() => { throw new Error('fixture_finished_before_lead'); })]); - expect(action).toBeDefined(); - const startCommand = () => activity!({ event: 'item_started', itemType: 'commandExecution' }); - const finishCommand = () => activity!({ event: 'item_completed', itemType: 'commandExecution' }); - const startCompaction = () => activity!({ event: 'item_started', itemType: 'contextCompaction' }); - const finishCompaction = () => activity!({ event: 'item_completed', itemType: 'contextCompaction' }); - const reasoning = () => activity!({ event: 'reasoning' }); - const command = (save?: () => void) => { startCommand(); save?.(); finishCommand(); }; - const write = (response: unknown) => fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), - '```math-plan\n' + JSON.stringify(response) + '\n```\n'); - const revision = (decide = true) => ({ baseVersion: action!.planVersion, upsert: [], ...(decide ? { - researchDecisions: [{ deliveryId: 'bridge-delivery', outcome: 'decline', - reason: 'The current exact consumer uses a different argument.' }], - } : {}) }); - const awaitSlice = async () => { - await vi.advanceTimersByTimeAsync(SLICE_MS - 30_000); - activity!({ event: 'reasoning' }); - await vi.advanceTimersByTimeAsync(30_000); - expect(notify.mock.calls.some(([message]) => message.includes('bridge-delivery'))).toBe(true); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_awaiting_request', - details: expect.objectContaining({ workerId: 'solver', maxWaitMs: WAIT_MS }) }); - expect(interrupt).not.toHaveBeenCalled(); - }; - return { state, events, interrupt, check, command, startCommand, finishCommand, write, revision, awaitSlice, - startCompaction, finishCompaction, reasoning, - pulse: () => cooperation!.pulse(workers[0].id), action: action!, workspace, notice, notify }; - } - - it('keeps the turn open when the first successful command only reads the inherited plan', async () => { - const f = await fixture(); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(113_000); - f.command(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).not.toHaveBeenCalled(); - expect(f.events.some(event => event.event === 'cooperative_checkpoint_request_settled')).toBe(false); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('waits through an incomplete saved draft and stops after a complete decision is saved', async () => { - const f = await fixture(); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(60_000); - f.command(() => f.write(f.revision(false))); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).not.toHaveBeenCalled(); - expect(f.notify.mock.calls.map(([message]) => message)).toContainEqual( - expect.stringContaining('math_plan_research_decisions_missing')); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - await vi.advanceTimersByTimeAsync(30_000); - f.command(() => f.write(f.revision())); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'request-returned', waitedMs: 90_000 }) }); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('continues only until the original wait deadline when no valid decision is saved', async () => { - const f = await fixture(); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(WAIT_MS / 2); - f.command(); - await vi.advanceTimersByTimeAsync(WAIT_MS / 2 - 1); - expect(f.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'wait-limit', waitedMs: WAIT_MS }) }); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('waits for the writing tool to finish even when its valid draft is already visible', async () => { - const f = await fixture(); await f.awaitSlice(); - f.command(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).not.toHaveBeenCalled(); - f.startCommand(); f.write(f.revision()); - await vi.advanceTimersByTimeAsync(30_000); - expect(f.interrupt).not.toHaveBeenCalled(); - f.finishCommand(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'request-returned', waitedMs: 30_000 }) }); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('waits when a tool has saved a complete decision before the slice but has not returned', async () => { - const f = await fixture(); - await vi.advanceTimersByTimeAsync(SLICE_MS - 30_000); - f.startCommand(); f.write(f.revision()); - await vi.advanceTimersByTimeAsync(30_000); - expect(f.interrupt).not.toHaveBeenCalled(); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - await vi.advanceTimersByTimeAsync(30_000); - expect(f.interrupt).not.toHaveBeenCalled(); - f.finishCommand(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'request-returned', waitedMs: 30_000 }) }); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('keeps the original wait window after a queued notice arrives before the next model output', async () => { - const f = await fixture({ pendingNotice: true }); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(3 * 60_000); - f.command(); // This request boundary can deliver the queued notice, but no decision exists. - f.notice.resolve(); await vi.advanceTimersByTimeAsync(30_000); - // An acknowledged steer is not a model response; provider latency must not consume the handoff. - expect(f.interrupt).not.toHaveBeenCalled(); - expect(f.events.some(event => event.event === 'cooperative_checkpoint_request_settled')).toBe(false); - await vi.advanceTimersByTimeAsync(30_000); - f.command(() => f.write(f.revision())); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'request-returned', waitedMs: 4 * 60_000 }) }); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('keeps the ordinary scheduling checkpoint when notifications are unavailable', async () => { - const f = await fixture({ noNotify: true }); - await vi.advanceTimersByTimeAsync(SLICE_MS - 30_000); - f.startCommand(); f.finishCommand(); - await vi.advanceTimersByTimeAsync(30_000); - f.command(); - await vi.advanceTimersByTimeAsync(0); - expect(f.notify).not.toHaveBeenCalled(); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events.some(event => event.event === 'lead_handoff_requested')).toBe(false); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('ends the bounded wait when a queued notification fails', async () => { - const f = await fixture({ pendingNotice: true }); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(3 * 60_000); - f.notice.reject(new Error('fixture_notice_rejected')); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'notice-failed', waitedMs: 3 * 60_000 }) }); - expect(f.events.some(event => event.event === 'lead_handoff_requested')).toBe(false); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('does not keep waiting after this dispatch has published a valid decision', async () => { - const f = await fixture(); await f.awaitSlice(); - fs.appendFileSync(path.join(f.workspace, leadPlanDeliveryFile(f.action)!), JSON.stringify({ - kind: 'plan', dispatchNonce: f.action.planNonce, ...f.revision(), - }) + '\n'); - await f.pulse(); - expect(f.state.cooperation!.planPublication).toMatchObject({ nonce: f.action.planNonce }); - expect(f.state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'bridge-delivery', outcome: 'decline' })); - f.command(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.check).not.toHaveBeenCalled(); - }); - - it.each(['during-compaction', 'at-recovery'] as const)( - 'preserves the required Lead handoff when the queued notice arrives %s', async delivery => { - const f = await fixture({ pendingNotice: true }); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(34_000); - f.startCompaction(); - await vi.advanceTimersByTimeAsync(5 * 60_000 - 9); - expect(f.interrupt).not.toHaveBeenCalled(); - if (delivery === 'during-compaction') { f.notice.resolve(); await vi.advanceTimersByTimeAsync(0); } - await vi.advanceTimersByTimeAsync(9); - f.finishCompaction(); - if (delivery === 'at-recovery') f.notice.resolve(); - // No reasoning or tool output has arrived since before the wait started. A delivered - // reminder and a completed compaction do not complete the dispatch's required decision. - await vi.advanceTimersByTimeAsync(13); - expect(f.interrupt).not.toHaveBeenCalled(); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - expect(f.events.some(event => event.event === 'cooperative_checkpoint_request_settled')).toBe(false); - f.startCommand(); f.write(f.revision()); - await vi.advanceTimersByTimeAsync(30_000); - expect(f.interrupt).not.toHaveBeenCalled(); - f.finishCommand(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'request-returned', waitedMs: 364_013 }) }); - expect(f.events.filter(event => event.event === 'cooperative_checkpoint_awaiting_request')).toHaveLength(1); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('keeps the original wait deadline after compaction resumes without a saved required decision', async () => { - const f = await fixture({ pendingNotice: true }); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(34_000); - f.startCompaction(); - await vi.advanceTimersByTimeAsync(5 * 60_000); - f.notice.resolve(); await vi.advanceTimersByTimeAsync(0); - f.finishCompaction(); - await vi.advanceTimersByTimeAsync(13); - expect(f.interrupt).not.toHaveBeenCalled(); - // The five minutes spent compacting still count against this one existing wait window. - await vi.advanceTimersByTimeAsync(WAIT_MS - 334_013 - 1); - expect(f.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'wait-limit', waitedMs: WAIT_MS }) }); - expect(f.events.filter(event => event.event === 'cooperative_checkpoint_awaiting_request')).toHaveLength(1); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('checkpoints on recovery when compaction has crossed the original wait deadline', async () => { - const f = await fixture({ pendingNotice: true }); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(34_000); - f.startCompaction(); - await vi.advanceTimersByTimeAsync(60_000); - f.notice.resolve(); await vi.advanceTimersByTimeAsync(0); - await vi.advanceTimersByTimeAsync(WAIT_MS - 94_000 + 1); - expect(f.interrupt).not.toHaveBeenCalled(); - f.finishCompaction(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ workerId: 'solver', boundary: 'wait-limit', waitedMs: WAIT_MS + 1 }) }); - expect(f.events.filter(event => event.event === 'cooperative_checkpoint_awaiting_request')).toHaveLength(1); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('preserves notification failure as a checkpoint boundary after compaction', async () => { - const f = await fixture({ pendingNotice: true }); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(34_000); - f.startCompaction(); - await vi.advanceTimersByTimeAsync(60_000); - f.notice.reject(new Error('fixture_notice_rejected')); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(4 * 60_000); - f.finishCompaction(); - await vi.advanceTimersByTimeAsync(13); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events.filter(event => event.event === 'cooperative_checkpoint_notice_failed')).toHaveLength(1); - expect(f.events.some(event => event.event === 'lead_handoff_requested')).toBe(false); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('keeps the ordinary checkpoint on compaction recovery when notifications are unavailable', async () => { - const f = await fixture({ noNotify: true }); - await vi.advanceTimersByTimeAsync(SLICE_MS - 30_000); f.reasoning(); - await vi.advanceTimersByTimeAsync(30_000); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_awaiting_request', - details: expect.objectContaining({ workerId: 'solver', maxWaitMs: WAIT_MS }) }); - await vi.advanceTimersByTimeAsync(34_000); - f.startCompaction(); - await vi.advanceTimersByTimeAsync(5 * 60_000); - f.finishCompaction(); - await vi.advanceTimersByTimeAsync(13); - expect(f.interrupt).not.toHaveBeenCalled(); - f.command(); - await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.notify).not.toHaveBeenCalled(); - expect(f.events.some(event => event.event === 'lead_handoff_requested')).toBe(false); - expect(f.state.cooperation!.researchDecisions).toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); - }); - - it('does not reopen a required handoff after a valid decision was published during compaction', async () => { - const f = await fixture({ pendingNotice: true }); await f.awaitSlice(); - await vi.advanceTimersByTimeAsync(34_000); - f.startCompaction(); - await vi.advanceTimersByTimeAsync(5 * 60_000); - fs.appendFileSync(path.join(f.workspace, leadPlanDeliveryFile(f.action)!), JSON.stringify({ - kind: 'plan', dispatchNonce: f.action.planNonce, ...f.revision(), - }) + '\n'); - await f.pulse(); - expect(f.state.cooperation!.planPublication).toMatchObject({ nonce: f.action.planNonce }); - expect(f.state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'bridge-delivery', outcome: 'decline' })); - f.notice.resolve(); await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).not.toHaveBeenCalled(); - f.finishCompaction(); - await vi.advanceTimersByTimeAsync(13); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events.some(event => event.event === 'lead_handoff_requested')).toBe(false); - expect(f.check).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/leadPlanRejectionFeedback.test.ts b/tests/leadPlanRejectionFeedback.test.ts index c01810ea..35e531c7 100644 --- a/tests/leadPlanRejectionFeedback.test.ts +++ b/tests/leadPlanRejectionFeedback.test.ts @@ -2,11 +2,10 @@ import fs from 'node:fs'; import path from 'node:path'; import { expect, it, vi } from 'vitest'; import type { SolverRunState } from '../src/solver/archive'; -import type { CooperationState } from '../src/solver/cooperation'; +import type { CooperationState } from '../src/solver/cooperationShared'; import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; import { parseCooperationPlan, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; const formal = 'theorem target : True := by sorry'; @@ -94,48 +93,3 @@ it.each(['task', 'review'] as const)('keeps Lead plan errors out of %s dispatche expect(dispatch.manifest.included.some(section => section.id === 'plan-rejection')).toBe(false); } }); - -it('updates only the Lead inbox on plan rejection and clears it when a repaired plan is accepted', async () => { - const example = localExample('solver-plan-rejection-feedback-', 'lead'); - const lead = leadWorker(example.problem, example.workspace); - const peer = peerWorker(example, 'engineer', { role: 'engineer' }); - const plan = parseCooperationPlan(example.problem, { tasks: example.problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, - })) }); - const state = solverState(example.problem, example.workspace, { runId: 'rejection-feedback', phase: 'running', - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })), error: 'fixture_request_new_plan' } }); - const controller = new AbortController(); - const cooperative = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: example.directory, - signal: controller.signal }); - const inbox = (worktree: string) => JSON.parse(fs.readFileSync(path.join(worktree, 'COOPERATION.json'), 'utf8')); - const deliver = async (value: unknown) => { - const action = await cooperative.next(lead, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead'); - expect(cooperative.started(lead, action)).toBe(true); - cooperative.activate(lead, action, vi.fn(async () => {}), async () => {}); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(value) + '\n```'); - cooperative.deactivate(lead); - await cooperative.deliver(lead, action, commitSolverSources(example.problem, lead.worktree)); - }; - try { - await deliver({ tasks: [] }); - expect(state.cooperation!.error).toBe('math_plan_invalid'); - expect(state.cooperation!.planRejection).toMatchObject({ issues: [{ path: 'tasks', - message: 'Supply a nonempty array of task objects.' }] }); - expect(inbox(lead.worktree)).toMatchObject({ error: state.cooperation!.error, planRejection: state.cooperation!.planRejection }); - expect(inbox(peer.worktree)).not.toHaveProperty('error'); - expect(inbox(peer.worktree)).not.toHaveProperty('planRejection'); - await deliver({ tasks: plan.tasks, groups: plan.groups }); - expect(state.cooperation!.error).toBeUndefined(); - expect(state.cooperation!.planRejection).toBeUndefined(); - expect(inbox(lead.worktree)).not.toHaveProperty('error'); - expect(inbox(lead.worktree)).not.toHaveProperty('planRejection'); - expect(inbox(peer.worktree)).not.toHaveProperty('error'); - expect(inbox(peer.worktree)).not.toHaveProperty('planRejection'); - } finally { - controller.abort(); - await cooperative.stop(); - fs.rmSync(example.directory, { recursive: true, force: true }); - } -}); diff --git a/tests/libraryApplication.test.ts b/tests/libraryApplication.test.ts index ffdee690..5e75b222 100644 --- a/tests/libraryApplication.test.ts +++ b/tests/libraryApplication.test.ts @@ -6,16 +6,16 @@ import { bootstrapLeanTask } from '../src/math/leanTask'; import { LIBRARY_PACK_SCHEMA } from '../src/math/libraryPacks'; import { leanReferenceCommands, parseLeanReferenceReport } from '../src/math/leanReferences'; import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { parseCooperationPlan } from '../src/solver/cooperation'; +import { parseCooperationPlan } from '../src/solver/tasks'; import { checkTaskProof } from '../src/solver/cooperativeProof'; import { readInstalledLibrarySnapshot } from '../src/solver/installedLibraryContext'; import * as installedLibraryContext from '../src/solver/installedLibraryContext'; import { applyOriginalLibraryTasks, prepareLibraryApplication } from '../src/solver/libraryApplication'; import { directSolverModules } from '../src/solver/modules'; import { committedSource, git, readSolverProblem, withSolverWorktree } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { runResearchLead } from '../src/solver/research'; import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; +import { workerAccess } from './helpers/solver'; import { temporaryDirectory } from './helpers/files'; import { newestLeanBinary } from './helpers/lean'; import { leadWorker, solverState } from './helpers/solver'; @@ -564,14 +564,14 @@ describe('host applications of installed theorems', () => { it('resumes a saved single-worker library proof through whole-problem acceptance without a model', async () => { const f = fixture(), worker = leadWorker(f.problem, f.worktree); const state = solverState(f.problem, f.worktree, { runId: 'library-resume', phase: 'running', environmentDigest }); - const access = workerAccess([worker], f.root); - access.get(worker.id)!.installedLibrary = f.library; + const access = workerAccess([worker], f.root).get(worker.id)!; + access.installedLibrary = f.library; const interrupted = new AbortController(); let saved: typeof state | undefined; - const input = { state, workers: [worker], access, modules: directSolverModules, + const input = { state, access, modules: directSolverModules, root: f.root, buildFile: 'unused', taskText: 'Prove the target.', executable: 'unused', profile: 'unused', deadline: Infinity, maxTurns: 0, maxTurnMs: Infinity, maxTotalTokens: 0, emit: vi.fn() }; - const interruption = await runResearchWorkers({ ...input, signal: interrupted.signal, save: () => { + const interruption = await runResearchLead({ ...input, signal: interrupted.signal, save: () => { if (!saved && state.phase === 'checking' && !state.check?.passed) { saved = JSON.parse(JSON.stringify(state)); interrupted.abort(); @@ -580,7 +580,7 @@ describe('host applications of installed theorems', () => { expect(interrupted.signal.aborted, String(interruption)).toBe(true); expect(saved).toMatchObject({ phase: 'checking', turns: 0 }); expect(read(f)).not.toContain('by sorry'); - const winner = await runResearchWorkers({ ...input, state: saved!, + const winner = await runResearchLead({ ...input, state: saved!, signal: new AbortController().signal, save: vi.fn() }); expect(winner?.check.passed).toBe(true); expect(saved!.turns).toBe(0); @@ -603,72 +603,4 @@ describe('host applications of installed theorems', () => { ...(outcome === 'rejected' ? { passed: false, usedDeclarations: [] } : { checkError: expect.any(String) }) })); }); - it('keeps a rejected library probe diagnostic out of the original task feedback', async () => { - const f = fixture(), peer = path.join(f.root, 'proof'); - git(f.worktree, ['worktree', 'add', '--quiet', '--detach', peer, f.seedCommit]); - const workers = [leadWorker(f.problem, f.worktree), { ...leadWorker(f.problem, peer, 'proof'), role: 'researcher' as const }]; - const plan = parseCooperationPlan(f.problem, { tasks: [{ ...f.task, ownerId: 'proof' }], - groups: [{ id: 'main', objective: 'Prove the goal', status: 'active', maxConcurrent: 1 }] }); - const originalFeedback = 'Original target diagnostic: preserve the closed-ideal hypotheses.'; - const state = solverState(f.problem, f.worktree, { runId: 'library-probe-rejected', phase: 'running', environmentDigest, - cooperation: { canonicalCommit: f.seedCommit, tasks: plan.tasks.map(task => - ({ task, status: 'pending', attempts: 0, feedback: originalFeedback })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const access = workerAccess(workers, f.root); - for (const worker of access.values()) worker.installedLibrary = f.library; - const probeDiagnostic = 'Type mismatch: Probability.sum_biasedWeight does not prove the closed-ideal goal.'; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => - failedBatch(verifiedBatch(request, { sessionId: 'library-probe-rejected', checks: true }), { - stdoutPreview: () => probeDiagnostic, - })); - const emit = vi.fn(), cooperative = cooperativeResearch({ state, workers, access, retrievalRoot: f.root, emit, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: host.model, execute: host.model } } }); - try { - expect(await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity })) - .toMatchObject({ kind: 'task', task: { id: f.task.id } }); - const node = state.cooperation!.tasks.find(node => node.task.id === f.task.id)!; - expect(node.feedback).toContain(originalFeedback); - expect(node.feedback).toContain('Host library application attempt (advisory)'); - expect(node.feedback).not.toContain(probeDiagnostic); - expect(node.feedback).not.toContain('Type mismatch'); - expect(emit).toHaveBeenCalledWith('task_library_application', expect.objectContaining({ passed: false, - diagnostic: expect.stringContaining(probeDiagnostic), receiptIds: expect.any(Array) })); - expect(host.model).not.toHaveBeenCalled(); - } finally { await cooperative.stop(); } - }); - - it.each(['goal', 'lemma'] as const)('integrates a library-closed %s through normal cooperative acceptance without a model', async kind => { - const f = fixture(), peer = path.join(f.root, 'proof'); - git(f.worktree, ['worktree', 'add', '--quiet', '--detach', peer, f.seedCommit]); - const workers = [leadWorker(f.problem, f.worktree), { ...leadWorker(f.problem, peer, 'proof'), role: 'researcher' as const }]; - const task: CooperativeTask = kind === 'goal' ? f.task : { ...f.task, id: 'helper', kind, theoremName: 'Current.helper', - type: 'forall (n : Nat), n + 0 = n' }; - const plan = parseCooperationPlan(f.problem, { tasks: [ - { ...task, ownerId: 'proof' }, - { id: 'followup', kind: 'research', objective: 'Observe checked dependency', ownerId: 'proof', dependsOn: [task.id] }, - ...(kind === 'lemma' ? [{ ...f.task, status: 'paused' }] : []), - ], groups: [{ id: 'main', objective: 'Prove the goal', status: 'active', maxConcurrent: 1 }] }); - const state = solverState(f.problem, f.worktree, { runId: 'library-application', phase: 'running', environmentDigest, - cooperation: { canonicalCommit: f.seedCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const access = workerAccess(workers, f.root); - for (const worker of access.values()) worker.installedLibrary = f.library; - const emit = vi.fn(), applyLibrary = vi.fn(prepareLibraryApplication), taskText = 'Use Frozen.add_zero.'; - const cooperative = cooperativeResearch({ state, workers, access, retrievalRoot: f.root, emit, taskText, - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, applyLibrary }, - M1: { ...directSolverModules.M1, open: host.model, execute: host.model } } }); - try { - expect(await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity })) - .toMatchObject({ kind: 'task', task: { id: 'followup' } }); - const node = state.cooperation!.tasks.find(node => node.task.id === task.id)!; - expect(node).toMatchObject({ status: 'integrated', attempts: 0, integratedCheck: { passed: true, taskDigest: taskVersion(node.task) } }); - expect(read(f, state.cooperation!.canonicalCommit)).toContain('exact _root_.Frozen.add_zero'); - expect(state.cooperation!.deliveries!.find(delivery => delivery.taskId === task.id)).toMatchObject({ - knowledgeUses: [expect.objectContaining({ source: 'installed-library', status: 'checked-reference', declaration: reference })] }); - expect(emit).toHaveBeenCalledWith('task_library_application', expect.objectContaining({ passed: true, usedDeclarations: [reference] })); - expect(applyLibrary).toHaveBeenCalledWith(expect.objectContaining({ taskText })); - expect(state.turns).toBe(0); - expect(host.model).not.toHaveBeenCalled(); - } finally { await cooperative.stop(); } - }); }); diff --git a/tests/nativeDelegation.test.ts b/tests/nativeDelegation.test.ts deleted file mode 100644 index fc717136..00000000 --- a/tests/nativeDelegation.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createCodexMathSession, type MathAgentSession } from '../src/runtime/codexSession'; -import { readMathAgentSkill } from '../src/runtime/codexSkills'; -import type { ModelRequestGate } from '../src/runtime/modelRequest'; -import type { NativeResearchAgent } from '../src/runtime/nativeDelegation'; - -const relay = vi.hoisted(() => ({ close: vi.fn(async () => {}), gate: undefined as ModelRequestGate | undefined })); -vi.mock('../src/runtime/formalizationRelay', () => ({ startFormalizationRelay: async (options: { requestGate?: ModelRequestGate }) => { - relay.gate = options.requestGate; return ({ - close: relay.close, baseUrl: 'http://127.0.0.1:1/v1', apiKey: 'disposable-fixture-only', -}); } })); - -const peer = String.raw` -const fs=require('node:fs'),path=require('node:path'),readline=require('node:readline'); -const send=value=>process.stdout.write(JSON.stringify(value)+'\n'); -let child=0,parentTurn,callback=100; -const finish=(status='completed')=>{ - send({method:'item/completed',params:{threadId:'parent',turnId:parentTurn,item:{type:'agentMessage',id:'response',text:'Saved research.'}}}); - send({method:'turn/completed',params:{threadId:'parent',turn:{id:parentTurn,status}}}); -}; -readline.createInterface({input:process.stdin}).on('line',line=>{ - const c=JSON.parse(line),p=c.params||{},reply=result=>send({id:c.id,result}); - fs.appendFileSync(process.env.TRACE,JSON.stringify(c)+'\n'); - if(c.method==='initialize')return reply({}); - if(c.method==='skills/list')return reply({data:[{cwd:p.cwds[0],errors:[],skills:[{name:'fixture',enabled:true,path:process.env.SKILL}]}]}); - if(!c.method){ - if(c.id===100){ - if(process.env.MODE==='duplicate') {callback=101;return send({id:101,method:'item/tool/call',params:{threadId:'parent',turnId:parentTurn,callId:'investigate',namespace:null,tool:'theoremos_investigate',arguments:{questions:['Read local sources.','Check a bounded argument.']}}});} - return finish(); - } - if(c.id===101)return finish(); - } - if(c.method==='thread/start'||c.method==='thread/resume'){ - const turns=c.method==='thread/resume'&&process.env.MODE==='long-resume'&&!p.excludeTurns - ? [{id:'saved-turn',items:[{type:'agentMessage',text:'x'.repeat(8*1024*1024)}]}] : []; - return reply({thread:{id:p.permissions==='math-investigator'?'child-'+(++child):'parent',turns},model:'fixture-model',reasoningEffort:'high',modelProvider:'sub2api',approvalPolicy:'never',activePermissionProfile:{id:p.permissions==='math-investigator'?(process.env.MODE==='wrong-permission'?'math-worker':'math-investigator'):'math-worker'}}); - } - if(c.method==='thread/archive')return process.env.MODE==='archive-error'?send({id:c.id,error:{code:-32603}}):reply({}); - if(c.method==='turn/interrupt'){reply({});return finish('interrupted');} - if(c.method==='turn/start'){ - const turn=p.clientUserMessageId;reply({turn:{id:turn}}); - if(p.threadId!=='parent'){ - fs.writeFileSync(process.env.CHILD_READY,p.threadId); - if(process.env.MODE==='waiting')return; - send({method:'thread/tokenUsage/updated',params:{threadId:p.threadId,turnId:turn,tokenUsage:{total:{totalTokens:7}}}}); - send({method:'item/completed',params:{threadId:p.threadId,turnId:turn,item:{type:'agentMessage',id:'response',text:'Advisory '+p.threadId}}}); - return send({method:'turn/completed',params:{threadId:p.threadId,turn:{id:turn,status:'completed'}}}); - } - parentTurn=turn; - if(p.input[0].text==='delegate'){ - send({id:100,method:'item/tool/call',params:{threadId:'parent',turnId:turn,callId:'investigate',namespace:null,tool:'theoremos_investigate',arguments:{questions:['Read local sources.','Check a bounded argument.']}}}); - if(process.env.MODE==='parent-early')finish(); - return; - } - return finish(); - } - if(c.method==='thread/compact/start'){ - reply({}); - const turnId = 'compact-turn'; - const notify = (method, params) => send({ method, params: { threadId: 'parent', ...params } }); - const release = path.join(path.dirname(process.env.TRACE), 'compact-release'); - const timer = setInterval(() => { - if (!fs.existsSync(release)) return; - clearInterval(timer); - notify('turn/completed', { turn: { id: turnId, status: fs.readFileSync(release, 'utf8') } }); - }, 5); - notify('turn/started', { turn: { id: turnId, status: 'inProgress' } }); - notify('turn/completed', { turn: { id: 'older-turn', status: 'failed' } }); - notify('thread/compacted', {}); - notify('item/completed', { - turnId: process.env.MODE === 'wrong-summary' ? 'older-turn' : turnId, - item: { type: 'contextCompaction', id: 'compacted' }, - }); - } -});`; - -describe('native delegation availability and compaction', () => { - let root: string, profile: string, executable: string, skill: ReturnType; - let session: MathAgentSession | undefined; - beforeEach(() => { - root=fs.mkdtempSync(path.join(os.tmpdir(),'native-investigation-test-')); - profile=path.join(root,'profile');fs.mkdirSync(profile); - fs.writeFileSync(path.join(profile,'config.toml'),'model_provider="sub2api"\n[model_providers.sub2api]\nbase_url="http://127.0.0.1:1/v1"\nwire_api="responses"\n'); - const directory=path.join(root,'.agents/skills/fixture');fs.mkdirSync(directory,{recursive:true}); - fs.writeFileSync(path.join(directory,'SKILL.md'),'---\nname: fixture\ndescription: Fixed research methods.\n---\nRead the original question.\n'); - skill=readMathAgentSkill(path.join(directory,'SKILL.md')); - executable=path.join(root,'peer');fs.writeFileSync(executable,'#!'+process.execPath+'\n'+peer,{mode:0o700}); - relay.close.mockClear(); - }); - afterEach(async()=>{await session?.close();session=undefined;fs.rmSync(root,{recursive:true,force:true});}); - const options=()=>({executable,profile,workspace:root,model:'fixture-model',effort:'high',skills:[skill], - instructions:'Fixed problem.',onUsage:vi.fn(),requestGate:()=>({allowed:true as const,settle:()=>{}}), - environment:{PATH:process.env.PATH,SKILL:skill.path,TRACE:path.join(root,'trace'),CHILD_READY:path.join(root,'child-ready')}}); - - const trace=()=>fs.readFileSync(path.join(root,'trace'),'utf8').trim().split('\n').map(line=>JSON.parse(line)); - const delegated=(mode='normal',onNativeAgent=(agent:NativeResearchAgent)=>{})=>({...options(),delegation:{mode:'read-only' as const,maxAgents:3}, - onNativeAgent,environment:{...options().environment,MODE:mode}}); - - it('dispatches independent named read-only threads through one native tool and archives before returning',async()=>{ - const observations:NativeResearchAgent[]=[]; - const configured=delegated('normal',agent=>observations.push(agent)); - session=await createCodexMathSession(configured); - expect(await session.run('delegate','one',root,()=>{})).toBe('completed'); - const calls=trace(),start=calls.find(c=>c.method==='thread/start'); - expect(calls.find(c=>c.method==='initialize').params.capabilities).toEqual({experimentalApi:true}); - expect(start.params.dynamicTools[0].name).toBe('theoremos_investigate'); - expect(start.params.config['agents.enabled']).toBe(false); - const children=calls.filter(c=>c.method==='thread/start'&&c.params.permissions==='math-investigator'); - expect(children).toHaveLength(2); - expect(children.every(c=>!c.params.dynamicTools&&!c.params.sandbox)).toBe(true); - expect(children[0].params.config['permissions.math-investigator.filesystem'][root]).toBe('read'); - expect(children[0].params.config['permissions.math-investigator.network.enabled']).toBe(false); - expect(calls.filter(c=>c.method==='thread/archive')).toHaveLength(2); - const returned=calls.find(c=>c.id===100&&!c.method); - expect(returned.result.success).toBe(true); - expect(JSON.parse(returned.result.contentItems[0].text)).toMatchObject({dispatch:'host-mediated-native-threads',advisory:true}); - expect(observations.some(agent=>agent.status==='completed'&&agent.stoppedAt&&agent.usage?.totalTokens===7)).toBe(true); - expect(configured.onUsage).not.toHaveBeenCalled(); - expect(await session.stopForFreeze!()).toEqual({status:'stopped'}); - }); - - it('does not execute a duplicate native call twice',async()=>{ - session=await createCodexMathSession(delegated('duplicate')); - expect(await session.run('delegate','one',root,()=>{})).toBe('completed'); - expect(trace().filter(c=>c.method==='thread/start'&&c.params.permissions==='math-investigator')).toHaveLength(2); - }); - - it.each(['wrong-permission','archive-error'])('stops the whole tree after %s instead of returning unsafe evidence',async mode=>{ - session=await createCodexMathSession(delegated(mode)); - await expect(session.run('delegate','one',root,()=>{})).rejects.toThrow(/math_native_investigation|math_codex_transport/u); - if(mode==='wrong-permission')expect(trace().filter(c=>c.method==='turn/start'&&c.params.threadId!=='parent')).toHaveLength(0); - expect(await session.stopForFreeze!()).toEqual({status:'stopped'}); - }); - - it('cancels active investigators and confirms the entire owned process group stopped',async()=>{ - const observations:NativeResearchAgent[]=[]; - session=await createCodexMathSession(delegated('waiting',agent=>observations.push(agent))); - const running=session.run('delegate','one',root,()=>{});void running.catch(()=>{}); - await vi.waitFor(()=>expect(fs.existsSync(path.join(root,'child-ready'))).toBe(true)); - const identity={requestId:'child-request',threadId:fs.readFileSync(path.join(root,'child-ready'),'utf8')}; - expect(relay.gate!(identity)).toMatchObject({allowed:true}); - expect(await session.stopForFreeze!()).toEqual({status:'unconfirmed',reason:'turn-not-settled'}); - await session.interrupt(); - await expect(running).rejects.toThrow(/math_codex_transport/u); - expect(await session.stopForFreeze!()).toEqual({status:'stopped'}); - expect(observations.filter(agent=>agent.stoppedAt).length).toBeGreaterThanOrEqual(2); - expect(relay.gate!(identity)).toMatchObject({allowed:false}); - }); - - it('restores the persisted native tool on resume without creating replacement tools or children',async()=>{ - session=await createCodexMathSession({...delegated(),threadId:'parent'}); - expect(await session.run('delegate','one',root,()=>{})).toBe('completed'); - const resume=trace().find(c=>c.method==='thread/resume'); - expect(resume.params.dynamicTools).toBeUndefined(); - expect(trace().filter(c=>c.method==='thread/start'&&c.params.permissions==='math-investigator')).toHaveLength(2); - }); - - it('resumes a regular metered thread whose history exceeds the stdio frame limit', async () => { - session = await createCodexMathSession({ ...options(), threadId: 'parent', - environment: { ...options().environment, MODE: 'long-resume' } }); - expect(session.usageSource).toBe('upstream-requests'); - expect(await session.run('Continue the saved research.', 'next', root, () => {})).toBe('completed'); - }); - - it('preserves a configured checkpoint result while stopping active child threads',async()=>{ - session=await createCodexMathSession({...delegated('waiting'),turnTimeoutMs:75}); - expect(await session.run('delegate','one',root,()=>{})).toBe('checkpoint'); - expect(await session.stopForFreeze!()).toEqual({status:'stopped'}); - }); - - it('rejects delegation when no metered provider gate exists',async()=>{ - await expect(createCodexMathSession({...options(),requestGate:undefined,delegation:{mode:'read-only',maxAgents:2}})) - .rejects.toThrow('math_native_delegation_requires_skill_and_metered_relay'); - expect(fs.existsSync(path.join(root,'trace'))).toBe(false); - }); - - it.each([ - ['matching-summary','completed',undefined], - ['matching-summary','failed','math_codex_compaction_failed'], - ['wrong-summary','completed','math_codex_compaction_missing_summary'], - ])('settles ordinary compaction using the matching terminal turn (%s, %s)', async (mode, status, error) => { - const onItem = vi.fn(); - session = await createCodexMathSession({ ...options(), onItem, environment: { ...options().environment, MODE: mode } }); - expect(await session.run('Initial research.', 'one', root, () => {})).toBe('completed'); - const compact = session.compact!(); - void compact.catch(() => {}); - try { - await vi.waitFor(() => expect(onItem).toHaveBeenCalledWith('completed', - expect.objectContaining({ type: 'contextCompaction' }), expect.anything())); - await expect(session.run('Overlapping.', 'overlap', root, () => {})).rejects.toThrow('math_codex_turn_already_running'); - } finally { - fs.writeFileSync(path.join(root, 'compact-release'), status); - } - if (error) await expect(compact).rejects.toThrow(error); - else { - await compact; - expect(session.threadId).toBe('parent'); - expect(await session.run('Continue from preserved sources.', 'two', root, () => {})).toBe('completed'); - } - }); - -}); diff --git a/tests/nativeInvestigations.test.ts b/tests/nativeInvestigations.test.ts deleted file mode 100644 index dfdc0874..00000000 --- a/tests/nativeInvestigations.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { NativeInvestigations, type NativeResearchAgent } from '../src/runtime/nativeDelegation'; - -function fixture(maxAgents = 3) { - const agents: NativeResearchAgent[] = []; - let next = 0; - const request = vi.fn(async (method: string, params: Record): Promise> => { - if (method === 'thread/start') return { thread: { id: `child-${++next}` }, model: 'fixture', - reasoningEffort: 'high', approvalPolicy: 'never', activePermissionProfile: { id: 'math-investigator' } }; - if (method === 'turn/start') return { turn: { id: params.threadId + '-turn' } }; - return {}; - }); - const fail = vi.fn(); - const controller = new NativeInvestigations({ maxAgents, parentThreadId: 'parent', workspace: '/workspace', model: 'fixture', - effort: 'high', settings: { developerInstructions: 'Fixed original problem.' }, request, - active: turnId => turnId === 'parent-turn', changed: agent => agents.push(agent), activity: vi.fn(), fail }); - const call = (changes: Record = {}) => controller.call({ threadId: 'parent', turnId: 'parent-turn', - callId: 'call-1', namespace: null, tool: 'theoremos_investigate', arguments: { questions: ['Bounded question.'] }, ...changes }); - return { controller, request, call, agents, fail }; -} - -describe('bounded native investigation tool', () => { - it.each([ - { threadId: 'another-thread' }, { turnId: 'old-turn' }, { namespace: 'other' }, - { arguments: { questions: [] } }, { arguments: { questions: ['a', 'b', 'c'] } }, - { arguments: { questions: ['a'], executable: '/host/command' } }, - ])('rejects foreign or invalid requests before native dispatch: %j', async changes => { - const f = fixture(); - expect(await f.call(changes)).toMatchObject({ success: false }); - expect(f.request).not.toHaveBeenCalled(); - }); - - it('reserves capacity atomically, keeps call identity, and only releases after native archive', async () => { - const f = fixture(2); - const first = f.call(); - await vi.waitFor(() => expect(f.request).toHaveBeenCalledWith('turn/start', expect.anything())); - expect(await f.call({ callId: 'call-2' })).toMatchObject({ success: false }); - expect(await f.call({ arguments: { questions: ['Changed question.'] } })).toMatchObject({ success: false }); - expect(f.controller.busy).toBe(true); - f.controller.observe('turn/completed', { threadId: 'unrelated', turn: { id: 'child-1-turn', status: 'completed' } }); - expect(f.controller.busy).toBe(true); - f.controller.observe('turn/completed', { threadId: 'child-1', turn: { id: 'child-1-turn', status: 'completed', - items: [{ type: 'agentMessage', text: 'Source reference and advisory findings.' }] } }); - expect(await first).toMatchObject({ success: true }); - expect(await f.call()).toEqual(await first); - expect(f.request.mock.calls.filter(([method]) => method === 'thread/start')).toHaveLength(1); - expect(f.request).toHaveBeenCalledWith('thread/archive', { threadId: 'child-1' }); - expect(f.agents.at(-1)).toMatchObject({ status: 'completed', stoppedAt: expect.any(Number), - dispatch: 'host-mediated-native-threads', question: 'Bounded question.' }); - expect(f.controller.busy).toBe(false); - }); - - it('does not silently abandon a child when archive fails', async () => { - const f = fixture(); - f.request.mockImplementation(async method => { - if (method === 'thread/start') return { thread: { id: 'child-1' }, model: 'fixture', reasoningEffort: 'high', - approvalPolicy: 'never', activePermissionProfile: { id: 'math-investigator' } }; - if (method === 'turn/start') return { turn: { id: 'child-1-turn' } }; - throw new Error('archive fixture failure'); - }); - const first = f.call(); - await vi.waitFor(() => expect(f.request).toHaveBeenCalledWith('turn/start', expect.anything())); - f.controller.observe('turn/completed', { threadId: 'child-1', turn: { id: 'child-1-turn', status: 'completed' } }); - await first; - expect(f.fail).toHaveBeenCalledOnce(); - expect(f.agents.at(-1)).not.toHaveProperty('stoppedAt'); - f.controller.stop(); await f.controller.settled(); f.controller.confirmStopped(false); - expect(f.agents.at(-1)?.status).toBe('unknown'); - }); -}); diff --git a/tests/nativeSkillComparison.test.ts b/tests/nativeSkillComparison.test.ts index 5c2697af..1acfe61c 100644 --- a/tests/nativeSkillComparison.test.ts +++ b/tests/nativeSkillComparison.test.ts @@ -88,7 +88,7 @@ describe('isolated native single-task and Skill runtime comparison', () => { expect(options).toMatchObject({ proofProjectRoot: path.join(options.workspace, 'generated/problem'), hiddenRoots: [DEFAULT_TACTIC_BATTERY_FAILURE_CACHE_ROOT], environment: { DEEPSCIENTIST_MATH_WORKER_ID: 'solver', DEEPSCIENTIST_MATH_WORKER_WORKTREE: options.workspace } }); - expect(options.turnTimeoutMs).toBeUndefined(); expect(options.delegation).toBeUndefined(); + expect(options.turnTimeoutMs).toBeUndefined(); expect(result).toMatchObject({ accepted: true, status: 'evaluated_passed', writerStopped: true, turns: 1, totalTokens: 7, requestUsageAccounting: { startedRequests: 1, reportedRequests: 1, pendingRequests: 0, incomplete: false }, evaluator: { status: 'passed', method: 'host-lean-kernel-all-targets', official: false } }); diff --git a/tests/nativeTurnUsage.test.ts b/tests/nativeTurnUsage.test.ts index 11374b56..c9b6ea43 100644 --- a/tests/nativeTurnUsage.test.ts +++ b/tests/nativeTurnUsage.test.ts @@ -9,7 +9,7 @@ function fixture(prior?: SolverRunState) { const state = prior ?? { turns: 0 } as SolverRunState; initializeUsageAccounting(state); const events: string[] = []; - const usage = new ResearchUsage({ state, research: state, maxTotalTokens: 100, signal: new AbortController().signal, + const usage = new ResearchUsage({ state, research: state, signal: new AbortController().signal, remainingMs: () => Infinity, changed: () => { state.tokenBudget = buildTokenBudget(100, [state]); }, emit: event => { events.push(event); } }); const open = (id: string, source: MathAgentSession['usageSource'] = 'native-turn-totals') => { diff --git a/tests/nextChecks.test.ts b/tests/nextChecks.test.ts deleted file mode 100644 index 01becdfc..00000000 --- a/tests/nextChecks.test.ts +++ /dev/null @@ -1,312 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { parseLeadPlan } from '../src/solver/cooperationShared'; -import { currentNextCheck, prepareNextCheckDecisions } from '../src/solver/nextChecks'; -import { buildResearchContext } from '../src/solver/modules/context'; -import { commitSolverSources } from '../src/solver/problem'; -import { prepareResearchDelivery } from '../src/solver/researchAdmission'; -import { researchCheckpointLocalInputDigest } from '../src/solver/researchCheckpoints'; -import { queueResearchObservation } from '../src/solver/researchObservation'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ createSession: vi.fn() })); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); -const instances: { stop: () => Promise; directory?: string }[] = []; -afterEach(async () => { - for (const item of instances.splice(0).reverse()) { await item.stop(); if (item.directory) fs.rmSync(item.directory, { recursive: true, force: true }); } - expect(host.createSession).not.toHaveBeenCalled(); host.createSession.mockReset(); -}); - -async function fixture(constructionDependencies = ['goal_0']) { - const example = localExample('scoped-next-check-'), lead = leadWorker(example.problem, example.workspace); - const author = peerWorker(example, 'author'), checker = peerWorker(example, 'checker'); - const plan = parseCooperationPlan(example.problem, { tasks: [ - ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', objective: 'Prove the original target.', status: 'paused' })), - { id: 'construction', kind: 'research', objective: 'Find the missing construction.', ownerId: author.id, dependsOn: constructionDependencies }, - ] }); - const state = solverState(example.problem, example.workspace, { runId: 'next-check-fixture', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const controller = new AbortController(), events: string[] = []; - const cooperation = cooperativeResearch({ state, workers: [lead, author, checker], retrievalRoot: example.directory, - signal: controller.signal, emit: event => events.push(event) }); - instances.push({ directory: example.directory, stop: async () => { controller.abort(); await cooperation.stop(); } }); - const action = await cooperation.next(author, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('missing author assignment'); - expect(cooperation.started(author, action)).toBe(true); - cooperation.activate(author, action, async () => {}, async () => {}); - const goal = state.cooperation!.tasks.find(node => node.task.id === 'goal_0')!.task; - const gap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, previousGap: 'The construction needs a missing membership fact.', - reduced: 'The candidate operator is defined.', remaining: 'Prove membership in the original algebra.', - evidenceScope: 'Only the stated construction and current assumptions.', reconsiderWhen: ['A valid membership argument.'], - nextCheck: { action: 'construction-check' as const, objective: 'Test whether the construction belongs to the required algebra.', - expectedEvidence: 'A scoped application with its assumptions, or the exact unsupported inference.', targetTaskId: 'construction' } }; - const publishGap = async (summary = 'Check the hardest membership premise.') => { - queueResearchObservation({ worktree: author.worktree, finding: { summary, mathematicalGap: gap } }); - await cooperation.pulse(author.id); - return state.cooperation!.nextChecks![0]!; - }; - const record = await publishGap(); - const identity = { problemReceiptDigest: example.problem.receiptDigest, environmentDigest: state.environmentDigest }; - const publishOutcome = async (beforePublish?: (action: Extract) => void) => { - const checkAction = await cooperation.next(checker, { maxTurns: Infinity, remainingMs: Infinity }); - if (checkAction?.kind !== 'task') throw new Error('missing check assignment'); - expect(checkAction.task.id).toBe(record.taskId); - expect(cooperation.started(checker, checkAction)).toBe(true); - cooperation.activate(checker, checkAction, async () => {}, async () => {}); - beforePublish?.(checkAction); - queueResearchObservation({ worktree: checker.worktree, finding: { summary: 'The membership inference is still unknown.', - checkOutcome: { checkId: record.id, conclusion: 'inconclusive', summary: 'The available assumptions do not yet provide a membership argument.', evidenceRefs: [] } } }); - await cooperation.pulse(checker.id); - return checkAction; - }; - const leadDecision = async () => { - const leadAction = await cooperation.next(lead, { maxTurns: Infinity, remainingMs: Infinity }); - if (leadAction?.kind !== 'lead') throw new Error('missing Lead decision'); - const view = cooperation.contextState(leadAction, lead); - expect(cooperation.started(lead, leadAction)).toBe(true); - cooperation.activate(lead, leadAction, async () => {}, async () => {}); - const publish = async (decisions?: unknown[]) => { - fs.appendFileSync(path.join(lead.worktree, leadPlanDeliveryFile(leadAction)!), JSON.stringify({ kind: 'plan', - dispatchNonce: leadAction.planNonce, baseVersion: leadAction.planVersion, upsert: [], - ...(decisions ? { nextCheckDecisions: decisions } : {}) }) + '\n'); - await cooperation.pulse(lead.id); - }; - return { leadAction, view, publish }; - }; - return { ...example, lead, author, checker, workers: [lead, author, checker], state, cooperation, controller, - action, gap, record, identity, events, publishGap, publishOutcome, leadDecision }; -} - -describe('scoped next check lifecycle', () => { - it.each(['live', 'legacy restart'] as const)('keeps a parked check paused through progress rephrasing and resumes it on new evidence (%s)', async mode => { - const f = await fixture([]), budget = { maxTurns: Infinity, remainingMs: Infinity }; - let state = f.state.cooperation!, check = state.tasks.find(node => node.nextCheckId === f.record.id)!; - let cooperation = f.cooperation, assignment = f.action.assignment; - const progress = async (summary: string, evidenceRefs?: string[]) => { - const log = path.join(f.author.worktree, assignmentDeliveryFile(assignment)); - fs.appendFileSync(log, JSON.stringify({ kind: 'progress', summary, evidenceRefs }) + '\n'); - await cooperation.pulse(f.author.id); - expect(state.deliveries!.at(-1)).toMatchObject({ kind: 'progress', status: 'advisory', summary }); - }; - await progress('Saved the unfinished comparison. No new evidence.'); - for (let attempt = 0; attempt < 3; attempt++) { - const action = await f.cooperation.next(f.checker, budget); - if (action?.kind !== 'task') throw new Error('missing scoped check assignment'); - expect(action.task.id).toBe(check.task.id); - expect(f.cooperation.started(f.checker, action)).toBe(true); - fs.writeFileSync(path.join(f.checker.worktree, 'RESEARCH.md'), 'Membership remains open.\n'); - await f.cooperation.deliver(f.checker, action, commitSolverSources(f.problem, f.checker.worktree), true); - } - expect(check.status).toBe('blocked'); - const checkpoint = structuredClone(state.researchCheckpoints![check.task.id]); - expect(checkpoint).toMatchObject({ count: 3, paused: true }); - if (mode === 'legacy restart') { - const legacyDigest = researchCheckpointLocalInputDigest({ task: check.task, workerId: f.checker.id, - tasks: state.tasks, deliveries: state.deliveries!, environmentDigest: f.state.environmentDigest, - problemReceiptDigest: f.problem.receiptDigest }, true); - expect(legacyDigest).not.toBe(checkpoint.localInputDigest); - state.researchCheckpoints![check.task.id].localInputDigest = legacyDigest; - const file = path.join(f.directory, 'state.json'); - writeSolverRunState(file, f.state); - f.controller.abort(); await f.cooperation.stop(); - - const restored = readSolverRunState(file), controller = new AbortController(); - state = restored.cooperation!; - check = state.tasks.find(node => node.nextCheckId === f.record.id)!; - cooperation = cooperativeResearch({ state: restored, workers: f.workers, retrievalRoot: f.directory, - signal: controller.signal, emit: event => f.events.push(event) }); - instances.push({ stop: async () => { controller.abort(); await cooperation.stop(); } }); - await cooperation.restore(); - expect(check.status).toBe('blocked'); - const action = await cooperation.next(f.author, budget); - if (action?.kind !== 'task') throw new Error('missing author assignment on restart'); - expect(cooperation.started(f.author, action)).toBe(true); - cooperation.activate(f.author, action, async () => {}, async () => {}); - assignment = action.assignment; - } - - await progress('Retained the same comparison and its open question in the draft.'); - expect(check.status).toBe('blocked'); - expect(state.researchCheckpoints![check.task.id]).toEqual(checkpoint); - expect(f.events).not.toContain('research_checkpoint_reopened'); - - await progress('Found a supporting calculation for this membership test.', ['calculation:membership-reduction']); - expect(check.status).toBe('pending'); - expect(f.events).toContain('research_checkpoint_reopened'); - const resumed = await cooperation.next(f.checker, budget); - expect(resumed).toMatchObject({ kind: 'task', task: { id: check.task.id } }); - expect(f.record.outcome).toBeUndefined(); - }); - - it('schedules independent work, consumes an unknown outcome, applies a Lead stop and preserves it across restart', async () => { - const f = await fixture(); - expect(f.record).toMatchObject({ status: 'pending', scope: { parent: { taskId: 'construction' }, - target: { taskId: 'construction' }, consumer: { taskId: 'goal_0' } } }); - expect(f.state.cooperation!.tasks.find(node => node.task.id === f.record.taskId)?.task.reviewScope).toBe('feasibility'); - await f.publishOutcome(); - expect(f.record.status).toBe('awaiting-decision'); - expect(f.record.outcome?.conclusion).toBe('inconclusive'); - expect(f.state.cooperation!.tasks.find(node => node.task.id === f.record.taskId)?.status).toBe('completed'); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'construction')?.status).toBe('running'); - const lead = await f.leadDecision(); - const template = JSON.parse(lead.view.leadDecisionInstruction!.match(/Current response template[^\n]*\n([^\n]+)\n/u)![1]); - expect(template).toMatchObject({ baseVersion: lead.leadAction.planVersion, upsert: [], - nextCheckDecisions: [{ checkId: f.record.id, outcomeDeliveryId: f.record.outcome!.deliveryId }] }); - expect(template.nextCheckDecisions[0].action).toBe(''); - await lead.publish([{ checkId: f.record.id, outcomeDeliveryId: f.record.outcome!.deliveryId, action: 'stop', reason: 'Try another route before spending more effort on this construction.' }]); - expect(f.state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(f.record).toMatchObject({ status: 'decided', decision: { action: 'stop' } }); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'construction')?.task.status).toBe('paused'); - expect(f.events).toEqual(expect.arrayContaining(['next_check_scheduled', 'next_check_outcome', 'next_check_decided'])); - expect(f.state.cooperation!.tasks.some(node => node.proof || node.integratedCheck)).toBe(false); - const file = path.join(f.directory, 'state.json'); writeSolverRunState(file, f.state); - const restored = readSolverRunState(file); - expect(restored.cooperation!.nextChecks).toEqual(f.state.cooperation!.nextChecks); - f.controller.abort(); await f.cooperation.stop(); - const resumed = cooperativeResearch({ state: restored, workers: f.workers, retrievalRoot: f.directory }); - instances.push({ stop: () => resumed.stop() }); - await resumed.restore(); - expect(restored.cooperation!.nextChecks).toHaveLength(1); - expect(restored.cooperation!.tasks.filter(node => node.nextCheckId === f.record.id)).toHaveLength(1); - expect(restored.cooperation!.nextChecks![0]!.decision?.action).toBe('stop'); - }); - - it('requires the shown outcome to receive an explicit decision and keeps it in full and same-thread contexts', async () => { - const f = await fixture(); - const access = { root: f.directory, environment: {}, retrievalRoot: f.directory, taskText: 'Prove the original target.', - maxOptionalContextBytes: 0 }; - const draft = buildResearchContext(f.problem, { ...f.state, cooperation: f.cooperation.contextState(f.action, f.author) }, - { ...access, worktree: f.author.worktree, assignment: f.action }); - for (const message of [draft.message, draft.continuationMessage]) { - expect(message).toContain(f.record.id); - expect(message).not.toContain('checkOutcome:'); - expect(message).not.toContain('guidanceDecisions:'); - } - await f.publishOutcome(action => { - const context = buildResearchContext(f.problem, { ...f.state, cooperation: f.cooperation.contextState(action, f.checker) }, - { ...access, worktree: f.checker.worktree, assignment: action }); - expect(context.message).toContain(f.record.id); - expect(context.message).toContain('checkOutcome:'); - expect(context.message).toContain('with research-observe'); - }); - const lead = await f.leadDecision(); - const context = buildResearchContext(f.problem, { ...f.state, cooperation: lead.view }, - { ...access, worktree: f.workspace, assignment: lead.leadAction }); - for (const text of [context.message, context.continuationMessage]) { - expect(text).toContain(f.record.id); expect(text).toContain(f.record.outcome!.deliveryId); - expect(text).toContain('inconclusive'); - expect(text).toContain('nextCheckDecisions'); - expect(text).not.toContain('checkOutcome:'); - } - await lead.publish(); - expect(f.state.cooperation!.planPublicationRejection?.reason).toContain('math_plan_next_check_decision_required'); - expect(f.record.status).toBe('awaiting-decision'); - await lead.publish([{ checkId: f.record.id, outcomeDeliveryId: f.record.outcome!.deliveryId, action: 'continue', reason: 'Retain this route while seeking the missing argument.' }]); - expect(f.state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(f.record.status).toBe('decided'); - }); - - it('reconciles a running task for a decided check left by an older continuation', async () => { - const f = await fixture(); - await f.publishOutcome(); - const lead = await f.leadDecision(); - await lead.publish([{ checkId: f.record.id, outcomeDeliveryId: f.record.outcome!.deliveryId, action: 'continue', - reason: 'Continue the other estimate using the archived result.' }]); - const check = f.state.cooperation!.tasks.find(node => node.nextCheckId === f.record.id)!; - f.state.cooperation!.tasks = f.state.cooperation!.tasks.map(node => node === check - ? { ...node, status: 'running', assignment: undefined, attempts: 0 } : node); - const file = path.join(f.directory, 'state.json'); - writeSolverRunState(file, f.state); - f.controller.abort(); await f.cooperation.stop(); - - const restored = readSolverRunState(file), controller = new AbortController(), assigned: unknown[] = []; - const resumed = cooperativeResearch({ state: restored, workers: f.workers, retrievalRoot: f.directory, - signal: controller.signal, emit: (event, details) => { if (event === 'task_assigned') assigned.push(details); } }); - instances.push({ stop: async () => { controller.abort(); await resumed.stop(); } }); - await resumed.restore(); - expect(restored.cooperation!.nextChecks![0]).toMatchObject({ id: f.record.id, status: 'decided' }); - expect(restored.cooperation!.tasks.find(node => node.nextCheckId === f.record.id)).toMatchObject({ status: 'completed', attempts: 0 }); - - // Even an inconsistent pending record reaching the scheduler cannot be reserved. - restored.cooperation!.tasks = restored.cooperation!.tasks.map(node => node.nextCheckId === f.record.id - ? { ...node, status: 'pending' } : node); - const offered = resumed.next(f.checker, { maxTurns: Infinity, remainingMs: Infinity }); - try { - await expect(Promise.race([offered, new Promise(resolve => setTimeout(resolve, 30, 'waiting'))])).resolves.toBe('waiting'); - expect(assigned).toEqual([]); - } finally { - controller.abort(); - await offered.catch(() => {}); - } - }); - - it('deduplicates the same question across notes-only publications and rejects an outcome from its author', async () => { - const f = await fixture(); - await f.publishGap('The same missing inference, reported again after a checkpoint.'); - expect(f.state.cooperation!.nextChecks).toHaveLength(1); - expect(f.events.filter(event => event === 'next_check_scheduled')).toHaveLength(1); - expect(() => queueResearchObservation({ worktree: f.author.worktree, finding: { summary: 'An author self-report.', - checkOutcome: { checkId: f.record.id, conclusion: 'supporting', summary: 'I believe this method works.', evidenceRefs: [] } } })) - .toThrow('math_delivery_invalid:check_outcome_scope'); - expect(f.record.status).toBe('pending'); - }); - - it('keeps a pending check and its exact scope after checkpoint reload without creating another task', async () => { - const f = await fixture(), file = path.join(f.directory, 'pending.json'); - writeSolverRunState(file, f.state); const restored = readSolverRunState(file); - f.controller.abort(); await f.cooperation.stop(); - const resumed = cooperativeResearch({ state: restored, workers: f.workers, retrievalRoot: f.directory }); - instances.push({ stop: () => resumed.stop() }); await resumed.restore(); - expect(restored.cooperation!.nextChecks).toHaveLength(1); - const check = await resumed.next(f.checker, { maxTurns: Infinity, remainingMs: Infinity }); - expect(check?.kind === 'task' && check.task.id).toBe(f.record.taskId); - expect(currentNextCheck(restored.cooperation!.nextChecks![0]!, restored.cooperation!, f.identity)).toBe(true); - }); - - it('expires a changed target and rejects its old scoped outcome', async () => { - const f = await fixture(); - const task = f.state.cooperation!.tasks.find(node => node.task.id === f.record.taskId)!; - const assigned = { taskId: task.task.id, taskDigest: taskVersion(task.task), workerId: f.checker.id, seedCommit: f.problem.baseCommit }; - fs.appendFileSync(path.join(f.directory, 'edits.jsonl'), JSON.stringify({ id: 'changed-construction', - baseVersion: f.state.cooperation!.planVersion, tasks: f.state.cooperation!.tasks.filter(node => !node.nextCheckId) - .map(node => node.task.id === 'construction' ? { ...node.task, objective: 'Investigate a different construction.', revision: 1 } : node.task) }) + '\n'); - await f.cooperation.pulse(f.lead.id); - expect(f.state.cooperation!.edits?.at(-1)?.status).toBe('applied'); - expect(f.record.status).toBe('stale'); - expect(f.state.cooperation!.tasks.find(node => node.nextCheckId === f.record.id)).toBeUndefined(); - const admission = prepareResearchDelivery({ kind: 'event', value: { summary: 'An old result.', - checkOutcome: { checkId: f.record.id, conclusion: 'inconclusive', summary: 'The old construction remains unknown.', evidenceRefs: [] } } }, - { source: task.task, assignment: assigned, ...f.state.cooperation!, identity: f.identity }); - expect(admission).toMatchObject({ status: 'rejected', code: 'math_delivery_invalid:check_outcome_scope' }); - }); - - it('keeps an unanswered scoped outcome owed to Lead after restart', async () => { - const f = await fixture(); await f.publishOutcome(); - const file = path.join(f.directory, 'awaiting.json'); writeSolverRunState(file, f.state); - const restored = readSolverRunState(file); f.controller.abort(); await f.cooperation.stop(); - const resumed = cooperativeResearch({ state: restored, workers: f.workers, retrievalRoot: f.directory }); - instances.push({ stop: () => resumed.stop() }); await resumed.restore(); - const action = await resumed.next(f.lead, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind).toBe('lead'); - expect(resumed.contextState(action, f.lead).nextChecks).toContainEqual(expect.objectContaining({ - id: f.record.id, status: 'awaiting-decision', outcome: expect.objectContaining({ deliveryId: f.record.outcome!.deliveryId }) })); - expect(restored.cooperation!.tasks.filter(node => node.nextCheckId)).toHaveLength(1); - expect(restored.cooperation!.tasks.find(node => node.nextCheckId)?.status).toBe('completed'); - }); - - it('rejects a claimed revision that merely renames the objective and retains legacy plans', async () => { - const f = await fixture(); await f.publishOutcome(); - const base = { version: f.state.cooperation!.planVersion!, tasks: f.state.cooperation!.tasks.filter(node => !node.nextCheckId).map(node => node.task), - groups: f.state.cooperation!.groups!.map(record => record.group) }; - const plan = parseLeadPlan(f.problem, { baseVersion: base.version, upsert: [{ id: 'construction', objective: 'A renamed core problem.' }], - nextCheckDecisions: [{ checkId: f.record.id, outcomeDeliveryId: f.record.outcome!.deliveryId, action: 'revise', reason: 'Rename the central problem.' }] }, base); - expect(() => prepareNextCheckDecisions(f.state.cooperation!, f.identity, plan, plan.nextCheckDecisions)) - .toThrow('math_plan_next_check_revision_required'); - expect(parseLeadPlan(f.problem, { tasks: base.tasks, groups: base.groups }).nextCheckDecisions).toBeUndefined(); - }); -}); diff --git a/tests/openCodeSession.test.ts b/tests/openCodeSession.test.ts index c4fe7f7e..630132e4 100644 --- a/tests/openCodeSession.test.ts +++ b/tests/openCodeSession.test.ts @@ -143,10 +143,9 @@ describe('OpenCode native session adapter', () => { controller.abort(); await expect(completion).rejects.toThrow(); expect(f.missing).toHaveBeenCalledOnce(); }); - it('fails before launch for unsupported native skill and delegation', async () => { + it('fails before launch for unsupported native skill loading', async () => { const f = fixture(); await expect(f.open({ skills: [{ ...f.options.skills![0], loading: 'native' }] })).rejects.toThrow('requires_file_skill'); - await expect(f.open({ delegation: { mode: 'read-only', maxAgents: 2 } })).rejects.toThrow('delegation_unsupported'); expect(fs.existsSync(path.join(f.profile, 'xdg/data/opencode-peer-state.json'))).toBe(false); }); diff --git a/tests/portableCooperation.test.ts b/tests/portableCooperation.test.ts deleted file mode 100644 index e3b2ebe6..00000000 --- a/tests/portableCooperation.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import type { MathAgentSession } from '../src/runtime/agentSession'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { planMathAgentSession } from '../src/runtime/agentSessionPlan'; -import { readCliConfiguration } from '../src/runtime/cliConfiguration'; -import { researchHarness } from '../src/runtime/researchHarness'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { directSolverModules } from '../src/solver/modules'; -import { git } from '../src/solver/problem'; -import { runResearchWorkers, type WorkerAccess } from '../src/solver/research'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -// Native processes, scoped role context, source freezing, task checking and original -// checks are real. Only the unrelated source-bundle receipt is replaced. -vi.mock('../src/math/mathBuildManifest', async original => ({ - ...await original(), readMathBuildManifest: vi.fn(), -})); -const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); - -function fixture(harnessId: 'claude-code' | 'opencode' | 'cli', invalid: boolean) { - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); - const example = localExample('portable-cooperation-'); roots.push(example.directory); - const { workspace, problem, directory } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'engineer', { role: 'engineer' }), - peerWorker(example, 'reviewer', { role: 'reviewer' })]; - const profile = path.join(directory, 'native-profile'); fs.mkdirSync(profile); - const executable = path.join(directory, 'native-peer.cjs'); - fs.copyFileSync(path.join(repository, 'tests/fixtures/portableCooperationPeer.cjs'), executable); fs.chmodSync(executable, 0o700); - const tasks = problem.targets.map((target, index) => ({ id: 'goal_' + (index + 1), kind: 'goal', - objective: 'Prove the unchanged original tutorial declaration ' + target.theoremName, ...target, - ownerId: 'engineer', dependsOn: index ? ['goal_1'] : [] })); - fs.writeFileSync(path.join(profile, 'portable-fixture.json'), JSON.stringify({ tasks, invalid, - proofs: { 'Tutorial.add_zero': 'by rfl', 'Tutorial.zero_add': 'by exact Nat.zero_add n' } })); - if (harnessId === 'opencode') fs.writeFileSync(path.join(profile, 'opencode.json'), JSON.stringify({ provider: { - fixture: { npm: '@ai-sdk/openai-compatible', models: { model: { name: 'Fixture', variants: { high: {} } } } }, - } })); - if (harnessId === 'cli') fs.writeFileSync(path.join(profile, 'cli.json'), JSON.stringify({ schema: 'theorem-os.cli-harness.v1', executable, - args: ['--model', '{model}', '--effort', '{effort}', '--profile', '{profile}'], efforts: ['high'], - session: { mode: 'generated', startArgs: ['--session-id', '{sessionId}'], resumeArgs: ['--resume', '{sessionId}'] }, - output: { format: 'json', sessionId: { field: '/session/id' }, text: { field: '/result/text' }, - usage: { inputTokens: '/stats/input', outputTokens: '/stats/output', completeness: 'complete', scope: 'turn' } } })); - const researchSkill = researchSkillIdentity(readMathAgentSkill(path.join(repository, 'skills/theoremos-research/SKILL.md'), 'file')); - const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, ELAN_HOME: path.join(os.homedir(), '.elan'), - LEAN_PATH: '', LEAN_SYSROOT: '', DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'absent.env') }; - const access = new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory, - researchSkill: prepareResearchSkill(repository, worker.worktree, researchSkill, problem) }])); - const opened: MathAgentSession[] = []; - const open = vi.fn(async options => { - const session = await researchHarness(harnessId).open(options); opened.push(session); return session; - }); - const modules = { ...directSolverModules, M1: { ...directSolverModules.M1, open } }; - const stateFile = path.join(directory, 'state.json'); - const state = solverState(problem, workspace, { runId: 'portable-full-' + harnessId + '-' + invalid, - phase: 'running', coordination: 'cooperative', workerCount: workers.length, - environmentDigest: mathDigest('portable-full-cooperation'), model: harnessId === 'claude-code' ? 'claude-fixture' : 'fixture/model', - effort: 'high', researchMode: 'skill', researchSkillWorkflow: 'full', researchSkill, - agentSessionPlan: planMathAgentSession(harnessId, { skills: [access.get(workers[0].id)!.researchSkill!] }, - harnessId === 'cli' ? readCliConfiguration(profile) : undefined), - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })) }); - const events: { event: string; details?: Record }[] = []; - const run = async (current: typeof state, maxTurns: number) => await runResearchWorkers({ state: current, - workers, access, modules, root: repository, buildFile: path.join(directory, 'unused-build.json'), - taskText: 'Prove the frozen original tutorial statements using the full cooperative workflow.', - executable, profile, signal: new AbortController().signal, deadline: Infinity, maxTurns, maxTurnMs: Infinity, - maxTotalTokens: 1000, proofTimeoutMs: 30_000, - save: () => writeSolverRunState(stateFile, current), emit: (event, details) => events.push({ event, details }) }); - const calls = () => fs.readFileSync(path.join(profile, 'portable-native-calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); - return { ...example, workers, state, stateFile, run, calls, opened, open, events }; -} - -describe('full Skill cooperation over portable native harnesses', () => { - it.each(['claude-code', 'opencode', 'cli'] as const)('restores the %s plan and accepts only the independently checked original goals', async harness => { - const f = fixture(harness, false); - expect(await f.run(f.state, 1)).toBeUndefined(); - const planned = readSolverRunState(f.stateFile); - expect(planned.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(planned.cooperation!.tasks.every(node => node.status !== 'integrated')).toBe(true); - expect(planned.check?.passed).not.toBe(true); expect(planned.turns).toBe(1); - expect(f.calls()).toMatchObject([{ worker: 'solver', kind: 'lead' }]); - for (const session of f.opened) expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - const winner = await f.run(planned, 12); - expect(winner?.check.passed).toBe(true); - expect(winner!.check.verification.results).toHaveLength(f.problem.targets.length); - expect(winner!.check.verification.results.every(result => result.status === 'kernel_verified')).toBe(true); - expect(planned.cooperation!.tasks.every(node => node.status === 'integrated')).toBe(true); - expect(f.calls().filter(call => call.kind === 'task').map(call => call.taskId)).toEqual(['goal_1', 'goal_2']); - expect(f.calls().some(call => call.kind === 'review' && call.worker === 'reviewer')).toBe(true); - expect(planned.usage!.totalTokens).toBe(planned.turns * 16); - expect(planned.workers!.every(worker => !worker.writerStopUnconfirmed)).toBe(true); - for (const session of f.opened) expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - expect(git(f.workspace, ['rev-parse', 'HEAD'])).not.toBe(f.problem.baseCommit); - }, 90_000); - - it.each(['claude-code', 'opencode', 'cli'] as const)('rejects an incorrect %s goal even when the native turn reports completed', async harness => { - const f = fixture(harness, true); - expect(await f.run(f.state, 5)).toBeUndefined(); - const bad = f.state.cooperation!.tasks.find(node => node.task.id === 'goal_2')!; - expect(f.calls().some(call => call.kind === 'task' && call.taskId === 'goal_2')).toBe(true); - expect(bad.status).not.toBe('integrated'); expect(bad.integratedCheck?.passed).not.toBe(true); - expect(f.state.cooperation!.deliveries!.some(delivery => delivery.kind === 'failure' && delivery.taskId === 'goal_2')).toBe(true); - expect(f.state.check?.passed).not.toBe(true); - expect(f.state.workers!.every(worker => !worker.writerStopUnconfirmed)).toBe(true); - for (const session of f.opened) expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - }, 90_000); -}); diff --git a/tests/proofSearchRecords.test.ts b/tests/proofSearchRecords.test.ts index 6079c479..044df47d 100644 --- a/tests/proofSearchRecords.test.ts +++ b/tests/proofSearchRecords.test.ts @@ -6,14 +6,13 @@ import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { deliveryDetails } from '../src/solver/deliveries'; import type { NextCheckRecord } from '../src/solver/nextCheckContract'; -import { parseCooperationPlan } from '../src/solver/cooperation'; +import { parseCooperationPlan } from '../src/solver/tasks'; import { assignmentDeliveryFile } from '../src/solver/tasks'; import { latestProofSearchRecord, MAX_PROOF_SEARCH_CHECKPOINT_BYTES, projectProofSearchRecord, proofSearchRecordMatches, proofSearchTargetForAssignment, readProofSearchCheckpoint, retainProofSearchCheckpoint, type ProofSearchCheckpointReference, type ProofSearchScope, } from '../src/solver/proofSearchRecords'; -import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; const forbidden = vi.hoisted(() => ({ model: vi.fn(), lean: vi.fn() })); @@ -155,57 +154,3 @@ describe('host-retained advisory proof search records', () => { expect(() => deliveryDetails({ kind: 'proof', searchCheckpoint: reference })).toThrow('math_delivery_invalid'); }); }); - -describe('proof search progress intake and archive recovery', () => { - it('keeps publication advisory, deduplicates intake and exposes a scoped recoverable checkpoint', async () => { - const example = localExample('proof-search-intake-'), lead = leadWorker(example.problem, example.workspace); - const worker = peerWorker(example, 'worker'), other = peerWorker(example, 'other'); - const controller = new AbortController(); - const plan = parseCooperationPlan(example.problem, { tasks: [ - ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', - objective: 'Prove original target.', status: 'paused' })), - { id: 'explore', kind: 'research', objective: 'Explore a local proof.', ownerId: worker.id }, - ] }); - const state = solverState(example.problem, example.workspace, { runId: 'search-intake', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const cooperation = cooperativeResearch({ state, workers: [lead, worker, other], retrievalRoot: example.directory, signal: controller.signal }); - try { - const action = await cooperation.next(worker, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('missing fixture assignment'); - expect(cooperation.started(worker, action)).toBe(true); - cooperation.activate(worker, action, async () => {}, async () => {}); - const project = path.join(worker.worktree, example.problem.projectRelative); - const currentScope = { taskId: action.task.id, taskDigest: action.assignment.taskDigest, - problemReceiptDigest: example.problem.receiptDigest, environmentDigest: state.environmentDigest }; - const saved = saveCheckpoint(project, currentScope); - const event = JSON.stringify({ kind: 'progress', id: saved.reference.digest, summary: 'A prefix remains open.', searchCheckpoint: saved.reference }) + '\n'; - const log = path.join(worker.worktree, assignmentDeliveryFile(action.assignment)); - const otherScope = saveCheckpoint(project, { ...currentScope, taskId: 'other-task' }); - fs.appendFileSync(log, JSON.stringify({ kind: 'progress', id: 'wrong-scope', summary: 'Incorrect search scope.', - searchCheckpoint: otherScope.reference }) + '\n'); - await cooperation.pulse(worker.id); - expect(state.cooperation!.proofSearchRecords).toBeUndefined(); - expect(state.cooperation!.deliveryReceipts?.some(receipt => receipt.status === 'needs-correction')).toBe(true); - fs.appendFileSync(log, event + event); await cooperation.pulse(worker.id); - const record = state.cooperation!.proofSearchRecords!.explore; - expect(record.checkpoint.digest).toBe(saved.reference.digest); - expect(state.cooperation!.deliveries?.filter(item => item.submissionId === saved.reference.digest)).toHaveLength(1); - expect(state.cooperation!.tasks.find(node => node.task.id === 'explore')).toMatchObject({ status: 'running' }); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - const visible = JSON.parse(fs.readFileSync(path.join(worker.worktree, 'COOPERATION.json'), 'utf8')); - expect(visible.proofSearchRecords.explore.checkpoint.path.startsWith(project + path.sep)).toBe(true); - const peer = JSON.parse(fs.readFileSync(path.join(other.worktree, 'COOPERATION.json'), 'utf8')); - expect(peer.proofSearchRecords).toEqual({}); - const archive = path.join(example.directory, 'state.json'); writeSolverRunState(archive, state); - const restored = readSolverRunState(archive); - expect(restored.cooperation!.proofSearchRecords).toEqual(state.cooperation!.proofSearchRecords); - delete restored.cooperation!.proofSearchRecords; writeSolverRunState(archive, restored); - expect(readSolverRunState(archive).cooperation!.proofSearchRecords).toBeUndefined(); - } finally { - controller.abort(); await cooperation.stop(); - expect(forbidden.model).not.toHaveBeenCalled(); expect(forbidden.lean).not.toHaveBeenCalled(); - fs.rmSync(example.directory, { recursive: true, force: true }); - } - }); -}); diff --git a/tests/repeatedDelivery.test.ts b/tests/repeatedDelivery.test.ts deleted file mode 100644 index 7a6c1404..00000000 --- a/tests/repeatedDelivery.test.ts +++ /dev/null @@ -1,752 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { ownedSourceDigest, type TaskProof } from '../src/solver/cooperativeProof'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { markTaskAcceptance, taskVersion, type CooperativeAction, type CooperativeTask, type TaskAssignment, type TaskRecord } from '../src/solver/tasks'; -import type { SolverRunState } from '../src/solver/archive'; -import { git, type SolverProblem } from '../src/solver/problem'; -import { hashMathFormalSourceDeclaration } from '../src/math/leanSource'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; - -const task = (id: string, kind: CooperativeTask['kind'] = 'lemma', dependsOn: string[] = []): CooperativeTask => ({ - id, kind, objective: id, revision: 0, dependsOn, - ...(['lemma', 'goal'].includes(kind) ? { proofPath: 'Submission.lean', theoremName: id, type: 'True' } : {}), -}); -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -const missing = 'math_task_missing_declaration\nThe assigned theorem is absent; no Lean check started.'; - -describe('persistent typed delivery failure guards', () => { - let directory: string, seed: string, candidate: TaskRecord, state: SolverRunState; - let lead: ResearchWorker, researcher: ResearchWorker, cooperative: CooperativeResearch; - let action: Extract; - let checker: ReturnType>; - let emit: ReturnType; - const instances: CooperativeResearch[] = []; - const sourceFile = () => path.join(directory, 'generated/p/Submission.lean'); - const commit = (notes = 'Saved notes.') => { - fs.writeFileSync(path.join(directory, 'RESEARCH.md'), notes); - git(directory, ['add', '--', 'generated', 'RESEARCH.md']); - git(directory, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--no-gpg-sign', '--quiet', '--allow-empty', '-m', 'Saved candidate']); - return git(directory, ['rev-parse', 'HEAD']); - }; - const failure = (worktree: string, version: string, obligation: CooperativeTask, assignment: TaskAssignment, - conditions: readonly CooperativeTask[] = []): TaskProof => ({ - commit: version, sourceDigest: ownedSourceDigest(state.problem, worktree, version), taskDigest: taskVersion(obligation), - seedCommit: assignment.seedCommit, passed: false, changes: [], imports: [], - conditions: conditions.map(task => ({ taskId: task.id, taskDigest: taskVersion(task) })), - verification: { status: 'failed', targetCommit: version, results: [{ status: 'failed', targetCommit: version, - error: 'Lean exited with status 1.', stdoutPreview: 'Submission.lean:1:1: error: Unknown identifier FAILURE' }] }, - } as TaskProof); - const create = (restored = state) => { - const instance = cooperativeResearch({ state: restored, workers: [lead, researcher], retrievalRoot: '', - access: new Map([[lead.id, { environment: {} } as any]]), emit, - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask: checker } } }); - vi.spyOn(instance as any, 'seed').mockReturnValue(seed); - instances.push(instance); return instance; - }; - const check = (version = seed, conditions?: readonly CooperativeTask[], instance = cooperative) => - (instance as any).check(candidate.task, candidate.assignment, directory, version, conditions, undefined, true) as Promise; - const reseed = (source: string) => { - fs.writeFileSync(sourceFile(), source); - seed = commit(); state.cooperation!.canonicalCommit = seed; candidate.assignment!.seedCommit = seed; - }; - const failWith = (edit: (proof: TaskProof) => void) => checker.mockImplementation( - async (_problem, worktree, version, obligation, assignment, _goals, _env, _signal, _timeout, conditions) => { - const proof = failure(worktree, version, obligation, assignment, conditions); edit(proof); return proof; - }); - const accepted = (record: TaskRecord, after: string, receiptId: string) => { - record.integratedCheck = { ...failure(directory, seed, record.task, candidate.assignment!), passed: true, - changes: [{ file: 'Submission.lean', name: record.task.id, after }], - verification: { status: 'kernel_verified', targetCommit: seed, - results: [{ status: 'kernel_verified', targetCommit: seed, receiptId }] } } as TaskProof; - markTaskAcceptance(record.integratedCheck); return record; - }; - const exhaustRepair = async () => { - await cooperative.deliver(researcher, action, seed); - const repair = await cooperative.next(researcher, budget); - expect(repair).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); - if (repair?.kind !== 'task') throw new Error('expected_local_repair'); - expect(cooperative.started(researcher, repair)).toBe(true); - await cooperative.deliver(researcher, repair, seed); - expect(candidate.status).toBe('blocked'); - return repair; - }; - const resumeTask = async (instance = cooperative) => { - const next = await instance.next(researcher, budget); - if (next?.kind !== 'task') throw new Error('expected_resumed_assignment'); - expect(instance.started(researcher, next)).toBe(true); - return next; - }; - const recoverUntouched = async () => { - let work = action; - for (let turn = 0; turn < 3; turn++) { - await cooperative.deliver(researcher, work, seed, true, 'request-failure'); - expect(candidate.status).toBe('pending'); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(checker).not.toHaveBeenCalled(); - work = await resumeTask(); - } - return work; - }; - beforeEach(() => { - directory = temporaryDirectory('repeated-delivery-'); - fs.mkdirSync(path.join(directory, 'generated/p'), { recursive: true }); - fs.writeFileSync(sourceFile(), 'lemma candidate : True := by exact FAILURE\n'); - fs.writeFileSync(path.join(directory, 'generated/p/notes.txt'), 'Advisory material.'); - git(directory, ['init', '--quiet']); seed = commit(); - lead = { id: 'lead', role: 'lead', worktree: directory, ownedFiles: ['Submission.lean', 'notes.txt'] }; - researcher = { ...lead, id: 'researcher', role: 'researcher' }; - candidate = { task: task('candidate'), status: 'running', attempts: 1, - assignment: { taskId: 'candidate', taskDigest: taskVersion(task('candidate')), workerId: 'researcher', seedCommit: seed } }; - state = { runId: 'fixture', turns: 0, environmentDigest: 'environment', buildDigest: 'build', evaluatorDigest: 'evaluator', - // Keep this goal prerequisite-first so dispatches exercise the candidate's local repair. - cooperation: { canonicalCommit: seed, tasks: [candidate, - { task: { ...task('goal', 'goal', ['candidate']), conditional: false }, status: 'pending', attempts: 0 }], - groups: [{ group: { id: 'main', objective: 'Original goal', status: 'active', revision: 0 }, turns: 0 }] }, - problem: { receiptDigest: 'problem', projectRelative: 'generated/p', ownedFiles: lead.ownedFiles, - declarations: { 'Submission.lean': [] }, targets: [{ proofPath: 'Submission.lean', theoremName: 'goal' }], - trustedFiles: {}, baseCommit: seed, sourceStructure: { 'Submission.lean': mathDigest('') }, sourceImports: {}, - contract: { assumptions: [], formalStatement: 'Original goal.' } } as unknown as SolverProblem } as SolverRunState; - checker = vi.fn(async (_problem, worktree, version, obligation, assignment, _goals, _environment, _signal, _timeout, conditions = []) => - failure(worktree, version, obligation, assignment, conditions)); - emit = vi.fn(); cooperative = create(); - action = { kind: 'task', task: candidate.task, assignment: candidate.assignment! }; - }); - afterEach(async () => { - for (const instance of instances.splice(0)) await instance.stop(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['notes', 'owned-non-Lean'] as const)('skips a repeated deterministic failure after a %s commit', async change => { - await check(); - if (change === 'owned-non-Lean') fs.writeFileSync(path.join(directory, 'generated/p/notes.txt'), 'Different prose.'); - const version = commit('A new explanation of the unchanged proof.'); - await expect(check(version)).rejects.toThrow('math_task_repeated_failed_input'); - expect(checker).toHaveBeenCalledTimes(1); - expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - }); - - it('persists a coded unknownIdentifier rejection and offers its worker a local repair', async () => { - failWith(proof => { proof.verification.results[0]!.stdoutPreview = - 'Submission.lean:1:1: error(lean.unknownIdentifier): Unknown identifier FAILURE'; }); - await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('pending'); - expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - expect(state.cooperation!.failedTaskInputs![0]).toMatchObject({ - feedback: expect.stringContaining('error(lean.unknownIdentifier)'), repair: { pending: true, workerId: researcher.id }, - }); - expect(await cooperative.next(researcher, budget)).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); - expect(checker).toHaveBeenCalledOnce(); - }); - - it.each(['compile', 'missing', 'source-contract'] as const)( - 'keeps the first local %s repair after transport-only recoveries, then blocks another completed failure', async kind => { - const work = await recoverUntouched(); - expect(candidate.attempts).toBe(4); - const reject = async (current: typeof work) => { - if (kind === 'source-contract') cooperative.rejected(current, 'math_original_context_changed'); - else await cooperative.deliver(researcher, current, version); - }; - fs.writeFileSync(sourceFile(), kind === 'missing' ? '' : 'lemma candidate : True := by exact FIRST_REAL_FAILURE\n'); - const version = commit('The first completed proof after transport recovery.'); - if (kind === 'missing') checker.mockRejectedValue(new Error(missing)); - await reject(work); - expect(candidate.status).toBe('pending'); - if (kind === 'source-contract') expect(candidate.sourceRepair?.pending).toBe(true); - else expect(state.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - const repair = await resumeTask(); - expect(repair.assignment).toBe(work.assignment); - await reject(repair); - expect(candidate.status).toBe('blocked'); - expect(emit.mock.calls.filter(([event]) => event === 'task_repair_requested')).toHaveLength(1); - expect(checker).toHaveBeenCalledTimes(kind === 'source-contract' ? 0 : 1); - expect(candidate.integratedCheck).toBeUndefined(); - }); - - it.each(['source-then-compile', 'compile-then-source'].flatMap(order => - [false, true].map(restart => ({ order, restart }))))( - 'shares one local repair between source-contract and typed failure ($order, restart: $restart)', async ({ order, restart }) => { - const sourceFirst = order === 'source-then-compile'; - if (sourceFirst) cooperative.rejected(action, 'math_original_context_changed'); - else await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('pending'); - if (restart) { - state = JSON.parse(JSON.stringify(state)) as SolverRunState; - candidate = state.cooperation!.tasks[0]; cooperative = create(); - await cooperative.restore(); - } - const repair = await resumeTask(); - if (sourceFirst) await cooperative.deliver(researcher, repair, seed); - else cooperative.rejected(repair, 'math_original_context_changed'); - expect(candidate.status).toBe('blocked'); - expect(emit.mock.calls.filter(([event]) => event === 'task_repair_requested')).toHaveLength(1); - expect(checker).toHaveBeenCalledOnce(); - if (sourceFirst) expect(state.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - else expect(candidate.sourceRepair).toBeUndefined(); - }); - - it('does not grant a second completed repair for changed proof bytes', async () => { - await cooperative.deliver(researcher, action, seed); - const repair = await resumeTask(); - fs.writeFileSync(sourceFile(), 'lemma candidate : True := by exact DIFFERENT_FAILURE\n'); - await cooperative.deliver(researcher, repair, commit()); - expect(candidate.status).toBe('blocked'); - expect(state.cooperation!.failedTaskInputs).toHaveLength(2); - expect(state.cooperation!.failedTaskInputs![1].repair).toBeUndefined(); - expect(emit.mock.calls.filter(([event]) => event === 'task_repair_requested')).toHaveLength(1); - expect(checker).toHaveBeenCalledTimes(2); - }); - - it('restores the first saved failure repair after transport-only turns without granting another completed retry', async () => { - await recoverUntouched(); - // The host can stop after persisting a check failure but before delivering its pending repair. - await check(); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState; - delete restored.cooperation!.failedTaskInputs![0].repair; - const resumed = create(restored); - await resumed.restore(); - expect(restored.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - const repair = await resumeTask(resumed); - await resumed.deliver(researcher, repair, seed); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - expect(restored.cooperation!.failedTaskInputs![0].repair).toMatchObject({ pending: false }); - expect(checker).toHaveBeenCalledOnce(); - await resumed.restore(); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - expect(restored.cooperation!.failedTaskInputs![0].repair?.pending).toBe(false); - }); - - it('retains the repair grant through next and release, and consumes it only at started', async () => { - checker.mockRejectedValue(new Error(missing)); - await cooperative.deliver(researcher, action, seed); - const failed = state.cooperation!.failedTaskInputs![0]; - expect(candidate.status).toBe('pending'); expect(failed.repair?.pending).toBe(true); - let repair = await cooperative.next(researcher, budget); - expect(repair).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); expect(failed.repair?.pending).toBe(true); - if (repair?.kind !== 'task') throw new Error('expected_local_repair'); - cooperative.release(researcher, repair); - expect(candidate.attempts).toBe(1); expect(failed.repair?.pending).toBe(true); - repair = await cooperative.next(researcher, budget); - expect(repair).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); - if (repair?.kind !== 'task') throw new Error('expected_reserved_repair'); - expect(cooperative.started(researcher, repair)).toBe(true); - expect(failed.repair?.pending).toBe(false); expect(candidate.attempts).toBe(2); - await cooperative.deliver(researcher, repair, seed); - expect(candidate.status).toBe('blocked'); expect(checker).toHaveBeenCalledTimes(1); - }); - - const publishGap = async (extra: Record = {}, sources?: Record) => { - const consumer = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.task; - await (cooperative as any).receive(researcher, action, { id: 'mathematical-gap', kind: 'research', - taskId: action.task.id, taskDigest: action.assignment.taskDigest, ...(sources ? { sources } : {}), finding: { - summary: 'The classification input is unavailable; no declaration was proved.', conclusion: 'inconclusive', needsDecision: true, - mathematicalGap: { consumer: { taskId: consumer.id, taskDigest: taskVersion(consumer) }, previousGap: 'Critical-set sufficiency', - reduced: 'Only elementary rank reduction is checked', remaining: 'The independent classification theorem is still missing', - evidenceScope: 'Advisory report; no Lean proof', reconsiderWhen: ['A checked classification input or a genuinely different plan'] }, - ...extra, - } }); - }; - const missingCandidate = () => { - const source = 'theorem goal : True := by sorry\n'; - reseed(source); - state.problem = { ...state.problem, targets: [{ proofPath: 'Submission.lean', theoremName: 'goal', - declarationHash: hashMathFormalSourceDeclaration(source, 'goal')! }] }; - checker.mockRejectedValue(new Error(missing)); - }; - - it('keeps a current mathematical gap blocked after transport-only recoveries', async () => { - missingCandidate(); - const work = await recoverUntouched(); - await publishGap(); - await cooperative.deliver(researcher, work, seed); - expect(candidate.status).toBe('blocked'); - expect(state.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - expect(emit.mock.calls.some(([event]) => event === 'task_repair_requested')).toBe(false); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState, resumed = create(restored); - await resumed.restore(); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - expect(restored.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - }); - - it('blocks an unchanged absent theorem with a current mathematical gap instead of granting local repair', async () => { - missingCandidate(); await publishGap(); - await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('blocked'); expect(candidate.attempts).toBe(1); - expect(state.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - expect(candidate.proof).toBeUndefined(); expect(candidate.integratedCheck).toBeUndefined(); - expect(emit.mock.calls.some(([event]) => event === 'task_repair_requested')).toBe(false); - expect(emit).toHaveBeenCalledWith('task_mathematical_gap_blocked', expect.objectContaining({ taskId: 'candidate' })); - expect(await cooperative.next(lead, budget)).toMatchObject({ kind: 'lead' }); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState, resumed = create(restored); - await resumed.restore(); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - expect(restored.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - }); - - it('persists the mathematical stop before delivery publication so restore cannot invent a repair', async () => { - missingCandidate(); await publishGap(); - await expect(check()).rejects.toThrow('math_task_missing_declaration'); - expect(candidate.status).toBe('blocked'); - expect(state.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState, resumed = create(restored); - await resumed.restore(); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - expect(restored.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - }); - - it('hands a missing declaration with frozen new supporting sources and a current gap to Lead', async () => { - missingCandidate(); - fs.appendFileSync(sourceFile(), 'lemma supporting : True := by trivial\n'); - const source = fs.readFileSync(sourceFile(), 'utf8'), head = git(directory, ['rev-parse', 'HEAD']); - await publishGap({}, { 'Submission.lean': source }); - expect(git(directory, ['rev-parse', 'HEAD'])).toBe(head); - const [report] = state.cooperation!.deliveries!; - expect(report.artifacts?.artifacts[0].declarations).toMatchObject([{ name: 'supporting', draft: false }]); - seed = commit('The target is still unproved; supporting code and its exact gap are retained.'); - await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('blocked'); expect(candidate.attempts).toBe(1); - expect(state.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - expect(candidate.proof).toBeUndefined(); expect(candidate.integratedCheck).toBeUndefined(); - expect(emit.mock.calls.some(([event]) => event === 'task_repair_requested')).toBe(false); - expect(await cooperative.next(lead, budget)).toMatchObject({ kind: 'lead' }); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState, resumed = create(restored); - await resumed.restore(); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - expect(restored.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - }); - - it('keeps local repair when a source snapshot gap predates further Lean source edits', async () => { - missingCandidate(); - fs.appendFileSync(sourceFile(), 'lemma supporting : True := by trivial\n'); - await publishGap({}, { 'Submission.lean': fs.readFileSync(sourceFile(), 'utf8') }); - fs.appendFileSync(sourceFile(), 'lemma later_support : True := by trivial\n'); - seed = commit(); - await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('pending'); - expect(state.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - expect(candidate.proof).toBeUndefined(); expect(candidate.integratedCheck).toBeUndefined(); - expect(emit.mock.calls.some(([event]) => event === 'task_mathematical_gap_blocked')).toBe(false); - }); - - it.each(['checkpoint', 'request-failure'] as const)('keeps a current mathematical gap blocked after %s recovery', async recovery => { - missingCandidate(); await publishGap(); - await cooperative.deliver(researcher, action, seed, true, recovery); - expect(candidate.status).toBe('blocked'); expect(candidate.attempts).toBe(1); - expect(state.cooperation!.failedTaskInputs![0].repair).toBeUndefined(); - expect(emit.mock.calls.some(([event]) => event === 'task_checkpoint_continuation_requested')).toBe(false); - expect(emit.mock.calls.some(([event]) => event === 'task_repair_requested')).toBe(false); - expect(await cooperative.next(lead, budget)).toMatchObject({ kind: 'lead' }); - }); - - it('records no failed input for a request failure on the untouched seed, so the first real checkpoint continues', async () => { - missingCandidate(); - const resume = async () => { - const work = await cooperative.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); - if (work?.kind !== 'task') throw new Error('expected_resumed_assignment'); - expect(cooperative.started(researcher, work)).toBe(true); return work; - }; - for (let index = 0; index < 3; index++) { - await cooperative.deliver(researcher, index ? await resume() : action, seed, true, 'request-failure'); - expect(candidate.status).toBe('pending'); expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - } - expect(checker).not.toHaveBeenCalled(); - expect(emit.mock.calls.some(([event]) => event === 'task_failed_input_recorded')).toBe(false); - const notesOnly = commit('Planned the bridge; no Lean edit yet.'); - await cooperative.deliver(researcher, await resume(), notesOnly, true, 'scheduling-checkpoint'); - expect(candidate.status).toBe('pending'); - expect(state.cooperation!.failedTaskInputs).toMatchObject([{ feedback: missing, repair: { pending: true } }]); - await cooperative.deliver(researcher, await resume(), notesOnly, true, 'scheduling-checkpoint'); - expect(candidate.status).toBe('blocked'); expect(candidate.feedback).toMatch(/^math_task_repeated_failed_input\n/u); - }); - - it.each(['no-decision', 'historical-consumer', 'changed-source', 'different-assignment'] as const)( - 'keeps missing declaration repair for a %s gap report', async scenario => { - missingCandidate(); await publishGap(scenario === 'no-decision' ? { needsDecision: false } : {}); - if (scenario === 'historical-consumer') { - const consumer = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!; - consumer.task = { ...consumer.task, revision: 1 }; - } else if (scenario === 'changed-source') { - fs.appendFileSync(sourceFile(), 'lemma supporting : True := by trivial\n'); seed = commit(); - } else if (scenario === 'different-assignment') action.assignment.assignmentId = 'new-assignment'; - await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('pending'); expect(state.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - }); - - it('retains deterministic compile repair even when a mathematical gap was reported', async () => { - await publishGap(); await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('pending'); expect(state.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it('reopens the mathematical stop for a changed typed contract without accepting the reported gap', async () => { - missingCandidate(); await publishGap(); await cooperative.deliver(researcher, action, seed); - candidate.task = { ...candidate.task, type: '1 = 1', revision: 1 }; - candidate.assignment!.taskDigest = taskVersion(candidate.task); - (cooperative as any).refreshFailedTaskInputs(); - expect(candidate.status).toBe('pending'); expect(candidate.proof).toBeUndefined(); - await cooperative.deliver(researcher, { kind: 'task', task: candidate.task, assignment: candidate.assignment! }, seed); - expect(state.cooperation!.failedTaskInputs).toHaveLength(2); - expect(state.cooperation!.failedTaskInputs![1].repair?.pending).toBe(true); - }); - - it.each(['transport', 'restart'] as const)('preserves an uncompleted repair after %s before a source edit', async interruption => { - await cooperative.deliver(researcher, action, seed); - let work = await cooperative.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); - if (work?.kind !== 'task') throw new Error('expected_local_repair'); - expect(cooperative.started(researcher, work)).toBe(true); - let current = cooperative, currentState = state; - if (interruption === 'restart') { - currentState = JSON.parse(JSON.stringify(state)) as SolverRunState; - current = create(currentState); await current.restore(); - } else await current.deliver(researcher, work, seed, true, 'request-failure'); - expect(currentState.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - work = await current.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); - if (work?.kind !== 'task') throw new Error('expected_resumed_repair'); - expect(current.started(researcher, work)).toBe(true); - await current.deliver(researcher, work, seed); - expect(currentState.cooperation!.tasks[0].status).toBe('blocked'); - expect(currentState.cooperation!.failedTaskInputs![0].repair).toMatchObject({ pending: false }); - expect(currentState.cooperation!.failedTaskInputs![0].repair?.startedAttempt).toBeUndefined(); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it.each(['checkpoint', 'request-failure'] as const)('continues successive changed drafts after %s without a turn limit', async kind => { - let work = action, version = seed; - for (let index = 0; index < 4; index++) { - fs.writeFileSync(sourceFile(), `lemma candidate : True := by exact FAILURE_${index}\n`); version = commit(); - await cooperative.deliver(researcher, work, version, true, kind); - expect(candidate.status).toBe('pending'); - const next = await cooperative.next(researcher, budget); - expect(next).toMatchObject({ kind: 'task', task: { id: candidate.task.id } }); - if (next?.kind !== 'task') throw new Error('expected_changed_draft_continuation'); - expect(cooperative.started(researcher, next)).toBe(true); work = next; - } - expect(candidate.attempts).toBe(5); expect(checker).toHaveBeenCalledTimes(4); - await cooperative.deliver(researcher, work, version, true, 'checkpoint'); - expect(candidate.status).toBe('blocked'); expect(checker).toHaveBeenCalledTimes(4); - }); - - it('restores the first repair after failure persistence before delivery publication', async () => { - await check(); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState; - delete restored.cooperation!.failedTaskInputs![0].repair; - const resumed = create(restored); await resumed.restore(); - expect(restored.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - const work = await resumed.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: 'candidate' } }); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it('keeps one repair after duplicate live proof receipts and completed delivery', async () => { - const submission = { id: 'first', kind: 'proof', taskId: candidate.task.id, taskDigest: action.assignment.taskDigest, - commit: seed, summary: 'The saved candidate.' }; - await (cooperative as any).receive(researcher, action, submission); - await (cooperative as any).receive(researcher, action, { ...submission, id: 'second' }); - await cooperative.deliver(researcher, action, seed); - expect(candidate.status).toBe('pending'); expect(candidate.attempts).toBe(1); - expect(state.cooperation!.failedTaskInputs![0].repair?.pending).toBe(true); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it('blocks a revision, prose and missing-helper rename before dispatch while independent research remains ready', async () => { - reseed('theorem goal : True := by sorry\n'); - checker.mockRejectedValue(new Error(missing)); await exhaustRepair(); - candidate.task = { ...candidate.task, id: 'renamed', theoremName: 'new_helper', revision: 7, objective: 'A different description.' }; - candidate.status = 'pending'; candidate.attempts = 0; candidate.assignment = undefined; candidate.proof = undefined; - state.cooperation!.tasks[1].task = task('goal', 'goal', ['renamed']); - state.cooperation!.tasks.push({ task: task('investigate', 'research'), status: 'pending', attempts: 0 }); - const work = await cooperative.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: 'investigate' } }); - expect(candidate.status).toBe('blocked'); expect(candidate.attempts).toBe(0); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it('dispatches an independent declaration of the same type while an absent helper stays blocked', async () => { - reseed('theorem goal : True := by sorry\n'); - checker.mockRejectedValue(new Error(missing)); await exhaustRepair(); - const independent: TaskRecord = { task: task('independent'), status: 'pending', attempts: 0 }; - state.cooperation!.tasks.push(independent); - (cooperative as any).refreshFailedTaskInputs(); - expect(candidate.status).toBe('blocked'); expect(independent.status).toBe('pending'); - expect(await cooperative.next(researcher, budget)).toMatchObject({ kind: 'task', task: { id: independent.task.id } }); - expect(checker).toHaveBeenCalledOnce(); - }); - - it('preserves failure and unused repair records across serialization and restore', async () => { - await cooperative.deliver(researcher, action, seed); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState, resumed = create(restored); - await resumed.restore(); - const work = await resumed.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: 'candidate' } }); - if (work?.kind !== 'task') throw new Error('expected_restored_repair'); - expect(resumed.started(researcher, work)).toBe(true); - await resumed.deliver(researcher, work, seed); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - expect(restored.cooperation!.failedTaskInputs![0].repair?.pending).toBe(false); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it('reopens a failed assignment after changed Lean bytes owned by its current session', async () => { - await exhaustRepair(); - fs.writeFileSync(sourceFile(), 'lemma candidate : True := by exact NEW_ATTEMPT\n'); - const version = commit(); - const work = await cooperative.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: 'candidate' } }); - await check(version); expect(checker).toHaveBeenCalledTimes(2); - expect(state.cooperation!.failedTaskInputs).toHaveLength(2); - }); - - it('does not reopen an old failure from a worktree reused for another task', async () => { - await exhaustRepair(); - state.workers = [{ id: researcher.id, sessionTaskId: 'different', sessionTaskVersion: 'different' }] as SolverRunState['workers']; - fs.writeFileSync(sourceFile(), 'lemma unrelated : True := by trivial\n'); commit(); - (cooperative as any).changed(); - expect(candidate.status).toBe('blocked'); expect(candidate.feedback).toContain('math_task_repeated_failed_input'); - }); - - it.each(['premises', 'type', 'environment', 'environment-variable', 'build', 'evaluator', 'conditions'] as const)( - 'permits a new check after changed %s inputs', async change => { - await check(); - if (change === 'premises') candidate.task = { ...candidate.task, premises: ['A new explicit premise.'] }; - else if (change === 'type') candidate.task = { ...candidate.task, type: '1 = 1' }; - else if (change === 'environment') state.environmentDigest = 'new-environment'; - else if (change === 'environment-variable') (cooperative as any).input.access.get(lead.id).environment.LEAN_PATH = '/new/path'; - else if (change === 'build') state.buildDigest = 'new-build'; - else if (change === 'evaluator') state.evaluatorDigest = 'new-evaluator'; - candidate.assignment!.taskDigest = taskVersion(candidate.task); - await check(seed, change === 'conditions' ? [task('assumption')] : undefined); - expect(checker).toHaveBeenCalledTimes(2); - }); - - it('does not reset a deterministic failure when only the checker timeout changes', async () => { - await check(); (cooperative as any).input.timeoutMs = Infinity; - await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - (cooperative as any).input.timeoutMs = 999; - await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it('keeps recurrence stable after unrelated shell environment changes on restart', async () => { - await check(); - Object.assign((cooperative as any).input.access.get(lead.id).environment, { PWD: '/other', SHLVL: '3', TERM: 'xterm' }); - await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - expect(checker).toHaveBeenCalledTimes(1); - }); - - const checkedDependency = () => { - const dependency = accepted({ task: task('dependency'), status: 'integrated', attempts: 1 }, - 'lemma dependency : True := by trivial\n', 'first'); - state.cooperation!.tasks.push(dependency); candidate.task = { ...candidate.task, dependsOn: ['dependency'] }; - candidate.assignment!.taskDigest = taskVersion(candidate.task); - return dependency; - }; - - it.each(['environment', 'environment-variable', 'build', 'evaluator'] as const)( - 'keeps an absent mathematical declaration blocked after only %s changes', async change => { - missingCandidate(); await publishGap(); await cooperative.deliver(researcher, action, seed); - (cooperative as any).refreshFailedTaskInputs(); emit.mockClear(); - if (change === 'environment') state.environmentDigest = 'new-environment'; - else if (change === 'environment-variable') (cooperative as any).input.access.get(lead.id).environment.LEAN_PATH = '/new/path'; - else if (change === 'build') state.buildDigest = 'new-build'; - else state.evaluatorDigest = 'new-evaluator'; - (cooperative as any).refreshFailedTaskInputs(); - expect(candidate.status).toBe('blocked'); - await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - expect(checker).toHaveBeenCalledTimes(1); expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - expect(emit.mock.calls.some(([event]) => event === 'task_failed_input_reopened')).toBe(false); - }); - - it('keeps an absent declaration blocked across environment changes and loss of dependency acceptance on restart', async () => { - missingCandidate(); checkedDependency(); action = { kind: 'task', task: candidate.task, assignment: candidate.assignment! }; - await publishGap(); await cooperative.deliver(researcher, action, seed); - (cooperative as any).refreshFailedTaskInputs(); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState; - restored.environmentDigest = 'new-environment'; const resumed = create(restored); - (resumed as any).refreshFailedTaskInputs(); - expect(restored.cooperation!.tasks[0].status).toBe('blocked'); - await expect(check(seed, undefined, resumed)).rejects.toThrow('math_task_repeated_failed_input'); - expect(checker).toHaveBeenCalledTimes(1); expect(restored.cooperation!.failedTaskInputs).toHaveLength(1); - }); - - it('reopens an absent declaration for a changed checked dependency even across environment changes', async () => { - missingCandidate(); const dependency = checkedDependency(); - action = { kind: 'task', task: candidate.task, assignment: candidate.assignment! }; - await publishGap(); await cooperative.deliver(researcher, action, seed); - (cooperative as any).refreshFailedTaskInputs(); - state.environmentDigest = 'new-environment'; - dependency.integratedCheck!.changes[0].after = 'lemma dependency : True := by exact True.intro\n'; - markTaskAcceptance(dependency.integratedCheck!); - (cooperative as any).refreshFailedTaskInputs(); - expect(candidate.status).toBe('pending'); - await expect(check()).rejects.toThrow('math_task_missing_declaration'); - expect(checker).toHaveBeenCalledTimes(2); expect(state.cooperation!.failedTaskInputs).toHaveLength(2); - }); - - it.each(['support', 'target'] as const)('reopens an absent declaration after changed %s source', async change => { - missingCandidate(); await publishGap(); await cooperative.deliver(researcher, action, seed); - (cooperative as any).refreshFailedTaskInputs(); state.environmentDigest = 'new-environment'; - fs.appendFileSync(sourceFile(), `lemma ${change === 'target' ? 'candidate' : 'supporting'} : True := by trivial\n`); - const version = commit(); - (cooperative as any).refreshFailedTaskInputs(); expect(candidate.status).toBe('pending'); - await expect(check(version)).rejects.toThrow('math_task_missing_declaration'); - expect(checker).toHaveBeenCalledTimes(2); expect(state.cooperation!.failedTaskInputs).toHaveLength(2); - }); - - it('does not suppress an environment repair for a missing-declaration rejection with a present source target', async () => { - checker.mockRejectedValue(new Error(missing)); - await expect(check()).rejects.toThrow('math_task_missing_declaration'); - state.environmentDigest = 'new-environment'; - await expect(check()).rejects.toThrow('math_task_missing_declaration'); - expect(checker).toHaveBeenCalledTimes(2); - }); - - it('allows a different checked route to reopen an absent declaration after an environment change', async () => { - missingCandidate(); candidate.task = task('candidate', 'goal'); candidate.assignment!.taskDigest = taskVersion(candidate.task); - action = { kind: 'task', task: candidate.task, assignment: candidate.assignment! }; - const branches = ['left', 'right'].map(id => - accepted({ task: task(id), status: 'integrated', attempts: 1 }, `lemma ${id} : True := by trivial\n`, id)); - state.cooperation!.tasks.push(...branches); - state.cooperation!.proofRoutes = branches.map(record => ({ id: `via_${record.task.id}`, targetTaskId: candidate.task.id, - prerequisiteTaskIds: [], closingTaskId: record.task.id })); - (cooperative as any).syncProofRoutes(); candidate.assignment!.routeId = 'via_left'; - await exhaustRepair(); state.environmentDigest = 'new-environment'; - (cooperative as any).refreshFailedTaskInputs(); expect(candidate.status).toBe('blocked'); - candidate.assignment!.routeId = 'via_right'; - (cooperative as any).refreshFailedTaskInputs(); expect(candidate.status).toBe('pending'); - await expect(check()).rejects.toThrow('math_task_missing_declaration'); - expect(checker).toHaveBeenCalledTimes(2); - }); - - it('ignores dependency receipt replay and whole-file metadata but allows new checked declaration evidence', async () => { - const dependency = checkedDependency(); await check(); - dependency.integratedCheck!.sourceDigest = 'unrelated-whole-file-change'; - dependency.integratedCheck!.verification.results[0].receiptId = 'replayed'; - markTaskAcceptance(dependency.integratedCheck!); - await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - dependency.integratedCheck!.changes[0].after = 'lemma dependency : True := by exact True.intro\n'; - markTaskAcceptance(dependency.integratedCheck!); - await check(); expect(checker).toHaveBeenCalledTimes(2); - }); - - it('does not treat loss of a fresh dependency acceptance after restart as new mathematical input', async () => { - checkedDependency(); await check(); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState, resumed = create(restored); - await expect(check(seed, undefined, resumed)).rejects.toThrow('math_task_repeated_failed_input'); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it.each(['retained', 'reset'] as const)('switches to a different checked OR branch after failure with a %s assignment', async assignment => { - candidate.task = task('candidate', 'goal'); candidate.assignment!.taskDigest = taskVersion(candidate.task); - action = { kind: 'task', task: candidate.task, assignment: candidate.assignment! }; - const branches = ['left', 'right'].map(id => - accepted({ task: task(id), status: 'integrated', attempts: 1 }, `lemma ${id} : True := by trivial\n`, id)); - state.cooperation!.tasks.push(...branches); - state.cooperation!.proofRoutes = branches.map(record => ({ id: `via_${record.task.id}`, targetTaskId: candidate.task.id, - prerequisiteTaskIds: [], closingTaskId: record.task.id })); - (cooperative as any).syncProofRoutes(); candidate.assignment!.routeId = 'via_left'; - await exhaustRepair(); - if (assignment === 'reset') { - candidate.assignment = undefined; candidate.proof = undefined; candidate.status = 'pending'; - } - const research: TaskRecord = { task: task('investigate', 'research'), status: 'pending', attempts: 0 }; - state.cooperation!.tasks.push(research); - const independent = await cooperative.next(researcher, budget); - expect(independent).toMatchObject({ kind: 'task', task: { id: 'investigate' } }); - expect(candidate.status).toBe('blocked'); expect(checker).toHaveBeenCalledTimes(1); - if (assignment === 'retained') expect(candidate.assignment?.routeId).toBe('via_left'); - research.status = 'completed'; branches[0].status = 'blocked'; - const alternate = await cooperative.next(researcher, budget); - expect(alternate).toMatchObject({ kind: 'task', task: { id: 'candidate' }, assignment: { routeId: 'via_right' } }); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it('serializes identical in-flight candidates before persisting a deterministic failure', async () => { - const { promise: pending, resolve: release } = deferred(); - checker.mockImplementationOnce(async (_problem, worktree, version, obligation, assignment, _goals, _env, _signal, _timeout, conditions) => { - await pending; return failure(worktree, version, obligation, assignment, conditions); - }); - const first = check(), repeated = check(); release(); - const results = await Promise.allSettled([first, repeated]); - expect(results.map(result => result.status)).toEqual(['fulfilled', 'rejected']); - expect(checker).toHaveBeenCalledTimes(1); - }); - - it.each(['unavailable', 'blocked', 'cleanup', 'no-diagnostics'] as const)('does not persist %s verification as a mathematical failure', async kind => { - failWith(proof => { - if (kind === 'unavailable' || kind === 'blocked') proof.verification.status = kind; - else if (kind === 'cleanup') proof.verification.results[0].cleanupError = 'Temporary checkout unavailable.'; - else proof.verification.results[0].stdoutPreview = 'Request timed out before diagnostics.'; - }); - await check(); await check(); - expect(checker).toHaveBeenCalledTimes(2); expect(state.cooperation!.failedTaskInputs).toBeUndefined(); - }); - - it.each(['sorry', 'admit'] as const)('persists an explicit %s rejection even without compiler diagnostics', async kind => { - failWith(proof => { - proof.verification.results[0].stdoutPreview = undefined; - proof.verification.results[0][kind === 'sorry' ? 'sorryCount' : 'admitCount'] = 1; - }); - await check(); await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - expect(checker).toHaveBeenCalledTimes(1); expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - }); - - it.each(['Invalid authentication', 'Request failed: rate limit', 'Request timed out'])( - 'ignores a transient verifier error even if a result retains diagnostics: %s', async error => { - failWith(proof => { proof.verification.results[0].error = error; }); - await check(); await check(); - expect(checker).toHaveBeenCalledTimes(2); expect(state.cooperation!.failedTaskInputs).toBeUndefined(); - }); - - it.each(['Invalid authentication', '429 rate limit', 'stream disconnected before completion'])( - 'does not persist a transient request failure: %s', async message => { - checker.mockRejectedValue(new Error(message)); - await expect(check()).rejects.toThrow(message); await expect(check()).rejects.toThrow(message); - expect(checker).toHaveBeenCalledTimes(2); expect(state.cooperation!.failedTaskInputs).toBeUndefined(); - }); - - it.each(['integrated', 'conditional', 'delivered', 'pending'] as const)('preserves a current passed proof in %s state', async status => { - await check(); candidate.status = status; - candidate.proof = { ...failure(directory, seed, candidate.task, candidate.assignment!), passed: true }; - (cooperative as any).changed(); - expect(candidate.status).toBe(status); expect(candidate.proof.passed).toBe(true); - }); - - it('allows a different already saved proof of the same type after a missing target', async () => { - reseed('lemma available : True := by trivial\n'); - checker.mockRejectedValueOnce(new Error(missing)); await cooperative.deliver(researcher, action, seed); - candidate.task = { ...candidate.task, theoremName: 'available' }; - candidate.assignment!.taskDigest = taskVersion(candidate.task); - expect(await cooperative.next(researcher, budget)).toMatchObject({ kind: 'task', task: { theoremName: 'available' } }); - checker.mockImplementation(async (_problem, worktree, version, obligation, assignment) => { - const proof = failure(worktree, version, obligation, assignment), taskDigest = taskVersion(obligation); - return { ...proof, passed: true, verification: { status: 'kernel_verified', targetCommit: version, - results: [{ status: 'kernel_verified', targetCommit: version, proofPath: obligation.proofPath, - theoremName: obligation.theoremName, statementHash: taskDigest, leanStatementHash: taskDigest, claim: 'statement', - receiptId: 'checked-available-proof', - sourceDeclarationHash: hashMathFormalSourceDeclaration(fs.readFileSync(sourceFile(), 'utf8'), obligation.theoremName!) }] } } as TaskProof; - }); - const passed = await check(); - expect(passed.passed).toBe(true); expect(checker).toHaveBeenCalledTimes(2); - }); - - it('separates saved same-body targets with different namespace and notation contexts', async () => { - reseed('namespace Bad\nlocal notation "witness" => (0 : Nat)\nlemma bad : True := by exact witness\nend Bad\n' + - 'namespace Good\nlocal notation "witness" => True.intro\nlemma good : True := by exact witness\nend Good\n'); - candidate.task = { ...candidate.task, theoremName: 'Bad.bad' }; - candidate.assignment!.taskDigest = taskVersion(candidate.task); - await check(); - candidate.task = { ...candidate.task, theoremName: 'Good.good' }; - candidate.assignment!.taskDigest = taskVersion(candidate.task); - await check(); - expect(checker).toHaveBeenCalledTimes(2); - }); -}); diff --git a/tests/researchArchive.test.ts b/tests/researchArchive.test.ts index 7ff34365..ee430903 100644 --- a/tests/researchArchive.test.ts +++ b/tests/researchArchive.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { canonicalMathJson } from '../src/math/mathRuntimeIo'; +import { canonicalMathJson, createMathJsonCheckpointWriter } from '../src/math/mathRuntimeIo'; import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; import { captureResearchBasis, settleResearch } from '../src/solver/researchRecords'; import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; @@ -56,6 +56,21 @@ describe('research completion archive schema', () => { expect(fs.statSync(file).mode & 0o777).toBe(0o600); }); + it('persists deleted and truncated array slots without losing later entries or accepting undefined', () => { + const file = path.join(root, 'checkpoint.json'), write = createMathJsonCheckpointWriter(); + const entries: (string | undefined)[] = ['first', 'removed', 'last']; + write(file, entries); + delete entries[1]; + write(file, entries); + expect(fs.readFileSync(file, 'utf8')).toBe('["first",null,"last"]'); + entries.length = 2; + write(file, entries); + expect(fs.readFileSync(file, 'utf8')).toBe('["first",null]'); + entries[1] = undefined; + expect(() => write(file, entries)).toThrow('math_runtime_invalid_json'); + expect(fs.readFileSync(file, 'utf8')).toBe('["first",null]'); + }); + it.each([undefined, [], ['relevant-candidate']])('preserves the automatic candidate filter independently of the raw pool: %j', relevant => { state.knowledgeRetrievals = { dropped: 0, observations: [{ sectionId: 'knowledge:route', catalogDigest: 'fixture-catalog', searchInputDigest: 'fixture-search', diff --git a/tests/researchDurableCheckpoint.test.ts b/tests/researchDurableCheckpoint.test.ts deleted file mode 100644 index 64900282..00000000 --- a/tests/researchDurableCheckpoint.test.ts +++ /dev/null @@ -1,292 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { acceptContextCheckpoint } from '../src/solver/contextCheckpoint'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { committedSource } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import { parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -describe('durable advisory research checkpoints', () => { - const roots: string[] = [], controllers: AbortController[] = [], running: Promise[] = []; - beforeEach(() => { - vi.useFakeTimers(); - vi.spyOn(CooperativeResearch.prototype, 'restore').mockImplementation(async () => {}); - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - }); - afterEach(async () => { - controllers.forEach(controller => controller.abort()); - await Promise.allSettled(running); - vi.useRealTimers(); vi.restoreAllMocks(); - roots.splice(0).forEach(root => fs.rmSync(root, { recursive: true, force: true })); - controllers.splice(0); running.splice(0); - }); - - function fixture(options: { notes?: string; turns?: number; kind?: 'research' | 'sketch'; feasibility?: boolean } = {}) { - const example = localExample('research-durable-checkpoint-'); roots.push(example.directory); - const { directory, workspace, problem } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'researcher')]; - const notesFile = path.join(workers[1].worktree, 'RESEARCH.md'); - if (options.notes !== undefined) fs.writeFileSync(notesFile, options.notes); - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index + 1}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, ...target, status: 'paused' })), - { id: 'investigate', kind: options.kind ?? 'research', ownerId: 'researcher', objective: 'Resolve the precise missing construction.', - ...(options.feasibility ? { reviewScope: 'feasibility' } : {}) }, - ] }); - const state = solverState(problem, workspace, { runId: 'durable-research-fixture', phase: 'prepared', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const check = vi.fn(async () => { throw new Error('fixture_unexpected_proof_acceptance'); }); - const events: { event: string; details?: Record }[] = []; - const controller = new AbortController(); controllers.push(controller); - const count = options.turns ?? 1; - const started = Array.from({ length: count }, () => deferred()); - const done = Array.from({ length: count }, () => deferred()); - const actions: Extract[] = []; - let active: ReturnType> | undefined, turn = 0; - let sessionOptions: MathAgentOptions; - const interrupt = vi.fn(async () => { active?.resolve('interrupted'); }); - const notify = vi.fn(async (_message: string) => {}); - const open = vi.fn(async (settings: MathAgentOptions): Promise => { - sessionOptions = settings; - return { threadId: 'durable-research-thread', interrupt, notify, - close: async () => { active?.resolve('interrupted'); }, - run: async (message, _messageId, _workspace, onStarted) => { - const index = turn++, action = JSON.parse(message) as CooperativeAction; - if (index >= count || action.kind !== 'task' || action.task.id !== 'investigate') - throw new Error('fixture_unexpected_turn'); - actions.push(action); active = done[index]; onStarted(`research-turn-${index}`); - settings.onActivity?.({ event: 'reasoning' }); started[index].resolve(); - return done[index].promise; - } }; - }); - const modules: SolverModules = { ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M2: { ...directSolverModules.M2, check, checkTask: check }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Offline durable checkpoint fixture.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }) } }; - const run = () => { - const completion = runResearchWorkers({ state, workers, modules, access: workerAccess(workers, directory), - root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original targets.', - executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, - deadline: Infinity, maxTurnMs: Infinity, maxTurns: count, maxTotalTokens: 0, - goalProgressReviewMs: 24 * 3_600_000, save: () => {}, emit: (event, details) => events.push({ event, details }) }); - running.push(completion); void completion.catch(() => {}); return completion; - }; - const activity = (event: Parameters>[0]) => sessionOptions.onActivity?.(event); - const tool = (save?: string) => { - activity({ event: 'item_started', itemType: 'commandExecution' }); - if (save !== undefined) fs.writeFileSync(notesFile, save); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - }; - const reachSlice = async (completion: Promise, index = 0) => { - await Promise.race([started[index].promise, completion.then(() => { throw new Error('fixture_turn_did_not_start'); })]); - const sliceMs = events.filter(item => item.event === 'cooperative_checkpoint_scheduled').at(-1)!.details!.checkpointAfterMs as number; - await vi.advanceTimersByTimeAsync(sliceMs - 30_000); activity({ event: 'reasoning' }); - await vi.advanceTimersByTimeAsync(30_000); - }; - return { state, workers, notesFile, events, check, controller, notify, interrupt, open, run, tool, activity, reachSlice, - wait: (index: number) => started[index].promise, settle: (index: number, status: string) => done[index].resolve(status), actions }; - } - - it('reminds an independent reviewer to save reproducible work without yielding, then preserves its context handoff', async () => { - const f = fixture({ feasibility: true }), completion = f.run(); await f.wait(0); - const schedule = f.events.find(event => event.event === 'cooperative_checkpoint_scheduled')!; - expect(schedule.details).toMatchObject({ noticeOnly: true, noProgressStreak: 0 }); - await vi.advanceTimersByTimeAsync(35 * 60_000); - expect(f.notify).toHaveBeenCalledOnce(); - expect(f.notify.mock.calls[0][0]).toContain('A scratch path alone is not a recoverable probe'); - expect(f.notify.mock.calls[0][0]).toContain('exact failed search scope'); - expect(f.interrupt).not.toHaveBeenCalled(); - const notes = 'Checked only finite independent families; no uniform construction found in the searched declarations.\r\n' + - 'Probe .scratch/tmp/Probe1.lean, rerun with: lake env lean .scratch/tmp/Probe1.lean\r\n' + - '```lean\r\nimport Mathlib\r\n#check Finset.sum_eq_single\r\n```\r\n' + - 'Observed result: the local probe succeeds; the infinite-family inference remains unproved.\r\n' + - '```math-result\n{"summary":"Provisional only","conclusion":"supporting"}\n```\n'; - f.tool(notes); - const research = f.state.workers![1]; - research.contextCheckpoint = { threadId: research.threadId!, requestedAt: Date.now(), requestId: 'review-handoff' }; - acceptContextCheckpoint(research, f.workers[1].worktree, - { kind: 'checkpoint', requestId: 'review-handoff', notesDigest: mathDigest(notes) }); - await vi.advanceTimersByTimeAsync(5_000); await expect(completion).resolves.toBeUndefined(); - const draft = f.state.cooperation!.researchDrafts!.investigate; - expect(committedSource(f.workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(notes); - expect(draft).toMatchObject({ handoffNotesDigest: mathDigest(notes), - feasibilityInputDigest: f.actions[0].assignment.feasibilityInputDigest }); - const node = f.state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - expect(node.status).toBe('pending'); expect(node.researchCompletion).toBeUndefined(); - expect(f.state.cooperation!.researchCheckpoints?.investigate).toBeUndefined(); - expect(f.state.cooperation!.deliveries?.filter(record => record.kind === 'research') ?? []).toEqual([]); - expect(f.check).not.toHaveBeenCalled(); expect(f.interrupt).toHaveBeenCalledOnce(); - }); - - it('opens a fresh independent reviewer thread when inspection inputs change between interrupted turns', async () => { - const f = fixture({ feasibility: true, turns: 2 }), completion = f.run(); await f.wait(0); - f.tool('Old-library review notes; still no verdict.\n'); - f.state.knowledgeDigest = mathDigest('new inspected library knowledge'); - f.settle(0, 'interrupted'); await f.wait(1); - expect(f.actions[1].assignment.assignmentId).not.toBe(f.actions[0].assignment.assignmentId); - expect(f.actions[1].assignment.feasibilityInputDigest).not.toBe(f.actions[0].assignment.feasibilityInputDigest); - expect(f.open).toHaveBeenCalledTimes(2); - expect(f.open.mock.calls[1][0].threadId).toBeUndefined(); - expect(f.events).toContainEqual(expect.objectContaining({ event: 'context_restarted', - details: expect.objectContaining({ reason: 'responsibility' }) })); - expect(fs.readFileSync(f.notesFile, 'utf8')).toBe(''); - f.settle(1, 'interrupted'); await expect(completion).resolves.toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); - }); - - it.each([undefined, ' \n\t', 'Inherited notes from a different responsibility.\n'])( - 'keeps a search result open until the current assignment saves notes (seed: %j)', async notes => { - const f = fixture({ notes }), completion = f.run(); - await f.reachSlice(completion); await vi.advanceTimersByTimeAsync(10_000); - if (notes !== undefined) - expect(committedSource(f.workers[1].worktree, f.actions[0].assignment.seedCommit, 'RESEARCH.md')).toBe(notes); - f.tool(); await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).not.toHaveBeenCalled(); - expect(f.events.filter(event => event.event === 'research_handoff_requested')).toHaveLength(1); - expect(f.notify.mock.calls.at(-1)![0]).toContain('do not invent a finding or proof'); - // The first search's completion is not the requested handoff. A later write gets its own result. - await vi.advanceTimersByTimeAsync(30_000); - const handoff = 'The checked reduction uses the finite basis identity; the uniform estimate remains unresolved.\n'; - f.tool(handoff); await expect(completion).resolves.toBeUndefined(); - expect(f.interrupt).toHaveBeenCalledOnce(); - const draft = f.state.cooperation!.researchDrafts!.investigate; - expect(committedSource(f.workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(handoff); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.proof).toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); - expect(f.events.some(event => event.event === 'research_checkpoint_missing_notes')).toBe(false); - expect(vi.getTimerCount()).toBe(0); - }); - - it('waits for a running search tool at the slice end before accepting a later notes write', async () => { - const f = fixture(), completion = f.run(); - await f.wait(0); await vi.advanceTimersByTimeAsync(90_000); - f.activity({ event: 'item_started', itemType: 'commandExecution' }); - await vi.advanceTimersByTimeAsync(30_000); - expect(f.interrupt).not.toHaveBeenCalled(); - f.activity({ event: 'item_completed', itemType: 'commandExecution' }); - await vi.advanceTimersByTimeAsync(0); expect(f.interrupt).not.toHaveBeenCalled(); - f.tool('Search result: the relevant module lacks this exact premise; the next step is to prove the estimate.\n'); - await expect(completion).resolves.toBeUndefined(); expect(f.interrupt).toHaveBeenCalledOnce(); - }); - - it('finishes a notes write spanning the slice end before freezing the saved handoff', async () => { - const f = fixture(), completion = f.run(); - await f.wait(0); await vi.advanceTimersByTimeAsync(90_000); - f.activity({ event: 'item_started', itemType: 'commandExecution' }); - fs.writeFileSync(f.notesFile, 'The reduction is saved, but this writing command still owns the worktree.\n'); - await vi.advanceTimersByTimeAsync(30_000); expect(f.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(30_000); - const notes = 'The completed reduction leaves exactly the stated norm estimate unresolved.\n'; - fs.writeFileSync(f.notesFile, notes); - f.activity({ event: 'item_completed', itemType: 'commandExecution' }); - await expect(completion).resolves.toBeUndefined(); expect(f.interrupt).toHaveBeenCalledOnce(); - expect(committedSource(f.workers[1].worktree, f.state.cooperation!.researchDrafts!.investigate.commit, 'RESEARCH.md')).toBe(notes); - expect(f.events.some(event => event.event === 'research_handoff_requested')).toBe(false); - expect(f.check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it('keeps the original deadline through repeated search results and an empty handoff', async () => { - const f = fixture(), completion = f.run(); await f.reachSlice(completion); - await vi.advanceTimersByTimeAsync(10_000); f.tool(); await vi.advanceTimersByTimeAsync(0); - await vi.advanceTimersByTimeAsync(5 * 60_000); f.tool(' \n\t'); - await vi.advanceTimersByTimeAsync(5 * 60_000 - 10_001); - expect(f.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); await expect(completion).resolves.toBeUndefined(); - expect(f.interrupt).toHaveBeenCalledOnce(); expect(f.notify).toHaveBeenCalledTimes(2); - expect(f.events.filter(event => event.event === 'research_handoff_requested')).toHaveLength(1); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', details: expect.objectContaining({ - boundary: 'wait-limit', waitedMs: 10 * 60_000 }) }); - expect(f.events.filter(event => event.event === 'research_checkpoint_missing_notes')).toHaveLength(1); - expect(f.check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it('ends the bounded handoff when its extra save notice fails', async () => { - const f = fixture(), notice = deferred(); - f.notify.mockImplementationOnce(async () => {}).mockImplementationOnce(() => notice.promise); - const completion = f.run(); await f.reachSlice(completion); f.tool(); await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).not.toHaveBeenCalled(); - notice.reject(new Error('offline_handoff_notice_failed')); await expect(completion).resolves.toBeUndefined(); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', details: expect.objectContaining({ - boundary: 'notice-failed' }) }); - expect(f.events).toContainEqual({ event: 'cooperative_checkpoint_notice_failed', details: expect.objectContaining({ - reason: 'offline_handoff_notice_failed' }) }); - expect(f.interrupt).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0); - }); - - it('cleans the fixed deadline on cancellation while a handoff notice is pending', async () => { - const f = fixture(), notice = deferred(); - f.notify.mockImplementationOnce(async () => {}).mockImplementationOnce(() => notice.promise); - const completion = f.run(); await f.reachSlice(completion); f.tool(); await vi.advanceTimersByTimeAsync(0); - f.controller.abort(new Error('fixture_handoff_cancelled')); - await expect(completion).rejects.toThrow('fixture_handoff_cancelled'); - const events = f.events.length; notice.resolve(); await vi.advanceTimersByTimeAsync(30 * 60_000); - expect(f.events).toHaveLength(events); expect(vi.getTimerCount()).toBe(0); - }); - - it('allows accurate retained notes for the same assignment on its next slice', async () => { - const f = fixture({ turns: 2 }), completion = f.run(); await f.reachSlice(completion); - const notes = 'The saved derivation reduces the problem to the precise missing norm estimate.\n'; - f.tool(notes); await f.wait(1); - await f.reachSlice(completion, 1); f.tool(); - await expect(completion).resolves.toBeUndefined(); expect(f.interrupt).toHaveBeenCalledTimes(2); - expect(f.events.some(event => event.event === 'research_handoff_requested')).toBe(false); - expect(f.actions[1].assignment.assignmentId).toBe(f.actions[0].assignment.assignmentId); - expect(f.state.cooperation!.researchDrafts!.investigate.handoffNotesDigest).toBe(mathDigest(notes)); - expect(committedSource(f.workers[1].worktree, f.state.cooperation!.researchDrafts!.investigate.commit, 'RESEARCH.md')).toBe(notes); - expect(f.check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it('keeps acknowledged seed-equal notes attributed after rotating the context and resuming the task', async () => { - const notes = 'This existing reduction is accurate for the current assignment; the norm estimate remains open.\n'; - const f = fixture({ notes, turns: 2 }), completion = f.run(); await f.wait(0); - const research = f.state.workers![1]; - research.contextCheckpoint = { threadId: research.threadId!, requestedAt: Date.now(), requestId: 'confirm-current-notes' }; - acceptContextCheckpoint(research, f.workers[1].worktree, { kind: 'checkpoint', - requestId: 'confirm-current-notes', notesDigest: mathDigest(notes) }); - await vi.advanceTimersByTimeAsync(5_000); await f.wait(1); - expect(f.state.cooperation!.researchDrafts!.investigate.handoffNotesDigest).toBe(mathDigest(notes)); - expect(f.events.filter(item => item.event === 'context_restarted')).toHaveLength(1); - expect(research.contextCheckpoint).toBeUndefined(); - await f.reachSlice(completion, 1); f.tool(); - await expect(completion).resolves.toBeUndefined(); - expect(f.interrupt).toHaveBeenCalledTimes(2); - expect(f.events.some(item => item.event === 'research_handoff_requested' || item.event === 'research_checkpoint_missing_notes')).toBe(false); - expect(committedSource(f.workers[1].worktree, f.actions[1].assignment.seedCommit, 'RESEARCH.md')).toBe(notes); - expect(f.check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['research', 'sketch'] as const)('does not attribute inherited %s notes merely because an earlier slice timed out', async kind => { - const inherited = 'An earlier responsibility investigated a different boundary condition.\n'; - const f = fixture({ notes: inherited, turns: 2, kind }), completion = f.run(); - await f.reachSlice(completion); await vi.advanceTimersByTimeAsync(10 * 60_000); await f.wait(1); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.state.cooperation!.researchCheckpoints!.investigate).toMatchObject({ count: 1, paused: false }); - expect(f.actions[1].assignment.assignmentId).toBe(f.actions[0].assignment.assignmentId); - expect(f.actions[1].assignment.seedCommit).toBe(f.actions[0].assignment.seedCommit); - expect(fs.readFileSync(f.notesFile, 'utf8')).toBe(inherited); - expect(f.state.cooperation!.researchDrafts!.investigate.handoffNotesDigest).toBeUndefined(); - await f.reachSlice(completion, 1); f.tool(); await vi.advanceTimersByTimeAsync(0); - expect(f.interrupt).toHaveBeenCalledOnce(); - expect(f.events.filter(item => item.event === 'research_handoff_requested')).toHaveLength(1); - const current = 'For this assignment, the checked reduction leaves only the stated estimate unresolved.\n'; - f.tool(current); await expect(completion).resolves.toBeUndefined(); - expect(f.interrupt).toHaveBeenCalledTimes(2); - expect(f.state.cooperation!.researchDrafts!.investigate.handoffNotesDigest).toBe(mathDigest(current)); - expect(committedSource(f.workers[1].worktree, f.state.cooperation!.researchDrafts!.investigate.commit, 'RESEARCH.md')).toBe(current); - expect(f.events.filter(item => item.event === 'research_checkpoint_missing_notes')).toHaveLength(1); - expect(f.check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); -}); diff --git a/tests/researchObservation.test.ts b/tests/researchObservation.test.ts deleted file mode 100644 index d1a364ad..00000000 --- a/tests/researchObservation.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { queueResearchObservation } from '../src/solver/researchObservation'; -import { researchPublicationNotes } from '../src/solver/researchPublication'; -import { parseMathResponse } from '../src/solver/deliveries'; -import { assignmentDeliveryFile, parseCooperationPlan } from '../src/solver/tasks'; -import { committedSource } from '../src/solver/problem'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { buildResearchContext } from '../src/solver/modules/context'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ createSession: vi.fn() })); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); -const instances: { stop: () => Promise; directory: string }[] = []; -const root = fileURLToPath(new URL('..', import.meta.url)); -const cli = path.join(root, 'bin/math.ts'); -afterEach(async () => { - for (const item of instances.splice(0)) { await item.stop(); fs.rmSync(item.directory, { recursive: true, force: true }); } - expect(host.createSession).not.toHaveBeenCalled(); -}); - -async function fixture() { - const example = localExample('research-observation-'), lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'peer'); - const plan = parseCooperationPlan(example.problem, { tasks: [ - ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', objective: 'Prove the original target.', status: 'paused' })), - { id: 'investigate', kind: 'research', objective: 'Check a concrete construction.', ownerId: peer.id }, - ] }); - const state = solverState(example.problem, example.workspace, { runId: 'observation-fixture', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const controller = new AbortController(); - const cooperative = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: example.directory, signal: controller.signal }); - instances.push({ directory: example.directory, stop: async () => { controller.abort(); await cooperative.stop(); } }); - const action = await cooperative.next(peer, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('missing observation assignment'); - expect(action.task.id).toBe('investigate'); - expect(cooperative.started(peer, action)).toBe(true); - cooperative.activate(peer, action, async () => {}, async () => {}); - await cooperative.pulse(peer.id); - return { ...example, state, peer, cooperative, action, log: path.join(peer.worktree, assignmentDeliveryFile(action.assignment)) }; -} - -describe('immediate advisory observation publication', () => { - it('executes the complete help and generated-context file example through the real CLI', async () => { - const f = await fixture(); - const helpResult = spawnSync('bun', [cli, 'research-observe', '--help'], - { cwd: f.peer.worktree, encoding: 'utf8', timeout: 10_000 }); - expect(helpResult.status, helpResult.stderr).toBe(0); - const help = JSON.parse(helpResult.stdout); - expect(help.usage).toContain('--finding FILE'); - const context = buildResearchContext(f.problem, f.state, { root, worktree: f.peer.worktree, - environment: {}, taskText: 'Investigate the synthetic construction.', retrievalRoot: f.directory, assignment: f.action }); - expect(context.instructions).toContain('Use research-observe from .scratch/theoremos-help.md'); - expect(context.toolHelp?.text).toContain('research-observe --worktree'); - - - const commands = path.join(f.directory, 'commands'); - fs.mkdirSync(commands); - fs.writeFileSync(path.join(commands, 'theorem-os'), - "#!/bin/sh\nexec bun '" + cli.replace(/'/gu, "'\\''") + "' \"$@\"\n", { mode: 0o700 }); - const probe = path.join(f.peer.worktree, '.scratch', 'probe.lean'); - fs.mkdirSync(path.dirname(probe), { recursive: true }); - const code = 'lemma cli_probe : True := by trivial'; - fs.writeFileSync(probe, code); - const published = spawnSync('sh', ['-c', help.example + ' --probe .scratch/probe.lean --snapshot-sources'], - { cwd: f.peer.worktree, env: { ...process.env, PATH: commands + path.delimiter + process.env.PATH }, - encoding: 'utf8', timeout: 10_000 }); - expect(published.status, published.stderr).toBe(0); - const result = JSON.parse(published.stdout); - expect(result).toMatchObject({ status: 'queued', authority: 'advisory-unverified', retainedProbes: 1, snapshotSources: true }); - expect(result.receipt).toContain('queued is not host acceptance'); - const event = JSON.parse(fs.readFileSync(f.log, 'utf8').trim()); - expect(event.finding).toMatchObject({ conclusion: 'inconclusive', remainingObligations: ['Establish the missing bound.'] }); - expect(event.probes).toEqual([{ source: '.scratch/probe.lean', code }]); - expect(Object.keys(event.sources)).toEqual(f.problem.ownedFiles); - fs.rmSync(probe); - await f.cooperative.pulse(f.peer.id); - expect(f.state.cooperation!.deliveries!.filter(record => record.submissionId === result.submissionId)) - .toEqual([expect.objectContaining({ kind: 'research', status: 'conditional', artifacts: expect.objectContaining({ scope: 'advisory-unverified' }) })]); - expect(f.state.cooperation!.tasks.some(node => node.proof || node.integratedCheck)).toBe(false); - }); - - it('returns actionable CLI diagnostics without appending for inline JSON, bad paths or invalid files', async () => { - const f = await fixture(), before = fs.existsSync(f.log) ? fs.readFileSync(f.log, 'utf8') : ''; - fs.writeFileSync(path.join(f.peer.worktree, 'invalid.json'), '```json\n{}\n```'); - fs.writeFileSync(path.join(f.peer.worktree, 'wrong-field.json'), JSON.stringify({ summary: 'A missing bound.', remainingObligations: 'bound' })); - const cases = [ - ['{"summary":"Inline JSON is not a file."}', 'math_observation_finding_file_required', '--finding', 'Save the finding'], - ['absent.json', 'math_observation_finding_file_unreadable', '--finding', 'existing regular file'], - ['invalid.json', 'math_observation_finding_json_invalid', '--finding', 'without Markdown fences'], - ['wrong-field.json', 'math_delivery_invalid', 'remainingObligations', 'array'], - ]; - for (const [file, code, field, message] of cases) { - const result = spawnSync('bun', [cli, 'research-observe', '--worktree', f.peer.worktree, '--finding', file!], - { cwd: f.peer.worktree, encoding: 'utf8', timeout: 10_000 }); - expect(result.status, result.stderr).toBe(1); - expect(result.stdout).toBe(''); - expect(JSON.parse(result.stderr)).toMatchObject({ status: 'rejected', code, recovery: 'correct-and-resubmit', - issues: [expect.objectContaining({ path: field, message: expect.stringContaining(message!) })] }); - expect(fs.existsSync(f.log) ? fs.readFileSync(f.log, 'utf8') : '').toBe(before); - } - fs.writeFileSync(path.join(f.peer.worktree, 'wrong-field.json'), JSON.stringify({ summary: 'A missing bound.', remainingObligations: ['bound'] })); - const corrected = spawnSync('bun', [cli, 'research-observe', '--worktree', f.peer.worktree, '--finding', 'wrong-field.json'], - { cwd: f.peer.worktree, encoding: 'utf8', timeout: 10_000 }); - expect(corrected.status, corrected.stderr).toBe(0); - expect(JSON.parse(corrected.stdout).status).toBe('queued'); - expect(fs.readFileSync(f.log, 'utf8').trim().split('\n')).toHaveLength(1); - }); - - it('retains a deleted scratch probe through actual host intake and checkpoint reload without accepting a proof', async () => { - const f = await fixture(), probe = path.join(f.peer.worktree, '.scratch', 'probe.lean'); - fs.mkdirSync(path.dirname(probe), { recursive: true }); - const code = 'namespace ObservationProbe\nlemma identity (n : Nat) : n = n := by rfl\nend ObservationProbe'; - fs.writeFileSync(probe, code); - const result = queueResearchObservation({ worktree: f.peer.worktree, finding: { - summary: 'The identity check is retained; the original construction remains open.', - leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['ObservationProbe.identity'] }], - }, probes: [probe] }); - expect(result).toMatchObject({ status: 'queued', authority: 'advisory-unverified', retainedProbes: 1 }); - fs.rmSync(probe); - await f.cooperative.pulse(f.peer.id); - const records = f.state.cooperation!.deliveries!.filter(record => record.submissionId === result.submissionId); - expect(records).toHaveLength(1); - expect(records[0]).toMatchObject({ kind: 'research', status: 'advisory', taskId: 'investigate', - artifacts: { scope: 'advisory-unverified', artifacts: [{ kind: 'notes-lean', declarations: [{ name: 'ObservationProbe.identity' }] }] } }); - expect(committedSource(f.peer.worktree, records[0]!.commit!, 'RESEARCH.md')).toContain(code); - expect(f.state.cooperation!.tasks.some(node => node.proof || node.integratedCheck)).toBe(false); - const checkpoint = path.join(f.directory, 'state.json'); - writeSolverRunState(checkpoint, f.state); - expect(readSolverRunState(checkpoint).cooperation!.deliveries!.find(record => record.id === records[0]!.id)?.artifacts) - .toEqual(records[0]!.artifacts); - }); - - it('reports an invalid field before appending and permits a corrected submission', async () => { - const f = await fixture(), before = fs.existsSync(f.log) ? fs.readFileSync(f.log, 'utf8') : ''; - expect(() => queueResearchObservation({ worktree: f.peer.worktree, - finding: { summary: 'One missing premise.', remainingObligations: 'the bound' } })) - .toThrow('math_delivery_invalid'); - expect(fs.existsSync(f.log) ? fs.readFileSync(f.log, 'utf8') : '').toBe(before); - queueResearchObservation({ worktree: f.peer.worktree, - finding: { summary: 'One missing premise.', remainingObligations: ['the bound'] } }); - await f.cooperative.pulse(f.peer.id); - expect(f.state.cooperation!.deliveries!.at(-1)?.remainingObligations).toEqual(['the bound']); - }); - - it('uses the existing host identity to deduplicate a repeated observation', async () => { - const f = await fixture(), input = { worktree: f.peer.worktree, finding: { summary: 'A scoped negative search.' } }; - const first = queueResearchObservation(input), second = queueResearchObservation(input); - expect(second.submissionId).toBe(first.submissionId); - await f.cooperative.pulse(f.peer.id); - expect(f.state.cooperation!.deliveries!.filter(record => record.submissionId === first.submissionId)).toHaveLength(1); - }); - - it('freezes explicit source bytes at publication before the writer changes them', async () => { - const f = await fixture(), file = path.join(f.peer.worktree, f.problem.projectRelative, f.problem.ownedFiles.find(file => file.endsWith('.lean'))!); - const saved = fs.readFileSync(file, 'utf8'); - queueResearchObservation({ worktree: f.peer.worktree, finding: { summary: 'This observation concerns the current saved sources.' }, snapshotSources: true }); - const event = JSON.parse(fs.readFileSync(f.log, 'utf8').trim()); - fs.writeFileSync(file, saved + '\n-- later edit\n'); - expect(Object.values(event.sources)).toContain(saved); - expect(Object.values(event.sources)).not.toContain(saved + '\n-- later edit\n'); - }); - - it('keeps a single parseable result with probe artifacts and rejects ambiguous fences', () => { - const finding = { taskId: 'a', taskDigest: 'd', conclusion: 'inconclusive' as const, summary: 'Partial check.' }; - const notes = researchPublicationNotes(finding, [{ source: 'probe.lean', code: 'lemma p : True := by trivial' }]); - expect(parseMathResponse(notes, 'math-result')).toEqual(finding); - expect(() => researchPublicationNotes(finding, [{ source: 'probe.lean', code: '```math-result\n{}\n```' }])) - .toThrow('math_research_delivery_invalid'); - }); -}); diff --git a/tests/researchUsage.test.ts b/tests/researchUsage.test.ts index ebb13bb8..41c5b61c 100644 --- a/tests/researchUsage.test.ts +++ b/tests/researchUsage.test.ts @@ -6,10 +6,10 @@ import { directSolverModules } from '../src/solver/modules'; import type { SolverModules } from '../src/solver/modules'; import type { ProofCheck } from '../src/solver/modules/evidence'; import { commitSolverSources } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { runResearchLead } from '../src/solver/research'; import { ResearchUsage } from '../src/solver/researchUsage'; import { buildTokenBudget } from '../src/solver/usageBudget'; -import { workerAccess } from './helpers/cooperation'; +import { workerAccess } from './helpers/solver'; import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); @@ -33,8 +33,8 @@ function fixture(cooperative = false) { status: 'paused' as const, dependsOn: [], revision: 0 }, status: 'pending' as const, attempts: 0 })), ] } } : {}) }); const emit = vi.fn(), save = vi.fn(); - const run = (modules: SolverModules, maxTurns: number) => runResearchWorkers({ state, workers, - access: workerAccess(workers, directory), modules, + const run = (modules: SolverModules, maxTurns: number) => runResearchLead({ state, + access: workerAccess(workers, directory).get('solver')!, modules, root: directory, buildFile: path.join(directory, 'mock-build.json'), taskText: 'Fixture', executable: 'unused-fixture', profile: 'unused-fixture', signal: new AbortController().signal, deadline: Infinity, maxTurnMs: Infinity, maxTurns, maxTotalTokens: 0, save, emit }); const check = vi.fn(async (): Promise => { @@ -56,7 +56,7 @@ describe('research usage at the real research worker boundary', () => { it.each([true, false])('accounts native compaction without inventing a proof turn (usage reported: %s)', reported => { const { state, emit, save } = fixture(); state.usageAccounting = { startedTurns: 0, reportedTurns: 0, pending: false, incomplete: false }; - const usage = new ResearchUsage({ state, research: state, maxTotalTokens: 0, + const usage = new ResearchUsage({ state, research: state, signal: new AbortController().signal, remainingMs: () => Infinity, emit, changed: save }); const callbacks = usage.bindSession('maintenance-session', () => 12); usage.sessionOpened({ threadId: 'maintenance-thread', usageSource: 'native-thread-totals', run: async () => 'completed', interrupt: async () => {}, close: async () => {} }); @@ -71,7 +71,7 @@ describe('research usage at the real research worker boundary', () => { const { state, emit, save } = fixture(); state.tokenBudget = buildTokenBudget(0, [state]); state.usageAccounting = { startedTurns: 0, reportedTurns: 0, pending: false, incomplete: false }; - const usage = new ResearchUsage({ state, research: state, maxTotalTokens: 0, + const usage = new ResearchUsage({ state, research: state, signal: new AbortController().signal, remainingMs: () => Infinity, emit, changed: save }); const callbacks = usage.bindSession('maintenance-session', () => undefined); usage.sessionOpened({ threadId: 'maintenance-thread', usageSource: 'upstream-requests', run: async () => 'completed', interrupt: async () => {}, close: async () => {} }); @@ -89,7 +89,7 @@ describe('research usage at the real research worker boundary', () => { it('keeps usage incomplete when a turn starts without a bound native session', () => { const { state, emit, save } = fixture(); state.usageAccounting = { startedTurns: 0, reportedTurns: 0, pending: false, incomplete: false }; - const usage = new ResearchUsage({ state, research: state, maxTotalTokens: 0, + const usage = new ResearchUsage({ state, research: state, signal: new AbortController().signal, remainingMs: () => Infinity, emit, changed: save }); const session: MathAgentSession = { usageSource: 'native-turn-totals', run: async () => 'completed', interrupt: async () => {}, close: async () => {} }; @@ -241,22 +241,4 @@ describe('research usage at the real research worker boundary', () => { expect(state.tokenBudget).toMatchObject({ status: 'unlimited', reportedTotalTokens: 13, usageComplete: complete }); }); - it('saves an interrupted cooperative assignment as an advisory draft without checking it', async () => { - const { state, run, modules, check } = fixture(true); - const open = vi.fn(async (options: MathAgentOptions): Promise => ({ threadId: 'advisory-thread', - run: async (_message, _messageId, workspace, onStarted) => { - onStarted('advisory-checkpoint'); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), 'A useful boundary-case argument with one remaining gap.'); - options.onUsage({ totalTokens: 20 }); return 'interrupted'; - }, interrupt: async () => {}, close: async () => {} })); - await expect(run(modules(open), 1)).resolves.toBeUndefined(); - expect(open).toHaveBeenCalledTimes(1); expect(check).not.toHaveBeenCalled(); - const draft = state.cooperation!.researchDrafts!.investigation!; - expect(draft).toMatchObject({ workerId: 'peer' }); - expect(draft.assignmentId).toBeTypeOf('string'); - expect(state.workers!.find(worker => worker.id === 'peer')!.usage!.totalTokens).toBe(20); - expect(state.taskUsage).toEqual({ investigation: { totalTokens: 20 } }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigation')!.status).toBe('pending'); - expect(state.cooperation!.tasks.filter(node => node.task.kind === 'goal').every(node => !node.integratedCheck)).toBe(true); - }); }); diff --git a/tests/runContinuationSeed.test.ts b/tests/runContinuationSeed.test.ts deleted file mode 100644 index cc67f3c0..00000000 --- a/tests/runContinuationSeed.test.ts +++ /dev/null @@ -1,343 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { MATH_PROOF_ENVIRONMENT_ENV } from '../src/math/mathProofEnvironment'; -import { canonicalMathJson, mathDigest, withMathRuntimeLease } from '../src/math/mathRuntimeIo'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import type { TaskProof } from '../src/solver/cooperativeProof'; -import { readContinuationPage, readContinuationSnapshot } from '../src/solver/continuationInput'; -import * as continuationInput from '../src/solver/continuationInput'; -import { directSolverModules } from '../src/solver/modules'; -import { commitSolverSources, git } from '../src/solver/problem'; -import type { runResearchWorkers } from '../src/solver/research'; -import { runSolver } from '../src/solver/run'; -import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { localExample, solverState } from './helpers/solver'; -import { receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), prepare: vi.fn(), dispose: vi.fn(), run: vi.fn(), packages: '' })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); -vi.mock('../src/math/leanDiagnostics', async original => ({ - ...await original(), - runLeanDiagnostics: async () => ({ exitCode: 0, timedOut: false, phases: [] }), -})); -vi.mock('../src/math/leanToolchainReadiness', () => ({ checkResolvedLeanToolchainReadiness: () => ({ status: 'ready' }) })); -vi.mock('../src/math/verifier', async original => ({ - ...await original(), - checkManyFormalVerifications: host.verify, resolveMathematicsLakePackagesCache: () => host.packages, -})); -vi.mock('../src/math/mathProofEnvironment', async original => ({ - ...await original(), prepareMathProofEnvironment: host.prepare, -})); -vi.mock('../src/solver/research', () => ({ runResearchWorkers: host.run })); - -type ResearchInput = Parameters[0]; -const directories: string[] = []; -const taskText = 'Keep the original tutorial statements and continue the frozen proof.\n'; -const modules = { ...directSolverModules, M1: { ...directSolverModules.M1, - open: vi.fn(() => { throw new Error('fixture_model_call_forbidden'); }) } }; - -function fixture() { - const example = localExample('run-continuation-seed-'); - const { directory, workspace, problem } = example; - directories.push(directory); - const oldDirectory = path.join(directory, 'old.json.runtime'); - fs.mkdirSync(oldDirectory, { mode: 0o700 }); - const sourceWorkers = ['solver', 'engineer'].map((id, index) => { - const worktree = path.join(oldDirectory, index ? 'worktree-2' : 'worktree'); - git(workspace, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - return { id, role: index ? 'engineer' as const : 'lead' as const, worktree, phase: 'running' as const, turns: 1 }; - }); - const source = path.join(sourceWorkers[0].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(source, fs.readFileSync(source, 'utf8').replace('namespace Tutorial', - 'namespace Tutorial\n\nlemma saved_helper : True := by trivial')); - const canonical = commitSolverSources(problem, sourceWorkers[0].worktree); - fs.writeFileSync(path.join(sourceWorkers[1].worktree, 'RESEARCH.md'), 'Frozen worker notes.\n'); - const helper: CooperativeTask = { id: 'saved_helper', kind: 'lemma', objective: 'Prove the saved helper.', - theoremName: 'Tutorial.saved_helper', proofPath: 'Submission.lean', type: 'True', ownerId: 'engineer', dependsOn: [], revision: 0 }; - const tasks: CooperativeTask[] = [helper, ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal' as const, - objective: `Prove ${target.theoremName}.`, theoremName: target.theoremName, proofPath: target.proofPath, - ownerId: 'engineer', dependsOn: [helper.id], revision: 0 }))]; - const historical: TaskProof = { commit: canonical, sourceDigest: 'historical', passed: true, - taskDigest: taskVersion(helper), seedCommit: problem.baseCommit, changes: [], - verification: { status: 'kernel_verified', targetCommit: canonical, - results: [{ status: 'kernel_verified', targetCommit: canonical, receiptId: 'historical' }] } as TaskProof['verification'] }; - const sourceStateFile = path.join(oldDirectory, 'state.json'); - writeSolverRunState(sourceStateFile, solverState(problem, sourceWorkers[0].worktree, { - runId: 'historical-run', phase: 'running', taskDigest: mathDigest(taskText), turns: 2, - environmentDigest: mathDigest('historical-proof-environment'), - workerCount: 2, workers: sourceWorkers, coordination: 'cooperative', cooperation: { canonicalCommit: canonical, - tasks: tasks.map(task => ({ task, status: task.kind === 'lemma' ? 'integrated' : 'pending', attempts: 1, - ...(task.kind === 'lemma' ? { integratedCheck: historical } : {}) })), - groups: [{ group: { id: 'main', objective: 'Prove the tutorial.', status: 'active', revision: 0, engineerId: 'engineer' }, turns: 2 }] }, - })); - const output = path.join(directory, 'continued.json'), stateFile = `${output}.runtime/state.json`; - const taskFile = path.join(directory, 'task.md'), buildFile = path.join(directory, 'build.json'); - fs.writeFileSync(taskFile, taskText); fs.writeFileSync(buildFile, '{}'); - host.packages = path.join(directory, 'packages'); fs.mkdirSync(host.packages); - const args = ['--workspace', workspace, '--task-file', taskFile, '--build-manifest', buildFile, '--output', output, - '--workers', '2', '--model', 'fixture', '--continuation-source-run', sourceStateFile, - '--max-turns', '0', '--max-run-seconds', '0', '--max-turn-seconds', '0', '--no-explanations']; - return { directory, output, stateFile, sourceStateFile, sourceWorkers, problem, args }; -} - -beforeEach(() => { - vi.spyOn(console, 'log').mockImplementation(() => {}); - host.prepare.mockReset().mockResolvedValue({ environmentValue: 'live-run-proof-environment', dispose: host.dispose, - stats: { files: 0, bytes: 0, publications: 1 } }); - host.dispose.mockReset().mockResolvedValue(undefined); - host.verify.mockReset().mockImplementation((request: MathematicsVerifierBatchRequest) => receiptBatch(request, - { sessionId: 'continued', receiptId: (_index, theoremName) => `continued-${request.targetCommit}-${theoremName}` })); - host.run.mockReset().mockResolvedValue(undefined); -}); -afterEach(() => { - vi.restoreAllMocks(); vi.clearAllMocks(); - for (const directory of directories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }); -}); - -describe('same-process CLI continuation initialization', () => { - it('shares the held lock, environment and proof objects through restore without another helper verification', async () => { - const f = fixture(), historical = fs.readFileSync(f.sourceStateFile); - host.run.mockImplementation(async (input: ResearchInput) => { - expect(host.dispose).not.toHaveBeenCalled(); - expect(input.maxTurns).toBe(Infinity); expect(input.deadline).toBe(Infinity); expect(input.maxTurnMs).toBe(Infinity); - const helper = input.state.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!; - expect(input.freshContinuationChecks).toEqual([helper.integratedCheck]); - expect(input.freshContinuationChecks![0]).toBe(helper.integratedCheck); - expect(helper.integratedCheck!.verification.results[0].receiptId).not.toBe('historical'); - await expect(withMathRuntimeLease({ lockPath: path.join(path.dirname(f.stateFile), 'run.lock'), - flockExecutable: '/usr/bin/flock' }, async () => undefined)).rejects.toThrow('math_runtime_lease_busy'); - for (const worker of input.workers) { - const access = input.access.get(worker.id)!; - expect(access.environment[MATH_PROOF_ENVIRONMENT_ENV]).toBe('live-run-proof-environment'); - expect(access.continuation!.digest).toBe(input.state.continuationDigest); - expect(readContinuationSnapshot(access.continuation!.file, access.continuation!.digest).manifest.attachments) - .toContainEqual(expect.objectContaining({ id: 'draft-engineer' })); - } - const cooperative = new CooperativeResearch({ ...input, exclusiveCheck: check => check() }); - try { - await cooperative.restore(); - expect(host.verify).toHaveBeenCalledOnce(); - expect(helper.status).toBe('integrated'); - } finally { await cooperative.stop(); } - }); - expect(await runSolver(f.args, f.directory, modules), fs.readFileSync(f.output, 'utf8')).toBe(4); - expect(host.run).toHaveBeenCalledOnce(); expect(host.prepare).toHaveBeenCalledOnce(); expect(host.dispose).toHaveBeenCalledOnce(); - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][1].env[MATH_PROOF_ENVIRONMENT_ENV]).toBe('live-run-proof-environment'); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - expect(modules.M1.open).not.toHaveBeenCalled(); - }); - - it('freezes a zero-turn startup checkpoint and checks its saved helpers once when resumed', async () => { - const f = fixture(); - expect(await runSolver([...f.args, '--startup-only'], f.directory, modules)).toBe(0); - const state = readSolverRunState(f.stateFile); - expect(state.phase).toBe('prepared'); expect(state.turns).toBe(0); expect(state.solveStartedAt).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'saved_helper')).toMatchObject({ status: 'pending' }); - expect(state.workers!.every(worker => fs.existsSync(path.join(worker.worktree, f.problem.projectRelative, '.lake/continuation.json')))).toBe(true); - expect(host.run).not.toHaveBeenCalled(); expect(host.prepare).toHaveBeenCalledOnce(); expect(host.dispose).toHaveBeenCalledOnce(); - expect(host.verify).not.toHaveBeenCalled(); - - fs.writeFileSync(path.join(f.sourceWorkers[1].worktree, 'RESEARCH.md'), 'Historical notes added after preflight.\n'); - host.run.mockImplementation(async (input: ResearchInput) => { - const helper = input.state.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!; - expect(input.freshContinuationChecks?.[0]).toBe(helper.integratedCheck); - expect(helper.status).toBe('integrated'); - const solver = new CooperativeResearch({ ...input, exclusiveCheck: check => check() }); - try { await solver.restore(); } - finally { await solver.stop(); } - }); - const sourceFlag = f.args.indexOf('--continuation-source-run'); - const resume = f.args.filter((_arg, index) => index !== sourceFlag && index !== sourceFlag + 1); - expect(await runSolver([...resume, '--resume'], f.directory, modules), fs.readFileSync(f.output, 'utf8')).toBe(4); - expect(host.run).toHaveBeenCalledOnce(); expect(host.verify).toHaveBeenCalledOnce(); - expect(readSolverRunState(f.stateFile)).toMatchObject({ continuationDigest: state.continuationDigest }); - expect(readSolverRunState(f.stateFile).pendingContinuationSource).toBeUndefined(); - const draft = JSON.parse(readContinuationPage(path.join(path.dirname(f.stateFile), 'continuation.json'), - state.continuationDigest!, 'draft-engineer').text); - expect(draft.notes).toBe('Frozen worker notes.\n'); - expect(modules.M1.open).not.toHaveBeenCalled(); - }); - - it('startup-only preserves started initial-planning activity and leaves the new run ready for its first plan', async () => { - const f = fixture(), source = readSolverRunState(f.sourceStateFile); - source.turns = 3; source.dispatchCounts = { planning: 3 }; - source.usage = { inputTokens: 1200, outputTokens: 300, totalTokens: 1500 }; - source.cooperation = { canonicalCommit: f.problem.baseCommit, leadSeedCommit: f.problem.baseCommit, tasks: [], proofRoutes: [], - planVersion: mathDigest(canonicalMathJson({ tasks: [], groups: undefined })), - deliveries: [{ id: 'saved-initial-draft', producer: 'solver', kind: 'progress', status: 'advisory', - statement: source.problem.contract.formalStatement, premises: source.problem.contract.assumptions, - dependencies: [], remainingObligations: [], evidenceRefs: [], createdAt: 10, commit: f.problem.baseCommit, - summary: 'Saved Lead draft pending integration: math_math-plan_missing_or_too_large. This draft has no proof acceptance.' }] }; - const lead = source.workers![0]; - Object.assign(lead, { turns: 3, threadId: 'old-initial-thread', previousThreadIds: ['old-planning-thread'], - sessionRole: 'lead', dispatchCounts: { planning: 3 }, usage: source.usage, - usageAccounting: { startedTurns: 3, reportedTurns: 2, pending: true, incomplete: true } }); - const peer = source.workers![1]; peer.turns = 0; peer.dispatchCounts = {}; - git(lead.worktree, ['reset', '--hard', f.problem.baseCommit]); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'Incomplete initial plan with prior mathematical reasoning.\n'); - writeSolverRunState(f.sourceStateFile, source); - const historical = fs.readFileSync(f.sourceStateFile); - expect(await runSolver([...f.args, '--startup-only'], f.directory, modules)).toBe(0); - const state = readSolverRunState(f.stateFile); - expect(state).toMatchObject({ phase: 'prepared', turns: 0 }); - expect(state.workers!.every(worker => worker.turns === 0 && !worker.threadId && !worker.usage)).toBe(true); - expect(state.cooperation).toMatchObject({ tasks: [], planEdited: false }); - expect(state.cooperation!.planVersion).toBeUndefined(); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - const directory = path.dirname(f.stateFile), snapshot = path.join(directory, 'continuation.json'); - const history = JSON.parse(readContinuationPage(snapshot, state.continuationDigest, 'seed-history').text); - expect(history).toMatchObject({ source: { runId: 'historical-run' }, - history: { deliveries: source.cooperation.deliveries, activity: { turns: 3, usage: source.usage, workers: [expect.objectContaining({ id: 'solver', turns: 3, - usageAccounting: lead.usageAccounting }), expect.objectContaining({ id: 'engineer', turns: 0 })] } } }); - const draft = JSON.parse(readContinuationPage(snapshot, state.continuationDigest, 'draft-solver').text); - expect(draft.notes).toBe('Incomplete initial plan with prior mathematical reasoning.\n'); - expect(host.run).not.toHaveBeenCalled(); expect(host.verify).not.toHaveBeenCalled(); - expect(modules.M1.open).not.toHaveBeenCalled(); - }); - - it('preserves initialization progress after an error and retries the frozen source with resume', async () => { - const f = fixture(); let interrupt = true; - vi.mocked(console.log).mockImplementation(message => { - if (interrupt && JSON.parse(String(message)).event === 'continuation_seed_checked') { - interrupt = false; throw new Error('fixture_initialization_interrupted'); - } - }); - expect(await runSolver(f.args, f.directory, modules)).toBe(1); - const interrupted = readSolverRunState(f.stateFile), digest = interrupted.continuationDigest; - expect(interrupted.phase).toBe('prepared'); expect(interrupted.solveStartedAt).toBeUndefined(); - expect(interrupted.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!.status).toBe('integrated'); - expect(host.run).not.toHaveBeenCalled(); - fs.writeFileSync(path.join(f.sourceWorkers[1].worktree, 'RESEARCH.md'), 'Late historical notes.\n'); - expect(await runSolver([...f.args, '--resume'], f.directory, modules)).toBe(4); - const resumed = readSolverRunState(f.stateFile); - expect(resumed.continuationDigest).toBe(digest); - const draft = JSON.parse(readContinuationPage(path.join(path.dirname(f.stateFile), 'continuation.json'), digest!, 'draft-engineer').text); - expect(draft.notes).toBe('Frozen worker notes.\n'); - expect(host.run).toHaveBeenCalledOnce(); expect(host.verify).toHaveBeenCalledTimes(2); expect(host.dispose).toHaveBeenCalledTimes(2); - }); - - it.each(['continuation-copy', 'environment-write'] as const)( - 'retries %s failure after seeding without leaving the prepared initialization', async failure => { - const f = fixture(), directory = path.dirname(f.stateFile), historical = fs.readFileSync(f.sourceStateFile); - const environmentFile = path.join(directory, 'environment-engineer.json'); - const reportFile = path.join(directory, 'continuation-seed.json'); - const target = failure === 'continuation-copy' - ? path.join(directory, 'worktree-2', f.problem.projectRelative, '.lake/continuation.json') : environmentFile; - let failPublication = true, refreshEnvironment = failure === 'environment-write'; - // Environment publication may otherwise reuse its first durable write. Make - // the peer need its file again after the fresh helper check has completed. - vi.mocked(console.log).mockImplementation(message => { - if (refreshEnvironment && JSON.parse(String(message)).event === 'continuation_seed_checked') { - refreshEnvironment = false; fs.unlinkSync(environmentFile); - } - }); - const rename = fs.renameSync; - vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (failPublication && String(to) === target && fs.existsSync(reportFile) && - JSON.parse(fs.readFileSync(reportFile, 'utf8')).stage === 'complete') { - failPublication = false; throw new Error(`fixture_${failure}_interrupted`); - } - return rename(from, to); - }); - - expect(await runSolver(f.args, f.directory, modules)).toBe(1); - expect(failPublication).toBe(false); - expect(JSON.parse(fs.readFileSync(f.output, 'utf8')).reason).toBe(`fixture_${failure}_interrupted`); - expect(JSON.parse(fs.readFileSync(reportFile, 'utf8')).stage).toBe('complete'); - const interrupted = readSolverRunState(f.stateFile), digest = interrupted.continuationDigest!; - const frozenFile = path.join(directory, 'continuation-seed-source.json'), frozenSource = fs.readFileSync(frozenFile); - expect(interrupted.phase).toBe('prepared'); expect(interrupted.solveStartedAt).toBeUndefined(); - expect(interrupted.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!.status).toBe('integrated'); - expect(host.verify).toHaveBeenCalledOnce(); expect(host.run).not.toHaveBeenCalled(); - // Earlier workers completed real snapshot publication before the peer failed. - expect(readContinuationSnapshot(path.join(directory, 'worktree', f.problem.projectRelative, '.lake/continuation.json'), digest) - .digest).toBe(digest); - - fs.writeFileSync(path.join(f.sourceWorkers[1].worktree, 'RESEARCH.md'), 'Late notes after worker publication failed.\n'); - host.run.mockImplementation(async (input: ResearchInput) => { - const helper = input.state.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!; - expect(input.freshContinuationChecks![0]).toBe(helper.integratedCheck); - for (const worker of input.workers) { - const continuation = input.access.get(worker.id)!.continuation!; - expect(readContinuationSnapshot(continuation.file, continuation.digest).digest).toBe(digest); - } - }); - expect(await runSolver([...f.args, '--resume'], f.directory, modules), fs.readFileSync(f.output, 'utf8')).toBe(4); - expect(readSolverRunState(f.stateFile).continuationDigest).toBe(digest); - expect(fs.readFileSync(frozenFile)).toEqual(frozenSource); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - const draft = JSON.parse(readContinuationPage(path.join(directory, 'continuation.json'), digest, 'draft-engineer').text); - expect(draft.notes).toBe('Frozen worker notes.\n'); - expect(host.run).toHaveBeenCalledOnce(); expect(host.verify).toHaveBeenCalledTimes(2); expect(host.dispose).toHaveBeenCalledTimes(2); - }); - - it.each(['root-snapshot-read', 'ready-observer', 'startup-output'] as const)( - 'retries %s failure after a complete seed while retaining the prepared checkpoint', async failure => { - const f = fixture(), directory = path.dirname(f.stateFile), historical = fs.readFileSync(f.sourceStateFile); - const reportFile = path.join(directory, 'continuation-seed.json'), snapshotFile = path.join(directory, 'continuation.json'); - const startupOnly = failure === 'startup-output'; - const args = startupOnly ? [...f.args, '--startup-only'] : f.args; - const seedReady = () => fs.existsSync(reportFile) && - JSON.parse(fs.readFileSync(reportFile, 'utf8')).stage === (startupOnly ? 'awaiting-checks' : 'complete'); - const fault = `fixture_${failure}_interrupted`; - let failures = 0; - if (failure === 'root-snapshot-read') { - const readSnapshot = continuationInput.readContinuationSnapshot; - vi.spyOn(continuationInput, 'readContinuationSnapshot').mockImplementation((...input) => { - if (!failures && input[0] === snapshotFile && seedReady()) { failures++; throw new Error(fault); } - return readSnapshot(...input); - }); - } else if (failure === 'ready-observer') { - vi.mocked(console.log).mockImplementation(message => { - if (!failures && JSON.parse(String(message)).event === 'ready' && seedReady()) { - failures++; throw new Error(fault); - } - }); - } else { - const rename = fs.renameSync; - vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (!failures && String(to) === f.output && seedReady()) { failures++; throw new Error(fault); } - return rename(from, to); - }); - } - - expect(await runSolver(args, f.directory, modules)).toBe(1); - expect(failures).toBe(1); - expect(seedReady()).toBe(true); - expect(JSON.parse(fs.readFileSync(f.output, 'utf8')).reason).toBe(fault); - const interrupted = readSolverRunState(f.stateFile), digest = interrupted.continuationDigest!; - const frozenFile = path.join(directory, 'continuation-seed-source.json'), frozenSource = fs.readFileSync(frozenFile); - expect(interrupted.phase).toBe('prepared'); expect(interrupted.turns).toBe(0); - expect(interrupted.solveStartedAt).toBeUndefined(); - expect(interrupted.cooperation!.tasks.find(node => node.task.id === 'saved_helper')!.status).toBe(startupOnly ? 'pending' : 'integrated'); - expect(host.verify).toHaveBeenCalledTimes(startupOnly ? 0 : 1); expect(host.run).not.toHaveBeenCalled(); - - fs.writeFileSync(path.join(f.sourceWorkers[1].worktree, 'RESEARCH.md'), 'Late notes after the prepared checkpoint failed.\n'); - expect(await runSolver([...args, '--resume'], f.directory, modules), fs.readFileSync(f.output, 'utf8')) - .toBe(startupOnly ? 0 : 4); - const resumed = readSolverRunState(f.stateFile); - expect(failures).toBe(1); expect(resumed.continuationDigest).toBe(digest); - expect(fs.readFileSync(frozenFile)).toEqual(frozenSource); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(historical); - for (const worker of resumed.workers!) { - expect(readContinuationSnapshot(path.join(worker.worktree, f.problem.projectRelative, '.lake/continuation.json'), digest) - .digest).toBe(digest); - } - const draft = JSON.parse(readContinuationPage(snapshotFile, digest, 'draft-engineer').text); - expect(draft.notes).toBe('Frozen worker notes.\n'); - expect(host.run).toHaveBeenCalledTimes(startupOnly ? 0 : 1); - expect(host.verify).toHaveBeenCalledTimes(startupOnly ? 0 : 2); expect(host.dispose).toHaveBeenCalledTimes(2); - expect(modules.M1.open).not.toHaveBeenCalled(); - }); - - it.each([['--workers', '1'], ['--coordination', 'independent'], ['--continuation-manifest', '/unused.json']])( - 'rejects incompatible %s before preparing a workspace', async (flag, value) => { - await expect(runSolver(['--continuation-source-run', '/unused-run', flag, value], '/unused-root', modules)) - .rejects.toThrow('--continuation-source-run'); - expect(host.run).not.toHaveBeenCalled(); expect(host.prepare).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/runLeaseSafety.test.ts b/tests/runLeaseSafety.test.ts index 1c84347b..d3a79684 100644 --- a/tests/runLeaseSafety.test.ts +++ b/tests/runLeaseSafety.test.ts @@ -18,7 +18,7 @@ vi.mock('../src/math/leanToolchainReadiness', () => ({ checkResolvedLeanToolchai vi.mock('../src/math/verifier', async original => ({ ...await original(), resolveMathematicsLakePackagesCache: () => undefined, })); -vi.mock('../src/solver/research', () => ({ runResearchWorkers: host.run })); +vi.mock('../src/solver/research', () => ({ runResearchLead: host.run })); const directories: string[] = []; const open = vi.fn(() => { throw new Error('fixture_model_call_forbidden'); }); diff --git a/tests/singleContinuationSeed.test.ts b/tests/singleContinuationSeed.test.ts index e8f8debb..7e96d8a9 100644 --- a/tests/singleContinuationSeed.test.ts +++ b/tests/singleContinuationSeed.test.ts @@ -7,7 +7,7 @@ import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { saveAgentTeamResearchArtifact } from '../src/solver/agentTeamResearch'; import { searchContinuation } from '../src/solver/continuationSearch'; -import { seedSingleSolverContinuation } from '../src/solver/continuationSeed'; +import { seedSingleSolverContinuation } from '../src/solver/singleContinuationSeed'; import { freezeContinuationInput, readContinuationContents, readContinuationPage, type ContinuationManifest } from '../src/solver/continuationInput'; import { readDeclarationArtifacts } from '../src/solver/declarationArtifacts'; import { committedSource, commitSolverSources, git } from '../src/solver/problem'; diff --git a/tests/skillContextContinuation.test.ts b/tests/skillContextContinuation.test.ts index 4ed5472f..07298ba9 100644 --- a/tests/skillContextContinuation.test.ts +++ b/tests/skillContextContinuation.test.ts @@ -221,11 +221,10 @@ describe.each([{ common: false, mode: 'standalone skill' }, { common: true, mode const context = buildResearchContext(f.problem, f.state, { ...f.access, teamRole: { id: 'lead', role: 'lead' } }); for (const continuation of [false, true]) { const dispatch = finalizeResearchDispatch(context, { continuation }); - expect(dispatch.instructions).toContain('the Lead of an Agent-organized research team'); + expect(dispatch.instructions).toContain('the Lead of a flat mathematical research team'); expect(dispatch.instructions).toContain('theoremos_team'); expect(dispatch.instructions).not.toContain('native child agents are not enabled'); expect(dispatch.message).toContain('A durable question sent between native turns.'); - expect(dispatch.message).toContain('latestSequence is not an acknowledgment'); if (!continuation) expect(dispatch.manifest?.included.map(item => item.id)).toContain('agent-team'); } }); diff --git a/tests/skillProcessRecovery.test.ts b/tests/skillProcessRecovery.test.ts index da948f63..50877272 100644 --- a/tests/skillProcessRecovery.test.ts +++ b/tests/skillProcessRecovery.test.ts @@ -60,7 +60,7 @@ import fs from 'node:fs';import path from 'node:path'; import { withMathRuntimeLease,writeMathJsonDurable } from './src/math/mathRuntimeIo'; import { readSolverRunState,writeSolverRunState } from './src/solver/archive'; import { prepareResearchSkill } from './src/solver/researchSkill'; -import { runResearchWorkers } from './src/solver/research'; +import { runResearchLead } from './src/solver/research'; import { git } from './src/solver/problem'; import { directSolverModules } from './src/solver/modules'; const config=JSON.parse(fs.readFileSync(process.argv[2],'utf8')),recovery=process.argv[3]==='resume'; @@ -90,9 +90,8 @@ await withMathRuntimeLease({lockPath,flockExecutable:'/usr/bin/flock'},async lea if(!recovery&&config.phase==='whole-proof-pending'&&state.pendingProofCheck)hold(); if(!recovery&&config.phase==='whole-proof-accepted'&&state.pendingProofCheck&&state.check?.passed)hold();}; if(!recovery&&config.phase==='prepared')hold(); - const result=await runResearchWorkers({state,root:config.repo,buildFile:config.buildFile,taskText:'Prove the fixed original target.', - workers:[{id:'solver',role:'lead',worktree:state.worktree,ownedFiles:state.problem.ownedFiles}], - access:new Map([['solver',{researchSkill:skill,environment:{...config.environment,FIXTURE_ROOT:config.root,FIXTURE_PHASE:config.phase,FIXTURE_RECOVERY:recovery?'1':'0'},retrievalRoot:state.worktree}]]), + const result=await runResearchLead({state,root:config.repo,buildFile:config.buildFile,taskText:'Prove the fixed original target.', + access:{researchSkill:skill,environment:{...config.environment,FIXTURE_ROOT:config.root,FIXTURE_PHASE:config.phase,FIXTURE_RECOVERY:recovery?'1':'0'},retrievalRoot:state.worktree}, modules:directSolverModules,executable:path.join(config.root,'peer'),profile:path.join(config.root,'profile'),signal:lease.signal, deadline:Infinity,maxTurns:config.phase==='pending-verifier'?1:config.phase==='frozen'?2:1,maxTurnMs:Infinity,maxTotalTokens:1000,proofTimeoutMs:30000, save,emit:(event,details)=>{fs.appendFileSync(path.join(config.root,'events.jsonl'),JSON.stringify({event,details})+'\n'); @@ -121,7 +120,7 @@ beforeAll(() => { fs.cpSync(path.join(sourceRoot, 'scripts'), path.join(runtimeRoot, 'scripts'), { recursive: true }); const startedAt = new Date().toISOString(), source = mathBuildSource(runtimeRoot); const bundleRoot = path.join(runtimeRoot, 'out/main'); - buildSync({ entryPoints: Object.fromEntries(['runMathProof', 'searchLean', 'checkLean', 'proofSearch'] + buildSync({ entryPoints: Object.fromEntries(['runMathProof', 'searchLean', 'checkLean'] .map((name, index) => [MATH_RUNTIME_BUNDLES[index].replace(/\.js$/u, ''), path.join(runtimeRoot, 'scripts/mathematics', name + '.ts')])), outdir: bundleRoot, bundle: true, platform: 'node', format: 'cjs', diff --git a/tests/skillResearchRuntime.test.ts b/tests/skillResearchRuntime.test.ts index f7646b4b..bb8c0d28 100644 --- a/tests/skillResearchRuntime.test.ts +++ b/tests/skillResearchRuntime.test.ts @@ -8,12 +8,12 @@ import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSes import { directSolverModules, type SolverModules } from '../src/solver/modules'; import { committedSource, git } from '../src/solver/problem'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { runResearchWorkers, type WorkerAccess } from '../src/solver/research'; +import { runResearchLead, type WorkerAccess } from '../src/solver/research'; import { DeclarationArtifactCheckError } from '../src/solver/declarationArtifacts'; import { VerificationCheckpointError, withVerificationCheckpoints } from '../src/solver/verificationCheckpoint'; import { VerifierFailureError } from '../src/solver/verifierFailure'; import { deferred } from './helpers/async'; -import { leadWorker, localExample, solverState } from './helpers/solver'; +import { localExample, solverState } from './helpers/solver'; import { failedBatch, receiptBatch } from './helpers/verifier'; const host = vi.hoisted(() => ({ verify: vi.fn(), declarations: vi.fn(), writeDeclarations: vi.fn() })); @@ -72,7 +72,7 @@ describe('skill research runtime', () => { agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [] } } as const : {}), ...(common ? { commonResearchSkill: { name: skill.name, digest: skill.digest, loading: skill.loading } } : {}) }); - const workers = [leadWorker(problem, workspace)], controller = new AbortController(); + const controller = new AbortController(); const opened: MathAgentOptions[] = [], messages: string[] = [], events: { event: string; details?: Record }[] = []; const stops = vi.fn(async () => { if (stop === 'throw') throw new Error('fixture-shutdown-failed'); @@ -111,18 +111,18 @@ describe('skill research runtime', () => { M1: { ...directSolverModules.M1, open }, M2: { ...directSolverModules.M2, applyLibrary }, M3: { ...directSolverModules.M3, select }, M4: { ...directSolverModules.M4, build, tools }, }; - const access = new Map([['solver', { environment: {}, retrievalRoot: directory, + const access: WorkerAccess = { environment: {}, retrievalRoot: directory, researchSkill: skill, ...(common ? { commonResearchSkill: skill } : {}), installedLibrary: { digest: 'installed-fixture', - base: { entries: [], evidence: [], contexts: [], routeFindings: [] } } }]]); + base: { entries: [], evidence: [], contexts: [], routeFindings: [] } } }; const source = path.join(workspace, problem.projectRelative, 'Submission.lean'), notes = path.join(workspace, 'RESEARCH.md'); const requestFile = path.join(workspace, '.scratch/declaration-submission.json'); const savedStates: Record[] = []; - const current = { ...base, state, workers, access, modules, controller, opened, messages, events, savedStates, + const current = { ...base, state, access, modules, controller, opened, messages, events, savedStates, open, close, stops, select, build, applyLibrary, source, notes, requestFile, skill }; const completion = withVerificationCheckpoints({ environmentDigest: state.environmentDigest, problemReceiptDigest: problem.receiptDigest, checkpoints: state.verificationCheckpoints ??= [], save: () => { savedStates.push(JSON.parse(JSON.stringify(state))); }, - emit: (event, details) => events.push({ event, details }) }, () => runResearchWorkers({ state, workers, access, modules, root: directory, + emit: (event, details) => events.push({ event, details }) }, () => runResearchLead({ state, access, modules, root: directory, buildFile: path.join(directory, 'unused-build.json'), taskText: 'Prove both original addition targets.', executable: 'offline-no-model', profile: 'offline-no-credentials', signal: controller.signal, deadline: Infinity, maxTurns: plans.length, maxTurnMs: Infinity, maxTotalTokens: 0, @@ -144,8 +144,8 @@ describe('skill research runtime', () => { checkpoints: current.state.verificationCheckpoints ??= [], save: () => { current.savedStates.push(JSON.parse(JSON.stringify(current.state))); }, emit: (event, details) => current.events.push({ event, details }), - }, () => runResearchWorkers({ - state: current.state, workers: current.workers, access: current.access, modules: current.modules, + }, () => runResearchLead({ + state: current.state, access: current.access, modules: current.modules, root: current.directory, buildFile: path.join(current.directory, 'unused-build.json'), taskText: 'Prove both original addition targets.', executable: 'offline-no-model', profile: 'offline-no-credentials', signal: new AbortController().signal, deadline: Infinity, maxTurnMs: Infinity, ...limits, @@ -258,33 +258,6 @@ describe('skill research runtime', () => { .toEqual(['full', 'full']); }); - it('retains child observations on disk and records uncertain recovery without replaying investigations', async () => { - const plans: Plan[] = [f => { fs.writeFileSync(f.notes, 'Initial research saved.\n'); }]; - const current = fixture(plans); - await current.completion; - current.state.researchDelegation = { mode: 'read-only', maxAgents: 2 }; - current.state.nativeAgents = [{ threadId: 'previous-child', parentThreadId: 'previous-parent', - startedAt: 1, updatedAt: 1, status: 'running', dispatch: 'host-mediated-native-threads' }]; - plans.push((f, options) => { - expect(f.state.nativeAgents![0].status).toBe('unknown'); - expect(options.delegation).toEqual(f.state.researchDelegation); - options.onNativeAgent!({ threadId: 'current-child', parentThreadId: 'persistent-native-research-thread', - startedAt: 2, updatedAt: 3, stoppedAt: 4, status: 'completed', permissionProfile: 'math-investigator', - dispatch: 'host-mediated-native-threads', parentTurnId: 'parent-turn', callId: 'call', turnId: 'child-turn', - question: 'Bounded question', message: 'Advisory source reference.' }); - fs.appendFileSync(f.notes, 'Only the primary researcher updates notes.\n'); - }); - await resumeDeclarations(current, { maxTurns: 2, maxTotalTokens: 0 }); - const stateFile = path.join(current.directory, 'delegation-state.json'); - writeSolverRunState(stateFile, current.state); - expect(readSolverRunState(stateFile).nativeAgents).toEqual(current.state.nativeAgents); - expect(current.events.filter(item => item.event === 'investigator_recovery_recorded')).toEqual([ - { event: 'investigator_recovery_recorded', details: { threadId: 'previous-child', replayed: false } }, - ]); - expect(current.state.nativeAgents).toHaveLength(2); - expect(host.verify).not.toHaveBeenCalled(); - }); - it('uses the host-projected tool bundle when the application source is hidden', async () => { const current = fixture([f => { const help = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); @@ -771,7 +744,7 @@ describe('skill research runtime', () => { expect(current.state.writerStopUnconfirmed).toMatchObject({ reason: expect.any(String) }); expect(host.verify).not.toHaveBeenCalled(); expect(host.declarations).not.toHaveBeenCalled(); expect(host.writeDeclarations).not.toHaveBeenCalled(); expect(current.open).toHaveBeenCalledTimes(1); - await expect(runResearchWorkers({ state: current.state, workers: current.workers, access: current.access, + await expect(runResearchLead({ state: current.state, access: current.access, modules: current.modules, root: current.directory, buildFile: 'unused', taskText: 'Same original problem.', executable: 'offline-no-model', profile: 'offline-no-credentials', signal: current.controller.signal, deadline: Infinity, maxTurns: 1, maxTurnMs: Infinity, maxTotalTokens: 0, save: () => {}, emit: () => {} })) diff --git a/tests/skillSolver.test.ts b/tests/skillSolver.test.ts index 04826ce7..47358ace 100644 --- a/tests/skillSolver.test.ts +++ b/tests/skillSolver.test.ts @@ -10,7 +10,7 @@ import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/resea import { runSolver } from '../src/solver/run'; import { assertSolverSources, git } from '../src/solver/problem'; import { localExample } from './helpers/solver'; -import { researchHarness } from '../src/runtime/researchHarness'; +import { bindResearchHarness, researchHarness } from '../src/runtime/researchHarness'; import { prepareWestlakeProfile } from '../src/runtime/westlake'; vi.mock('../src/math/mathBuildManifest', async original => ({ @@ -162,29 +162,6 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(open).not.toHaveBeenCalled(); }); - it('pins the same shared mathematical guidance for legacy workers without changing their mode', async () => { - const common = [...args, '--common-research-skill', 'native', '--workers', '2']; - expect(await runSolver(common, root, modules)).toBe(0); - const saved = state(); - expect(saved.researchMode).toBeUndefined(); expect(saved.researchSkill).toBeUndefined(); - expect(saved.commonResearchSkill).toMatchObject({ name: 'theoremos-research', loading: 'native' }); - for (const worker of saved.workers!) { - const skill = readMathAgentSkill(path.join(worker.worktree, '.agents/skills/theoremos-research/SKILL.md')); - expect(researchSkillIdentity(skill)).toEqual(saved.commonResearchSkill); - } - expect(await runSolver([...common, '--resume', '--common-research-skill', 'file'], root, modules)).toBe(1); - rejected('math_resume_research_strategy_changed'); expect(open).not.toHaveBeenCalled(); - }); - - it('freezes explicit host-mediated read-only delegation and retains it on resume', async () => { - const flags=[...args, '--research-mode', 'skill', '--skill-delegation', 'read-only', '--skill-max-agents', '2']; - expect(await runSolver(flags, root, modules)).toBe(0); - expect(state().researchDelegation).toEqual({mode:'read-only',maxAgents:2}); - expect(await runSolver([...args,'--resume'],root,modules)).toBe(0); - expect(state().researchDelegation).toEqual({mode:'read-only',maxAgents:2}); - expect(open).not.toHaveBeenCalled(); - }); - it.each([{ flags: [], capacity: 4 }, { flags: ['--skill-max-agents', '8'], capacity: 8 }])( 'pins an Agent-led team of $capacity including one Lead and restores it on resume', async ({ flags: capacityFlags, capacity }) => { const flags = [...args, '--research-mode', 'skill', '--skill-delegation', 'team', ...capacityFlags]; @@ -204,31 +181,33 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(open).not.toHaveBeenCalled(); }); - it('freezes the direct Westlake Chat team with host tools and preserves that on resume', async () => { + it('rejects a new direct Westlake Chat team before saving a run', async () => { const profile = path.join(example.directory, 'westlake-profile'); prepareWestlakeProfile(profile, 'deepseek-flash', 'high'); - vi.stubEnv('DEEPSCIENTIST_MATH_CODEX_EXECUTABLE', process.execPath); vi.stubEnv('THEOREMOS_CODEX_BACKEND_EXECUTABLE', path.join(example.directory, 'missing-native-backend')); - expect(await runSolver([...args, '--agent-team', '3', '--harness-profile', profile], root, modules)).toBe(0); - const saved = state(); - expect(saved).toMatchObject({ agentTeam: { transport: 'host-tools' }, agentHarness: { executable: fs.realpathSync(process.execPath) }, - researchDelegation: { mode: 'team', maxAgents: 3 }, turns: 0 }); - expect(await runSolver([...args, '--resume'], root, modules)).toBe(0); - expect(state()).toMatchObject({ runId: saved.runId, agentTeam: { transport: 'host-tools' }, turns: 0 }); + expect(await runSolver([...args, '--agent-team', '3', '--harness-profile', profile], root, modules)).toBe(1); + rejected('math_westlake_native_team_unsupported: select a native-compatible Codex profile such as the Responses gateway.'); + expect(fs.existsSync(output + '.runtime/state.json')).toBe(false); expect(open).not.toHaveBeenCalled(); }); - it('rejects an unfinished Westlake run with a frozen native team without changing its checkpoint', async () => { + it.each(['host-tools', 'native-agent-control'] as const)('preserves a historical Westlake checkpoint with %s transport', async transport => { + expect(await runSolver([...args, '--agent-team', '3', '--codex', process.execPath], root, modules)).toBe(0); const profile = path.join(example.directory, 'westlake-profile'); prepareWestlakeProfile(profile, 'deepseek-flash', 'high'); - expect(await runSolver([...args, '--agent-team', '3', '--harness-profile', profile, '--codex', process.execPath], root, modules)).toBe(0); const saved = state(); - saved.agentTeam!.transport = 'native-agent-control'; + saved.agentHarness = bindResearchHarness('codex', process.execPath, profile, process.env, saved.model); + saved.agentTeam!.transport = transport; const stateFile = output + '.runtime/state.json'; writeSolverRunState(stateFile, saved); const original = fs.readFileSync(stateFile); - expect(await runSolver([...args, '--resume'], root, modules)).toBe(1); - rejected('math_westlake_native_team_unsupported: create a new team run with your saved artifacts. Direct Westlake uses host tools for new runs.'); + if (transport === 'host-tools') { + await expect(runSolver([...args, '--resume'], root, modules, undefined, 'cli')) + .rejects.toThrow('math_legacy_collaboration_retired'); + } else { + expect(await runSolver([...args, '--resume'], root, modules, undefined, 'cli')).toBe(1); + rejected('math_westlake_native_team_unsupported: select a native-compatible Codex profile such as the Responses gateway.'); + } expect(fs.readFileSync(stateFile)).toEqual(original); expect(open).not.toHaveBeenCalled(); }); @@ -272,8 +251,6 @@ describe('opt-in skill research CLI and pinned identity', () => { }); it.each([ - { initial: 'team', changes: ['--skill-delegation', 'read-only'] }, - { initial: 'read-only', changes: ['--skill-delegation', 'team'] }, { initial: 'team', changes: ['--skill-max-agents', '2'] }, ])('rejects changing frozen $initial delegation through $changes on resume', async ({ initial, changes }) => { expect(await runSolver([...args, '--research-mode', 'skill', '--skill-delegation', initial, '--skill-max-agents', '3'], root, modules)).toBe(0); @@ -285,7 +262,7 @@ describe('opt-in skill research CLI and pinned identity', () => { }); it.each([ - ['--workers', '2'], ['--coordination', 'cooperative'], ['--module-plan', 'unused-team-plan.json'], ['--plan-approval'], + ['--coordination', 'cooperative'], ['--module-plan', 'unused-team-plan.json'], ].map(flags => ({ flags })))('rejects host-controlled team configuration $flags before opening any session', async ({ flags }) => { await expect(runSolver([...args, '--research-mode', 'skill', '--skill-delegation', 'team', '--skill-max-agents', '3', ...flags], root, modules)).rejects.toThrow('math_team_requires_single_lead'); @@ -293,6 +270,43 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(fs.existsSync(output + '.runtime/state.json')).toBe(false); }); + it.each([['--workers', '2'], ['--coordination', 'cooperative'], ['--skill-delegation', 'read-only']])( + 'rejects retired execution flag %s before starting or writing a run', async (...flags) => { + await expect(runSolver([...args, ...flags], root, modules)).rejects.toThrow('math_legacy_collaboration_retired'); + expect(fs.existsSync(output + '.runtime/state.json')).toBe(false); + expect(open).not.toHaveBeenCalled(); + }); + + it.each(['fixed workers', 'completed portfolio'] as const)('keeps history readable and rejects resuming %s', async mode => { + expect(await runSolver(args, root, modules)).toBe(0); + const historical = state(); + if (mode === 'fixed workers') { + historical.workerCount = 2; + historical.coordination = 'cooperative'; + } else historical.portfolioExploration = { phase: 'completed', durationMs: 1000, scouts: [] }; + const stateFile = output + '.runtime/state.json'; + writeSolverRunState(stateFile, historical); + const original = fs.readFileSync(stateFile); + expect(state()).toMatchObject({ runId: historical.runId, coordination: historical.coordination, + workerCount: historical.workerCount, ...(historical.portfolioExploration ? { portfolioExploration: historical.portfolioExploration } : {}) }); + await expect(runSolver([...args, '--resume'], root, modules, undefined, 'cli')) + .rejects.toThrow('math_legacy_collaboration_retired'); + expect(fs.readFileSync(stateFile)).toEqual(original); + expect(open).not.toHaveBeenCalled(); + }); + + it.each([false, true])('defaults public CLI runs to a native team, with optional approval %s', async required => { + const flags = [...args, ...(required ? ['--plan-approval'] : [])]; + expect(await runSolver(flags, root, modules, undefined, 'cli')).toBe(0); + const saved = state(); + expect(saved).toMatchObject({ agentTeam: { transport: 'native-agent-control' }, + researchDelegation: { mode: 'team', maxAgents: 4 }, workerCount: 1, turns: 0 }); + expect(Boolean(saved.planApproval)).toBe(required); + expect(await runSolver([...args, '--resume'], root, modules, undefined, 'cli')).toBe(0); + expect(state().runId).toBe(saved.runId); + expect(open).not.toHaveBeenCalled(); + }); + it.each(['claude-code', 'opencode', 'cli'] as const)('clearly rejects Agent-led team tools on the %s adapter', async id => { await expect(runSolver([...args, '--harness', id, '--model', 'offline-fixture', '--research-mode', 'skill', '--skill-delegation', 'team', '--skill-max-agents', '3'], root, modules)) @@ -301,11 +315,9 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(fs.existsSync(output + '.runtime/state.json')).toBe(false); }); - it.each([['--skill-delegation', 'read-only'], ['--skill-max-agents', '3'], + it.each([['--skill-max-agents', '3'], ['--skill-preferred-profiles', 'engineer'], - ['--research-mode', 'skill', '--skill-delegation', 'read-only', '--skill-preferred-profiles', 'engineer'], ['--research-mode', 'skill', '--skill-delegation', 'team', '--skill-max-agents', '9'], - ['--research-mode', 'skill', '--skill-delegation', 'read-only', '--skill-max-agents', '5'], ['--research-mode', 'skill', '--skill-loading', 'file', '--common-research-skill', 'native']].map(flags => ({ flags }))) ('rejects an incompatible optional research capability $flags', async ({ flags }) => { await expect(runSolver([...args, ...flags], root, modules)).rejects.toThrow(/invalid --/u); @@ -320,37 +332,6 @@ describe('opt-in skill research CLI and pinned identity', () => { rejected('math_resume_research_strategy_changed'); }); - it.each(['codex', 'claude-code', 'opencode'] as const)('prepares and resumes full Skill cooperation through %s', async id => { - const flags = id === 'codex' ? [] : harnessArguments(id).flags; - expect(await runSolver([...args, ...flags, '--research-mode', 'skill', '--workers', '4', '--plan-approval'], root, modules)).toBe(0); - const before = state(); - expect(before).toMatchObject({ researchMode: 'skill', researchSkillWorkflow: 'full', workerCount: 4, - coordination: 'cooperative', planApproval: true, agentSessionPlan: { harness: id, structuredOutput: 'none' } }); - expect(before.workers).toHaveLength(4); - for (const worker of before.workers!) expect(researchSkillIdentity(readMathAgentSkill( - path.join(worker.worktree, '.agents/skills/theoremos-research/SKILL.md'), before.researchSkill!.loading))).toEqual(before.researchSkill); - expect(await runSolver([...args, '--resume', '--plan-approval'], root, modules)).toBe(0); - expect(state()).toMatchObject({ runId: before.runId, workerCount: 4, coordination: 'cooperative', - researchSkillWorkflow: 'full', agentSessionPlan: before.agentSessionPlan }); - expect(open).not.toHaveBeenCalled(); - }); - - it('allows full independent Skill workers and retains the existing scheduler implementation', async () => { - expect(await runSolver([...args, '--research-mode', 'skill', '--workers', '2', '--coordination', 'independent', - '--scheduler', 'continuation'], root)).toBe(0); - expect(state()).toMatchObject({ researchSkillWorkflow: 'full', workerCount: 2, coordination: 'independent' }); - expect(state().workers).toHaveLength(2); - expect(state().moduleConfiguration!.versions.M3).toContain('continuation'); - }); - - it('allows full legacy host guidance on a non-Codex adapter', async () => { - const h = harnessArguments('claude-code'); - expect(await runSolver([...args, ...h.flags, '--research-mode', 'legacy'], root, modules)).toBe(0); - expect(state().researchSkill).toBeUndefined(); - expect(state()).toMatchObject({ workerCount: 4, coordination: 'cooperative', - agentSessionPlan: { harness: 'claude-code', skillLoading: 'none' } }); - }); - it('keeps old Skill checkpoints on their frozen single-researcher workflow', async () => { expect(await runSolver([...args, '--research-mode', 'skill'], root, modules)).toBe(0); const historical = state(); delete historical.researchSkillWorkflow; delete historical.agentSessionPlan; @@ -358,7 +339,7 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(await runSolver([...args, '--resume'], root, modules)).toBe(0); expect(state().researchSkillWorkflow).toBeUndefined(); expect(state().agentSessionPlan).toBeUndefined(); await expect(runSolver([...args, '--resume', '--workers', '2'], root, modules)) - .rejects.toThrow('math_skill_research_requires_single_independent_direct'); + .rejects.toThrow('math_legacy_collaboration_retired'); expect(open).not.toHaveBeenCalled(); }); @@ -370,9 +351,9 @@ describe('opt-in skill research CLI and pinned identity', () => { rejected('math_resume_session_plan_changed'); expect(open).not.toHaveBeenCalled(); }); - it('still rejects approval without a cooperative team', async () => { + it('rejects approval on a solo run', async () => { await expect(runSolver([...args, '--research-mode', 'skill', '--plan-approval'], root, modules)) - .rejects.toThrow('--plan-approval requires cooperative coordination and at least 2 workers'); + .rejects.toThrow('--plan-approval requires a native team'); }); it('rejects modified references on resume rather than silently refreshing a live strategy', async () => { diff --git a/tests/solver.test.ts b/tests/solver.test.ts index fa735d04..b41ccf6f 100644 --- a/tests/solver.test.ts +++ b/tests/solver.test.ts @@ -22,7 +22,8 @@ import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSes import { prepareDeepSeekProfile } from '../src/runtime/deepseek'; import { prepareWestlakeProfile } from '../src/runtime/westlake'; import { prepareSub2apiProfile } from '../src/runtime/sub2api'; -import { CooperativeResearch, readCooperationPlan, parseCooperationPlan, taskVersion, assignmentDeliveryFile, type CooperativeAction, type CooperativeTask, type RouteGroup } from '../src/solver/cooperation'; +import { readCooperationPlan } from '../src/solver/cooperationShared'; +import { parseCooperationPlan, taskVersion, assignmentDeliveryFile, type CooperativeAction, type CooperativeTask, type RouteGroup } from '../src/solver/tasks'; import { leadWakePending } from '../src/solver/leadWakes'; import { canonicalMathJson } from '../src/math/mathRuntimeIo'; import { deliveryDetails, readDeliveryLines, readMathResponse } from '../src/solver/deliveries'; @@ -270,38 +271,6 @@ describe('isolated solver and host acceptance', () => { expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ status: 'evaluated_passed', explanations: { status: 'disabled' } }); }); - it('runs the saved opt-in portfolio before proof dispatch and keeps scout Lean edits out of the proof worktree', async () => { - const flags = [...args, '--workers', '2', '--coordination', 'independent', '--max-turns', '3', '--no-explanations']; - expect(await runSolver([...flags, '--portfolio-exploration', '--portfolio-seconds', '30', '--startup-only'], directory)).toBe(0); - const stateFile = output + '.runtime/state.json'; - expect(readSolverRunState(stateFile).portfolioExploration).toMatchObject({ phase: 'exploring', durationMs: 30_000 }); - const dispatched: string[] = []; - host.createSession.mockImplementation(session('fixture-thread', async (options, message) => { - const worker = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - dispatched.push(worker); - const source = path.join(options.workspace, problem.projectRelative, 'Submission.lean'); - expect(fs.readFileSync(source, 'utf8')).toBe(original); - if (worker.startsWith('portfolio-')) { - const routeId = worker.slice('portfolio-'.length); - fs.writeFileSync(source, 'axiom scout_edit : False\n'); - fs.writeFileSync(path.join(options.workspace, 'PORTFOLIO.json'), JSON.stringify({ reports: [{ - routeId, status: 'proposed', blueprintSummary: 'Prove the original targets by a common reduction.', - keyTransformations: [], proposedFoundationLemmas: [], - }] })); - } else { - expect(message).toContain('Phase 1 portfolio gate'); - fs.writeFileSync(source, original.replaceAll('by sorry', 'by trivial')); - } - return 'completed'; - }, { stopForFreeze: async () => ({ status: 'stopped' }) })); - expect(await runSolver([...flags, '--resume'], directory)).toBe(0); - expect(dispatched.slice(0, 2).sort()).toEqual(['portfolio-explicit-constructive', 'portfolio-structural-symmetry']); - expect(dispatched).toHaveLength(3); - expect(readSolverRunState(stateFile)).toMatchObject({ - turns: 3, check: { passed: true }, portfolioExploration: { phase: 'completed' }, - }); - }); - it('does not generate explanations for failed acceptance', async () => { host.officialGate.mockResolvedValue({ comparison: { status: 'failed' } }); expect(await runSolver(args, directory)).toBe(2); @@ -395,26 +364,6 @@ describe('isolated solver and host acceptance', () => { return { file, source, text, sha256 }; } - it('freezes explicit attachments for all four roles while preserving the verbatim task digest', async () => { - const taskFile = args[args.indexOf('--task-file') + 1]; - const taskText = 'Preserve all controls.\n\n# Previous proof\nThis remains literal task text.\n'; - fs.writeFileSync(taskFile, taskText); - const fixture = continuationFixture(); - expect(await runSolver([...args, '--workers', '4', '--startup-only', '--continuation-manifest', fixture.file], directory)).toBe(0); - expect(host.createSession).not.toHaveBeenCalled(); - const state = readSolverRunState(`${output}.runtime/state.json`); - expect(state.taskDigest).toBe(mathDigest(taskText)); - expect(fs.readFileSync(taskFile, 'utf8')).toBe(taskText); - expect(state.continuationDigest).toMatch(/^[a-f0-9]{64}$/u); - for (const worker of state.workers!) { - const snapshot = path.join(worker.worktree, problem.projectRelative, '.lake/continuation.json'); - expect(fs.statSync(snapshot).mode & 0o777).toBe(0o400); - expect(readContinuationSnapshot(snapshot, state.continuationDigest!).manifest.taskDigest).toBe(state.taskDigest); - expect(readContinuationPage(snapshot, state.continuationDigest!, 'previous').text).toBe(fixture.text); - expect(fs.readdirSync(path.join(path.dirname(snapshot), 'continuation'))).toEqual([`${fixture.sha256}.txt`]); - } - }); - it('resumes from frozen attachments after the original input files are removed', async () => { const fixture = continuationFixture(); expect(await runSolver([...args, '--startup-only', '--continuation-manifest', fixture.file], directory)).toBe(0); @@ -537,29 +486,6 @@ describe('isolated solver and host acceptance', () => { return { ...hostFixture, receipt, catalog, hostedArgs: args.map(value => value === workspace ? hostedWorkspace : value) }; } - it('copies only authorized knowledge on hosted startup and rejects policy drift before resume', async () => { - const f = hostedKnowledgeFixture(); - const hostedArgs = [...f.hostedArgs, '--workers', '4', '--startup-only', '--knowledge-base', f.catalog.file]; - expect(await runSolver(hostedArgs, directory), vi.mocked(console.log).mock.calls.flat().join('\n')).toBe(0); - expect(host.createSession).not.toHaveBeenCalled(); - const state = readSolverRunState(output + '.runtime/state.json'); - for (const worker of state.workers!) { - const copy = path.join(worker.worktree, state.problem.projectRelative, '.lake/theorem-knowledge.json'); - const loaded = readKnowledgeCatalog(copy, f.catalog.sha256); - expect(loaded.base.libraryAuthorization!.binding).toEqual(f.receipt.libraryBinding); - expect(loaded.base.entries).toHaveLength(2); - } - fs.appendFileSync(f.configPath, ' '); - expect(await runSolver([...hostedArgs, '--resume'], directory)).toBe(1); - expect(host.createSession).not.toHaveBeenCalled(); - }); - it('rejects raw historical catalogs and continuation attachments before starting a hosted worker', async () => { - const f = hostedKnowledgeFixture(), raw = knowledgeFixture(); - expect(await runSolver([...f.hostedArgs, '--startup-only', '--knowledge-base', raw.file], directory)).toBe(1); - expect(await runSolver([...f.hostedArgs, '--continuation-manifest', '/missing'], directory)).toBe(1); - expect(await runSolver([...f.hostedArgs, '--workers', '2', '--continuation-source-run', '/missing'], directory)).toBe(1); - expect(host.createSession).not.toHaveBeenCalled(); - }); it('rejects a full release catalog before reading it or admitting a hosted provider', async () => { const f = hostedKnowledgeFixture(); expect(await runSolver([...f.hostedArgs, '--library-catalog', '/missing', @@ -615,23 +541,6 @@ describe('isolated solver and host acceptance', () => { expect(host.createSession).not.toHaveBeenCalled(); }); - it.each(['v1', 'v2'] as const)('prepares identical read-only %s knowledge snapshots for all four workers without opening a model', async format => { - const catalog = knowledgeFixture('knowledge.json', 'True', format); - expect(await runSolver([...args, '--workers', '4', '--startup-only', '--knowledge-base', catalog.file], directory)).toBe(0); - expect(host.createSession).not.toHaveBeenCalled(); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.knowledgeDigest).toBe(catalog.sha256); - for (const worker of state.workers) { - const snapshot = path.join(worker.worktree, 'generated/p/.lake/theorem-knowledge.json'); - expect(mathDigest(fs.readFileSync(snapshot))).toBe(catalog.sha256); - expect(fs.statSync(snapshot).mode & 0o222).toBe(0); - const saved = readKnowledgeCatalog(snapshot, catalog.sha256); - expect(saved.format).toBe(format); - expect(Object.values(saved.base.sources)).toEqual(Object.values(readKnowledgeCatalog(catalog.file).base.sources)); - } - expect(await runSolver([...args, '--workers', '4', '--startup-only', '--resume', '--knowledge-base', catalog.file], directory)).toBe(0); - }); - it('offers pinned knowledge commands to the solver while retaining independent proof acceptance', async () => { const catalog = knowledgeFixture(); const entry = readKnowledgeCatalog(catalog.file).base.entries[0]!; @@ -716,70 +625,6 @@ describe('isolated solver and host acceptance', () => { expect(host.createSession).not.toHaveBeenCalled(); }); - it('runs independent peers without planning or sharing and accounts for both sessions', async () => { - let started = 0; - const bothStarted = deferred(); - host.createSession.mockImplementation(session('independent', async (options, message) => { - expect(message).not.toContain('Cooperative assignment:'); - expect(fs.existsSync(path.join(options.workspace, 'COOPERATION.json'))).toBe(false); - options.onUsage({ totalTokens: 100, inputTokens: 80, outputTokens: 20 }); - if (++started === 2) bothStarted.resolve(); - await bothStarted.promise; - fs.writeFileSync(path.join(options.workspace, 'generated/p/Submission.lean'), original.replaceAll('by sorry', 'by trivial')); - return 'completed'; - })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '2', '--coordination', 'independent'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation).toBeUndefined(); - expect(state.coordination).toBe('independent'); - expect(state.turns).toBe(2); - expect(state.dispatchCounts).toEqual({ proof: 2 }); - expect(state.workers.map((worker: any) => worker.dispatchCounts)).toEqual([{ proof: 1 }, { proof: 1 }]); - expect(JSON.parse(fs.readFileSync(output, 'utf8')).solveWallMs).toBeGreaterThanOrEqual(0); - expect(state.usage).toEqual({ totalTokens: 200, inputTokens: 160, outputTokens: 40 }); - expect(state.workers.map((worker: any) => worker.turns)).toEqual([1, 1]); - expect(host.createSession).toHaveBeenCalledTimes(2); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('lets independent proof work exceed twenty dispatches under the default wall-time budget', async () => { - const attempts = new Map(); - host.verify.mockImplementation(async request => { - const checked = verified(request); - return fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8').includes('sorry') ? failed(checked) : checked; - }); - host.createSession.mockImplementation(session(options => options.workspace, async options => { - const count = (attempts.get(options.workspace) ?? 0) + 1; - attempts.set(options.workspace, count); - await Promise.resolve(); - if (count === 6) fs.writeFileSync(path.join(options.workspace, 'generated/p/Submission.lean'), - original.replaceAll('by sorry', 'by trivial')); - return 'completed'; - })); - const defaultBudget = args.filter((_, index) => args[index] !== '--max-turns' && args[index - 1] !== '--max-turns'); - expect(await runSolver([...defaultBudget, '--workers', '4', '--coordination', 'independent'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.turns).toBeGreaterThan(20); - expect(state.turns).toBeLessThanOrEqual(24); - expect(state.dispatchCounts).toEqual({ proof: state.turns }); - expect(state.workers.every((worker: any) => worker.turns >= 5)).toBe(true); - }); - - it('counts failed independent turns within one shared budget', async () => { - host.verify.mockImplementation(async request => failed(verified(request))); - host.createSession.mockImplementation(session('failed-independent', async options => { - options.onUsage({ totalTokens: 75 }); return 'failed'; - }, { lastError: 'fixture model failure' })); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '3', '--coordination', 'independent'], directory)).toBe(1); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.turns).toBe(3); - expect(state.usage.totalTokens).toBe(225); - expect(host.createSession).toHaveBeenCalledTimes(3); - expect(state.error).toBe('math_model_turn_failed'); - expect(state.workers.filter((worker: any) => worker.turns).every((worker: any) => worker.error === 'math_model_turn_failed')).toBe(true); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - it('stops new model turns at the reported token allowance without cancelling final proof verification', async () => { host.createSession.mockImplementation(session('token-proof', async options => { options.onUsage({ totalTokens: 120, inputTokens: 100, outputTokens: 20 }); @@ -797,29 +642,6 @@ describe('isolated solver and host acceptance', () => { expect((await host.createSession.mock.results[0].value).interrupt).not.toHaveBeenCalled(); }); - it('uses one reported allowance across independent workers and records in-flight overrun', async () => { - host.verify.mockImplementation(async request => failed(verified(request))); - let started = 0; - const running = deferred(); - const runs = vi.fn(); - const interrupts = vi.fn(); - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ threadId: options.workspace, - run: async () => { - runs(); if (++started === 4) running.resolve(); await running.promise; - options.onUsage({ totalTokens: 40 }); - return 'completed'; - }, close: vi.fn(), interrupt: interrupts })); - expect(await runSolver([...args, '--workers', '4', '--coordination', 'independent', '--max-turns', '20', - '--max-total-tokens', '100'], directory)).toBe(4); - const result = JSON.parse(fs.readFileSync(output, 'utf8')); - expect(result).toMatchObject({ status: 'limit_reached', reason: 'math_total_token_limit', turns: 4, - usage: { totalTokens: 160 }, tokenBudget: { maxTotalTokens: 100, status: 'exhausted', - reportedTotalTokens: 160, overrunTokens: 60, usageComplete: true } }); - expect(runs).toHaveBeenCalledTimes(4); - expect(interrupts).not.toHaveBeenCalled(); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - it.each([false, true])('gates internal requests without losing complete usage or final proof checks (solved: %s)', async solved => { const profile = path.join(directory, 'westlake-request-budget'); prepareWestlakeProfile(profile, 'deepseek-flash', 'high'); @@ -860,29 +682,6 @@ describe('isolated solver and host acceptance', () => { expect(host.officialGate).toHaveBeenCalledTimes(Number(solved)); }); - it('uses complete receipts from concurrent peers before allowing their next internal request', async () => { - host.verify.mockImplementation(async request => failed(verified(request))); - let started = 0, settled = 0; - const running = deferred(), consumed = deferred(); - const requests = vi.fn(); - host.createSession.mockImplementation(session(options => options.workspace, async options => { - const admission = options.requestGate!(); expect(admission.allowed).toBe(true); - if (admission.allowed) { - requests(); if (++started === 2) running.resolve(); await running.promise; - admission.settle({ usage: { totalTokens: 60, inputTokens: 50, outputTokens: 10 }, complete: true }); - if (++settled === 2) consumed.resolve(); await consumed.promise; - } - expect(options.requestGate!()).toEqual({ allowed: false, reason: 'math_total_token_limit' }); - return 'failed'; - }, { usageSource: 'upstream-requests' })); - expect(await runSolver([...args, '--workers', '2', '--coordination', 'independent', '--max-turns', '20', '--max-total-tokens', '100'], directory)).toBe(4); - expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ status: 'limit_reached', reason: 'math_total_token_limit', - usage: { totalTokens: 120 }, tokenBudget: { status: 'exhausted', usageComplete: true, overrunTokens: 20 } }); - expect(requests).toHaveBeenCalledTimes(2); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.workers.every((worker: any) => worker.requestUsageAccounting.startedRequests === 1 && !worker.requestUsageAccounting.incomplete)).toBe(true); - }); - it('blocks internal requests immediately after a missing receipt and retains known earlier usage', async () => { host.verify.mockImplementation(async request => failed(verified(request))); host.createSession.mockImplementation(session('request-missing-usage', async options => { @@ -903,30 +702,6 @@ describe('isolated solver and host acceptance', () => { expect(host.delay).not.toHaveBeenCalled(); }); - it('keeps a peer rejected before its first upstream request at known zero consumption', async () => { - host.verify.mockImplementation(async request => failed(verified(request))); - let entered = 0; - const running = deferred(), exhausted = deferred(); - host.createSession.mockImplementation(session(options => options.workspace, async options => { - if (++entered === 2) running.resolve(); await running.promise; - if (options.environment?.DEEPSCIENTIST_MATH_WORKER_ID === 'solver') { - const admission = options.requestGate!(); - expect(admission.allowed).toBe(true); - if (admission.allowed) admission.settle({ usage: { totalTokens: 120, inputTokens: 100, outputTokens: 20 }, complete: true }); - exhausted.resolve(); return 'completed'; - } - await exhausted.promise; - expect(options.requestGate!()).toEqual({ allowed: false, reason: 'math_total_token_limit' }); - return 'failed'; - }, { usageSource: 'upstream-requests' })); - expect(await runSolver([...args, '--workers', '2', '--coordination', 'independent', '--max-turns', '20', '--max-total-tokens', '100'], directory)).toBe(4); - expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ status: 'limit_reached', reason: 'math_total_token_limit', - usage: { totalTokens: 120 }, tokenBudget: { reportedTotalTokens: 120, usageComplete: true } }); - const peer = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).workers[1]; - expect(peer.turns).toBe(1); expect(peer.usage).toBeUndefined(); - expect(peer.requestUsageAccounting).toEqual({ startedRequests: 0, reportedRequests: 0, pendingRequests: 0, incomplete: false }); - }); - it.each([false, true])('adds receipts after resuming a thread and preserves its historical label (legacy: %s)', async legacy => { const profile = path.join(directory, 'request-resume-profile'); prepareWestlakeProfile(profile, 'deepseek-flash', 'high'); @@ -991,24 +766,6 @@ describe('isolated solver and host acceptance', () => { expect(state.tokenBudget).toMatchObject({ reportedTotalTokens: 80, usageComplete: true, status: 'available' }); }); - it.each([false, true])('fails closed on unavailable completed usage with a finite allowance (partial: %s)', async partial => { - host.verify.mockImplementation(async request => failed(verified(request))); - const runs = vi.fn(); - let started = 0; - const running = deferred(); - host.createSession.mockImplementation(session(options => options.workspace, async options => { - runs(); if (++started === (partial ? 2 : 1)) running.resolve(); await running.promise; - if (partial && options.environment?.DEEPSCIENTIST_MATH_WORKER_ID === 'solver') options.onUsage({ totalTokens: 40 }); - return 'completed'; - })); - expect(await runSolver([...args, '--workers', partial ? '2' : '1', '--coordination', 'independent', - '--max-turns', '20', '--max-total-tokens', '100'], directory)).toBe(4); - expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ status: 'limit_reached', reason: 'math_model_usage_unavailable', - tokenBudget: { status: 'usage-unavailable', usageComplete: false, reportedTotalTokens: partial ? 40 : null } }); - expect(runs).toHaveBeenCalledTimes(partial ? 2 : 1); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - it.each(['transport', 'exception', 'failed', 'checkpoint', 'interrupted'] as const) ('keeps intermediate usage incomplete after a %s model turn with a finite allowance', async failure => { host.verify.mockImplementation(async request => failed(verified(request))); @@ -1085,39 +842,6 @@ describe('isolated solver and host acceptance', () => { tokenBudget: { status: 'unlimited', reportedTotalTokens: 80, usageComplete: false } }); }); - it('rechecks the shared allowance after opening a session while another worker consumes it', async () => { - host.verify.mockImplementation(async request => failed(verified(request))); - const peerOpening = deferred(), allowanceConsumed = deferred(); - const runs = vi.fn(); - host.createSession.mockImplementation(async (options: MathAgentOptions) => { - const lead = options.environment?.DEEPSCIENTIST_MATH_WORKER_ID === 'solver'; - if (!lead) { peerOpening.resolve(); await allowanceConsumed.promise; } - return { threadId: options.workspace, run: async () => { - runs(); await peerOpening.promise; - options.onUsage({ totalTokens: 100 }); allowanceConsumed.resolve(); return 'completed'; - }, close: vi.fn(), interrupt: vi.fn() }; - }); - expect(await runSolver([...args, '--workers', '2', '--coordination', 'independent', '--max-turns', '20', - '--max-total-tokens', '100'], directory)).toBe(4); - expect(host.createSession).toHaveBeenCalledTimes(2); - expect(runs).toHaveBeenCalledOnce(); - expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ status: 'limit_reached', turns: 1, - tokenBudget: { status: 'exhausted', reportedTotalTokens: 100, usageComplete: true } }); - }); - - it('admits the actual model request atomically after asynchronous turn preparation', async () => { - host.verify.mockImplementation(async request => failed(verified(request))); - const runs = vi.fn(); - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ threadId: options.workspace, - run: async () => { runs(); options.onUsage({ totalTokens: 100 }); return 'completed'; }, - close: vi.fn(), interrupt: vi.fn() })); - expect(await runSolver([...args, '--workers', '2', '--coordination', 'independent', '--max-turns', '20', - '--max-total-tokens', '100'], directory)).toBe(4); - expect(runs).toHaveBeenCalledOnce(); - expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ turns: 1, dispatchCounts: { proof: 1 }, - tokenBudget: { status: 'exhausted', reportedTotalTokens: 100, usageComplete: true } }); - }); - it.each([80, 0])('retains the cumulative token allowance on resume and allows explicitly changing it to %s', async allowance => { let turns = 0; host.verify.mockImplementation(async request => turns < 2 ? failed(verified(request)) : verified(request)); @@ -1145,7 +869,7 @@ describe('isolated solver and host acceptance', () => { it.each(['coordination', 'scheduler'])('freezes the CLI %s policy across resume', async policy => { expect(await runSolver([...args, '--startup-only'], directory)).toBe(0); const prepared = fs.readFileSync(output, 'utf8'); - expect(await runSolver([...args, '--resume', `--${policy}`, policy === 'scheduler' ? 'continuation' : 'independent'], directory)).toBe(1); + expect(await runSolver([...args, '--resume', `--${policy}`, policy === 'scheduler' ? 'continuation' : 'cooperative'], directory)).toBe(1); expect(fs.readFileSync(output, 'utf8')).toBe(prepared); expect(host.createSession).not.toHaveBeenCalled(); }); @@ -1996,734 +1720,6 @@ describe('isolated solver and host acceptance', () => { }); } - it.each(['adopted', 'unadopted'] as const)('presents a research proposal to an ordinary Lead plan that leaves it %s', async status => { - const question: CooperativeTask = { id: 'question', kind: 'research', objective: 'Find a concrete bridge', dependsOn: [], revision: 0 }; - const proposal: CooperativeTask = { ...planTasks()[0], id: 'bridge', theoremName: 'Submission.bridge', objective: 'Bridge for the first original goal' }; - const initial = [question, ...planTasks().slice(2).map(task => ({ ...task, status: 'paused' as const, - dependsOn: task.id === 'first' ? ['question'] : task.dependsOn }))]; - let plans = 0; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - if (++plans === 1) { writePlan(options.workspace, initial); return 'completed'; } - expect(message).toContain('Research inputs for this planning decision'); - expect(message).toContain(JSON.stringify(proposal.theoremName)); - expect(cooperationState().tasks.find((item: any) => item.task.id === 'first').attempts).toBe(0); - expect(host.officialGate).not.toHaveBeenCalled(); - const tasks = [question, ...(status === 'adopted' ? [proposal] : []), ...initial.slice(1).map(task => ({ ...task, - status: 'active', dependsOn: task.id === 'first' && status === 'adopted' ? ['bridge'] : task.dependsOn }))]; - const deliveryId = /"deliveryId":"([^"]+)"/u.exec(message)?.[1]; - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), JSON.stringify({ tasks, - researchDecisions: [{ deliveryId, outcome: status === 'adopted' ? 'adopt' : 'decline', - ...(status === 'adopted' ? { taskIds: ['bridge'] } : {}), - reason: status === 'adopted' ? 'The exact bridge is a new proof obligation for the first goal.' : - 'The first goal has a direct proof without this proposed bridge.' }] })); - } else if (action.kind === 'task' && action.task.id === question.id) { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), JSON.stringify({ - summary: 'This exact bridge has a concrete original-goal consumer.', conclusion: 'supporting', lemmaRequests: [proposal] })); - } else if (action.kind === 'task' && action.task.kind === 'goal') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'), name = action.task.theoremName!.split('.').at(-1); - const proof = name === 'first' ? status === 'adopted' ? 'by exact bridge' : 'by trivial' : 'by exact first'; - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${name} : True := by sorry`, `${name} : True := ${proof}`)); - } else finishAssignment(action, options); - return 'completed'; - }); - const code = await runSolver([...args, '--workers', '2', '--max-turns', '9'], directory); - expect(code, JSON.parse(fs.readFileSync(output, 'utf8')).reason).toBe(0); - const state = cooperationState(); - expect(state.tasks.find((item: any) => item.task.id === 'bridge')?.status).toBe(status === 'adopted' ? 'integrated' : undefined); - expect(unadoptedProposals(state).map((task: CooperativeTask) => task.id)).toEqual(status === 'adopted' ? [] : ['bridge']); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - function proposalQueue(count = 18) { - const question: CooperativeTask = { id: 'question', kind: 'research', objective: 'Investigate exact bridges', dependsOn: [], revision: 0 }; - const proposals = Array.from({ length: count }, (_, index) => ({ ...planTasks()[0], - id: `bridge_${index}`, theoremName: `Submission.bridge_${index}` })); - const tasks = [...planTasks().slice(2).map(task => ({ ...task, dependsOn: [], status: 'paused' as const })), question]; - const plan = parseCooperationPlan(problem, { tasks }); - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peer = { ...lead, id: 'researcher-1', role: 'researcher' } as const; - const state = { problem, environmentDigest: 'environment', turns: 0, - cooperation: { planVersion: mathDigest(canonicalMathJson({ tasks: plan.tasks, groups: plan.groups })), - tasks: plan.tasks.map(task => ({ task, status: task.id === question.id ? 'completed' : 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })), deliveries: [{ - id: 'proposals', producer: peer.id, taskId: question.id, taskDigest: taskVersion(question), kind: 'research', status: 'advisory', - summary: 'Exact bridge proposals.', statement: '', premises: [], dependencies: [], remainingObligations: [], - evidenceRefs: [], createdAt: 1, lemmaRequests: proposals }] } } as any; - const emit = vi.fn(); - const create = (restored = state) => new CooperativeResearch({ state: restored, workers: [lead, peer], access: new Map(), - signal: new AbortController().signal, modules: directSolverModules, - save: vi.fn(), emit, exclusiveCheck: check => check() }); - return { state, question, proposals, lead, peer, emit, create, cooperative: create() }; - } - - it('does not let unadopted proposals bypass the repeated invalid-plan guard', async () => { - const { state, lead, emit, create, cooperative } = proposalQueue(); - for (let attempt = 0; attempt < 2; attempt++) { - const action = await cooperative.next(lead, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'lead') throw new Error('missing_proposal_retry'); - writePlan(workspace, state.cooperation.tasks.map((item: any, index: number) => - index ? item.task : { ...item.task, dependsOn: ['missing_input'] })); - await cooperative.deliver(lead, action, commitSolverSources(problem, workspace)); - } - expect(state.cooperation.planRejection.stalled).toBe(true); - expect(await cooperative.next(lead, { maxTurns: Infinity, remainingMs: Infinity })).toBeUndefined(); - expect(emit).toHaveBeenCalledWith('plan_stalled', expect.anything()); - expect(unadoptedProposals(state.cooperation)).toHaveLength(18); - const restored = JSON.parse(JSON.stringify(state)), resumed = create(restored); - await resumed.restore(); - expect(await resumed.next(lead, { maxTurns: Infinity, remainingMs: Infinity })).toBeUndefined(); - expect(restored.cooperation.planRejection.stalled).toBe(true); - expect(unadoptedProposals(restored.cooperation)).toHaveLength(18); - }); - - it('gives a ready original goal to a live peer after its pinned engineer exits instead of waiting for an impossible assignment', async () => { - const tasks = planTasks().slice(2).map(task => ({ ...task, dependsOn: task.id === 'first' ? [] : ['first'] })); - const plan = parseCooperationPlan(problem, { tasks, groups: [{ id: 'main', objective: 'Original goals', engineerId: 'engineer' }] }); - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peer = { ...lead, id: 'researcher-1', role: 'researcher' } as const; - const engineer = { ...lead, id: 'engineer', role: 'engineer' } as const; - const state = { problem, environmentDigest: 'environment', turns: 0, - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } } as any; - const cooperative = new CooperativeResearch({ state, workers: [lead, peer, engineer], access: new Map(), signal: new AbortController().signal, - modules: directSolverModules, save: vi.fn(), emit: vi.fn(), exclusiveCheck: check => check() }); - expect(assessTaskResponsibility(state.cooperation.tasks[0], peer, state.cooperation)).toEqual({ kind: 'blocked', reason: 'engineer' }); - cooperative.stopped(engineer, 'math_model_request_failed'); - // A stopped engineer's route pin no longer binds live peers, so no replanning turn is needed. - expect(await cooperative.next(peer, { maxTurns: Infinity, remainingMs: Infinity })).toMatchObject({ kind: 'task', task: { id: 'first' } }); - expect(state.cooperation.groups[0].group.engineerId).toBe('engineer'); - expect(host.createSession).not.toHaveBeenCalled(); - }); - - it.each([false, true])('allocates exploration from synchronous reservations with a cooling peer: %s', async coolingPeer => { - await withSolverWorktree(workspace, problem.baseCommit, async researcherRoot => { - await withSolverWorktree(workspace, problem.baseCommit, async engineerRoot => { - const tasks: CooperativeTask[] = [...planTasks().slice(0, 2), - { id: 'alternative', kind: 'research', objective: 'Investigate a distinct route', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, conditional: false }))]; - const plan = parseCooperationPlan(problem, { tasks }); - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const researcher = { ...lead, id: 'researcher-1', role: 'researcher', worktree: researcherRoot } as const; - const engineer = { ...lead, id: 'engineer', role: 'engineer', worktree: engineerRoot } as const; - const workers = [lead, researcher, engineer, ...(coolingPeer ? [{ ...researcher, id: 'cooling-peer' }] : [])]; - const state: any = { problem, environmentDigest: 'environment', turns: 0, - workers: workers.map(worker => ({ ...worker, turns: 0, phase: 'running', - ...(worker.id === 'cooling-peer' ? { recovery: { phase: 'cooling-down', reason: 'math_model_request_failed', - cycles: 1, startedAt: 1, nextRetryAt: Date.now() + 60_000, waitedMs: 0 } } : {}) })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }; - const cooperative = new CooperativeResearch({ state, workers, access: new Map(), signal: new AbortController().signal, - modules: directSolverModules, save: vi.fn(), emit: vi.fn(), exclusiveCheck: check => check() }); - try { - expect(await cooperative.next(researcher, { maxTurns: Infinity, remainingMs: Infinity })) - .toMatchObject({ kind: 'task', task: { id: 'a' } }); - expect(await cooperative.next(engineer, { maxTurns: Infinity, remainingMs: Infinity })) - .toMatchObject({ kind: 'task', task: { id: 'alternative' } }); - expect(state.cooperation.tasks.find((node: TaskRecord) => node.task.id === 'b').status).toBe('pending'); - expect(host.createSession).not.toHaveBeenCalled(); - } finally { await cooperative.stop(); } - }); - }); - }); - - it('starts peer work after a completed invalid initial plan without consuming an unlimited planning loop', async () => { - let leadTurns = 0; - const peers = new Set(); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - leadTurns++; - writePlan(options.workspace, planTasks().map(task => task.id === 'a' ? { ...task, theoremName: 'Submission.bad;name' } : task)); - } else if (action.kind === 'task') { - peers.add(action.assignment.workerId); - if (action.task.kind === 'goal') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - const name = action.task.theoremName!.split('.').at(-1); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${name} : True := by sorry`, `${name} : True := by trivial`)); - } else fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'Independent route findings retained.'); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '0'], directory)).toBe(0); - const state = cooperationState(); - expect(leadTurns).toBe(1); - expect(peers.size).toBeGreaterThanOrEqual(2); - expect(state.initialPlanFallback.reason).toContain('math_plan_invalid_proof_target'); - expect(state.tasks.filter((node: any) => node.task.kind === 'goal').every((node: any) => node.status === 'integrated')).toBe(true); - expect(readCooperationPlan(problem, `${output}.runtime/worktree`).tasks).toEqual(state.tasks.map((node: any) => node.task)); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each(['environment', 'peer-evidence'])('parks identical rejected plans across notes commits and resume, and retries after new %s', async input => { - const plan = parseCooperationPlan(problem, { tasks: planTasks().map(task => ({ ...task, status: 'paused' })) }); - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peer = { ...lead, id: 'researcher-1', role: 'researcher' } as const; - const state: any = { problem, runId: 'rejected-plan', turns: 0, phase: 'running', environmentDigest: 'fixture', - cooperation: { error: 'repair_requested', canonicalCommit: problem.baseCommit, - planVersion: mathDigest(canonicalMathJson(plan)), tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }; - const progress = { id: 'known-progress', taskId: plan.tasks[0].id, taskDigest: taskVersion(plan.tasks[0]), - kind: 'progress', status: 'advisory', summary: 'Known obstacle.', evidenceRefs: [], dependencies: [], remainingObligations: [] }; - state.cooperation.deliveries = [progress]; - const events: string[] = []; - const create = () => new CooperativeResearch({ state, workers: [lead, peer], access: new Map(), - signal: new AbortController().signal, save: () => {}, emit: event => events.push(event), modules: directSolverModules, - exclusiveCheck: async check => check() }); - const cooperative = create(), budget = { maxTurns: Infinity, remainingMs: Infinity }; - const invalid = plan.tasks.map(task => task.id === 'first' ? { ...task, theoremName: 'Submission.changed' } : task); - const commits: string[] = []; - for (let attempt = 0; attempt < 2; attempt++) { - const action = await cooperative.next(lead, budget); - expect(action?.kind).toBe('lead'); - if (action?.kind !== 'lead') throw new Error('missing_repair_assignment'); - writePlan(workspace, invalid); - fs.appendFileSync(path.join(workspace, 'RESEARCH.md'), `\nRepeated blocker explanation ${attempt}.\n`); - const commit = commitSolverSources(problem, workspace); commits.push(commit); - await cooperative.deliver(lead, action, commit); - } - expect(commits[0]).not.toBe(commits[1]); - expect(state.cooperation.planRejection).toMatchObject({ stalled: true, error: expect.stringMatching(/^math_plan_changed_original_target: /u) }); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(events).toContain('plan_stalled'); - await cooperative.stop(); - const resumed = create(); - await resumed.restore(); - expect(await resumed.next(lead, budget)).toBeUndefined(); - state.cooperation.deliveries.push({ ...progress, id: 'heartbeat-new-id', createdAt: 42 }); - expect(await resumed.next(lead, budget)).toBeUndefined(); - if (input === 'environment') state.environmentDigest = 'repaired-environment'; - else state.cooperation.deliveries = [{ id: 'new-progress', taskId: plan.tasks[0].id, - taskDigest: taskVersion(plan.tasks[0]), kind: 'progress', status: 'advisory', summary: 'New concrete library evidence.', - evidenceRefs: ['Library.connection'], dependencies: [], remainingObligations: [] }]; - const reopened = await resumed.next(lead, budget); - expect(reopened?.kind).toBe('lead'); - if (reopened?.kind !== 'lead') throw new Error('missing_reopened_assignment'); - writePlan(workspace, plan.tasks); - await resumed.deliver(lead, reopened, commitSolverSources(problem, workspace)); - expect(state.cooperation.planRejection).toBeUndefined(); - expect(state.cooperation.error).toBeUndefined(); - expect(host.createSession).not.toHaveBeenCalled(); - expect(host.officialGate).not.toHaveBeenCalled(); - await resumed.stop(); - }); - - it('retries an unfinished parked-frontier plan after restore and remembers a completed plan', async () => { - const plan = parseCooperationPlan(problem, { tasks: planTasks() }); - writePlan(workspace, plan.tasks); - const canonicalCommit = commitSolverSources(problem, workspace); - let state: any = { problem, runId: 'frontier-restore', turns: 0, phase: 'running', environmentDigest: 'fixture', - cooperation: { canonicalCommit, tasks: plan.tasks.map(task => ({ task, attempts: task.kind === 'lemma' ? 1 : 0, - status: task.kind === 'lemma' ? 'blocked' : 'pending' })), groups: plan.groups.map(group => ({ group, turns: 0 })), blockers: [] } }; - const core = state.cooperation.tasks[0], blockers = state.cooperation.blockers; - const proposal = { mechanism: 'A checked analytic input is missing.', scope: 'The core inference.', - reopenOn: [{ kind: 'contract-changed' as const }] }; - for (let i = 0; i < 2; i++) recordRouteBlockers(blockers, [proposal], core.task, state.cooperation.tasks, - state.environmentDigest, problem.receiptDigest); - refreshRouteBlockers(blockers, state.cooperation.tasks, state.environmentDigest, problem.receiptDigest); - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peer = { ...lead, id: 'researcher-1', role: 'researcher' } as const; - const create = () => new CooperativeResearch({ state, workers: [lead, peer], access: new Map(), - signal: new AbortController().signal, save: () => {}, emit: () => {}, modules: directSolverModules, - exclusiveCheck: async check => check() }); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const initial = create(); await initial.restore(); - expect(await initial.next(lead, budget)).toMatchObject({ kind: 'lead' }); - expect(state.cooperation.lastLeadInputDigest).toBeUndefined(); - await initial.stop(); state = JSON.parse(JSON.stringify(state)); - const resumed = create(); await resumed.restore(); - const action = await resumed.next(lead, budget); - expect(action).toMatchObject({ kind: 'lead' }); - if (action?.kind !== 'lead') throw new Error('missing_resumed_frontier_assessment'); - writePlan(workspace, plan.tasks); - await resumed.deliver(lead, action, commitSolverSources(problem, workspace)); - expect(state.cooperation.lastLeadInputDigest).toBe(action.planningInputDigest); - expect(state.cooperation.tasks[0].routeParking).toHaveLength(1); - await resumed.stop(); state = JSON.parse(JSON.stringify(state)); - const completed = create(); await completed.restore(); - // The answered blocked frontier does not request the same Lead input again. - expect(leadWakePending(state.cooperation.leadWakes)).toBe(false); - await completed.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - it.each(['official_verified', 'failed'])('retains independent acceptance after integrating an original definition goal (%s)', async officialStatus => { - const { task } = configureDefinitionGoal(); - const tasks: CooperativeTask[] = [task, ...['first', 'second'].map(name => ({ id: name, kind: 'goal' as const, - objective: `Prove ${name} after filling the constant`, theoremName: `Submission.${name}`, proofPath: 'Submission.lean', - dependsOn: ['constant'], revision: 0 }))]; - host.officialGate.mockResolvedValue({ comparison: { status: officialStatus } }); - configureCooperation(async (action, options) => { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task') { - expect(host.officialGate).not.toHaveBeenCalled(); - const source = fs.readFileSync(file, 'utf8'); - if (action.task.id === 'constant') { - expect(options.instructions).toContain('An original goal may be a def'); - expect(source).toContain('theorem first : True := by sorry'); - expect(source).toContain('theorem second : True := by sorry'); - fs.writeFileSync(file, source.replace('C : Nat := by sorry', 'C : Nat := 7')); - } else { - expect(source).toContain('noncomputable def C : Nat := 7'); - fs.writeFileSync(file, source.replace(`${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } - } else throw new Error('unexpected_definition_goal_action'); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '3', '--max-turns', '7'], directory)).toBe(officialStatus === 'official_verified' ? 0 : 2); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks.every((node: any) => node.status === 'integrated')).toBe(true); - expect(state.cooperation.review).toBeUndefined(); - expect(host.officialGate).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls.filter(([request]) => request.items.length === problem.targets.length).length).toBeGreaterThanOrEqual(2); - expect(JSON.parse(fs.readFileSync(output, 'utf8')).status).toBe(officialStatus === 'official_verified' ? 'evaluated_passed' : 'evaluated_failed'); - }); - - it('counts cooperative planning toward the token allowance and leaves unstarted proof work resumable', async () => { - configureCooperation(); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '0', '--max-total-tokens', '1200'], directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state).toMatchObject({ turns: 1, dispatchCounts: { planning: 1 }, - tokenBudget: { status: 'exhausted', reportedTotalTokens: 1200, usageComplete: true } }); - expect(state.cooperation.tasks.map((node: any) => node.status)).toEqual(['pending', 'pending', 'pending', 'pending']); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('continues through proof checks and independent acceptance after a bounded initial planning checkpoint', async () => { - configureCooperation(); - let leadTurns = 0, proofTurns = 0; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ - threadId: options.threadId ?? `bounded-${options.environment!.DEEPSCIENTIST_MATH_WORKER_ID}`, - usageSource: 'upstream-requests' as const, lastError: 'HTTP 403 Forbidden', - lastFailureDiagnostic: { code: 'unauthorized' as const }, close: vi.fn(), interrupt: vi.fn(), - run: async (message: string) => { - const action = assignmentFrom(message); - const admission = options.requestGate!(); expect(admission.allowed).toBe(true); - const totalTokens = action.kind === 'lead' ? 300 : 20; - if (admission.allowed) admission.settle({ usage: { totalTokens, inputTokens: totalTokens - 5, outputTokens: 5 }, complete: true }); - if (action.kind === 'lead') { - leadTurns++; - expect(options.requestGate!()).toEqual({ allowed: false, reason: 'math_initial_planning_limit' }); - return 'failed'; - } - if (action.kind === 'task' && action.task.kind === 'goal') { - proofTurns++; - expect(host.officialGate).not.toHaveBeenCalled(); - const file = path.join(options.workspace, problem.projectRelative, action.task.proofPath!); - const name = action.task.theoremName!.split('.').at(-1); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${name} : True := by sorry`, `${name} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }, - })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8', '--max-total-tokens', '1000'], directory)).toBe(0); - const state = readSolverRunState(`${output}.runtime/state.json`); - expect(leadTurns).toBe(1); expect(proofTurns).toBe(2); - expect(state.cooperation!.initialPlanFallback).toBeDefined(); - expect(state.tokenBudget).toMatchObject({ status: 'available', usageComplete: true }); - expect(state.workers!.every(worker => !worker.lastFailure && !worker.error)).toBe(true); - expect(state.cooperation!.tasks.every(node => node.status === 'integrated')).toBe(true); - expect(state.check?.passed).toBe(true); - expect(JSON.parse(fs.readFileSync(output, 'utf8')).status).toBe('evaluated_passed'); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('keeps cooperative in-flight helper checks after reaching the shared token allowance', async () => { - let started = 0; - const bothStarted = deferred(); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - // Both proof slots must reach the helper barrier before this fixture exhausts its allowance. - writePlan(options.workspace, planTasks().map(task => task.kind === 'goal' ? { ...task, conditional: false } : task)); - return 'completed'; - } - if (action.kind === 'task' && action.task.kind === 'lemma') { - if (++started === 2) bothStarted.resolve(); await bothStarted.promise; - } - finishAssignment(action, options); return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '0', '--max-total-tokens', '3600'], directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state).toMatchObject({ turns: 3, dispatchCounts: { planning: 1, proof: 2 }, - tokenBudget: { status: 'exhausted', reportedTotalTokens: 3600, usageComplete: true } }); - expect(state.cooperation.tasks.map((node: any) => node.status)).toEqual(['integrated', 'integrated', 'pending', 'pending']); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('commits saved cooperative proofs on the host and persists worker activity', async () => { - configureCooperation(async (action, options, message) => { - if (action.kind === 'task') { - expect(options.instructions).toContain('save the assigned declaration and return for host checking'); - expect(message).not.toContain('commit allowed sources and notes'); - expect(options.instructions).not.toContain('Report checker startup errors and return'); - expect(options.instructions).toContain('then retry the saved-file check'); - options.onActivity!({ event: 'lean_lock_waiting', itemType: 'commandExecution' }); - } - finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks.every((node: any) => node.status === 'integrated')).toBe(true); - expect(state.workers.find((worker: any) => worker.id === 'researcher-1').lastActivity) - .toMatchObject({ event: 'lean_lock_waiting', at: expect.any(Number) }); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it.each([false, true])('preserves cooperative saved work after a disconnected request, target saved=%s', async complete => { - let attempts = 0, seedCommit = ''; - configureCooperation(async (action, options, message) => { - if (action.kind === 'task' && action.task.id === 'a') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - if (++attempts === 1) { - seedCommit = action.assignment.seedCommit; - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', 'lemma saved_support : True := by trivial\ntheorem first')); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'Saved partial proof; finish a next.'); - if (complete) finishAssignment(action, options); - return 'failed'; - } - expect(action.assignment.seedCommit).toBe(seedCommit); - expect(fs.readFileSync(file, 'utf8')).toContain('lemma saved_support : True := by trivial'); - expect(fs.readFileSync(path.join(options.workspace, 'RESEARCH.md'), 'utf8')).toContain('Saved partial proof'); - expect(message).toContain('math_task_missing_declaration'); - } - finishAssignment(action, options); return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - lastError: 'stream disconnected before completion: error sending request' })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory)).toBe(0); - expect(attempts).toBe(complete ? 1 : 2); - expect(host.delay).toHaveBeenCalledTimes(complete ? 0 : 1); - expect(cooperationState().tasks.every((node: any) => node.status === 'integrated')).toBe(true); - expect(cooperationState().deliveries.some((record: any) => record.taskId === 'a' && record.kind === 'failure')).toBe(false); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each([2, 4])('starts original goal work after an empty Lead checkpoint with %s workers', async count => { - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - expect(options.turnTimeoutMs).toBe(180_000); - return 'checkpoint'; - } - if (action.kind === 'task' && action.task.kind === 'research') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'Both targets have direct proofs; this finding is advisory.'); - } else if (action.kind === 'task' && action.task.kind === 'goal') { - expect(action.task.dependsOn).toEqual([]); - expect(options.turnTimeoutMs).toBe(180_000); - const name = action.task.theoremName!.split('.').at(-1); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`theorem ${name} : True := by sorry`, `theorem ${name} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', String(count), '--max-turns', '6', '--max-turn-seconds', '180'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.initialPlanFallback).toMatchObject({ reason: expect.any(String) }); - expect(state.cooperation.tasks.filter((node: any) => node.task.kind === 'goal').map((node: any) => node.task.theoremName)) - .toEqual(problem.targets.map(target => target.theoremName)); - expect(state.workers.find((worker: any) => worker.role === 'lead').turns).toBeGreaterThan(0); - expect(state.workers.some((worker: any) => worker.role !== 'lead' && worker.turns > 0)).toBe(true); - expect(state.cooperation.tasks.filter((node: any) => node.task.kind === 'goal') - .every((node: any) => node.status === 'integrated' && node.attempts > 0)).toBe(true); - expect(state.usage).toMatchObject({ inputTokens: state.turns * 1000, totalTokens: state.turns * 1200 }); - }); - - it.each([180, 0])('keeps a valid task graph at a Lead checkpoint and respects turn limit %s', async seconds => { - configureCooperation(async (action, options) => { - if (action.kind === 'lead') expect(options.turnTimeoutMs).toBe(seconds === 0 ? undefined : seconds * 1000); - finishAssignment(action, options); - return action.kind === 'lead' ? 'checkpoint' : 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6', '--max-turn-seconds', String(seconds)], directory)).toBe(0); - expect(cooperationState().initialPlanFallback).toBeUndefined(); - expect(cooperationState().tasks.map((node: any) => node.task.id)).toEqual(planTasks().map(task => task.id)); - }); - - it.each([ - { status: 'checkpoint', savedFinding: false }, - { status: 'interrupted', savedFinding: false }, - { status: 'checkpoint', savedFinding: true }, - ])('resumes an advisory $status without unlocking consumers (saved finding: $savedFinding)', async ({ status, savedFinding }) => { - const tasks: CooperativeTask[] = [ - { id: 'question', kind: 'research', objective: 'Find a proof route', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: task.id === 'first' ? ['question'] : ['first'] })), - ]; - let attempts = 0, seed = '', researchWorkspace = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - writePlan(options.workspace, tasks); - for (const worker of JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).workers.slice(1)) { - writePlan(worker.worktree, tasks); - commitSolverSources(problem, worker.worktree); - } - } else if (action.kind === 'task' && action.task.id === 'question') { - if (++attempts === 1) { - seed = action.assignment.seedCommit; researchWorkspace = options.workspace; - if (savedFinding) fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'The current route uses True.intro; both targets remain to be proved.'); - return status; - } - expect(action.assignment.seedCommit).toBe(seed); - expect(options.workspace).toBe(researchWorkspace); - expect(cooperationState().deliveries ?? []).toEqual([]); - expect(cooperationState().tasks.slice(1).every((node: any) => node.attempts === 0)).toBe(true); - if (savedFinding) expect(fs.readFileSync(path.join(options.workspace, 'RESEARCH.md'), 'utf8')).toContain('The current route'); - else fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'The current route uses True.intro; both targets remain to be proved.'); - } else if (action.kind === 'task') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '6'], directory)).toBe(0); - expect(attempts).toBe(2); - expect(cooperationState().deliveries.filter((record: any) => record.kind === 'research')) - .toMatchObject([{ taskId: 'question', summary: 'The current route uses True.intro; both targets remain to be proved.' }]); - expect(cooperationState().tasks[0]).toMatchObject({ status: 'completed', attempts: 2 }); - }); - - it.each([false, true])('checks saved cooperative proof checkpoints without publishing unfinished work as failure (complete: %s)', async complete => { - let attempts = 0, seed = ''; - configureCooperation(async (action, options, message) => { - if (action.kind === 'task' && action.task.id === 'a') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - if (++attempts === 1) { - seed = action.assignment.seedCommit; - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', 'lemma partial : True := by trivial\ntheorem first')); - if (complete) finishAssignment(action, options); - return 'checkpoint'; - } - expect(action.assignment.seedCommit).toBe(seed); - expect(fs.readFileSync(file, 'utf8')).toContain('lemma partial : True := by trivial'); - expect(message).toContain('math_task_missing_declaration'); - expect(cooperationState().deliveries?.some((record: any) => record.taskId === 'a' && record.kind === 'failure')).toBeFalsy(); - } - finishAssignment(action, options); return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory)).toBe(0); - expect(attempts).toBe(complete ? 1 : 2); - expect(cooperationState().tasks[0].status).toBe('integrated'); - }); - - it.each(['markdown', 'json'])('requests a Lead decision after two unchanged completed %s research deliveries', async format => { - const tasks: CooperativeTask[] = [ - { id: 'question', kind: 'research', objective: 'Find a current proof route', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: task.id === 'first' ? ['question'] : ['first'] })), - ]; - let attempts = 0; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - writePlan(options.workspace, tasks); - for (const worker of JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).workers.slice(1)) { - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), format === 'markdown' ? 'An old route that has not been checked.' : - JSON.stringify({ summary: 'An old route that has not been checked.' })); - commitSolverSources(problem, worker.worktree); - } - } else { - expect(action.kind === 'task' && action.task.id).toBe('question'); - if (++attempts > 1) expect(message).toContain('math_research_delivery_unchanged'); - // Changing only the mode must not make the inherited finding fresh. - fs.chmodSync(path.join(options.workspace, 'RESEARCH.md'), 0o755); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '3'], directory)).toBe(4); - expect(attempts).toBe(2); - expect(cooperationState().tasks[0]).toMatchObject({ status: 'blocked', attempts: 2, feedback: expect.stringContaining('math_research_delivery_unchanged') }); - expect(cooperationState().tasks.slice(1).every((node: any) => node.attempts === 0)).toBe(true); - expect(cooperationState().deliveries).toEqual([expect.objectContaining({ taskId: 'question', kind: 'failure', status: 'failed' })]); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it.each(['never written', 'deleted'])('rejects research deliveries whose RESEARCH.md is %s without stopping the worker', async mode => { - const tasks: CooperativeTask[] = [ - { id: 'question', kind: 'research', objective: 'Find a current proof route', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: task.id === 'first' ? ['question'] : ['first'] })), - ]; - let attempts = 0; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - writePlan(options.workspace, tasks); - if (mode === 'deleted') for (const worker of JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).workers.slice(1)) { - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'An old route that has not been checked.'); - commitSolverSources(problem, worker.worktree); - } - } else { - expect(action.kind === 'task' && action.task.id).toBe('question'); - if (++attempts > 1) expect(message).toContain('math_research_delivery_unchanged'); - fs.rmSync(path.join(options.workspace, 'RESEARCH.md'), { force: true }); - } - return 'completed'; - }); - const exitCode = await runSolver([...args, '--workers', '2', '--max-turns', '3'], directory); - expect(exitCode, fs.readFileSync(output, 'utf8')).toBe(4); - expect(attempts).toBe(2); - // Tracked deletions are checkpointed; both missing-file cases submit no current findings. - expect(cooperationState().tasks[0]).toMatchObject({ status: 'blocked', attempts: 2, - feedback: expect.stringContaining('Write RESEARCH.md') }); - expect(cooperationState().deliveryReceipts).toEqual(expect.arrayContaining([expect.objectContaining({ taskId: 'question', - code: 'math_research_delivery_unchanged', submissionDigest: mathDigest('') })])); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('lets a worker replace deleted inherited notes and complete the same research assignment', async () => { - const tasks: CooperativeTask[] = [ - { id: 'question', kind: 'research', objective: 'Find a current proof route', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: task.id === 'first' ? ['question'] : ['first'] })), - ]; - let attempts = 0, seed = '', researchWorkspace = '', seeded = false; - const finding = 'The current route uses True.intro for both original targets.'; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - writePlan(options.workspace, tasks); - if (!seeded) { - seeded = true; - for (const worker of JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).workers.slice(1)) { - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'An old route that has not been checked.'); - commitSolverSources(problem, worker.worktree); - } - } - } else if (action.kind === 'task' && action.task.id === 'question') { - if (++attempts === 1) { - seed = action.assignment.seedCommit; researchWorkspace = options.workspace; - fs.rmSync(path.join(options.workspace, 'RESEARCH.md')); - } else { - expect(action.assignment.seedCommit).toBe(seed); - expect(options.workspace).toBe(researchWorkspace); - expect(message).toContain('math_research_delivery_unchanged: Write RESEARCH.md'); - expect(cooperationState().deliveries ?? []).toEqual([]); - expect(cooperationState().deliveryReceipts).toContainEqual(expect.objectContaining({ taskId: 'question', - code: 'math_research_delivery_unchanged', submissionDigest: mathDigest('') })); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), finding); - } - } else if (action.kind === 'task') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - const exitCode = await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory); - expect(exitCode, fs.readFileSync(output, 'utf8')).toBe(0); - expect(attempts).toBe(2); - expect(cooperationState().tasks[0]).toMatchObject({ status: 'completed', attempts: 2 }); - expect(cooperationState().deliveries.filter((record: any) => record.kind === 'research')) - .toMatchObject([{ taskId: 'question', summary: finding }]); - expect(host.verify).toHaveBeenCalled(); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('accepts rewritten research notes after recovering a committed deletion', async () => { - const tasks: CooperativeTask[] = [ - { id: 'question', kind: 'research', objective: 'Find a current proof route', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, status: 'paused' as const, - dependsOn: task.id === 'first' ? ['question'] : ['first'] })), - ]; - const finding = 'The current route uses True.intro; both original targets still require independent proofs.'; - let attempts = 0, plans = 0; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - writePlan(options.workspace, tasks); - if (++plans === 1) for (const worker of JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).workers.slice(1)) { - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'An old route that has not been checked.'); - commitSolverSources(problem, worker.worktree); - } - } else if (action.kind === 'task' && action.task.id === 'question') { - if (++attempts === 1) fs.rmSync(path.join(options.workspace, 'RESEARCH.md')); - else { - expect(attempts).toBe(2); - expect(message).toContain('Write RESEARCH.md'); - expect(cooperationState().deliveryReceipts).toContainEqual(expect.objectContaining({ taskId: 'question', - code: 'math_research_delivery_unchanged', submissionDigest: mathDigest('') })); - expect(cooperationState().tasks.filter((node: TaskRecord) => node.task.kind === 'goal') - .every((node: TaskRecord) => node.attempts === 0)).toBe(true); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), finding); - } - } else if (action.kind === 'task') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - const exitCode = await runSolver([...args, '--workers', '2', '--max-turns', '6'], directory); - expect(exitCode, fs.readFileSync(output, 'utf8')).toBe(4); - expect(cooperationState().tasks[0]).toMatchObject({ status: 'completed', attempts: 2 }); - expect(cooperationState().deliveries.filter((record: any) => record.kind === 'research')) - .toMatchObject([{ taskId: 'question', summary: finding }]); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('routes active candidate questions to a single fixed review with the default scheduler', async () => { - const tasks = reviewedPlanTasks(); - tasks.push({ id: 'independent_candidate_review', kind: 'research', objective: 'Did the helper introduce an extra premise?', - dependsOn: ['a'], revision: 0 }, - { id: 'paused_audit', kind: 'research', objective: 'PAUSED_AUDIT_QUESTION', reviewScope: 'final-candidate', - status: 'paused', dependsOn: [], revision: 0 }); - let reviews = 0; - const assigned: string[] = []; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task') assigned.push(action.task.id); - else if (action.kind === 'review') { - reviews++; - expect(message).toContain(tasks[4].objective); - expect(message).toContain(tasks[5].objective); - expect(message).not.toContain('"question":"PAUSED_AUDIT_QUESTION"'); - expect(host.officialGate).not.toHaveBeenCalled(); - } - if (action.kind !== 'lead') finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '12'], directory)).toBe(0); - expect(assigned.sort()).toEqual(['a', 'b', 'first', 'second']); - expect(reviews).toBe(1); - expect(cooperationState().review.status).toBe('accepted'); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('cancels an in-flight candidate review when its only request is paused', async () => { - const tasks = reviewedPlanTasks(), interrupted = deferred(); - let reviewerWorkspace: string | undefined, reviews = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'review') { - expect(++reviews).toBe(1); - reviewerWorkspace = options.workspace; - tasks[4] = { ...tasks[4], status: 'paused' }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'pause-audit', - baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await interrupted.promise; - } - if (action.kind !== 'lead') finishAssignment(action, options); - return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === reviewerWorkspace) interrupted.resolve(); }) })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '9'], directory)).toBe(0); - expect(cooperationState().edits[0]).toMatchObject({ status: 'applied' }); - expect(cooperationState().review).toBeUndefined(); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('resumes a proof review checkpoint without accepting its saved verdict prematurely', async () => { - let reviews = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'review' && ++reviews === 1) { - finishAssignment(action, options); return 'checkpoint'; - } - if (action.kind === 'review') { - expect(cooperationState().review.status).toBe('running'); - expect(cooperationState().deliveries.some((record: any) => record.kind === 'review')).toBe(false); - expect(host.officialGate).not.toHaveBeenCalled(); - } - if (action.kind === 'lead') writePlan(options.workspace, reviewedPlanTasks()); - else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '7'], directory)).toBe(0); - expect(reviews).toBe(2); - expect(cooperationState().deliveries.filter((record: any) => record.kind === 'review')).toMatchObject([{ status: 'accepted' }]); - }); function finishAssignment(action: CooperativeAction, options: MathAgentOptions) { if (action.kind === 'lead') { writePlan(options.workspace, planTasks()); return; } @@ -2755,82 +1751,6 @@ describe('isolated solver and host acceptance', () => { } else fs.writeFileSync(file, source.replace('second : True := by sorry', 'second : True := by exact first')); } - it('preflights each worker against its assignment while keeping other original proofs frozen', async () => { - const inspected: string[] = []; - configureCooperation(async (action, options) => { - const project = path.join(options.workspace, problem.projectRelative); - if (action.kind !== 'task') { - if (action.kind === 'review') { - const constraints = JSON.parse(fs.readFileSync(path.join(project, '.lake/source-constraints.json'), 'utf8')); - expect(constraints.declarations).toEqual(problem.declarations); - expect(() => assertSolverProjectSources(constraints, project)).not.toThrow(); - } - finishAssignment(action, options); return 'completed'; - } - const file = path.join(project, 'Submission.lean'); - const constraints = JSON.parse(fs.readFileSync(path.join(project, '.lake/source-constraints.json'), 'utf8')); - finishAssignment(action, options); - const candidate = fs.readFileSync(file, 'utf8'); - expect(() => assertSolverProjectSources(constraints, project)).not.toThrow(); - const peer = action.task.id === 'first' ? 'second' : 'first'; - const regions = inspectLeanDeclarationRegions(candidate); - const region = regions.find(item => item.name === peer)!; - fs.writeFileSync(file, candidate.slice(0, region.bodyOffset) + - (candidate.slice(region.bodyOffset, region.endOffset).includes('sorry') ? 'by trivial\n' : 'by sorry\n') + - candidate.slice(region.endOffset)); - expect(() => assertSolverProjectSources(constraints, project)).toThrow('math_original_declaration_changed'); - try { assertSolverProjectSources(constraints, project); } catch (error) { - expect(error).toMatchObject({ declarationName: peer }); - expect((error as SolverSourceError).recovery).toContain('frozen proof'); - } - fs.writeFileSync(file, candidate); - inspected.push(action.task.id); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory)).toBe(0); - expect(inspected.toSorted()).toEqual(['a', 'b', 'first', 'second']); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('provides an unambiguous Lead plan example when multiple Lean files are owned', async () => { - const helper = 'Submission/Helpers.lean'; - fs.mkdirSync(path.join(project, 'Submission')); - fs.writeFileSync(path.join(project, helper), 'namespace Submission.Helpers\nend Submission.Helpers\n'); - const receipt = JSON.parse(fs.readFileSync(problem.activeProblemPath, 'utf8')); - receipt.solverOwnedFiles.push(helper); - fs.writeFileSync(problem.activeProblemPath, JSON.stringify(receipt)); - git(workspace, ['add', '--', 'generated/p/Submission/Helpers.lean']); - commitFixture(workspace, 'Owned helper module'); - problem = readSolverProblem(workspace, problem.activeProblemPath); - expect(await runSolver([...args, '--workers', '4', '--startup-only'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - state.cooperation = { tasks: [] }; - const context = directSolverModules.M4.build(problem, state, { root: directory, worktree: state.worktree, - environment: {}, taskText: 'Prove both targets', retrievalRoot: project, - assignment: { kind: 'lead', seedCommit: problem.baseCommit } }); - expect(context.instructions).toContain(JSON.stringify(problem.ownedFiles)); - expect(context.instructions).toContain('leave Lean sources unchanged during planning'); - expect(context.instructions).toContain('Return the plan without running Lean diagnostics'); - expect(context.instructions).not.toContain('FULL_CLOSED_LEAN_TYPE'); - const exampleText = context.instructions.match(/Use this plan schema in the draft passed to plan-apply: (\{.*?\})\. Include/u); - expect(exampleText).not.toBeNull(); - const example = JSON.parse(exampleText![1]); - example.tasks[0].theoremName = 'Submission.helper'; - example.tasks[0].type = 'True'; - example.tasks[1].theoremName = 'Submission.first'; - example.tasks.push({ id: 'second', kind: 'goal', objective: 'Prove the second target', theoremName: 'Submission.second' }); - expect(parseCooperationPlan(problem, example).tasks[0].proofPath).toBe('Submission.lean'); - example.tasks[0].proofPath = helper; - expect(parseCooperationPlan(problem, example).tasks[0].proofPath).toBe(helper); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), - 'Mathematical route: prove the shared helper, then apply it to each original target.\n\n```math-plan\n' + - JSON.stringify(example) + '\n```\n'); - expect(readCooperationPlan(problem, workspace).tasks[0].proofPath).toBe(helper); - delete example.tasks[0].proofPath; - expect(() => parseCooperationPlan(problem, example)).toThrow('math_plan_invalid_proof_target'); - expect(host.createSession).not.toHaveBeenCalled(); - }); - it('accepts larger cooperative plans and preserves their full mathematical content', () => { const type = '(True ∧ '.repeat(1000) + 'True' + ')'.repeat(1000); const premises = ['P'.repeat(2001), ...Array(32).fill('A')]; @@ -2860,296 +1780,6 @@ describe('isolated solver and host acceptance', () => { expect(parseCooperationPlan(problem, { tasks })).toEqual(planned); }); - it.each(['lead', 'task', 'backtranslate', 'statement-review', 'review'])('does not charge an unstarted cooperative %s assignment', async stoppedKind => { - const statementPhase = stoppedKind === 'backtranslate' || stoppedKind === 'statement-review'; - const tasks = statementPhase ? statementTasks() : stoppedKind === 'review' ? reviewedPlanTasks() : planTasks(); - // Keep independent proof work from stopping all peers before the statement context is ready. - if (statementPhase) tasks[1] = { ...tasks[1], dependsOn: ['a'] }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else finishAssignment(action, options); - return 'completed'; - }); - const select = vi.fn((...inputs: Parameters) => { - const assignment = inputs[3]!; - const stop = stoppedKind === 'lead' ? true : stoppedKind === 'review' ? assignment.kind === 'review' : - assignment.kind !== 'lead' && !(stoppedKind === 'statement-review' && assignment.kind === 'backtranslate'); - return stop ? { operation: 'stop' as const, reason: 'no-operation' as const } : directSolverModules.M3.select(...inputs); - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '12'], directory, - { ...directSolverModules, M3: { ...directSolverModules.M3, select } })).toBe(4); - expect(select.mock.calls.some(call => call[3]?.kind === stoppedKind)).toBe(true); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - const spent = stoppedKind === 'review' ? 4 : stoppedKind === 'statement-review' ? 1 : 0; - expect(state.cooperation.groups?.[0]?.turns ?? 0).toBe(spent); - expect(state.turns).toBe(spent + (stoppedKind === 'lead' ? 0 : 1)); - expect(Object.values(state.dispatchCounts).reduce((sum: number, value: any) => sum + value, 0)).toBe(state.turns); - expect(state.dispatchCounts.planning ?? 0).toBe(stoppedKind === 'lead' ? 0 : 1); - expect(state.cooperation.tasks.filter((node: TaskRecord) => node.task.reviewScope !== 'final-candidate').every((node: TaskRecord) => node.attempts === (stoppedKind === 'review' ? 1 : 0))).toBe(true); - if (stoppedKind === 'review') expect(state.cooperation.review.status).toBe('pending'); - if (stoppedKind === 'backtranslate') expect(state.cooperation.statementReviews[0].status).toBe('pending'); - if (stoppedKind === 'statement-review') expect(state.cooperation.statementReviews[0].status).toBe('translated'); - }); - - it('executes the direct method through cooperative roles without singleton lemma proposals', async () => { - const operations: string[] = []; - configureCooperation(async (action, options, message) => { - expect(message).not.toContain('Propose one new ordinary theorem'); - expect(message).not.toContain('"target":"Original.qualifiedTarget"'); - expect(message).not.toContain('Research operation:'); - finishAssignment(action, options); return 'completed'; - }); - const execute = vi.fn(async (...inputs: Parameters) => { - operations.push(inputs[2]); - return directSolverModules.M1.execute(...inputs); - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory, - { ...directSolverModules, M1: { ...directSolverModules.M1, execute } })).toBe(0); - expect(new Set(operations)).toEqual(new Set(['direct'])); - expect(cooperationState().tasks.every((node: any) => node.status === 'integrated')).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('uses replacement task evidence, blind contexts, role slots and reviewer selection in one cooperative solve', async () => { - const checkTask = vi.fn(directSolverModules.M2.checkTask); - const workers = vi.fn((...inputs: Parameters) => - directSolverModules.M5.workers(...inputs).map((worker, index) => index === 1 ? { ...worker, id: 'mathematician' } : - index === 2 ? { ...worker, id: 'auditor', role: 'reviewer' as const } : worker)); - const reviewer = vi.fn(directSolverModules.M5.reviewer); - const statement = vi.fn((...inputs: Parameters) => { - if (inputs[1].kind === 'backtranslate') { - expect(inputs[0].intendedStatement).toBe(''); expect(inputs[0].premises).toEqual([]); - expect(inputs[0].translation).toBeUndefined(); expect(JSON.stringify(inputs)).not.toContain('INTENT_SECRET'); - } - const context = directSolverModules.M4.statement(...inputs); - return { ...context, instructions: context.instructions + '\nCUSTOM_STATEMENT_CONTEXT' }; - }); - const reviews: string[] = []; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, statementTasks()); - else { - if (isStatementAction(action)) expect(options.instructions).toContain('CUSTOM_STATEMENT_CONTEXT'); - if (isStatementAction(action) || action.kind === 'review') reviews.push(options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!); - finishAssignment(action, options); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory, { - ...directSolverModules, M2: { ...directSolverModules.M2, checkTask }, M4: { ...directSolverModules.M4, statement }, - M5: { ...directSolverModules.M5, workers, reviewer }, - })).toBe(0); - expect(checkTask).toHaveBeenCalled(); expect(statement).toHaveBeenCalledTimes(2); expect(workers).toHaveBeenCalledOnce(); - expect(reviewer).toHaveBeenCalled(); expect(reviews).toEqual(['auditor', 'auditor', 'auditor']); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each([4, 8])('prepares the default proof-writing roster for %s workers without opening a model', async count => { - const workerArgs = count === 4 ? args.slice(0, -2) : [...args, '--workers', '8']; - expect(await runSolver([...workerArgs, '--startup-only'], directory)).toBe(0); - const state = readSolverRunState(`${output}.runtime/state.json`); - const roster = count === 4 - ? [['solver', 'lead'], ['researcher-1', 'researcher'], ['researcher-2', 'researcher'], ['engineer', 'engineer']] - : [['solver', 'lead'], ['researcher-1', 'researcher'], ['researcher-2', 'researcher'], - ...[1, 2, 3, 4].map(index => [`prover-${index}`, 'prover']), ['engineer', 'engineer']]; - expect(state.workerCount).toBe(count); - expect(state.workers!.map(worker => [worker.id, worker.role])).toEqual(roster); - expect(new Set(state.workers!.map(worker => worker.worktree)).size).toBe(count); - for (const worker of state.workers!) { - expect(git(worker.worktree, ['rev-parse', '--show-toplevel'])).toBe(worker.worktree); - expect(fs.readFileSync(path.join(worker.worktree, 'generated/p/Submission.lean'), 'utf8')).toBe(original); - } - expect(host.createSession).not.toHaveBeenCalled(); - expect(host.verify).not.toHaveBeenCalled(); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('roundtrips a prover session role and resumes the same eight-worker roster without a model', async () => { - const eightWorkers = [...args, '--workers', '8', '--startup-only']; - expect(await runSolver(eightWorkers, directory)).toBe(0); - const stateFile = `${output}.runtime/state.json`; - const state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); - const prover = state.workers.find((worker: any) => worker.id === 'prover-1'); - prover.sessionRole = 'prover'; prover.threadId = 'saved-prover-thread'; - fs.writeFileSync(stateFile, JSON.stringify(state)); - expect(readSolverRunState(stateFile).workers!.find(worker => worker.id === 'prover-1')) - .toMatchObject({ role: 'prover', sessionRole: 'prover', threadId: 'saved-prover-thread' }); - expect(await runSolver([...eightWorkers, '--resume'], directory)).toBe(0); - expect(readSolverRunState(stateFile).workers!.find(worker => worker.id === 'prover-1')) - .toMatchObject({ role: 'prover', sessionRole: 'prover', threadId: 'saved-prover-thread' }); - expect(host.createSession).not.toHaveBeenCalled(); - expect(host.verify).not.toHaveBeenCalled(); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('validates human-edited prover ownership for typed lemmas while preserving role boundaries', async () => { - configureCooperation(undefined, waitingPlanTasks); - expect(await runSolver([...args, '--workers', '8', '--max-turns', '1'], directory)).toBe(4); - const stateFile = `${output}.runtime/state.json`, checkpoint = fs.readFileSync(stateFile, 'utf8'); - const state = readSolverRunState(stateFile); - const { queueRunEdit } = await import('../src/solver/humanEdit'); - const proposal = { id: 'assign_prover', baseVersion: state.cooperation!.planVersion, - tasks: waitingPlanTasks().map(task => task.id === 'a' ? { ...task, ownerId: 'prover-1' } : task) }; - expect(await queueRunEdit(output, proposal, true)).toMatchObject({ status: 'validated' }); - for (const invalid of [ - { ...proposal, tasks: [...proposal.tasks, - { id: 'advice', kind: 'research', objective: 'Explore a possible proof route', ownerId: 'prover-1' }] }, - { ...proposal, tasks: proposal.tasks.map(task => task.id === 'first' ? { ...task, ownerId: 'prover-1' } : task) }, - { ...proposal, tasks: proposal.tasks.map(task => task.id === 'a' ? { ...task, ownerId: 'solver' } : task) }, - ]) await expect(queueRunEdit(output, invalid, true)).rejects.toThrow('math_plan_task_owner_unavailable'); - expect(fs.readFileSync(stateFile, 'utf8')).toBe(checkpoint); - expect(fs.existsSync(`${output}.runtime/edits.jsonl`)).toBe(false); - expect(host.createSession).toHaveBeenCalledOnce(); - expect(host.verify).not.toHaveBeenCalled(); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('runs four owned prover lemmas concurrently and delivers their checked sources to the Engineer', async () => { - const helpers = ['a', 'b', 'c', 'd']; - const tasks: CooperativeTask[] = [ - ...[1, 2].map(index => ({ id: `question-${index}`, kind: 'research' as const, - objective: `Investigate independent question ${index}`, ownerId: `researcher-${index}`, dependsOn: [], revision: 0 })), - ...helpers.map((id, index) => ({ id, kind: 'lemma' as const, objective: `Prove the exact helper ${id}`, - ownerId: `prover-${index + 1}`, theoremName: `Submission.${id}`, proofPath: 'Submission.lean', - type: 'True', dependsOn: [], revision: 0 })), - ...waitingPlanTasks().slice(2).map(task => ({ ...task, ownerId: 'engineer', - dependsOn: task.id === 'first' ? helpers : task.dependsOn })), - ]; - const started = new Set(), allStarted = deferred(); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - writePlan(options.workspace, tasks, [{ id: 'main', objective: 'Prove both original goals', - engineerId: 'engineer', status: 'active', revision: 0 }]); - } else if (action.kind === 'task' && action.task.kind === 'research') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), `Independent finding for ${action.task.id}.`); - } else if (action.kind === 'task' && action.task.kind === 'lemma') { - expect(action.assignment.workerId).toBe(action.task.ownerId); - expect(options.instructions).toContain('Your role: prover'); - expect(options.instructions).toContain('Prove the assigned Lean declaration with its exact requested type'); - expect(options.instructions).not.toContain('You are a Mathematical Researcher'); - expect(readSolverRunState(`${output}.runtime/state.json`).workers! - .find(worker => worker.id === action.assignment.workerId)).toMatchObject({ role: 'prover', sessionRole: 'prover' }); - expect(host.officialGate).not.toHaveBeenCalled(); - started.add(action.assignment.workerId); - if (started.size === 4) allStarted.resolve(); - await allStarted.promise; - finishAssignment(action, options); - } else if (action.kind === 'task' && action.task.id === 'first') { - expect(action.assignment.workerId).toBe('engineer'); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - const source = fs.readFileSync(file, 'utf8'); - for (const helper of helpers) expect(source).toContain(`lemma ${helper} : True := by trivial`); - expect(cooperationState().tasks.filter((node: any) => node.task.kind === 'lemma') - .every((node: any) => node.status === 'integrated' && node.integratedCheck?.passed)).toBe(true); - fs.writeFileSync(file, source.replace('first : True := by sorry', - 'first : True := by exact And.left (And.intro a (And.intro b (And.intro c d)))')); - } else finishAssignment(action, options); - return 'completed'; - }); - const code = await runSolver([...args, '--workers', '8', '--max-turns', '12', '--max-run-seconds', '10'], directory); - expect(code, fs.readFileSync(output, 'utf8')).toBe(0); - expect(started).toEqual(new Set(['prover-1', 'prover-2', 'prover-3', 'prover-4'])); - const state = readSolverRunState(`${output}.runtime/state.json`); - expect(state.cooperation!.groups![0].group.maxConcurrent).toBe(7); - for (const helper of helpers) { - expect(state.cooperation!.tasks.find(node => node.task.id === helper)) - .toMatchObject({ status: 'integrated', proof: { passed: true }, integratedCheck: { passed: true } }); - expect(host.verify.mock.calls.some(([request]) => request.items.some(item => item.theoremName === `Submission.${helper}`))).toBe(true); - } - expect(state.workers!.filter(worker => worker.role === 'prover') - .every(worker => worker.sessionRole === 'prover' && worker.dispatchCounts?.proof === 1)).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it.each(['research', 'goal'] as const)('rejects a custom M5 assigning %s work to a Prover before opening its model', async kind => { - const tasks: CooperativeTask[] = [ - { id: 'advice', kind: 'research', objective: 'Inspect a distinct mathematical uncertainty', dependsOn: [], revision: 0 }, - ...planTasks(), - ]; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.kind === 'research') - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'The original targets follow from the exact checked helpers.'); - else finishAssignment(action, options); - return 'completed'; - }); - let invalidOffered = false; - const assign = (...inputs: Parameters) => { - if (inputs[1].id === 'prover-1') { - const invalid = inputs[0].find(node => node.task.kind === kind); - if (invalid) invalidOffered = true; - return invalid; - } - // The host validates this return synchronously. Keep ordinary work available after - // the bad selection instead of making readiness depend on a later state-file save. - return invalidOffered ? directSolverModules.M5.assign(...inputs) : undefined; - }; - const code = await runSolver([...args, '--workers', '8', '--max-turns', '10'], directory, - { ...directSolverModules, M5: { ...directSolverModules.M5, assign } }); - expect(code, fs.readFileSync(output, 'utf8')).toBe(0); - expect(readSolverRunState(`${output}.runtime/state.json`).workers!.find(worker => worker.id === 'prover-1')) - .toMatchObject({ error: 'math_task_assignment_invalid', turns: 0 }); - expect(host.createSession.mock.calls.some(([options]) => options.environment!.DEEPSCIENTIST_MATH_WORKER_ID === 'prover-1')) - .toBe(false); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each(['count', 'role'] as const)('rejects an expanded run with a changed worker %s before opening a model', async changed => { - expect(await runSolver([...args, '--workers', '8', '--startup-only'], directory)).toBe(0); - const prepared = fs.readFileSync(output, 'utf8'); - const stateFile = `${output}.runtime/state.json`, checkpoint = fs.readFileSync(stateFile, 'utf8'); - const workers = (...inputs: Parameters) => - directSolverModules.M5.workers(...inputs).map(worker => worker.id === 'prover-1' - ? { ...worker, role: 'researcher' as const } : worker); - expect(await runSolver([...args, '--workers', changed === 'count' ? '4' : '8', '--startup-only', '--resume'], directory, - changed === 'role' ? { ...directSolverModules, M5: { ...directSolverModules.M5, workers } } : undefined)).toBe(1); - expect(fs.readFileSync(output, 'utf8')).toBe(prepared); - expect(fs.readFileSync(stateFile, 'utf8')).toBe(checkpoint); - expect(host.createSession).not.toHaveBeenCalled(); - expect(host.verify).not.toHaveBeenCalled(); - expect(console.log).toHaveBeenCalledWith(expect.stringContaining(changed === 'count' - ? 'math_resume_worker_count_changed' : 'math_resume_worker_identity_changed')); - }); - - it('rejects changed module role identities on resume before opening a model session', async () => { - expect(await runSolver([...args, '--workers', '4', '--startup-only'], directory)).toBe(0); - const prepared = fs.readFileSync(output, 'utf8'); - const workers = (...inputs: Parameters) => - directSolverModules.M5.workers(...inputs).map((worker, index) => index === 1 ? { ...worker, id: 'changed' } : worker); - expect(await runSolver([...args, '--workers', '4', '--resume'], directory, - { ...directSolverModules, M5: { ...directSolverModules.M5, workers } })).toBe(1); - expect(fs.readFileSync(output, 'utf8')).toBe(prepared); expect(host.createSession).not.toHaveBeenCalled(); - expect(console.log).toHaveBeenCalledWith(expect.stringContaining('math_resume_worker_identity_changed')); - }); - - it('rejects task evidence carrying a different assignment version', async () => { - configureCooperation(); - const checkTask = async (...inputs: Parameters) => - ({ ...await directSolverModules.M2.checkTask(...inputs), taskDigest: 'wrong-version' }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '3'], directory, - { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(4); - expect(cooperationState().tasks.some((node: any) => node.feedback === 'math_task_check_identity_changed')).toBe(true); - expect(cooperationState().tasks.some((node: any) => node.status === 'integrated')).toBe(false); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each(['worktree', 'files', 'reviewer'])('keeps host ownership when replacement M5 changes %s', async invalid => { - configureCooperation(undefined, invalid === 'reviewer' ? reviewedPlanTasks : planTasks); - const workers = (...inputs: Parameters) => - directSolverModules.M5.workers(...inputs).map((worker, index) => index !== 1 ? worker : invalid === 'worktree' ? - { ...worker, worktree: workspace } : invalid === 'files' ? { ...worker, ownedFiles: ['Challenge.lean'] } : worker); - const reviewer = vi.fn((...inputs: Parameters) => invalid === 'reviewer' ? - { id: 'outsider', role: 'reviewer' as const, worktree: workspace, ownedFiles: problem.ownedFiles } : directSolverModules.M5.reviewer(...inputs)); - // Reviewer selection happens when a candidate is ready for review. - const result = await runSolver([...args, '--workers', '4', '--max-turns', invalid === 'reviewer' ? '10' : '3'], directory, - { ...directSolverModules, M5: { ...directSolverModules.M5, workers, reviewer } }); - expect(result).toBe(1); - expect(host.officialGate).not.toHaveBeenCalled(); - if (invalid === 'reviewer') { - expect(reviewer).toHaveBeenCalled(); - expect(cooperationState().review).toMatchObject({ status: 'pending' }); - } else expect(host.createSession).not.toHaveBeenCalled(); - }); - it('applies revised M4 instructions while resuming the same model thread', async () => { const seen: string[] = [], emitted: string[] = []; let calls = 0; @@ -3175,378 +1805,11 @@ describe('isolated solver and host acceptance', () => { expect(host.createSession.mock.calls[1][0].threadId).toBe('audit-thread'); }); - it('rejects a replacement M5 assigning a task to someone other than its explicit owner', async () => { - const tasks = planTasks(); tasks[0] = { ...tasks[0], ownerId: 'researcher-1' }; - const assignments: any[] = []; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task') { assignments.push({ task: action.task.id, owner: action.task.ownerId, assigned: action.assignment.workerId }); finishAssignment(action, options); } - else finishAssignment(action, options); - return 'completed'; - }); - const assign = (...inputs: Parameters) => inputs[1].id === 'researcher-2' - ? inputs[0].find(node => node.task.id === 'a') ?? directSolverModules.M5.assign(...inputs) - : inputs[1].id === 'researcher-1' ? inputs[0].find(node => node.task.id === 'b') ?? directSolverModules.M5.assign(...inputs) : directSolverModules.M5.assign(...inputs); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory, - { ...directSolverModules, M5: { ...directSolverModules.M5, assign } })).toBe(0); - expect(assignments).toContainEqual({ task: 'a', owner: 'researcher-1', assigned: 'researcher-1' }); - expect(assignments).not.toContainEqual({ task: 'a', owner: 'researcher-1', assigned: 'researcher-2' }); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.workers.find((worker: any) => worker.id === 'researcher-2').error).toBe('math_task_assignment_invalid'); - }); - it.each(['single', 'task', 'backtranslate'])('refunds an unopened %s session reservation and keeps its assignment pending', async kind => { - if (kind !== 'single') configureCooperation(async (action, options) => { - if (action.kind === 'lead' && kind === 'backtranslate') writePlan(options.workspace, statementTasks()); - else finishAssignment(action, options); - return 'completed'; - }); - const open = async (...inputs: Parameters) => { - if (kind === 'single' || inputs[0].environment!.DEEPSCIENTIST_MATH_WORKER_ID !== 'solver') throw new Error('fixture_transport_unavailable'); - return directSolverModules.M1.open(...inputs); - }; - expect(await runSolver([...args, '--workers', kind === 'single' ? '1' : '2', '--max-turns', '2'], directory, - { ...directSolverModules, M1: { ...directSolverModules.M1, open } })).toBe(1); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.turns).toBe(kind === 'single' ? 0 : 1); - expect(host.createSession).toHaveBeenCalledTimes(kind === 'single' ? 0 : 1); - expect(host.verify).not.toHaveBeenCalled(); - if (kind !== 'single') { - expect(state.cooperation.groups[0].turns).toBe(0); - expect(state.cooperation.tasks[0]).toMatchObject({ attempts: 0, status: 'pending' }); - expect(state.cooperation.tasks[0].assignment).toBeUndefined(); - if (kind === 'backtranslate') expect(state.cooperation.statementReviews[0].status).toBe('pending'); - } - }); - - it.each(['sourceDeclarationHash', 'targetCommit', 'claim'])('rejects replacement M2 receipts with a mismatched %s', async field => { - configureCooperation(); - const checkTask = async (...inputs: Parameters) => { - const proof = await directSolverModules.M2.checkTask(...inputs); - return { ...proof, verification: { ...proof.verification, results: proof.verification.results.map(result => - ({ ...result, [field]: field === 'claim' ? 'negation' : 'incorrect-identity' })) } }; - }; - expect(await runSolver([...args, '--workers', '4', '--max-turns', '3'], directory, - { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(4); - const tasks = cooperationState().tasks; - expect(tasks.some((node: any) => node.feedback === 'math_task_check_identity_changed')).toBe(true); - expect(tasks.some((node: any) => node.status === 'integrated')).toBe(false); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - - it('filters private statement reviews from both route prompts and cooperation journals', () => { - const secret = { ...planTasks()[0], objective: 'PRIVATE_TASK_OBJECTIVE', groupId: 'private', sharing: 'group' as const }; - const publicTask = { ...planTasks()[1], groupId: 'public' }; - const shared = { ...planTasks()[2], groupId: 'private', sharing: 'problem' as const }; - const pending = { id: 'public-pending', kind: 'research' as const, objective: 'Explore a public route', - groupId: 'private', sharing: 'problem' as const, dependsOn: [], revision: 0 }; - const progress = { id: 'public-progress', taskId: pending.id, taskDigest: taskVersion(pending), dependencies: [], - producer: 'researcher-2', kind: 'progress', status: 'advisory', summary: 'PUBLIC_PENDING_PROGRESS' }; - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peerRoot = path.join(directory, 'peer'); fs.mkdirSync(peerRoot); - const peer = { id: 'researcher-1', role: 'researcher', worktree: peerRoot, ownedFiles: problem.ownedFiles } as const; - const assignment = { taskId: publicTask.id, taskDigest: taskVersion(publicTask), workerId: peer.id, seedCommit: problem.baseCommit }; - const action = { kind: 'task' as const, task: publicTask, assignment }; - const reviews = [secret, publicTask, shared].map(task => ({ id: task.id, taskId: task.id, taskDigest: taskVersion(task), status: 'accepted', - leanStatement: `theorem ${task.id} : True`, intendedStatement: task.id === secret.id ? 'PRIVATE_ROUTE_MARKER' : 'VISIBLE_' + task.id, - premises: [], dependencies: [], workspace: directory, files: [], commit: problem.baseCommit, snapshotDigest: 'fixture', environmentDigest: 'fixture' })); - const archive: any = { tasks: [{ task: secret, status: 'integrated', attempts: 1 }, - { task: publicTask, status: 'running', attempts: 0, assignment }, { task: shared, status: 'integrated', attempts: 1 }, - { task: pending, status: 'running', attempts: 1 }], statementReviews: reviews, - researchCheckpoints: { - [secret.id]: { taskDigest: taskVersion(secret), inputDigest: 'PRIVATE_CHECKPOINT', outputDigest: 'private', count: 2, paused: true }, - [publicTask.id]: { taskDigest: taskVersion(publicTask), inputDigest: 'VISIBLE_CHECKPOINT', outputDigest: 'visible', count: 1, paused: false }, - [shared.id]: { taskDigest: 'stale', inputDigest: 'STALE_CHECKPOINT', outputDigest: 'stale', count: 1, paused: false }, - }, deliveries: [progress, - { ...progress, id: 'private-progress', taskId: secret.id, taskDigest: taskVersion(secret), summary: 'PRIVATE_PROGRESS' }, - { ...progress, id: 'stale-progress', taskDigest: 'stale', summary: 'STALE_PROGRESS' }, - { ...progress, id: 'superseded-progress', status: 'superseded', summary: 'SUPERSEDED_PROGRESS' }, - { ...progress, id: 'stale-dependency', dependencies: [{ taskId: publicTask.id, taskDigest: 'stale' }], summary: 'STALE_DEPENDENCY' }] }; - const hiddenRoute = { id: 'PRIVATE_ROUTE_MARKER', targetTaskId: shared.id, - prerequisiteTaskIds: [], closingTaskId: secret.id }; - archive.tasks.find((node: TaskRecord) => node.task.id === shared.id).alternativeRoutes = [hiddenRoute]; - archive.proofRoutes = [hiddenRoute]; - const state: any = { problem, runId: 'audit', turns: 0, phase: 'running', failures: [], cooperation: archive, - workers: [{ id: peer.id, worktree: peerRoot, sessionTaskId: publicTask.id }] }; - const cooperative = new CooperativeResearch({ state, workers: [lead, peer], access: new Map(), - signal: new AbortController().signal, save: () => {}, emit: () => {}, modules: directSolverModules, exclusiveCheck: async check => check() }); - const scoped = cooperative.contextState(action); - const bundle = directSolverModules.M4.build(problem, { ...state, cooperation: scoped }, { - root: directory, worktree: peerRoot, taskText: 'Prove', environment: {}, retrievalRoot: workspace, assignment: action }); - expect(scoped.tasks.map(node => node.task.id)).toEqual([publicTask.id, shared.id]); - expect(bundle.message).not.toContain('PRIVATE_ROUTE_MARKER'); - expect(bundle.message).toContain('VISIBLE_' + publicTask.id); expect(bundle.message).toContain('VISIBLE_' + shared.id); - expect(scoped.deliveries).toEqual([progress]); - expect(Object.keys(scoped.researchCheckpoints ?? {})).toEqual([publicTask.id]); - expect(JSON.stringify(scoped)).not.toContain('PRIVATE_CHECKPOINT'); expect(JSON.stringify(scoped)).not.toContain('STALE_CHECKPOINT'); - expect(bundle.message).toContain('PUBLIC_PENDING_PROGRESS'); - expect(bundle.message).not.toContain('PRIVATE_PROGRESS'); expect(bundle.message).not.toContain('STALE_PROGRESS'); - expect(bundle.message).not.toContain('SUPERSEDED_PROGRESS'); expect(bundle.message).not.toContain('STALE_DEPENDENCY'); - cooperative.activate(peer, action, async () => {}, async () => {}); - const journal = JSON.parse(fs.readFileSync(path.join(peerRoot, 'COOPERATION.json'), 'utf8')); - expect(journal.statements.map((review: any) => review.taskId)) - .toEqual([publicTask.id, shared.id]); - expect(journal.continuation.evidence).toBe('recorded-not-replayed'); - expect(journal.routePriority).toMatchObject({ count: 0, routes: [], digest: mathDigest(canonicalMathJson([])) }); - expect(journal.frontierFocus.digest).toBe(mathDigest(canonicalMathJson(journal.frontierFocus.taskIds))); - expect(JSON.stringify(journal.routePriority)).not.toContain('PRIVATE_ROUTE_MARKER'); - expect(scoped.tasks.find(node => node.task.id === shared.id)?.alternativeRoutes).toEqual([]); - const fullIndex = JSON.parse(fs.readFileSync(path.join(workspace, 'COOPERATION.json'), 'utf8')).routePriority; - expect(fullIndex.count).toBe(1); - expect(fullIndex.digest).toBe(mathDigest(canonicalMathJson(fullIndex.routes))); - expect(fullIndex.routes[0].routeId).toBe(hiddenRoute.id); - expect(journal.continuation.goals.map((goal: any) => goal.taskId)).toEqual([shared.id]); - expect(JSON.stringify(journal.continuation)).not.toContain('PRIVATE_TASK_OBJECTIVE'); - expect(JSON.stringify(journal.continuation)).not.toContain('PRIVATE_ROUTE_MARKER'); - cooperative.deactivate(peer); - expect(fs.readFileSync(path.join(peerRoot, 'COOPERATION.json'), 'utf8')).not.toContain('PRIVATE_ROUTE_MARKER'); - expect(cooperative.contextState(undefined, peer).statementReviews?.map(review => review.taskId)).toEqual([publicTask.id, shared.id]); - expect(cooperative.contextState({ ...action, task: secret }).statementReviews?.map(review => review.taskId)).toContain(secret.id); - expect(cooperative.contextState({ ...action, task: secret }).researchCheckpoints?.[secret.id]?.inputDigest).toBe('PRIVATE_CHECKPOINT'); - expect(cooperative.contextState(undefined, lead).statementReviews).toHaveLength(3); - }); - - it.each(['backtranslate', 'statement-review'] as const)('publishes a %s rejection with the complete failure state', async kind => { - const task = planTasks()[0]; - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peerRoot = path.join(directory, 'peer'); fs.mkdirSync(peerRoot); - const peer = { id: 'researcher-1', role: 'researcher', worktree: peerRoot, ownedFiles: problem.ownedFiles } as const; - const review = { id: 'statement', taskId: task.id, taskDigest: taskVersion(task), - status: kind === 'backtranslate' ? 'translating' : 'reviewing', workerId: peer.id, - commit: problem.baseCommit, snapshotDigest: 'snapshot', workspace: peerRoot }; - const action = { kind, reviewId: review.id, taskId: task.id, taskDigest: review.taskDigest, - seedCommit: review.commit, snapshotDigest: review.snapshotDigest, workspace: peerRoot }; - const state: any = { problem, runId: 'rejection', turns: 0, phase: 'running', - cooperation: { tasks: [{ task, status: 'pending', attempts: 0 }], - groups: [{ group: { id: 'main', status: 'active' }, turns: 0 }], statementReviews: [review] } }; - const saved: any[] = []; - const notify = vi.fn(async () => { - const snapshot = saved.at(-1); - expect(snapshot.error).toBe('fixture_rejected'); - expect(snapshot.statementReviews[0]).toMatchObject({ status: 'changes_requested', summary: 'fixture_rejected' }); - expect(snapshot.deliveries.at(-1)).toMatchObject({ kind: 'failure', status: 'failed', summary: 'fixture_rejected' }); - }); - const cooperative = new CooperativeResearch({ state, workers: [lead, peer], access: new Map(), - signal: new AbortController().signal, save: () => saved.push(JSON.parse(JSON.stringify(state.cooperation))), - emit: () => {}, modules: directSolverModules, exclusiveCheck: async check => check() }); - cooperative.activate(lead, { kind: 'lead', seedCommit: problem.baseCommit }, async () => {}, notify); - cooperative.rejected(action, 'fixture_rejected'); - await cooperative.stop(); - expect(notify).toHaveBeenCalledOnce(); - await expect(notify.mock.results[0].value).resolves.toBeUndefined(); - }); - - it('preserves an unavailable task check for recovery without recording a mathematical failure', async () => { - configureCooperation(); - const checkTask = async (...inputs: Parameters) => { - const proof = await directSolverModules.M2.checkTask(...inputs); - return { ...proof, passed: false, verification: { ...proof.verification, status: 'unavailable' as const } }; - }; - expect(await runSolver([...args, '--workers', '2', '--max-turns', '2'], directory, - { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(1); - const result = JSON.parse(fs.readFileSync(output, 'utf8')); - expect(result).toMatchObject({ status: 'runtime_error', reason: 'math_verifier_unavailable', verifierFailure: { - schema: 'theorem-os.verifier-failure.v1', stage: 'task-proof-delivery', - verification: { status: 'unavailable', results: [expect.objectContaining({ receiptId: expect.any(String) })] }, - } }); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.verifierFailure).toEqual(result.verifierFailure); - expect(state.workers.some((worker: any) => worker.verifierFailure?.stage === 'task-proof-delivery')).toBe(true); - const events = vi.mocked(console.log).mock.calls.map(([line]) => JSON.parse(line)); - expect(events.some((event: any) => event.event === 'worker_failed' && - event.verification?.verification?.status === 'unavailable')).toBe(true); - const archived = state.cooperation; - const pending = archived.tasks.find((node: any) => node.status === 'pending' && - node.feedback === 'math_verifier_unavailable' && node.proof.verification.status === 'unavailable'); - expect(pending).toBeDefined(); - for (const commit of [pending.proof.commit, pending.proof.verification.targetCommit]) - expect(git(state.worktree, ['rev-parse', `refs/math/${state.runId}/evidence/${commit}`])).toBe(commit); - expect((archived.deliveries ?? []).filter((record: any) => record.taskId === pending.task.id && - (record.kind === 'failure' || record.status === 'failed'))).toEqual([]); - expect(archived.failedTaskInputs ?? []).toEqual([]); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each(['stale-body', 'changed-context'])('rejects replacement M2 receipts for a different %s projection', async kind => { - configureCooperation(); - const task = planTasks()[0]; - const file = path.join(project, 'Submission.lean'); - fs.writeFileSync(file, original.replace('theorem first', 'lemma a : True := by trivial\ntheorem first')); - const goodCommit = commitSolverSources(problem, workspace); - const assignment = { taskId: task.id, taskDigest: taskVersion(task), workerId: 'researcher-1', seedCommit: problem.baseCommit }; - const good = await directSolverModules.M2.checkTask(problem, workspace, goodCommit, task, assignment, [], {}, new AbortController().signal); - expect(good.passed).toBe(true); - let submittedCommit = goodCommit; - if (kind === 'stale-body') { - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('lemma a : True := by trivial', 'lemma a : True := by sorry')); - submittedCommit = commitSolverSources(problem, workspace); - } else { - await withSolverWorktree(workspace, good.verification.targetCommit!, async checkout => { - fs.writeFileSync(path.join(checkout, 'generated/p/Challenge.lean'), 'def changedTrusted : Nat := 0\n'); - git(checkout, ['add', '--', 'generated/p/Challenge.lean']); - commitFixture(checkout, 'Alter context'); - const targetCommit = git(checkout, ['rev-parse', 'HEAD']); - good.verification = { ...good.verification, targetCommit, results: good.verification.results.map(result => ({ ...result, targetCommit })) }; - }); - } - const checkTask = async (...inputs: Parameters) => { - const fresh = await directSolverModules.M2.checkTask(...inputs); - expect(fresh.passed).toBe(kind !== 'stale-body'); - return { ...fresh, passed: good.passed, verification: good.verification }; - }; - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const state: any = { problem, environmentDigest: 'fixture', cooperation: { tasks: [{ task, status: 'running', attempts: 1, assignment }] } }; - const cooperative = new CooperativeResearch({ state, workers: [lead], access: new Map([[lead.id, { environment: {}, retrievalRoot: workspace }]]), - signal: new AbortController().signal, save: () => {}, emit: () => {}, - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } }, exclusiveCheck: async check => check() }); - await expect((cooperative as any).check(task, assignment, workspace, submittedCommit)).rejects.toThrow('math_task_check_identity_changed'); - }); - const budgetFixturePlan = () => waitingPlanTasks().map(task => task.id === 'a' ? { ...task, ownerId: 'researcher-1' } : task.id === 'b' ? { ...task, ownerId: 'researcher-2' } : task); - it.each([false, true])('keeps healthy peers available while a pending open settles with failure=%s', async failure => { - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, budgetFixturePlan()); - else finishAssignment(action, options); - return 'completed'; - }); - let pendingOpen: { turns: number; healthyPhase: string } | undefined; - const open = async (...inputs: Parameters) => { - if (inputs[0].environment!.DEEPSCIENTIST_MATH_WORKER_ID === 'researcher-2') { - await expect.poll(() => cooperationState().tasks[0].status).toBe('integrated'); - // Let the healthy worker reach its next assignment request while the last turn is still reserved. - await new Promise(resolve => setImmediate(resolve)); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - pendingOpen = { turns: state.turns, healthyPhase: state.workers.find((worker: any) => worker.id === 'researcher-1').phase }; - if (failure) throw new Error('fixture_pending_open_failed'); - } - return directSolverModules.M1.open(...inputs); - }; - const code = await runSolver([...args, '--workers', '4', '--max-turns', '3'], directory, - { ...directSolverModules, M1: { ...directSolverModules.M1, open } }); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(code).toBe(failure ? 1 : 4); - expect(pendingOpen).toMatchObject({ turns: 3, healthyPhase: expect.not.stringMatching(/^finished$/u) }); - if (failure) expect(state.workers.find((worker: any) => worker.id === 'researcher-2')) - .toMatchObject({ error: 'fixture_pending_open_failed', turns: 0 }); - expect(state.turns).toBe(3); - expect(state.cooperation.tasks.slice(0, 2).map((node: any) => node.status)).toEqual(['integrated', 'integrated']); - expect(state.cooperation.tasks.slice(0, 2).map((node: any) => node.attempts)).toEqual([1, 1]); - expect(state.cooperation.groups[0].turns).toBe(2); - if (failure) expect(state.workers.filter((worker: any) => ['researcher-1', 'engineer'].includes(worker.id)) - .reduce((turns: number, worker: any) => turns + worker.turns, 0)).toBe(2); - }); - - - it('keeps preassigned peers available when another worker reserves the last turn', async () => { - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, budgetFixturePlan()); - else finishAssignment(action, options); - return 'completed'; - }); - let pendingOpen: { turns: number; peerPhase: string; assignment: unknown } | undefined; - const open = async (...inputs: Parameters) => { - if (inputs[0].environment!.DEEPSCIENTIST_MATH_WORKER_ID === 'researcher-1') { - await new Promise(resolve => setImmediate(resolve)); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - pendingOpen = { turns: state.turns, peerPhase: state.workers.find((worker: any) => worker.id === 'researcher-2').phase, - assignment: state.cooperation.tasks[1].assignment }; - throw new Error('fixture_pending_open_failed'); - } - return directSolverModules.M1.open(...inputs); - }; - expect(await runSolver([...args, '--workers', '4', '--max-turns', '2'], directory, - { ...directSolverModules, M1: { ...directSolverModules.M1, open } })).toBe(1); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(pendingOpen).toMatchObject({ turns: 2, peerPhase: expect.not.stringMatching(/^finished$/u), - assignment: { taskId: 'b', workerId: 'researcher-2' } }); - expect(state.workers.find((worker: any) => worker.id === 'researcher-1')) - .toMatchObject({ error: 'fixture_pending_open_failed', turns: 0 }); - expect(state.turns).toBe(2); - expect(state.workers.find((worker: any) => worker.id === 'researcher-2').turns).toBe(1); - expect(state.cooperation.tasks[1]).toMatchObject({ status: 'integrated', attempts: 1 }); - }); - - it('rejects replacement M5 assignments outside the configured route engineer', async () => { - const tasks = planTasks().slice(2).map(task => ({ ...task, dependsOn: [] })); - const assignments: string[] = []; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks, - [{ id: 'main', objective: 'Prove the original obligations', status: 'active', revision: 0, engineerId: 'engineer' }]); - else if (action.kind === 'task') { - assignments.push(action.assignment.workerId); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - const assign = (...inputs: Parameters) => inputs[1].id === 'researcher-1' - ? inputs[0][0] : directSolverModules.M5.assign(...inputs); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '4'], directory, - { ...directSolverModules, M5: { ...directSolverModules.M5, assign } })).toBe(0); - expect(assignments).toEqual(['engineer', 'engineer']); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.workers.find((worker: any) => worker.id === 'researcher-1').error).toBe('math_task_assignment_invalid'); - }); - - it('lets replacement M4 exclude peer history from the final cooperative prompt', async () => { - const tasks: CooperativeTask[] = [{ id: 'question', kind: 'research', objective: 'Explore first', dependsOn: [], revision: 0 }, ...planTasks()]; - tasks[1] = { ...tasks[1], dependsOn: ['question'] }; - const build = (...inputs: Parameters) => ({ - ...directSolverModules.M4.build(...inputs), message: 'CUSTOM_CONTEXT_WITHOUT_PEER_HISTORY\nCooperative assignment:\n' + JSON.stringify(inputs[2].assignment) }); - let checked = false; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.kind === 'research') - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math\n{"summary":"EXCLUDED_PEER_HISTORY"}\n```'); - else { - if (action.kind === 'task' && action.task.id === 'a') { - expect(message).toContain('CUSTOM_CONTEXT_WITHOUT_PEER_HISTORY'); - expect(message).not.toContain('EXCLUDED_PEER_HISTORY'); checked = true; - } - finishAssignment(action, options); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '7'], directory, - { ...directSolverModules, M4: { ...directSolverModules.M4, build } })).toBe(0); - expect(checked).toBe(true); - }); - - it.each(['math', 'json', 'plain', 'markdown'])('accepts %s responses for plans, research, backtranslation and reviews', async format => { - const tasks: CooperativeTask[] = [{ id: 'question', kind: 'research', objective: 'Explore a route', dependsOn: [], revision: 0 }, ...planTasks()]; - tasks[3] = { ...tasks[3], statementReview: true, informalStatement: 'The proposition True holds.' }; - const mathematics = format === 'markdown' ? '# Mathematics\nThe proposition True holds.\n\n```math\n\\top\n```\n\n```math\nTrue\n```' : 'The proposition True holds.'; - const review = { verdict: 'accepted', ...(format === 'math' ? { summary: 'x'.repeat(3007), evidenceRefs: Array(17).fill('S'.repeat(1001)) } : - format === 'json' ? { summary: 'The statement matches its intention.', evidenceRefs: [123, 'STATEMENT.json'] } : - format === 'markdown' ? { evidenceRefs: 'STATEMENT.json' } : {}) }; - const write = (workspace: string, value: object) => fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), - ['math', 'json'].includes(format) ? '```' + format + '\n' + JSON.stringify(value) + '\n```' : JSON.stringify(value)); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') write(options.workspace, { tasks: tasks.map(({ revision: _revision, proofPath: _path, dependsOn, ...task }) => - ({ ...task, ...(dependsOn.length ? { dependsOn } : {}) })) }); - else if (action.kind === 'backtranslate' && format === 'markdown') fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), mathematics); - else if (action.kind === 'backtranslate') write(options.workspace, { mathematics }); - else if (action.kind === 'statement-review' || action.kind === 'review') write(options.workspace, review); - else if (action.kind === 'task' && action.task.kind === 'research' && format === 'markdown') - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'True.intro provides the needed proof.'); - else if (action.kind === 'task' && action.task.kind === 'research') write(options.workspace, { summary: 'True.intro provides the needed proof.' }); - else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '9'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks.map((node: any) => node.task)).toEqual(tasks); - expect(state.cooperation.statementReviews[0]).toMatchObject({ status: 'accepted', translation: { - mathematics, assumptions: [], definitions: [], evidenceRefs: [] } }); - expect(state.cooperation.review).toMatchObject({ status: 'accepted', summary: deliveryDetails(review).summary }); - expect(state.cooperation.deliveries.find((record: any) => record.kind === 'review').evidenceRefs).toEqual(deliveryDetails(review).evidenceRefs); - expect(state.cooperation.deliveries.find((record: any) => record.kind === 'research')).toMatchObject({ taskId: 'question', evidenceRefs: [] }); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); it('prefers an explicit research response and rejects ambiguous legacy blocks', () => { const file = path.join(workspace, 'RESEARCH.md'); @@ -3945,197 +2208,6 @@ describe('isolated solver and host acceptance', () => { }); }); - it('shares simple progress and fixed proofs early without requiring agents to repeat assignment metadata', async () => { - const bothStarted = deferred(), aDelivered = deferred(); let started = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'task' && action.task.kind === 'lemma') { - if (++started === 2) bothStarted.resolve(); - await bothStarted.promise; - const log = path.join(options.workspace, assignmentDeliveryFile(action.assignment)); - const progress = JSON.stringify({ summary: 'Working on the assigned helper' }); - fs.appendFileSync(log, progress + '\n' + progress + '\n'); - finishAssignment(action, options); - fs.appendFileSync(log, JSON.stringify({ kind: 'proof', commit: commitSolverSources(problem, options.workspace), summary: 'Helper proved' }) + '\n'); - await expect.poll(() => cooperationState().tasks.find((node: any) => node.task.id === action.task.id)?.status).toBe('integrated'); - if (action.task.id === 'a') aDelivered.resolve(); - else await aDelivered.promise; - } else finishAssignment(action, options); - return 'completed'; - }); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '5']; - expect(await runSolver(parallelArgs, directory)).toBe(0); - const records = cooperationState().deliveries; - for (const id of ['a', 'b']) { - expect(records.filter((record: any) => record.taskId === id && record.kind === 'progress')).toHaveLength(1); - expect(records.find((record: any) => record.taskId === id && record.kind === 'proof')).toMatchObject({ status: 'verified', taskDigest: taskVersion(planTasks().find(task => task.id === id)!) }); - } - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('keeps simplified delivery logs bound to their assignment across live revisions', async () => { - const tasks = planTasks(); let oldLog = '', oldCommit = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'a') { - const log = path.join(options.workspace, assignmentDeliveryFile(action.assignment)); - fs.appendFileSync(log, '{"summary":"Same progress text"}\n'); - await expect.poll(() => cooperationState().deliveries.some((record: any) => record.taskId === 'a' && - record.taskDigest === action.assignment.taskDigest && record.kind === 'progress')).toBe(true); - if (action.task.revision === 0) { - oldLog = log; finishAssignment(action, options); oldCommit = commitSolverSources(problem, options.workspace); - tasks[0] = { ...tasks[0], revision: 1 }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'simple-revision', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.[0]?.status).toBe('applied'); - } else { - expect(log).not.toBe(oldLog); - fs.appendFileSync(oldLog, JSON.stringify({ kind: 'proof', summary: 'Late old proof', commit: oldCommit }) + '\n'); - fs.appendFileSync(log, '{"summary":"New assignment continues"}\n'); - await expect.poll(() => cooperationState().deliveries.some((record: any) => record.summary === 'New assignment continues')).toBe(true); - finishAssignment(action, options); - } - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory)).toBe(0); - const records = cooperationState().deliveries, progress = records.filter((record: any) => record.summary === 'Same progress text'); - expect(progress).toHaveLength(2); expect(progress[0].status).toBe('superseded'); - expect(progress[0].submissionId).not.toBe(progress[1].submissionId); - expect(progress[1].taskDigest).toBe(taskVersion(tasks[0])); - expect(records.some((record: any) => record.summary === 'Late old proof')).toBe(false); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('requires a new simplified review response after the reviewed proof version changes', async () => { - const tasks = reviewedPlanTasks(), reviewStopped = deferred(); let reviews = 0, reviewerWorkspace = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'review') { - if (++reviews === 1) { - reviewerWorkspace = options.workspace; - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math\n{"verdict":"accepted","summary":"Old version reviewed"}\n```'); - tasks[0] = { ...tasks[0], revision: 1 }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'simple-review-revision', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await reviewStopped.promise; - } - // The next review deliberately writes nothing; the previous response cannot authorize it. - } else finishAssignment(action, options); - return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === reviewerWorkspace) reviewStopped.resolve(); }) })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '10'], directory)).toBe(4); - expect(reviews).toBe(2); - expect(cooperationState().review.status).toBe('changes_requested'); - expect(cooperationState().deliveries.filter((record: any) => record.kind === 'review').map((record: any) => record.status)) - .toEqual(['superseded', 'changes_requested']); - expect(host.officialGate).not.toHaveBeenCalled(); - }, 20_000); - - it('runs distinct helpers concurrently, combines same-file changes and checks the canonical proof after the turn budget is exhausted', async () => { - let started = 0; - const bothStarted = deferred(); - const checking = new Set(); - const bothChecking = deferred(); - const checkTask = async (...inputs: Parameters) => { - const task = inputs[3]; - if (task.kind === 'lemma' && !checking.has(task.id)) { - checking.add(task.id); - if (checking.size === 2) bothChecking.resolve(); - await bothChecking.promise; - } - return directSolverModules.M2.checkTask(...inputs); - }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, waitingPlanTasks()); return 'completed'; } - if (action.kind === 'task' && action.task.kind === 'lemma') { - expect(fs.readFileSync(path.join(options.workspace, 'generated/p/Submission.lean'), 'utf8')).toBe(original); - if (++started === 2) bothStarted.resolve(); - await bothStarted.promise; - } - finishAssignment(action, options); return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '5'], directory, - { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(0); - expect(started).toBe(2); - expect(checking.size).toBe(2); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks.map(node => node.status)).toEqual(['integrated', 'integrated', 'integrated', 'integrated']); - expect(state.turns).toBe(5); - expect(state.cooperation.review).toBeUndefined(); - expect(state.winningWorker).toBe('solver'); - expect(state.usage).toMatchObject({ inputTokens: 5000, totalTokens: 6000 }); - const source = fs.readFileSync(path.join(state.worktree, 'generated/p/Submission.lean'), 'utf8'); - expect(source).toContain('lemma a'); expect(source).toContain('lemma b'); expect(source).not.toContain('sorry'); - const events = vi.mocked(console.log).mock.calls.map(([event]) => JSON.parse(event)); - const assigned = events.findIndex(event => event.event === 'task_assigned' && event.taskId === 'first'); - for (const id of ['a', 'b']) expect(events.findIndex(event => event.event === 'task_integrated' && event.taskId === id)).toBeLessThan(assigned); - expect(host.verify.mock.calls.filter(([request]) => request.items.length === 2)).toHaveLength(2); - expect(host.officialGate).toHaveBeenCalledOnce(); - for (const result of await Promise.all(host.createSession.mock.results.map(result => result.value))) - expect(result.close).toHaveBeenCalledBefore(host.officialGate); - }); - - it('discards a proof superseded by an edit while its independent check is running', async () => { - let originalSubmission: { commit: string; taskDigest: string } | undefined; - const originalDelivery = () => cooperationState().deliveries?.find((delivery: any) => - delivery.taskId === 'a' && delivery.kind === 'proof' && delivery.commit === originalSubmission?.commit && - delivery.taskDigest === originalSubmission?.taskDigest); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, waitingPlanTasks()); return 'completed'; } - if (action.kind === 'task' && action.task.id === 'a' && action.task.revision === 1) { - // Let the old check settle before final proof acceptance cancels outstanding work. - await expect.poll(() => originalDelivery()?.status, { timeout: 5_000 }).toBe('superseded'); - } - finishAssignment(action, options); - if (action.kind === 'task' && action.task.id === 'a' && action.task.revision === 0) - originalSubmission = { commit: commitSolverSources(problem, options.workspace), taskDigest: action.assignment.taskDigest }; - return 'completed'; - }); - let edited = false; - const checkTask = async (...inputs: Parameters) => { - const proof = await directSolverModules.M2.checkTask(...inputs); - if (inputs[2] === originalSubmission?.commit && inputs[4].taskDigest === originalSubmission?.taskDigest && !edited) { - expect(proof.passed).toBe(true); - edited = true; - const journal = JSON.parse(fs.readFileSync(path.join(inputs[1], 'COOPERATION.json'), 'utf8')); - fs.appendFileSync(path.join(`${output}.runtime`, 'edits.jsonl'), JSON.stringify({ - id: 'during-check', baseVersion: journal.planVersion, - tasks: waitingPlanTasks().map(task => task.id === 'a' ? { ...task, revision: 1 } : task), - }) + '\n'); - await expect.poll(() => cooperationState().edits?.find((edit: any) => edit.id === 'during-check')?.status, - { timeout: 5_000 }).toBe('applied'); - } - return proof; - }; - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory, - { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(0); - expect(edited).toBe(true); - expect(originalDelivery()?.status).toBe('superseded'); - expect(cooperationState().tasks.find((node: any) => node.task.id === 'a')).toMatchObject({ task: { revision: 1 }, status: 'integrated' }); - }); - - it('does not accept checked partial proofs as a solution and rechecks integrated evidence on resume', async () => { - configureCooperation(undefined, waitingPlanTasks); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks.slice(0, 2).map(node => node.status)).toEqual(['integrated', 'integrated']); - expect(state.check).toBeUndefined(); - expect(host.officialGate).not.toHaveBeenCalled(); - const before = fs.readFileSync(output, 'utf8'); - expect(await runSolver([...parallelArgs, '--resume', '--workers', '2'], directory)).toBe(1); - expect(fs.readFileSync(output, 'utf8')).toBe(before); - const checks = host.verify.mock.calls.length; - const sessions = host.createSession.mock.calls.length; - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '6'], directory)).toBe(0); - expect(host.verify.mock.calls[checks][0].items.map(item => item.theoremName)).toEqual(['Submission.a', 'Submission.b']); - expect(host.verify.mock.calls[checks][1].expectedDeclarationTypes).toEqual({ 'Submission.a': 'True', 'Submission.b': 'True' }); - for (const [options] of host.createSession.mock.calls.slice(sessions)) expect(options.threadId).toBe( - options.environment.DEEPSCIENTIST_MATH_WORKER_ID === 'solver' ? 'thread-solver' : undefined); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - it('keeps per-target receipts and closed types when batching identical proof projections', async () => { fs.writeFileSync(path.join(project, 'Submission.lean'), original.replace('theorem first', 'lemma a : True := by trivial\nlemma b : True → True := by intro h; exact h\ntheorem first')); @@ -4162,147 +2234,6 @@ describe('isolated solver and host acceptance', () => { expect(host.verify).not.toHaveBeenCalled(); }); - it('preserves restoration progress after an opaque batch failure without expanding verifier retries', async () => { - configureCooperation(undefined, waitingPlanTasks); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const verify = host.verify.getMockImplementation()!; - const progress: number[] = []; - host.verify.mockImplementation(async (request, options) => { - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - progress.push(state.cooperation.recheck?.completed ?? -1); - const result = await verify(request, options); - return request.items.length > 1 && request.items[0].theoremName === 'Submission.a' ? failed(result) : result; - }); - const before = host.verify.mock.calls.length, sessions = host.createSession.mock.calls.length; - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '6'], directory)).toBe(1); - expect(host.verify.mock.calls.slice(before).map(([request]) => request.items.map(item => item.theoremName))) - .toEqual([['Submission.a', 'Submission.b']]); - expect(progress).toEqual([0]); - expect(cooperationState().tasks.slice(0, 2).map((node: TaskRecord) => node.status)).toEqual(['integrated', 'integrated']); - expect(cooperationState().recheck.completed).toBe(0); - expect(host.createSession).toHaveBeenCalledTimes(sessions); - expect(host.officialGate).not.toHaveBeenCalled(); - host.verify.mockImplementation(verify); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '6'], directory)).toBe(0); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each(['partial', 'shared-source', 'infrastructure'])('retains attributable passes and rechecks deterministic failures after a %s restoration batch', async mode => { - configureCooperation(undefined, waitingPlanTasks); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const before = host.verify.mock.calls.length, sessions = host.createSession.mock.calls.length; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - if (request.items.length === 2) { - batch.status = 'failed'; - for (const [index, result] of batch.results.entries()) if (index === 1 || mode !== 'partial') - Object.assign(result, mode === 'infrastructure' && index === 1 ? { status: 'unavailable', error: 'Lean is unavailable.' } : - { status: 'failed', error: 'Lean exited with status 1.', stdoutPreview: 'Submission.lean:3:1: error: unsolved goals' }); - } - return batch; - }); - expect(await runSolver([...parallelArgs, '--resume'], directory)).toBe(mode === 'infrastructure' ? 1 : 4); - expect(host.verify.mock.calls.slice(before).map(([request]) => request.items.map(item => item.theoremName))) - .toEqual(mode === 'infrastructure' ? [['Submission.a', 'Submission.b']] : mode === 'partial' - ? [['Submission.a', 'Submission.b'], ['Submission.b']] - : [['Submission.a', 'Submission.b'], ['Submission.a'], ['Submission.b']]); - expect(host.createSession).toHaveBeenCalledTimes(sessions); - const saved = cooperationState(); - expect(saved.tasks.slice(0, 2).map((node: TaskRecord) => node.status)).toEqual(['integrated', 'integrated']); - if (mode !== 'infrastructure') for (const node of saved.tasks.slice(0, 2)) - expect(node.integratedCheck.verification.results).toEqual([ - expect.objectContaining({ status: 'kernel_verified', theoremName: node.task.theoremName })]); - expect(saved.recheck.completed).toBe(mode === 'infrastructure' ? 0 : 2); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('keeps restored proof receipts reachable through evidence refs', async () => { - configureCooperation(undefined, waitingPlanTasks); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const before = cooperationState().tasks[0].integratedCheck.verification.targetCommit; - const sessions = host.createSession.mock.calls.length; - expect(await runSolver([...parallelArgs, '--resume'], directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - const proofs = state.cooperation.tasks.slice(0, 2).map((node: any) => node.integratedCheck); - expect(proofs[0].verification.targetCommit).not.toBe(before); - for (const proof of proofs) for (const commit of [proof.commit, proof.verification.targetCommit]) - expect(git(state.worktree, ['rev-parse', `refs/math/${state.runId}/evidence/${commit}`])).toBe(commit); - expect(state.cooperation.recheck).toMatchObject({ total: 2, completed: 2 }); - expect(host.createSession).toHaveBeenCalledTimes(sessions); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each(['batch', 'individual'].flatMap(phase => ['reject', 'return'].map(settlement => ({ phase, settlement })))) - ('preserves integrated proofs and unfinished progress when cancelling a restored $phase check ($settlement)', async ({ phase, settlement }) => { - configureCooperation(undefined, waitingPlanTasks); - const modules = phase === 'individual' ? { ...directSolverModules, M2: { ...directSolverModules.M2, - version: directSolverModules.M2.version + '/individual-recovery-fixture', - checkTask: (...input: Parameters) => checkTaskProof(...input) } } : directSolverModules; - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory, modules)).toBe(4); - const before = cooperationState(), sessions = host.createSession.mock.calls.length; - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request, options) => { - if (request.items.length > 1 && request.items[0].theoremName === 'Submission.a') { - if (phase === 'batch') { - process.emit('SIGTERM'); - if (settlement === 'reject') options.signal.throwIfAborted(); - } - const result = await verify(request, options); - return failed(result); - } - if (phase === 'individual' && request.items[0].theoremName === 'Submission.b') { - process.emit('SIGTERM'); - if (settlement === 'reject') options.signal.throwIfAborted(); - const result = await verify(request, options); - return failed(result); - } - return verify(request, options); - }); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '6'], directory, modules)).toBe(4); - const interrupted = cooperationState(), taskId = phase === 'batch' ? 'a' : 'b'; - expect(interrupted.tasks.slice(0, 2).map((node: any) => node.status)).toEqual(['integrated', 'integrated']); - for (const node of interrupted.tasks.slice(0, 2)) { - const previous = before.tasks.find((item: any) => item.task.id === node.task.id); - expect(node.proof).toEqual(previous.proof); - expect(node.feedback).toBe(previous.feedback); - if (phase === 'batch' || node.task.id === 'b') expect(node.integratedCheck).toEqual(previous.integratedCheck); - } - expect(interrupted.recheck).toMatchObject({ total: 2, completed: phase === 'batch' ? 0 : 1, taskId }); - expect(host.createSession).toHaveBeenCalledTimes(sessions); - expect(host.officialGate).not.toHaveBeenCalled(); - - host.verify.mockImplementation(verify); - const checks = host.verify.mock.calls.length; - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '6'], directory, modules)).toBe(0); - expect(host.verify.mock.calls[checks][0].items.map(item => item.theoremName)) - .toEqual(phase === 'batch' ? ['Submission.a', 'Submission.b'] : ['Submission.a']); - expect(cooperationState().tasks.map((node: any) => node.attempts)).toEqual([1, 1, 1, 1]); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each([0, 1800])('honors default unlimited or explicit proof-check time %s with an unlimited solving budget', async seconds => { - configureCooperation(); - const exitCode = await runSolver([...args, '--workers', '4', '--max-turns', '0', '--max-run-seconds', '0', - ...(seconds ? ['--proof-timeout-seconds', String(seconds)] : [])], directory); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(exitCode, JSON.stringify({ result: JSON.parse(fs.readFileSync(output, 'utf8')), - tasks: state.cooperation.tasks.map((node: any) => ({ id: node.task.id, status: node.status, feedback: node.feedback })), - workers: state.workers.map((worker: any) => ({ id: worker.id, error: worker.error })), - events: vi.mocked(console.log).mock.calls.map(([event]) => JSON.parse(event)) - .filter(event => /error|failed|blocked|idle/u.test(event.event)) }, null, 2)).toBe(0); - // Task checks can share a batch or reuse an identical checked projection; the timeout applies to every actual request. - const taskChecks = host.verify.mock.calls.filter(([request]) => request.items.every(item => - state.cooperation.tasks.some((node: TaskRecord) => item.theoremName === node.task.theoremName && item.statementHash === taskVersion(node.task)))); - for (const node of state.cooperation.tasks) expect(taskChecks.some(([request]) => - request.targetCommit === node.integratedCheck.verification.targetCommit && request.items.some(item => item.theoremName === node.task.theoremName))).toBe(true); - for (const [request] of taskChecks) expect(request).toMatchObject({ timeoutMs: seconds ? seconds * 1000 : Infinity, - batchTimeoutMs: seconds ? seconds * 1000 : Infinity }); - }); - const routeGroups = (): RouteGroup[] => [ { id: 'main', objective: 'Prove the original obligations', status: 'active', revision: 0, engineerId: 'engineer' }, { id: 'alternative', objective: 'Test an alternative bridge', status: 'active', revision: 0, maxTurns: 2, maxConcurrent: 1 }, @@ -4310,196 +2241,6 @@ describe('isolated solver and host acceptance', () => { const groupedTasks = () => planTasks().map(task => ({ ...task, groupId: task.id === 'b' ? 'alternative' : 'main', sharing: task.id === 'b' ? 'problem' as const : 'group' as const })); - it('gives every proof turn a fresh index of the saved owned declarations', async () => { - const turns: { key: string; index: unknown[]; source: string }[] = []; - configureCooperation(async (action, options) => { - expect(options.instructions).toContain(path.join(options.workspace, 'DECLARATIONS.jsonl')); - turns.push({ key: action.kind === 'task' ? action.task.id : action.kind, - index: fs.readFileSync(path.join(options.workspace, 'DECLARATIONS.jsonl'), 'utf8').trimEnd().split('\n').map(line => JSON.parse(line)), - source: fs.readFileSync(path.join(options.workspace, 'generated/p/Submission.lean'), 'utf8') }); - finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory)).toBe(0); - for (const turn of turns) expect(turn.index, turn.key).toEqual(ownedSourceDeclarations('Submission.lean', turn.source)); - // The second goal starts from a seed with the checked helpers and first goal, so only its own target has sorry. - expect(turns.find(turn => turn.key === 'second')!.index.map((entry: any) => [entry.name, entry.sorry])).toEqual([ - ['Submission.fixed', false], ['Submission.a', false], ['Submission.b', false], ['Submission.first', false], ['Submission.second', true]]); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(git(state.worktree, ['ls-files', '--', 'DECLARATIONS.jsonl'])).toBe(''); - }); - - it('reuses a checked cross-route lemma with its explicit sharing, producer and version', async () => { - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, groupedTasks().map(task => - task.kind === 'goal' ? { ...task, conditional: false } : task), routeGroups()); - else { - if (action.kind === 'task' && action.task.id === 'first') { - expect(message).toContain('"groupId":"alternative"'); - expect(message).toContain('"producer":"researcher-'); - const graph = JSON.parse(message.split('Lead task graph and host feedback:\n')[1].split('\n')[0]); - const projected = JSON.parse(fs.readFileSync(path.join(options.workspace, 'COOPERATION.json'), 'utf8')) - .tasks.find((row: any) => row.task.id === 'b').integratedCheck; - expect(graph.find((row: any) => row.id === 'b').evidence).toMatchObject({ - commit: projected.commit, sourceDigest: projected.sourceDigest, taskDigest: projected.taskDigest, - }); - } - finishAssignment(action, options); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.groups.map(route => [route.group.id, route.turns])).toEqual([['main', 3], ['alternative', 1]]); - const bridge = state.cooperation.tasks.find(node => node.task.id === 'b'); - expect(bridge.assignment).toMatchObject({ groupId: 'alternative', canonicalCommit: expect.any(String) }); - expect(bridge.integratedCheck.passed).toBe(true); - expect(state.cooperation.tasks.filter(node => node.task.kind === 'goal').every(node => node.assignment.workerId === 'engineer')).toBe(true); - }); - - it.each(['paused', 'stopped', 'budget'] as const)('keeps inactive-route work idle and continues independent tasks (%s)', async mode => { - const groups = routeGroups(); - groups[1] = { ...groups[1], ...(mode === 'budget' ? { maxTurns: 0 } : { status: mode }) }; - const tasks = groupedTasks(); - tasks[3] = { ...tasks[3], dependsOn: [] }; - let started = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks, groups); - else if (action.kind === 'task' && action.task.id === 'second') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('second : True := by sorry', 'second : True := by trivial')); - started++; - } else finishAssignment(action, options); - return 'completed'; - }); - // Spare global turns must not be spent repeatedly asking the Lead to restart an inactive route: `first`, whose - // remaining input sits on it, stalls once. This Lead restates its plan without answering, so the stall is asked - // once more and then recorded as ignored, never asked again. - expect(await runSolver([...args, '--workers', '4', '--max-turns', '10'], directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(started).toBe(1); - expect(state.turns).toBe(5); - expect(state.cooperation.goalPathStall).toMatchObject({ unanswered: 2, ignoredAt: expect.any(Number) }); - expect(state.cooperation.tasks.map(node => node.status)).toEqual(['integrated', 'pending', 'pending', 'integrated']); - expect(state.cooperation.groups[1].turns).toBe(0); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('enforces per-route concurrency and preserves the accumulated route budget when extended on resume', async () => { - const groups = [{ ...routeGroups()[0], maxTurns: 1, maxConcurrent: 1 }]; - let active = 0, peak = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, waitingPlanTasks(), groups); - else { - active++; peak = Math.max(peak, active); - await Promise.resolve(); - finishAssignment(action, options); active--; - } - return 'completed'; - }); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '10']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.groups[0].turns).toBe(1); - // The spent route cap stalls both goals. The Lead restates its plan without answering, so it is asked once more - // and the stall is then recorded as ignored before the run idles. - expect(state.turns).toBe(4); - expect(state.cooperation.goalPathStall).toMatchObject({ unanswered: 2, ignoredAt: expect.any(Number) }); - expect(state.cooperation.tasks[0].status).toBe('integrated'); - writePlan(state.worktree, waitingPlanTasks(), [{ ...groups[0], maxTurns: 4 }]); - expect(await runSolver([...parallelArgs, '--resume'], directory)).toBe(0); - const resumed = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(resumed.cooperation.groups[0].turns).toBe(4); - expect(resumed.cooperation.tasks[0].attempts).toBe(1); - expect(resumed.cooperation.history).toBeUndefined(); - expect(peak).toBe(1); - }); - - it('shows only a route\'s own artifacts and checked public findings in its task context and seeded source', async () => { - const tasks: CooperativeTask[] = [ - { ...planTasks()[0], groupId: 'alternative', sharing: 'group' }, - ...planTasks().slice(2).map(task => ({ ...task, groupId: 'main', dependsOn: task.id === 'first' ? [] : ['first'] })), - ]; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks, routeGroups()); - else if (action.kind === 'task' && action.task.kind === 'goal') { - expect(message).not.toContain('Prove helper a'); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - const source = fs.readFileSync(file, 'utf8'); - expect(source).not.toContain('lemma a'); - fs.writeFileSync(file, source.replace(`${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '5'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(fs.readFileSync(path.join(state.worktree, 'generated/p/Submission.lean'), 'utf8')).toContain('lemma a'); - }); - - it('reactivates a paused route on resume and retains unrelated integrated work', async () => { - const groups = routeGroups(); - groups[1] = { ...groups[1], status: 'paused' }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, groupedTasks(), groups); - else finishAssignment(action, options); - return 'completed'; - }); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '10']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks[0].status).toBe('integrated'); - writePlan(state.worktree, groupedTasks(), routeGroups()); - expect(await runSolver([...parallelArgs, '--resume'], directory)).toBe(0); - const resumed = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(resumed.cooperation.tasks.map(node => node.attempts)).toEqual([1, 1, 1, 1]); - expect(resumed.cooperation.groups.map(route => route.turns)).toEqual([3, 1]); - expect(resumed.cooperation.history).toBeUndefined(); - }); - - it('invalidates a revised route and cross-route consumers while preserving the other route\'s verified lemma', async () => { - const tasks = () => [...groupedTasks(), reviewedPlanTasks().at(-1)!]; - const reviewAcceptances: { accepted: boolean; receiptIds: string[]; assignmentId?: string }[] = []; - const modules = { ...directSolverModules, M4: { ...directSolverModules.M4, - build: (...inputs: Parameters) => { - const second = inputs[1].cooperation?.tasks.find(node => node.task.id === 'second'); - if (inputs[2].assignment?.kind === 'review' && second) reviewAcceptances.push({ - accepted: freshlyAccepted(second, taskVersion(second.task)), - receiptIds: second.integratedCheck!.verification.results.map(receipt => receipt.receiptId), - assignmentId: second.assignment?.assignmentId, - }); - return directSolverModules.M4.build(...inputs); - } } }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks(), routeGroups()); - else finishAssignment(action, options); - return 'completed'; - }); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '5']; - expect(await runSolver(parallelArgs, directory, modules)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks.slice(0, 4).every(node => node.status === 'integrated')).toBe(true); - const groups = routeGroups(); - groups[1] = { ...groups[1], revision: 1 }; - writePlan(state.worktree, tasks(), groups); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '9'], directory, modules)).toBe(0); - const resumed = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(resumed.cooperation.tasks.map(node => node.attempts)).toEqual([1, 1, 2, 1, 0]); - expect(resumed.cooperation.history.map(node => node.task.id)).toEqual(['b', 'first', 'second']); - expect(resumed.cooperation.groups[1]).toMatchObject({ group: { revision: 1 }, turns: 1 }); - const bridge = resumed.cooperation.tasks[1]; - expect(bridge).toMatchObject({ status: 'integrated', proof: { passed: true }, - integratedCheck: { passed: true, taskDigest: taskVersion(bridge.task) } }); - expect(bridge.assignment.assignmentId).not.toBe(state.cooperation.tasks[1].assignment.assignmentId); - const second = resumed.cooperation.tasks[3]; - expect(second.assignment.assignmentId).not.toBe(state.cooperation.tasks[3].assignment.assignmentId); - const probe = vi.mocked(console.log).mock.calls.map(([event]) => JSON.parse(event)) - .findLast(event => event.event === 'task_canonical_probe' && event.taskId === 'second'); - expect(probe).toMatchObject({ passed: true, status: 'kernel_verified', taskDigest: taskVersion(second.task), - seedCommit: second.assignment.seedCommit, receiptIds: second.proof.verification.results.map(receipt => receipt.receiptId) }); - expect(reviewAcceptances.at(-1)).toEqual({ accepted: true, assignmentId: second.assignment.assignmentId, - receiptIds: second.integratedCheck.verification.results.map(receipt => receipt.receiptId) }); - }); - it.each(['unknown', 'private-dependency', 'concurrency', 'duplicate', 'budget'] as const)('rejects an invalid route plan (%s)', flaw => { const tasks = groupedTasks(); const groups = routeGroups(); @@ -4512,984 +2253,53 @@ describe('isolated solver and host acceptance', () => { expect(() => readCooperationPlan(problem, workspace)).toThrow(/math_plan/u); }); - it.each([false, true])('proves ready original goals concurrently with idle Researchers (explicit owner: %s)', async pinned => { - const tasks = planTasks().slice(2).map((task, index) => ({ ...task, dependsOn: [], - ...(pinned ? { ownerId: index === 0 ? 'researcher-1' : 'engineer' } : {}) })); - const assignments: { taskId: string; workerId: string }[] = []; - const bothStarted = deferred(); - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task') { - expect(action.task.kind).toBe('goal'); - expect(message).toContain('Your role: engineer'); - assignments.push({ taskId: action.task.id, workerId: action.assignment.workerId }); - if (assignments.length === 2) bothStarted.resolve(); - await bothStarted.promise; - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace( - `${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '4'], directory)).toBe(0); - expect(assignments).toHaveLength(2); - expect(new Set(assignments.map(item => item.workerId)).size).toBe(2); - expect(assignments.some(item => item.workerId.startsWith('researcher-'))).toBe(true); - if (pinned) expect(assignments).toEqual(expect.arrayContaining([ - { taskId: 'first', workerId: 'researcher-1' }, { taskId: 'second', workerId: 'engineer' }, - ])); - expect(cooperationState().tasks.every((node: any) => node.status === 'integrated')).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('lets the Engineer prove an independent goal while both Researchers work on helpers', async () => { - let started = 0; - const threeStarted = deferred(); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - writePlan(options.workspace, planTasks().map(task => task.id === 'second' ? { ...task, dependsOn: [] } : task)); - } else if (action.kind === 'task' && action.task.id !== 'first') { - if (++started === 3) threeStarted.resolve(); - await threeStarted.promise; - if (action.task.id === 'second') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, original.replace('second : True := by sorry', 'second : True := by trivial')); - } else finishAssignment(action, options); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(started).toBe(3); - }); - - it('shares blocking helpers concurrently across all three proof workers with critical-path scheduling', async () => { - const tasks = planTasks(); - tasks.splice(2, 0, { ...tasks[0], id: 'c', theoremName: 'Submission.c' }); - tasks[3] = { ...tasks[3], dependsOn: ['a', 'b', 'c'] }; - const assignments: { taskId: string; workerId: string; worktree: string }[] = []; - const threeStarted = deferred(); - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else { - if (action.kind === 'task' && action.task.kind === 'lemma') { - expect(message).toContain('Your role: prover'); - assignments.push({ taskId: action.task.id, workerId: action.assignment.workerId, worktree: options.workspace }); - if (assignments.length === 3) threeStarted.resolve(); - await threeStarted.promise; - } - finishAssignment(action, options); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--scheduler', 'critical-path', '--max-turns', '7'], directory)).toBe(0); - expect(assignments).toHaveLength(3); - expect(new Set(assignments.map(item => item.taskId)).size).toBe(3); - expect(new Set(assignments.map(item => item.workerId)).size).toBe(3); - expect(new Set(assignments.map(item => item.worktree)).size).toBe(3); - expect(assignments.some(item => item.workerId === 'engineer')).toBe(true); - expect(cooperationState().tasks.every((record: any) => record.status === 'integrated')).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('rechecks a revised task on resume, invalidates consumers and keeps unrelated checked work', async () => { - configureCooperation(undefined, waitingPlanTasks); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - writePlan(state.worktree, waitingPlanTasks().map(task => task.id === 'a' - ? { ...task, revision: 1, premises: ['Revised mathematical premise'] } : task)); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '7'], directory)).toBe(0); - const resumed = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(resumed.cooperation.tasks.slice(0, 2).map(node => node.attempts)).toEqual([1, 1]); - expect(resumed.cooperation.history.map(node => node.task.id)).toEqual(['a', 'first', 'second']); - expect(resumed.cooperation.tasks[0].task.revision).toBe(1); - const revised = resumed.cooperation.tasks[0]; - expect(revised.proof.taskDigest).toBe(taskVersion(revised.task)); - expect(revised.integratedCheck.taskDigest).toBe(taskVersion(revised.task)); - expect(revised.proof.taskDigest).not.toBe(state.cooperation.tasks[0].proof.taskDigest); - expect(resumed.cooperation.deliveries).toContainEqual(expect.objectContaining({ - taskId: 'a', taskDigest: taskVersion(revised.task), kind: 'proof', status: 'verified', - })); - }); - - it('rechecks modified canonical helpers and prevents consumers from using invalid evidence on resume', async () => { - configureCooperation(undefined, waitingPlanTasks); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - const file = path.join(state.worktree, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('lemma a : True := by trivial', 'lemma a : True := by sorry')); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '4'], directory)).toBe(4); - const resumed = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(resumed.cooperation.tasks[0].status).toBe('blocked'); - expect(resumed.cooperation.tasks[1].status).toBe('integrated'); - expect(resumed.cooperation.tasks.slice(2).every(node => node.attempts === 0)).toBe(true); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('rejects a Reviewer that changes the fixed proof and keeps review separate from Lean acceptance', async () => { - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, reviewedPlanTasks()); - else finishAssignment(action, options); - if (action.kind === 'review') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('by exact first', 'by trivial')); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.review).toMatchObject({ status: 'changes_requested', summary: 'math_review_source_changed' }); - expect(state.check).toBeUndefined(); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each(['missing', 'lean', 'sorry', 'scope', 'context'].flatMap(failure => [false, true].map(repaired => ({ failure, repaired })))) - ('allows one local task repair before Lead escalation ($failure, repaired: $repaired)', async ({ failure, repaired }) => { - let leadTurns = 0, helperTurns = 0; - let firstAssignment: Extract['assignment'] | undefined; - let firstWorkspace: string | undefined; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - leadTurns++; - finishAssignment(action, options); - } else if (action.kind === 'task' && action.task.id === 'a') { - helperTurns++; - if (firstAssignment) { - expect(action.assignment).toEqual(firstAssignment); - expect(options.workspace).toBe(firstWorkspace); - expect(message).toContain(failure === 'missing' ? 'math_task_missing_declaration' : - failure === 'sorry' ? 'Proof source contains sorry or admit.' : - failure === 'scope' ? 'math_task_existing_declaration_changed' : - failure === 'context' ? 'math_original_context_changed' : 'Unknown identifier LOCAL_REPAIR_GAP'); - } else { firstAssignment = { ...action.assignment }; firstWorkspace = options.workspace; } - if (helperTurns === 1 || !repaired) { - if (failure !== 'missing' && helperTurns === 1) { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - const source = fs.readFileSync(file, 'utf8'); - let candidate = source.replace('theorem first', - `lemma a : True := by ${failure === 'sorry' ? 'sorry' : failure === 'lean' ? 'exact LOCAL_REPAIR_GAP' : 'trivial'}\ntheorem first`); - if (failure === 'scope') candidate = candidate.replace('first : True := by sorry', 'first : True := by trivial'); - if (failure === 'context') candidate = 'set_option pp.universes true\n' + candidate; - fs.writeFileSync(file, candidate); - } - } else { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - let source = fs.readFileSync(file, 'utf8').replace('by exact LOCAL_REPAIR_GAP', 'by trivial'); - if (failure === 'scope') source = source.replace('first : True := by trivial', 'first : True := by sorry'); - if (failure === 'context') source = source.replace('set_option pp.universes true\n', ''); - fs.writeFileSync(file, source); - finishAssignment(action, options); - } - } else finishAssignment(action, options); - return 'completed'; - }); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request, options) => { - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); - if (source.includes('LOCAL_REPAIR_GAP') || /lemma a : True := by sorry/u.test(source)) { - const checked = verified(request); - return failed(checked, { error: failure === 'sorry' ? 'Proof source contains sorry or admit.' : 'Lean exited with status 1.', - sorryCount: failure === 'sorry' ? 1 : 0, - stderrPreview: failure === 'lean' ? 'Submission.lean:3:1: error: Unknown identifier LOCAL_REPAIR_GAP' : undefined }); - } - return verify(request, options); - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory)).toBe(repaired ? 0 : 4); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(helperTurns).toBe(2); - if (repaired) expect(leadTurns).toBe(1); - else expect(leadTurns).toBeGreaterThanOrEqual(2); - expect(state.turns).toBeLessThanOrEqual(8); - expect(state.cooperation.tasks[0]).toMatchObject({ attempts: 2, status: repaired ? 'integrated' : 'blocked' }); - if (!repaired) expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each(['scope', 'context'])('resumes a %s repair with its saved helper and keeps acceptance separate', async failure => { - let helperTurns = 0; - let assignment: Extract['assignment'] | undefined; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, planTasks()); - else if (action.kind === 'task' && action.task.id === 'a') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - if (++helperTurns === 1) { - assignment = { ...action.assignment }; - let source = fs.readFileSync(file, 'utf8').replace('theorem first', 'lemma a : True := by trivial\ntheorem first'); - source = failure === 'scope' ? source.replace('first : True := by sorry', 'first : True := by trivial') - : 'set_option pp.universes true\n' + source; - fs.writeFileSync(file, source); - options.onUsage({ inputTokens: 100_000, totalTokens: 100_000 }); - } else { - expect(action.assignment).toEqual(assignment); - expect(message).toContain(failure === 'scope' ? 'math_task_existing_declaration_changed' : 'math_original_context_changed'); - expect(fs.readFileSync(file, 'utf8')).toContain('lemma a : True := by trivial'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by trivial', 'first : True := by sorry') - .replace('set_option pp.universes true\n', '')); - } - } else finishAssignment(action, options); - return 'completed'; - }); - const parallel = [...args, '--workers', '2']; - expect(await runSolver([...parallel, '--max-turns', '20', '--max-total-tokens', '100000'], directory)).toBe(4); - expect(cooperationState().tasks[0]).toMatchObject({ attempts: 1, status: 'pending' }); - expect(cooperationState().tasks[0].sourceRepair).toMatchObject({ pending: true }); - expect(cooperationState().failedTaskInputs ?? []).toEqual([]); - expect(cooperationState().tasks.find((record: TaskRecord) => record.task.id === 'b')).toMatchObject({ attempts: 0, status: 'pending' }); - expect(cooperationState().tasks[0].integratedCheck).toBeUndefined(); - expect(host.officialGate).not.toHaveBeenCalled(); - expect(await runSolver([...parallel, '--max-turns', '20', '--max-total-tokens', '0', '--resume'], directory)).toBe(0); - expect(helperTurns).toBe(2); - expect(cooperationState().tasks.every((record: TaskRecord) => record.status === 'integrated')).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each(['scope', 'context'])('continues an interrupted %s repair without granting another completed retry', async failure => { - let helperTurns = 0; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, planTasks()); - else if (action.kind === 'task' && action.task.id === 'a') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - if (++helperTurns === 1) { - let source = fs.readFileSync(file, 'utf8').replace('theorem first', 'lemma a : True := by trivial\ntheorem first'); - source = failure === 'scope' ? source.replace('first : True := by sorry', 'first : True := by trivial') - : 'set_option pp.universes true\n' + source; - fs.writeFileSync(file, source); - } else if (helperTurns === 2) return 'checkpoint'; - else { - expect(helperTurns).toBe(3); - expect(message).toContain(failure === 'scope' ? 'math_task_existing_declaration_changed' : 'math_original_context_changed'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by trivial', 'first : True := by sorry') - .replace('set_option pp.universes true\n', '')); - } - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '20'], directory)).toBe(0); - expect(helperTurns).toBe(3); - expect(cooperationState().failedTaskInputs ?? []).toEqual([]); - expect(cooperationState().tasks[0].sourceRepair).toMatchObject({ pending: false }); - expect(cooperationState().tasks[0].sourceRepair.startedAttempt).toBeUndefined(); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each([false, true])('keeps an unchanged rejected helper blocked after a Lead decision (revision: %s)', async revise => { - let leadTurns = 0, helperTurns = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - const tasks = planTasks().filter(task => task.id !== 'b') - .map(task => task.id === 'first' ? { ...task, dependsOn: ['a'] } : task); - if (++leadTurns > 1) { - expect(cooperationState().tasks[0].status).toBe('blocked'); - if (revise) tasks[0] = { ...tasks[0], revision: 1 }; - } - writePlan(options.workspace, tasks); - } else if (action.kind === 'task' && action.task.id === 'a') { - if (++helperTurns === 1) fs.writeFileSync(path.join(options.workspace, 'generated/p/Submission.lean'), - original.replace('theorem first', 'lemma a : False := by trivial\ntheorem first')); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory)).toBe(4); - expect(leadTurns).toBeGreaterThanOrEqual(2); - expect(helperTurns).toBe(2); - expect(cooperationState().tasks[0]).toMatchObject({ status: 'blocked', task: { revision: revise ? 1 : 0, type: 'True' } }); - expect(cooperationState().failedTaskInputs).toHaveLength(1); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each([false, true])('reopens a rejected helper only after its saved proof changes (changed: %s)', async changed => { - let leadTurns = 0, helperTurns = 0; - let draftWorktree: string | undefined, savedProofChanged = false; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - const tasks = planTasks().filter(task => task.id !== 'b') - .map(task => task.id === 'first' ? { ...task, dependsOn: ['a'] } : task); - if (++leadTurns > 1) { - expect(message).toContain('task type mismatch'); - if (changed && !savedProofChanged) { - if (!draftWorktree) throw new Error('missing_saved_helper_draft'); - const file = path.join(draftWorktree, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('lemma a : False := by trivial', 'lemma a : True := by trivial')); - commitSolverSources(problem, draftWorktree); savedProofChanged = true; - } - } - writePlan(options.workspace, tasks); - } else if (action.kind === 'task' && action.task.id === 'a') { - draftWorktree = options.workspace; - if (++helperTurns === 1) fs.writeFileSync(path.join(options.workspace, 'generated/p/Submission.lean'), - original.replace('theorem first', 'lemma a : False := by trivial\ntheorem first')); - } else if (action.kind === 'task' && action.task.id === 'first') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact a')); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '12'], directory)).toBe(changed ? 0 : 4); - expect(helperTurns).toBe(changed ? 3 : 2); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.tasks[0]).toMatchObject({ status: changed ? 'integrated' : 'blocked', task: { revision: 0, type: 'True' } }); - expect(host.verify.mock.calls.filter(([, options]) => options.expectedDeclarationType).length).toBeGreaterThan(0); - expect(host.verify.mock.calls.filter(([, options]) => options.expectedDeclarationType) - .every(([, options]) => options.expectedDeclarationType === 'True')).toBe(true); - expect(host.officialGate).toHaveBeenCalledTimes(changed ? 1 : 0); - }); - it.each(['cycle', 'missing', 'duplicate', 'coverage', 'target'])('rejects a %s plan before dispatch', flaw => { const tasks = planTasks(); if (flaw === 'cycle') tasks[0] = { ...tasks[0], dependsOn: ['first'] }; if (flaw === 'missing') tasks[0] = { ...tasks[0], dependsOn: ['unknown'] }; if (flaw === 'duplicate') tasks.push({ ...tasks[2], id: 'duplicate' }); if (flaw === 'coverage') tasks.pop(); - if (flaw === 'target') tasks[2] = { ...tasks[2], theoremName: 'Submission.changed' }; - writePlan(workspace, tasks); - expect(() => readCooperationPlan(problem, workspace)).toThrow(/math_plan/u); - }); - - it('shares routine research findings without a Lead relay or accepting them as proof', async () => { - const tasks: CooperativeTask[] = [{ id: 'route', kind: 'research', objective: 'Review the route and look for counterexamples', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: ['route'] }))]; - let leadTurns = 0; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - if (++leadTurns > 1) expect(message).toContain('Use True.intro'); - writePlan(options.workspace, tasks); - } else if (action.kind === 'task' && action.task.kind === 'research') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math-result\n' + - JSON.stringify({ taskId: 'route', summary: 'Use True.intro', conclusion: 'supporting', evidenceRefs: ['Lean core: True.intro'] }) + '\n```'); - } else if (action.kind === 'review') finishAssignment(action, options); - else if (action.kind === 'task') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - const name = action.task.id; - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${name} : True := by sorry`, `${name} : True := by trivial`)); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(leadTurns).toBe(1); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.dispatchCounts).toEqual({ planning: 1, research: 1, proof: 2 }); - expect(state.cooperation.review).toBeUndefined(); - expect(host.officialGate).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls.some(([request]) => request.items.some(item => item.theoremName === 'route'))).toBe(false); - }); - - it('uses fresh reviewer sessions for early checks of different inputs after ordinary research', async () => { - const warmup: CooperativeTask = { id: 'warmup', kind: 'research', ownerId: 'researcher-1', - objective: 'Locate the doubtful core estimates.', dependsOn: [], revision: 0 }; - const checks: CooperativeTask[] = ['a', 'b'].map(id => ({ id: `check_${id}`, kind: 'research', - objective: `Independently test the proposed input ${id}.`, dependsOn: [id], revision: 0, - reviewScope: 'feasibility', ownerId: 'researcher-1', status: 'paused' })); - const proofs = planTasks().map(task => ({ ...task, status: 'paused' as const, - ...(task.kind === 'lemma' ? { ownerId: 'researcher-2' } : {}) })); - let plans = 0; - const reviewed: string[] = []; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { - plans++; - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ - tasks: [warmup, ...proofs, ...checks.map(task => ({ ...task, - status: plans > 1 ? 'active' as const : 'paused' as const }))], - ...(plans > 1 ? { researchDecisions: [{ deliveryId: /"deliveryId":"([^"]+)"/u.exec(message)?.[1], - outcome: 'adopt', taskIds: ['check_a', 'check_b'], - reason: 'The two distinct input checks are now active.' }] } : {}), - }) + '\n```'); - } else if (action.kind === 'task' && action.task.id === warmup.id) { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), JSON.stringify({ - summary: 'The inputs a and b need distinct feasibility checks.', conclusion: 'inconclusive', needsDecision: true })); - } else if (action.kind === 'task' && action.task.reviewScope === 'feasibility') { - reviewed.push(action.task.id); - expect(action.assignment.workerId).toBe('researcher-1'); - expect(message).toContain('Your role: reviewer'); - expect(message).toContain('"stage":"feasibility-review"'); - expect(message).toContain('"acceptance":"advisory-only"'); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), JSON.stringify({ - summary: `The input ${action.task.dependsOn[0]} still requires a substantive proof.`, conclusion: 'inconclusive' })); - } else throw new Error('unexpected_early_review_fixture_assignment'); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '5'], directory)).toBe(4); - expect(plans).toBe(2); - expect(reviewed).toEqual(['check_a', 'check_b']); - const openings = host.createSession.mock.calls.map(([options]) => options as MathAgentOptions) - .filter(options => options.environment?.DEEPSCIENTIST_MATH_WORKER_ID === 'researcher-1'); - expect(openings).toHaveLength(3); - expect(openings.map(options => options.threadId)).toEqual([undefined, undefined, undefined]); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.workers.find((worker: any) => worker.id === 'researcher-1')) - .toMatchObject({ sessionRole: 'reviewer', sessionTaskId: 'check_b', previousThreadIds: [expect.any(String), expect.any(String)] }); - expect(state.cooperation.tasks.filter((node: TaskRecord) => node.task.reviewScope === 'feasibility') - .every((node: TaskRecord) => node.status === 'completed' && !node.integratedCheck)).toBe(true); - expect(fs.readFileSync(path.join(state.worktree, 'generated/p/Submission.lean'), 'utf8')).toBe(original); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each(['checkpoint', 'replacement', 'legacy'] as const) - ('restores early review sessions by assignment identity (%s)', async mode => { - const task: CooperativeTask = { id: 'route_check', kind: 'research', reviewScope: 'feasibility', - objective: 'Independently test the doubtful core input.', dependsOn: ['a'], revision: 0, ownerId: 'researcher-1' }; - const tasks = [...planTasks().map(task => ({ ...task, status: 'paused' as const, - ...(task.kind === 'lemma' ? { ownerId: 'researcher-2' } : {}) })), task]; - const assignments: string[] = []; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === task.id) { - assignments.push(action.assignment.assignmentId ?? 'legacy'); - const summary = `Discriminating evidence checkpoint ${assignments.length}.`; - // This fixture exercises assignment/thread recovery. A structured partial finding - // has a separate publication protocol that correctly requests a new Lead decision. - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), assignments.length < 3 - ? summary + '\n' : JSON.stringify({ summary, conclusion: 'inconclusive' })); - return assignments.length < 3 ? 'checkpoint' : 'completed'; - } else throw new Error('unexpected_review_identity_fixture_assignment'); - return 'completed'; - }); - const parallelArgs = [...args, '--workers', '4']; - expect(await runSolver([...parallelArgs, '--max-turns', '2'], directory)).toBe(4); - const stateFile = `${output}.runtime/state.json`; - const before = readSolverRunState(stateFile); - const reviewer = before.workers!.find(worker => worker.id === 'researcher-1')!; - const node = before.cooperation!.tasks.find(node => node.task.id === task.id)!; - expect(reviewer.sessionAssignmentId).toBe(node.assignment!.assignmentId); - if (mode === 'replacement') node.assignment!.assignmentId = 'replacement-review-assignment'; - if (mode === 'legacy') { - delete node.assignment!.assignmentId; - delete reviewer.sessionAssignmentId; - } - fs.writeFileSync(stateFile, JSON.stringify(before)); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '3'], directory)).toBe(4); - const resumed = readSolverRunState(stateFile); - expect(resumed.workers!.find(worker => worker.id === reviewer.id)!.sessionAssignmentId) - .toBe(node.assignment!.assignmentId ?? `legacy-task:${node.assignment!.seedCommit}`); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '4'], directory)).toBe(4); - const openings = host.createSession.mock.calls.map(([options]) => options as MathAgentOptions) - .filter(options => options.environment?.DEEPSCIENTIST_MATH_WORKER_ID === reviewer.id); - expect(openings.map(options => options.threadId)) - .toEqual([undefined, mode === 'checkpoint' ? reviewer.threadId : undefined, reviewer.threadId]); - expect(assignments).toEqual([assignments[0], mode === 'checkpoint' ? assignments[0] : - mode === 'legacy' ? 'legacy' : 'replacement-review-assignment', assignments[1]]); - expect(cooperationState().tasks.find((node: TaskRecord) => node.task.id === task.id)) - .toMatchObject({ status: 'completed', attempts: 3 }); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it.each(['markdown', 'json'] as const)('passes a complete %s research argument to its proof consumers', async format => { - const tasks: CooperativeTask[] = [{ id: 'route', kind: 'research', objective: 'Find the closing inference', dependsOn: [], revision: 0 }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: ['route'] }))]; - const argument = 'A reusable mathematical argument. '.repeat(300) + 'EXACT_CLOSING_INFERENCE: use True.intro.'; - let consumers = 0; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.kind === 'research') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), format === 'markdown' ? argument : - '```math-result\n' + JSON.stringify({ summary: 'A complete route is available.', argument, conclusion: 'supporting' }) + '\n```'); - } else if (action.kind === 'review') finishAssignment(action, options); - else if (action.kind === 'task') { - consumers++; - expect(message).toContain('EXACT_CLOSING_INFERENCE'); - expect(message).toContain('"summarySource":"finding:route"'); - const finding = JSON.parse(message.split('Advisory finding for route:\n')[1].split('\n\n')[0]); - const research = cooperationState().deliveries.find((item: any) => item.taskId === 'route' && item.kind === 'research'); - expect(finding.savedSource).toMatchObject({ deliveryId: research.id, commit: research.commit, notesPath: 'RESEARCH.md' }); - expect(research.findingDigest).toBe(mathDigest(finding.finding)); - expect(JSON.parse(finding.finding)[format === 'markdown' ? 'summary' : 'argument']).toBe(argument); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${action.task.id} : True := by sorry`, - `${action.task.id} : True := by trivial`)); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(consumers).toBe(2); - const state = cooperationState(), finding = state.tasks.find((item: TaskRecord) => item.task.id === 'route'); - expect(finding.status).toBe('completed'); - expect(finding.integratedCheck).toBeUndefined(); - expect(finding.finding).toContain('EXACT_CLOSING_INFERENCE'); - const restored = readSolverRunState(`${output}.runtime/state.json`); - expect(restored.dispatchCounts).toEqual({ planning: 1, research: 1, proof: 2 }); - expect(restored.cooperation!.tasks.find(item => item.task.id === 'route')!.finding).toBe(finding.finding); - const restoredDelivery = restored.cooperation!.deliveries!.find(item => item.taskId === 'route' && item.kind === 'research')!; - expect(restoredDelivery.findingDigest).toBe(mathDigest(finding.finding)); - const restoredContext = directSolverModules.M4.build(problem, restored, { root: directory, worktree: restored.worktree, - environment: {}, taskText: 'Prove both targets', retrievalRoot: project, - assignment: { kind: 'lead', seedCommit: restored.cooperation!.canonicalCommit! } }); - expect(restoredContext.message).toContain('EXACT_CLOSING_INFERENCE'); - const restoredSource = JSON.parse(restoredContext.message.split('Advisory finding for route:\n')[1].split('\n\n')[0]).savedSource; - expect(restoredSource).toMatchObject({ deliveryId: restoredDelivery.id, commit: restoredDelivery.commit, notesPath: 'RESEARCH.md' }); - expect(host.verify.mock.calls.some(([request]) => request.items.some(item => item.theoremName === 'route'))).toBe(false); - }); - - it('cancels active task sessions, preserves drafts and resumes the same assignments', async () => { - let started = 0; - const stop = new Map void>(); - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ - threadId: `thread-${options.environment!.DEEPSCIENTIST_MATH_WORKER_ID}`, interrupt: vi.fn(), - close: vi.fn(async () => { stop.get(options.workspace)?.(); }), - run: async (message: string) => { - const action = assignmentFrom(message); - if (action.kind === 'lead') { writePlan(options.workspace, waitingPlanTasks()); return 'completed'; } - if (action.kind !== 'task') throw new Error('unexpected_action'); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, original.replace('theorem first', `lemma ${action.task.id} : True := by sorry\ntheorem first`)); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), `Draft ${action.task.id}`); - const stopped = new Promise(resolve => { stop.set(options.workspace, resolve); }); - if (++started === 2) process.emit('SIGTERM'); - await stopped; return 'interrupted'; - }, - })); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '3'], directory)).toBe(4); - expect(host.verify).not.toHaveBeenCalled(); - for (const result of await Promise.all(host.createSession.mock.results.map(result => result.value))) expect(result.close).toHaveBeenCalledOnce(); - configureCooperation(async (action, options) => { - if (action.kind === 'task' && action.task.kind === 'lemma') { - expect(options.threadId).toBe(`thread-${options.environment!.DEEPSCIENTIST_MATH_WORKER_ID}`); - expect(fs.readFileSync(path.join(options.workspace, 'RESEARCH.md'), 'utf8')).toBe(`Draft ${action.task.id}`); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`lemma ${action.task.id} : True := by sorry`, `lemma ${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8', '--resume'], directory)).toBe(0); - }); - - const cooperationState = () => JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).cooperation; - const appendDelivery = (options: MathAgentOptions, action: Extract, value: Record) => - fs.appendFileSync(path.join(options.workspace, 'DELIVERIES.jsonl'), JSON.stringify({ taskId: action.task.id, - taskDigest: action.assignment.taskDigest, evidenceRefs: [], ...value }) + '\n'); - - const statementTasks = () => { - const tasks = planTasks(); - tasks[0] = { ...tasks[0], statementReview: true, informalStatement: 'INTENT_SECRET: the proposition True holds.' }; - return tasks; - }; - - const configureStatementReferenceReports = () => { - const prepare = host.prepare.getMockImplementation()!; - host.prepare.mockImplementation(async input => { - const result = await prepare(input); - for (const file of input.files) if (/^StatementContext[0-9a-f]+\.lean$/u.test(file)) { - const report = path.join(input.projectRoot, '.lake', file.replace('StatementContext', 'statement-context-').replace('.lean', '.json')); - const contexts = JSON.parse(fs.readFileSync(report, 'utf8')); - for (const context of contexts) Object.assign(context.context, { references: { statement: [], proof: [] } }); - fs.writeFileSync(report, JSON.stringify(contexts)); - } - return result; - }); - }; - - it('accepts empty sandbox metadata directories throughout independent statement review', async () => { - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, statementTasks()); - else { - if (isStatementAction(action)) for (const name of ['.git', '.codex', '.agents', '.aws']) - fs.mkdirSync(path.join(options.workspace, name), { recursive: true }); - finishAssignment(action, options); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory)).toBe(0); - expect(cooperationState().statementReviews[0].status).toBe('accepted'); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each(['disable', 'intent'])('updates review configuration without restarting checked proofs or active consumers (%s)', async change => { - const tasks = statementTasks(); let translations = 0, edited = false; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate') translations++; - if (action.kind === 'task' && action.task.id === 'first' && !edited) { - edited = true; - await expect.poll(() => cooperationState().statementReviews[0].status).toBe('accepted'); - const before = cooperationState(), checked = before.tasks.find((node: any) => node.task.id === 'a').integratedCheck.commit; - tasks[0] = { ...tasks[0], ...(change === 'disable' - ? { statementReview: false, informalStatement: undefined } - : { informalStatement: 'A revised interpretation of True.' }) }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'review-policy', baseVersion: before.planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.[0]?.status).toBe('applied'); - const after = cooperationState(); - expect(after.planVersion).not.toBe(before.planVersion); - expect(after.edits[0].affectedTasks).toEqual([]); - expect(after.tasks.find((node: any) => node.task.id === 'a')).toMatchObject({ status: 'integrated', integratedCheck: { commit: checked } }); - expect(after.tasks.find((node: any) => node.task.id === 'first')).toMatchObject({ status: 'running', assignment: action.assignment }); - } - finishAssignment(action, options); return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '10'], directory)).toBe(0); - const state = cooperationState(); - expect(edited).toBe(true); - expect(state.tasks.map((node: any) => node.attempts)).toEqual([1, 1, 1, 1]); - expect(state.deliveries.filter((record: any) => record.kind === 'proof' && record.status === 'superseded')).toEqual([]); - expect(translations).toBe(change === 'disable' ? 1 : 2); - expect(state.statementReviews.map((review: any) => review.status)).toEqual(change === 'disable' ? ['superseded'] : ['superseded', 'accepted']); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it.each(['nonempty-metadata', 'linked-metadata', 'unexpected-directory'])('rejects unsafe or unexpected statement snapshot entries (%s)', entry => { - const task = statementTasks()[0], reviewWorkspace = path.join(directory, 'blind'); - const snapshot = statementSnapshot(problem, task, workspace, problem.baseCommit, 'fixed-env', []); - const review = { workspace: reviewWorkspace, files: writeStatementSnapshot(reviewWorkspace, snapshot) } as any; - if (entry === 'linked-metadata') fs.symlinkSync(path.join(reviewWorkspace, 'definitions'), path.join(reviewWorkspace, '.codex')); - else { - const extra = path.join(reviewWorkspace, entry === 'nonempty-metadata' ? '.codex' : 'extra'); - fs.mkdirSync(extra); - if (entry === 'nonempty-metadata') fs.writeFileSync(path.join(extra, 'unexpected.txt'), 'Unexpected content'); - } - expect(() => assertStatementSnapshot(review)).toThrow('math_statement_snapshot_changed'); - }); - - it('reviews a fixed statement before its proof finishes, using blind fresh sessions and the shared budget', async () => { - const tasks = statementTasks(), proofStarted = deferred(), comparisonDone = deferred(); - const statements: MathAgentOptions[] = []; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'task' && action.task.id === 'a') { proofStarted.resolve(); await comparisonDone.promise; } - if (isStatementAction(action)) { - statements.push(options); - expect(options.threadId).toBeUndefined(); expect(options.workspace).toBe(action.workspace); - expect(Object.keys(options.environment!).filter(key => key.startsWith('DEEPSCIENTIST_MATH_')).sort()) - .toEqual(['DEEPSCIENTIST_MATH_WORKER_ID', 'DEEPSCIENTIST_MATH_WORKER_WORKTREE']); - expect(fs.existsSync(path.join(options.workspace, '.git'))).toBe(false); - expect(fs.existsSync(path.join(options.workspace, 'COOPERATION.json'))).toBe(false); - const view = fs.readFileSync(path.join(options.workspace, 'STATEMENT.json'), 'utf8') + - fs.readdirSync(path.join(options.workspace, 'definitions')).map(file => fs.readFileSync(path.join(options.workspace, 'definitions', file), 'utf8')).join(''); - expect(view).not.toContain('INTENT_SECRET'); expect(view).not.toContain('by sorry'); - if (action.kind === 'backtranslate') { - expect(message + options.instructions).not.toContain('INTENT_SECRET'); expect(message).not.toContain('Original problem:'); - await proofStarted.promise; - } else { - expect(message).toContain('INTENT_SECRET'); expect(message).toContain('The proposition True holds.'); - expect(cooperationState().tasks[0].status).toBe('running'); - expect(host.officialGate).not.toHaveBeenCalled(); comparisonDone.resolve(); - } - } - finishAssignment(action, options); return 'completed'; - }); - const execute = vi.fn(directSolverModules.M1.execute); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory, - { ...directSolverModules, M1: { ...directSolverModules.M1, execute } })).toBe(0); - expect(statements).toHaveLength(2); expect(execute.mock.calls.every(call => call[1].scope !== 'fixed-statement')).toBe(true); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.turns).toBe(8); expect(state.usage).toMatchObject({ inputTokens: 8000, totalTokens: 9600 }); - expect(state.cooperation.groups[0].turns).toBe(6); expect(state.cooperation.statementReviews).toHaveLength(1); - expect(state.cooperation.statementReviews[0]).toMatchObject({ status: 'accepted', translation: { mathematics: 'The proposition True holds.' } }); - const records = state.cooperation.deliveries.filter((record: any) => ['backtranslation', 'statement-review'].includes(record.kind)); - expect(records.map((record: any) => record.status)).toEqual(['advisory', 'accepted']); - expect(records.every((record: any) => record.evidence === undefined)).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }); - - it('counts both statement phases against route limits without granting any proof acceptance', async () => { - const tasks = statementTasks(); - tasks[1] = { ...tasks[1], dependsOn: ['a'] }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks, [{ id: 'main', objective: 'Prove both goals', status: 'active', revision: 0, maxTurns: 2 }]); - else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory)).toBe(4); - expect(cooperationState().statementReviews[0].status).toBe('accepted'); - expect(cooperationState().tasks.every((node: any) => node.status === 'pending')).toBe(true); - expect(cooperationState().groups[0].turns).toBe(2); - expect(host.verify).not.toHaveBeenCalled(); expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('waits for the blind session to close before another worker can compare its statement', async () => { - const tasks = statementTasks(), closing = deferred(), releaseClose = deferred(); - let blindWorkspace = '', closed = false, comparisonStarted = false, closeHeld = false; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate') blindWorkspace = options.workspace; - if (action.kind === 'statement-review') { expect(closed).toBe(true); comparisonStarted = true; } - if (action.kind === 'task' && action.task.id === 'a') { - await closing.promise; - expect(comparisonStarted).toBe(false); releaseClose.resolve(); - } - finishAssignment(action, options); return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => { - const session = await create(options); - return { ...session, close: vi.fn(async () => { - if (options.workspace === blindWorkspace && !closeHeld) { - closeHeld = true; closing.resolve(); await releaseClose.promise; closed = true; - } - await session.close(); - }) }; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory)).toBe(0); - expect(comparisonStarted).toBe(true); - }); - - it.each(['meaning-rejected', 'snapshot-tampered', 'statement-wrong-binding', 'statement-invalid-verdict', 'proof-wrong-binding', 'proof-invalid-verdict']) - ('withholds final acceptance for %s', async failure => { - const tasks = statementTasks(); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else { - finishAssignment(action, options); - if (action.kind === 'backtranslate' && failure === 'snapshot-tampered') fs.appendFileSync(path.join(options.workspace, 'STATEMENT.json'), ' '); - if (action.kind === 'statement-review' && failure === 'meaning-rejected') { - const file = path.join(options.workspace, 'RESEARCH.md'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('"verdict":"accepted"', '"verdict":"changes_requested"')); - } - if ((action.kind === 'statement-review' && failure.startsWith('statement-')) || (action.kind === 'review' && failure.startsWith('proof-'))) - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), JSON.stringify({ - verdict: failure.endsWith('invalid-verdict') ? 'probably accepted' : 'accepted', - ...(failure.endsWith('wrong-binding') ? action.kind === 'statement-review' ? { snapshotDigest: 'wrong-snapshot' } : { commit: 'wrong-commit' } : {}), - })); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '12'], directory)).toBe(4); - expect(failure.startsWith('proof-') ? cooperationState().review.status : cooperationState().statementReviews[0].status).toBe('changes_requested'); - if (failure === 'snapshot-tampered') expect(cooperationState().statementReviews[0]).toMatchObject({ summary: 'math_statement_snapshot_changed' }); - expect(host.officialGate).not.toHaveBeenCalled(); - }); - - it('cancels a blind translation after a live statement revision and archives its stale delivery', async () => { - const tasks = statementTasks(), cancelled = deferred(); let translations = 0, oldWorkspace = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate' && ++translations === 1) { - oldWorkspace = options.workspace; tasks[0] = { ...tasks[0], revision: 1, informalStatement: 'REVISED_INTENT: True holds.' }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'revise-statement', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await cancelled.promise; - } - finishAssignment(action, options); return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === oldWorkspace) cancelled.resolve(); }) })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '10'], directory)).toBe(0); - expect(translations).toBe(2); - expect(cooperationState().statementReviews.map((review: any) => review.status)).toEqual(['superseded', 'accepted']); - expect(cooperationState().deliveries.find((record: any) => record.kind === 'backtranslation').status).toBe('superseded'); - expect(cooperationState().statementReviews[1].intendedStatement).toContain('REVISED_INTENT'); - }); - - it('resumes an interrupted comparison in a fresh session without repeating its saved backtranslation', async () => { - const tasks = statementTasks(); let translations = 0, comparisons = 0; - tasks[1] = { ...tasks[1], dependsOn: ['a'] }; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate') translations++; - if (action.kind === 'statement-review') { - expect(options.threadId).toBeUndefined(); expect(message).toContain('The proposition True holds.'); - if (++comparisons === 1) { finishAssignment(action, options); return 'checkpoint'; } - } - finishAssignment(action, options); return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '3'], directory)).toBe(4); - const savedReview = cooperationState().statementReviews[0]; - expect(savedReview.status).toBe('translated'); expect(host.officialGate).not.toHaveBeenCalled(); - expect(translations).toBe(1); expect(comparisons).toBe(1); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '9', '--resume'], directory)).toBe(0); - expect(translations).toBe(1); expect(comparisons).toBe(2); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(state.cooperation.statementReviews).toMatchObject([{ id: savedReview.id, snapshotDigest: savedReview.snapshotDigest, status: 'accepted' }]); - expect(state.turns).toBe(9); expect(state.usage).toMatchObject({ inputTokens: 9000, totalTokens: 10800 }); - }); - - it('retries a disconnected statement review without rejecting its statement or repeating the translation', async () => { - const tasks = statementTasks(); let translations = 0, comparisons = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate') translations++; - if (action.kind === 'statement-review' && ++comparisons === 1) return 'failed'; - finishAssignment(action, options); return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - lastError: 'stream disconnected before completion: error sending request' })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '10'], directory)).toBe(0); - expect(translations).toBe(1); expect(comparisons).toBe(2); - expect(host.delay).toHaveBeenCalledOnce(); - expect(cooperationState().statementReviews[0].status).toBe('accepted'); - expect(host.officialGate).toHaveBeenCalledOnce(); + if (flaw === 'target') tasks[2] = { ...tasks[2], theoremName: 'Submission.changed' }; + writePlan(workspace, tasks); + expect(() => readCooperationPlan(problem, workspace)).toThrow(/math_plan/u); }); - it('releases a paused statement session, resumes it freshly and keeps peer notifications out', async () => { - const tasks = statementTasks(), cancelled = deferred(); - const notices: ReturnType[] = []; let translations = 0, oldWorkspace = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate' && ++translations === 1) { - oldWorkspace = options.workspace; tasks[0] = { ...tasks[0], status: 'paused' }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'pause-statement', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await cancelled.promise; - expect(cooperationState().statementReviews[0].status).toBe('pending'); - tasks[0] = { ...tasks[0], status: 'active' }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'resume-statement', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === 'resume-statement' && edit.status === 'applied')).toBe(true); - } - finishAssignment(action, options); return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => { - const notify = vi.fn(); if (options.workspace.includes('/statement-reviews/')) notices.push(notify); - return { ...await create(options), notify, - interrupt: vi.fn(async () => { if (options.workspace === oldWorkspace) cancelled.resolve(); }) }; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '10'], directory)).toBe(0); - expect(translations).toBe(2); expect(cooperationState().statementReviews).toHaveLength(1); - expect(notices.every(notify => !notify.mock.calls.length)).toBe(true); - }); - - it('invalidates an accepted statement review when integrated definitions change, while keeping proof-only changes valid', async () => { - const tasks = statementTasks(); let translations = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate') translations++; - finishAssignment(action, options); - if (action.kind === 'task' && action.task.id === 'a') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', 'def extra : Nat := 0\ntheorem first')); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '10'], directory)).toBe(0); - const reviews = cooperationState().statementReviews; - expect(translations).toBe(2); expect(reviews.map((review: any) => review.status)).toEqual(['superseded', 'accepted']); - expect(reviews[0].snapshotDigest).not.toBe(reviews[1].snapshotDigest); expect(reviews[0].summary).toContain('agrees'); - expect(cooperationState().deliveries.filter((record: any) => record.statementReviewId === reviews[0].id) - .every((record: any) => record.status === 'superseded')).toBe(true); - }); - - it('uses fresh pending-type references to preserve review across an unrelated definition integration before proof evidence exists', async () => { - const tasks = statementTasks(); let translations = 0; - configureCooperation(async (action, options) => { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'a') { - const state = cooperationState(); - expect(state.statementReviews.find((review: any) => review.status === 'accepted')?.references) - .toMatchObject({ scope: 'statement', statementType: 'True', statement: [] }); - expect(state.tasks.find((node: any) => node.task.id === 'a').integratedCheck).toBeUndefined(); - finishAssignment(action, options); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', 'def unrelated : Nat := 10\ntheorem first')); - } else { - if (action.kind === 'backtranslate') translations++; - finishAssignment(action, options); - } - return 'completed'; - }); - configureStatementReferenceReports(); - const exit = await runSolver([...args, '--workers', '2', '--max-turns', '12'], directory); - const details = JSON.stringify({ reviews: cooperationState().statementReviews.map((review: any) => ({ status: review.status, - translated: !!review.translation, references: review.references, snapshotDigest: review.snapshotDigest })), - tasks: cooperationState().tasks.map((node: any) => ({ id: node.task.id, status: node.status, feedback: node.feedback })) }); - expect(exit, details).toBe(0); - expect(translations, details).toBe(1); - expect(cooperationState().statementReviews.filter((review: any) => review.translation).map((review: any) => review.status)) - .toEqual(['accepted']); - }); - - it('revalidates serialized pending-type references instead of trusting a forged empty closure after resume', async () => { - const tasks = statementTasks(); - tasks[1] = { ...tasks[1], status: 'paused' }; - let translations = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else { - if (action.kind === 'backtranslate') translations++; - finishAssignment(action, options); - } - return 'completed'; - }); - configureStatementReferenceReports(); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '3'], directory)).toBe(4); - const stateFile = `${output}.runtime/state.json`, state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); - const worktree = state.workers[0].worktree, file = path.join(worktree, 'generated/p/Submission.lean'); - tasks[1] = { ...tasks[1], status: 'active' }; - state.cooperation.tasks.find((node: TaskRecord) => node.task.id === 'b').task = tasks[1]; - writePlan(worktree, tasks); - const review = state.cooperation.statementReviews.find((review: any) => review.status === 'accepted'); - expect(review, JSON.stringify(state.cooperation.statementReviews.map((item: any) => ({ status: item.status, references: item.references })))).toBeDefined(); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', 'def unrelated : Nat := 10\ntheorem first')); - const commit = commitSolverSources(problem, worktree); - state.cooperation.canonicalCommit = commit; - review.references = captureProofReferences(problem, worktree, commit, - { name: tasks[0].theoremName!, file: tasks[0].proofPath! }, { statement: [], proof: [] }, state.environmentDigest, 'statement', tasks[0].type); - fs.writeFileSync(stateFile, JSON.stringify(state)); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '12', '--resume'], directory)).toBe(0); - expect(translations).toBe(2); - expect(cooperationState().statementReviews.filter((review: any) => review.translation).map((review: any) => review.status)).toEqual(['superseded', 'accepted']); - }); - - it.each(['description', 'type', 'intent', 'premises', 'dependency', 'dependency-description', 'dependency-revision', 'dependency-type', 'dependency-premises'])('reuses an accepted helper review only for an identical formal snapshot (%s)', async change => { - const tasks = statementTasks(); - if (change.startsWith('dependency-')) tasks[0] = { ...tasks[0], dependsOn: ['b'] }; - let translations = 0, edited = false, reviewId = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate') translations++; - if (action.kind === 'task' && action.task.id === 'first' && !edited) { - edited = true; - const before = cooperationState(); - expect(before.statementReviews[0].status).toBe('accepted'); - reviewId = before.statementReviews[0].id; - if (change.startsWith('dependency-')) tasks[1] = { ...tasks[1], - ...(change === 'dependency-description' ? { objective: 'Explain the same supporting fact more clearly.' } : - change === 'dependency-revision' ? { revision: 1 } : change === 'dependency-type' ? { type: 'And True True' } : - { premises: ['An explicit revised dependency premise.'] }) }; - else tasks[0] = { ...tasks[0], revision: 1, - ...(change === 'description' ? { objective: 'Use the established True interface in the original goal.' } : - change === 'type' ? { type: 'And True True' } : change === 'intent' ? { informalStatement: 'A revised meaning.' } : - change === 'premises' ? { premises: ['An explicit revised premise.'] } : { dependsOn: ['b'] }) }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'helper-review-change', baseVersion: before.planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.[0]?.status).toBe('applied'); - } - finishAssignment(action, options); return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '16'], directory)).toBe(0); - const state = cooperationState(), reusable = ['description', 'dependency-description', 'dependency-revision'].includes(change); - expect(edited).toBe(true); - expect(translations).toBe(reusable ? 1 : 2); - expect(state.statementReviews.map((review: any) => review.status)).toEqual(reusable ? ['accepted'] : ['superseded', 'accepted']); - const accepted = state.statementReviews.find((review: any) => review.status === 'accepted'); - expect(accepted.taskDigest).toBe(taskVersion(tasks[0])); - expect(accepted.dependencies.map((dependency: any) => dependency.taskId)).toEqual(tasks[0].dependsOn); - if (change.startsWith('dependency-')) expect(accepted.dependencies).toEqual([{ taskId: 'b', taskDigest: taskVersion(tasks[1]) }]); - expect(state.deliveries.filter((record: any) => record.kind === 'statement-review' && record.status === 'accepted')) - .toContainEqual(expect.objectContaining({ taskDigest: taskVersion(tasks[0]), statementReviewId: accepted.id, - dependencies: accepted.dependencies })); - if (reusable) { - expect(accepted.id).toBe(reviewId); - expect(state.deliveries.filter((record: any) => record.statementReviewId === reviewId && record.status !== 'superseded') - .every((record: any) => record.taskDigest === taskVersion(tasks[0]))).toBe(true); - } - }); + const cooperationState = () => JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')).cooperation; + const appendDelivery = (options: MathAgentOptions, action: Extract, value: Record) => + fs.appendFileSync(path.join(options.workspace, 'DELIVERIES.jsonl'), JSON.stringify({ taskId: action.task.id, + taskDigest: action.assignment.taskDigest, evidenceRefs: [], ...value }) + '\n'); - it.each(['schedule', 'dependency', 'intent', 'premises', 'imports'])('reuses the original statement review only when mathematics is unchanged (%s)', async change => { + const statementTasks = () => { const tasks = planTasks(); - tasks[2] = { ...tasks[2], statementReview: true, informalStatement: 'The first target is True.' }; - let translations = 0, edited = false; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { writePlan(options.workspace, tasks); return 'completed'; } - if (action.kind === 'backtranslate') translations++; - if (action.kind === 'task' && action.task.id === 'first' && !edited) { - edited = true; - expect(cooperationState().statementReviews[0].status).toBe('accepted'); - if (change === 'imports') { - finishAssignment(action, options); - const file = path.join(options.workspace, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, 'import Mathlib.Data.Nat.Basic\n' + fs.readFileSync(file, 'utf8')); - return 'completed'; - } - if (change === 'dependency') tasks[0] = { ...tasks[0], revision: 1, objective: 'Try a different proof method' }; - else tasks[2] = { ...tasks[2], revision: 1, - ...(change === 'schedule' ? { objective: 'Assemble the checked helper proofs', dependsOn: ['b', 'a'] } : - change === 'intent' ? { informalStatement: 'The first target holds under revised meaning.' } : { premises: ['A revised premise'] }) }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'review-change', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.[0]?.status).toBe('applied'); + tasks[0] = { ...tasks[0], statementReview: true, informalStatement: 'INTENT_SECRET: the proposition True holds.' }; + return tasks; + }; + + const configureStatementReferenceReports = () => { + const prepare = host.prepare.getMockImplementation()!; + host.prepare.mockImplementation(async input => { + const result = await prepare(input); + for (const file of input.files) if (/^StatementContext[0-9a-f]+\.lean$/u.test(file)) { + const report = path.join(input.projectRoot, '.lake', file.replace('StatementContext', 'statement-context-').replace('.lean', '.json')); + const contexts = JSON.parse(fs.readFileSync(report, 'utf8')); + for (const context of contexts) Object.assign(context.context, { references: { statement: [], proof: [] } }); + fs.writeFileSync(report, JSON.stringify(contexts)); } - finishAssignment(action, options); return 'completed'; + return result; }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '12'], directory)).toBe(0); - const state = cooperationState(), reusable = change === 'schedule' || change === 'dependency'; - expect(translations).toBe(reusable ? 1 : 2); - expect(state.statementReviews.map((review: any) => review.status)).toEqual(reusable ? ['accepted'] : ['superseded', 'accepted']); - expect(state.deliveries.filter((record: any) => record.kind === 'statement-review' && record.status === 'accepted')) - .toContainEqual(expect.objectContaining({ taskDigest: taskVersion(tasks[2]), dependencies: [] })); + }; + + it.each(['nonempty-metadata', 'linked-metadata', 'unexpected-directory'])('rejects unsafe or unexpected statement snapshot entries (%s)', entry => { + const task = statementTasks()[0], reviewWorkspace = path.join(directory, 'blind'); + const snapshot = statementSnapshot(problem, task, workspace, problem.baseCommit, 'fixed-env', []); + const review = { workspace: reviewWorkspace, files: writeStatementSnapshot(reviewWorkspace, snapshot) } as any; + if (entry === 'linked-metadata') fs.symlinkSync(path.join(reviewWorkspace, 'definitions'), path.join(reviewWorkspace, '.codex')); + else { + const extra = path.join(reviewWorkspace, entry === 'nonempty-metadata' ? '.codex' : 'extra'); + fs.mkdirSync(extra); + if (entry === 'nonempty-metadata') fs.writeFileSync(path.join(extra, 'unexpected.txt'), 'Unexpected content'); + } + expect(() => assertStatementSnapshot(review)).toThrow('math_statement_snapshot_changed'); }); it('builds formal-only snapshots that bind definitions and helper dependencies but ignore goal scheduling', () => { @@ -5654,325 +2464,6 @@ describe('isolated solver and host acceptance', () => { }); }; - it.each(['notes-only', 'changed-source'] as const)('keeps integrated evidence after an unused planned dependency is revised (%s completion)', async completion => { - const tasks = reviewedPlanTasks(); tasks[3] = { ...tasks[3], status: 'paused' }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'first') { - expect(action.assignment.connectionCheck).toBeDefined(); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact b')); - appendDelivery(options, action, { id: 'first-ready', kind: 'proof', summary: 'Only b is used', commit: commitSolverSources(problem, options.workspace) }); - await expect.poll(() => cooperationState().tasks[2].status).toBe('integrated'); - tasks[0] = { ...tasks[0], revision: 1, premises: ['Revised mathematical input'], status: 'paused' }; tasks[3] = { ...tasks[3], status: 'active' }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'unused-revision', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === 'unused-revision' && edit.status === 'applied')).toBe(true); - expect(cooperationState().tasks[2].status).toBe('integrated'); - const edit = cooperationState().edits.find((record: any) => record.id === 'unused-revision'); - expect(edit).toMatchObject({ status: 'applied', receivedAt: expect.any(Number), appliedAt: expect.any(Number), - planVersion: cooperationState().planVersion, affectedTasks: ['a'], - recheck: { status: 'pending', tasks: [{ taskId: 'a', taskDigest: taskVersion(tasks[0]), status: 'pending' }] } }); - expect(edit.recheck.tasks[0].lastCheck).toBeUndefined(); - fs.appendFileSync(path.join(options.workspace, 'RESEARCH.md'), '\nProof integrated; the revised a is unused.\n'); - if (completion === 'changed-source') fs.writeFileSync(file, - fs.readFileSync(file, 'utf8').replace('first : True := by exact b', 'first : True := by sorry')); - } else { - if (action.kind === 'task' && ['a', 'b'].includes(action.task.id)) - await expect.poll(() => cooperationState().tasks[2].status).toBe('conditional'); - if (action.kind === 'task' && action.task.id === 'second') { - expect(action.assignment.dependencies?.map(dependency => dependency.taskId)).toEqual(['first', 'b']); - const context = JSON.parse(fs.readFileSync(path.join(options.workspace, 'COOPERATION.json'), 'utf8')); - expect(context.deliveries.find((record: any) => record.taskId === 'first' && record.status === 'verified')) - .toMatchObject({ dependencies: [{ taskId: 'b', taskDigest: taskVersion(tasks[1]) }] }); - expect(context.deliveries.some((record: any) => record.submissionId === 'first-ready')).toBe(false); - expect(context.peers.find((peer: any) => peer.id === 'a').status).toBe('pending'); - expect(context.edits.find((record: any) => record.id === 'unused-revision').recheck.status).toBe('pending'); - } - finishAssignment(action, options); - } - return 'completed'; - }); - configureReferenceReports({ first: ['b'], second: ['first', 'b'] }); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '5']; - const code = await runSolver(parallelArgs, directory); - const before = cooperationState(), delivery = before.deliveries.find((record: any) => record.taskId === 'first' && record.status === 'verified'); - expect(before.history.map((node: any) => node.task.id)).toEqual(['a']); - expect(delivery).toMatchObject({ status: 'verified', dependencies: [{ taskId: 'b', taskDigest: taskVersion(tasks[1]) }] }); - expect(before.deliveries.find((record: any) => record.submissionId === 'first-ready')).toMatchObject({ status: 'conditional', - dependencies: [{ taskId: 'a' }, { taskId: 'b', taskDigest: taskVersion(tasks[1]) }] }); - expect(before.tasks[2].integratedCheck.conditions ?? []).toEqual([]); - expect(before.tasks[2].integratedCheck.references.tasks).toEqual([{ taskId: 'b', taskDigest: taskVersion(tasks[1]) }]); - expect(before.deliveries.some((record: any) => record.taskId === 'first' && record.status === 'superseded')).toBe(false); - expect(host.officialGate).not.toHaveBeenCalled(); - if (completion === 'changed-source') { - expect(code).toBe(1); - expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ run_outcome: 'runtime_error', reason: 'math_task_condition_version_invalid' }); - expect(git(workspace, ['show', `${before.tasks[2].integratedCheck.commit}:generated/p/Submission.lean`])) - .toContain('first : True := by exact b'); - return; - } - expect(code).toBe(4); - host.verify.mockClear(); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '6'], directory)).toBe(0); - const resumed = cooperationState(); - expect(resumed.tasks.map((node: any) => node.attempts)).toEqual([1, 1, 1, 1, 0]); - expect(resumed.tasks[0].status).toBe('pending'); - expect(resumed.edits[0].recheck.status).toBe('pending'); - const refreshedDelivery = resumed.deliveries.find((record: any) => record.id === delivery.id); - const refreshedProof = resumed.tasks[2].integratedCheck; - expect(resumed.deliveries.filter((record: any) => record.taskId === 'first' && record.status === 'verified')).toEqual([refreshedDelivery]); - expect(refreshedDelivery).toMatchObject({ commit: refreshedProof.commit, sourceDigest: refreshedProof.sourceDigest, - actualReferences: refreshedProof.references, createdAt: delivery.createdAt, assignmentKey: delivery.assignmentKey, - evidence: { passed: true, verification: { status: 'kernel_verified', targetCommit: refreshedProof.verification.targetCommit, - results: refreshedProof.verification.results.map(({ receiptId }: { receiptId: string }) => ({ receiptId })) } } }); - expect(refreshedProof.conditions ?? []).toEqual([]); - expect(refreshedDelivery.artifacts).toEqual(delivery.artifacts); - expect(resumed.deliveries.find((record: any) => record.submissionId === 'first-ready')) - .toEqual(before.deliveries.find((record: any) => record.submissionId === 'first-ready')); - for (const name of ['b', 'first', 'second']) expect(host.verify.mock.calls.some(([request]) => - request.items.length === 1 && request.items[0].theoremName === `Submission.${name}`)).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('revalidates checked sources without new model proof turns after descriptive plan revisions', async () => { - const tasks = reviewedPlanTasks(), reviewStopped = deferred(); - let reviews = 0, reviewerWorkspace = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'review' && ++reviews === 1) { - reviewerWorkspace = options.workspace; - tasks[0] = { ...tasks[0], objective: 'Clarify the same helper theorem', revision: 1 }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'description-only', - baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await reviewStopped.promise; - finishAssignment(action, options); - } else finishAssignment(action, options); - return 'completed'; - }); - configureReferenceReports(); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === reviewerWorkspace) reviewStopped.resolve(); }) })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '9'], directory)).toBe(0); - const state = cooperationState(); - expect(state.tasks.map((node: TaskRecord) => node.attempts)).toEqual([1, 1, 1, 1, 0]); - expect(state.edits[0]).toMatchObject({ status: 'applied', recheck: { status: 'passed' } }); - expect(state.tasks[0].integratedCheck.taskDigest).toBe(taskVersion(tasks[0])); - expect(state.tasks[2].integratedCheck.references.tasks).toContainEqual({ taskId: 'a', taskDigest: taskVersion(tasks[0]) }); - expect(reviews).toBe(2); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it.each(['actual', 'missing', 'whole-module'] as const)('invalidates dependent proofs and archives their old deliveries after a live revision (%s references)', async trace => { - const tasks = reviewedPlanTasks(), reviewStopped = deferred(); - const reviewAcceptances: { accepted: boolean; receiptIds: string[]; assignmentId?: string }[] = []; - const modules = { ...directSolverModules, M4: { ...directSolverModules.M4, - build: (...inputs: Parameters) => { - const second = inputs[1].cooperation?.tasks.find(node => node.task.id === 'second'); - if (inputs[2].assignment?.kind === 'review' && second) reviewAcceptances.push({ - accepted: freshlyAccepted(second, taskVersion(second.task)), - receiptIds: second.integratedCheck!.verification.results.map(receipt => receipt.receiptId), - assignmentId: second.assignment?.assignmentId, - }); - return directSolverModules.M4.build(...inputs); - } } }; - let reviews = 0, reviewerWorkspace = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'review' && ++reviews === 1) { - reviewerWorkspace = options.workspace; tasks[0] = { ...tasks[0], revision: 1, premises: ['Revised mathematical input'] }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'used-revision', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await reviewStopped.promise; - finishAssignment(action, options); - } else finishAssignment(action, options); - return 'completed'; - }); - if (trace !== 'missing') configureReferenceReports(trace === 'actual' - ? { first: ['a', 'b'], second: ['first', 'a', 'b'] } - : { first: ['generated'], second: ['first', 'generated'] }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === reviewerWorkspace) reviewStopped.resolve(); }) })); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '12'], directory, modules)).toBe(0); - const state = cooperationState(); - expect(state.history.map((node: any) => node.task.id)).toEqual(['a', 'first', 'second']); - expect(state.tasks.map((node: any) => node.attempts)).toEqual([1, 1, 2, 1, 0]); - for (const id of ['a', 'first', 'second']) { - const statuses = state.deliveries.filter((record: any) => record.taskId === id && record.kind === 'proof') - .map((record: any) => record.status); - expect(statuses).toContain('superseded'); expect(statuses.at(-1)).toBe('verified'); - expect(statuses.filter((status: string) => status === 'verified')).toHaveLength(1); - expect(statuses.slice(0, -1).every((status: string) => ['superseded', 'conditional'].includes(status))).toBe(true); - } - const edit = state.edits[0]; - expect(edit).toMatchObject({ status: 'applied', affectedTasks: ['a', 'first', 'second'], recheck: { status: 'passed' } }); - for (const result of edit.recheck.tasks) { - const proof = state.tasks.find((node: any) => node.task.id === result.taskId).integratedCheck; - expect(result).toMatchObject({ status: 'passed', taskDigest: proof.taskDigest, - lastCheck: { commit: proof.commit, sourceDigest: proof.sourceDigest, passed: true, conditional: false, - receiptIds: proof.verification.results.map((receipt: any) => receipt.receiptId) } }); - } - const events = vi.mocked(console.log).mock.calls.map(([event]) => JSON.parse(event)); - expect(events.findIndex(event => event.event === 'edit_received')).toBeLessThan(events.findIndex(event => event.event === 'edit_applied')); - expect(events.find(event => event.event === 'edit_applied').recheck.status).toBe('pending'); - const second = state.tasks[3], probeIndex = events.findLastIndex(event => - event.event === 'task_canonical_probe' && event.taskId === 'second'); - expect(probeIndex).toBeGreaterThan(events.findIndex(event => event.event === 'edit_applied')); - expect(events[probeIndex]).toMatchObject({ passed: true, status: 'kernel_verified', taskDigest: taskVersion(second.task), - seedCommit: second.assignment.seedCommit, receiptIds: second.proof.verification.results.map(receipt => receipt.receiptId) }); - expect(reviewAcceptances.length).toBeGreaterThanOrEqual(2); - expect(second.assignment.assignmentId).not.toBe(reviewAcceptances[0].assignmentId); - expect(reviewAcceptances.at(-1)).toEqual({ accepted: true, assignmentId: second.assignment.assignmentId, - receiptIds: second.integratedCheck.verification.results.map(receipt => receipt.receiptId) }); - if (trace === 'actual') expect(state.tasks[2].integratedCheck.references.tasks).toContainEqual({ taskId: 'a', taskDigest: taskVersion(tasks[0]) }); - expect(reviews).toBe(2); expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('records kernel-reported actual dependencies separately from the planned graph and binds their source and environment', async () => { - const tasks = waitingPlanTasks(); - // Save the unplanned input before its consumer becomes ready. - [tasks[0], tasks[1]] = [tasks[1], tasks[0]]; - tasks[2] = { ...tasks[2], dependsOn: ['a'] }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'first') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact b')); - } else finishAssignment(action, options); - return 'completed'; - }); - configureReferenceReports({ first: ['b'], second: ['first', 'b'] }); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request, options) => { - if (request.items.some(item => item.theoremName === 'Submission.first')) - expect(fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8')).toContain('lemma b : True'); - return verify(request, options); - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '6'], directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - const first = state.cooperation.tasks[2]; - expect(first.task.dependsOn).toEqual(['a']); - expect(first.integratedCheck.references.tasks).toEqual([{ taskId: 'b', taskDigest: taskVersion(tasks[0]) }]); - expect(first.integratedCheck.references).toMatchObject({ sourceCommit: first.integratedCheck.commit, environmentDigest: state.environmentDigest }); - expect(first.integratedCheck.references.inputs.map((input: any) => input.name)).toEqual(['b', 'first']); - const live = JSON.parse(fs.readFileSync(path.join(state.worktree, 'COOPERATION.json'), 'utf8')); - expect(live.peers[2].actualReferences.tasks).toEqual(first.integratedCheck.references.tasks); - for (const [index, peer] of live.peers.entries()) { - expect(peer.taskDigest).toBe(taskVersion(state.cooperation.tasks[index].task)); - expect(peer.objectiveDigest).toBe(mathDigest(state.cooperation.tasks[index].task.objective)); - } - }); - - it('retains a supporting declaration fingerprint without inventing a whole producer-task dependency', async () => { - const helper = 'Submission/Helpers.lean'; - fs.mkdirSync(path.join(project, 'Submission')); - fs.writeFileSync(path.join(project, helper), 'namespace Submission.Helpers\nend Submission.Helpers\n'); - const receipt = JSON.parse(fs.readFileSync(problem.activeProblemPath, 'utf8')); - receipt.solverOwnedFiles.push(helper); - fs.writeFileSync(problem.activeProblemPath, JSON.stringify(receipt)); - git(workspace, ['add', '--', `generated/p/${helper}`]); - commitFixture(workspace, 'Owned helper module'); - problem = readSolverProblem(workspace, problem.activeProblemPath); - configureCooperation(async (action, options) => { - finishAssignment(action, options); - if (action.kind === 'task' && action.task.id === 'a') { - fs.writeFileSync(path.join(options.workspace, problem.projectRelative, helper), - 'namespace Submission.Helpers\nlemma support : True := by trivial\nend Submission.Helpers\n'); - } - return 'completed'; - }); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request, options) => { - const result = await verify(request, options); - if (!options.collectDeclarationReferences) return result; - return { ...result, results: result.results.map(item => ({ ...item, declarationReferences: { statement: [], - proof: item.theoremName === 'Submission.first' ? [{ name: 'Submission.Helpers.support', file: helper }] : [] } })) }; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '6'], directory)).toBe(0); - const first = cooperationState().tasks.find((node: any) => node.task.id === 'first'); - expect(first.integratedCheck.references.tasks).toEqual([]); - expect(first.integratedCheck.references.inputs).toContainEqual(expect.objectContaining({ file: helper, name: 'support' })); - }); - - it('rechecks a changed definition consumer while retaining the unrelated checked proof at its original receipt commit', async () => { - const update: CooperativeTask = { id: 'update', kind: 'research', objective: 'Request a definition revision', dependsOn: ['a', 'b'], revision: 0 }; - const tasks = planTasks(); - tasks[2] = { ...tasks[2], dependsOn: [...tasks[2].dependsOn, update.id] }; - tasks.splice(2, 0, update); let leads = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - if (++leads === 2) { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('def selected : Nat := 2', 'def selected : Nat := 3')); - } - writePlan(options.workspace, tasks, undefined, leads === 2 ? [{ - deliveryId: cooperationState().deliveries.find((item: any) => item.taskId === update.id).id, - outcome: 'source', sourcePaths: ['Submission.lean'], - reason: 'The selected definition was changed in the owned Lean source.' }] : undefined); - } else if (action.kind === 'task' && action.task.id === 'a') { - finishAssignment(action, options); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('lemma a', 'def selected : Nat := 2\nlemma a')); - } else if (action.kind === 'task' && action.task.id === 'update') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math-result\n' + JSON.stringify({ taskId: 'update', - summary: 'Revise the selected definition', conclusion: 'supporting', needsDecision: true, evidenceRefs: [] }) + '\n```'); - } else finishAssignment(action, options); - return 'completed'; - }); - configureReferenceReports({ a: ['selected'] }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '8'], directory)).toBe(0); - expect(leads).toBe(2); - for (const [name, count] of [['a', 2], ['b', 1]] as const) - expect(host.verify.mock.calls.filter(([request]) => request.items.length === 1 && request.items[0].theoremName === `Submission.${name}`)).toHaveLength(count); - const state = cooperationState(); - expect(state.tasks[0].integratedCheck.references.inputs.find((input: any) => input.name === 'selected')).toBeDefined(); - expect(state.tasks[1].integratedCheck.commit).not.toBe(state.canonicalCommit); - const events = vi.mocked(console.log).mock.calls.map(([event]) => JSON.parse(event)); - expect(events.filter(event => event.event === 'task_check_reused').map(event => event.taskId)).toContain('b'); - expect(events.filter(event => event.event === 'task_check_reused').map(event => event.taskId)).not.toContain('a'); - }); - - it('revalidates archived reference evidence on resume instead of trusting an unchanged recorded footprint', async () => { - configureCooperation(); configureReferenceReports(); - const parallelArgs = [...args, '--workers', '2', '--max-turns', '3']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - expect(cooperationState().tasks[0].integratedCheck.references).toBeDefined(); - host.verify.mockClear(); - expect(await runSolver([...parallelArgs, '--max-turns', '6', '--resume'], directory)).toBe(0); - for (const id of ['a', 'b']) expect(host.verify.mock.calls.some(([request]) => - request.items.some(item => item.theoremName === `Submission.${id}`))).toBe(true); - }); - - it('preserves a reviewed statement after unrelated definitions change once Lean has identified its actual statement references', async () => { - const tasks = statementTasks(); - tasks.splice(2, 0, { id: 'update', kind: 'research', objective: 'Revise an unrelated helper definition', dependsOn: ['a', 'b'], revision: 0 }); - let leads = 0, translations = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - if (++leads === 2) { - expect(cooperationState().statementReviews[0].references.scope).toBe('statement'); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', 'def unrelated : Nat := 10\ntheorem first')); - } - writePlan(options.workspace, tasks, undefined, leads === 2 ? [{ - deliveryId: cooperationState().deliveries.find((item: any) => item.taskId === 'update').id, - outcome: 'source', sourcePaths: ['Submission.lean'], - reason: 'The new definition was added to the owned Lean source.' }] : undefined); - } else if (action.kind === 'task' && action.task.id === 'update') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math-result\n' + JSON.stringify({ taskId: 'update', - summary: 'Add unrelated helper definition', conclusion: 'supporting', needsDecision: true, evidenceRefs: [] }) + '\n```'); - } else { - if (action.kind === 'backtranslate') translations++; - finishAssignment(action, options); - } - return 'completed'; - }); - configureReferenceReports(); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '10'], directory)).toBe(0); - expect(translations).toBe(1); expect(cooperationState().statementReviews).toHaveLength(1); - expect(cooperationState().statementReviews[0].status).toBe('accepted'); - }); - it('binds statement references to types and definitions while preserving them across proof-body changes', () => { const file = path.join(project, 'Submission.lean'); const source = original.replace('theorem first', 'def selected : Nat := 2\nlemma supporting : True := by trivial\ntheorem first'); @@ -6015,586 +2506,6 @@ describe('isolated solver and host acceptance', () => { expect(captureProofReferences(problem, workspace, commit, root, { statement: [], proof: [{ name: 'outside', file: '../outside.lean' }] }, 'fixed-env')).toBeUndefined(); }); - it('checks a conditional parent while its lemmas run and integrates it without another model turn once they close', async () => { - const tasks = planTasks(); tasks[2] = { ...tasks[2], conditional: true }; - let parentTurns = 0, conditionalChecks = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.kind === 'lemma') { - await expect.poll(() => cooperationState().tasks[2].status).toBe('conditional'); - expect(host.officialGate).not.toHaveBeenCalled(); - const parent = cooperationState().tasks[2]; - expect(parent.integratedCheck).toBeUndefined(); - expect(parent.proof.conditions.map((condition: any) => condition.taskId)).toEqual(['a', 'b']); - finishAssignment(action, options); - } else if (action.kind === 'task' && action.task.id === 'first') { - parentTurns++; - expect(cooperationState().tasks.slice(0, 2).every((node: any) => node.status === 'running')).toBe(true); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', - 'first : True := by\n -- Submission.a remains a reference in this comment.\n exact And.left (And.intro Submission.a Submission.b)')); - const commit = commitSolverSources(problem, options.workspace); - appendDelivery(options, action, { id: 'conditional-parent', kind: 'proof', summary: 'Parent proved assuming a and b', commit }); - await expect.poll(() => cooperationState().deliveries.some((record: any) => record.submissionId === 'conditional-parent' && record.status === 'conditional')).toBe(true); - } else finishAssignment(action, options); - return 'completed'; - }); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request, options) => { - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); - if (source.includes('theorem first : theorem_os_conditional_type%')) { - conditionalChecks++; - expect(source).toContain('exact And.left (And.intro _root_.Submission.a _root_.Submission.b)'); - expect(source).not.toContain('-- Submission.a remains a reference in this comment.'); - expect(source).not.toMatch(/lemma [ab]/u); - expect(source).not.toContain('sorry'); - } - return verify(request, options); - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(parentTurns).toBe(1); expect(conditionalChecks).toBe(1); - expect(cooperationState().tasks.every((node: any) => node.status === 'integrated')).toBe(true); - const records = cooperationState().deliveries.filter((record: any) => record.taskId === 'first' && record.kind === 'proof'); - expect(records.map((record: any) => record.status)).toEqual(['conditional', 'verified']); - expect(records[0].remainingObligations).toEqual(['a', 'b']); - expect(records[1].remainingObligations).toEqual([]); - const source = fs.readFileSync(path.join(project, 'Submission.lean'), 'utf8'); - expect(source).not.toContain('(a : True)'); - expect(source).toContain('-- Submission.a remains a reference in this comment.'); - expect(source).toContain('And.intro Submission.a Submission.b'); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it.each(['unproved-child', 'failed-combination'])('keeps a checked conditional parent incomplete after %s', async failure => { - const tasks = planTasks(); tasks[2] = { ...tasks[2], conditional: true }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.kind === 'lemma') { - await expect.poll(() => cooperationState().tasks[2].status).toBe('conditional'); - finishAssignment(action, options); - if (failure === 'unproved-child' && action.task.id === 'a') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('a : True := by trivial', 'a : True := by sorry')); - } - } else if (action.kind === 'task' && action.task.id === 'first') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact a')); - } else finishAssignment(action, options); - return 'completed'; - }); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request, options) => { - const result = await verify(request, options); - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); - return failure === 'failed-combination' && request.items[0].theoremName === 'Submission.first' && - !source.includes('theorem first : theorem_os_conditional_type%') - ? failed(result, { error: 'Lean exited with status 1.', stdoutPreview: 'Submission.lean:1:0: error: fixture combined proof does not close the target' }) - : result; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '4'], directory)).toBe(4); - expect(cooperationState().tasks[2].status).toBe(failure === 'unproved-child' ? 'conditional' : 'blocked'); - expect(cooperationState().tasks[3].attempts).toBe(0); - expect(cooperationState().deliveries.some((record: any) => record.taskId === 'first' && record.status === 'conditional')).toBe(true); - expect(JSON.parse(fs.readFileSync(output, 'utf8')).solver_ready_receipt_valid).toBe(false); - expect(host.officialGate).not.toHaveBeenCalled(); - expect(git(workspace, ['rev-parse', 'HEAD'])).toBe(problem.baseCommit); - }, 20_000); - - it('closes a chain of conditional parents in dependency order without repeating their model calls', async () => { - const tasks = planTasks(); - tasks[1] = { ...tasks[1], conditional: true, dependsOn: ['a'] }; - tasks[2] = { ...tasks[2], conditional: true, dependsOn: ['b'] }; - const calls: string[] = [], checkedTypes: string[] = []; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task') { - calls.push(action.task.id); - if (action.task.id === 'a') { - await expect.poll(() => cooperationState().tasks.slice(1, 3).every((node: any) => node.status === 'conditional')).toBe(true); - expect(host.officialGate).not.toHaveBeenCalled(); finishAssignment(action, options); - } else if (action.task.id === 'b' || action.task.id === 'first') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'), source = fs.readFileSync(file, 'utf8'); - fs.writeFileSync(file, action.task.id === 'b' - ? source.replace('theorem first', 'lemma b : True := by exact a\ntheorem first') - : source.replace('first : True := by sorry', 'first : True := by exact b')); - } else finishAssignment(action, options); - } else finishAssignment(action, options); - return 'completed'; - }); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request, options) => { - if (request.items[0].theoremName === 'Submission.b' && options.expectedDeclarationType) checkedTypes.push(options.expectedDeclarationType); - return verify(request, options); - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(calls.filter(id => id === 'b')).toHaveLength(1); expect(calls.filter(id => id === 'first')).toHaveLength(1); - expect(checkedTypes).toContain(conditionalExpectedType('Submission.b', 'True', [{ theoremName: 'Submission.a', type: 'True' }])); - expect(checkedTypes).toContain('True'); - expect(cooperationState().deliveries.filter((record: any) => record.status === 'verified').map((record: any) => record.taskId)) - .toEqual(['a', 'b', 'first', 'second']); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('invalidates a conditional parent when a live edit changes its assumed lemma version', async () => { - const tasks = planTasks(); tasks[2] = { ...tasks[2], conditional: true }; - let parentTurns = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'a' && action.task.revision === 0) { - await expect.poll(() => cooperationState().deliveries.some((record: any) => record.taskId === 'first' && record.status === 'conditional')).toBe(true); - tasks[0] = { ...tasks[0], revision: 1 }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'revise-assumption', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === 'revise-assumption' && edit.status === 'applied')).toBe(true); - finishAssignment(action, options); - } else if (action.kind === 'task' && action.task.id === 'a' && action.task.revision === 1) { - await expect.poll(() => cooperationState().tasks[2].status).toBe('conditional'); - const result = cooperationState().edits[0].recheck.tasks.find((result: any) => result.taskId === 'first'); - expect(result).toMatchObject({ status: 'conditional', lastCheck: { passed: true, conditional: true } }); - expect(cooperationState().edits[0].recheck.status).toBe('pending'); - expect(host.officialGate).not.toHaveBeenCalled(); - finishAssignment(action, options); - } else if (action.kind === 'task' && action.task.id === 'first') { - parentTurns++; - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact a')); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory)).toBe(0); - expect(parentTurns).toBe(2); - const state = cooperationState(); - expect(state.history.find((record: any) => record.task.id === 'first').proof.conditions) - .toContainEqual({ taskId: 'a', taskDigest: taskVersion({ ...tasks[0], revision: 0 }) }); - expect(state.deliveries.some((record: any) => record.taskId === 'first' && record.status === 'superseded')).toBe(true); - expect(state.tasks[2]).toMatchObject({ status: 'integrated', attempts: 2 }); - expect(state.edits[0].recheck.status).toBe('passed'); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('resumes a saved conditional parent, rechecks its archived evidence and avoids repeating the parent model call', async () => { - const tasks = planTasks(); tasks[0] = { ...tasks[0], status: 'paused' }; tasks[1] = { ...tasks[1], status: 'paused' }; - tasks[2] = { ...tasks[2], conditional: true }; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'first') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact a')); - } else throw new Error('Only the conditional parent should run'); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '2'], directory)).toBe(4); - const before = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(before.cooperation.tasks[2]).toMatchObject({ status: 'conditional', attempts: 1 }); - const projection = before.cooperation.tasks[2].proof.projection; - const conditionalSourceHash = before.cooperation.tasks[2].proof.verification.results - .find((result: any) => result.theoremName === 'Submission.first').sourceDeclarationHash; - expect(conditionalSourceHash).toEqual(expect.any(String)); - expect(projection).toMatchObject({ environmentDigest: before.environmentDigest, - problemReceiptDigest: expect.any(String), sourceDigest: expect.any(String) }); - host.createSession.mockClear(); host.verify.mockClear(); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '2', '--resume'], directory)).toBe(4); - expect(host.createSession).not.toHaveBeenCalled(); - expect(cooperationState().tasks[2]).toMatchObject({ status: 'conditional', attempts: 1, proof: { projection, passed: true } }); - expect(cooperationState().tasks[0].task.status).toBe('paused'); - expect(cooperationState().tasks[1].task.status).toBe('paused'); - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.officialGate).not.toHaveBeenCalled(); - writePlan(before.worktree, tasks.map(task => ({ ...task, status: 'active' }))); - const resumed: string[] = []; - configureCooperation(async (action, options) => { - if (action.kind === 'task') resumed.push(action.task.id); - finishAssignment(action, options); return 'completed'; - }); - host.verify.mockClear(); - const result = await runSolver([...args, '--workers', '4', '--max-turns', '6', '--resume'], directory); - expect(result, JSON.stringify(cooperationState().tasks.map((node: any) => ({ id: node.task.id, status: node.status, feedback: node.feedback })))).toBe(0); - expect(resumed).not.toContain('first'); - expect(cooperationState().tasks[2]).toMatchObject({ status: 'integrated', attempts: 1 }); - expect(host.verify.mock.calls.filter(([request]) => { - const source = request.items[0].theoremName === 'Submission.first' && request.items[0].expectedSourceDeclarationHash; - return source === conditionalSourceHash; - })).toHaveLength(1); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('integrates helpers and starts independent consumers while a mathematical Lead decision is still running', async () => { - const leadBusy = deferred(), consumerStarted = deferred(); - let leadTurns = 0; - const tasks: CooperativeTask[] = [{ id: 'question', kind: 'research', objective: 'Decide a mathematical route', dependsOn: [], revision: 0 }, ...waitingPlanTasks()]; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') { - if (++leadTurns === 2) { leadBusy.resolve(); await consumerStarted.promise; } - writePlan(options.workspace, tasks, undefined, leadTurns === 2 ? [{ - deliveryId: cooperationState().deliveries.find((item: any) => item.taskId === 'question').id, - outcome: 'decline', reason: 'The independent checked helpers close the goals without a route change.' }] : undefined); - } else if (action.kind === 'task' && action.task.id === 'question') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math-result\n' + JSON.stringify({ - taskId: 'question', summary: 'Please choose a route', conclusion: 'inconclusive', evidenceRefs: [], needsDecision: true }) + '\n```'); - } else { - if (action.kind === 'task' && action.task.id === 'a') await leadBusy.promise; - if (action.kind === 'task' && action.task.id === 'first') { - expect(leadTurns).toBe(2); consumerStarted.resolve(); - } - finishAssignment(action, options); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '9'], directory)).toBe(0); - expect(cooperationState().tasks.filter((node: any) => node.task.kind !== 'research').every((node: any) => node.status === 'integrated')).toBe(true); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('checks and integrates an immutable early proof before its producer finishes the turn', async () => { - const consumerStarted = deferred(); - let deliveredCommit: string | undefined, producerId: string | undefined; - let consumer: { message: string; accepted: boolean } | undefined; - configureCooperation(async (action, options, message) => { - if (action.kind === 'lead') { writePlan(options.workspace, waitingPlanTasks()); return 'completed'; } - if (action.kind === 'task' && action.task.id === 'a') { - finishAssignment(action, options); - producerId = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID; - deliveredCommit = commitSolverSources(problem, options.workspace); - appendDelivery(options, action, { id: 'early-a', kind: 'proof', summary: 'The helper is ready', commit: deliveredCommit }); - await consumerStarted.promise; - expect(cooperationState().tasks[0].status).toBe('integrated'); - } else { - if (action.kind === 'task' && action.task.id === 'first') { - consumer = { message, accepted: host.officialGate.mock.calls.length > 0 }; - consumerStarted.resolve(); - } - finishAssignment(action, options); - } - return 'completed'; - }); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (...inputs) => { - const result: MathematicsVerifierBatchResult = await verify(...inputs); - return { ...result, events: [{ event: 'diagnostic.emitted', details: { message: 'FULL_CHECK_TRACE' } }], - results: result.results.map(receipt => ({ ...receipt, stdoutPreview: 'FULL_CHECK_OUTPUT' })) }; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(consumer).toMatchObject({ message: expect.stringContaining('early-a'), accepted: false }); - const state = cooperationState(), proof = state.tasks[0].proof, integrated = state.tasks[0].integratedCheck; - const delivery = state.deliveries.find((record: any) => record.submissionId === 'early-a'); - expect(delivery).toMatchObject({ - kind: 'proof', status: 'verified', producer: producerId, commit: integrated.commit, - sourceDigest: integrated.sourceDigest, - statement: 'True', remainingObligations: [], evidence: { passed: true } }); - expect(delivery.actualReferences).toEqual(integrated.references); - expect(proof.commit).toBe(deliveredCommit); - expect(delivery.artifacts.commit).toBe(deliveredCommit); - expect(integrated.conditions ?? []).toEqual([]); - expect(delivery.evidence.verification).toMatchObject({ status: 'kernel_verified', targetCommit: integrated.verification.targetCommit, - results: expect.arrayContaining([expect.objectContaining({ receiptId: expect.any(String) })]) }); - expect(delivery.evidence.verification.results).toEqual(integrated.verification.results.map((receipt: any) => ({ receiptId: receipt.receiptId }))); - expect(delivery.evidence.verification).not.toHaveProperty('events'); - expect(delivery.evidence.verification.results[0]).not.toHaveProperty('stdoutPreview'); - expect(proof.verification.events[0].details.message).toBe('FULL_CHECK_TRACE'); - expect(proof.verification.results[0].stdoutPreview).toBe('FULL_CHECK_OUTPUT'); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('starts a conditional sketch before its proof dependency, steers it with public progress and retains the unproved obligation', async () => { - const sketchStarted = deferred(), progressNotified = deferred(); - let sketchWorkspace: string | undefined, producerId: string | undefined; - let initialPeerStatus: string | undefined, notifiedPeer: unknown; - const tasks: CooperativeTask[] = [ - { ...planTasks()[0], groupId: 'alternative', sharing: 'problem' }, - { id: 'draft', kind: 'sketch', objective: 'Explore the bridge before it is proved', dependsOn: ['a'], revision: 0, groupId: 'main' }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: task.id === 'first' ? ['draft'] : ['first'], groupId: 'main' })), - ]; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks, routeGroups()); - else if (action.kind === 'task' && action.task.id === 'a') { - producerId = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID; - await sketchStarted.promise; - appendDelivery(options, action, { id: 'hint-a', kind: 'progress', summary: 'Try True.intro', remainingObligations: ['a'] }); - await progressNotified.promise; - await expect.poll(() => cooperationState().tasks.find((node: any) => node.task.id === 'draft')?.status).toBe('completed'); - finishAssignment(action, options); - } else if (action.kind === 'task' && action.task.id === 'draft') { - sketchWorkspace = options.workspace; - const peers = JSON.parse(fs.readFileSync(path.join(options.workspace, 'COOPERATION.json'), 'utf8')).peers; - initialPeerStatus = peers.find((peer: any) => peer.id === 'a')?.status; - sketchStarted.resolve(); await progressNotified.promise; - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math-result\n' + JSON.stringify({ - taskId: 'draft', summary: 'Conditional argument using a', conclusion: 'supporting', evidenceRefs: ['hint-a'] }) + '\n```'); - } else if (action.kind === 'task') { - if (action.assignment.connectionCheck) expect(action.assignment.connectionCheck.inputs) - .toEqual([{ taskId: 'a', taskDigest: taskVersion(tasks[0]) }]); - else expect(cooperationState().tasks[0].status).toBe('integrated'); - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(`${action.task.id} : True := by sorry`, `${action.task.id} : True := by trivial`)); - } else finishAssignment(action, options); - return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), notify: vi.fn(async () => { - if (options.workspace !== sketchWorkspace) return; - const snapshot = JSON.parse(fs.readFileSync(path.join(options.workspace, 'COOPERATION.json'), 'utf8')); - if (snapshot.deliveries.some((record: any) => record.submissionId === 'hint-a')) { - notifiedPeer = snapshot.peers.find((peer: any) => peer.id === 'a'); - progressNotified.resolve(); - } - }) })); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(['pending', 'running']).toContain(initialPeerStatus); - expect(notifiedPeer).toMatchObject({ status: 'running', owner: producerId }); - const records = cooperationState().deliveries; - expect(records.find((record: any) => record.submissionId === 'hint-a')).toMatchObject({ status: 'conditional', remainingObligations: ['a'] }); - expect(records.find((record: any) => record.taskId === 'draft' && record.kind === 'research')).toMatchObject({ - status: 'conditional', dependencies: [{ taskId: 'a', taskDigest: taskVersion(tasks[0]) }], remainingObligations: ['a'] }); - expect(host.verify.mock.calls.some(([request]) => request.items.some(item => item.theoremName === 'draft'))).toBe(false); - }, 20_000); - - it('applies live versions, cancels only the affected writer, retains over 32 historical versions and archives late deliveries', async () => { - const oldStarted = deferred(), oldStopped = deferred(); - let oldWorkspace = '', oldInterrupts = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'task' && action.task.id === 'a' && action.task.revision === 0) { - oldWorkspace = options.workspace; oldStarted.resolve(); await oldStopped.promise; - finishAssignment(action, options); return 'completed'; - } - if (action.kind === 'task' && action.task.id === 'b') { - await oldStarted.promise; - const state = cooperationState(); let baseVersion = state.planVersion; - const groups = state.groups.map((route: any) => route.group); - const edits = Array.from({ length: 35 }, (_, index) => { - const tasks = planTasks(); tasks[0] = { ...tasks[0], revision: index + 1 }; - const edit = { id: `revision-${index + 1}`, baseVersion, tasks, groups }; - baseVersion = mathDigest(canonicalMathJson(parseCooperationPlan(problem, edit))); - return JSON.stringify(edit); - }); - fs.appendFileSync(`${output}.runtime/edits.jsonl`, edits.join('\n') + '\n'); - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === 'revision-35' && edit.status === 'applied')).toBe(true); - } - finishAssignment(action, options); return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === oldWorkspace) { oldInterrupts++; oldStopped.resolve(); } }) })); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory)).toBe(0); - const state = cooperationState(); - expect(state.edits.filter((edit: any) => edit.status === 'applied')).toHaveLength(35); - expect(state.edits.slice(0, -1).every((edit: any) => edit.recheck.status === 'superseded')).toBe(true); - expect(state.edits.at(-1).recheck.status).toBe('passed'); - expect(state.history.filter((node: any) => node.task.id === 'a')).toHaveLength(35); - expect(state.history[0].task.revision).toBe(0); - expect(state.tasks[1]).toMatchObject({ attempts: 1, status: 'integrated' }); - expect(state.tasks[0].task.revision).toBe(35); - expect(oldInterrupts).toBe(1); - expect(state.deliveries.find((record: any) => record.status === 'superseded' && record.taskId === 'a')).toMatchObject({ - taskDigest: taskVersion(planTasks()[0]), commit: expect.stringMatching(/^[a-f0-9]{40}$/u) }); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('pauses a live task and transfers its responsibility without invalidating independent checked work', async () => { - const oldStarted = deferred(), oldStopped = deferred(); - let oldWorkspace = '', newOwner: string | undefined; - configureCooperation(async (action, options) => { - if (action.kind === 'task' && action.task.id === 'a' && action.task.ownerId === undefined) { - oldWorkspace = options.workspace; oldStarted.resolve(); await oldStopped.promise; - return 'interrupted'; - } - if (action.kind === 'task' && action.task.id === 'b') { - await oldStarted.promise; - const tasks = planTasks(); tasks[0] = { ...tasks[0], status: 'paused' }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'pause', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === 'pause' && edit.status === 'applied')).toBe(true); - await expect.poll(() => JSON.parse(fs.readFileSync(path.join(oldWorkspace, 'COOPERATION.json'), 'utf8')) - .agents.find((agent: any) => agent.id === 'researcher-1').status).toBe('idle'); - expect(cooperationState().history).toBeUndefined(); - tasks[0] = { ...tasks[0], status: 'active', ownerId: 'researcher-2' }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'transfer', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === 'transfer' && edit.status === 'applied')).toBe(true); - } - if (action.kind === 'task' && action.task.id === 'a') newOwner = action.assignment.workerId; - finishAssignment(action, options); return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === oldWorkspace) oldStopped.resolve(); }) })); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory)).toBe(0); - expect(newOwner).toBe('researcher-2'); - expect(cooperationState().tasks[1]).toMatchObject({ status: 'integrated', attempts: 1 }); - expect(cooperationState().history).toBeUndefined(); - expect(cooperationState().edits.map((edit: any) => edit.recheck.status)).toEqual(['not-required', 'not-required']); - }, 20_000); - - it('discards a review invalidated by a live edit and independently reviews the replacement version', async () => { - const reviewStopped = deferred(); - let reviews = 0, reviewerWorkspace = ''; - configureCooperation(async (action, options) => { - if (action.kind === 'review' && ++reviews === 1) { - reviewerWorkspace = options.workspace; - const tasks = reviewedPlanTasks(); tasks[0] = { ...tasks[0], revision: 1 }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'during-review', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await reviewStopped.promise; - } - if (action.kind === 'lead') writePlan(options.workspace, reviewedPlanTasks()); - else finishAssignment(action, options); - return 'completed'; - }); - const create = host.createSession.getMockImplementation()!; - host.createSession.mockImplementation(async (options: MathAgentOptions) => ({ ...await create(options), - interrupt: vi.fn(async () => { if (options.workspace === reviewerWorkspace) reviewStopped.resolve(); }) })); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '12'], directory)).toBe(0); - expect(reviews).toBe(2); - const records = cooperationState().deliveries.filter((record: any) => record.kind === 'review'); - expect(records.map((record: any) => record.status)).toEqual(['superseded', 'accepted']); - expect(records[0].commit).not.toBe(records[1].commit); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('counts an early proof producer until its turn ends when enforcing route concurrency', async () => { - let helperTurns = 0; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, planTasks(), [{ id: 'main', objective: 'One proof worker at a time', revision: 0, status: 'active', maxConcurrent: 1 }]); - else if (action.kind === 'task' && action.task.id === 'a') { - helperTurns++; finishAssignment(action, options); - const commit = commitSolverSources(problem, options.workspace); - appendDelivery(options, action, { id: 'bounded-early-proof', kind: 'proof', summary: 'Proof ready; still writing notes', commit }); - await expect.poll(() => cooperationState().tasks[0].status).toBe('integrated'); - expect(cooperationState().groups[0].busy).toBe(1); - expect(helperTurns).toBe(1); - } else { - if (action.kind === 'task' && action.task.id === 'b') helperTurns++; - finishAssignment(action, options); - } - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(helperTurns).toBe(2); - }, 20_000); - - it('rejects stale and cyclic human edits without stopping independent proof work', async () => { - configureCooperation(async (action, options) => { - if (action.kind === 'task' && action.task.id === 'a') { - const state = cooperationState(), tasks = planTasks(); tasks[0] = { ...tasks[0], dependsOn: ['first'] }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, [ - { id: 'stale', baseVersion: 'old-version', tasks: planTasks() }, - { id: 'cycle', baseVersion: state.planVersion, tasks }, - ].map(edit => JSON.stringify(edit)).join('\n') + '\n'); - await expect.poll(() => cooperationState().edits?.length).toBe(2); - } - finishAssignment(action, options); return 'completed'; - }); - expect(await runSolver([...args, '--workers', '4', '--max-turns', '6'], directory)).toBe(0); - expect(cooperationState().edits).toMatchObject([ - { id: 'stale', status: 'rejected', reason: 'math_edit_version_conflict' }, - { id: 'cycle', status: 'rejected', reason: expect.stringMatching(/^math_plan_dependency_cycle: /u) }, - ]); - for (const edit of cooperationState().edits) { - expect(edit.receivedAt).toEqual(expect.any(Number)); expect(edit.recheck).toBeUndefined(); - } - expect(cooperationState().history).toBeUndefined(); - }, 20_000); - - it('revalidates an applied edit on resume and reports a failed Lean receipt instead of the archived success', async () => { - const tasks = waitingPlanTasks(); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'a' && action.task.revision === 0) { - tasks[0] = { ...tasks[0], revision: 1 }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'rechecked-edit', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.[0]?.status).toBe('applied'); - finishAssignment(action, options); - } else finishAssignment(action, options); - return 'completed'; - }); - const parallelArgs = [...args, '--workers', '2', '--max-turns', '4']; - expect(await runSolver(parallelArgs, directory)).toBe(4); - const before = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - const check = before.cooperation.edits[0].recheck.tasks.find((result: any) => result.taskId === 'a'); - expect(check).toMatchObject({ status: 'passed', lastCheck: { passed: true } }); - const file = path.join(before.worktree, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('lemma a : True := by trivial', 'lemma a : True := by sorry')); - expect(await runSolver([...parallelArgs, '--resume', '--max-turns', '5'], directory)).toBe(4); - const resumed = cooperationState(), failed = resumed.edits[0].recheck.tasks.find((result: any) => result.taskId === 'a'); - expect(resumed.edits[0]).toMatchObject({ status: 'applied', recheck: { status: 'failed' } }); - expect(failed).toMatchObject({ status: 'failed', lastCheck: { passed: false, conditional: false } }); - expect(failed.lastCheck.commit).not.toBe(check.lastCheck.commit); - expect(failed.lastCheck.receiptIds).toEqual(resumed.tasks[0].integratedCheck.verification.results.map((receipt: any) => receipt.receiptId)); - expect(resumed.tasks[1].status).toBe('integrated'); expect(host.officialGate).not.toHaveBeenCalled(); - }, 20_000); - - it('finishes a durably received edit on resume and applies repeated delivery of its id only once', async () => { - configureCooperation(); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '1'], directory)).toBe(4); - const file = `${output}.runtime/state.json`, state = JSON.parse(fs.readFileSync(file, 'utf8')); - const tasks = planTasks(); tasks[0] = { ...tasks[0], revision: 1 }; - const edit = { id: 'received-before-stop', baseVersion: state.cooperation.planVersion, tasks }; - state.cooperation.edits = [{ id: edit.id, baseVersion: edit.baseVersion, status: 'received', receivedAt: 100 }]; - fs.writeFileSync(file, JSON.stringify(state)); - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify(edit) + '\n' + JSON.stringify(edit) + '\n'); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '9', '--resume'], directory)).toBe(0); - const resumed = cooperationState(); - expect(resumed.edits).toHaveLength(1); - expect(resumed.edits[0]).toMatchObject({ id: edit.id, status: 'applied', receivedAt: 100, recheck: { status: 'passed' } }); - expect(resumed.history.filter((node: any) => node.task.id === 'a')).toHaveLength(1); - const events = vi.mocked(console.log).mock.calls.map(([event]) => JSON.parse(event)); - expect(events.filter(event => event.event === 'edit_applied' && event.id === edit.id)).toHaveLength(1); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('keeps the old check receipt after another edit supersedes a completed task with unchanged consumer digests', async () => { - const tasks = planTasks(); let oldCheck: any; - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'a' && action.task.revision < 2) { - if (action.task.revision === 1) { - finishAssignment(action, options); - appendDelivery(options, action, { id: 'revision-one-proof', kind: 'proof', summary: 'First revised version proved', - commit: commitSolverSources(problem, options.workspace) }); - await expect.poll(() => cooperationState().edits[0].recheck.tasks[0].status).toBe('passed'); - oldCheck = cooperationState().edits[0].recheck.tasks[0].lastCheck; - } - tasks[0] = { ...tasks[0], revision: action.task.revision + 1 }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: `edit-${tasks[0].revision}`, baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === `edit-${tasks[0].revision}` && edit.status === 'applied')).toBe(true); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '9'], directory)).toBe(0); - const edits = cooperationState().edits; - expect(edits[0].recheck.status).toBe('superseded'); - expect(edits[0].recheck.tasks[0]).toMatchObject({ status: 'superseded', lastCheck: oldCheck }); - expect(edits[0].recheck.tasks[1]).toMatchObject({ taskDigest: taskVersion(tasks[2]), status: 'superseded' }); - expect(edits[1].recheck.status).toBe('passed'); - expect(edits[1].recheck.tasks[0].taskDigest).not.toBe(edits[0].recheck.tasks[0].taskDigest); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('includes added formal tasks and removed task versions in an edit without checking a removed obligation', async () => { - const tasks = planTasks(), removedDigest = taskVersion(tasks[1]); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') writePlan(options.workspace, tasks); - else if (action.kind === 'task' && action.task.id === 'a') { - tasks[1] = { ...tasks[1], id: 'c', theoremName: 'Submission.c' }; - tasks[2] = { ...tasks[2], dependsOn: ['a', 'c'] }; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'replace-helper', baseVersion: cooperationState().planVersion, tasks }) + '\n'); - await expect.poll(() => cooperationState().edits?.[0]?.status).toBe('applied'); - const recheck = cooperationState().edits[0].recheck; - expect(recheck.tasks.find((result: any) => result.taskId === 'b')).toEqual({ taskId: 'b', taskDigest: removedDigest, status: 'removed' }); - expect(recheck.tasks.find((result: any) => result.taskId === 'c')).toMatchObject({ taskDigest: taskVersion(tasks[1]), status: 'pending' }); - finishAssignment(action, options); - } else if (action.kind === 'task' && action.task.id === 'first') { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact a')); - } else finishAssignment(action, options); - return 'completed'; - }); - expect(await runSolver([...args, '--workers', '2', '--max-turns', '7'], directory)).toBe(0); - expect(cooperationState().edits[0]).toMatchObject({ affectedTasks: ['b', 'first', 'second', 'c'], recheck: { status: 'passed' } }); - expect(host.verify.mock.calls.some(([request]) => request.items.some(item => item.theoremName === 'Submission.b'))).toBe(false); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - it('reads appended delivery lines without consuming a partial write or replaying a saved cursor', () => { const file = path.join(directory, 'deliveries.jsonl'); fs.writeFileSync(file, '{"id":"one"}\n{"id":'); @@ -6608,60 +2519,6 @@ describe('isolated solver and host acceptance', () => { expect(readDeliveryLines(file, second.offset).entries).toMatchObject([{ error: 'math_delivery_log_rewritten', offset: 0 }]); }); - it('checks two independent early deliveries concurrently while both producers are still running', async () => { - const entered = new Set(); - const both = deferred(); - const checkTask = async (...input: Parameters) => { - const task = input[3]; - if (['a', 'b'].includes(task.id) && input[1] !== path.join(`${output}.runtime`, 'worktree')) { - entered.add(task.id); if (entered.size === 2) both.resolve(); await both.promise; - } - return checkTaskProof(...input); - }; - configureCooperation(async (action, options) => { - finishAssignment(action, options); - if (action.kind === 'task' && ['a', 'b'].includes(action.task.id)) { - const commit = commitSolverSources(problem, options.workspace); - fs.appendFileSync(path.join(options.workspace, assignmentDeliveryFile(action.assignment)), JSON.stringify({ kind: 'proof', commit }) + '\n'); - await expect.poll(() => cooperationState().tasks.filter((node: any) => ['a', 'b'].includes(node.task.id)) - .every((node: any) => node.status === 'integrated')).toBe(true); - } - return 'completed'; - }); - try { - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory, - { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(0); - expect(entered.size).toBe(2); - } finally { both.resolve(); } - }, 30_000); - - it('continues polling human edits while an early proof check is waiting', async () => { - const checking = deferred(), resume = deferred(); - const checkTask = async (...input: Parameters) => { - if (input[3].id === 'a' && input[1] !== path.join(`${output}.runtime`, 'worktree')) { - checking.resolve(); await resume.promise; - } - return checkTaskProof(...input); - }; - configureCooperation(async (action, options) => { - finishAssignment(action, options); - if (action.kind === 'task' && action.task.id === 'a') { - const commit = commitSolverSources(problem, options.workspace); - appendDelivery(options, action, { id: 'waiting-proof', kind: 'proof', commit, summary: 'Ready' }); - await checking.promise; - fs.appendFileSync(`${output}.runtime/edits.jsonl`, JSON.stringify({ id: 'during-check', baseVersion: 'stale' }) + '\n'); - try { - await expect.poll(() => cooperationState().edits?.find((edit: any) => edit.id === 'during-check')?.status).toBe('rejected'); - } finally { resume.resolve(); } - } - return 'completed'; - }); - try { - expect(await runSolver([...args, '--workers', '4', '--max-turns', '8'], directory, - { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } })).toBe(0); - } finally { resume.resolve(); } - }, 30_000); - it('keeps search stopping decisions separate from proof acceptance', async () => { const select = vi.fn((...inputs: Parameters) => { expect(inputs[2]).toMatchObject({ maxTurns: 1, aborted: false }); @@ -6734,68 +2591,6 @@ describe('isolated solver and host acceptance', () => { expect(vi.getTimerCount()).toBe(0); }); - it('keeps a pending human plan alive beyond its execution allowance and accepts the original run after approval', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - let cooperative: CooperativeResearch | undefined; - const activate = CooperativeResearch.prototype.activate; - vi.spyOn(CooperativeResearch.prototype, 'activate').mockImplementation(function (this: CooperativeResearch, ...inputs) { - cooperative = this; return activate.apply(this, inputs); - }); - const waiting = deferred(); - vi.mocked(console.log).mockImplementation(line => { - if (typeof line === 'string' && JSON.parse(line).event === 'plan_approval_wait_started') waiting.resolve(); - }); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') await vi.advanceTimersByTimeAsync(200); - finishAssignment(action, options); return 'completed'; - }); - const completion = runSolver([...args, '--workers', '4', '--max-turns', '10', '--max-run-seconds', '1', '--plan-approval'], directory); - await Promise.race([waiting.promise, completion.then(code => { throw new Error(`fixture_finished_before_approval:${code}`); })]); - const stateFile = `${output}.runtime/state.json`, pending = readSolverRunState(stateFile); - expect(pending.cooperation!.planApproval!.approvedAt).toBeUndefined(); - await vi.advanceTimersByTimeAsync(600_000); - expect(fs.existsSync(output)).toBe(false); - expect(host.officialGate).not.toHaveBeenCalled(); - fs.appendFileSync(planApprovalLog(stateFile), JSON.stringify({ id: 'owner', planVersion: pending.cooperation!.planVersion }) + '\n'); - await cooperative!.pulse(); - expect(await completion).toBe(0); - const result = JSON.parse(fs.readFileSync(output, 'utf8')); - expect(result).toMatchObject({ runId: pending.runId, status: 'evaluated_passed', solveExecutionMs: 200, - solveWaitingMs: 600_000, solveWallMs: 600_200 }); - const accepted = readSolverRunState(stateFile); - expect(accepted.problem.receiptDigest).toBe(pending.problem.receiptDigest); - expect(accepted.cooperation!.planApproval).toMatchObject({ approvedId: 'owner' }); - expect(accepted.solveWaitingMs).toBe(600_000); - expect(host.officialGate).toHaveBeenCalledOnce(); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['SIGINT', 'SIGTERM'] as const)('still stops a human approval wait on %s and preserves its checkpoint', async interrupt => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - const waiting = deferred(); - vi.mocked(console.log).mockImplementation(line => { - if (typeof line === 'string' && JSON.parse(line).event === 'plan_approval_wait_started') waiting.resolve(); - }); - configureCooperation(async (action, options) => { - if (action.kind === 'lead') await vi.advanceTimersByTimeAsync(200); - finishAssignment(action, options); return 'completed'; - }); - const completion = runSolver([...args, '--workers', '4', '--max-turns', '10', '--max-run-seconds', '1', '--plan-approval'], directory); - await Promise.race([waiting.promise, completion.then(code => { throw new Error(`fixture_finished_before_approval:${code}`); })]); - const stateFile = `${output}.runtime/state.json`, pending = readSolverRunState(stateFile); - await vi.advanceTimersByTimeAsync(600_000); - process.emit(interrupt); - expect(await completion).toBe(4); - expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ runId: pending.runId, - status: 'limit_reached', reason: 'math_run_stopped', solveExecutionMs: 200, solveWaitingMs: 600_000 }); - expect(readSolverRunState(stateFile)).toMatchObject({ runId: pending.runId, phase: 'finished', - cooperation: { planApproval: { requestedVersion: pending.cooperation!.planVersion } } }); - expect(host.officialGate).not.toHaveBeenCalled(); - expect(vi.getTimerCount()).toBe(0); - }); - it.each([1, 300, 3_000_000])('applies a finite %s-second evaluator budget to the integrated Lean recheck', async seconds => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); host.officialGate.mockImplementation(async ({ signal }) => { @@ -7280,68 +3075,6 @@ describe('isolated solver and host acceptance', () => { expect(console.log).toHaveBeenCalledWith(expect.stringContaining('No manifest-compatible Lake package cache')); }); - it('repairs stale package links for every worker on resume before checking dependencies', async () => { - host.packages = path.join(directory, 'pinned-packages'); - fs.mkdirSync(host.packages); - const startup = [...args, '--workers', '4', '--startup-only']; - expect(await runSolver(startup, directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - const obsolete = path.join(directory, 'obsolete-packages'); - fs.mkdirSync(obsolete); - for (const [index, worker] of state.workers.entries()) { - const packages = path.join(worker.worktree, 'generated/p/.lake/packages'); - fs.unlinkSync(packages); - fs.symlinkSync(index % 2 ? obsolete : path.join(directory, 'deleted-packages'), packages, 'dir'); - } - const peers = new Set(), ready = deferred(); - host.prepare.mockClear().mockImplementation(async input => { - expect(fs.realpathSync(path.join(input.projectRoot, '.lake/packages'))).toBe(host.packages); - if (input.projectRoot !== path.join(state.worktree, problem.projectRelative)) { - peers.add(input.projectRoot); - if (peers.size === 3) ready.resolve(); - await ready.promise; - } - return { exitCode: 0, timedOut: false, phases: [] }; - }); - expect(await runSolver([...startup, '--resume'], directory)).toBe(0); - expect(host.prepare).toHaveBeenCalledTimes(4); - expect(peers.size).toBe(3); - expect(host.freeze.mock.calls.at(-1)![2].deadlineAt).toBeGreaterThan(Date.now()); - expect(host.createSession).not.toHaveBeenCalled(); - }); - - it('reuses every worker read-only corpus on resume and rejects changed copies', async () => { - host.packages = path.join(directory, 'packages'); - const library = path.join(host.packages, 'mathlib/Mathlib/Algebra/Basic.lean'); - fs.mkdirSync(path.dirname(library), { recursive: true }); - fs.writeFileSync(library, 'lemma library_helper : True := by trivial\n'); - fs.writeFileSync(path.join(host.packages, 'mathlib/lakefile.toml'), 'name = "mathlib"\n'); - fs.writeFileSync(path.join(project, 'lake-manifest.json'), JSON.stringify({ packages: [ - { name: 'mathlib', rev: 'a'.repeat(40), url: 'https://github.com/leanprover-community/mathlib4' }, - ] })); - git(workspace, ['add', '--', 'generated/p/lake-manifest.json']); - commitFixture(workspace, 'Pinned library'); - const startup = [...args, '--workers', '4', '--startup-only']; - expect(await runSolver(startup, directory)).toBe(0); - const state = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - const files = state.workers.slice(1).map(worker => path.join(worker.worktree, 'generated/p/.lake/retrieval-corpus.json')); - const snapshots = files.map(file => ({ bytes: fs.readFileSync(file), stat: fs.statSync(file) })); - const writes = vi.spyOn(fs, 'writeFileSync'); - expect(await runSolver([...startup, '--resume'], directory)).toBe(0); - for (const [index, file] of files.entries()) { - expect(fs.readFileSync(file)).toEqual(snapshots[index].bytes); - expect(fs.statSync(file)).toMatchObject({ ino: snapshots[index].stat.ino, mtimeMs: snapshots[index].stat.mtimeMs }); - expect(fs.statSync(file).mode & 0o777).toBe(0o400); - expect(writes.mock.calls.some(call => call[0] === file)).toBe(false); - } - fs.chmodSync(files[1], 0o600); - fs.appendFileSync(files[1], '\n'); - fs.chmodSync(files[1], 0o400); - expect(await runSolver([...startup, '--resume'], directory)).toBe(1); - expect(JSON.parse(fs.readFileSync(output, 'utf8')).reason).toBe('math_corpus_identity_changed'); - expect(host.createSession).not.toHaveBeenCalled(); - }); - it('checks a timed checkpoint and resumes with host diagnostics', async () => { host.verify.mockImplementationOnce(async request => failed(verified(request), { stdoutPreview: 'Submission.lean:4:1: error: unsolved goals' })); const messages: string[] = []; @@ -7629,235 +3362,4 @@ describe('isolated solver and host acceptance', () => { expect(fs.readFileSync(output, 'utf8')).toBe(receipt); }); - it('roundtrips alternative proof routes through human export, queued edit, resume and canonical checks', async () => { - const bridge: CooperativeTask = { id: 'bridge', kind: 'lemma', objective: 'Close the B route', dependsOn: ['b'], - proofPath: 'Submission.lean', theoremName: 'Submission.bridge', type: 'True → True', revision: 0 }; - const tasks = [ - { ...planTasks()[0], status: 'paused' as const }, planTasks()[1], bridge, - { ...planTasks()[2], dependsOn: [] }, planTasks()[3], - ]; - const proofRoutes = [ - { id: 'route_a', targetTaskId: 'first', prerequisiteTaskIds: [], closingTaskId: 'a' }, - { id: 'route_b', targetTaskId: 'first', prerequisiteTaskIds: ['b'], closingTaskId: 'bridge' }, - ]; - let currentProofRoutes = proofRoutes; - const goalAssignments: Extract[] = []; - configureCooperation(async (action, options, message) => { - const file = path.join(options.workspace, 'generated/p/Submission.lean'); - if (action.kind === 'lead') fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), - '```math-plan\n' + JSON.stringify({ tasks, proofRoutes: currentProofRoutes }) + '\n```\n'); - else if (action.kind === 'task' && action.task.id === 'bridge') { - expect(action.assignment.dependencies).toEqual([{ taskId: 'b', taskDigest: taskVersion(tasks[1]) }]); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', - 'lemma bridge : True → True := by intro _; exact b\ntheorem first')); - } else if (action.kind === 'task' && action.task.id === 'first') { - // A queued edit may arrive after a resumed worker has reserved its old - // assignment. Let the host cancel that version before exercising B again. - if (action.assignment.routeId === 'route_b') { - await expect.poll(() => cooperationState().edits?.some((edit: any) => edit.id === 'route_roundtrip' && edit.status === 'applied')).toBe(true); - return 'interrupted'; - } - goalAssignments.push(action); - expect(action.task.dependsOn).toEqual([]); - expect(action.assignment.routeId).toBe('preferred_b'); - expect(action.assignment.dependencies).toEqual([ - { taskId: 'b', taskDigest: taskVersion(tasks[1]) }, { taskId: 'bridge', taskDigest: taskVersion(bridge) }, - ]); - expect(message).toContain('Submission.bridge'); - expect(message).toContain('True → True'); - expect(fs.readFileSync(file, 'utf8')).toContain('lemma bridge : True → True'); - expect(host.officialGate).not.toHaveBeenCalled(); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('first : True := by sorry', 'first : True := by exact bridge b')); - } else finishAssignment(action, options); - return 'completed'; - }); - configureReferenceReports({ bridge: ['b'], first: ['bridge', 'b'], second: ['first', 'bridge', 'b'] }); - const parallelArgs = [...args, '--workers', '4', '--max-turns', '3']; - const initialExit = await runSolver(parallelArgs, directory); - expect(initialExit, fs.readFileSync(output, 'utf8')).toBe(4); - const before = JSON.parse(fs.readFileSync(`${output}.runtime/state.json`, 'utf8')); - expect(before.cooperation.tasks.filter((item: any) => item.task.kind === 'goal').map((item: any) => item.status)) - .toEqual(['pending', 'pending']); - expect(before.cooperation.tasks.filter((item: any) => ['b', 'bridge'].includes(item.task.id)).map((item: any) => item.status)) - .toEqual(['integrated', 'integrated']); - expect(before.cooperation.error).toBeUndefined(); - expect(before.check).toBeUndefined(); expect(goalAssignments).toHaveLength(0); - expect(host.officialGate).not.toHaveBeenCalled(); - const { exportRunPlan } = await import('../src/solver/inspection'); - const { queueRunEdit } = await import('../src/solver/humanEdit'); - const exported = exportRunPlan(before); - expect(exported.proofRoutes).toEqual(proofRoutes); - const revisedRoutes = proofRoutes.map(route => route.id === 'route_b' ? { ...route, id: 'preferred_b' } : route); - expect(await queueRunEdit(output, { ...exported, id: 'route_roundtrip', proofRoutes: revisedRoutes })).toMatchObject({ status: 'queued' }); - currentProofRoutes = revisedRoutes; - const checksBeforeResume = host.verify.mock.calls.length; - const resumedExit = await runSolver([...parallelArgs, '--resume', '--max-turns', '8'], directory); - expect(resumedExit, fs.readFileSync(output, 'utf8')).toBe(0); - const after = cooperationState(); - expect(after.proofRoutes).toEqual(revisedRoutes); - expect(after.edits.find((edit: any) => edit.id === 'route_roundtrip')).toMatchObject({ status: 'applied' }); - expect(goalAssignments).toHaveLength(1); - const original = after.tasks.find((item: any) => item.task.id === 'first'); - expect(original.alternativeRoutes).toEqual(revisedRoutes); - expect(original.integratedCheck.references.tasks).toEqual(expect.arrayContaining([ - { taskId: 'bridge', taskDigest: taskVersion(bridge) }, { taskId: 'b', taskDigest: taskVersion(tasks[1]) }, - ])); - expect(original.integratedCheck.references.proof).toContainEqual({ name: 'Submission.bridge', file: 'Submission.lean' }); - const delivery = after.deliveries.find((item: any) => item.taskId === 'first' && item.status === 'verified'); - expect(delivery.dependencies).toEqual(goalAssignments[0].assignment.dependencies); - for (const receipt of original.integratedCheck.verification.results) - expect(receipt.targetCommit).toBe(original.integratedCheck.verification.targetCommit); - expect(host.verify.mock.calls[checksBeforeResume][0].items.map((item: any) => item.theoremName)).toContain('Submission.b'); - expect(host.officialGate).toHaveBeenCalledOnce(); - }, 20_000); - - it('reassigns a pending A draft to fresh B inputs while preserving the committed draft and notes', async () => { - configureCooperation(); configureReferenceReports({ closing_b: ['b'] }); - const { markTaskAcceptance } = await import('../src/solver/tasks'); - const source = original.replace('theorem first', 'lemma a : True := by sorry\nlemma b : True := by trivial\n' + - 'lemma closing_a : True → True := by intro _; exact a\n' + - 'lemma closing_b : True → True := by intro _; exact b\ntheorem first'); - fs.writeFileSync(path.join(project, 'Submission.lean'), source); - const canonical = commitSolverSources(problem, workspace); - const tasks: CooperativeTask[] = [planTasks()[0], planTasks()[1], ...['a', 'b'].map(id => ({ - id: `closing_${id}`, kind: 'lemma' as const, objective: `Close route ${id}`, dependsOn: [id], revision: 0, - proofPath: 'Submission.lean', theoremName: `Submission.closing_${id}`, type: 'True → True', - })), { ...planTasks()[2], dependsOn: [] }, { ...planTasks()[3], status: 'paused' }]; - const proofRoutes = ['a', 'b'].map(id => ({ id: `route_${id}`, targetTaskId: 'first', prerequisiteTaskIds: [id], closingTaskId: `closing_${id}` })); - const plan = parseCooperationPlan(problem, { tasks, proofRoutes }); - const records: any[] = plan.tasks.map(task => ({ task, status: ['a', 'closing_a'].includes(task.id) ? 'blocked' : 'pending', attempts: 1 })); - for (const id of ['b', 'closing_b']) { - const node = records.find(item => item.task.id === id); - const assignment = { taskId: id, taskDigest: taskVersion(node.task), workerId: 'researcher-1', seedCommit: canonical }; - const proof = await checkTaskProof(problem, workspace, canonical, node.task, assignment, [], {}, new AbortController().signal, Infinity, [], 'fixture'); - expect(proof.passed).toBe(true); - proof.references!.tasks = id === 'b' ? [] : [{ taskId: 'b', taskDigest: taskVersion(records[1].task) }]; - markTaskAcceptance(proof); node.status = 'integrated'; node.integratedCheck = proof; - } - await withSolverWorktree(workspace, canonical, async peerRoot => { - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peer = { id: 'researcher-1', role: 'researcher', worktree: peerRoot, ownedFiles: problem.ownedFiles } as const; - const file = path.join(peerRoot, 'generated/p/Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem first', 'lemma saved_a_support : True := by trivial\ntheorem first')); - fs.writeFileSync(path.join(peerRoot, 'RESEARCH.md'), 'Saved A draft: the missing inference remains open.'); - const draftCommit = commitSolverSources(problem, peerRoot); - const root = records.find(item => item.task.id === 'first'); - const previousAssignment = root.assignment = { taskId: 'first', taskDigest: taskVersion(root.task), workerId: peer.id, - seedCommit: canonical, canonicalCommit: canonical, routeId: 'route_a', dependencies: ['a', 'closing_a'].map(id => ({ - taskId: id, taskDigest: taskVersion(records.find(item => item.task.id === id).task), - })) }; - const state: any = { problem, runId: 'resumed-route-choice', turns: 0, phase: 'running', environmentDigest: 'fixture', - workers: [lead, peer].map(worker => ({ ...worker, turns: 0, failures: [] })), cooperation: { - tasks: records, groups: plan.groups.map(group => ({ group, turns: 0 })), proofRoutes, canonicalCommit: canonical, - } }; - const cooperative = new CooperativeResearch({ state, workers: [lead, peer], access: new Map(), signal: new AbortController().signal, - save: () => {}, emit: () => {}, modules: directSolverModules, exclusiveCheck: async check => check() }); - const action = await cooperative.next(peer, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind).toBe('task'); - if (action?.kind !== 'task') throw new Error('missing_replacement_assignment'); - expect(action.assignment).not.toBe(previousAssignment); - expect(action.assignment.routeId).toBe('route_b'); - expect(action.assignment.canonicalCommit).toBe(canonical); - expect(action.assignment.dependencies).toEqual(['b', 'closing_b'].map(id => ({ - taskId: id, taskDigest: taskVersion(records.find(item => item.task.id === id).task), - }))); - expect(fs.readFileSync(file, 'utf8')).toContain('lemma closing_b : True → True'); - expect(fs.readFileSync(path.join(peerRoot, 'RESEARCH.md'), 'utf8')).toContain('Saved A draft'); - expect(git(peerRoot, ['show', `${draftCommit}:generated/p/Submission.lean`])).toContain('lemma saved_a_support : True'); - expect(git(peerRoot, ['merge-base', '--is-ancestor', draftCommit, 'HEAD'])).toBe(''); - expect(cooperative.current(action)).toBe(true); - expect(host.createSession).not.toHaveBeenCalled(); expect(host.officialGate).not.toHaveBeenCalled(); - cooperative.interrupted(peer, action); await cooperative.stop(); - }); - }, 20_000); - - it('parks repeated local blockers across a revision, isolates groups and reopens after a fresh dependency check', async () => { - configureCooperation(); - const { routeAllowsTask } = await import('../src/solver/modules/search'); - const groups = [{ id: 'main', objective: 'Main route' }, { id: 'private', objective: 'Independent route' }]; - const tasks: CooperativeTask[] = [ - { id: 'root_research', kind: 'research', objective: 'Find the missing inference', dependsOn: ['b'], revision: 0, ownerId: 'researcher-1' }, - { ...planTasks()[1], status: 'paused' }, - ...planTasks().slice(2).map(task => ({ ...task, dependsOn: [], status: 'paused' as const })), - { id: 'private_research', kind: 'research', objective: 'PRIVATE_INFERENCE', dependsOn: [], revision: 0, - groupId: 'private', sharing: 'group', ownerId: 'researcher-2' }, - ]; - const plan = parseCooperationPlan(problem, { tasks, groups }); - await withSolverWorktree(workspace, problem.baseCommit, async peerRoot => { - await withSolverWorktree(workspace, problem.baseCommit, async privateRoot => { - const lead = { id: 'solver', role: 'lead', worktree: workspace, ownedFiles: problem.ownedFiles } as const; - const peer = { id: 'researcher-1', role: 'researcher', worktree: peerRoot, ownedFiles: problem.ownedFiles } as const; - const other = { id: 'researcher-2', role: 'researcher', worktree: privateRoot, ownedFiles: problem.ownedFiles } as const; - const state: any = { problem, runId: 'blocker-lifecycle', turns: 0, phase: 'running', environmentDigest: 'fixture', - workers: [lead, peer, other].map(worker => ({ ...worker, turns: 0, failures: [] })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }; - const events: { event: string; [key: string]: unknown }[] = []; - const cooperative = new CooperativeResearch({ state, workers: [lead, peer, other], - access: new Map([[lead.id, { environment: {}, retrievalRoot: workspace }]]), signal: new AbortController().signal, - save: () => {}, emit: (event, details) => events.push({ event, ...details }), modules: directSolverModules, - exclusiveCheck: async check => check() }); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const first = await cooperative.next(peer, budget); - expect(first?.kind).toBe('task'); - if (first?.kind !== 'task') throw new Error('missing_root_assignment'); - cooperative.activate(peer, first, async () => {}, async () => {}); - const report = (action: Extract, worktree: string, id: string, mechanism: string) => - fs.appendFileSync(path.join(worktree, assignmentDeliveryFile(action.assignment)), JSON.stringify({ id, kind: 'progress', - summary: 'The local inference still needs its declared mathematical input.', blockers: [{ mechanism, - scope: 'local-inference', reopenOn: [{ kind: 'dependency-checked', taskId: 'b' }] }] }) + '\n'); - report(first, peerRoot, 'first_report', 'same-missing-bridge'); - await cooperative.pulse(peer.id); - expect(state.cooperation.blockers[0]).toMatchObject({ count: 1, status: 'open', evidenceStatus: 'advisory' }); - const blockerId = state.cooperation.blockers[0].id; - const privateAction = await cooperative.next(other, budget); - expect(privateAction?.kind).toBe('task'); - if (privateAction?.kind !== 'task') throw new Error('missing_private_assignment'); - cooperative.activate(other, privateAction, async () => {}, async () => {}); - fs.appendFileSync(path.join(privateRoot, assignmentDeliveryFile(privateAction.assignment)), JSON.stringify({ id: 'private_report', - summary: 'PRIVATE_EVIDENCE', blockers: [{ mechanism: 'PRIVATE_BLOCKER', scope: 'private-inference' }] }) + '\n'); - await cooperative.pulse(other.id); - expect(state.cooperation.blockers.find((blocker: any) => blocker.id === blockerId).count).toBe(1); - const revisedTasks = plan.tasks.map(task => task.id === first.task.id ? { ...task, revision: 1 } : task); - fs.appendFileSync(path.join(path.dirname(workspace), 'edits.jsonl'), JSON.stringify({ id: 'same_math_revision', - baseVersion: state.cooperation.planVersion, tasks: revisedTasks, groups: plan.groups }) + '\n'); - await cooperative.pulse(); cooperative.deactivate(peer); - const second = await cooperative.next(peer, budget); - expect(second?.kind).toBe('task'); - if (second?.kind !== 'task') throw new Error('missing_revised_assignment'); - expect(second.task.revision).toBe(1); - cooperative.activate(peer, second, async () => {}, async () => {}); - report(second, peerRoot, 'second_report', 'same-missing-bridge'); - await cooperative.pulse(peer.id); - const obstruction = state.cooperation.blockers.find((blocker: any) => blocker.id === blockerId); - expect(obstruction).toMatchObject({ count: 2, status: 'parked', taskDigest: taskVersion(second.task) }); - const root = state.cooperation.tasks.find((item: any) => item.task.id === second.task.id); - expect(routeAllowsTask(root.task, state.cooperation.tasks, state.cooperation.groups)).toBe(false); - expect(cooperative.contextState(privateAction).blockers?.map(blocker => blocker.mechanism)).toEqual(['PRIVATE_BLOCKER']); - expect(cooperative.contextState(second).blockers?.map(blocker => blocker.mechanism)).toEqual(['same-missing-bridge']); - expect(fs.readFileSync(path.join(peerRoot, 'COOPERATION.json'), 'utf8')).not.toContain('PRIVATE_BLOCKER'); - cooperative.interrupted(peer, second); cooperative.deactivate(peer); - const activeTasks = revisedTasks.map(task => task.id === 'b' ? { ...task, status: 'active' as const } : task); - fs.appendFileSync(path.join(path.dirname(workspace), 'edits.jsonl'), JSON.stringify({ id: 'prove_local_input', - baseVersion: state.cooperation.planVersion, tasks: activeTasks, groups: plan.groups }) + '\n'); - await cooperative.pulse(); - expect(obstruction.status).toBe('parked'); - const dependency = await cooperative.next(peer, budget); - expect(dependency?.kind === 'task' && dependency.task.id).toBe('b'); - if (dependency?.kind !== 'task') throw new Error('missing_dependency_assignment'); - cooperative.activate(peer, dependency, async () => {}, async () => {}); - finishAssignment(dependency, { workspace: peerRoot } as MathAgentOptions); - await cooperative.deliver(peer, dependency, commitSolverSources(problem, peerRoot)); - cooperative.deactivate(peer); - expect(obstruction).toMatchObject({ status: 'reopened', reopenedReason: 'dependency-checked', count: 2 }); - expect(root.routeParking).toEqual([]); - expect(routeAllowsTask(root.task, state.cooperation.tasks, state.cooperation.groups)).toBe(true); - expect(events).toContainEqual(expect.objectContaining({ event: 'route_parked', blockerId })); - expect(events).toContainEqual(expect.objectContaining({ event: 'route_reopened', blockerId })); - expect(state.cooperation.tasks.filter((item: any) => item.task.kind === 'goal').every((item: any) => item.status === 'pending')).toBe(true); - expect(host.officialGate).not.toHaveBeenCalled(); - cooperative.interrupted(other, privateAction); cooperative.deactivate(other); await cooperative.stop(); - }); - }); - }, 20_000); }); diff --git a/tests/solverAdvisoryPriority.test.ts b/tests/solverAdvisoryPriority.test.ts deleted file mode 100644 index a292e90a..00000000 --- a/tests/solverAdvisoryPriority.test.ts +++ /dev/null @@ -1,312 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import type { SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import { parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -type TaskAction = Extract; - -describe('advisory turns yielding to executable proof work', () => { - let directory: string, problem: SolverProblem, state: SolverRunState; - let lead: ResearchWorker, peer: ResearchWorker, engineer: ResearchWorker; - let cooperative: CooperativeResearch, controller: AbortController, action: TaskAction; - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - const refresh = () => (cooperative as any).changed(); - const publishTypedWork = () => { - node('checked_bridge').task = { ...node('checked_bridge').task, status: 'active' }; refresh(); - }; - const shouldYield = () => Boolean(cooperative.proofHandoffTarget(engineer, action)); - - beforeEach(async () => { - const example = localExample('solver-advisory-priority-', 'lead'); - ({ directory, problem } = example); - lead = leadWorker(problem, example.workspace); - peer = peerWorker(example, 'researcher-1'); engineer = peerWorker(example, 'engineer', { role: 'engineer' }); - const workers = [lead, peer, engineer]; - const plan = parseCooperationPlan(problem, { tasks: [ - { id: 'bridge_audit', kind: 'research', reviewScope: 'feasibility', ownerId: engineer.id, - objective: 'Check the exact library interface and retain the verified construction for its proof consumer.' }, - { id: 'checked_bridge', kind: 'lemma', status: 'paused', ownerId: engineer.id, type: 'True', - proofPath: 'Submission.lean', theoremName: 'Tutorial.checked_bridge', - objective: 'Integrate the exact helper produced by the library audit.' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', ownerId: peer.id, - objective: `Prove ${target.theoremName}.`, theoremName: target.theoremName, - proofPath: target.proofPath, dependsOn: ['checked_bridge'] })), - ], groups: [{ id: 'main', objective: 'Close the original goals.', engineerId: peer.id, maxConcurrent: 1 }] }); - state = solverState(problem, example.workspace, { runId: 'advisory-priority-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - continuousResearch: true }); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - const assigned = await cooperative.next(engineer, budget); - if (assigned?.kind !== 'task') throw new Error('fixture_expected_audit'); - action = assigned; - expect(action.task.id).toBe('bridge_audit'); - expect(cooperative.started(engineer, action)).toBe(true); - cooperative.activate(engineer, action, async () => {}, async () => {}); - }); - afterEach(async () => { - controller?.abort(); await cooperative?.stop(); - vi.useRealTimers(); - vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('yields an independent feasibility review when its assigned proof work becomes executable, even in a full group', () => { - expect(shouldYield()).toBe(false); - publishTypedWork(); - expect(state.cooperation!.groups![0].busy).toBe(1); - const before = JSON.stringify(state.cooperation); - expect(shouldYield()).toBe(true); - expect(JSON.stringify(state.cooperation)).toBe(before); - expect(cooperative.current(action)).toBe(true); - }); - - it.each(['research', 'sketch'] as const)('also yields a running %s task without changing its responsibility', kind => { - const current = node(action.task.id); - current.task = { ...current.task, kind, reviewScope: undefined }; - // Refresh this fixture's current dispatch rather than simulating a stale publication. - action = { ...action, task: current.task }; - current.assignment!.taskDigest = taskVersion(current.task); - publishTypedWork(); - expect(shouldYield()).toBe(true); - }); - - it.each(['owner', 'saved-assignment'] as const)('does not release a review for typed work pinned to another peer by %s', pin => { - const helper = node('checked_bridge'); - if (pin === 'owner') helper.task = { ...helper.task, ownerId: peer.id }; - else { - helper.task = { ...helper.task, ownerId: undefined }; - helper.assignment = { taskId: helper.task.id, taskDigest: taskVersion(helper.task), workerId: peer.id, - seedCommit: problem.baseCommit, assignmentId: 'other-peer-saved-proof' }; - } - publishTypedWork(); - if (helper.assignment) helper.assignment.taskDigest = taskVersion(helper.task); - expect(shouldYield()).toBe(false); - }); - - it('waits for actual advisory prerequisites and host preparation before yielding', () => { - const helper = node('checked_bridge'); - helper.task = { ...helper.task, dependsOn: ['bridge_audit'] }; publishTypedWork(); - expect(shouldYield()).toBe(false); - helper.task = { ...helper.task, dependsOn: [] }; - (cooperative as any).preparingTaskTypes.set(helper, { workerId: engineer.id }); - expect(shouldYield()).toBe(false); - (cooperative as any).preparingTaskTypes.delete(helper); - expect(shouldYield()).toBe(true); - }); - - it.each(['M3', 'M5'] as const)('respects the configured %s when no proof dispatch is allowed', module => { - publishTypedWork(); - expect(shouldYield()).toBe(true); - const modules = (cooperative as any).input.modules; - if (module === 'M3') vi.spyOn(modules.M3, 'ready').mockReturnValue([]); - else vi.spyOn(modules.M5, 'assign').mockReturnValue(undefined); - expect(shouldYield()).toBe(false); - }); - - it('does not discount a slot held by another worker or yield an in-flight proof', () => { - publishTypedWork(); - expect(cooperative.proofHandoffTarget(peer, action)).toBeUndefined(); - const current = node(action.task.id); - current.task = { ...current.task, kind: 'lemma', reviewScope: undefined, proofPath: 'Submission.lean', - theoremName: 'Tutorial.active_proof', type: 'True' }; - current.assignment!.taskDigest = taskVersion(current.task); - action = { ...action, task: current.task }; - expect(shouldYield()).toBe(false); - }); - - it('keeps running when full dispatch would choose a higher-priority review', async () => { - publishTypedWork(); - state.cooperation!.tasks.push({ - status: 'pending', attempts: 0, - task: { ...node('bridge_audit').task, id: 'fresh_review', objective: 'Independently test the other route before formalization.' }, - }); - refresh(); - expect(shouldYield()).toBe(false); - cooperative.deactivate(engineer); - cooperative.interrupted(engineer, action); - const replacement = await cooperative.next(engineer, budget); - expect(replacement).toMatchObject({ kind: 'task', task: { id: 'fresh_review', kind: 'research' } }); - }); - - it('disables further handoffs for ten minutes after dispatch returns the worker to research', async () => { - vi.useFakeTimers(); - publishTypedWork(); - const target = cooperative.proofHandoffTarget(engineer, action); - expect(target?.taskId).toBe('checked_bridge'); - cooperative.recordProofHandoff(engineer, action.task.id, target!.taskId); - cooperative.deactivate(engineer); - cooperative.interrupted(engineer, action); - node('checked_bridge').task = { ...node('checked_bridge').task, status: 'paused' }; refresh(); - const replacement = await cooperative.next(engineer, budget); - expect(replacement).toMatchObject({ kind: 'task', task: { id: 'bridge_audit', kind: 'research' } }); - publishTypedWork(); - expect(cooperative.proofHandoffTarget(engineer, replacement!)).toBeUndefined(); - await vi.advanceTimersByTimeAsync(10 * 60_000 - 1); - expect(cooperative.proofHandoffTarget(engineer, replacement!)).toBeUndefined(); - await vi.advanceTimersByTimeAsync(1); - expect(cooperative.proofHandoffTarget(engineer, replacement!)?.taskId).toBe('checked_bridge'); - }); - - it('accounts for a statement review that would take the released slot before a proof', async () => { - publishTypedWork(); - vi.spyOn(directSolverModules.M5, 'reviewer').mockImplementation(available => available.find(worker => worker.id === engineer.id)); - const helper = node('checked_bridge'); - state.cooperation!.statementReviews = [{ - id: 'bridge-statement-review', taskId: helper.task.id, taskDigest: taskVersion(helper.task), - snapshotDigest: 'fixture-snapshot', environmentDigest: state.environmentDigest, commit: problem.baseCommit, - leanStatement: 'True', intendedStatement: 'True holds.', premises: [], dependencies: [], - workspace: engineer.worktree, files: [], status: 'pending', - }]; - expect(shouldYield()).toBe(false); - cooperative.deactivate(engineer); - cooperative.interrupted(engineer, action); - expect(await cooperative.next(engineer, budget)).toMatchObject({ kind: 'backtranslate', taskId: helper.task.id }); - }); - - it('keeps the researcher on task when an idle peer would pick up the same proof', () => { - const group = state.cooperation!.groups![0]; - group.group = { ...group.group, maxConcurrent: 2 }; - node('checked_bridge').task = { ...node('checked_bridge').task, ownerId: undefined }; - publishTypedWork(); - expect(shouldYield()).toBe(false); - group.group = { ...group.group, maxConcurrent: 1 }; refresh(); - expect(shouldYield()).toBe(true); - }); - - it('ignores an executable lemma that is outside the active proof route', () => { - for (const goal of state.cooperation!.tasks.filter(item => item.task.kind === 'goal')) - goal.task = { ...goal.task, status: 'paused' }; - publishTypedWork(); - expect(shouldYield()).toBe(false); - }); - - it('retains repeated early handoffs without parking research or spending its unchanged checkpoints', async () => { - const current = node(action.task.id); - current.task = { ...current.task, reviewScope: undefined }; - current.assignment!.taskDigest = taskVersion(current.task); - action = { ...action, task: current.task }; - const notes = 'A partial reduction with one remaining estimate.\n'; - fs.writeFileSync(path.join(engineer.worktree, 'RESEARCH.md'), notes); - const commit = commitSolverSources(problem, engineer.worktree); - cooperative.deactivate(engineer); - await cooperative.deliver(engineer, action, commit, true, 'scheduling-checkpoint'); - expect(state.cooperation!.researchCheckpoints?.bridge_audit).toMatchObject({ count: 1, paused: false }); - - for (let i = 0; i < 3; i++) { - const resumed = await cooperative.next(engineer, budget); - if (resumed?.kind !== 'task') throw new Error('fixture_expected_resumed_research'); - expect(resumed.task.id).toBe('bridge_audit'); - const saved = commitSolverSources(problem, engineer.worktree); - await cooperative.deliver(engineer, resumed, saved, true, 'proof-handoff'); - } - expect(current.status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints?.bridge_audit).toMatchObject({ count: 1, paused: false }); - expect(state.cooperation!.researchDrafts?.bridge_audit?.assignmentId).toBe(action.assignment.assignmentId); - expect(state.cooperation!.blockers?.some(item => item.mechanism === 'unchanged-research-checkpoint')).not.toBe(true); - }); - - it('retains a yielded review as an exact-input draft, runs its proof consumer, and can resume the review', async () => { - publishTypedWork(); - expect(shouldYield()).toBe(true); - const notes = 'Inspected only the pinned library. The helper has a checked construction.\n' + - '```lean\nexample : True := by trivial\n```\nNo completed review verdict.\n'; - fs.writeFileSync(path.join(engineer.worktree, 'RESEARCH.md'), notes); - const commit = commitSolverSources(problem, engineer.worktree); - cooperative.deactivate(engineer); - await cooperative.deliver(engineer, action, commit, true, 'scheduling-checkpoint'); - const audit = node('bridge_audit'), draft = state.cooperation!.researchDrafts!.bridge_audit; - expect(audit.status).toBe('pending'); expect(audit.finding).toBeUndefined(); - expect(audit.researchCompletion).toBeUndefined(); - expect(draft).toMatchObject({ commit, workerId: engineer.id, - feasibilityInputDigest: action.assignment.feasibilityInputDigest }); - expect(state.cooperation!.deliveries?.some(record => record.kind === 'research') ?? false).toBe(false); - - const typed = await cooperative.next(engineer, budget); - if (typed?.kind !== 'task') throw new Error('fixture_expected_typed_work'); - expect(typed.task.id).toBe('checked_bridge'); - expect(audit.status).toBe('pending'); - expect(state.cooperation!.researchDrafts!.bridge_audit).toMatchObject({ commit, suspended: true }); - cooperative.interrupted(engineer, typed); - node('checked_bridge').task = { ...node('checked_bridge').task, status: 'paused' }; refresh(); - const resumed = await cooperative.next(engineer, budget); - if (resumed?.kind !== 'task') throw new Error('fixture_expected_resumed_review'); - expect(resumed.task.id).toBe('bridge_audit'); - expect(resumed.assignment.feasibilityInputDigest).toBe(action.assignment.feasibilityInputDigest); - expect(resumed.assignment.assignmentId).toBe(action.assignment.assignmentId); - expect(fs.readFileSync(path.join(engineer.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - expect(audit.finding).toBeUndefined(); expect(audit.researchCompletion).toBeUndefined(); - }); - - it('keeps an unfinished review as a draft when the model saves notes and naturally returns after a typed-work notice', async () => { - cooperative.deactivate(engineer); cooperative.interrupted(engineer, action); await cooperative.stop(); - for (const goal of state.cooperation!.tasks.filter(item => item.task.kind === 'goal')) - goal.task = { ...goal.task, status: 'paused' }; - vi.useFakeTimers(); - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - const started = deferred(), done = deferred(), saved = deferred(); - const notes = 'Saved exact pinned-library observations and reproduction commands.\nThe independent review is unfinished.\n'; - const notify = vi.fn(async (message: string) => { - if (message.includes('A typed proof task is now ready')) { - fs.writeFileSync(path.join(engineer.worktree, 'RESEARCH.md'), notes); - done.resolve('completed'); - } - }); - const open = vi.fn(async (options: MathAgentOptions): Promise => ({ - threadId: 'natural-review-handoff', notify, advisoryNotifications: 'native-history', - interrupt: async () => { done.resolve('interrupted'); }, - close: async () => { done.resolve('interrupted'); }, - run: async (_message, _id, _workspace, onStarted) => { - onStarted('natural-review-turn'); options.onActivity?.({ event: 'reasoning' }); - started.resolve(); return done.promise; - }, - })); - const workers = [lead, peer, engineer]; - const completion = runResearchWorkers({ state, workers, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M4: { ...directSolverModules.M4, build: () => ({ instructions: 'Offline natural-return fixture.', - message: 'Review the precise pinned inputs.', scope: 'original-problem-and-allowed-library', - sources: { problemReceiptDigest: problem.receiptDigest } }) } }, - access: workerAccess(workers, directory), root: directory, buildFile: path.join(directory, 'build.json'), - taskText: 'Prove the original targets.', executable: 'offline-fixture', profile: 'offline-fixture', - signal: controller.signal, deadline: Infinity, maxTurnMs: Infinity, maxTurns: 2, maxTotalTokens: 0, - goalProgressReviewMs: 24 * 3_600_000, minAdvisorySliceMs: 5_000, save: () => {}, - emit: event => { if (event === 'feasibility_review_checkpoint_saved') saved.resolve(); }, - }); - try { - await Promise.race([started.promise, completion.then(() => { throw new Error('fixture_expected_review_turn'); })]); - // The helper becomes eligible on an active goal's path once the review has started. - for (const goal of state.cooperation!.tasks.filter(item => item.task.kind === 'goal')) - goal.task = { ...goal.task, status: 'active' }; - publishTypedWork(); - await vi.advanceTimersByTimeAsync(5_000); - await Promise.race([saved.promise, completion.then(() => { throw new Error('fixture_expected_saved_review'); })]); - expect(notify).toHaveBeenCalledWith(expect.stringContaining('A typed proof task is now ready'), { mode: 'advisory' }); - const audit = node('bridge_audit'); - expect(audit.status).toBe('pending'); - expect(audit.finding).toBeUndefined(); expect(audit.researchCompletion).toBeUndefined(); - expect(state.cooperation!.researchDrafts!.bridge_audit).toMatchObject({ workerId: engineer.id, - feasibilityInputDigest: action.assignment.feasibilityInputDigest }); - expect(state.cooperation!.deliveries?.some(record => record.kind === 'research') ?? false).toBe(false); - } finally { - controller.abort(); done.resolve('interrupted'); await Promise.allSettled([completion]); - } - }); -}); diff --git a/tests/solverAssemblyLeadYield.test.ts b/tests/solverAssemblyLeadYield.test.ts deleted file mode 100644 index 0ec841ab..00000000 --- a/tests/solverAssemblyLeadYield.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_PROOF } from '../src/math/localExample'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { parseCooperationPlan, taskVersion } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -describe('complete candidate yields an active Lead to host assembly', () => { - let directory: string, problem: SolverProblem, workers: ResearchWorker[], state: SolverRunState; - let cooperative: CooperativeResearch, controller: AbortController; - let events: { event: string; details?: Record }[]; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const sourceFile = (worker: ResearchWorker) => path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - const graph = () => ({ tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(route => route.group) }); - const changed = () => cooperative.deactivate(workers[1]); - const finishGoals = () => { - fs.writeFileSync(sourceFile(workers[1]), LOCAL_EXAMPLE_PROOF); - const commit = commitSolverSources(problem, workers[1].worktree); - state.cooperation!.canonicalCommit = commit; - for (const node of state.cooperation!.tasks) node.status = 'integrated'; - return commit; - }; - const startLead = async () => { - const action = await cooperative.next(workers[0], budget); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead'); - expect(cooperative.started(workers[0], action)).toBe(true); - const interrupt = vi.fn(async () => {}); - cooperative.activate(workers[0], action, interrupt, async () => {}); - expect(cooperative.current(action)).toBe(true); - return { action, interrupt }; - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(() => { throw new Error('fixture_unexpected_verification'); }); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('solver-assembly-lead-yield-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'engineer', { role: 'engineer' })]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, - })) }); - state = solverState(problem, example.workspace, { runId: 'assembly-lead-yield-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, error: 'The Lead has a pending route decision.', - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - events = []; controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }) }); - }); - - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.verify).not.toHaveBeenCalled(); expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('interrupts once, rejects the stopped Lead plan and sources, then assembles without another model turn', async () => { - const { action, interrupt } = await startLead(); - fs.writeFileSync(sourceFile(workers[0]), fs.readFileSync(sourceFile(workers[0]), 'utf8') - .replace('theorem add_zero', 'lemma stale_lead_draft : True := by trivial\ntheorem add_zero')); - const stalePlan = graph(); - stalePlan.tasks[0] = { ...stalePlan.tasks[0], objective: 'Reopen the completed original goal.' }; - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), JSON.stringify(stalePlan)); - const staleCommit = commitSolverSources(problem, workers[0].worktree); - const canonical = finishGoals(), tasks = structuredClone(state.cooperation!.tasks); - const planVersion = state.cooperation!.planVersion; - - changed(); changed(); - expect(interrupt).toHaveBeenCalledTimes(1); - expect(events.filter(item => item.event === 'lead_yielded_for_assembly')).toEqual([ - { event: 'lead_yielded_for_assembly', details: { workerId: workers[0].id, seedCommit: action.seedCommit, commit: canonical } }, - ]); - expect(cooperative.current(action)).toBe(false); - - cooperative.deactivate(workers[0]); - // A changing readiness predicate cannot make a stopped dispatch current again. - state.cooperation!.tasks[0].status = 'pending'; changed(); - expect(cooperative.current(action)).toBe(false); - state.cooperation!.tasks[0].status = 'integrated'; changed(); - await expect(cooperative.deliver(workers[0], action, staleCommit, true, 'scheduling-checkpoint')) - .resolves.toEqual({ checkWhole: false }); - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect(state.cooperation!.planVersion).toBe(planVersion); - expect(state.cooperation!.tasks).toEqual(tasks); - expect(committedSource(workers[0].worktree, canonical, `${problem.projectRelative}/Submission.lean`)).toBe(LOCAL_EXAMPLE_PROOF); - expect(events.some(item => item.event === 'lead_decision_superseded')).toBe(true); - - const assembly = await cooperative.next(workers[0], { maxTurns: 0, remainingMs: 1000 }); - expect(assembly).toMatchObject({ kind: 'assemble' }); - expect(state.cooperation!.review).toBeUndefined(); - expect(state.check).toBeUndefined(); - }); - - it.each(['incomplete-goal', 'approval', 'synchronization'] as const) - ('keeps the Lead active while the candidate is blocked by %s', async blocker => { - const { action, interrupt } = await startLead(); - const canonical = finishGoals(); - if (blocker === 'incomplete-goal') state.cooperation!.tasks[0].status = 'conditional'; - else if (blocker === 'approval') state.planApproval = true; - else state.cooperation!.tasks[0].pendingValidation = { id: 'pending-check', - taskDigest: taskVersion(state.cooperation!.tasks[0].task), canonicalCommit: canonical, - environmentDigest: state.environmentDigest, problemReceiptDigest: problem.receiptDigest }; - changed(); - expect(interrupt).not.toHaveBeenCalled(); - expect(cooperative.current(action)).toBe(true); - - state.cooperation!.tasks[0].status = 'integrated'; - state.planApproval = false; - delete state.cooperation!.tasks[0].pendingValidation; - // Synchronization completion and budget updates may only wake waiters, without changed(). - cooperative.modelBudgetChanged(); - expect(interrupt).toHaveBeenCalledTimes(1); - expect(cooperative.current(action)).toBe(false); - }); -}); diff --git a/tests/solverAssignmentRelease.test.ts b/tests/solverAssignmentRelease.test.ts deleted file mode 100644 index 38d83116..00000000 --- a/tests/solverAssignmentRelease.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources } from '../src/solver/problem'; -import { recordRouteBlockers, refreshRouteBlockers, validateBlockerProposals } from '../src/solver/routeControl'; -import { checkSolverRunState } from '../src/solver/stateInvariants'; -import { taskConnectionCheckCurrent } from '../src/solver/taskConnections'; -import { parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -type TaskAction = Extract; - -describe('assignment reservation cleanup', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - let directory: string, state: SolverRunState, cooperative: CooperativeResearch; - let lead: ResearchWorker, engineer: ResearchWorker, sourceWorker: ResearchWorker; - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - const group = () => state.cooperation!.groups![0]; - const next = async () => { - const action = await cooperative.next(engineer, budget); - if (action?.kind !== 'task') throw new Error('fixture_expected_task'); - return action; - }; - const retain = (action: TaskAction) => { - fs.writeFileSync(path.join(engineer.worktree, 'RESEARCH.md'), 'Retained route and exact remaining inference.\n'); - const commit = commitSolverSources(state.problem, engineer.worktree); - cooperative.retainContextDraft(engineer, action, commit); - return state.cooperation!.researchDrafts![action.task.id]; - }; - - beforeEach(() => { - const example = localExample('solver-assignment-release-', 'lead'); - directory = example.directory; - lead = leadWorker(example.problem, example.workspace); - engineer = peerWorker(example, 'engineer', { role: 'engineer' }); - sourceWorker = peerWorker(example, 'source'); - const plan = parseCooperationPlan(example.problem, { tasks: [ - { id: 'prior', kind: 'research', objective: 'Prior mathematical evidence.', ownerId: sourceWorker.id }, - { id: 'investigate', kind: 'research', objective: 'Investigate the exact remaining inference.', - ownerId: engineer.id, dependsOn: ['prior'] }, - ...example.problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', objective: 'Original target.', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ], groups: [{ id: 'main', objective: 'Original problem.', maxConcurrent: 1, engineerId: engineer.id }] }); - state = solverState(example.problem, example.workspace, { runId: 'assignment-release-fixture', phase: 'running', - workers: [lead, engineer, sourceWorker].map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: task.id === 'prior' ? 'completed' : 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const forbidden = () => { throw new Error('fixture_model_or_verifier_forbidden'); }; - cooperative = cooperativeResearch({ state, workers: [lead, engineer, sourceWorker], retrievalRoot: directory, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: forbidden }, - M2: { ...directSolverModules.M2, check: forbidden, checkTask: forbidden } } }); - }); - afterEach(async () => { - await cooperative.stop(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['release', 'interrupted'] as const)( - 'reclaims a superseded %s reservation and keeps its draft available for inspection', async cleanup => { - const action = await next(); - if (cleanup === 'interrupted') expect(cooperative.started(engineer, action)).toBe(true); - const draft = retain(action); - expect(node('investigate').status).toBe('running'); - expect(group()?.busy).toBe(1); - node('prior').task = { ...node('prior').task, revision: node('prior').task.revision + 1 }; - expect(cooperative.current(action)).toBe(false); - expect(cooperative.started(engineer, action)).toBe(false); - - cooperative[cleanup](engineer, action); - - expect(node('investigate').status).toBe('pending'); - expect(node('investigate').assignment).toBeUndefined(); - expect(group()?.busy).toBe(0); - expect(state.cooperation!.researchDrafts!.investigate).toBe(draft); - expect(checkSolverRunState(state).filter(item => item.code === 'worker_multiple_running_tasks')).toEqual([]); - const successor = await next(); - expect(successor.task.id).toBe('investigate'); - expect(successor.assignment).not.toBe(action.assignment); - expect(successor.assignment.dependencies).toEqual([{ taskId: 'prior', taskDigest: taskVersion(node('prior').task) }]); - expect(cooperative.started(engineer, successor)).toBe(true); - - // A delayed callback for the old dispatch cannot revoke the new writer. - cooperative[cleanup](engineer, action); - expect(node('investigate').status).toBe('running'); - expect(node('investigate').assignment).toBe(successor.assignment); - expect(group()?.busy).toBe(1); - }); - - it('does not release a matching-looking assignment object owned by a newer dispatch', async () => { - const action = await next(); - const successor = { ...action.assignment, assignmentId: 'successor' }; - node('investigate').assignment = successor; - cooperative.release(engineer, action); - cooperative.interrupted(engineer, action); - expect(node('investigate')).toMatchObject({ status: 'running', assignment: successor }); - }); - - it('ignores cleanup by another worker or for a removed task', async () => { - const action = await next(); - cooperative.release(sourceWorker, action); - cooperative.interrupted(sourceWorker, action); - expect(node('investigate').status).toBe('running'); - state.cooperation!.tasks = state.cooperation!.tasks.filter(item => item.task.id !== action.task.id); - expect(() => cooperative.release(engineer, action)).not.toThrow(); - expect(() => cooperative.interrupted(engineer, action)).not.toThrow(); - }); - - it('renews a conditional connection when restoring a draft onto newer canonical sources', async () => { - node('investigate').task = { ...node('investigate').task, status: 'paused' }; - node('prior').task = { ...node('prior').task, kind: 'lemma', type: 'True', - theoremName: 'Tutorial.input', proofPath: 'Submission.lean' }; - node('prior').status = 'pending'; - node('goal_0').task = { ...node('goal_0').task, status: 'active', ownerId: engineer.id, dependsOn: ['prior'] }; - const action = await next(); - expect(action.task.id).toBe('goal_0'); - expect(taskConnectionCheckCurrent(action.task, action.assignment, state.cooperation!.tasks)).toBe(true); - const draft = retain(action); - cooperative.interrupted(engineer, action); - draft.suspended = true; - const canonicalFile = path.join(lead.worktree, state.problem.projectRelative, 'Submission.lean'); - fs.appendFileSync(canonicalFile, '\n-- Canonical sources advanced while this task was suspended.\n'); - state.cooperation!.canonicalCommit = commitSolverSources(state.problem, lead.worktree); - - const resumed = await next(); - - expect(resumed.assignment.assignmentId).not.toBe(action.assignment.assignmentId); - expect(resumed.assignment.seedCommit).not.toBe(action.assignment.seedCommit); - expect(resumed.assignment.connectionCheck).toMatchObject({ assignmentId: resumed.assignment.assignmentId, - seedCommit: resumed.assignment.seedCommit, workerId: engineer.id }); - expect(taskConnectionCheckCurrent(resumed.task, resumed.assignment, state.cooperation!.tasks)).toBe(true); - expect(cooperative.current(resumed)).toBe(true); - expect(state.cooperation!.researchDrafts!.goal_0.assignmentId).toBe(resumed.assignment.assignmentId); - expect(cooperative.started(engineer, resumed)).toBe(true); - expect(fs.readFileSync(path.join(engineer.worktree, 'RESEARCH.md'), 'utf8')).toContain('Retained route'); - }); - - it('dispatches a revised research question after a formal plan edit without discarding typed obstruction history', async () => { - await cooperative.pulse(); - // Dispatch initializes the same versioned plan used by the normal edit queue. - const initial = await next(); - cooperative.release(engineer, initial); - const records = state.cooperation!.blockers ??= []; - for (const item of [node('investigate'), node('goal_0')]) { - const proposals = validateBlockerProposals([{ mechanism: 'unchanged-research-checkpoint', - scope: 'assigned-local-inference/checkpoint:previous-output' }], item.task, state.cooperation!.tasks); - for (let count = 0; count < 2; count++) recordRouteBlockers(records, proposals, item.task, - state.cooperation!.tasks, state.environmentDigest, state.problem.receiptDigest); - } - refreshRouteBlockers(records, state.cooperation!.tasks, state.environmentDigest, state.problem.receiptDigest); - expect(node('investigate').routeParking).toHaveLength(1); - expect(node('goal_0').routeParking).toHaveLength(1); - const revised = { ...node('investigate').task, revision: 1, - objective: 'Find the exact bounded averaging lemma and its application to the remaining operator norm estimate.' }; - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'new-research-input', - baseVersion: state.cooperation!.planVersion, - tasks: state.cooperation!.tasks.map(item => item.task.id === revised.id ? revised : item.task), - groups: state.cooperation!.groups!.map(item => item.group) }) + '\n'); - - await cooperative.pulse(); - - const edit = state.cooperation!.edits!.at(-1)!; - expect(edit.status, edit.reason).toBe('applied'); - expect(node('investigate')).toMatchObject({ status: 'pending', task: { revision: 1 }, routeParking: [] }); - expect(records.find(record => record.taskId === revised.id)).toMatchObject({ status: 'reopened', reopenedReason: 'contract-changed' }); - expect(records.find(record => record.taskId === 'goal_0')).toMatchObject({ status: 'parked', count: 2 }); - expect(node('goal_0').routeParking).toHaveLength(1); - expect((await next()).task.id).toBe(revised.id); - }); -}); diff --git a/tests/solverAtomicPlanApply.test.ts b/tests/solverAtomicPlanApply.test.ts index 1a05cdaf..5bcc9241 100644 --- a/tests/solverAtomicPlanApply.test.ts +++ b/tests/solverAtomicPlanApply.test.ts @@ -2,12 +2,8 @@ import fs from 'node:fs'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { afterEach, describe, expect, it } from 'vitest'; -import { readCooperationPlan } from '../src/solver/cooperationShared'; -import { applyCooperationPlanFile, validateCooperationPlan, validateCooperationPlanFile } from '../src/solver/planTool'; -import { parseCooperationPlan } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import './helpers/solverAtomicPlanRejection'; +import { validateCooperationPlan, validateCooperationPlanFile } from '../src/solver/planTool'; +import { localExample } from './helpers/solver'; const roots: string[] = []; const notes = '## Current argument\nKeep this explanation.\n\n```json\n{"example":42}\n```\n'; @@ -27,7 +23,7 @@ function fixture() { return { example, workspace, problem, plan, file }; } -describe('atomic cooperative plan commands', () => { +describe('validation of archived cooperative plans', () => { it('leaves the notes byte-for-byte unchanged on invalid JSON, a graph violation, and invalid retirement fields', () => { const { workspace, plan, file, problem } = fixture(); const invalidTask = { tasks: [{ ...plan.tasks[0], status: 'verified' }] }; @@ -48,76 +44,22 @@ describe('atomic cooperative plan commands', () => { const result = validateCooperationPlanFile(input); expect(result).toMatchObject({ ok: false, error: item.error, issues: item.fields.map(field => ({ path: field, message: expect.any(String) })) }); - expect(applyCooperationPlanFile(input)).toEqual(result); expect(fs.readFileSync(file, 'utf8')).toBe(notes + '\n' + malformed); } }); - it('accepts full JSON through the CLI from stdin and replaces only old plan fences', () => { - const { workspace, plan, file, problem } = fixture(); - const extraPlan = '```math\n' + JSON.stringify(plan) + '\n```\n'; - fs.appendFileSync(file, extraPlan + '\nEnd of notes.\n'); - const invoke = (command: 'plan-validate' | 'plan-apply', input: string) => spawnSync('bun', - ['bin/math.ts', command, '--workspace', workspace], { input, encoding: 'utf8', timeout: 15_000 }); - const rejected = invoke('plan-apply', '{"tasks":['); - expect(rejected.status, rejected.stderr || String(rejected.error ?? '')).toBe(1); + it('validates a plan from stdin without changing the archived notes', () => { + const { workspace, plan, file } = fixture(); + const original = fs.readFileSync(file, 'utf8'); + const invoke = (input: string) => spawnSync('bun', ['bin/math.ts', 'plan-validate', '--workspace', workspace], + { input, encoding: 'utf8', timeout: 15_000 }); + const rejected = invoke('{"tasks":['); + expect(rejected.status, rejected.stderr).toBe(1); expect(JSON.parse(rejected.stdout)).toMatchObject({ ok: false, error: 'math_plan_json_invalid' }); - expect(fs.readFileSync(file, 'utf8')).toContain(malformed + extraPlan); - const checked = invoke('plan-validate', JSON.stringify(plan)); - expect(checked.status, checked.stderr || String(checked.error ?? '')).toBe(0); - expect(fs.readFileSync(file, 'utf8')).toContain(malformed); - const applied = invoke('plan-apply', JSON.stringify(plan)); - expect(applied.status, applied.stderr || String(applied.error ?? '')).toBe(0); - const parsed = JSON.parse(checked.stdout); - expect(parsed).toMatchObject({ ok: true, tasksCount: plan.tasks.length, planVersion: expect.stringMatching(/^[a-f0-9]{64}$/u) }); - expect(JSON.parse(applied.stdout)).toEqual({ ...parsed, file }); - const result = fs.readFileSync(file, 'utf8'); - expect(result).toContain(notes); - expect(result).toContain('End of notes.'); - expect(result.match(/```math-plan\n/g)).toHaveLength(1); - expect(result).not.toContain(extraPlan); - expect(readCooperationPlan(problem, workspace)).toEqual(parseCooperationPlan(problem, plan)); - }); - - it('uses the host-projected revision base, rejects a stale base, and retains checked retirement directives', async () => { - const { example, workspace, plan, file, problem } = fixture(); - const lead = leadWorker(problem, workspace), peer = peerWorker(example, 'engineer', { role: 'engineer' }); - const basePlan = parseCooperationPlan(problem, plan); - const state = solverState(problem, workspace, { runId: 'atomic-plan', phase: 'running', cooperation: { - tasks: basePlan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: basePlan.groups.map(group => ({ group, turns: 0 })), planVersion: 'current', error: 'fixture_needs_revision', - } }); - const host = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: example.directory }); - host.start(); - try { - const action = await host.next(lead, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind).toBe('lead'); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead_dispatch'); - expect(host.started(lead, action)).toBe(true); - const version = state.cooperation!.planVersion!; - const invalidPatches = [ - { patch: { baseVersion: 'stale', upsert: [] }, error: 'math_plan_patch_version_conflict', path: 'baseVersion', - message: expect.stringContaining(version) }, - { patch: { baseVersion: version, tasks: { baseVersion: 'stale', upsert: [] } }, error: 'math_plan_patch_invalid', - path: 'tasks.baseVersion' }, - { patch: { baseVersion: version, remove: ['unknown'] }, error: 'math_plan_patch_unknown_task', path: 'remove[0]' }, - ]; - for (const { patch, error, path, message } of invalidPatches) { - const input = { workspace, text: JSON.stringify(patch) }; - const result = validateCooperationPlanFile(input); - expect(result).toMatchObject({ ok: false, error, issues: [{ path, message: message ?? expect.any(String) }] }); - expect(applyCooperationPlanFile(input)).toEqual(result); - } - expect(fs.readFileSync(file, 'utf8')).toBe(notes + '\n' + malformed); - const revise = { tasks: { baseVersion: version, upsert: [{ id: plan.tasks[0].id, objective: 'A sharper reduction.' }] }, - retireRoutes: [{ routeId: 'dead', reason: 'Counterexample at the boundary.' }] }; - expect(applyCooperationPlanFile({ workspace, text: JSON.stringify(revise) })).toMatchObject({ ok: true, baseVersion: version, - retireRoutesCount: 1, tasksCount: basePlan.tasks.length }); - const applied = readCooperationPlan(problem, workspace, { version, ...basePlan }); - expect(applied.tasks[0].objective).toBe('A sharper reduction.'); - expect(applied).toMatchObject({ fromPatch: true, retireRoutes: revise.retireRoutes }); - const peerContext = JSON.parse(fs.readFileSync(path.join(peer.worktree, 'COOPERATION.json'), 'utf8')); - expect(peerContext.planTool).toBeUndefined(); - } finally { await host.stop(); } + const checked = invoke(JSON.stringify(plan)); + expect(checked.status, checked.stderr).toBe(0); + expect(JSON.parse(checked.stdout)).toMatchObject({ ok: true, tasksCount: plan.tasks.length, + planVersion: expect.stringMatching(/^[a-f0-9]{64}$/u) }); + expect(fs.readFileSync(file, 'utf8')).toBe(original); }); }); diff --git a/tests/solverCanonicalGoalProof.test.ts b/tests/solverCanonicalGoalProof.test.ts deleted file mode 100644 index 5718d80c..00000000 --- a/tests/solverCanonicalGoalProof.test.ts +++ /dev/null @@ -1,302 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { checkTaskProof } from '../src/solver/cooperativeProof'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git, readSolverProblem } from '../src/solver/problem'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { freshlyAccepted, taskVersion } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { newestLeanBinary } from './helpers/lean'; -import { leadWorker, solverState } from './helpers/solver'; -import { failedBatch, receiptBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), model: vi.fn() })); -vi.mock('../src/math/verifier', async original => ({ ...await original(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'canonical-goal-fixture-tools', -})); -vi.mock('../src/math/mathProofEnvironment', async original => ({ - ...await original(), resolveMathProofEnvironment: () => undefined, -})); - -const source = [ - 'namespace Canonical', - 'theorem already (n : Nat) : n + 0 = n := by rfl', - 'theorem usesAlready (n : Nat) : n + 0 = n := by exact already n', - 'def value (n : Nat) : Nat := n', - 'theorem unfinished : True := by sorry', - 'end Canonical', '', -].join('\n'); - -describe('canonical original goals before model dispatch', () => { - let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; - let controller: AbortController, allowed: boolean, environment: NodeJS.ProcessEnv, emit: ReturnType; - let exclusive: (operation: () => Promise) => Promise; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const node = (id = 'already') => state.cooperation!.tasks.find(item => item.task.id === id)!; - const canonical = () => committedSource(workers[0].worktree, state.cooperation!.canonicalCommit!, - `${state.problem.projectRelative}/Submission.lean`); - const verified = (request: MathematicsVerifierBatchRequest) => verifiedBatch(request, { sessionId: 'canonical-goal-fixture', checks: true }); - const next = (index = 1) => cooperative.next(workers[index], budget); - const activate = (id: string) => { - for (const record of state.cooperation!.tasks.filter(item => item.task.kind === 'goal')) - record.task = { ...record.task, status: record.task.id === id ? 'active' : 'paused' }; - node('followup').task = { ...node('followup').task, dependsOn: [id] }; - }; - const writeCanonical = (text: string) => { - fs.writeFileSync(path.join(workers[0].worktree, state.problem.projectRelative, 'Submission.lean'), text); - state.cooperation!.canonicalCommit = commitSolverSources(state.problem, workers[0].worktree); - }; - const noAcceptance = (id = 'already') => { - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(node(id).proof).toBeUndefined(); expect(node(id).integratedCheck).toBeUndefined(); - expect(node(id).attempts).toBe(0); expect(state.turns).toBe(0); - expect(state.cooperation!.groups![0].turns).toBe(0); - }; - const holdVerifier = () => { - const entered = deferred(), release = deferred(); - host.verify.mockImplementationOnce(async (request: MathematicsVerifierBatchRequest) => { - entered.resolve(request); await release.promise; return verified(request); - }); - return { entered: entered.promise, release: () => release.resolve() }; - }; - - beforeEach(() => { - directory = temporaryDirectory('solver-canonical-original-goal-'); - const receipt = bootstrapLeanTask(path.join(directory, 'workspace'), { - source, task: 'Prove the original targets.', definitionTargets: ['Canonical.value'], - }); - const workspace = receipt.workspaceRoot, problem = readSolverProblem(workspace, receipt.activeProblemPath); - workers = [leadWorker(problem, workspace), ...['proof', 'other'].map(id => { - const worktree = path.join(directory, id); - git(workspace, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - return { id, worktree, role: 'researcher' as const, ownedFiles: problem.ownedFiles }; - })]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map(target => ({ id: target.theoremName.split('.').at(-1)!, kind: 'goal', objective: 'Original goal', - proofPath: target.proofPath, theoremName: target.theoremName, ownerId: 'proof', - status: target.theoremName === 'Canonical.already' ? 'active' : 'paused' })), - { id: 'followup', kind: 'research', objective: 'Use the checked original', dependsOn: ['already'], ownerId: 'proof' }, - { id: 'independent', kind: 'research', objective: 'Independent work', ownerId: 'other' }, - ], groups: [{ id: 'main', objective: 'Original problem', status: 'active', maxConcurrent: 1 }] }); - state = solverState(problem, workspace, { runId: 'canonical-goal-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, groups: plan.groups.map(group => ({ group, turns: 0 })), - tasks: plan.tasks.map(task => ({ task, attempts: 0, status: 'pending' })) } }); - const envFile = path.join(directory, 'fixture.env'); fs.writeFileSync(envFile, ''); - environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - controller = new AbortController(); allowed = true; emit = vi.fn(); exclusive = operation => operation(); - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.model.mockReset().mockImplementation(() => { throw new Error('fixture_models_forbidden'); }); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, emit, - access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory }])), - modelDispatchAllowed: () => allowed, exclusiveCheck: operation => exclusive(operation), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: host.model, execute: host.model } } }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async () => { - throw new Error('original_goal_must_not_use_helper_type_preflight'); - }); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); expect(host.model).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['already', 'value'] as const)('checks a complete original %s independently, without a library or model attempt', async id => { - activate(id); - const before = canonical(); - expect(node(id).task.type).toBeUndefined(); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(node(id)).toMatchObject({ status: 'integrated', attempts: 0, proof: { passed: true, changes: [] }, - integratedCheck: { passed: true, changes: [] } }); - expect(freshlyAccepted(node(id), taskVersion(node(id).task))).toBe(true); - expect(freshlyAccepted(structuredClone(node(id)), taskVersion(node(id).task))).toBe(false); - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][0].items).toHaveLength(1); - expect(host.verify.mock.calls[0][0].items[0].theoremName).toBe(`Canonical.${id}`); - expect(host.verify.mock.calls[0][1].expectedDeclarationType).toBeUndefined(); - expect(state.cooperation!.tasks.filter(item => item.task.kind === 'goal' && item.task.id !== id) - .every(item => item.status === 'pending' && !item.proof)).toBe(true); - expect(state.check).toBeUndefined(); expect(state.turns).toBe(0); expect(state.cooperation!.groups![0].turns).toBe(0); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ taskId: id, kind: 'proof', status: 'verified' })); - expect(canonical()).toBe(before); - }); - - it('makes a rejected existing proof advisory input and returns ordinary model work without failure memory', async () => { - host.verify.mockImplementationOnce(async request => failedBatch(verified(request), - { stdoutPreview: () => 'Submission.lean:2:1: error: inherited proof does not close this target' })); - const action = await next(); - expect(action).toMatchObject({ kind: 'task', task: { id: 'already' } }); - if (action?.kind !== 'task') throw new Error('expected_task_assignment'); - expect(action.assignment.canonicalProbe).toMatchObject({ evidence: 'advisory-canonical-check', proofAcceptance: 'not-accepted', - sourceCommit: action.assignment.seedCommit, environmentDigest: state.environmentDigest, verificationStatus: 'failed' }); - expect(action.assignment.canonicalProbe!.feedback).toContain('inherited proof does not close'); - expect(action.assignment.canonicalProbe!.receiptIds).toHaveLength(1); - expect(node().status).toBe('running'); expect(node().repair).toBeUndefined(); - expect(node().feedback).toBeUndefined(); expect(host.verify).toHaveBeenCalledOnce(); noAcceptance(); - }); - - it('falls through after checker unavailability with bounded advisory diagnostics', async () => { - (cooperative as any).input.modules.M2 = { ...directSolverModules.M2, - checkTask: vi.fn().mockRejectedValue(new Error('fixture_checker_unavailable: ' + '诊断'.repeat(3000))) }; - const action = await next(); - expect(action).toMatchObject({ kind: 'task', task: { id: 'already' } }); - if (action?.kind !== 'task') throw new Error('expected_task_assignment'); - expect(action.assignment.canonicalProbe).toMatchObject({ evidence: 'advisory-canonical-check', proofAcceptance: 'not-accepted' }); - expect(action.assignment.canonicalProbe!.feedback).toContain('fixture_checker_unavailable'); - expect(Buffer.byteLength(action.assignment.canonicalProbe!.feedback)).toBeLessThanOrEqual(2000); - expect(action.assignment.canonicalProbe!.feedback).not.toContain('\uFFFD'); - expect(host.verify).not.toHaveBeenCalled(); noAcceptance(); - }); - - it.each(['sorry', 'admit', 'saved-assignment', 'conditional', 'wrong-namespace', 'not-original', 'duplicate-leaf'] as const) - ('keeps %s work on the model path without a canonical probe', async kind => { - if (kind === 'sorry') activate('unfinished'); - if (kind === 'admit') { activate('unfinished'); writeCanonical(source.replace('by sorry', 'by admit')); } - if (kind === 'saved-assignment') node().assignment = { taskId: 'already', taskDigest: taskVersion(node().task), - workerId: workers[1].id, seedCommit: state.cooperation!.canonicalCommit!, assignmentId: 'saved-goal' }; - if (kind === 'conditional') node().task = { ...node().task, conditional: true }; - if (kind === 'wrong-namespace') node().task = { ...node().task, theoremName: 'Other.already' }; - if (kind === 'not-original') { - node().task = { ...node().task, theoremName: 'Canonical.extra' }; - writeCanonical(source.replace('theorem unfinished', 'theorem extra : True := by trivial\ntheorem unfinished')); - } - if (kind === 'duplicate-leaf') writeCanonical(source.replace('theorem unfinished', - 'theorem Other.already : True := by trivial\ntheorem unfinished')); - const saved = node().assignment, id = kind === 'sorry' || kind === 'admit' ? 'unfinished' : 'already'; - expect(await next()).toMatchObject({ kind: 'task', task: { id } }); - if (kind === 'saved-assignment') expect(node().assignment).toBe(saved); - expect(host.verify).not.toHaveBeenCalled(); noAcceptance(id); - }); - - it('preserves conditional connection work when an explicit helper dependency is not checked', async () => { - node().task = { ...node().task, dependsOn: ['child'] }; - state.cooperation!.tasks.push({ task: { id: 'child', kind: 'lemma', theoremName: 'Canonical.child', type: 'True', - proofPath: 'Submission.lean', objective: 'Unproved dependency', ownerId: 'other', revision: 0, dependsOn: [] }, - status: 'pending', attempts: 0 }); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'already' }, - assignment: { connectionCheck: expect.any(Object) } }); - expect(host.verify).not.toHaveBeenCalled(); noAcceptance(); - }); - - it.each(['header', 'context'] as const)('keeps the frozen %s constraint in the independent checker', async change => { - const changed = change === 'header' ? source.replace('n + 0 = n := by rfl', 'True := by trivial') : - source.replace('namespace Canonical', 'namespace Canonical\nset_option autoImplicit false'); - fs.writeFileSync(path.join(workers[0].worktree, state.problem.projectRelative, 'Submission.lean'), changed); - const error = `math_original_${change === 'header' ? 'declaration' : 'context'}_changed`; - expect(() => commitSolverSources(state.problem, workers[0].worktree)).toThrow(error); - // A bad archived commit must not bypass the independent checker even if it - // entered Git without the ordinary host writer's frozen-source checks. - git(workers[0].worktree, ['add', '--', `${state.problem.projectRelative}/Submission.lean`]); - git(workers[0].worktree, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', - 'commit', '--no-gpg-sign', '--quiet', '-m', 'Deliberately invalid archived source']); - const commit = git(workers[0].worktree, ['rev-parse', 'HEAD']); - await expect(checkTaskProof(state.problem, workers[0].worktree, commit, node().task, - { taskId: 'already', taskDigest: taskVersion(node().task), workerId: workers[0].id, seedCommit: commit }, - [], environment, controller.signal)).rejects.toThrow(error); - noAcceptance(); expect(host.verify).not.toHaveBeenCalled(); - }); - - it('does not probe a complete definition in place of the original theorem kind', async () => { - writeCanonical(source.replace('theorem already', 'def already')); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'already' } }); - noAcceptance(); expect(host.verify).not.toHaveBeenCalled(); - }); - - it('lets independent work dispatch while an original proof check is running', async () => { - state.cooperation!.groups![0].group.maxConcurrent = 2; - const held = holdVerifier(), pending = next(); await held.entered; - expect(node()).toMatchObject({ status: 'pending', attempts: 0 }); expect(node().assignment).toBeUndefined(); - try { expect(await next(2)).toMatchObject({ kind: 'task', task: { id: 'independent' } }); } - finally { held.release(); } - expect(await pending).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(host.verify).toHaveBeenCalledOnce(); - }); - - it.each(['source', 'contract', 'paused', 'route', 'worker-environment', 'lead-environment', 'worker-head', 'worker-stopped', 'problem-receipt'] as const) - ('discards a result when its %s changes while the original proof is checked', async change => { - // Observe one dispatch only, so its own identity gate must discard the - // result even though model admission remains open for a later dispatch. - const held = holdVerifier(), pending = (cooperative as any).nextPeer(workers[1], budget, true); await held.entered; - try { - if (change === 'source') { - git(workers[0].worktree, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', - 'commit', '--allow-empty', '--no-gpg-sign', '--quiet', '-m', 'New canonical']); - state.cooperation!.canonicalCommit = git(workers[0].worktree, ['rev-parse', 'HEAD']); - } - if (change === 'contract') node().task = { ...node().task, revision: node().task.revision + 1 }; - if (change === 'paused') node().task = { ...node().task, status: 'paused' }; - if (change === 'route') state.cooperation!.groups![0].group.status = 'paused'; - if (change.endsWith('-environment')) (cooperative as any).input.access.set(workers[change === 'lead-environment' ? 0 : 1].id, - { environment: {}, retrievalRoot: directory }); - if (change === 'worker-head') git(workers[1].worktree, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', - 'commit', '--allow-empty', '--no-gpg-sign', '--quiet', '-m', 'Worker advanced']); - if (change === 'worker-stopped') cooperative.stopped(workers[1]); - if (change === 'problem-receipt') state.problem = { ...state.problem, receiptDigest: 'changed-receipt' }; - } finally { held.release(); } - expect(typeof await pending).toBe('symbol'); expect(allowed).toBe(true); noAcceptance(); - expect(node().status).toBe('pending'); expect(node().assignment).toBeUndefined(); - expect(emit.mock.calls.some(call => call[0] === 'task_canonical_probe')).toBe(false); - }); - - it('rechecks publication identity after waiting for the canonical transaction', async () => { - const entered = deferred(), release = deferred(); - exclusive = async operation => { entered.resolve(); await release.promise; return operation(); }; - const pending = next(); await entered.promise; - try { - writeCanonical(source + '-- New canonical snapshot\n'); allowed = false; cooperative.modelBudgetChanged(); - } finally { release.resolve(); } - expect(await pending).toBeUndefined(); noAcceptance(); expect(node().assignment).toBeUndefined(); - }); - - it('waits for cancelled original proof checks to release their worktrees before stop returns', async () => { - const before = git(workers[0].worktree, ['worktree', 'list', '--porcelain']); - const held = holdVerifier(), pending = next(); await held.entered; - let stopped = false; - const stopping = cooperative.stop().then(() => { stopped = true; }); - await new Promise(resolve => setImmediate(resolve)); - try { expect(stopped).toBe(false); } finally { held.release(); } - expect(await pending).toBeUndefined(); await stopping; - noAcceptance(); expect(node().assignment).toBeUndefined(); expect(stopped).toBe(true); - expect(git(workers[0].worktree, ['worktree', 'list', '--porcelain'])).toBe(before); - }); - - it('checks complete original theorem and def bodies with native Lean, retaining only freshly accepted original inputs', async () => { - const lean = newestLeanBinary(); - if (!lean) throw new Error('Native Lean is required for canonical original-goal regression.'); - const native: { theorem: string; source: string; output: string }[] = []; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const text = committedSource(workers[0].worktree, request.targetCommit!, `${state.problem.projectRelative}/Submission.lean`); - const file = path.join(directory, 'NativeCanonicalCheck.lean'); - fs.writeFileSync(file, text + '\n' + request.items.map(item => `#print ${item.theoremName}\n#print axioms ${item.theoremName}`).join('\n')); - const result = spawnSync(lean, [file], { cwd: request.projectRoot, encoding: 'utf8', timeout: 20_000 }); - expect(result.error).toBeUndefined(); - const output = `${result.stdout}${result.stderr}`; - for (const item of request.items) native.push({ theorem: item.theoremName!, source: text, output }); - const batch = receiptBatch(request, { sessionId: 'native-canonical-goal-fixture', - receiptId: (_, name) => `native-${request.targetCommit}-${name}` }); - return result.status === 0 && !output.includes('sorryAx') && !/\b(?:sorry|admit)\b/u.test(text) - ? batch : failedBatch(batch, { stdoutPreview: () => output }); - }); - for (const id of ['already', 'usesAlready', 'value']) { - activate(id); - const action = await next(); - expect(action).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(node(id).status, JSON.stringify(node(id).assignment?.canonicalProbe ?? native.at(-1))).toBe('integrated'); - expect(freshlyAccepted(node(id), taskVersion(node(id).task))).toBe(true); - expect(node(id).attempts).toBe(0); - if (action) cooperative.release(workers[1], action); - } - expect(native.map(item => item.theorem)).toEqual(['Canonical.already', 'Canonical.usesAlready', 'Canonical.value']); - expect(native.find(item => item.theorem === 'Canonical.usesAlready')!.source).toContain('theorem already'); - expect(native.every(item => !item.source.includes('theorem unfinished') && !item.output.includes('sorryAx'))).toBe(true); - expect(canonical()).toBe(source); expect(node('unfinished').proof).toBeUndefined(); expect(state.turns).toBe(0); - }); -}); diff --git a/tests/solverCanonicalTaskProof.test.ts b/tests/solverCanonicalTaskProof.test.ts deleted file mode 100644 index b5714db0..00000000 --- a/tests/solverCanonicalTaskProof.test.ts +++ /dev/null @@ -1,298 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_STATEMENT } from '../src/math/localExample'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git } from '../src/solver/problem'; -import { freshlyAccepted, taskVersion } from '../src/solver/tasks'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), model: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'canonical-fixture-tools', -})); -vi.mock('../src/math/mathProofEnvironment', async importOriginal => ({ - ...await importOriginal(), resolveMathProofEnvironment: () => undefined, -})); - -describe('canonical helper checks before model dispatch', () => { - let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; - let controller: AbortController, allowed: boolean, environment: NodeJS.ProcessEnv; - let exclusive: (operation: () => Promise) => Promise; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const node = () => state.cooperation!.tasks.find(item => item.task.id === 'helper')!; - const verified = (request: MathematicsVerifierBatchRequest) => verifiedBatch(request, { sessionId: 'canonical-fixture', checks: true }); - const mismatchMessage = 'Helper declaration has a different type or additional assumptions'; - const rejectCandidate = (message = mismatchMessage) => host.verify.mockImplementationOnce(async request => - failedBatch(verified(request), { stdoutPreview: () => `Submission.lean:1:1: error: ${message}` })); - const next = (index = 1) => cooperative.next(workers[index], budget); - const noDelivery = () => { - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(node().proof).toBeUndefined(); expect(node().integratedCheck).toBeUndefined(); - expect(node().attempts).toBe(0); - }; - const writeCanonical = (source: string) => { - fs.writeFileSync(path.join(workers[0].worktree, state.problem.projectRelative, 'Submission.lean'), source); - state.cooperation!.canonicalCommit = commitSolverSources(state.problem, workers[0].worktree); - }; - const source = (declaration = 'lemma helper : True := by trivial') => - LOCAL_EXAMPLE_STATEMENT.replace('theorem add_zero', `${declaration}\ntheorem add_zero`); - const holdVerifier = () => { - const entered = deferred(), release = deferred(); - host.verify.mockImplementationOnce(async (request: MathematicsVerifierBatchRequest) => { - entered.resolve(request); await release.promise; return verified(request); - }); - return { entered: entered.promise, release: () => release.resolve() }; - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.model.mockReset().mockImplementation(() => { throw new Error('fixture_models_forbidden'); }); - const example = localExample('solver-canonical-helper-'), { workspace, problem } = example; - directory = example.directory; - workers = [leadWorker(problem, workspace), peerWorker(example, 'proof'), peerWorker(example, 'other')]; - const plan = parseCooperationPlan(problem, { tasks: [ - { id: 'helper', kind: 'lemma', objective: 'Prove exact helper', theoremName: 'Tutorial.helper', - proofPath: 'Submission.lean', type: 'True', ownerId: 'proof' }, - { id: 'followup', kind: 'research', objective: 'Observe dependency readiness', dependsOn: ['helper'], ownerId: 'proof' }, - { id: 'independent', kind: 'research', objective: 'Independent work', ownerId: 'other' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', objective: 'Original goal', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ], groups: [{ id: 'main', objective: 'Original problem', status: 'active', maxConcurrent: 1 }] }); - state = solverState(problem, workspace, { runId: 'canonical-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, groups: plan.groups.map(group => ({ group, turns: 0 })), - tasks: plan.tasks.map(task => ({ task, attempts: 0, status: 'pending' })) } }); - writeCanonical(source()); - const envFile = path.join(directory, 'math.env'); fs.writeFileSync(envFile, ''); - environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - controller = new AbortController(); allowed = true; exclusive = operation => operation(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory }])), - modelDispatchAllowed: () => allowed, exclusiveCheck: operation => exclusive(operation), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: host.model, execute: host.model } } }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ current: () => !input.signal?.aborted, - result: { taskDigest: taskVersion(input.task), inputDigest: 'fixture', evidence: 'advisory-type-elaboration', - proofAcceptance: 'not-assessed', status: 'deferred', reason: 'fixture' } })); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.model).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('integrates an existing exact helper, reuses its kernel check and returns its ready consumer', async () => { - const canonical = state.cooperation!.canonicalCommit!, original = committedSource(workers[0].worktree, - canonical, `${state.problem.projectRelative}/Submission.lean`); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(node()).toMatchObject({ status: 'integrated', attempts: 0, proof: { passed: true, changes: [] }, - integratedCheck: { passed: true, changes: [] } }); - expect(node().proof!.conditions ?? []).toEqual([]); - expect(freshlyAccepted(node(), taskVersion(node().task))).toBe(true); - expect(freshlyAccepted(JSON.parse(JSON.stringify(node())), taskVersion(node().task))).toBe(false); - expect(state.turns).toBe(0); expect(state.cooperation!.groups![0].turns).toBe(0); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ taskId: 'helper', kind: 'proof', status: 'verified' })); - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][1].expectedDeclarationType).toBe('True'); - expect(state.cooperation!.tasks.filter(item => item.task.kind === 'goal').every(item => - item.status === 'pending' && !item.proof)).toBe(true); - expect(state.check).toBeUndefined(); - expect(committedSource(workers[0].worktree, state.cooperation!.canonicalCommit!, - `${state.problem.projectRelative}/Submission.lean`)).toBe(original); - }); - - it.each(['different-type', 'extra-assumptions'] as const)('returns normal model work after a %s rejection without recording failure', async kind => { - if (kind === 'different-type') node().task = { ...node().task, type: 'False' }; - else writeCanonical(source('lemma helper (extra : False) : True := by trivial')); - rejectCandidate(); - const action = await next(); - expect(action).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - if (action?.kind !== 'task') throw new Error('expected_task_assignment'); - const context = directSolverModules.M4.build(state.problem, - { ...state, cooperation: cooperative.contextState(action, workers[1]) }, { - root: directory, worktree: workers[1].worktree, environment, retrievalRoot: directory, - taskText: 'Prove the original problem.', assignment: action, maxOptionalContextBytes: 0, - }); - for (const message of [context.message, context.continuationMessage]) - expect(message).toContain(mismatchMessage); - for (const message of [context.instructions, context.continuationMessage]) - expect(message).toContain('historical source diagnostic, not a model failure or a mathematical refutation'); - expect(action.assignment.canonicalProbe).toMatchObject({ evidence: 'advisory-canonical-check', proofAcceptance: 'not-accepted', - sourceCommit: action.assignment.seedCommit, environmentDigest: state.environmentDigest, verificationStatus: 'failed' }); - expect(action.assignment.canonicalProbe!.receiptIds).toHaveLength(1); - expect(context.manifest!.optionalBytes).toBe(0); - expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'assignment', required: true })); - expect(host.verify).toHaveBeenCalledOnce(); noDelivery(); - expect(node().status).toBe('running'); - expect(node().feedback).toBeUndefined(); expect(node().repair).toBeUndefined(); - }); - - it('preserves prior task feedback alongside the candidate diagnostic without charging a model failure', async () => { - node().feedback = 'Existing source correction remains relevant.'; - rejectCandidate(); - const action = await next(); - expect(action?.kind === 'task' && action.assignment.canonicalProbe?.feedback).toContain(mismatchMessage); - expect(node().feedback).toBe('Existing source correction remains relevant.'); - expect(node().sourceRepair).toBeUndefined(); noDelivery(); - expect(state.turns).toBe(0); expect(state.cooperation!.groups![0].turns).toBe(0); - }); - - it('keeps UTF-8 candidate diagnostics bounded before they become mandatory assignment input', async () => { - rejectCandidate('类型不符:' + '完整诊断'.repeat(3000)); - const action = await next(); - if (action?.kind !== 'task') throw new Error('expected_task_assignment'); - const feedback = action.assignment.canonicalProbe!.feedback; - expect(Buffer.byteLength(feedback)).toBeLessThanOrEqual(2000); - expect(feedback).toContain('类型不符'); expect(feedback).not.toContain('\uFFFD'); - noDelivery(); - }); - - it('preserves the advisory diagnostic through archive recovery without trusting it as proof', async () => { - rejectCandidate(); await next(); - const file = path.join(directory, 'state.json'); writeSolverRunState(file, state); - const restored = readSolverRunState(file), task = restored.cooperation!.tasks.find(item => item.task.id === 'helper')!; - expect(task.assignment!.canonicalProbe).toEqual(node().assignment!.canonicalProbe); - const context = directSolverModules.M4.build(restored.problem, restored, { - root: directory, worktree: workers[1].worktree, environment, retrievalRoot: directory, - taskText: 'Prove the original problem.', maxOptionalContextBytes: 0, - assignment: { kind: 'task', task: task.task, assignment: task.assignment! }, - }); - expect(context.message).toContain(mismatchMessage); expect(context.continuationMessage).toContain(mismatchMessage); - expect(task.proof).toBeUndefined(); expect(task.integratedCheck).toBeUndefined(); - expect(freshlyAccepted(task, taskVersion(task.task))).toBe(false); - expect(host.verify).toHaveBeenCalledOnce(); noDelivery(); - delete task.assignment!.canonicalProbe; writeSolverRunState(file, restored); - expect(readSolverRunState(file).cooperation!.tasks.find(item => item.task.id === 'helper')!.assignment!.canonicalProbe).toBeUndefined(); - }); - - it('rejects an archive that relabels an advisory candidate diagnostic as accepted proof', async () => { - rejectCandidate(); await next(); - const file = path.join(directory, 'state.json'); - (node().assignment!.canonicalProbe as any).proofAcceptance = 'kernel_verified'; - writeSolverRunState(file, state); - expect(() => readSolverRunState(file)).toThrow('math_resume_state_invalid:cooperation.tasks.0.assignment.canonicalProbe.proofAcceptance'); - noDelivery(); - }); - - it('shares the diagnostic only through the existing visible task scope', async () => { - node().task = { ...node().task, groupId: 'private', sharing: 'group' }; - const followup = state.cooperation!.tasks.find(item => item.task.id === 'followup')!; - followup.task = { ...followup.task, groupId: 'private', sharing: 'group' }; - state.cooperation!.groups!.push({ group: { id: 'private', objective: 'Private route', revision: 0, - status: 'active', maxConcurrent: 1 }, turns: 0 }); - rejectCandidate(); await next(); - const view = (index: number) => JSON.parse(fs.readFileSync(path.join(workers[index].worktree, 'COOPERATION.json'), 'utf8')); - for (const index of [0, 1]) expect(view(index).peers.find((item: any) => item.id === 'helper').canonicalProbe) - .toEqual(node().assignment!.canonicalProbe); - expect(view(2).peers.find((item: any) => item.id === 'helper').canonicalProbe).toBeUndefined(); - expect(JSON.stringify(view(2))).not.toContain(mismatchMessage); noDelivery(); - }); - - it('drops an unstarted assignment diagnostic before redispatching from repaired canonical source', async () => { - writeCanonical(source('lemma helper (extra : False) : True := by trivial')); - rejectCandidate(); const rejected = await next(); - if (rejected?.kind !== 'task') throw new Error('expected_task_assignment'); - expect(rejected.assignment.canonicalProbe?.feedback).toContain(mismatchMessage); - cooperative.release(workers[1], rejected); expect(node().assignment).toBeUndefined(); - writeCanonical(source()); - const ready = await next(); - expect(ready).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(node()).toMatchObject({ status: 'integrated', attempts: 0 }); - expect(node().assignment!.canonicalProbe).toBeUndefined(); - expect(ready?.kind === 'task' && ready.assignment.canonicalProbe).toBeUndefined(); - const view = JSON.parse(fs.readFileSync(path.join(workers[1].worktree, 'COOPERATION.json'), 'utf8')); - expect(view.peers.find((item: any) => item.id === 'helper').canonicalProbe).toBeUndefined(); - expect(host.verify).toHaveBeenCalledTimes(2); - }); - - it.each(['missing', 'wrong-namespace', 'ambiguous-leaf', 'sorry', 'admit', 'conditional', 'saved-assignment'] as const) - ('keeps %s work on the existing model path without a canonical check', async kind => { - if (kind === 'missing') writeCanonical(LOCAL_EXAMPLE_STATEMENT); - if (kind === 'wrong-namespace') node().task = { ...node().task, theoremName: 'Other.helper' }; - if (kind === 'ambiguous-leaf') writeCanonical(source('lemma Other.helper : True := by trivial\nlemma helper : True := by trivial')); - if (kind === 'sorry' || kind === 'admit') writeCanonical(source(`lemma helper : True := by ${kind}`)); - if (kind === 'conditional') node().task = { ...node().task, conditional: true }; - if (kind === 'saved-assignment') { - // A resumable assignment owns a checkout descended from its recorded seed. - git(workers[1].worktree, ['reset', '--hard', state.cooperation!.canonicalCommit!]); - node().assignment = { taskId: 'helper', taskDigest: taskVersion(node().task), - workerId: workers[1].id, seedCommit: state.cooperation!.canonicalCommit!, assignmentId: 'saved' }; - } - const savedAssignment = node().assignment; - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - if (kind === 'saved-assignment') expect(node().assignment).toBe(savedAssignment); - expect(host.verify).not.toHaveBeenCalled(); noDelivery(); - }); - - it('preserves normal conditional connection dispatch for unfinished dependencies', async () => { - const original = state.cooperation!.tasks.find(item => item.task.id === 'goal_0')!; - original.task = { ...original.task, status: 'active', dependsOn: ['helper'], ownerId: 'other' }; - node().task = { ...node().task, dependsOn: ['child'] }; - state.cooperation!.tasks.push({ task: { id: 'child', kind: 'lemma', theoremName: 'Tutorial.child', type: 'True', - proofPath: 'Submission.lean', objective: 'Unproved dependency', ownerId: 'other', revision: 0, dependsOn: [] }, - status: 'pending', attempts: 0 }); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'helper' }, assignment: { connectionCheck: expect.any(Object) } }); - expect(host.verify).not.toHaveBeenCalled(); noDelivery(); - }); - - it('leaves independent work dispatchable while awaiting the canonical check', async () => { - state.cooperation!.groups![0].group.maxConcurrent = 2; - const held = holdVerifier(), pending = next(); await held.entered; - expect(node()).toMatchObject({ status: 'pending', attempts: 0 }); - expect(node().assignment).toBeUndefined(); - expect(await next(2)).toMatchObject({ kind: 'task', task: { id: 'independent' } }); - held.release(); expect(await pending).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(host.verify).toHaveBeenCalledOnce(); - }); - - it.each(['canonical', 'contract', 'paused', 'route', 'lead-environment', 'worker-stopped'] as const) - ('discards a check whose %s changes while Lean is running', async change => { - const held = holdVerifier(), pending = next(); await held.entered; - if (change === 'canonical') { - git(workers[0].worktree, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', - 'commit', '--allow-empty', '--no-gpg-sign', '--quiet', '-m', 'New canonical']); - state.cooperation!.canonicalCommit = git(workers[0].worktree, ['rev-parse', 'HEAD']); - } - if (change === 'contract') node().task = { ...node().task, type: 'False', revision: node().task.revision + 1 }; - if (change === 'paused') node().task = { ...node().task, status: 'paused' }; - if (change === 'route') state.cooperation!.groups![0].group.status = 'paused'; - if (change === 'lead-environment') (cooperative as any).input.access.set(workers[0].id, { environment: {}, retrievalRoot: directory }); - if (change === 'worker-stopped') cooperative.stopped(workers[1]); - allowed = false; cooperative.modelBudgetChanged(); held.release(); - expect(await pending).toBeUndefined(); noDelivery(); - expect(node().assignment).toBeUndefined(); expect(node().status).toBe('pending'); - }); - - it('rechecks the canonical snapshot after waiting for the publication transaction', async () => { - const entered = deferred(), release = deferred(); - exclusive = async operation => { entered.resolve(); await release.promise; return operation(); }; - const pending = next(); await entered.promise; - expect(node().assignment).toBeUndefined(); - try { - git(workers[0].worktree, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', - 'commit', '--allow-empty', '--no-gpg-sign', '--quiet', '-m', 'New canonical before publication']); - state.cooperation!.canonicalCommit = git(workers[0].worktree, ['rev-parse', 'HEAD']); - allowed = false; cooperative.modelBudgetChanged(); - } finally { release.resolve(); } - expect(await pending).toBeUndefined(); noDelivery(); - expect(node().status).toBe('pending'); expect(node().assignment).toBeUndefined(); - }); - - it('waits for a cancelled canonical check to clean up before stop returns', async () => { - const held = holdVerifier(), pending = next(); await held.entered; - let stopped = false; - const stopping = cooperative.stop().then(() => { stopped = true; }); - await new Promise(resolve => setImmediate(resolve)); expect(stopped).toBe(false); - held.release(); expect(await pending).toBeUndefined(); await stopping; - expect(stopped).toBe(true); noDelivery(); expect(node().assignment).toBeUndefined(); - }); -}); diff --git a/tests/solverCapabilityFeedback.test.ts b/tests/solverCapabilityFeedback.test.ts deleted file mode 100644 index 6f64c171..00000000 --- a/tests/solverCapabilityFeedback.test.ts +++ /dev/null @@ -1,269 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import type { TaskProof } from '../src/solver/cooperativeProof'; -import type { DeliveryRecord } from '../src/solver/deliveries'; -import { GOAL_PROGRESS_REVIEW_MS, observeGoalProgress, type GoalProgressState } from '../src/solver/goalProgress'; -import { bindMathematicalGap, mathematicalGaps } from '../src/solver/mathematicalGaps'; -import { buildResearchContext } from '../src/solver/modules/context'; -import { captureObligationSnapshot } from '../src/solver/obligationProgress'; -import { captureProofReferences } from '../src/solver/proofReferences'; -import { commitSolverSources } from '../src/solver/problem'; -import { prepareResearchDelivery } from '../src/solver/researchAdmission'; -import { recordRouteBlockers, refreshRouteBlockers, type RouteBlocker } from '../src/solver/routeControl'; -import { automaticTaskConnection, createTaskConnectionCheck } from '../src/solver/taskConnections'; -import { invalidatedTaskIds, markTaskAcceptance, taskProofContractVersion, taskVersion, - type CooperativeAction, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState, type LocalExample } from './helpers/solver'; -import { receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ createSession: vi.fn() })); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const identity = { problemReceiptDigest: 'fixture-receipt', environmentDigest: 'feedback-environment' }; -const roots: string[] = []; -const running: { cooperation: CooperativeResearch; controller: AbortController }[] = []; -const fixture = () => { const result = localExample('solver-capability-feedback-'); roots.push(result.directory); return result; }; -const helper = (id: string, dependsOn: readonly string[] = []): CooperativeTask => ({ id, kind: 'lemma', - objective: `Prove ${id}.`, revision: 0, proofPath: 'Submission.lean', theoremName: `Tutorial.${id}`, type: 'True', dependsOn }); -const node = (task: CooperativeTask): TaskRecord => ({ task, status: 'pending', attempts: 0 }); -const goals = (example: LocalExample): CooperativeTask[] => example.problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, revision: 0, dependsOn: [], ...target, -})); -const assignment = (task: CooperativeTask, seedCommit: string) => ({ taskId: task.id, taskDigest: taskVersion(task), - workerId: 'peer', seedCommit, assignmentId: 'feedback-assignment', dependencies: [] }); -const proof = (task: CooperativeTask, conditions: NonNullable = [], references?: TaskProof['references']): TaskProof => { - const digest = taskVersion(task), commit = 'f'.repeat(40); - return { taskDigest: digest, seedCommit: commit, commit, sourceDigest: 'fixture-source', passed: true, conditions, - changes: [{ file: task.proofPath!, name: task.theoremName!, after: `lemma ${task.theoremName} : ${task.type} := by trivial\n` }], - projection: { ...identity, sourceDigest: 'fixture-source' }, ...(references ? { references } : {}), - verification: receiptBatch({ projectRoot: '/unused-fixture', targetCommit: commit, items: [{ - proofPath: task.proofPath!, theoremName: task.theoremName, statementHash: digest, leanStatementHash: digest, - }] }, { sessionId: 'feedback-verifier', receiptId: () => `feedback-${task.id}` }) }; -}; - -afterEach(async () => { - for (const instance of running.splice(0)) { instance.controller.abort(); await instance.cooperation.stop(); } - expect(host.createSession).not.toHaveBeenCalled(); - host.createSession.mockReset(); - vi.useRealTimers(); - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -describe('mathematical feedback consumed by the next turn', () => { - it.each(['lead', 'task'] as const)('keeps scoped negative evidence inline in full and same-thread %s contexts', role => { - const example = fixture(), goalTasks = goals(example), goal = goalTasks[0]!; - const research: CooperativeTask = { id: 'finite_tree_audit', kind: 'research', revision: 0, - objective: 'Determine whether the finite-tree identity supports the original estimate.', dependsOn: [goal.id] }; - const tasks = [...goalTasks.map(node), node(research)], sourceAssignment = assignment(research, example.problem.baseCommit); - const gap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, - previousGap: 'The proposed finite-tree identity was assumed to give the norm estimate.', - reduced: 'Exact arithmetic in the saved finite example gives 6 ≠ 4, excluding that identity.', - remaining: 'A bound for the actual segment norm, followed by completion and density, remains unproved.', - evidenceScope: 'One exact finite calculation; no Lean proof or general counterexample to the original theorem.', - reconsiderWhen: ['A different finite-tree estimate with a concrete application to the original norm.'] }; - const admission = prepareResearchDelivery({ kind: 'event', value: { conclusion: 'inconclusive', - summary: 'The proposed identity fails; the original norm estimate is still open.', mathematicalGap: gap, - remainingObligations: [gap.remaining], lemmaRequests: [] } }, { - source: research, assignment: sourceAssignment, tasks, - identity: { ...identity, problemReceiptDigest: example.problem.receiptDigest }, - }); - if (admission.status !== 'admitted') throw new Error('fixture-research-not-admitted'); - expect(admission.finding.conclusion).toBe('inconclusive'); - const delivery: DeliveryRecord = { id: 'finite-negative-evidence', kind: 'research', status: 'advisory', - producer: 'researcher', taskId: research.id, taskDigest: taskVersion(research), - statement: '', premises: [], dependencies: [], remainingObligations: [gap.remaining], - summary: admission.finding.summary, evidenceRefs: ['RESEARCH.md exact finite calculation'], createdAt: 1, - mathematicalGap: gap, mathematicalGapScope: admission.mathematicalGapScope }; - const cooperation: NonNullable = { tasks, deliveries: [delivery], - canonicalCommit: example.problem.baseCommit, groups: [{ group: { id: 'main', objective: 'Original target', status: 'active', revision: 0 }, turns: 0 }] }; - cooperation.mathematicalGaps = mathematicalGaps(cooperation, { ...identity, problemReceiptDigest: example.problem.receiptDigest }); - const action: CooperativeAction = role === 'lead' ? { kind: 'lead', seedCommit: example.problem.baseCommit, planVersion: 'fixed-plan' } - : { kind: 'task', task: goal, assignment: assignment(goal, example.problem.baseCommit) }; - const state = solverState(example.problem, example.workspace, { runId: 'feedback-context', phase: 'running', - environmentDigest: identity.environmentDigest, cooperation }); - const context = buildResearchContext(example.problem, state, { root: example.directory, worktree: example.workspace, - environment: {}, taskText: 'Prove the frozen original goal.', retrievalRoot: example.directory, - assignment: action, maxOptionalContextBytes: 0 }); - expect(context.manifest?.included).toContainEqual(expect.objectContaining({ id: 'mathematical-gaps', required: true })); - for (const message of [context.message, context.continuationMessage]) { - expect(message).toContain(gap.reduced); - expect(message).toContain(gap.remaining); - expect(message).toContain(gap.evidenceScope); - expect(message).toContain(gap.reconsiderWhen[0]); - expect(message).toContain('finite-negative-evidence'); - expect(message).toContain('current-contracts'); - } - expect(tasks.filter(item => item.task.kind === 'lemma')).toEqual([]); - expect(goalTasks[0]).toBe(goal); - }); - - it('keeps changed-scope evidence historical without silently changing the consumer objective', () => { - const goal: CooperativeTask = { ...helper('original'), kind: 'goal', objective: 'Prove the original target using the proposed identity.' }; - const source: CooperativeTask = { id: 'audit', kind: 'research', objective: 'Audit the identity.', revision: 0, dependsOn: [goal.id] }; - const tasks = [node(goal), node(source)]; - const gap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, previousGap: 'The identity was assumed.', - reduced: 'The identity failed at the recorded finite input.', remaining: 'Find a different argument.', - evidenceScope: 'Exact finite input only.', reconsiderWhen: ['Changed norm estimate.'] }; - const scope = bindMathematicalGap(gap, source, { tasks }, identity); - const delivery: DeliveryRecord = { id: 'negative', producer: 'peer', kind: 'research', status: 'advisory', - taskId: source.id, taskDigest: taskVersion(source), statement: '', premises: [], dependencies: [], - remainingObligations: [gap.remaining], summary: gap.reduced, evidenceRefs: ['saved finite input'], createdAt: 1, - mathematicalGap: gap, mathematicalGapScope: scope }; - tasks[1]!.task = { ...source, objective: 'Audit a different estimate.', revision: 1 }; - const entries = mathematicalGaps({ tasks, deliveries: [delivery] }, identity); - expect(entries).toMatchObject([{ reduced: gap.reduced, scopeStatus: 'historical-scope' }]); - expect(tasks[0]!.task.objective).toBe(goal.objective); - expect(entries[0]!.evidence).toBe('model-reported-advisory'); - }); - - it('preserves a live assignment for route hints and supersedes it for a changed mathematical responsibility', async () => { - const example = fixture(), lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'peer'); - const task: CooperativeTask = { id: 'construction', kind: 'research', objective: 'Find a finite-tree norm estimate.', - revision: 0, dependsOn: [], ownerId: peer.id, informalProof: 'Try the identity.' }; - const plan = parseCooperationPlan(example.problem, { tasks: [ - ...goals(example).map(goal => ({ ...goal, status: 'paused' })), task, - ] }); - const state = solverState(example.problem, example.workspace, { runId: 'feedback-assignment', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, tasks: plan.tasks.map(node), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const controller = new AbortController(), cooperation = cooperativeResearch({ state, workers: [lead, peer], - retrievalRoot: example.directory, signal: controller.signal }); - running.push({ cooperation, controller }); - const action = await cooperation.next(peer, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture-assignment-missing'); - expect(cooperation.started(peer, action)).toBe(true); - const interrupt = vi.fn(async () => {}); - cooperation.activate(peer, action, interrupt, async () => {}); - const edit = async (id: string, change: (current: CooperativeTask) => CooperativeTask) => { - fs.appendFileSync(path.join(example.directory, 'edits.jsonl'), JSON.stringify({ id, baseVersion: state.cooperation!.planVersion, - tasks: state.cooperation!.tasks.map(item => item.task.id === task.id ? change(item.task) : item.task) }) + '\n'); - await cooperation.pulse(lead.id); - expect(state.cooperation!.edits?.find(record => record.id === id)?.status).toBe('applied'); - }; - await edit('hint-only', current => ({ ...current, informalProof: 'The identity failed at 6 ≠ 4; try a norm estimate.', - citations: ['RESEARCH.md exact finite calculation'] })); - const preserved = state.cooperation!.tasks.find(item => item.task.id === task.id)!; - expect(preserved.assignment).toBe(action.assignment); - expect(preserved.status).toBe('running'); - expect(taskVersion(preserved.task)).toBe(taskVersion(task)); - expect(interrupt).not.toHaveBeenCalled(); - await edit('new-responsibility', current => ({ ...current, objective: 'Study completion and density instead.', revision: 1 })); - expect(state.cooperation!.tasks.find(item => item.task.id === task.id)?.assignment).toBeUndefined(); - expect(interrupt).toHaveBeenCalledOnce(); - }); - - it('invalidates actual helper contracts and consumers while keeping blueprint edits outside proof identity', () => { - const core = helper('core'), consumer = helper('consumer', [core.id]), records = [node(core), node(consumer)]; - const hinted = { ...core, informalProof: 'Another argument.', citations: ['checked source'] }; - expect(taskVersion(hinted)).toBe(taskVersion(core)); - expect(invalidatedTaskIds(records, [hinted, consumer], new Set(), new Map())).toEqual(new Set()); - const changed = { ...core, type: 'False', revision: 1 }; - expect(taskProofContractVersion(changed)).not.toBe(taskProofContractVersion(core)); - expect(invalidatedTaskIds(records, [changed, consumer], new Set(), new Map())).toEqual(new Set([core.id, consumer.id])); - }); -}); - -describe('mathematical progress and conditional connections', () => { - it('counts a namespaced connection once across renamed wrappers, receipt replay and changed notes', () => { - const example = fixture(), core = helper('core'), first = helper('bridgeA', [core.id]), second = helper('bridgeB', [core.id]); - const goal = { ...goals(example)[0]!, dependsOn: [first.id] }; - const file = path.join(example.receipt.projectRoot, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', - 'lemma core : True := by sorry\nlemma bridgeA : True := core\nlemma bridgeB : True := core\n\ntheorem add_zero')); - const sourceCommit = commitSolverSources(example.problem, example.workspace); - const references = (task: CooperativeTask) => { - const result = captureProofReferences(example.problem, example.workspace, sourceCommit, - { file: 'Submission.lean', name: task.theoremName! }, { statement: [], proof: task.id === core.id ? [] : - [{ file: 'Submission.lean', name: core.theoremName! }] }, - identity.environmentDigest); - if (!result) throw new Error('fixture-references-missing'); - expect(result.inputs).toContainEqual(expect.objectContaining({ name: task.id })); - return result; - }; - let tasks: TaskRecord[] = [node(core), node(first), node(goal)]; - let state: GoalProgressState | undefined; - vi.useFakeTimers(); vi.setSystemTime(0); - const observe = () => { - const result = observeGoalProgress(state, { ...identity, targets: [example.problem.targets[0]!], tasks, - snapshot: captureObligationSnapshot(tasks, { environmentDigest: identity.environmentDigest }), activeTaskIds: new Set([core.id]) }); - state = result.state; return result; - }; - observe(); - vi.setSystemTime(1000); - const conditions = [{ taskId: core.id, taskDigest: taskVersion(core) }]; - const firstProof = proof(first, conditions, references(first)); - tasks[1] = { ...node(first), status: 'conditional', proof: firstProof }; - expect(observe().resumed).toEqual([goal.id]); - expect(state!.goals[0]!.seenEvidence).toHaveLength(1); - vi.setSystemTime(2000); - const noted = { ...first, objective: 'Same connection with updated checkpoint notes.', informalProof: 'Retain the open core.' }; - const replay = proof(noted, conditions, references(first)); - replay.verification.results[0]!.receiptId = 'replayed-receipt'; - tasks[1] = { ...node(noted), status: 'conditional', proof: replay, feedback: 'Checkpoint notes saved.' }; - expect(observe().resumed).toEqual([]); - expect(state!.goals[0]!.activeMs).toBe(1000); - vi.setSystemTime(1000 + GOAL_PROGRESS_REVIEW_MS - 1); - const repeated = { ...second, objective: 'Same connection, renamed in the updated notes.', informalProof: 'No new mathematical input.' }; - tasks = [node(core), { ...node(repeated), status: 'conditional', proof: proof(repeated, conditions, references(second)) }, - node({ ...goal, dependsOn: [second.id] })]; - const stalled = observe(); - expect(stalled.resumed).toEqual([]); - expect(state!.goals[0]!.seenEvidence).toHaveLength(1); - expect(state!.goals[0]!.activeMs).toBe(GOAL_PROGRESS_REVIEW_MS - 1); - expect(stalled.requested).toBe(true); // The useful connection did not close the old frontier. - vi.setSystemTime(1000 + GOAL_PROGRESS_REVIEW_MS); - expect(observe().requested).toBe(false); - expect(state!.pending).toBeDefined(); - expect(state!.goals[0]!.closed).toBe(false); - expect(captureObligationSnapshot(tasks, { environmentDigest: identity.environmentDigest }).obligations - .find(item => item.taskId === second.id)).toMatchObject({ recordedProof: 'conditional', closed: false }); - vi.setSystemTime(1001 + GOAL_PROGRESS_REVIEW_MS); - const checkedCore = proof(core, [], references(core)); - tasks[0] = { ...node(core), status: 'integrated', proof: checkedCore, integratedCheck: checkedCore }; - expect(captureObligationSnapshot(tasks, { environmentDigest: identity.environmentDigest }).obligations - .find(item => item.taskId === core.id)).toMatchObject({ recordedProof: 'checked', closed: true }); - expect(observe().resumed).toEqual([goal.id]); - expect(state!.goals[0]!.activeMs).toBe(0); - expect(state!.pending).toBeUndefined(); - expect(state!.goals[0]!.closed).toBe(false); - }); - - it('checks typed-input sufficiency while definitions remain unavailable as assumed inputs', () => { - const core = helper('core'), consumer = { ...helper('consumer', [core.id]), kind: 'goal' as const }, tasks = [node(core), node(consumer)]; - expect(automaticTaskConnection(consumer, tasks)).toBe(true); - const dispatched = { ...assignment(consumer, 'seed'), dependencies: [{ taskId: core.id, taskDigest: taskVersion(core) }] }; - const connection = createTaskConnectionCheck(consumer, dispatched, tasks, identity); - expect(connection.assumedInputs).toEqual(dispatched.dependencies); - const candidate = proof(consumer, connection.assumedInputs); - tasks[1] = { ...node(consumer), status: 'conditional', proof: candidate }; - const snapshot = captureObligationSnapshot(tasks, { environmentDigest: identity.environmentDigest }); - expect(snapshot.goals).toMatchObject([{ closed: false }]); - const definition = { ...core, declaration: 'definition' as const, type: 'Nat' }; - expect(automaticTaskConnection(consumer, [node(definition), node(consumer)])).toBe(false); - }); - - it('parks only the repeated local inference and reopens for a newly checked relevant input', () => { - const core = helper('core'), consumer = helper('consumer', [core.id]), original = { ...helper('original', [consumer.id]), kind: 'goal' as const }; - const tasks = [node(core), node(consumer), node(original)], records: RouteBlocker[] = []; - const proposal = { mechanism: 'Exact finite identity fails: 6 ≠ 4.', scope: 'This identity at the recorded finite input only.', - evidenceRefs: ['RESEARCH.md exact finite calculation'], reopenOn: [{ kind: 'dependency-checked' as const, taskId: core.id }] }; - recordRouteBlockers(records, [proposal], consumer, tasks, identity.environmentDigest, identity.problemReceiptDigest, 1); - recordRouteBlockers(records, [proposal], consumer, tasks, identity.environmentDigest, identity.problemReceiptDigest, 2); - refreshRouteBlockers(records, tasks, identity.environmentDigest, identity.problemReceiptDigest, 3); - expect(tasks[1]!.routeParking).toEqual([records[0]!.id]); - expect(tasks[2]!.routeParking).toEqual([]); - tasks[1]!.task = { ...consumer, objective: 'Reworded route, same inference.', revision: 1, informalProof: 'Try again.' }; - expect(refreshRouteBlockers(records, tasks, identity.environmentDigest, identity.problemReceiptDigest, 4)).toEqual([]); - expect(records[0]!.status).toBe('parked'); - const checked = proof(core); markTaskAcceptance(checked); - tasks[0] = { ...node(core), status: 'integrated', proof: checked, integratedCheck: checked }; - expect(refreshRouteBlockers(records, tasks, identity.environmentDigest, identity.problemReceiptDigest, 5)) - .toMatchObject([{ status: 'reopened', reopenedReason: 'dependency-checked', evidenceStatus: 'advisory' }]); - expect(tasks[1]!.routeParking).toEqual([]); - expect(tasks[2]!.status).toBe('pending'); - }); -}); diff --git a/tests/solverCapacityCli.test.ts b/tests/solverCapacityCli.test.ts index 31fcd237..3cad7225 100644 --- a/tests/solverCapacityCli.test.ts +++ b/tests/solverCapacityCli.test.ts @@ -30,13 +30,13 @@ afterEach(() => { }); describe('CLI worker capacity', () => { - it.each([1, 4, 8])('accepts %i workers at both CLI and module-plan boundaries', async workers => { + it.each([1, 4, 8])('reads historical module plans for %i workers and rejects multi-worker launches', async workers => { expect(() => configurableSolverModules(defaultResearchModulePlan(), 'cooperative', workers)).not.toThrow(); - await expect(runSolver(['--workers', String(workers)], root)).rejects.toThrow('--workspace is required'); + await expect(runSolver(['--workers', String(workers)], root)).rejects.toThrow(workers === 1 ? '--workspace is required' : 'math_legacy_collaboration_retired'); }); it.each(['0', '-1', '9', '1.5', 'NaN', '9007199254740992'])('rejects invalid worker count %s before accessing a workspace', async workers => { - await expect(runSolver([`--workers=${workers}`], root)).rejects.toThrow('invalid --workers'); + await expect(runSolver([`--workers=${workers}`], root)).rejects.toThrow(/invalid --workers|math_legacy_collaboration_retired/u); expect(() => configurableSolverModules(defaultResearchModulePlan(), 'cooperative', Number(workers))) .toThrow('math_module_invalid_workers'); }); @@ -49,14 +49,14 @@ describe('CLI worker capacity', () => { expect(() => describeModuleExperiment(experiment, MAX_RESEARCH_WORKERS + 1)).toThrow('math_module_invalid_workers'); }); - it('documents the shared capacity in the CLI and example help', async () => { + it('documents native team capacity and historical examples', async () => { const log = vi.spyOn(console, 'log').mockImplementation(() => {}); expect(await runSolver(['--help'], root)).toBe(0); - expect(log).toHaveBeenCalledWith(expect.stringContaining('--workers 1..8')); + expect(log).toHaveBeenCalledWith(expect.stringContaining('--agent-team N')); const help = spawnSync('bun', ['scripts/mathematics/runExample.ts', '--help'], { cwd: root, encoding: 'utf8', timeout: 10_000 }); expect(help.status, help.stderr).toBe(0); - expect(help.stdout).toContain('--workers 1..8'); + expect(help.stdout).toContain('pinned historical revision'); }); it.each([8, 9])('validates the example argument and saved configuration for %i workers', workers => { @@ -68,7 +68,7 @@ describe('CLI worker capacity', () => { { cwd: root, encoding: 'utf8', timeout: 10_000 }); expect(result.status).toBe(1); if (workers === 8) { - expect(result.stderr).toContain(path.join(directory, 'workspace')); + expect(result.stderr).toContain('pinned historical TheoremOS revision'); expect(result.stderr).not.toContain('Invalid example case'); } else expect(result.stderr).toContain('--workers must be an integer from 1 to 8'); expect(fs.readdirSync(directory)).toEqual(['case.json']); diff --git a/tests/solverCapacityExploration.test.ts b/tests/solverCapacityExploration.test.ts deleted file mode 100644 index e9437f99..00000000 --- a/tests/solverCapacityExploration.test.ts +++ /dev/null @@ -1,671 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { requestLeadWake } from '../src/solver/leadWakes'; -import { readCooperationPlan } from '../src/solver/cooperationShared'; -import * as contextCompiler from '../src/solver/contextCompiler'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { captureObligationSnapshot } from '../src/solver/obligationProgress'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion, - type CooperativeAction, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -describe('host exploration for spare cooperative capacity', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const focuses = ['boundary', 'construction', 'decomposition', 'interface']; - let directory: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let pending: Promise[], events: { event: string; details?: Record }[]; - let interrupts: Map>, model: ReturnType; - let modelAllowed: boolean; - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - const overlays = () => state.cooperation!.tasks.filter(item => item.capacityExploration); - const provers = () => workers.filter(worker => worker.role === 'prover'); - const track = (promise: Promise) => { pending.push(promise); void promise.catch(() => {}); return promise; }; - const refresh = () => (cooperative as any).changed(); - const create = (overrides: Partial[0]> = {}) => { - const controller = new AbortController(); - const instance = cooperativeResearch({ state, workers, retrievalRoot: directory, continuousResearch: true, - signal: controller.signal, modelDispatchAllowed: () => modelAllowed, - emit: (event, details) => events.push({ event, details }), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: model }, - M2: { ...directSolverModules.M2, - check: async () => { throw new Error('fixture_unexpected_verifier'); }, - checkTask: async () => { throw new Error('fixture_unexpected_verifier'); } } }, ...overrides }); - instances.push({ cooperative: instance, controller }); - return instance; - }; - const activate = (worker: ResearchWorker, action: CooperativeAction) => { - expect(cooperative.started(worker, action)).toBe(true); - const interrupt = vi.fn(async () => {}); - interrupts.set(worker.id, interrupt); - cooperative.activate(worker, action, interrupt, async () => {}); - return action; - }; - const taskAction = (action: CooperativeAction | undefined) => { - if (action?.kind !== 'task') throw new Error('fixture_expected_task'); - return action; - }; - const claim = async (worker: ResearchWorker) => { - const action = taskAction(await track(cooperative.next(worker, budget))); - activate(worker, action); - return action; - }; - const startGeneralists = async () => { - for (const worker of workers.filter(peer => peer.role === 'researcher')) { - const action = await claim(worker); - expect(node(action.task.id).capacityExploration).toBeUndefined(); - } - }; - const startLead = async () => { - // Stand in for an ordinary Lead planning input; these cases only need a running Lead. - requestLeadWake(state.cooperation!.leadWakes!, 'research-finding'); refresh(); - const action = await track(cooperative.next(workers[0], budget)); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead'); - activate(workers[0], action); - return action; - }; - const plan = () => ({ tasks: state.cooperation!.tasks.filter(item => !item.capacityExploration).map(item => item.task), - groups: state.cooperation!.groups!.map(item => item.group) }); - const snapshot = () => captureObligationSnapshot(state.cooperation!.tasks, - { groups: state.cooperation!.groups, environmentDigest: state.environmentDigest }); - const waitForCapacity = async (worker: ResearchWorker, dispatchBudget = budget) => { - let settled = false; - const waiting = track(cooperative.next(worker, dispatchBudget)); - void waiting.then(() => { settled = true; }, () => {}); - // Drain dispatch continuations before a later input change wakes this waiter. - // Repeated microtask wakes can otherwise make the fixture lose its final notification. - await new Promise(resolve => setImmediate(resolve)); - expect(settled).toBe(false); - return { waiting }; - }; - const complete = async (worker: ResearchWorker, action: Extract) => { - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), '```math-result\n' + JSON.stringify({ - taskId: action.task.id, conclusion: 'inconclusive', - summary: `The ${node(action.task.id).capacityExploration?.focus ?? 'planned'} investigation leaves the original statement open.`, - }) + '\n```\n'); - cooperative.deactivate(worker); - await cooperative.deliver(worker, action, commitSolverSources(problem, worker.worktree)); - expect(node(action.task.id).status).toBe('completed'); - }; - const restart = async () => { - const file = path.join(directory, 'capacity-state.json'); - writeSolverRunState(file, state); - instances.at(-1)!.controller.abort(); - await cooperative.stop(); - state = readSolverRunState(file); cooperative = create(); - await cooperative.restore(); - }; - - beforeEach(() => { - const example = localExample('solver-capacity-exploration-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), - peerWorker(example, 'researcher-1'), peerWorker(example, 'researcher-2'), - ...[1, 2, 3, 4].map(index => peerWorker(example, `prover-${index}`, { role: 'prover' })), - peerWorker(example, 'engineer', { role: 'engineer' })]; - const initial = parseCooperationPlan(problem, { tasks: [ - ...[1, 2].map(index => ({ id: `planned_research_${index}`, kind: 'research', ownerId: `researcher-${index}`, - objective: `Investigate the distinct planned mathematical question ${index}.` })), - { id: 'busy_helper', kind: 'lemma', ownerId: 'engineer', objective: 'Prove the active original-goal frontier.', - proofPath: 'Submission.lean', theoremName: 'Tutorial.busy_helper', type: 'True' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', ownerId: 'engineer', - objective: `Prove ${target.theoremName}.`, theoremName: target.theoremName, proofPath: target.proofPath, - dependsOn: ['busy_helper'] })), - ], groups: [{ id: 'main', objective: 'Prove the original targets.', engineerId: 'engineer', maxConcurrent: 7 }] }); - state = solverState(problem, example.workspace, { runId: 'capacity-exploration-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: initial.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: initial.groups.map(group => ({ group, turns: 0 })) } }); - pending = []; events = []; instances = []; interrupts = new Map(); modelAllowed = true; - model = vi.fn(() => { throw new Error('fixture_real_models_forbidden'); }); - cooperative = create(); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - state.cooperation!.planEdited = true; (cooperative as any).syncPlanNotes(); - const busy = node('busy_helper'); - busy.status = 'running'; - busy.assignment = { taskId: busy.task.id, taskDigest: taskVersion(busy.task), workerId: 'engineer', - seedCommit: problem.baseCommit, assignmentId: 'long-running-original-frontier' }; - activate(workers.at(-1)!, { kind: 'task', task: busy.task, assignment: busy.assignment }); - }); - afterEach(async () => { - for (const instance of instances) instance.controller.abort(); - await Promise.allSettled(pending); - await Promise.allSettled(instances.map(instance => instance.cooperative.stop())); - expect(model).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('keeps all eight roles occupied by assigning four distinct methods without superseding a running Lead', async () => { - await startGeneralists(); - const lead = await startLead(), version = state.cooperation!.planVersion; - const mathematicalInput = snapshot(), notes = fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'utf8'); - const actions = await Promise.all(provers().map(claim)); - expect(actions.every(action => action.task.kind === 'research')).toBe(true); - expect(new Set(actions.map(action => action.task.id)).size).toBe(4); - expect(overlays().map(item => item.capacityExploration!.focus).sort()).toEqual(focuses); - expect(new Set(overlays().map(item => item.capacityExploration!.inputDigest)).size).toBe(1); - expect(new Set(overlays().map(item => item.capacityExploration!.targetTaskId))).toEqual(new Set(['busy_helper'])); - for (const [index, action] of actions.entries()) { - expect(action.assignment.workerId).toBe(provers()[index].id); - expect(action.task.ownerId).toBe(provers()[index].id); - expect(node(action.task.id).assignment).toBe(action.assignment); - expect(cooperative.current(action)).toBe(true); - } - expect((cooperative as any).active.size).toBe(8); - expect(state.cooperation!.groups![0].busy).toBe(7); - expect(state.cooperation!.capacityExplorationInputs).toHaveLength(4); - expect(events.filter(item => item.event === 'capacity_exploration_requested')).toHaveLength(4); - expect(state.cooperation!.planVersion).toBe(version); - expect((cooperative as any).planVersion()).toBe(version); - expect(snapshot()).toEqual(mathematicalInput); - expect(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - expect(readCooperationPlan(problem, workers[0].worktree).tasks.map(task => task.id)).not.toEqual( - expect.arrayContaining(actions.map(action => action.task.id))); - expect(cooperative.current(lead)).toBe(true); - for (const interrupt of interrupts.values()) expect(interrupt).not.toHaveBeenCalled(); - }); - - it.each(['live', 'final'] as const)('retains host TaskRecords and assignments when a %s Lead graph predates exploration', async publication => { - await startGeneralists(); - const lead = await startLead(), proposal = plan(), version = state.cooperation!.planVersion; - const action = await claim(provers()[0]), original = node(action.task.id), assignment = original.assignment; - expect(proposal.tasks.some(task => task.id === action.task.id)).toBe(false); - expect(cooperative.current(lead)).toBe(true); - if (publication === 'live') { - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(lead)!), JSON.stringify({ - kind: 'plan', dispatchNonce: lead.planNonce, baseVersion: lead.planVersion, - summary: 'Continue the useful original graph while the host explores independent approaches.', ...proposal, - }) + '\n'); - await cooperative.pulse(); - expect(events.filter(item => item.event === 'plan_published')).toHaveLength(1); - expect(cooperative.current(lead)).toBe(true); - } else { - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(proposal) + '\n```\n'); - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], lead, commitSolverSources(problem, workers[0].worktree)); - expect(events.some(item => item.event === 'plan_updated')).toBe(true); - } - expect(node(action.task.id)).toBe(original); - expect(node(action.task.id).assignment).toBe(assignment); - expect(node(action.task.id).status).toBe('running'); - expect(cooperative.current(action)).toBe(true); - expect(state.cooperation!.planVersion).toBe(version); - expect(interrupts.get(provers()[0].id)).not.toHaveBeenCalled(); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('preserves an exploration marker and assignment through a group revision with unchanged mathematical inputs', async () => { - await startGeneralists(); - const lead = await startLead(), proposal = plan(), version = state.cooperation!.planVersion; - const worker = provers()[0], action = await claim(worker), original = node(action.task.id); - const marker = original.capacityExploration, assignment = original.assignment; - proposal.groups = proposal.groups.map(group => ({ ...group, revision: group.revision + 1, - objective: 'Reorganize the same exact proof obligations under the revised group.' })); - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(lead)!), JSON.stringify({ - kind: 'plan', dispatchNonce: lead.planNonce, baseVersion: lead.planVersion, - summary: 'Revise group coordination while retaining the exact consumer and its inputs.', ...proposal, - }) + '\n'); - await cooperative.pulse(); - expect(events.filter(item => item.event === 'plan_published')).toHaveLength(1); - expect(state.cooperation!.planVersion).not.toBe(version); - expect(node(action.task.id)).toBe(original); - expect(original.capacityExploration).toBe(marker); - expect(original.assignment).toBe(assignment); - expect(original.status).toBe('running'); - expect(cooperative.current(action)).toBe(true); - expect(interrupts.get(worker.id)).not.toHaveBeenCalled(); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('retires an exploration when a new proof-route input changes its target without changing the target declaration', async () => { - // Make the original declarations the active frontier so the route change concerns this exact consumer. - for (const item of state.cooperation!.tasks) if (item.task.kind === 'goal') item.task = { ...item.task, dependsOn: [] }; - state.cooperation!.planVersion = (cooperative as any).planVersion(); - state.cooperation!.planEdited = true; (cooperative as any).syncPlanNotes(); refresh(); - await startGeneralists(); - const lead = await startLead(), worker = provers()[0], action = await claim(worker), original = node(action.task.id); - expect(original.capacityExploration!.targetTaskId).toBe('goal_0'); - const targetDigest = taskVersion(node('goal_0').task), ledger = structuredClone(state.cooperation!.capacityExplorationInputs); - const proposal = { ...plan(), proofRoutes: [{ id: 'new_consumer_route', targetTaskId: 'goal_0', - prerequisiteTaskIds: [], closingTaskId: 'busy_helper' }] }; - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(lead)!), JSON.stringify({ - kind: 'plan', dispatchNonce: lead.planNonce, baseVersion: lead.planVersion, - summary: 'Declare the exact closing input for the original consumer.', ...proposal, - }) + '\n'); - await cooperative.pulse(); - expect(events.filter(item => item.event === 'plan_published')).toHaveLength(1); - expect(state.cooperation!.proofRoutes).toEqual(proposal.proofRoutes); - expect(taskVersion(node('goal_0').task)).toBe(targetDigest); - expect(state.cooperation!.tasks.some(item => item.task.id === action.task.id)).toBe(false); - expect(cooperative.current(action)).toBe(false); - expect(interrupts.get(worker.id)).toHaveBeenCalledOnce(); - expect(state.cooperation!.capacityExplorationInputs).toEqual(ledger); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('rejects a base plan depending on a host exploration ID before changing the archive', async () => { - const action = await claim(provers()[0]), proposal = plan(); - proposal.tasks.push(action.task); - proposal.tasks = proposal.tasks.map(task => task.id === 'goal_0' - ? { ...task, dependsOn: [...task.dependsOn, action.task.id] } : task); - // The host ID is present, so parsing succeeds and the host boundary must reject its use as a premise. - const parsed = parseCooperationPlan(problem, proposal), before = JSON.stringify(state.cooperation); - await expect((cooperative as any).acceptPlan(parsed)).rejects.toThrow('math_plan_host_exploration_dependency'); - expect(JSON.stringify(state.cooperation)).toBe(before); - expect(cooperative.current(action)).toBe(true); - }); - - it('keeps exploration context and its advisory work contract mandatory with zero optional allowance', async () => { - const worker = provers()[0], action = await claim(worker), marker = node(action.task.id).capacityExploration!; - const compile = vi.spyOn(contextCompiler, 'compileTaskContext'); - const context = directSolverModules.M4.build(problem, - { ...state, cooperation: cooperative.contextState(action, worker) }, - { root: directory, worktree: worker.worktree, retrievalRoot: directory, environment: {}, - taskText: 'Investigate the assigned original-goal frontier.', assignment: action, maxOptionalContextBytes: 0 }); - const section = compile.mock.calls.at(-1)![0].mandatory?.find(item => item.id === 'capacity-exploration'); - expect(section).toMatchObject({ kind: 'assignment' }); - expect(section!.text).toContain(JSON.stringify(marker.targetTaskId)); - expect(section!.text).toContain(JSON.stringify(marker.focus)); - expect(section!.text).toContain('advisory only'); - expect(context.message).toContain(section!.text); - expect(context.workContract).toMatchObject({ stage: 'capacity-exploration', acceptance: 'advisory-only', - sourcePolicy: 'read-only', capacityExploration: { targetTaskId: marker.targetTaskId, focus: marker.focus } }); - expect(context.manifest).toMatchObject({ maxOptionalBytes: 0, optionalBytes: 0 }); - expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'capacity-exploration', kind: 'assignment', required: true })); - expect(context.manifest!.omitted).not.toContainEqual(expect.objectContaining({ id: 'capacity-exploration' })); - }); - - it('accepts a plan revision that retires a host exploration with an unadopted proposal', async () => { - await startGeneralists(); - const worker = provers()[0], action = await claim(worker); - const helper: CooperativeTask = { id: 'proposed_typed_bridge', kind: 'lemma', - objective: 'Prove the exact proposed consumer interface.', theoremName: 'Tutorial.proposed_typed_bridge', - proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - const finding = JSON.stringify({ taskId: action.task.id, conclusion: 'supporting', - summary: 'The spare-capacity investigation proposes an exact typed bridge.', lemmaRequests: [helper] }); - (cooperative as any).record(worker, action.task, 'research', 'advisory', - 'An exact typed bridge needs a Lead decision.', { finding, findingDigest: mathDigest(finding), lemmaRequests: [helper] }); - const byId = () => new Map(state.cooperation!.tasks.map(item => [item.task.id, item])); - expect(contextCompiler.leadResearchInputs(state.cooperation!.deliveries ?? [], byId())).toHaveLength(1); - const lead = await startLead(); - const proposal = plan(); - proposal.tasks = proposal.tasks.map(task => task.id === 'busy_helper' ? { ...task, revision: task.revision + 1 } : task); - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(lead)!), JSON.stringify({ - kind: 'plan', dispatchNonce: lead.planNonce, baseVersion: lead.planVersion, - summary: 'Revise the exact consumer without adopting the obsolete candidate interface.', ...proposal, - researchDecisions: [{ deliveryId: state.cooperation!.deliveries!.at(-1)!.id, outcome: 'decline', - reason: 'This proposed interface is obsolete after the consumer revision.' }], - }) + '\n'); - await cooperative.pulse(); - expect(events.filter(item => item.event === 'plan_published')).toHaveLength(1); - expect(state.cooperation!.tasks.some(item => item.task.id === action.task.id)).toBe(false); - expect(cooperative.current(action)).toBe(false); - // The retired source version no longer presents its proposal to Lead. - expect(contextCompiler.leadResearchInputs(state.cooperation!.deliveries ?? [], byId())).toEqual([]); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('leaves ordinary research forbidden to a Prover even when a custom M5 returns it', async () => { - vi.spyOn(directSolverModules.M5, 'assign').mockImplementation(ready => ready.find(item => item.task.kind === 'research')); - await expect(track(cooperative.next(provers()[0], budget))).rejects.toThrow('math_task_assignment_invalid'); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - expect(node('planned_research_1').status).toBe('pending'); - }); - - it('honors a custom M5 deferring already ready work without an automatic retry loop', async () => { - const assign = vi.spyOn(directSolverModules.M5, 'assign').mockImplementation(() => { - if (assign.mock.calls.length > 8) throw new Error('fixture_scheduler_busy_loop'); - return undefined; - }); - const { waiting } = await waitForCapacity(workers[1]); - expect(assign).toHaveBeenCalledOnce(); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - expect(node('planned_research_1').status).toBe('pending'); - assign.mockRestore(); - refresh(); - expect(taskAction(await waiting).task.id).toBe('planned_research_1'); - }); - - it('enforces an exploration owner at admission and prevents another Prover from claiming its saved assignment', async () => { - const owner = provers()[0], other = provers()[1], action = await claim(owner), original = node(action.task.id); - const attempts = original.attempts; - expect(() => cooperative.started(other, action)).toThrow('math_task_assignment_invalid'); - expect(original.attempts).toBe(attempts); - cooperative.deactivate(owner); cooperative.interrupted(owner, action); - vi.spyOn(directSolverModules.M5, 'assign').mockReturnValue(original); - await expect(track(cooperative.next(other, budget))).rejects.toThrow('math_task_assignment_invalid'); - expect(original.assignment).toBe(action.assignment); - expect(original.task.ownerId).toBe(owner.id); - }); - - it('uses planned research before creating exploration for a Researcher', async () => { - const worker = workers[1], planned = await claim(worker); - expect(planned.task.id).toBe('planned_research_1'); - expect(overlays()).toHaveLength(0); - await complete(worker, planned); - const exploration = await claim(worker); - expect(node(exploration.task.id).capacityExploration).toBeDefined(); - expect(exploration.task.ownerId).toBe(worker.id); - }); - - it('persists completed input/method tombstones and does not repeat them after process restore', async () => { - const mathematicalInput = snapshot(); - const actions = await Promise.all(provers().map(claim)); - for (const [index, action] of actions.entries()) await complete(provers()[index], action); - const ledger = structuredClone(state.cooperation!.capacityExplorationInputs), ids = overlays().map(item => item.task.id); - expect(snapshot()).toEqual(mathematicalInput); - await waitForCapacity(provers()[0]); - expect(state.cooperation!.capacityExplorationInputs).toEqual(ledger); - await restart(); - await waitForCapacity(provers()[0]); - expect(state.cooperation!.capacityExplorationInputs).toEqual(ledger); - expect(overlays().map(item => item.task.id)).toEqual(ids); - expect(overlays().every(item => item.status === 'completed')).toBe(true); - expect(events.filter(item => item.event === 'capacity_exploration_requested')).toHaveLength(4); - }); - - it('uses an idle Engineer for advisory exploration and yields when typed work becomes ready', async () => { - const engineer = workers.at(-1)!; - const busy = node('busy_helper'); - busy.task = { ...busy.task, ownerId: provers()[3]!.id }; - busy.status = 'running'; - busy.assignment = { taskId: busy.task.id, taskDigest: taskVersion(busy.task), workerId: provers()[3]!.id, - seedCommit: problem.baseCommit, assignmentId: 'engineer-capacity-frontier' }; - cooperative.deactivate(engineer); - state.cooperation!.groups![0]!.group = { ...state.cooperation!.groups![0]!.group, engineerId: undefined }; - for (const goal of state.cooperation!.tasks.filter(item => item.task.kind === 'goal')) { - goal.task = { ...goal.task, ownerId: undefined }; - goal.status = 'blocked'; - } - refresh(); - - const ready = directSolverModules.M3.ready(state.cooperation!.tasks, state.cooperation!.groups); - expect(ready.some(item => directSolverModules.M5.assign([item], engineer, workers.slice(1), - state.cooperation!.groups, state.cooperation!.tasks) === item)).toBe(false); - const action = await claim(engineer); - expect(node(action.task.id).capacityExploration).toMatchObject({ workerId: engineer.id }); - - const typed: TaskRecord = { task: { id: 'engineer_typed_work', kind: 'lemma', ownerId: engineer.id, - objective: 'Prove the exact newly available typed input.', proofPath: 'Submission.lean', - theoremName: 'Tutorial.engineer_typed_work', type: 'True', dependsOn: [], revision: 0 }, status: 'pending', attempts: 0 }; - state.cooperation!.tasks.push(typed); - const goal = state.cooperation!.tasks.find(item => item.task.kind === 'goal')!; - goal.task = { ...goal.task, dependsOn: [typed.task.id] }; - refresh(); - expect(cooperative.proofHandoffTarget(engineer, action)?.capacity === true).toBe(true); - }); - - it('resumes a running exploration with its original assignment rather than spending another method tombstone', async () => { - const worker = provers()[0], first = await claim(worker), assignment = structuredClone(first.assignment); - const metadata = structuredClone(node(first.task.id).capacityExploration), ledger = structuredClone(state.cooperation!.capacityExplorationInputs); - await restart(); - const restored = node(first.task.id); - expect(restored.status).toBe('pending'); - expect(restored.assignment).toEqual(assignment); - const resumed = await claim(worker); - expect(resumed.task.id).toBe(first.task.id); - expect(resumed.assignment).toBe(restored.assignment); - expect(resumed.assignment).toEqual(assignment); - expect(restored.capacityExploration).toEqual(metadata); - expect(state.cooperation!.capacityExplorationInputs).toEqual(ledger); - expect(events.filter(item => item.event === 'capacity_exploration_requested')).toHaveLength(1); - }); - - it.each([ - { name: 'finite turns', maxTurns: 20, remainingMs: Infinity, continuous: true, workerCount: 8 }, - { name: 'finite time', maxTurns: Infinity, remainingMs: 10_000, continuous: true, workerCount: 8 }, - { name: 'bounded campaign', maxTurns: Infinity, remainingMs: Infinity, continuous: false, workerCount: 8 }, - { name: 'four workers', maxTurns: Infinity, remainingMs: Infinity, continuous: true, workerCount: 4 }, - ])('does not create optional work for $name', async scenario => { - const selected = scenario.workerCount === 4 ? [workers[0], workers[1], provers()[0], workers.at(-1)!] : workers; - cooperative = create({ workers: selected, continuousResearch: scenario.continuous }); - await waitForCapacity(provers()[0], scenario); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - }); - - it('keeps an eight-worker team with a solving deadline off even when the timed gate would open', async () => { - const worker = provers()[0]; - state.workers!.find(item => item.id === worker.id)!.scheduling = { status: 'idle', since: Date.now() - 31 * 60_000 }; - state.cooperation!.leadDecisionBasisAt = Date.now() - 90 * 60_000; - state.cooperation!.idlePeerWake = { at: Date.now() - 5 * 60_000, workerIds: [worker.id], count: 2 }; - await waitForCapacity(worker, { maxTurns: Infinity, remainingMs: 2 * 60 * 60_000 }); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - }); - - it('waits for a group slot and only records a method when the slot becomes available', async () => { - const route = state.cooperation!.groups![0]; - route.group = { ...route.group, maxConcurrent: 1 }; refresh(); - const { waiting } = await waitForCapacity(provers()[0]); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - route.group = { ...route.group, maxConcurrent: 7 }; refresh(); - const action = taskAction(await waiting); - expect(node(action.task.id).capacityExploration).toBeDefined(); - expect(state.cooperation!.capacityExplorationInputs).toHaveLength(1); - }); - - it('does not consume exploration capacity while model dispatch is cooling down', async () => { - modelAllowed = false; - expect(await track(cooperative.next(provers()[0], budget))).toBeUndefined(); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - modelAllowed = true; cooperative.modelBudgetChanged(); - expect(node((await claim(provers()[0])).task.id).capacityExploration).toBeDefined(); - }); - - it('waits through worker recovery and creates exploration only after that worker is eligible again', async () => { - const worker = provers()[0], saved = state.workers!.find(record => record.id === worker.id)!; - saved.recovery = { phase: 'cooling-down', reason: 'fixture provider cooldown', cycles: 1, - startedAt: Date.now(), nextRetryAt: Date.now() + 10_000, waitedMs: 0 }; - const { waiting } = await waitForCapacity(worker); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - saved.recovery = undefined; refresh(); - expect(node(taskAction(await waiting).task.id).capacityExploration).toBeDefined(); - }); - - it.each(['paused', 'stopped'] as const)('retains a %s host exploration as controlled work without reviving or redispatching its method', async status => { - const actions = await Promise.all(provers().map(claim)); - const worker = provers()[0], action = actions[0], original = node(action.task.id); - const marker = original.capacityExploration, assignment = original.assignment; - const ledger = structuredClone(state.cooperation!.capacityExplorationInputs), before = snapshot(); - const proposal = plan(); - proposal.tasks.push({ ...action.task, status }); - await (cooperative as any).acceptPlan(parseCooperationPlan(problem, proposal)); - const matching = state.cooperation!.tasks.filter(item => item.task.id === action.task.id); - expect(matching).toHaveLength(1); - expect(matching[0]).toBe(original); - expect(original.task.status).toBe(status); - expect(original.capacityExploration).toBe(marker); - expect(original.assignment).toBe(assignment); - expect(cooperative.current(action)).toBe(false); - expect(cooperative.started(worker, action)).toBe(false); - expect(interrupts.get(worker.id)).toHaveBeenCalledOnce(); - expect(state.cooperation!.capacityExplorationInputs).toEqual(ledger); - expect(snapshot()).toEqual(before); - expect(state.cooperation!.error).toBeUndefined(); - for (const other of actions.slice(1)) expect(cooperative.current(other)).toBe(true); - cooperative.deactivate(worker); - await waitForCapacity(worker); - expect(overlays()).toHaveLength(4); - expect(node(action.task.id).task.status).toBe(status); - expect(state.cooperation!.capacityExplorationInputs).toEqual(ledger); - expect(events.filter(item => item.event === 'capacity_exploration_requested')).toHaveLength(4); - }); - - it('yields a running exploration for an owned typed task even when its current group slot is full', async () => { - const worker = provers()[0], action = await claim(worker), route = state.cooperation!.groups![0]; - route.group = { ...route.group, maxConcurrent: route.busy }; refresh(); - expect(cooperative.proofHandoffTarget(worker, action)?.capacity === true).toBe(false); - const typed: TaskRecord = { task: { id: 'ready_typed_step', kind: 'lemma', ownerId: worker.id, - objective: 'Prove the exact newly available interface.', proofPath: 'Submission.lean', - theoremName: 'Tutorial.ready_typed_step', type: 'True', dependsOn: [], revision: 0 }, status: 'pending', attempts: 0 }; - state.cooperation!.tasks.push(typed); - const goal = state.cooperation!.tasks.find(item => item.task.kind === 'goal')!; - goal.task = { ...goal.task, dependsOn: [typed.task.id] }; - refresh(); - expect(cooperative.proofHandoffTarget(worker, action)?.capacity === true).toBe(true); - typed.task = { ...typed.task, ownerId: provers()[1].id }; refresh(); - expect(cooperative.proofHandoffTarget(worker, action)?.capacity === true).toBe(false); - }); - describe('four workers with a solving deadline', () => { - const timedBudget = { maxTurns: Infinity, remainingMs: 2 * 60 * 60_000 }; - const researchers = () => workers.filter(worker => worker.role === 'researcher'); - const idleFor = (worker: ResearchWorker, ms: number) => { - const record = state.workers!.find(item => item.id === worker.id)!; - record.scheduling = { status: 'idle', since: Date.now() - ms }; - }; - const unanswered = (count: number, at = Date.now() - 5 * 60_000) => { - state.cooperation!.leadDecisionBasisAt = Date.now() - 90 * 60_000; - state.cooperation!.idlePeerWake = { at, workerIds: researchers().map(worker => worker.id), count }; - }; - const timedClaim = async (worker: ResearchWorker, dispatchBudget = timedBudget) => { - const action = taskAction(await track(cooperative.next(worker, dispatchBudget))); - activate(worker, action); - return action; - }; - beforeEach(() => { - // The campaign team: solver Lead, two Researchers and the Engineer holding the crux. - instances.at(-1)!.controller.abort(); - workers = [workers[0], ...researchers(), workers.at(-1)!]; - state.workers = state.workers!.filter(record => workers.some(worker => worker.id === record.id)); - for (const planned of ['planned_research_1', 'planned_research_2']) (node(planned) as unknown as { status: string }).status = 'completed'; - cooperative = create(); - const busy = node('busy_helper'); - activate(workers.at(-1)!, { kind: 'task', task: busy.task, assignment: busy.assignment! }); - }); - - it('explores the crux once per idle peer after two unanswered Lead wakes, decomposition before construction', async () => { - const [first, second] = researchers(), mathematicalInput = snapshot(), version = state.cooperation!.planVersion; - idleFor(first, 31 * 60_000); idleFor(second, 31 * 60_000); unanswered(2); - const decomposition = await timedClaim(first), construction = await timedClaim(second); - expect(node(decomposition.task.id).capacityExploration).toMatchObject({ targetTaskId: 'busy_helper', focus: 'decomposition', workerId: first.id }); - expect(node(construction.task.id).capacityExploration).toMatchObject({ targetTaskId: 'busy_helper', focus: 'construction', workerId: second.id }); - expect(events.filter(item => item.event === 'capacity_exploration_requested').map(item => item.details?.gate)) - .toEqual(['timed-idle', 'timed-idle']); - expect(state.cooperation!.planVersion).toBe(version); - expect(snapshot()).toEqual(mathematicalInput); - }); - - it('opens one exploration per idle wait and never repeats a method for the same consumer input', async () => { - const worker = researchers()[0]; - idleFor(worker, 31 * 60_000); unanswered(2); - const decomposition = await timedClaim(worker); - expect(node(decomposition.task.id).capacityExploration).toMatchObject({ targetTaskId: 'busy_helper', focus: 'decomposition' }); - await complete(worker, decomposition); - // The completed turn starts a new wait; re-polling at once must not open the next method. - const { waiting } = await waitForCapacity(worker, timedBudget); - expect(overlays()).toHaveLength(1); - idleFor(worker, 31 * 60_000); unanswered(2); refresh(); - const construction = taskAction(await waiting); - expect(node(construction.task.id).capacityExploration).toMatchObject({ targetTaskId: 'busy_helper', focus: 'construction' }); - activate(worker, construction); await complete(worker, construction); - // Both timed methods are tombstoned for this consumer input. - idleFor(worker, 31 * 60_000); unanswered(2); - await waitForCapacity(worker, timedBudget); - expect(overlays().map(item => item.capacityExploration!.focus)).toEqual(['decomposition', 'construction']); - expect(state.cooperation!.capacityExplorationInputs).toHaveLength(2); - }); - - it('takes the consumer with the most started turns as the crux', async () => { - const goal = node('goal_0'), second = parseCooperationPlan(problem, { tasks: [...plan().tasks, - { id: 'second_helper', kind: 'lemma', ownerId: 'engineer', objective: 'Prove the other original-goal input.', - proofPath: 'Submission.lean', theoremName: 'Tutorial.second_helper', type: 'True' }], - groups: plan().groups }).tasks.find(task => task.id === 'second_helper')!; - state.cooperation!.tasks.push({ task: second, status: 'pending', attempts: 5 }); - goal.task = { ...goal.task, dependsOn: ['busy_helper', 'second_helper'] }; - node('busy_helper').attempts = 2; - state.cooperation!.planVersion = (cooperative as any).planVersion(); - state.cooperation!.planEdited = true; (cooperative as any).syncPlanNotes(); refresh(); - const worker = researchers()[0]; - idleFor(worker, 31 * 60_000); unanswered(2); - expect(node((await timedClaim(worker)).task.id).capacityExploration).toMatchObject({ targetTaskId: 'second_helper', focus: 'decomposition' }); - }); - - it.each([ - { name: 'a peer waiting under 30 minutes', idle: 29 * 60_000 }, - { name: 'one unanswered Lead wake', count: 1 }, - { name: 'a peer that went idle after the last wake', wakeAgo: 40 * 60_000 }, - { name: 'under 10 minutes of solving time left', remainingMs: 9 * 60_000 }, - { name: 'a finite turn budget', maxTurns: 50 }, - ] as { name: string; idle?: number; count?: number; wakeAgo?: number; remainingMs?: number; maxTurns?: number }[])( - 'does not explore with $name', async scenario => { - const worker = researchers()[0]; - idleFor(worker, scenario.idle ?? 31 * 60_000); - unanswered(scenario.count ?? 2, Date.now() - (scenario.wakeAgo ?? 5 * 60_000)); - await waitForCapacity(worker, { maxTurns: scenario.maxTurns ?? Infinity, remainingMs: scenario.remainingMs ?? timedBudget.remainingMs }); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - }); - - it('keeps an unresolved idle episode eligible after a plan was accepted without executable work', async () => { - const worker = researchers()[0]; - idleFor(worker, 31 * 60_000); unanswered(2); - state.cooperation!.leadDecisionBasisAt = Date.now() - 60_000; - expect(node((await timedClaim(worker)).task.id).capacityExploration).toMatchObject({ focus: 'decomposition' }); - }); - - it('uses spare capacity alongside a planning Lead when two unanswered wakes matured, with 15 minutes left', async () => { - const worker = researchers()[0]; - unanswered(2); - const lead = await startLead(); - idleFor(worker, 31 * 60_000); - const before = snapshot(), version = state.cooperation!.planVersion; - const exploration = await timedClaim(worker, { ...timedBudget, remainingMs: 15 * 60_000 }); - expect(lead.kind).toBe('lead'); - expect(node(exploration.task.id).capacityExploration).toMatchObject({ focus: 'decomposition' }); - expect(cooperative.current(lead)).toBe(true); - expect(interrupts.get(workers[0].id)).not.toHaveBeenCalled(); - expect(state.cooperation!.planVersion).toBe(version); - expect(snapshot()).toEqual(before); - }); - - it.each(['another-peer', 'previous-episode', 'first-wake'] as const) - ('does not borrow aggregate unanswered wakes from %s', async scenario => { - const worker = researchers()[0], other = researchers()[1]; - idleFor(worker, 31 * 60_000); unanswered(2); - const wake = state.cooperation!.idlePeerWake!; - const since = state.workers!.find(item => item.id === worker.id)!.scheduling!.since; - wake.count = 8; - wake.episodes = scenario === 'another-peer' - ? { [other.id]: { since, at: wake.at, count: 2 } } - : { [worker.id]: { since: scenario === 'previous-episode' ? since - 60_000 : since, - at: wake.at, count: scenario === 'first-wake' ? 1 : 2 } }; - await waitForCapacity(worker, timedBudget); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - }); - - it('does not let a legacy wake naming only another peer open exploration', async () => { - const worker = researchers()[0]; - idleFor(worker, 31 * 60_000); unanswered(2); - state.cooperation!.idlePeerWake!.workerIds = [researchers()[1].id]; - await waitForCapacity(worker, timedBudget); - expect(overlays()).toHaveLength(0); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - }); - - it('re-dispatches a waiting peer when its wait reaches 30 minutes', async () => { - const worker = researchers()[0]; - idleFor(worker, 30 * 60_000 - 3_000); unanswered(2); - const { waiting } = await waitForCapacity(worker, timedBudget); - expect(overlays()).toHaveLength(0); - const since = state.workers!.find(item => item.id === worker.id)!.scheduling!.since; - expect((cooperative as any).explorationTimer?.at).toBe(since + 30 * 60_000); - expect(node(taskAction(await waiting).task.id).capacityExploration).toMatchObject({ focus: 'decomposition' }); - }, 30_000); - }); -}); diff --git a/tests/solverCompactProjection.test.ts b/tests/solverCompactProjection.test.ts index 6256a29e..dd06146a 100644 --- a/tests/solverCompactProjection.test.ts +++ b/tests/solverCompactProjection.test.ts @@ -9,7 +9,6 @@ import { taskVersion, type CooperativeTask, type TaskAssignment } from '../src/s import { localExample } from './helpers/solver'; import { failedBatch, receiptBatch } from './helpers/verifier'; import { compactTaskSources } from '../src/solver/taskProjection'; -import { cooperativeResearch } from './helpers/cooperation'; import { leadWorker, solverState } from './helpers/solver'; const host = vi.hoisted(() => ({ verify: vi.fn() })); @@ -101,25 +100,6 @@ describe('compact single-task proof checks', () => { expect(host.verify).toHaveBeenCalledTimes(2); }); - it('validates compact evidence through the normal host seam, including a custom checker wrapper', async () => { - const commit = write(source()), raw = await check(commit); - const worker = leadWorker(problem, workspace), action = assignment(commit); - const state = solverState(problem, workspace, { runId: 'compact-host', phase: 'running', - cooperation: { canonicalCommit: commit, tasks: [{ task, assignment: action, status: 'delivered', proof: raw, attempts: 1 }] } }); - const cooperative = cooperativeResearch({ state, workers: [worker], retrievalRoot: workspace, - access: new Map([[worker.id, { environment: env, retrievalRoot: workspace }]]), signal: controller.signal, - exclusiveCheck: operation => operation() }); - try { - const custom = (...args: Parameters) => checkTaskProof(...args); - const modules = (cooperative as any).input.modules; - (cooperative as any).input.modules = { ...modules, M2: { ...modules.M2, checkTask: custom } }; - expect(await (cooperative as any).check(task, action, workspace, commit, [], raw)).toMatchObject({ passed: true }); - const forged = structuredClone(raw); - await expect((cooperative as any).check(task, action, workspace, commit, [], forged)) - .rejects.toThrow('math_task_check_identity_changed'); - } finally { await cooperative.stop(); } - }); - it('does not retry infrastructure failures as a full projection', async () => { host.verify.mockImplementation(async request => ({ ...verified(request), status: 'unavailable', results: verified(request).results.map(result => ({ ...result, status: 'unavailable', error: 'verifier unavailable' })) })); diff --git a/tests/solverCompletedGuidance.test.ts b/tests/solverCompletedGuidance.test.ts deleted file mode 100644 index 60c03ced..00000000 --- a/tests/solverCompletedGuidance.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentSession } from '../src/runtime/codexSession'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { readHumanGuidance } from '../src/solver/humanGuidance'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { runResearchWorkers } from '../src/solver/research'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { WorkerProofLifecycle } from '../src/solver/workerProofLifecycle'; -import { workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const runtime = vi.hoisted(() => ({ verify: vi.fn() })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), checkManyFormalVerifications: runtime.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); - -describe('completed final guidance before ordinary plan delivery', () => { - const cleanups: (() => Promise)[] = []; - afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); vi.restoreAllMocks(); }); - - async function fixture(mode: 'accepted' | 'published-plan' | 'proof-intercept' | 'interrupted' | 'stale-turn' | 'wrong-owner' | - 'wrong-scope' | 'unknown-evidence' | 'invalid-candidate') { - runtime.verify.mockReset().mockImplementation(() => { throw new Error('fixture_unexpected_proof_check'); }); - const example = localExample('solver-completed-guidance-', 'lead'); - const { directory, workspace, problem } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'engineer', { role: 'engineer' })]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, - })) }); - const state = solverState(problem, workspace, { runId: 'completed-guidance-fixture', phase: 'prepared', planApproval: true, - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - if (mode === 'proof-intercept') { - state.planApproval = false; - state.cooperation!.tasks.forEach((node, index) => { - node.task.status = index === 0 ? 'active' : 'paused'; node.task.ownerId = workers[1].id; - }); - } - const stateFile = path.join(directory, 'state.json'), guidanceFile = path.join(directory, 'human-guidance.json'); - const now = new Date().toISOString(), guidanceId = 'explicit-direction'; - fs.writeFileSync(guidanceFile, JSON.stringify({ schema: 'theorem-os.human-guidance.v1', runId: state.runId, records: [{ - id: guidanceId, recipient: mode === 'proof-intercept' ? { kind: 'task', id: 'goal_0' } : { kind: 'lead' }, - ...(mode === 'proof-intercept' ? { taskRef: { id: 'goal_0', version: taskVersion(state.cooperation!.tasks[0].task) } } : {}), - text: 'Revise the exact route and report your handling decision.', - observationRef: { sequence: 1, stateDigest: 'a'.repeat(64) }, status: 'queued', createdAt: now, updatedAt: now, - }] })); - const controller = new AbortController(); - let cooperation!: CooperativeResearch, deliveredBeforePlan = false; - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(function (this: CooperativeResearch) { cooperation = this; }); - const deliver = CooperativeResearch.prototype.deliver; - vi.spyOn(CooperativeResearch.prototype, 'deliver').mockImplementation(function (this: CooperativeResearch, ...args) { - deliveredBeforePlan = readHumanGuidance(stateFile, state.runId)[0]?.decision?.status === 'accepted'; - return deliver.apply(this, args); - }); - let deliveredBeforeProofIntercept = false; - if (mode === 'proof-intercept') vi.spyOn(WorkerProofLifecycle.prototype, 'settleTurn').mockImplementation(async action => { - if (action?.kind !== 'task') throw new Error('fixture_unexpected_proof_intercept'); - deliveredBeforeProofIntercept = readHumanGuidance(stateFile, state.runId)[0]?.decision?.status === 'accepted'; - return true; - }); - let response: MathAgentSession['lastCompletedResponse']; - let receivedGuidance = false, originalVersion: string | undefined; - const execute = directSolverModules.M1.execute; - const modules: SolverModules = { ...directSolverModules, - M1: { ...directSolverModules.M1, - execute: async (...args) => { - const candidate = await execute(...args); - return mode === 'invalid-candidate' ? { ...candidate, worktree: path.join(directory, 'foreign') } : candidate; - }, - open: async (): Promise => ({ threadId: 'current-thread', - get lastCompletedResponse() { return response; }, - interrupt: async () => {}, close: async () => {}, - notify: async message => { receivedGuidance = message.includes(guidanceId); }, - run: async (message, _id, worktree, onStarted) => { - const action = JSON.parse(message) as CooperativeAction; - if (mode === 'proof-intercept' ? action.kind !== 'task' : action.kind !== 'lead') - throw new Error('fixture_unexpected_model_responsibility'); - originalVersion = action.kind === 'lead' ? action.planVersion : undefined; - onStarted('current-turn'); - await cooperation.pulse(mode === 'proof-intercept' ? workers[1].id : workers[0].id); - expect(receivedGuidance).toBe(true); - if (mode === 'wrong-owner' || mode === 'wrong-scope') { - const records = readHumanGuidance(stateFile, state.runId); - if (mode === 'wrong-owner') records[0].deliveredTo = [workers[1].id]; - else records[0].deliveredScope = { planVersion: 'previous-plan-version' }; - fs.writeFileSync(guidanceFile, JSON.stringify({ schema: 'theorem-os.human-guidance.v1', runId: state.runId, records })); - } - const tasks = state.cooperation!.tasks.map(node => ({ ...node.task, objective: node.task.objective + ' Use the revised route.' })); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), JSON.stringify({ tasks })); - if (mode === 'published-plan' && action.kind === 'lead') { - fs.appendFileSync(path.join(workspace, leadPlanDeliveryFile(action)!), JSON.stringify({ - kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, tasks, - }) + '\n'); - await cooperation.pulse(workers[0].id); - expect(state.cooperation!.planVersion).not.toBe(originalVersion); - } - // The final contains no accepted plan. Its decoy task and proof must never enter the archive. - response = { turnId: mode === 'stale-turn' ? 'previous-turn' : 'current-turn', text: '```json\n' + JSON.stringify({ - status: 'plan_revised', tasks: [{ id: 'final-only-decoy' }], proof: 'not accepted', - guidanceDecisions: [{ guidanceId, status: 'accepted', reason: 'The exact requested route is relevant.', - evidenceRefs: mode === 'unknown-evidence' ? [{ kind: 'task', id: 'final-only-decoy', version: 'unknown' }] : [] }], - }) + '\n```' }; - return mode === 'interrupted' ? 'interrupted' : 'completed'; - }, - }), - }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Offline completed guidance fixture.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }) }, - }; - const events: { event: string; details?: Record }[] = []; - const completion = runResearchWorkers({ state, workers, modules, access: workerAccess(workers, directory), - root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the frozen original goals.', - executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, deadline: Infinity, - maxTurns: 1, maxTurnMs: Infinity, maxTotalTokens: 0, save: () => {}, emit: (event, details) => events.push({ event, details }) }); - void completion.catch(() => {}); - cleanups.push(async () => { controller.abort(); await Promise.allSettled([completion]); fs.rmSync(directory, { recursive: true, force: true }); }); - return { state, stateFile, completion, events, deliveredBeforePlan: () => deliveredBeforePlan, - deliveredBeforeProofIntercept: () => deliveredBeforeProofIntercept, originalVersion: () => originalVersion }; - } - - it('records the exact completed final decision before accepting the saved file plan', async () => { - const f = await fixture('accepted'); - expect(await f.completion).toBeUndefined(); - expect(f.deliveredBeforePlan()).toBe(true); - expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toMatchObject({ - status: 'accepted', workerId: 'solver', sourcePlanVersion: f.originalVersion(), evidenceRefs: [], - }); - expect(f.state.cooperation!.planVersion).not.toBe(f.originalVersion()); - expect(f.state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_0', 'goal_1']); - expect(f.state.cooperation!.tasks.every(node => node.task.objective.endsWith('Use the revised route.'))).toBe(true); - expect(f.state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - expect(f.state.check).toBeUndefined(); - expect(runtime.verify).not.toHaveBeenCalled(); - }); - - it('binds a final decision to its original dispatch after that turn published a revised plan', async () => { - const f = await fixture('published-plan'); await f.completion; - expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toMatchObject({ - status: 'accepted', sourcePlanVersion: f.originalVersion(), - }); - expect(f.state.cooperation!.planVersion).not.toBe(f.originalVersion()); - expect(f.state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_0', 'goal_1']); - }); - - it('records an Engineer final before the typed proof lifecycle takes over the source delivery', async () => { - const f = await fixture('proof-intercept'); await f.completion; - expect(f.deliveredBeforeProofIntercept()).toBe(true); - expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toMatchObject({ - status: 'accepted', workerId: 'engineer', sourceTaskRef: { id: 'goal_0', version: taskVersion(f.state.cooperation!.tasks[0].task) }, - }); - expect(f.state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - expect(runtime.verify).not.toHaveBeenCalled(); - }); - - it.each(['interrupted', 'stale-turn', 'wrong-owner', 'wrong-scope', 'unknown-evidence', 'invalid-candidate'] as const) - ('keeps the guidance undecided for %s', async mode => { - const f = await fixture(mode); - if (mode === 'invalid-candidate') await expect(f.completion).rejects.toThrow('math_candidate_identity_changed'); - else await f.completion; - expect(readHumanGuidance(f.stateFile, f.state.runId)[0].decision).toBeUndefined(); - expect(f.deliveredBeforePlan()).toBe(false); - if (mode === 'wrong-owner' || mode === 'wrong-scope' || mode === 'unknown-evidence') - expect(f.events.some(item => item.event === 'human_guidance_decision_rejected')).toBe(true); - expect(f.state.check).toBeUndefined(); - expect(runtime.verify).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/solverConditionalIntegration.test.ts b/tests/solverConditionalIntegration.test.ts deleted file mode 100644 index fae3e6cf..00000000 --- a/tests/solverConditionalIntegration.test.ts +++ /dev/null @@ -1,268 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LEAN_EVAL_BENCHMARK_COMMIT } from '../src/math/leanEvalCatalogAdapter'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { inspectLeanDeclarationRegions, inspectScopedLeanDeclarations } from '../src/math/leanSource'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { readCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git, readSolverProblem, type SolverProblem } from '../src/solver/problem'; -import type { CooperativeAction, CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch, workerDeliveryModules } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -describe('conditional proof declaration ownership', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let cooperative: CooperativeResearch; - let requiredParentHelpers: { file: string; name: string }[]; - let projections: { theoremName: string; files: Record }[]; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - type TaskAction = Extract; - - const sourcePath = (worker: ResearchWorker) => path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - const source = (worker: ResearchWorker) => fs.readFileSync(sourcePath(worker), 'utf8'); - const canonicalSource = () => committedSource(workspace, state.cooperation!.canonicalCommit!, - `${problem.projectRelative}/Submission.lean`); - const node = (id: string) => state.cooperation!.tasks.find(node => node.task.id === id)!; - const create = () => { - const controller = new AbortController(); - const cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - modules: workerDeliveryModules }); - instances.push({ cooperative, controller }); - return cooperative; - }; - const assigned = async (worker: ResearchWorker) => { - const action = await cooperative.next(worker, budget); - expect(action?.kind).toBe('task'); - if (action?.kind !== 'task') throw new Error('fixture_missing_task'); - expect(cooperative.started(worker, action)).toBe(true); - return action; - }; - const deliverParent = async (declaration = '', files: Record = {}, helper = 'support', imports: string[] = []) => { - const parent = await assigned(workers[2]); - expect(parent.task.id).toBe('goal_0'); - fs.writeFileSync(sourcePath(workers[2]), imports.map(module => `import ${module}\n`).join('') + source(workers[2]) - .replace('theorem add_zero', declaration + 'lemma support : True := by trivial\ntheorem add_zero') - .replace('n + 0 = n := by sorry', `n + 0 = n := by\n have h : True := And.left (And.intro child ${helper})\n rfl`)); - for (const [file, content] of Object.entries(files)) - fs.writeFileSync(path.join(workers[2].worktree, problem.projectRelative, file), content); - await cooperative.deliver(workers[2], parent, commitSolverSources(problem, workers[2].worktree)); - expect(node('goal_0').status).toBe('conditional'); - return parent; - }; - const deliverChild = async (child: TaskAction) => { - fs.writeFileSync(sourcePath(workers[1]), source(workers[1]) - .replace('theorem add_zero', 'lemma child : True := by trivial\ntheorem add_zero')); - await cooperative.deliver(workers[1], child, commitSolverSources(problem, workers[1].worktree)); - expect(node('child').status).toBe('integrated'); - }; - - beforeEach(async () => { - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const files = Object.fromEntries(problem.ownedFiles.filter(file => file.endsWith('.lean')) - .map(file => [file, fs.readFileSync(path.join(request.projectRoot, file), 'utf8')])); - for (const item of request.items) projections.push({ theoremName: item.theoremName, files }); - const result = verifiedBatch(request, { sessionId: 'conditional-fixture' }); - const parent = request.items.find(item => item.theoremName.endsWith('.add_zero')); - const namespace = parent?.theoremName.split('.').slice(0, -1).join('.'); - const target = parent && inspectLeanDeclarationRegions(files[parent.proofPath] ?? '').find(item => item.name === 'add_zero'); - const usesSupport = target && /\bsupport\b/u.test(files[parent!.proofPath]!.slice(target.startOffset, target.endOffset)); - // Compact rechecks may omit the inherited support lemma when this parent uses a different helper. - const required = parent ? [...(usesSupport ? [{ file: 'Submission.lean', name: `${namespace}.support` }] : []), - ...requiredParentHelpers] : []; - const missing = required.some(helper => !inspectScopedLeanDeclarations(files[helper.file] ?? '') - .some(declaration => declaration.qualifiedName === helper.name)); - return missing || Object.values(files).some(source => /\b(?:sorry|admit)\b/u.test(source)) ? { ...result, status: 'failed', - results: result.results.map(item => ({ ...item, status: 'failed', error: 'fixture_missing_local_declaration_or_unfinished_proof' })) } : result; - }); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('solver-conditional-integration-'); - ({ directory, workspace, problem } = example); - workers = [leadWorker(problem, workspace), ...(['researcher', 'engineer'] as const).map(id => peerWorker(example, id, { role: id }))]; - const tasks: CooperativeTask[] = [{ id: 'child', kind: 'lemma', objective: 'Prove a reusable child.', - theoremName: 'Tutorial.child', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0, - ownerId: 'researcher' }, ...problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal' as const, objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: index === 0 ? ['child'] : [], - revision: 0, ownerId: 'engineer', conditional: index === 0, status: index === 0 ? 'active' as const : 'paused' as const, - }))]; - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ tasks }) + '\n```'); - state = solverState(problem, workspace, { runId: 'conditional-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, tasks: [] } }); - instances = []; requiredParentHelpers = []; projections = []; - cooperative = create(); - await cooperative.restore(); - }); - afterEach(async () => { - for (const instance of instances) { instance.controller.abort(); await instance.cooperative.stop(); } - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['absent', 'placeholder', 'proved-draft']) - ('integrates a parent with its child declaration %s and preserves its own helpers', async variant => { - const child = await assigned(workers[1]); - const declaration = variant === 'absent' ? '' : `lemma child : True := by ${variant === 'placeholder' ? 'sorry' : 'exact True.intro'}\n`; - await deliverParent(declaration); - expect(node('goal_0').proof!.conditions).toHaveLength(1); - expect(node('goal_0').proof!.changes.map(change => change.name)).toEqual(['add_zero', 'support']); - - await deliverChild(child); - - expect(node('goal_0')).toMatchObject({ status: 'integrated', attempts: 1, integratedCheck: { passed: true } }); - expect(canonicalSource()).toContain('lemma child : True := by trivial'); - expect(canonicalSource()).toContain('lemma support : True := by trivial'); - expect(canonicalSource()).toContain('have h : True := And.left (And.intro child support)'); - const parentChecks = projections.filter(item => item.theoremName === 'Tutorial.add_zero') - .map(item => item.files['Submission.lean']); - expect(parentChecks).toHaveLength(2); - expect(parentChecks[0]).toContain('theorem add_zero : theorem_os_conditional_type%'); - expect(parentChecks[1]).toContain('theorem add_zero (n : Nat)'); - expect(parentChecks[1]).toContain('lemma child : True := by trivial'); - }); - - it.each(['Other.child', 'Tutorial.Other.child', '_root_.Tutorial.Other.child']) - ('preserves a required helper sharing the assumed child\'s leaf name when referenced as %s', async reference => { - const child = await assigned(workers[1]); - requiredParentHelpers.push({ file: 'Submission.lean', name: 'Tutorial.Other.child' }); - const module = 'Mathlib.Data.Nat.Basic'; - await deliverParent('lemma Other.child : True := by trivial\n', {}, reference, [module]); - expect(node('goal_0').proof!.changes.map(change => change.name)).toEqual(['add_zero', 'Other.child', 'support']); - expect(node('goal_0').proof!.imports).toEqual([{ file: 'Submission.lean', module }]); - - await deliverChild(child); - - expect(node('goal_0').status).toBe('integrated'); - expect(canonicalSource()).toContain('lemma Other.child : True := by trivial'); - expect(canonicalSource()).toContain('lemma child : True := by trivial'); - expect(canonicalSource()).toContain(`And.intro child ${reference}`); - expect(canonicalSource()).toContain(`import ${module}`); - }); - - it('preserves wrappers on a different qualified helper while removing wrappers on the actual assumption', async () => { - const child = await assigned(workers[1]); - requiredParentHelpers.push({ file: 'Submission.lean', name: 'Tutorial.Other.child' }, - { file: 'Submission.lean', name: 'Tutorial.Other.wrapper' }); - await deliverParent('lemma Other.child : True := by trivial\n' + - 'lemma Other.wrapper : True := Other.child\nlemma dependent : True := Tutorial.child\n', {}, 'Other.wrapper'); - const projected = projections.find(item => item.theoremName === 'Tutorial.add_zero')!.files['Submission.lean']; - expect(projected).toContain('lemma Other.child : True := by trivial'); - expect(projected).toContain('lemma Other.wrapper : True := Other.child'); - expect(projected).not.toContain('lemma dependent'); - - await deliverChild(child); - - expect(node('goal_0').status).toBe('integrated'); - expect(canonicalSource()).toContain('lemma dependent : True := Tutorial.child'); - expect(canonicalSource()).toContain('And.intro child Other.wrapper'); - }); - - it('preserves a required helper whose local binder shadows the assumed child', async () => { - const child = await assigned(workers[1]); - requiredParentHelpers.push({ file: 'Submission.lean', name: 'Tutorial.independent' }); - await deliverParent('lemma independent (child : True) : True := by exact child\n', {}, '(independent support)'); - - await deliverChild(child); - - expect(node('goal_0').status).toBe('integrated'); - expect(canonicalSource()).toContain('lemma independent (child : True) : True := by exact child'); - expect(canonicalSource()).toContain('And.intro child (independent support)'); - }); - - it.each([false, true])('preserves the same declaration name in a different owned proof file (imported: %s)', async imported => { - instances[0].controller.abort(); await cooperative.stop(); - const file = 'Helpers.lean'; - const plan = readCooperationPlan(problem, workspace); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ ...plan, - tasks: plan.tasks.map(task => ({ ...task, theoremName: task.theoremName?.replace('Tutorial.', 'Submission.') })), - }) + '\n```'); - fs.writeFileSync(sourcePath(workers[0]), (imported ? 'import Helpers\n' : '') + source(workers[0]).replaceAll('Tutorial', 'Submission')); - const namespace = imported ? 'Submission.Other' : 'Submission'; - fs.writeFileSync(path.join(workspace, problem.projectRelative, file), `namespace ${namespace}\nend ${namespace}\n`); - const receipt = JSON.parse(fs.readFileSync(problem.activeProblemPath, 'utf8')); - fs.writeFileSync(problem.activeProblemPath, JSON.stringify({ ...receipt, - schema: 'deepscientist.mathematics.lean-eval-bootstrap-receipt.v1', receiptId: 'two-file-fixture', - problemId: receipt.contract.problemId, benchmarkCommit: LEAN_EVAL_BENCHMARK_COMMIT, - catalogHash: 'a'.repeat(64), leaderboardSource: 'disabled', createdAt: 1, - solverOwnedFiles: [...receipt.solverOwnedFiles, file], - })); - git(workspace, ['add', '--', `${problem.projectRelative}/${file}`, `${problem.projectRelative}/Submission.lean`]); - git(workspace, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--no-gpg-sign', '--quiet', '-m', 'Owned helper module']); - problem = readSolverProblem(workspace, problem.activeProblemPath); - workers = workers.map(worker => { - const worktree = worker.role === 'lead' ? workspace : path.join(directory, `${worker.id}-two-files`); - if (worker.role !== 'lead') git(workspace, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - return { ...worker, worktree, ownedFiles: problem.ownedFiles }; - }); - state = { ...state, problem, cooperation: { canonicalCommit: problem.baseCommit, tasks: [] } }; - cooperative = create(); await cooperative.restore(); - const child = await assigned(workers[1]); - if (imported) requiredParentHelpers.push({ file, name: `${namespace}.child` }); - await deliverParent('lemma child : True := by sorry\n', { - [file]: `namespace ${namespace}\nlemma child : True := by exact True.intro\nend ${namespace}\n`, - }, imported ? 'Other.child' : 'support'); - expect(node('goal_0').proof!.changes.map(change => [change.file, change.name])).toEqual([ - ['Submission.lean', 'add_zero'], ['Submission.lean', 'support'], [file, 'child'], - ]); - expect(projections.find(item => item.theoremName === 'Submission.add_zero')!.files[file]) - .toContain('lemma child : True := by exact True.intro'); - - await deliverChild(child); - - expect(node('goal_0').status).toBe('integrated'); - expect(canonicalSource()).toContain('lemma child : True := by trivial'); - expect(committedSource(workspace, state.cooperation!.canonicalCommit!, `${problem.projectRelative}/${file}`)) - .toContain('lemma child : True := by exact True.intro'); - }); - - it('rechecks an archived parent carrying an old child placeholder before integrating it', async () => { - await assigned(workers[1]); - await deliverParent('lemma child : True := by sorry\n'); - const proof = node('goal_0').proof!; - // Older checkpoints captured the assumed declaration in the integration patch. - proof.changes.push({ file: 'Submission.lean', name: 'child', after: 'lemma child : True := by sorry\n', beforeName: 'add_zero' }); - instances[0].controller.abort(); await cooperative.stop(); - const archive = path.join(directory, 'state.json'); - writeSolverRunState(archive, state); state = readSolverRunState(archive); - cooperative = create(); await cooperative.restore(); - - await deliverChild(await assigned(workers[1])); - - expect(node('goal_0')).toMatchObject({ status: 'integrated', attempts: 1, integratedCheck: { passed: true } }); - expect(node('goal_0').proof!.changes.some(change => change.name === 'child')).toBe(false); - expect(canonicalSource()).toContain('lemma child : True := by trivial'); - expect(canonicalSource()).toContain('lemma support : True := by trivial'); - }); - - it('keeps the canonical child when the combined parent fails its independent merged check', async () => { - const child = await assigned(workers[1]); - await deliverParent('lemma child : True := by sorry\n'); - const verify = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const result = await verify(request); - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); - return request.items[0].theoremName === 'Tutorial.add_zero' && !source.includes('theorem_os_conditional_type%') - ? failedBatch(result, { stdoutPreview: () => 'Submission.lean:1:0: error: fixture combined proof does not close the target' }) : result; - }); - - await deliverChild(child); - - expect(node('goal_0').status).toBe('blocked'); - expect(node('goal_0').feedback).toContain('math_task_merged_proof_failed'); - expect(canonicalSource()).toContain('lemma child : True := by trivial'); - expect(canonicalSource()).toContain('n + 0 = n := by sorry'); - expect(canonicalSource()).not.toContain('lemma support'); - }); -}); diff --git a/tests/solverConditionalLibraryImports.test.ts b/tests/solverConditionalLibraryImports.test.ts deleted file mode 100644 index 92bc4c14..00000000 --- a/tests/solverConditionalLibraryImports.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { LIBRARY_PACK_SCHEMA } from '../src/math/libraryPacks'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { readInstalledLibrarySnapshot } from '../src/solver/installedLibraryContext'; -import { committedSource, commitSolverSources, readSolverProblem, withSolverWorktree } from '../src/solver/problem'; -import { applyTaskChanges, createTaskSourceProjector } from '../src/solver/cooperativeProof'; -import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch, workerAccess, workerDeliveryModules } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { leadWorker, peerWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const roots: string[] = []; -const instances: { controller: AbortController; cooperative: CooperativeResearch }[] = []; -afterEach(async () => { - for (const { controller, cooperative } of instances.splice(0)) { controller.abort(); await cooperative.stop(); } - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -describe('conditional consumer with an older library import context', () => { - it('checks the exact old candidate, records generated imports, and independently integrates after its producer', async () => { - const directory = temporaryDirectory('solver-conditional-library-imports-'); roots.push(directory); - const module = 'Submission.Library.Bounds'; - const receipt = bootstrapLeanTask(path.join(directory, 'workspace'), { - source: 'namespace Original\ntheorem target : True := by sorry\nend Original\n', task: 'Prove the original target.', - libraryPack: { schema: LIBRARY_PACK_SCHEMA, modules: [{ file: 'Submission/Library/Bounds.lean', - source: 'namespace Frozen\ndef value : Nat := 0\nend Frozen\n', - origin: { kind: 'upstream', repository: 'fixture', commit: 'a'.repeat(40), file: 'Bounds.lean' } }] }, - }); - const { workspaceRoot: workspace } = receipt; - const problem = readSolverProblem(workspace, receipt.activeProblemPath); - const example = { directory, workspace, receipt, problem }; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'researcher'), - peerWorker(example, 'engineer', { role: 'engineer' })]; - const tasks: CooperativeTask[] = [ - { id: 'producer', kind: 'lemma', objective: 'Prove the library interface.', theoremName: 'Original.producer', - proofPath: 'Submission.lean', type: 'Frozen.value = 0', dependsOn: [], revision: 0, ownerId: 'researcher' }, - { id: 'consumer', kind: 'goal', objective: 'Prove the original target.', theoremName: 'Original.target', - proofPath: 'Submission.lean', dependsOn: ['producer'], conditional: true, revision: 0, ownerId: 'engineer' }, - ]; - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ tasks }) + '\n```'); - const state = solverState(problem, workspace, { runId: 'conditional-library-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, tasks: [] } }); - const projections: { theorem: string; source: string }[] = []; - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); - for (const item of request.items) projections.push({ theorem: item.theoremName, source }); - if (source.includes('Frozen.value') && !source.includes(`import ${module}`)) - throw new Error('fixture_missing_conditional_library_import'); - return verifiedBatch(request, { sessionId: 'conditional-library-fixture' }); - }); - const controller = new AbortController(); - const access = workerAccess(workers, directory); - const library = readInstalledLibrarySnapshot(problem, state.environmentDigest); - for (const grant of access.values()) grant.installedLibrary = library; - const cooperative = cooperativeResearch({ state, workers, access, modules: workerDeliveryModules, - retrievalRoot: directory, signal: controller.signal }); - instances.push({ controller, cooperative }); - await cooperative.restore(); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const producer = await cooperative.next(workers[1], budget); - const consumer = await cooperative.next(workers[2], budget); - if (producer?.kind !== 'task' || consumer?.kind !== 'task') throw new Error('fixture_missing_task'); - expect(producer.task.id).toBe('producer'); expect(consumer.task.id).toBe('consumer'); - expect(cooperative.started(workers[1], producer)).toBe(true); - expect(cooperative.started(workers[2], consumer)).toBe(true); - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - - fs.writeFileSync(path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'), - `import ${module}\nnamespace Original\ntheorem producer : Frozen.value = 0 := by rfl\n` + - 'theorem target : True := by sorry\nend Original\n'); - await cooperative.deliver(workers[1], producer, commitSolverSources(problem, workers[1].worktree)); - expect(node('producer').status).toBe('integrated'); - - const oldCandidate = 'namespace Original\ntheorem target : True := by trivial\nend Original\n'; - fs.writeFileSync(path.join(workers[2].worktree, problem.projectRelative, 'Submission.lean'), oldCandidate); - const commit = commitSolverSources(problem, workers[2].worktree); - await cooperative.deliver(workers[2], consumer, commit); - const proof = node('consumer').proof!; - expect(node('consumer').status).toBe('integrated'); - expect(proof.commit).toBe(commit); - expect(proof.seedCommit).toBe(consumer.assignment.seedCommit); - expect(proof.conditions).toEqual([{ taskId: 'producer', taskDigest: taskVersion(producer.task) }]); - expect(proof.imports).toEqual([{ file: 'Submission.lean', module }]); - const projected = createTaskSourceProjector(problem, workers[2].worktree, commit)(consumer.task, [], [producer.task]); - expect(projections.some(item => item.theorem === 'Original.target' && item.source === projected.get('Submission.lean'))).toBe(true); - const conditionalType = /^theorem target : theorem_os_conditional_type% (.+) :=$/mu.exec(projected.get('Submission.lean')!); - expect(conditionalType).not.toBeNull(); - expect(JSON.parse(JSON.parse(conditionalType![1]!))).toEqual({ - declaration: 'theorem target : True := by trivial\n', - dependencies: [{ theoremName: 'Original.producer', type: 'Frozen.value = 0' }], - }); - expect(node('consumer').integratedCheck).toMatchObject({ passed: true }); - expect(node('consumer').integratedCheck!.conditions).toBeUndefined(); - expect(committedSource(workspace, state.cooperation!.canonicalCommit!, `${problem.projectRelative}/Submission.lean`)) - .toContain(`import ${module}`); - expect(committedSource(workspace, commit, `${problem.projectRelative}/Submission.lean`)).toBe(oldCandidate); - await withSolverWorktree(workspace, consumer.assignment.seedCommit, async checkout => { - applyTaskChanges(problem, checkout, proof.changes, proof.imports); - const merged = fs.readFileSync(path.join(checkout, problem.projectRelative, 'Submission.lean'), 'utf8'); - expect(merged).toContain(`import ${module}`); - expect(merged).toContain('theorem target : True := by trivial'); - }); - }); -}); diff --git a/tests/solverContinuation.test.ts b/tests/solverContinuation.test.ts deleted file mode 100644 index 79d42d06..00000000 --- a/tests/solverContinuation.test.ts +++ /dev/null @@ -1,1279 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { continuationResearchTasks, readyResearchTasks, researchCanAdvance } from '../src/solver/modules/search'; -import { assignSharedResearchTask, type ResearchWorker } from '../src/solver/modules/organization'; -import { taskVersion, parseCooperationPlan, markTaskAcceptance, type CooperativeAction, type TaskRecord, type RouteRecord } from '../src/solver/tasks'; -import { CooperativeResearch, type CooperationState } from '../src/solver/cooperation'; -import { requestLeadWake } from '../src/solver/leadWakes'; -import { directSolverModules } from '../src/solver/modules'; -import { git, type SolverProblem } from '../src/solver/problem'; -import type { SolverRunState } from '../src/solver/archive'; -import { readMathResponse } from '../src/solver/deliveries'; -import { recordRouteBlockers, refreshRouteBlockers } from '../src/solver/routeControl'; -import { ownedSourceDigest, type TaskProof } from '../src/solver/cooperativeProof'; -import { temporaryDirectory } from './helpers/files'; -import { answeredGoalPathStall, cooperativeResearch } from './helpers/cooperation'; -import { leadPlanningEvidence, leadPlanningEvidenceText } from '../src/solver/planningEvidence'; - -const node = (id: string, kind: TaskRecord['task']['kind'] = 'lemma', dependsOn: string[] = []): TaskRecord => ({ - task: { id, kind, objective: id, dependsOn, revision: 0, - ...(['lemma', 'goal'].includes(kind) ? { proofPath: 'Submission.lean', theoremName: id, type: 'True' } : {}) }, - status: 'pending', attempts: 0, -}); -const integrated = (record: TaskRecord): TaskRecord => { - record.status = 'integrated'; - record.integratedCheck = { passed: true, taskDigest: taskVersion(record.task), conditions: [], - verification: { status: 'kernel_verified', targetCommit: 'checked-source', results: [ - { status: 'kernel_verified', targetCommit: 'checked-source', receiptId: 'fixture-receipt' }, - ] } } as TaskRecord['integratedCheck']; - return record; -}; -const main: RouteRecord = { group: { id: 'main', objective: 'Original problem', status: 'active', revision: 0 }, turns: 0 }; - -describe('proof continuation scheduling', () => { - it('advances a consumer of checked helpers before untouched core gaps and disconnected work', () => { - const tasks = [node('explore', 'research'), node('core'), integrated(node('checked')), - node('bridge', 'lemma', ['checked']), node('middle', 'lemma', ['core']), node('goal', 'goal', ['bridge', 'middle'])]; - expect(continuationResearchTasks(tasks).map(record => record.task.id)).toEqual(['bridge', 'goal', 'core', 'middle', 'explore']); - expect(readyResearchTasks(tasks).map(record => record.task.id)).toEqual(['bridge', 'middle', 'explore', 'core', 'goal']); - tasks.find(record => record.task.id === 'checked')!.integratedCheck!.taskDigest = 'obsolete'; - expect(continuationResearchTasks(tasks).map(record => record.task.id)).toEqual(['goal', 'core', 'bridge', 'middle', 'explore']); - }); - - it('prefers a ready original target and never counts conditional premises as proved', () => { - const checked = integrated(node('checked')), open = node('open'); - const consumer = node('consumer', 'lemma', ['checked']), goal = node('ready-goal', 'goal', ['checked']); - const conditional = node('conditional-goal', 'goal', ['open']); conditional.task = { ...conditional.task, conditional: true }; - const tasks = [open, checked, consumer, node('later-goal', 'goal', ['consumer']), conditional, goal]; - expect(continuationResearchTasks(tasks).map(record => record.task.id)).toEqual([ - 'ready-goal', 'consumer', 'later-goal', 'open', 'conditional-goal', - ]); - expect(open.status).toBe('pending'); - expect(conditional.integratedCheck).toBeUndefined(); - }); - - it('offers a spare proof slot to a different route and keeps owner and group pins', () => { - const running = [node('working-a'), node('working-b')]; running.forEach(record => record.status = 'running'); - const tried = node('tried', 'research'); tried.attempts = 5; - const fresh = node('fresh', 'research'); fresh.task = { ...fresh.task, ownerId: 'researcher' }; - const core = node('core'), goal = node('goal', 'goal', [...running.map(record => record.task.id), 'core']); - // This fixture exercises spare capacity after the consumer has declined early checking. - goal.task = { ...goal.task, conditional: false }; - const tasks = [tried, core, ...running, fresh, goal]; - const ready = continuationResearchTasks(tasks, [main]); - expect(ready.map(record => record.task.id)).toEqual(['core', 'fresh', 'tried']); - const engineer: ResearchWorker = { id: 'engineer', role: 'engineer', worktree: '/engineer', ownedFiles: [] }; - const researcher: ResearchWorker = { ...engineer, id: 'researcher', role: 'researcher' }; - const busy = running.map((record, index) => { - const worker = { ...researcher, id: `busy-${index}` }; - record.assignment = { taskId: record.task.id, taskDigest: taskVersion(record.task), workerId: worker.id, seedCommit: 'seed' }; - return worker; - }); - const live = [engineer, researcher, ...busy]; - expect(assignSharedResearchTask(ready, engineer, live, [main], tasks)).toBe(tried); - expect(assignSharedResearchTask(ready, researcher, live, [main], tasks)).toBe(fresh); - fresh.status = 'running'; - expect(continuationResearchTasks(tasks, [main])).toEqual([]); - expect(continuationResearchTasks(tasks).map(record => record.task.id)).toEqual(['core', 'tried']); - core.task = { ...core.task, ownerId: 'researcher' }; - core.assignment = { taskId: 'core', taskDigest: taskVersion(core.task), workerId: 'researcher', seedCommit: 'seed' }; - expect(assignSharedResearchTask(continuationResearchTasks(tasks), engineer, [engineer, researcher], [main])).toBe(tried); - }); - - it.each(['original', 'consumer'] as const)('keeps a ready %s ahead of spare-slot exploration', kind => { - const running = [node('working-a'), node('working-b')]; - running.forEach(record => record.status = 'running'); - const checked = integrated(node('checked')); - const consumer = node('ready', kind === 'original' ? 'goal' : 'lemma', ['checked']); - const tasks = [node('explore', 'research'), ...running, checked, consumer, - node('unfinished-original', 'goal', [...running.map(record => record.task.id), 'ready'])]; - const workers = Array.from({ length: 3 }, (_, index) => ({ id: `worker-${index}`, role: 'researcher' as const, - worktree: `/worker-${index}`, ownedFiles: [] })); - running.forEach((record, index) => record.assignment = { taskId: record.task.id, taskDigest: taskVersion(record.task), - workerId: workers[index]!.id, seedCommit: 'fixture' }); - const before = structuredClone(tasks); - expect(continuationResearchTasks(tasks).map(record => record.task.id)).toEqual(kind === 'original' - ? ['ready', 'explore'] : ['ready', 'unfinished-original', 'explore']); - expect(assignSharedResearchTask(continuationResearchTasks(tasks), workers[2]!, workers, undefined, tasks)).toBe(consumer); - expect(tasks).toEqual(before); - }); - - it('preserves dependency, pause, spent route and concurrency gates', () => { - const tasks = [node('core'), node('blocked', 'goal', ['core']), node('paused'), node('full'), node('spent')]; - tasks[1].task = { ...tasks[1].task, conditional: false }; - tasks[2].task = { ...tasks[2].task, status: 'paused' }; - tasks[3].task = { ...tasks[3].task, groupId: 'full' }; tasks[4].task = { ...tasks[4].task, groupId: 'spent' }; - const groups: RouteRecord[] = [main, - { group: { ...main.group, id: 'full', maxConcurrent: 1 }, turns: 0, busy: 1 }, - { group: { ...main.group, id: 'spent', maxTurns: 1 }, turns: 1 }]; - expect(continuationResearchTasks(tasks, groups).map(record => record.task.id)).toEqual(['core']); - }); -}); - -describe('unchanged research delivery recovery and budget wakeup', () => { - let directory: string, seed: string, cooperative: CooperativeResearch, state: SolverRunState, record: TaskRecord; - let lead: ResearchWorker, researcher: ResearchWorker, action: Extract; - let allowed: boolean; - // These fixtures exercise frontier reconsideration under a finite solving deadline; - // continuous waiting remains explicitly enabled below. - const budget = { maxTurns: Infinity, remainingMs: 60_000 }; - const resume = (state: SolverRunState, input: Partial[0]> = {}) => - cooperativeResearch({ state, workers: [lead, researcher], retrievalRoot: '', access: new Map(), ...input }); - const checkpoint = (notes: string | undefined) => { - if (notes === undefined) fs.rmSync(path.join(directory, 'RESEARCH.md'), { force: true }); - else fs.writeFileSync(path.join(directory, 'RESEARCH.md'), notes); - git(directory, ['add', '--', 'RESEARCH.md']); - git(directory, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--no-gpg-sign', '--quiet', '--allow-empty', '-m', 'Research checkpoint']); - return git(directory, ['rev-parse', 'HEAD']); - }; - const addSource = (text: string) => { - fs.appendFileSync(path.join(directory, 'generated/p/Submission.lean'), text); git(directory, ['add', '--', 'generated']); - }; - const check = (commit = seed, conditions: TaskRecord['task'][] = []) => - (cooperative as any).check(record.task, record.assignment, directory, commit, conditions, undefined, true); - beforeEach(() => { - directory = temporaryDirectory('continuation-test-'); - fs.mkdirSync(path.join(directory, 'generated/p'), { recursive: true }); - fs.writeFileSync(path.join(directory, 'generated/p/Submission.lean'), 'theorem goal : True := by sorry\n'); - git(directory, ['init', '--quiet']); git(directory, ['add', '--', 'generated']); - seed = checkpoint('Inherited research notes.'); - record = node('question', 'research'); record.status = 'running'; - record.assignment = { taskId: record.task.id, taskDigest: taskVersion(record.task), workerId: 'researcher', seedCommit: seed }; - lead = { id: 'solver', role: 'lead', worktree: directory, ownedFiles: ['Submission.lean'] }; - researcher = { ...lead, id: 'researcher', role: 'researcher' }; - const cooperation: CooperationState = { canonicalCommit: seed, tasks: [record, node('goal', 'goal', ['question'])], - groups: [{ ...main, group: { ...main.group } }] }; - state = { runId: 'continuation-fixture', turns: 0, environmentDigest: 'fixture', cooperation, - problem: { projectRelative: 'generated/p', ownedFiles: ['Submission.lean'], declarations: {}, targets: [], - trustedFiles: {}, baseCommit: seed, sourceStructure: {}, sourceImports: {}, - contract: { assumptions: [], formalStatement: 'Prove the original goal.' } } as unknown as SolverProblem } as SolverRunState; - allowed = true; - cooperative = resume(state, { modelDispatchAllowed: () => allowed }); - action = { kind: 'task', task: record.task, assignment: record.assignment }; - }); - afterEach(async () => { await cooperative.stop(); vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - - const parkCore = () => { - const core = node('core'); core.status = 'blocked'; core.feedback = 'The required analytic estimate is still absent.'; - record.status = 'completed'; record.finding = 'The existing half-plane estimate does not reach the critical line.'; - const tasks = [core, record, node('goal', 'goal', ['core'])]; - const blockers = state.cooperation!.blockers = []; - const proposal = { mechanism: 'missing cancellation estimate', scope: 'critical-line inference', - reopenOn: [{ kind: 'contract-changed' as const }] }; - recordRouteBlockers(blockers, [proposal], core.task, tasks, 'fixture', 'problem'); - recordRouteBlockers(blockers, [proposal], core.task, tasks, 'fixture', 'problem'); - refreshRouteBlockers(blockers, tasks, 'fixture', 'problem'); - state.cooperation!.tasks = tasks; - state.problem.receiptDigest = 'problem'; - state.cooperation!.planVersion = (cooperative as any).planVersion(); - vi.spyOn(cooperative as any, 'seed').mockReturnValue(seed); - vi.spyOn(cooperative as any, 'acceptPlan').mockResolvedValue(undefined); - return core; - }; - // These fixtures mock acceptPlan, so a Lead's goalPath answer is recorded as acceptPlan would record it. - const declineGoalPath = (action: CooperativeAction, instance = cooperative) => { - const presented = (instance as any).presentedGoalPathStalls.get(action) as { taskIds: string[] } | undefined; - if (presented) (instance as any).recordGoalPathDecisions(action, { adopted: [], - declined: presented.taskIds.map(taskId => ({ taskId, reason: 'The recorded estimate is still missing; keep this input parked.' })) }); - }; - const assessFrontier = async (answer: 'decline' | 'none' = 'decline') => { - const action = await cooperative.next(lead, budget); - expect(action).toMatchObject({ kind: 'lead' }); - if (action?.kind !== 'lead') throw new Error('expected_frontier_assessment'); - if (answer === 'decline') declineGoalPath(action); - await cooperative.deliver(lead, action, action.seedCommit); - return action; - }; - - it('reconsiders a parked original-goal frontier once after later advisory findings without unblocking its proof', async () => { - const core = parkCore(); - state.cooperation!.lastLeadInputDigest = (cooperative as any).planningInputDigest(); - record.finding = 'A new paper reduces the original gap to a precise localized moment estimate.'; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - await assessFrontier(); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(emit).toHaveBeenCalledWith('blocked_tasks_reconsidered', expect.objectContaining({ taskIds: ['core'], goalIds: ['goal'] })); - expect(emit).toHaveBeenCalledWith('routes_idle', expect.objectContaining({ reason: 'unchanged-mathematical-input', - frontier: [expect.objectContaining({ taskId: 'core', parkedBy: core.routeParking })] })); - expect(core.status).toBe('blocked'); expect(core.routeParking).toHaveLength(1); - }); - - it('dispatches an imported unresolved frontier after one Lead assessment, then preserves a real failed attempt across restore', async () => { - const core = parkCore(); - const goal = state.cooperation!.tasks.find(node => node.task.id === 'goal')!; - goal.task = { ...goal.task, conditional: false }; - state.cooperation!.blockers = []; core.routeParking = []; - core.feedback = 'Historical unresolved checkpoint; needs current evidence.'; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - await assessFrontier(); - const waitingLead = cooperative.next(lead, budget); - expect(core.status).toBe('pending'); - expect(core.feedback).toContain('Historical unresolved checkpoint'); - expect(emit).toHaveBeenCalledWith('unattempted_frontier_resumed', { taskIds: ['core'], goalIds: ['goal'] }); - const work = await cooperative.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: 'core' } }); - if (work?.kind !== 'task') throw new Error('expected_imported_frontier_work'); - expect(cooperative.started(researcher, work)).toBe(true); - expect(core.attempts).toBe(1); - cooperative.rejected(work, 'The current candidate still lacks the needed estimate.', seed); - const reassessment = await waitingLead; - expect(reassessment).toMatchObject({ kind: 'lead' }); - if (reassessment?.kind !== 'lead') throw new Error('expected_failed_frontier_assessment'); - declineGoalPath(reassessment); - await cooperative.deliver(lead, reassessment, seed); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(core.status).toBe('blocked'); expect(core.integratedCheck).toBeUndefined(); - const resumed = resume(JSON.parse(JSON.stringify(state))); - vi.spyOn(resumed as any, 'seed').mockReturnValue(seed); - try { expect(await resumed.next(lead, budget)).toBeUndefined(); } - finally { await resumed.stop(); } - }); - - it.each(['assigned', 'proof-retained', 'archived-parking', 'owner-unavailable', 'M5-declines'])( - 'keeps an unchanged unresolved frontier idle when %s', async control => { - const core = parkCore(); - state.cooperation!.blockers = []; core.routeParking = []; - if (control === 'assigned') core.assignment = { ...action.assignment, taskId: 'core', taskDigest: taskVersion(core.task) }; - else if (control === 'proof-retained') core.proof = { passed: false, taskDigest: taskVersion(core.task), - verification: { status: 'failed', results: [] } } as unknown as TaskProof; - else if (control === 'archived-parking') { - const blockers = state.cooperation!.blockers; - const proposal = { mechanism: 'recurring gap', scope: 'core inference' }; - recordRouteBlockers(blockers, [proposal], core.task, state.cooperation!.tasks, 'fixture', 'problem'); - recordRouteBlockers(blockers, [proposal], core.task, state.cooperation!.tasks, 'fixture', 'problem'); - expect(blockers[0].status).toBe('parked'); expect(core.routeParking).toEqual([]); - } else if (control === 'owner-unavailable') core.task = { ...core.task, ownerId: 'stopped-researcher' }; - else (cooperative as any).input.modules = { ...directSolverModules, - M5: { ...directSolverModules.M5, assign: () => undefined } }; - state.cooperation!.lastLeadInputDigest = (cooperative as any).planningInputDigest(); - answeredGoalPathStall(state); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(core.status).toBe('blocked'); expect(core.attempts).toBe(0); - }); - - const prepareFailedCore = () => { - const core = parkCore(); - vi.mocked((cooperative as any).acceptPlan).mockRestore(); - state.cooperation!.blockers = []; core.routeParking = []; core.attempts = 2; - core.feedback = 'math_task_missing_declaration\nThe required compact seed declaration was absent twice.'; - state.problem.targets = [{ proofPath: 'Submission.lean', theoremName: 'goal' }]; - const plan = parseCooperationPlan(state.problem, { tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(route => route.group) }); - for (const node of state.cooperation!.tasks) node.task = plan.tasks.find(task => task.id === node.task.id)!; - state.cooperation!.planVersion = (cooperative as any).planVersion(); - return core; - }; - const planCommit = (tasks = state.cooperation!.tasks.map(node => node.task), extra = {}) => checkpoint( - '```math-plan\n' + JSON.stringify({ tasks, groups: state.cooperation!.groups!.map(route => route.group), ...extra }) + '\n```'); - const getLead = async () => { - const next = await cooperative.next(lead, budget); - expect(next).toMatchObject({ kind: 'lead' }); - if (next?.kind !== 'lead') throw new Error('expected_failed_core_plan'); - return next; - }; - /** A Lead revision that only answers the stalled goal path, read by the real acceptPlan. */ - const goalPathCommit = (goalPath: Record, upsert: unknown[] = []) => checkpoint('```math-plan\n' + - JSON.stringify({ baseVersion: state.cooperation!.planVersion, upsert, goalPath }) + '\n```'); - - it('wakes a blocked unattempted prerequisite of explicitly pending supporting work outside the goal cone', async () => { - parkCore(); - const prerequisite = node('supporting_compactness'); prerequisite.status = 'blocked'; - state.cooperation!.tasks.push(prerequisite, node('ambient_extension', 'lemma', ['supporting_compactness'])); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - state.cooperation!.lastLeadInputDigest = (cooperative as any).planningInputDigest(); - answeredGoalPathStall(state); - const leadNext = cooperative.next(lead, budget); - await vi.waitFor(() => expect(prerequisite.status).toBe('pending')); - const work = await cooperative.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: 'supporting_compactness' } }); - if (work?.kind !== 'task') throw new Error('expected_supporting_prerequisite'); - expect(cooperative.started(researcher, work)).toBe(true); - allowed = false; - cooperative.rejected(work, 'A concrete unresolved supporting premise remains.', seed); - expect(await leadNext).toBeUndefined(); - }); - - it('accepts a typed decomposition and offers its consumer check while the fresh premise remains unproved', async () => { - prepareFailedCore(); - const next = await getLead(); - const premise = node('compactness_premise'); premise.task = { ...premise.task, type: 'Nat.succ 0 = 1' }; - const tasks = state.cooperation!.tasks.map(node => node.task.id === 'core' ? - { ...node.task, dependsOn: ['compactness_premise'] } : node.task); - tasks.push(premise.task); - await cooperative.deliver(lead, next, planCommit(tasks)); - const work = await cooperative.next(researcher, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: 'core' }, assignment: { connectionCheck: { - inputs: [{ taskId: 'compactness_premise', taskDigest: taskVersion(premise.task) }], - } } }); - expect(readyResearchTasks(state.cooperation!.tasks).some(node => node.task.id === premise.task.id)).toBe(true); - expect(state.cooperation!.tasks.find(node => node.task.id === premise.task.id)!.integratedCheck).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'goal')!.integratedCheck).toBeUndefined(); - }); - - it('dispatches an independent advisory investigation of the failed core without accepting or retrying that proof', async () => { - const core = prepareFailedCore(), next = await getLead(); - const probe = node('investigate_missing_construction', 'research', ['core']); - const tasks = [...state.cooperation!.tasks.map(node => node.task), probe.task]; - await cooperative.deliver(lead, next, planCommit(tasks)); - expect(core.status).toBe('blocked'); expect(core.attempts).toBe(2); - expect(await cooperative.next(researcher, budget)).toMatchObject({ - kind: 'task', task: { id: probe.task.id, kind: 'research' }, - }); - expect(core.integratedCheck).toBeUndefined(); - }); - - it.each(['dependency-contract', 'group-revision'])( - 'does not treat a consumer of transitively invalidated evidence as ready after %s changes', async change => { - prepareFailedCore(); - const base = integrated(node('base')), bridge = integrated(node('bridge', 'lemma', ['base'])); - state.cooperation!.tasks.push(base, bridge); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - const next = await getLead(); - const fresh = node('consume_bridge', 'lemma', ['bridge']); - fresh.task = { ...fresh.task, type: '1 + 1 = (2 : Nat)', conditional: false }; - const tasks = state.cooperation!.tasks.map(node => node.task.id === 'core' ? { ...node.task, dependsOn: [fresh.task.id] } : - change === 'dependency-contract' && node.task.id === 'base' ? { ...node.task, type: 'And True True' } : node.task); - tasks.push(fresh.task); - const extra = change === 'group-revision' ? { groups: [{ ...main.group, revision: 1 }] } : {}; - await cooperative.deliver(lead, next, planCommit(tasks, extra)); - const consumer = state.cooperation!.tasks.find(node => node.task.id === fresh.task.id)!; - expect(consumer).toBeDefined(); - expect(readyResearchTasks(state.cooperation!.tasks, state.cooperation!.groups)).not.toContain(consumer); - expect(consumer.integratedCheck).toBeUndefined(); - }); - - it('rebinds an unattempted premise to a live owner before checking dispatchability', async () => { - prepareFailedCore(); - const premise = node('rebound_premise'); premise.task = { ...premise.task, type: 'Nat.succ 0 = 1', ownerId: 'offline' }; - premise.assignment = { ...action.assignment, workerId: 'offline', taskId: premise.task.id, taskDigest: taskVersion(premise.task) }; - state.cooperation!.tasks.push(premise); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - const next = await getLead(); - const tasks = state.cooperation!.tasks.map(node => node.task.id === 'core' ? { ...node.task, dependsOn: [premise.task.id] } : - node.task.id === premise.task.id ? { ...node.task, ownerId: researcher.id } : node.task); - await cooperative.deliver(lead, next, planCommit(tasks)); - expect(await cooperative.next(researcher, budget)).toMatchObject({ - kind: 'task', task: { id: 'core' }, assignment: { workerId: researcher.id, connectionCheck: { - inputs: [{ taskId: premise.task.id, taskDigest: taskVersion({ ...premise.task, ownerId: researcher.id }) }], - } }, - }); - const rebound = state.cooperation!.tasks.find(node => node.task.id === premise.task.id)!; - expect(rebound.task.ownerId).toBe(researcher.id); - expect(assignSharedResearchTask([rebound], researcher, [lead, researcher], state.cooperation!.groups, - state.cooperation!.tasks)).toBe(rebound); - }); - - it('records an accepted decomposition even if subsequent source integration fails', async () => { - prepareFailedCore(); - const saved: { premise: boolean; error?: string }[] = []; - (cooperative as any).input.save = () => saved.push({ - premise: state.cooperation!.tasks.some(node => node.task.id === 'fresh_premise'), error: state.cooperation!.error }); - const next = await getLead(), premise = node('fresh_premise'); - premise.task = { ...premise.task, type: 'Nat.succ 0 = 1' }; - const tasks = state.cooperation!.tasks.map(node => node.task.id === 'core' ? { ...node.task, dependsOn: [premise.task.id] } : node.task); - tasks.push(premise.task); - addSource('\nlemma fresh_premise : Nat.succ 0 = 1 := by rfl\n'); - await cooperative.deliver(lead, next, planCommit(tasks)); - expect(state.cooperation!.error).toBeTruthy(); - expect(saved).toContainEqual({ premise: true, error: undefined }); - expect(state.cooperation!.tasks.find(node => node.task.id === premise.task.id)).toBeDefined(); - expect(await cooperative.next(lead, budget)).toMatchObject({ kind: 'lead' }); - }); - - it('keeps a resumed frontier behind the existing M3 readiness gate', async () => { - const core = parkCore(); - state.cooperation!.blockers = []; core.routeParking = []; - (cooperative as any).input.modules = { ...directSolverModules, M3: { ...directSolverModules.M3, ready: () => [] } }; - state.cooperation!.lastLeadInputDigest = (cooperative as any).planningInputDigest(); - const reassessment = await cooperative.next(lead, budget); - expect(reassessment).toMatchObject({ kind: 'lead' }); - expect(core.status).toBe('pending'); expect(core.assignment).toBeUndefined(); expect(core.attempts).toBe(0); - if (reassessment?.kind !== 'lead') throw new Error('expected_gated_frontier_assessment'); - await cooperative.deliver(lead, reassessment, seed); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(core.status).toBe('pending'); expect(core.assignment).toBeUndefined(); - }); - - it('does not repeat a frontier decision for notes-only commits, duplicate delivery ids or restored state', async () => { - parkCore(); - const progress = { id: 'finding-one', taskId: record.task.id, taskDigest: taskVersion(record.task), kind: 'research' as const, - status: 'advisory' as const, summary: 'The current input does not prove the required cancellation.', evidenceRefs: [], - dependencies: [], remainingObligations: [] }; - state.cooperation!.deliveries = [progress as any]; - await assessFrontier(); - state.cooperation!.canonicalCommit = checkpoint('Only reword the explanation of the same obstacle.'); - state.cooperation!.deliveries.push({ ...progress, id: 'finding-new-id', createdAt: 42 } as any); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - const restoredState = JSON.parse(JSON.stringify(state)); - const resumed = resume(restoredState); - try { expect(await resumed.next(lead, budget)).toBeUndefined(); } - finally { await resumed.stop(); } - }); - - const savePausedPlan = () => { - vi.mocked((cooperative as any).acceptPlan).mockRestore(); - state.problem.targets = [{ proofPath: 'Submission.lean', theoremName: 'goal' }] as SolverProblem['targets']; - return checkpoint('```math-plan\n' + JSON.stringify({ - tasks: [...state.cooperation!.tasks.map(node => node.task), { - id: 'paused_probe', kind: 'research', objective: 'An explicitly deferred investigation', status: 'paused', - dependsOn: [], revision: 0, - }], groups: state.cooperation!.groups!.map(route => route.group), - }) + '\n```'); - }; - - it('consumes its own accepted plan changes without another frontier assessment', async () => { - parkCore(); - const action = await cooperative.next(lead, budget); - if (action?.kind !== 'lead') throw new Error('expected_frontier_assessment'); - const commit = savePausedPlan(); - await cooperative.deliver(lead, action, commit); - expect(state.cooperation!.lastLeadInputDigest).not.toBe(action.planningInputDigest); - expect(state.cooperation!.lastLeadInputDigest).toBe((cooperative as any).planningInputDigest()); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - }); - - it('retains peer evidence arriving while Lead is accepting its own plan changes', async () => { - parkCore(); - const action = await cooperative.next(lead, budget); - if (action?.kind !== 'lead') throw new Error('expected_frontier_assessment'); - const commit = savePausedPlan(); - (cooperative as any).record(researcher, record.task, 'research', 'advisory', 'A new precise estimate from a peer.'); - await cooperative.deliver(lead, action, commit); - expect(state.cooperation!.lastLeadInputDigest).toBe(action.planningInputDigest); - const next = await cooperative.next(lead, budget); - expect(next).toMatchObject({ kind: 'lead' }); - if (next?.kind !== 'lead') throw new Error('expected_new_evidence_assessment'); - await cooperative.deliver(lead, next, commit); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - }); - - it.each(['environment', 'proof-source'])('allows one new frontier assessment after changed %s', async change => { - const core = parkCore(); - await assessFrontier(); - if (change === 'environment') state.environmentDigest = 'new-pinned-environment'; - else { - addSource('\ntheorem new_input : True := by trivial\n'); - state.cooperation!.canonicalCommit = checkpoint('A newly saved proof input.'); - } - await assessFrontier(); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(core.status).toBe('blocked'); expect(core.routeParking).toHaveLength(1); - }); - - // An explicit pause of a frontier input is respected once the Lead has answered what it leaves: the stalled original - // goal path is owed a Lead turn with its candidates, and the declined frontier then stays idle, also across restore. - it.each(['paused-task', 'spent-group'])('asks once about an explicitly %s frontier, then keeps it', async control => { - const core = parkCore(); - if (control === 'paused-task') core.task = { ...core.task, status: 'paused' }; - else { state.cooperation!.groups![0].group.maxTurns = 1; state.cooperation!.groups![0].turns = 1; } - const emit = vi.fn(); (cooperative as any).input.emit = emit; - await assessFrontier(); - expect(emit).toHaveBeenCalledWith('goal_path_stalled', expect.objectContaining({ goalIds: ['goal'], taskIds: ['core'] })); - expect(emit).toHaveBeenCalledWith('goal_path_stall_dispatched', { digest: state.cooperation!.goalPathStall!.digest }); - expect(emit).toHaveBeenCalledWith('goal_path_decided', { adopted: [], declined: ['core'] }); - expect(state.cooperation!.goalPathStall).toMatchObject({ active: true, goalIds: ['goal'], answeredAt: expect.any(Number), - declined: [expect.objectContaining({ taskId: 'core', reason: expect.stringContaining('estimate') })] }); - expect(state.cooperation!.goalPathStall!.unanswered).toBeUndefined(); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(core.status).toBe('blocked'); - const resumed = resume(JSON.parse(JSON.stringify(state))); - vi.spyOn(resumed as any, 'seed').mockReturnValue(seed); - try { expect(await resumed.next(lead, budget)).toBeUndefined(); } - finally { await resumed.stop(); } - }); - - // A settled turn that neither adopts nor declines is asked once more with that feedback, then recorded as ignored. - it('re-asks an unanswered stall once, shows the miss to the Lead, then records it as ignored', async () => { - const core = parkCore(); - core.task = { ...core.task, status: 'paused' }; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - await assessFrontier('none'); - const digest = state.cooperation!.goalPathStall!.digest; - expect(emit).toHaveBeenCalledWith('goal_path_stall_unanswered', { digest, taskIds: ['core'], unanswered: 1 }); - expect(state.cooperation!.goalPathStall).toMatchObject({ active: true, unanswered: 1 }); - expect(state.cooperation!.goalPathStall!.answeredAt).toBeUndefined(); - const evidence = leadPlanningEvidence(state.cooperation!, state.environmentDigest); - expect(evidence.goalPath).toMatchObject({ unansweredTurns: 1, goals: [expect.objectContaining({ taskId: 'goal', stalled: true })] }); - expect(leadPlanningEvidenceText(evidence)).toContain('1 earlier turn(s) shown this stall answered none of it'); - // The unanswered stall keeps its wake across restore. - const resumed = resume(JSON.parse(JSON.stringify(state))); - vi.spyOn(resumed as any, 'seed').mockReturnValue(seed); - try { expect(await resumed.next(lead, budget)).toMatchObject({ kind: 'lead' }); } - finally { await resumed.stop(); } - await assessFrontier('none'); - expect(emit).toHaveBeenCalledWith('goal_path_stall_ignored', { digest, goalIds: ['goal'], taskIds: ['core'], unanswered: 2 }); - expect(state.cooperation!.goalPathStall).toMatchObject({ digest, active: true, unanswered: 2, - answeredAt: expect.any(Number), ignoredAt: expect.any(Number) }); - expect(leadPlanningEvidence(state.cooperation!, state.environmentDigest).goalPath).toMatchObject({ ignored: true }); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(core.status).toBe('blocked'); - }); - - it.each(['paused-group', 'paused-goal'])('does not reconsider an original goal set aside by its %s', async control => { - const core = parkCore(); - const goal = state.cooperation!.tasks.find(node => node.task.id === 'goal')!; - if (control === 'paused-group') state.cooperation!.groups![0].group.status = 'paused'; - else goal.task = { ...goal.task, status: 'paused' }; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(core.status).toBe('blocked'); - expect(emit).not.toHaveBeenCalledWith('goal_path_stalled', expect.anything()); - expect(state.cooperation!.goalPathStall).toBeUndefined(); - }); - - it.each(['decline', 'adopt-resume'] as const)('asks the Lead once more when its own plan pauses the only frontier of an original goal (%s)', async answer => { - prepareFailedCore(); - const core = state.cooperation!.tasks.find(node => node.task.id === 'core')!; - core.status = 'pending'; core.attempts = 0; core.feedback = undefined; - requestLeadWake(state.cooperation!.leadWakes!, 'progress-decision-requested'); - const emit = vi.fn(); (cooperative as any).input.emit = emit; - const first = await getLead(); - expect(emit).not.toHaveBeenCalledWith('goal_path_stall_dispatched', expect.anything()); - const commit = planCommit(state.cooperation!.tasks.map(node => node.task.id === 'core' ? { ...node.task, status: 'paused' as const } : node.task)); - await cooperative.deliver(lead, first, commit); - expect(state.cooperation!.tasks.find(node => node.task.id === 'core')!.task.status).toBe('paused'); - expect(state.cooperation!.lastLeadInputDigest).toBe((cooperative as any).planningInputDigest()); - const stall = state.cooperation!.goalPathStall!; - expect(stall).toMatchObject({ active: true, goalIds: ['goal'], taskIds: ['core'] }); - expect(stall.answeredAt).toBeUndefined(); - // The deciding turn never saw the stall its pause produced, so the unchanged input does not absorb it. - const owed = await getLead(); - expect(emit).toHaveBeenCalledWith('goal_path_stall_dispatched', { digest: stall.digest }); - if (answer === 'decline') { - await cooperative.deliver(lead, owed, goalPathCommit({ decline: [{ taskId: 'core', reason: 'Deferred until the compact seed is restated.' }] })); - expect(emit).toHaveBeenCalledWith('goal_path_decided', { adopted: [], declined: ['core'] }); - expect(state.cooperation!.goalPathStall).toMatchObject({ digest: stall.digest, answeredAt: expect.any(Number), - declined: [expect.objectContaining({ taskId: 'core' })] }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'core')!.task.status).toBe('paused'); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - } else { - // A mechanical candidate is applied from its id alone; the goal path is runnable again. - await cooperative.deliver(lead, owed, goalPathCommit({ adopt: ['resume:core'] })); - expect(emit).toHaveBeenCalledWith('goal_path_decided', { adopted: ['resume:core'], declined: [] }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'core')!.task.status).toBe('active'); - expect(state.cooperation!.goalPathStall).toMatchObject({ active: false }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'core')!.status).toBe('pending'); - expect(await cooperative.next(researcher, budget)).toMatchObject({ kind: 'task' }); - } - }); - - it('treats a re-pause of a goal the Lead was shown as answered and re-asks after a new stall', async () => { - prepareFailedCore(); - const emit = vi.fn(); (cooperative as any).input.emit = emit; - const first = await getLead(); - expect(emit).toHaveBeenCalledWith('goal_path_stall_dispatched', expect.anything()); - const commit = planCommit(state.cooperation!.tasks.map(node => node.task.id === 'core' ? { ...node.task, status: 'paused' as const } : node.task)); - await cooperative.deliver(lead, first, commit); - const repaused = state.cooperation!.goalPathStall!; - expect(repaused.answeredAt).toEqual(expect.any(Number)); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - // The same goal stalling differently through peer-side evidence is new input for the Lead. - const core = state.cooperation!.tasks.find(node => node.task.id === 'core')!; - core.feedback = 'A newly recorded obstruction on the paused route.'; - const again = await getLead(); - expect(state.cooperation!.goalPathStall!.digest).not.toBe(repaused.digest); - expect(emit).toHaveBeenLastCalledWith('goal_path_stall_dispatched', { digest: state.cooperation!.goalPathStall!.digest }); - await cooperative.deliver(lead, again, goalPathCommit({ decline: [{ taskId: 'core', reason: 'The new obstruction confirms the pause.' }] })); - expect(state.cooperation!.goalPathStall!.answeredAt).toEqual(expect.any(Number)); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - }); - - it('takes an applied human pause of the only frontier as its decision, but keeps a stall the Lead was already owed', async () => { - prepareFailedCore(); - const find = (id: string) => state.cooperation!.tasks.find(node => node.task.id === id)!; - Object.assign(find('core'), { status: 'pending', attempts: 0, feedback: undefined }); - const emit = vi.fn(); (cooperative as any).input.emit = emit; - const edit = (id: string, core: Partial) => { - const record = { id, status: 'received' as const, receivedAt: Date.now() }; - (state.cooperation!.edits ??= []).push(record); - return (cooperative as any).acceptPlan(parseCooperationPlan(state.problem, { - tasks: state.cooperation!.tasks.map(node => node.task.id === 'core' ? { ...node.task, ...core } : node.task), - groups: state.cooperation!.groups!.map(route => route.group) }), record); - }; - await edit('operator-pause', { status: 'paused' }); - expect(find('core').task.status).toBe('paused'); - expect(state.cooperation!.goalPathStall).toMatchObject({ active: true, goalIds: ['goal'], answeredAt: expect.any(Number) }); - expect(emit).toHaveBeenCalledWith('goal_path_stalled', expect.objectContaining({ goalIds: ['goal'], answeredByEdit: 'operator-pause' })); - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(emit).not.toHaveBeenCalledWith('goal_path_stall_dispatched', expect.anything()); - // New peer evidence makes the stall owed; a later edit that only revises the paused input does not answer it. - find('core').feedback = 'A newly recorded obstruction on the paused route.'; - (cooperative as any).refreshGoalPathStall(); - expect(state.cooperation!.goalPathStall!.answeredAt).toBeUndefined(); - await edit('operator-revision', { objective: 'Prove the core estimate in its revised form' }); - expect(state.cooperation!.goalPathStall).toMatchObject({ active: true, goalIds: ['goal'] }); - expect(state.cooperation!.goalPathStall!.answeredAt).toBeUndefined(); - await getLead(); - expect(emit).toHaveBeenCalledWith('goal_path_stall_dispatched', { digest: state.cooperation!.goalPathStall!.digest }); - }); - - it('lets work on a stalled goal\'s own route settle before asking the Lead about the stall', async () => { - prepareFailedCore(); - const find = (id: string) => state.cooperation!.tasks.find(node => node.task.id === id)!; - const core = find('core'), goal = find('goal'); - core.task = { ...core.task, status: 'paused' }; - goal.status = 'running'; - goal.assignment = { taskId: 'goal', taskDigest: taskVersion(goal.task), workerId: 'researcher', seedCommit: seed }; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - let settled = false; - const leadNext = cooperative.next(lead, budget).then(next => { settled = true; return next; }); - await new Promise(resolve => setTimeout(resolve, 50)); - expect(settled).toBe(false); - expect(state.cooperation!.goalPathStall).toMatchObject({ active: true, goalIds: ['goal'] }); - expect(emit).not.toHaveBeenCalledWith('goal_path_stall_dispatched', expect.anything()); - goal.status = 'pending'; goal.assignment = undefined; - (cooperative as any).changed(); - expect(await leadNext).toMatchObject({ kind: 'lead' }); - expect(emit).toHaveBeenCalledWith('goal_path_stall_dispatched', { digest: state.cooperation!.goalPathStall!.digest }); - }); - - it('retries a dispatched but unfinished frontier decision after restoring serialized state', async () => { - parkCore(); - expect(await cooperative.next(lead, budget)).toMatchObject({ kind: 'lead' }); - expect(state.cooperation!.lastLeadInputDigest).toBeUndefined(); - const resumed = resume(JSON.parse(JSON.stringify(state))); - vi.spyOn(resumed as any, 'seed').mockReturnValue(seed); - try { expect(await resumed.next(lead, budget)).toMatchObject({ kind: 'lead' }); } - finally { await resumed.stop(); } - }); - - const pausedLead = async (beforeCheckpoint?: () => void) => { - parkCore(); record.status = 'running'; - requestLeadWake(state.cooperation!.leadWakes!, 'research-finding'); - const next = await cooperative.next(lead, budget); - if (next?.kind !== 'lead') throw new Error('expected_unfinished_lead'); - const admitted = (cooperative as any).leadPauseInputDigest(next.seedCommit); - beforeCheckpoint?.(); - await cooperative.deliver(lead, next, seed, true, 'scheduling-checkpoint'); - expect(state.cooperation!.lastLeadPauseInputDigest).toBe(admitted); - expect(state.cooperation!.lastLeadInputDigest).toBeUndefined(); - return next; - }; - - it('waits through repeated budget wakeups after an unchanged unfinished Lead checkpoint', async () => { - await pausedLead(); - let dispatched = false; - const pending = cooperative.next(lead, budget).then(next => { dispatched = true; return next; }); - for (let wake = 0; wake < 3; wake++) { - cooperative.modelBudgetChanged(); await new Promise(setImmediate); - expect(dispatched).toBe(false); - } - await cooperative.stop(); - expect(await pending).toBeUndefined(); - expect(state.cooperation!.lastLeadInputDigest).toBeUndefined(); - }); - - it.each(['peer-evidence', 'environment', 'source', 'notes', 'task-feedback', 'task-control'] as const)( - 'immediately admits new %s after an unfinished Lead checkpoint', async change => { - await pausedLead(); - if (change === 'peer-evidence') - (cooperative as any).record(researcher, record.task, 'research', 'advisory', 'A new exact cancellation estimate.'); - else if (change === 'environment') state.environmentDigest = 'new-pinned-environment'; - else if (change === 'source') addSource('\ntheorem saved_input : True := by trivial\n'); - else if (change === 'notes') fs.writeFileSync(path.join(directory, 'RESEARCH.md'), 'A newly saved exact mathematical inference.'); - else if (change === 'task-feedback') record.feedback = 'A new checked premise narrows the unresolved inference.'; - else record.task = { ...record.task, status: 'paused' }; - expect(await cooperative.next(lead, budget)).toMatchObject({ kind: 'lead' }); - expect(state.cooperation!.lastLeadInputDigest).toBeUndefined(); - }); - - it('keeps peer evidence arriving during the unfinished Lead turn outside its pause identity', async () => { - await pausedLead(() => (cooperative as any).record(researcher, record.task, 'research', 'advisory', - 'A concurrent peer supplies a new exact estimate.')); - expect(state.cooperation!.lastLeadPauseInputDigest).not.toBe((cooperative as any).leadPauseInputDigest()); - expect(await cooperative.next(lead, budget)).toMatchObject({ kind: 'lead' }); - }); - - it('restores the unfinished pause without turning it into a completed Lead decision', async () => { - await pausedLead(); - const restored = JSON.parse(JSON.stringify(state)); - const resumed = resume(restored); - vi.spyOn(resumed as any, 'seed').mockReturnValue(seed); - let dispatched = false; - const pending = resumed.next(lead, budget).then(next => { dispatched = true; return next; }); - try { - await new Promise(setImmediate); resumed.modelBudgetChanged(); await new Promise(setImmediate); - expect(dispatched).toBe(false); - expect(restored.cooperation.lastLeadPauseInputDigest).toBe(state.cooperation!.lastLeadPauseInputDigest); - expect(restored.cooperation.lastLeadInputDigest).toBeUndefined(); - } finally { await resumed.stop(); await pending; } - }); - - it('admits initial planning despite an unchanged pause marker and never pauses its checkpoint', async () => { - state.cooperation!.tasks = []; - requestLeadWake(state.cooperation!.leadWakes!, 'initial-plan'); - vi.spyOn(cooperative as any, 'seed').mockReturnValue(seed); - vi.spyOn(cooperative as any, 'acceptPlan').mockResolvedValue(undefined); - state.cooperation!.lastLeadPauseInputDigest = (cooperative as any).leadPauseInputDigest(); - const initial = await cooperative.next(lead, budget); - expect(initial).toMatchObject({ kind: 'lead', initialPlanNonce: expect.any(String) }); - if (initial?.kind !== 'lead') throw new Error('expected_initial_lead'); - state.cooperation!.lastLeadPauseInputDigest = undefined; - await cooperative.deliver(lead, initial, seed, true, 'scheduling-checkpoint'); - expect(state.cooperation!.lastLeadPauseInputDigest).toBeUndefined(); - }); - - it.each([[0, true], [3, true], [4, false]] as const)( - 'continues a cut Lead draft when nothing else runs until the backoff cap (unchanged streak %i)', async (streak, resumes) => { - parkCore(); - requestLeadWake(state.cooperation!.leadWakes!, 'research-finding'); - const cut = await cooperative.next(lead, budget); - if (cut?.kind !== 'lead') throw new Error('expected_unfinished_lead'); - await cooperative.deliver(lead, cut, seed, true, 'scheduling-checkpoint'); - expect(state.cooperation!.lastLeadPauseInputDigest).toBeTruthy(); - state.advisoryCheckpoint = { scope: 'lead', noProgressStreak: streak }; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - const next = await cooperative.next(lead, budget); - if (resumes) { - expect(next).toMatchObject({ kind: 'lead', planNonce: expect.any(String) }); - expect(emit).toHaveBeenCalledWith('lead_pause_resumed', { noProgressStreak: streak }); - } else { - expect(next).toBeUndefined(); - expect(emit).toHaveBeenCalledWith('routes_idle', expect.anything()); - } - expect(state.cooperation!.lastLeadInputDigest).toBeUndefined(); - }); - - it('ignores a repeated advisory decision hint while a peer is still running on unchanged input', async () => { - parkCore(); record.status = 'running'; - const progress = { id: 'progress-one', kind: 'progress', taskId: record.task.id, - taskDigest: action.assignment.taskDigest, summary: 'The same known cancellation gap.', needsDecision: true }; - await (cooperative as any).receive(researcher, action, progress); - await assessFrontier(); - const completed = state.cooperation!.lastLeadInputDigest; - await (cooperative as any).receive(researcher, action, { ...progress, id: 'progress-two' }); - const pending = cooperative.next(lead, budget); - await Promise.resolve(); - allowed = false; record.status = 'completed'; cooperative.modelBudgetChanged(); - expect(await pending).toBeUndefined(); - expect(state.cooperation!.lastLeadInputDigest).toBe(completed); - }); - - it('exits idle after assessing a blocked core hidden behind completed advisory work', async () => { - const core = parkCore(); - record.task = { ...record.task, dependsOn: [core.task.id] }; - const goal = state.cooperation!.tasks.find(item => item.task.kind === 'goal')!; - goal.task = { ...goal.task, dependsOn: [record.task.id] }; - state.cooperation!.planVersion = (cooperative as any).planVersion(); - expect(researchCanAdvance(state.cooperation!.tasks, state.cooperation!.groups, new Set([lead.id, researcher.id]))).toBe(false); - expect(readyResearchTasks(state.cooperation!.tasks, state.cooperation!.groups)).toEqual([]); - const emit = vi.fn(); (cooperative as any).input.emit = emit; - await assessFrontier(); - const inputDigest = state.cooperation!.lastLeadInputDigest; - expect(await cooperative.next(lead, budget)).toBeUndefined(); - expect(emit).toHaveBeenCalledWith('routes_idle', expect.objectContaining({ goalIds: [goal.task.id], - frontier: [expect.objectContaining({ taskId: core.task.id, status: 'blocked', attempts: core.attempts, - parkedBy: core.routeParking })], inputDigest, reason: 'unchanged-mathematical-input' })); - expect(core.status).toBe('blocked'); expect(core.routeParking).toHaveLength(1); - }); - - it('retries the first unchanged completion and asks Lead to revise after the second', async () => { - record.attempts = 40; // Long-lived work and checkpoint counts must not consume the repair opportunity. - await cooperative.deliver(researcher, action, seed); - expect(record.status).toBe('pending'); - expect(state.cooperation!.unchangedResearch!.question.count).toBe(1); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.deliveries).toEqual([expect.objectContaining({ kind: 'failure', status: 'failed', taskId: 'question' })]); - vi.spyOn(cooperative as any, 'seed').mockReturnValue(seed); - await expect(cooperative.next(lead, budget)).resolves.toMatchObject({ kind: 'lead' }); - }); - - it('retains complete long-running plans when both inherited notes and task graphs exceed 64KB', () => { - const objective = 'Preserve this exact mathematical obligation. '.repeat(2000); - record.task = { ...record.task, objective }; - fs.writeFileSync(path.join(directory, 'RESEARCH.md'), 'Earlier advisory checkpoint. '.repeat(4000)); - for (let round = 0; round < 2; round++) { - state.cooperation!.planEdited = true; - (cooperative as any).syncPlanNotes(); - const response = readMathResponse(directory, 'math-plan'); - expect(response.tasks.find((task: any) => task.id === record.task.id).objective).toBe(objective); - expect(Buffer.byteLength(fs.readFileSync(path.join(directory, 'RESEARCH.md')))).toBeGreaterThan(64_000); - } - }); - - it('retains reproducible Lean probe artifacts with an advisory finding and never grants proof acceptance', async () => { - const next = checkpoint('```math-result\n' + JSON.stringify({ summary: 'A reusable supporting declaration.', - leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['probe'] }] }) + - '\n```\n\n```lean\ntheorem probe : True := by trivial\n```\n'); - await cooperative.deliver(researcher, action, next); - expect(record.status).toBe('completed'); - const delivery = state.cooperation!.deliveries!.find(item => item.kind === 'research')!; - expect(delivery.status).toBe('advisory'); - expect(delivery.artifacts).toMatchObject({ scope: 'advisory-unverified', commit: next, - taskId: record.task.id, taskDigest: action.assignment.taskDigest }); - expect(delivery.artifacts!.artifacts[0].declarations[0].name).toBe('probe'); - expect(delivery.artifacts!.reportedChecks![0].artifactIds).toHaveLength(1); - expect(delivery.evidence).toBeUndefined(); - expect(record.integratedCheck).toBeUndefined(); - }); - - it('does not count recovered checkpoints as unchanged completed findings and resets after new findings', async () => { - await cooperative.deliver(researcher, action, seed); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - expect(record.status).toBe('pending'); - expect(state.cooperation!.unchangedResearch!.question.count).toBe(1); - record.status = 'running'; - await cooperative.deliver(researcher, action, checkpoint('A new concrete route and unresolved mathematical gap.')); - expect(record.status).toBe('completed'); - expect(record.feedback).toBeUndefined(); - expect(state.cooperation!.unchangedResearch!.question).toBeUndefined(); - }); - - it('pauses only the identical advisory checkpoint and keeps the original goal unfinished', async () => { - await cooperative.deliver(researcher, action, seed, true); - expect(record.status).toBe('pending'); - record.status = 'running'; - await cooperative.deliver(researcher, action, checkpoint('Inherited research notes.'), true); - expect(record.status).toBe('pending'); - record.status = 'running'; - await cooperative.deliver(researcher, action, checkpoint('Inherited research notes.'), true); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toMatchObject({ count: 3, unchangedEvidenceCount: 3, paused: true }); - expect(record.feedback).toContain('math_research_checkpoint_unchanged'); - expect(state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.status).toBe('pending'); - expect(state.cooperation!.tasks[0].integratedCheck).toBeUndefined(); - }); - - const pauseCheckpoint = async (commit = seed) => { - for (let attempt = 0; attempt < 3; attempt++) { - record.status = 'running'; - await cooperative.deliver(researcher, action, commit, true); - } - expect(record.status).toBe('blocked'); - return structuredClone(state.cooperation!.researchCheckpoints!.question); - }; - - it.each(['', ' \n\t', undefined])('keeps the unchanged research pause when saved notes become %j', async notes => { - const paused = await pauseCheckpoint(); - const emit = vi.fn(); (cooperative as any).input.emit = emit; - checkpoint(notes); - for (let refresh = 0; refresh < 3; refresh++) (cooperative as any).changed(); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toEqual(paused); - expect(emit).not.toHaveBeenCalledWith('research_checkpoint_reopened', expect.anything()); - checkpoint('A new saved calculation after the lost notes is available.'); - (cooperative as any).changed(); - expect(record.status).toBe('pending'); - expect(emit).toHaveBeenCalledWith('research_checkpoint_reopened', { taskId: record.task.id, reason: 'new-output' }); - }); - - it('does not treat a host source reset and cleared notes as new checkpoint output', async () => { - addSource('\nlemma retained_candidate : True := by trivial\n'); - const paused = await pauseCheckpoint(checkpoint('A retained supporting calculation.')); - fs.writeFileSync(path.join(directory, 'generated/p/Submission.lean'), - 'theorem goal : True := by sorry\n'); - git(directory, ['add', '--', 'generated']); checkpoint(''); - (cooperative as any).changed(); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toEqual(paused); - addSource('\nlemma genuinely_new_candidate : True := by trivial\n'); checkpoint(''); - (cooperative as any).changed(); - expect(record.status).toBe('pending'); - }); - - it('keeps a checkpoint paused when HEAD returns to an older nonempty draft', async () => { - const paused = await pauseCheckpoint(checkpoint('The saved argument and exact remaining step.')); - git(directory, ['reset', '--hard', seed]); - (cooperative as any).changed(); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toEqual(paused); - }); - - it('does not attribute output from a suspended worktree to its previous task session', async () => { - const paused = await pauseCheckpoint(); - state.workers = [{ id: researcher.id, sessionTaskId: record.task.id, - sessionTaskVersion: taskVersion(record.task) }] as SolverRunState['workers']; - state.cooperation!.researchDrafts!.question.suspended = true; - addSource('\nlemma another_responsibility : True := by trivial\n'); - checkpoint('Nonempty notes saved after the old task released its worktree.'); - (cooperative as any).changed(); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toEqual(paused); - state.environmentDigest = 'new-environment'; - (cooperative as any).changed(); - expect(record.status).toBe('pending'); - }); - - it.each(['', undefined])('reopens for genuinely new owned Lean even with %j notes', async notes => { - await pauseCheckpoint(); - addSource('\nlemma new_construction : True := by trivial\n'); checkpoint(notes); - (cooperative as any).changed(); - expect(record.status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints!.question).toBeUndefined(); - }); - - it('restores a legacy checkpoint pause despite cleared notes in the live worktree', async () => { - const paused = await pauseCheckpoint(); - checkpoint(''); - const restoredState = JSON.parse(JSON.stringify(state)); - const resumed = resume(restoredState); - try { - await resumed.restore(); - expect(restoredState.cooperation.tasks[0].status).toBe('blocked'); - expect(restoredState.cooperation.researchCheckpoints.question).toEqual(paused); - } finally { await resumed.stop(); } - }); - - it('requires fresh input when a legacy checkpoint has no matching saved output baseline', async () => { - const paused = await pauseCheckpoint(); - delete state.cooperation!.researchDrafts!.question; - checkpoint('Unattributed nonempty output in an old worktree.'); - (cooperative as any).changed(); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toEqual(paused); - state.environmentDigest = 'new-environment'; - (cooperative as any).changed(); - expect(record.status).toBe('pending'); - }); - - it('continues indefinitely while advisory checkpoints save different notes or drafts', async () => { - for (let attempt = 0; attempt < 6; attempt++) { - record.status = 'running'; - const commit = checkpoint(`Investigation checkpoint ${attempt}: a distinct saved intermediate calculation.`); - await cooperative.deliver(researcher, action, commit, true); - expect(record.status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints!.question).toMatchObject({ count: 1, paused: false, - unchangedEvidenceCount: attempt + 1, candidateStatus: 'unclassified-draft' }); - } - }); - - it('does not count transport interruptions as repeated checkpoints', async () => { - await cooperative.deliver(researcher, action, seed, true); - for (let attempt = 0; attempt < 5; attempt++) { - record.status = 'running'; - cooperative.interrupted(researcher, action); - } - expect(record.status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints!.question).toMatchObject({ count: 1, paused: false }); - }); - - it.each(['peer', 'environment', 'notes', 'draft'] as const)('reopens an exact checkpoint pause after new %s input', async change => { - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - expect(record.status).toBe('blocked'); - if (change === 'environment') state.environmentDigest = 'new-environment'; - else if (change === 'peer') { - (cooperative as any).record(lead, record.task, 'progress', 'advisory', 'A peer supplies a distinct library connection.'); - } else if (change === 'notes') checkpoint('A new saved calculation is available.'); - else { - addSource('\nlemma candidate : True := by trivial\n'); - checkpoint('Inherited research notes.'); - } - (cooperative as any).changed(); - expect(record.status).toBe('pending'); - expect(record.feedback).toBeUndefined(); - expect(state.cooperation!.researchCheckpoints!.question).toBeUndefined(); - expect(state.cooperation!.blockers!.find(record => record.mechanism === 'unchanged-research-checkpoint')!.status).toBe('reopened'); - }); - - it('preserves an unchanged checkpoint pause through serialization and restore', async () => { - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - const restoredState = JSON.parse(JSON.stringify(state)); - const resumed = resume(restoredState); - try { - await resumed.restore(); - expect(restoredState.cooperation.tasks[0].status).toBe('blocked'); - expect(restoredState.cooperation.researchCheckpoints.question).toMatchObject({ count: 3, paused: true }); - } finally { await resumed.stop(); } - }); - - it('does not reopen a paused checkpoint for unrelated peer work or canonical helper changes', async () => { - const proofWorkspace = path.join(directory, 'isolated-researcher'); - fs.appendFileSync(path.join(directory, '.git/info/exclude'), '\nisolated-researcher/\n'); - git(directory, ['worktree', 'add', '--detach', '--quiet', proofWorkspace, seed]); - (researcher as { worktree: string }).worktree = proofWorkspace; - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - const paused = structuredClone(state.cooperation!.researchCheckpoints!.question); - const unrelated = node('unrelated', 'research'); - state.cooperation!.tasks.push(unrelated); - (cooperative as any).record(lead, unrelated.task, 'progress', 'advisory', 'A distinct result on another question.'); - addSource('\nlemma unrelated_helper : True := by trivial\n'); - state.cooperation!.canonicalCommit = checkpoint('Inherited research notes.'); - (cooperative as any).changed(); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toEqual(paused); - expect((cooperative as any).checkpointInputDigest(record.task, researcher.id)).not.toBe(paused.inputDigest); - expect((cooperative as any).checkpointLocalInputDigest(record.task, researcher.id)).toBe(paused.localInputDigest); - }); - - it.each(['running-assignment', 'different-session', 'new-task-version', 'reviewer'] as const)( - 'does not reopen an old checkpoint from another responsibility output (%s)', async responsibility => { - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - if (responsibility === 'running-assignment') { - const other = node('another-investigation', 'research'); other.status = 'running'; - other.assignment = { taskId: other.task.id, taskDigest: taskVersion(other.task), workerId: researcher.id, seedCommit: seed }; - state.cooperation!.tasks.push(other); - } else state.workers = [{ id: researcher.id, sessionTaskId: responsibility === 'different-session' ? 'other' : - responsibility === 'reviewer' ? undefined : record.task.id, - sessionTaskVersion: responsibility === 'new-task-version' ? 'new-version' : taskVersion(record.task), - }] as SolverRunState['workers']; - checkpoint('Notes saved for a different assigned responsibility.'); - (cooperative as any).changed(); - expect(record.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.question).toMatchObject({ count: 3, paused: true }); - }); - - it('reopens a checkpoint for new notes owned by the same task session and version', async () => { - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - record.status = 'running'; - await cooperative.deliver(researcher, action, seed, true); - state.workers = [{ id: researcher.id, sessionTaskId: record.task.id, sessionTaskVersion: taskVersion(record.task) }] as SolverRunState['workers']; - checkpoint('A new saved calculation for this exact investigation.'); - (cooperative as any).changed(); - expect(record.status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints!.question).toBeUndefined(); - }); - - const failureChecker = (result: Record = {}, verification: Record = {}) => { - // These fixtures exercise local repair and rejection reuse under ordinary dependency waiting. - const goal = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!; - goal.task = { ...goal.task, conditional: false }; - record.task = { ...record.task, kind: 'lemma', theoremName: 'question', proofPath: 'Submission.lean', type: 'True' }; - record.assignment!.taskDigest = taskVersion(record.task); - record.attempts = 1; - action = { kind: 'task', task: record.task, assignment: record.assignment! }; - const checkTask = vi.fn(async (_problem, worktree, commit, task, assignment, _goals, _environment, _signal, _timeout, conditions) => ({ - commit, sourceDigest: ownedSourceDigest(state.problem, worktree, commit), seedCommit: assignment.seedCommit, - taskDigest: taskVersion(task), passed: false, changes: [], imports: [], - conditions: conditions.map((task: TaskRecord['task']) => ({ taskId: task.id, taskDigest: taskVersion(task) })), - verification: { status: 'failed', targetCommit: commit, results: [{ status: 'failed', targetCommit: commit, - error: 'Lean exited with status 1.', stdoutPreview: 'Submission.lean:1:1: error: unsolved goals\n⊢ True', ...result }], ...verification }, - }) as TaskProof); - (cooperative as any).input.modules = { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask } }; - (cooperative as any).input.access.set(lead.id, { environment: {} }); - return checkTask; - }; - - it('checks an identical failed helper once across live submissions and completed delivery', async () => { - const checkTask = failureChecker(); - const submission = { id: 'failure_one', kind: 'proof', taskId: record.task.id, taskDigest: action.assignment.taskDigest, - commit: seed, summary: 'The same saved candidate.' }; - await (cooperative as any).receive(researcher, action, submission); - const repair = await cooperative.next(researcher, budget); - if (repair?.kind !== 'task') throw new Error('expected_local_repair'); - expect(cooperative.started(researcher, repair)).toBe(true); - await (cooperative as any).receive(researcher, action, { ...submission, id: 'failure_two' }); - await cooperative.deliver(researcher, action, seed); - expect(checkTask).toHaveBeenCalledTimes(1); - expect(record.status).toBe('blocked'); - }); - - it.each(['missing', 'ambiguous'] as const)('retains exact failures without linking a %s target as the same attempt', async invalid => { - const checkTask = failureChecker(); - if (invalid === 'ambiguous') fs.appendFileSync(path.join(directory, 'generated/p/Submission.lean'), - '\nnamespace A\nlemma question : True := by trivial\nend A\n' + - 'namespace B\nlemma question : True := by trivial\nend B\n'); - git(directory, ['add', '--', 'generated']); - const first = checkpoint('The required target has no unique declaration.'); - await check(first); - addSource('\nlemma unrelated : True := by trivial\n'); - await check(checkpoint('The target still has no unique declaration.')); - expect(checkTask).toHaveBeenCalledTimes(2); - expect(state.cooperation!.failedTaskInputs).toHaveLength(2); - for (const failure of state.cooperation!.failedTaskInputs!) { - expect(failure.attemptFingerprint).toBeUndefined(); - expect(failure.relatedFailureIds).toBeUndefined(); - } - }); - - it.each(['source', 'environment', 'environment-variable', 'build', 'evaluator', 'conditions'] as const)( - 'rechecks a failed helper after changed %s', async change => { - const checkTask = failureChecker(); - await check(); - if (change === 'environment') state.environmentDigest = 'new-environment'; - else if (change === 'environment-variable') (cooperative as any).input.access.get(lead.id).environment.LEAN_PATH = '/updated/lean'; - else if (change === 'build') state.buildDigest = 'repaired-verifier-build'; - else if (change === 'evaluator') state.evaluatorDigest = 'repaired-verifier-evaluator'; - else if (change === 'source') { - addSource('\nlemma candidate : True := by trivial\n'); - } - const commit = change === 'source' ? checkpoint('Inherited research notes.') : seed; - await check(commit, change === 'conditions' ? [node('condition').task] : []); - expect(checkTask).toHaveBeenCalledTimes(2); - }); - - it('preserves unlimited checker timeouts without treating timeout changes as new mathematics', async () => { - const checkTask = failureChecker(); - (cooperative as any).input.timeoutMs = Infinity; - await check(); - expect(checkTask.mock.calls[0][8]).toBe(Infinity); - for (const timeout of [Infinity, undefined, 999]) { - (cooperative as any).input.timeoutMs = timeout; - await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - } - record.task = { ...record.task, revision: 1 }; - record.assignment!.taskDigest = taskVersion(record.task); - await expect(check()).rejects.toThrow('math_task_repeated_failed_input'); - expect(checkTask).toHaveBeenCalledTimes(1); - }); - - it('links a moved failed target as a repeated attempt while still checking its changed full source', async () => { - const checkTask = failureChecker(); - addSource('\nlemma question : True := by sorry\n'); - const first = checkpoint('Saved failed target.'); - await check(first); - fs.writeFileSync(path.join(directory, 'generated/p/Submission.lean'), - 'theorem goal : True := by sorry\n\nlemma unrelated_helper : True := by trivial\n\nlemma question : True := by sorry\n'); - git(directory, ['add', '--', 'generated']); - const second = checkpoint('The same target after an unrelated insertion.'); - await check(second); - expect(checkTask).toHaveBeenCalledTimes(2); - const failures = state.cooperation!.failedTaskInputs!; - expect(failures).toHaveLength(2); - expect(failures[0].sourceDigest).not.toBe(failures[1].sourceDigest); - expect(failures[0].targetDigest).not.toBe(failures[1].targetDigest); - expect(failures[0].attemptFingerprint).toBe(failures[1].attemptFingerprint); - expect(failures[1].relatedFailureIds).toEqual([failures[0].id]); - }); - - it('rechecks a failed helper after its dependency proof changes', async () => { - const checkTask = failureChecker(); - const helper = integrated(node('dependency')); - helper.integratedCheck!.changes = [{ file: 'Submission.lean', name: helper.task.theoremName!, - after: 'lemma dependency : True := by trivial\n' }]; - markTaskAcceptance(helper.integratedCheck!); - state.cooperation!.tasks.push(helper); - record.task = { ...record.task, dependsOn: [helper.task.id] }; - record.assignment!.taskDigest = taskVersion(record.task); - await check(); - helper.integratedCheck!.changes[0].after = 'lemma dependency : True := by exact True.intro\n'; - markTaskAcceptance(helper.integratedCheck!); - await check(); - expect(checkTask).toHaveBeenCalledTimes(2); - }); - - it('honors cancellation before reusing a failed helper check', async () => { - const checkTask = failureChecker(); - await check(); - const controller = new AbortController(); controller.abort(); - (cooperative as any).input.signal = controller.signal; - await expect(check()).rejects.toThrow(); - expect(checkTask).toHaveBeenCalledTimes(1); - }); - - it.each([ - { result: { cleanupError: 'failed to remove checkout' } }, - { result: { stdoutPreview: 'compiler process exited without Lean diagnostics' } }, - { result: { status: 'blocked' } }, - { verification: { status: 'blocked' } }, - { verification: { status: 'unavailable' } }, - ])('never reuses an unavailable, incomplete, or unclean helper check ($result, $verification)', async ({ result, verification }) => { - const checkTask = failureChecker(result, verification); - for (let attempt = 0; attempt < 2; attempt++) - await check(); - expect(checkTask).toHaveBeenCalledTimes(2); - }); - - it('keeps failure suppression local to delivery checks and persistent across runtime restart', async () => { - const checkTask = failureChecker(); - await check(); - await (cooperative as any).check(record.task, record.assignment, directory, seed, []); - expect(checkTask).toHaveBeenCalledTimes(2); - const resumed = resume(JSON.parse(JSON.stringify(state)), { access: (cooperative as any).input.access, - modules: (cooperative as any).input.modules }); - try { await expect((resumed as any).check(record.task, record.assignment, directory, seed, [], undefined, true)) - .rejects.toThrow('math_task_repeated_failed_input'); } - finally { await resumed.stop(); } - expect(checkTask).toHaveBeenCalledTimes(2); - }); - - it('reopens a serialized helper parked by an old verifier and rechecks its saved source', async () => { - const checkTask = failureChecker({ stdoutPreview: 'Submission.lean:1:1: error: Unknown identifier `E`' }); - addSource('\ntheorem question : True := by trivial\n'); - seed = checkpoint('Saved helper rejected by the old projection.'); - state.cooperation!.canonicalCommit = seed; - record.assignment!.seedCommit = seed; - const submission = { id: 'old_projection_failure', kind: 'proof', taskId: record.task.id, - taskDigest: action.assignment.taskDigest, commit: seed, summary: 'Saved helper using an original definition.' }; - await (cooperative as any).receive(researcher, action, submission); - const repair = await cooperative.next(researcher, budget); - if (repair?.kind !== 'task') throw new Error('expected_local_repair'); - expect(cooperative.started(researcher, repair)).toBe(true); - await (cooperative as any).receive(researcher, action, { ...submission, id: 'old_projection_repeated' }); - await cooperative.deliver(researcher, action, seed); - expect(record.status).toBe('blocked'); - expect(record.feedback).toContain('math_task_repeated_failed_input'); - const restored = JSON.parse(JSON.stringify(state)) as SolverRunState; - restored.buildDigest = 'repaired-projection-build'; - const resumed = resume(restored, { access: (cooperative as any).input.access, - modules: (cooperative as any).input.modules }); - try { - expect((resumed as any).refreshFailedTaskInputs()).toBe(true); - const task = restored.cooperation!.tasks.find(node => node.task.id === record.task.id)!; - expect(task.status).toBe('pending'); expect(task.feedback).toBeUndefined(); - await (resumed as any).check(task.task, task.assignment, directory, seed, [], undefined, true); - expect(checkTask).toHaveBeenCalledTimes(2); - expect(checkTask.mock.calls[1][2]).toBe(seed); - } finally { await resumed.stop(); } - }); - - it('binds unchanged repetitions to the task version and inherited notes content', async () => { - await cooperative.deliver(researcher, action, seed); - seed = checkpoint('A different inherited checkpoint.'); - record.assignment!.seedCommit = seed; record.status = 'running'; - await cooperative.deliver(researcher, action, seed); - expect(record.status).toBe('pending'); - expect(state.cooperation!.unchangedResearch!.question.count).toBe(1); - await (cooperative as any).acceptPlan({ tasks: [ - { ...record.task, revision: 1 }, state.cooperation!.tasks[1].task, - ], groups: [{ ...main.group }] }); - expect(state.cooperation!.unchangedResearch!.question).toBeUndefined(); - record = state.cooperation!.tasks[0]; - record.assignment = { taskId: record.task.id, taskDigest: taskVersion(record.task), workerId: researcher.id, seedCommit: seed }; - record.status = 'running'; action = { kind: 'task', task: record.task, assignment: record.assignment }; - await cooperative.deliver(researcher, action, seed); - expect(record.status).toBe('pending'); - expect(state.cooperation!.unchangedResearch!.question.count).toBe(1); - }); - - it('wakes idle peers on model budget changes and does not schedule pending reviews', async () => { - record.status = 'blocked'; - let settled = false; - const pending = cooperative.next(researcher, budget).then(value => { settled = true; return value; }); - await new Promise(resolve => setImmediate(resolve)); - expect(settled).toBe(false); - state.cooperation!.review = { status: 'pending', commit: seed, sourceDigest: 'source' }; - allowed = false; cooperative.modelBudgetChanged(); - await expect(pending).resolves.toBeUndefined(); - await expect(cooperative.next(lead, budget)).resolves.toBeUndefined(); - expect(state.cooperation!.review.status).toBe('pending'); - state.cooperation!.review = undefined; - state.cooperation!.statementReviews = [{ taskId: 'question', status: 'pending' }] as CooperationState['statementReviews']; - await expect(cooperative.next(lead, budget)).resolves.toBeUndefined(); - expect(state.cooperation!.statementReviews[0].status).toBe('pending'); - }); - - it('waits for active work to settle after budget exhaustion while allowing host assembly', async () => { - cooperative.activate(researcher, action, async () => {}, async () => {}); - allowed = false; - let settled = false; - const pending = cooperative.next(lead, budget).then(value => { settled = true; return value; }); - await new Promise(resolve => setImmediate(resolve)); - expect(settled).toBe(false); - record.status = 'completed'; state.cooperation!.tasks[1].status = 'integrated'; - vi.spyOn(cooperative as any, 'seed').mockReturnValue(seed); - cooperative.deactivate(researcher); - await expect(pending).resolves.toMatchObject({ kind: 'assemble' }); - }); -}); diff --git a/tests/solverContinuationCapacity.test.ts b/tests/solverContinuationCapacity.test.ts deleted file mode 100644 index 134724e9..00000000 --- a/tests/solverContinuationCapacity.test.ts +++ /dev/null @@ -1,310 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LEAN_EVAL_BENCHMARK_COMMIT } from '../src/math/leanEvalCatalogAdapter'; -import { canonicalMathProblemStatementPayloads, type MathProblemContract } from '../src/math/contracts'; -import { hashMathFormalSourceDeclaration } from '../src/math/leanSource'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import { projectMathematicsRuntimeEnvironment } from '../src/math/mathRuntimeEnvironment'; -import { MATH_PROOF_ENVIRONMENT_ENV } from '../src/math/mathProofEnvironment'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { seedSolverContinuation } from '../src/solver/continuationSeed'; -import { createCapacityExploration, currentCapacityExploration, type CapacityExplorationFocus } from '../src/solver/capacityExploration'; -import { readContinuationPage, readContinuationSnapshot } from '../src/solver/continuationInput'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import type { TaskProof } from '../src/solver/cooperativeProof'; -import { verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), build: vi.fn(), prepare: vi.fn(), dispose: vi.fn(), - resolvePackages: vi.fn(), packages: undefined as string | undefined })); -vi.mock('../src/math/mathBuildManifest', async importOriginal => ({ ...await importOriginal(), - readMathBuildManifest: host.build })); -vi.mock('../src/math/verifier', async importOriginal => ({ ...await importOriginal(), - checkManyFormalVerifications: host.verify, resolveMathematicsLakePackagesCache: host.resolvePackages })); -vi.mock('../src/math/mathProofEnvironment', async importOriginal => ({ ...await importOriginal(), - prepareMathProofEnvironment: host.prepare })); - -const roots: string[] = []; -const original = 'import Submission.Helpers\nnamespace Submission\ntheorem original : True := by sorry\nend Submission\n'; -const emptyHelpers = 'namespace Submission.Helpers\nend Submission.Helpers\n'; -const helpers = 'namespace Submission.Helpers\nlemma first_helper : True := by trivial\nlemma second_helper : True := by trivial\nend Submission.Helpers\n'; -const commit = (root: string, message: string) => { - git(root, ['add', '--', '.']); - git(root, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--quiet', '--no-gpg-sign', '-m', message]); - return git(root, ['rev-parse', 'HEAD']); -}; - -function fixture() { - const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'continuation-seed-test-'))); roots.push(root); - const workspace = path.join(root, 'workspace'), projectRelative = 'generated/fixture', project = path.join(workspace, projectRelative); - fs.mkdirSync(path.join(project, 'Submission'), { recursive: true }); - const trusted = { 'Challenge.lean': 'theorem challenge : True := by trivial\n', - 'config.json': '{"theorem_names":["original"]}\n', 'holes.json': '{"id":"fixture","holes":[{"name":"original"}]}\n', - 'lean-toolchain': 'leanprover/lean4:v4.31.0\n', 'lakefile.toml': 'name = "fixture"\n[[lean_lib]]\nname = "Submission"\n' }; - for (const [file, text] of Object.entries(trusted)) fs.writeFileSync(path.join(project, file), text); - fs.writeFileSync(path.join(project, 'Submission.lean'), original); - fs.writeFileSync(path.join(project, 'Submission/Helpers.lean'), emptyHelpers); - git(workspace, ['init', '--quiet']); const base = commit(workspace, 'Public solver baseline'); - fs.appendFileSync(path.join(workspace, '.git/info/exclude'), `\n/${projectRelative}/.lake/\n/active-problem.json\n`); - const payloads = canonicalMathProblemStatementPayloads({ informalStatement: 'Prove the original claim.', formalStatement: original, assumptions: [] }); - const contract: MathProblemContract = { problemId: 'fixture', informalStatement: 'Prove the original claim.', formalStatement: original, - assumptions: [], knownTraps: [], acceptanceCriteria: ['Prove original'], officialVerificationCommand: 'lake test', - statementHash: mathDigest(payloads.informal), leanStatementHash: mathDigest(payloads.lean) }; - const receiptFile = path.join(workspace, 'active-problem.json'); - fs.writeFileSync(receiptFile, JSON.stringify({ schema: 'deepscientist.mathematics.lean-eval-bootstrap-receipt.v1', - receiptId: 'fixture', problemId: 'fixture', benchmarkCommit: LEAN_EVAL_BENCHMARK_COMMIT, catalogHash: 'a'.repeat(64), - leaderboardSource: 'disabled', contract, workspaceRoot: workspace, projectRoot: project, activeProblemPath: receiptFile, - createdAt: 1, trustedFiles: Object.keys(trusted), solverOwnedFiles: ['Submission.lean', 'Submission/Helpers.lean'], - publicObligations: [{ name: 'Submission.original', declarationHash: hashMathFormalSourceDeclaration(original, 'Submission.original') }] })); - const problem = readSolverProblem(workspace, receiptFile); - const oldDirectory = path.join(root, 'old.json.runtime'), directory = path.join(root, 'new.json.runtime'); - for (const parent of [oldDirectory, directory]) { - fs.mkdirSync(parent, { mode: 0o700 }); - for (const name of ['worktree', 'worktree-2']) git(workspace, ['worktree', 'add', '--quiet', '--detach', path.join(parent, name), base]); - } - const sourceWorktree = path.join(oldDirectory, 'worktree'), worktree = path.join(directory, 'worktree'); - fs.writeFileSync(path.join(sourceWorktree, projectRelative, 'Submission/Helpers.lean'), helpers); - const canonical = commit(sourceWorktree, 'Historical helpers'); - const notes = '\ufeffunfinished λ notes\r\n'; - fs.writeFileSync(path.join(oldDirectory, 'worktree-2', projectRelative, 'Submission/Helpers.lean'), helpers.replace('by trivial', 'by sorry')); - fs.writeFileSync(path.join(oldDirectory, 'worktree-2', 'RESEARCH.md'), notes); - fs.writeFileSync(path.join(sourceWorktree, 'RESEARCH.md'), 'Old Lead findings, still advisory.\n'); - const tasks: CooperativeTask[] = ['first', 'second'].map(name => ({ id: name, kind: 'lemma', objective: `Prove ${name}`, - dependsOn: [], revision: 0, ownerId: 'prover-1', proofPath: 'Submission/Helpers.lean', - theoremName: `Submission.Helpers.${name}_helper`, type: 'True' })); - tasks.push({ id: 'goal', kind: 'goal', objective: 'Prove original', dependsOn: [], revision: 0, - proofPath: 'Submission.lean', theoremName: 'Submission.original' }); - const archivedProof = (task: CooperativeTask): TaskProof => ({ commit: canonical, sourceDigest: 'old-source', passed: true, - taskDigest: taskVersion(task), seedCommit: base, changes: [], verification: { status: 'kernel_verified', targetCommit: canonical, - results: [{ status: 'kernel_verified', targetCommit: canonical, receiptId: `old-${task.id}` }] } as TaskProof['verification'] }); - const buildFile = path.join(root, 'manifest.json'); fs.writeFileSync(buildFile, '{"fixture":"new-build"}', { mode: 0o400 }); - const skeleton = { schema: 'deepscientist.math.solver.v1' as const, problem, taskDigest: mathDigest('Original unchanged task.\n'), - environmentDigest: mathDigest('new-environment'), evaluatorDigest: mathDigest('host-default'), model: 'fixture', effort: 'max', - coordination: 'cooperative' as const, turns: 0, dispatchCounts: {}, workerCount: 2 }; - const newState: SolverRunState = { ...skeleton, runId: 'new-run', buildDigest: mathDigest(fs.readFileSync(buildFile)), - methodDigest: 'new-method', phase: 'prepared', worktree, workers: [ - { id: 'solver', role: 'lead', worktree, phase: 'prepared', turns: 0, dispatchCounts: {} }, - { id: 'prover-1', role: 'prover', worktree: path.join(directory, 'worktree-2'), phase: 'prepared', turns: 0, dispatchCounts: {} }] }; - const oldState: SolverRunState = { ...skeleton, runId: 'old-run', buildDigest: 'historical-build', methodDigest: 'old-method', - phase: 'running', turns: 8, worktree: sourceWorktree, workers: [ - { id: 'solver', role: 'lead', worktree: sourceWorktree, phase: 'running', turns: 3, threadId: 'old-lead-thread' }, - { id: 'prover-1', role: 'prover', worktree: path.join(oldDirectory, 'worktree-2'), phase: 'running', turns: 5, threadId: 'old-prover-thread' }], - cooperation: { canonicalCommit: canonical, planVersion: 'historical-plan', groups: [{ group: { - id: 'main', objective: 'Original route', status: 'active', revision: 0 }, turns: 8 }], - tasks: tasks.map(task => ({ task, status: task.kind === 'goal' ? 'running' : 'integrated', attempts: 2, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'prover-1', seedCommit: base, assignmentId: `old-${task.id}` }, - ...(task.kind === 'lemma' ? { integratedCheck: archivedProof(task) } : {}) })), - deliveries: [{ id: 'old-delivery', producer: 'prover-1', kind: 'proof', status: 'verified', statement: 'True', premises: [], - dependencies: [], remainingObligations: [], summary: 'Historical check', evidenceRefs: [], createdAt: 1 }] } }; - const stateFile = path.join(directory, 'state.json'), sourceStateFile = path.join(oldDirectory, 'state.json'); - writeSolverRunState(stateFile, newState); writeSolverRunState(sourceStateFile, oldState); - const environmentFile = path.join(directory, 'environment-solver.json'); - host.packages = path.join(root, 'packages'); fs.mkdirSync(host.packages); - fs.writeFileSync(environmentFile, canonicalMathJson(projectMathematicsRuntimeEnvironment({ PATH: '/usr/bin:/bin', - DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages, - [MATH_PROOF_ENVIRONMENT_ENV]: 'disposed-startup-only-fixture' })), { mode: 0o400 }); - const controller = new AbortController(); - const options = { sourceRun: sourceStateFile, run: stateFile, root, buildManifest: buildFile, signal: controller.signal }; - return { root, directory, oldDirectory, workspace, worktree, sourceWorktree, projectRelative, stateFile, sourceStateFile, - newState, oldState, tasks, notes, base, environmentFile, options, controller, seed: () => seedSolverContinuation(options) }; -} - - -beforeEach(() => { - host.build.mockReset(); host.verify.mockReset(); host.prepare.mockReset(); host.dispose.mockReset(); host.resolvePackages.mockReset(); - host.resolvePackages.mockImplementation(() => host.packages); - host.dispose.mockResolvedValue(undefined); - host.prepare.mockResolvedValue({ environmentValue: 'fresh-capacity-seed-environment', dispose: host.dispose, - stats: { files: 0, bytes: 0, publications: 1 } }); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => verifiedBatch(request, - { sessionId: 'fresh-capacity-seed', receipt: 'fresh-capacity-seed', checks: true })); -}); -afterEach(() => { vi.restoreAllMocks(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); - -type Fixture = ReturnType; -function addExploration(f: Fixture, focus: CapacityExplorationFocus, status: TaskRecord['status'] = 'running', - workerId = 'prover-1', environmentDigest = f.oldState.environmentDigest) { - const target = f.oldState.cooperation!.tasks.find(node => node.task.id === 'goal')!; - const node = createCapacityExploration(target, { id: workerId }, f.oldState.cooperation!.tasks, - { environmentDigest, problemReceiptDigest: f.oldState.problem.receiptDigest }, focus); - node.status = status; node.attempts = 7; - node.finding = JSON.stringify({ summary: `Retained ${focus} investigation`, conclusion: 'inconclusive' }); - node.assignment = { taskId: node.task.id, taskDigest: taskVersion(node.task), workerId, - assignmentId: 'old-capacity-assignment', seedCommit: f.base }; - node.proof = f.oldState.cooperation!.tasks[0].integratedCheck; - node.integratedCheck = node.proof; - f.oldState.cooperation!.tasks.push(node); - (f.oldState.cooperation!.capacityExplorationInputs ??= []).push({ - inputDigest: node.capacityExploration!.inputDigest, focus, targetTaskId: target.task.id, taskId: node.task.id }); - return node; -} - -function publishNotes(f: Fixture, node: TaskRecord) { - const text = '\ufeffComplete saved λ candidate\r\n```lean\nnamespace Scratch\nlemma candidate : True := by trivial\nend Scratch\n```\n'; - fs.writeFileSync(path.join(f.sourceWorktree, 'RESEARCH.md'), text); - const notesCommit = commit(f.sourceWorktree, 'Immutable capacity finding'); - f.oldState.cooperation!.deliveries!.push({ id: 'capacity-research-delivery', producer: node.capacityExploration!.workerId, - taskId: node.task.id, taskDigest: taskVersion(node.task), kind: 'research', status: 'advisory', - statement: node.task.objective, premises: [], dependencies: [{ taskId: 'goal', - taskDigest: taskVersion(f.oldState.cooperation!.tasks.find(item => item.task.id === 'goal')!.task) }], - remainingObligations: ['goal'], summary: 'The complete code is retained in the immutable notes.', evidenceRefs: [], - createdAt: 1, commit: notesCommit, finding: node.finding }); - fs.writeFileSync(path.join(f.sourceWorktree, 'RESEARCH.md'), 'Later unrelated live notes must not replace the candidate.\n'); - return { text, notesCommit }; -} - -function saveSource(f: Fixture) { writeSolverRunState(f.sourceStateFile, f.oldState); } -function readCapacityAttachment(f: Fixture, digest: string) { - return JSON.parse(readContinuationPage(path.join(f.directory, 'continuation.json'), digest, 'seed-capacity-explorations').text); -} - -describe('capacity exploration continuation seeds', () => { - it('keeps host provenance and the method ledger while rechecking typed proofs and discarding assignments', async () => { - const f = fixture(), unfinished = addExploration(f, 'construction'), complete = addExploration(f, 'interface', 'completed'); - const delivered = publishNotes(f, complete); saveSource(f); - const sourceBytes = fs.readFileSync(f.sourceStateFile), liveNotes = fs.readFileSync(path.join(f.sourceWorktree, 'RESEARCH.md')); - const report = await f.seed(), state = readSolverRunState(f.stateFile), cooperation = state.cooperation!; - expect(report.checked).toEqual(['first', 'second']); expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][0].items.map(item => item.theoremName)) - .toEqual(['Submission.Helpers.first_helper', 'Submission.Helpers.second_helper']); - expect(cooperation.capacityExplorationInputs).toEqual(f.oldState.cooperation!.capacityExplorationInputs); - for (const sourceNode of [unfinished, complete]) { - const node = cooperation.tasks.find(item => item.task.id === sourceNode.task.id)!; - expect(node.capacityExploration).toEqual(sourceNode.capacityExploration); - expect(node.task).toEqual(sourceNode.task); expect(node.finding).toBe(sourceNode.finding); - expect(node.status).toBe(sourceNode.status === 'completed' ? 'completed' : 'pending'); - expect(node.attempts).toBe(0); expect(node.assignment).toBeUndefined(); - expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - expect(currentCapacityExploration(node, cooperation.tasks, { environmentDigest: state.environmentDigest, - problemReceiptDigest: state.problem.receiptDigest })).toBe(true); - } - expect(cooperation.tasks.filter(node => node.integratedCheck).map(node => node.task.id)).toEqual(['first', 'second']); - expect(cooperation.tasks[0].integratedCheck!.verification.results[0].receiptId).toContain('fresh-capacity-seed-'); - const frozenSource = JSON.parse(fs.readFileSync(path.join(f.directory, 'continuation-seed-source.json'), 'utf8')); - expect(frozenSource.plan.tasks.map((task: CooperativeTask) => task.id)).toEqual(['first', 'second', 'goal']); - expect(cooperation.planVersion).toBe(mathDigest(canonicalMathJson(frozenSource.plan))); - const capacity = readCapacityAttachment(f, state.continuationDigest!); - expect(capacity.notes).toEqual([{ taskId: complete.task.id, taskDigest: taskVersion(complete.task), - deliveryId: 'capacity-research-delivery', commit: delivered.notesCommit, notes: delivered.text }]); - expect(capacity.records).toHaveLength(2); - const snapshot = readContinuationSnapshot(path.join(f.directory, 'continuation.json'), state.continuationDigest!); - expect(snapshot.manifest.attachments.find(item => item.id === 'seed-capacity-explorations')!.provenance) - .toEqual({ evidence: 'recorded-not-replayed', runId: f.oldState.runId, source: f.sourceStateFile }); - expect(fs.readFileSync(f.sourceStateFile)).toEqual(sourceBytes); - expect(fs.readFileSync(path.join(f.sourceWorktree, 'RESEARCH.md'))).toEqual(liveNotes); - }); - - it.each(['environment', 'target', 'owner', 'stopped'] as const)('archives a stale %s binding without changing its provenance or ledger', async reason => { - const f = fixture(), node = addExploration(f, 'decomposition', 'running', reason === 'owner' ? 'former-prover' : 'prover-1', - reason === 'environment' ? mathDigest('previous-environment') : f.oldState.environmentDigest); - if (reason === 'target') { - const target = f.oldState.cooperation!.tasks.find(item => item.task.id === 'goal')!; - target.task = { ...target.task, objective: 'A changed target contract revision', revision: 1 }; - } - if (reason === 'stopped') node.task = { ...node.task, status: 'stopped' }; - saveSource(f); await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.some(item => item.task.id === node.task.id)).toBe(false); - expect(state.cooperation!.history).toContainEqual({ task: node.task, capacityExploration: node.capacityExploration, - status: 'running', producer: node.capacityExploration!.workerId, finding: node.finding }); - expect(state.cooperation!.capacityExplorationInputs).toEqual(f.oldState.cooperation!.capacityExplorationInputs); - expect(readCapacityAttachment(f, state.continuationDigest!).records[0].capacityExploration).toEqual(node.capacityExploration); - await expect(f.seed()).resolves.toMatchObject({ stage: 'complete' }); - }); - - it('retains previously archived host records as history without scheduling them again', async () => { - const f = fixture(), node = addExploration(f, 'boundary', 'completed'); - f.oldState.cooperation!.tasks = f.oldState.cooperation!.tasks.filter(item => item !== node); - f.oldState.cooperation!.history = [{ task: node.task, finding: node.finding, - ...{ capacityExploration: node.capacityExploration, status: node.status, producer: 'prover-1' } }]; - saveSource(f); await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.cooperation!.tasks.map(item => item.task.id)).toEqual(['first', 'second', 'goal']); - expect(state.cooperation!.history).toContainEqual({ task: node.task, capacityExploration: node.capacityExploration, - status: 'completed', producer: 'prover-1', finding: node.finding }); - expect(readCapacityAttachment(f, state.continuationDigest!).records[0].archived).toBe(true); - await expect(f.seed()).resolves.toMatchObject({ stage: 'complete' }); - }); - - it('retries an interrupted seed from the frozen host records and complete saved notes', async () => { - const f = fixture(), node = addExploration(f, 'interface', 'completed'), delivered = publishNotes(f, node); saveSource(f); - await expect(seedSolverContinuation({ ...f.options, onProgress: event => { - if (event === 'continuation_seed_checked') f.controller.abort(); - } })).rejects.toThrow(); - const sourceFile = path.join(f.directory, 'continuation-seed-source.json'), frozen = fs.readFileSync(sourceFile); - const digest = readSolverRunState(f.stateFile).continuationDigest; - f.oldState.cooperation!.capacityExplorationInputs = []; f.oldState.cooperation!.tasks.pop(); saveSource(f); - fs.writeFileSync(path.join(f.sourceWorktree, 'RESEARCH.md'), 'The source changed after the capture.'); - await seedSolverContinuation({ ...f.options, signal: new AbortController().signal }); - const state = readSolverRunState(f.stateFile); - expect(state.continuationDigest).toBe(digest); expect(fs.readFileSync(sourceFile)).toEqual(frozen); - expect(state.cooperation!.tasks.find(item => item.task.id === node.task.id)!.status).toBe('completed'); - expect(state.cooperation!.capacityExplorationInputs).toHaveLength(1); - expect(readCapacityAttachment(f, state.continuationDigest!).notes[0].notes).toBe(delivered.text); - }); - - it('keeps old frozen seeds without capacity fields byte compatible on retry', async () => { - const f = fixture(); await f.seed(); - const sourceFile = path.join(f.directory, 'continuation-seed-source.json'), frozen = fs.readFileSync(sourceFile); - const previous = readSolverRunState(f.stateFile), snapshot = fs.readFileSync(path.join(f.directory, 'continuation.json')); - expect(JSON.parse(frozen.toString()).capacityExplorations).toBeUndefined(); - addExploration(f, 'boundary'); saveSource(f); - await f.seed(); - const state = readSolverRunState(f.stateFile); - expect(state.continuationDigest).toBe(previous.continuationDigest); expect(fs.readFileSync(sourceFile)).toEqual(frozen); - expect(fs.readFileSync(path.join(f.directory, 'continuation.json'))).toEqual(snapshot); - expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - expect(state.cooperation!.tasks.some(node => node.capacityExploration)).toBe(false); - }); - - it('carries complete immutable notes through another build after live delivery records were cleared', async () => { - const f = fixture(), node = addExploration(f, 'interface', 'completed'), delivered = publishNotes(f, node); saveSource(f); - await f.seed(); - const seeded = readSolverRunState(f.stateFile); - expect(seeded.cooperation!.deliveries).toEqual([expect.objectContaining({ id: 'capacity-research-delivery', - taskId: node.task.id, taskDigest: taskVersion(node.task), kind: 'research', status: 'advisory', - commit: delivered.notesCommit, finding: node.finding })]); - // Continuation preserves advisory publication provenance. Explicitly remove - // the live record to exercise recovery from the immutable notes attachment. - seeded.cooperation!.deliveries = []; - writeSolverRunState(f.stateFile, seeded); - expect(readSolverRunState(f.stateFile).cooperation!.deliveries).toEqual([]); - const directory = path.join(f.root, 'next.json.runtime'); fs.mkdirSync(directory, { mode: 0o700 }); - const worktree = path.join(directory, 'worktree'); - for (const name of ['worktree', 'worktree-2']) git(f.workspace, - ['worktree', 'add', '--quiet', '--detach', path.join(directory, name), f.base]); - const buildFile = path.join(f.root, 'next-manifest.json'); fs.writeFileSync(buildFile, '{"fixture":"next-build"}', { mode: 0o400 }); - const stateFile = path.join(directory, 'state.json'), next: SolverRunState = { ...f.newState, - runId: 'next-run', buildDigest: mathDigest(fs.readFileSync(buildFile)), methodDigest: 'next-method', worktree, - workers: f.newState.workers!.map((worker, index) => ({ ...worker, - worktree: path.join(directory, index ? `worktree-${index + 1}` : 'worktree') })) }; - writeSolverRunState(stateFile, next); - const environmentFile = path.join(directory, 'environment-solver.json'); - fs.writeFileSync(environmentFile, canonicalMathJson(projectMathematicsRuntimeEnvironment({ PATH: '/usr/bin:/bin', - DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS: host.packages, - [MATH_PROOF_ENVIRONMENT_ENV]: 'disposed-next-startup-fixture' })), { mode: 0o400 }); - await seedSolverContinuation({ ...f.options, sourceRun: f.stateFile, run: stateFile, buildManifest: buildFile }); - const state = readSolverRunState(stateFile), capacity = JSON.parse(readContinuationPage(path.join(directory, 'continuation.json'), - state.continuationDigest!, 'seed-capacity-explorations').text); - expect(capacity.notes[0].notes).toBe(delivered.text); expect(capacity.notes[0].commit).toBe(delivered.notesCommit); - expect(state.cooperation!.capacityExplorationInputs).toEqual(f.oldState.cooperation!.capacityExplorationInputs); - expect(state.cooperation!.tasks.find(item => item.task.id === node.task.id)!.capacityExploration).toEqual(node.capacityExploration); - expect(state.cooperation!.tasks.find(item => item.task.id === node.task.id)!.status).toBe('completed'); - expect(state.cooperation!.tasks.every(item => !item.assignment)).toBe(true); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(host.verify.mock.calls.map(([request]) => request.items.map(item => item.theoremName))).toEqual([ - ['Submission.Helpers.first_helper', 'Submission.Helpers.second_helper'], - ['Submission.Helpers.first_helper', 'Submission.Helpers.second_helper']]); - }); - - it('refuses a changed destination capacity ledger before reinstalling the frozen seed', async () => { - const f = fixture(); addExploration(f, 'construction'); saveSource(f); await f.seed(); - const state = readSolverRunState(f.stateFile); - state.cooperation!.capacityExplorationInputs![0].inputDigest = mathDigest('changed local input'); - writeSolverRunState(f.stateFile, state); - await expect(f.seed()).rejects.toThrow('math_continuation_seed_destination_changed'); - }); -}); diff --git a/tests/solverContinuousResearch.test.ts b/tests/solverContinuousResearch.test.ts deleted file mode 100644 index f87fb962..00000000 --- a/tests/solverContinuousResearch.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import fs from 'node:fs'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import type { SolverProblem } from '../src/solver/problem'; -import { setTaskStatus } from '../src/solver/taskLifecycle'; -import { parseCooperationPlan } from '../src/solver/tasks'; -import { answeredGoalPathStall, cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -// A failed original route is an ordinary Lead planning input. Once the Lead has decided on exactly these inputs and -// nothing runs, no process input can arrive, so dispatch ends the run instead of waiting for outside input. -describe('idle original-goal frontier', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - let modules: SolverModules, controller: AbortController, cooperation: CooperativeResearch | undefined; - let events: { event: string; details?: Record }[]; - - beforeEach(() => { - const example = localExample('solver-continuous-research-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'researcher')]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}`, - proofPath: target.proofPath, theoremName: target.theoremName, - })) }); - state = solverState(problem, example.workspace, { runId: 'continuous-research-fixture', phase: 'prepared', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'blocked', attempts: 1 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - modules = { ...directSolverModules, - M1: { ...directSolverModules.M1, open: vi.fn(async () => { throw new Error('fixture_unexpected_model'); }) } }; - controller = new AbortController(); events = []; cooperation = undefined; - }); - - afterEach(async () => { - controller.abort(); - await cooperation?.stop(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - const create = (continuous: boolean) => cooperation = cooperativeResearch({ state, workers, modules, retrievalRoot: directory, - continuousResearch: continuous, signal: controller.signal, emit: (event, details) => events.push({ event, details }) }); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - - it.each([true, false])('ends after the Lead already decided on the failed frontier (continuous=%s)', async continuous => { - const fixture = create(continuous); - state.cooperation!.planVersion = (fixture as any).planVersion(); - state.cooperation!.lastLeadInputDigest = (fixture as any).planningInputDigest(); - // That decision's context showed the stalled goal path, as every live Lead turn does. - expect(answeredGoalPathStall(state)).toBeDefined(); - - await expect(fixture.next(workers[0], budget)).resolves.toBeUndefined(); - - expect(events.filter(item => item.event === 'routes_idle')).toEqual([expect.objectContaining({ - details: expect.objectContaining({ reason: 'unchanged-mathematical-input' }) })]); - expect(state.cooperation!.tasks.every(node => node.status === 'blocked' && node.attempts === 1)).toBe(true); - expect(modules.M1.open).not.toHaveBeenCalled(); expect(state.turns).toBe(0); - }); - - it('reconsiders a failed frontier with new inputs in an ordinary Lead plan turn', async () => { - const fixture = create(true); - state.cooperation!.planVersion = (fixture as any).planVersion(); - - const action = await fixture.next(workers[0], budget); - - expect(action).toMatchObject({ kind: 'lead', planNonce: expect.any(String) }); - expect(action).not.toHaveProperty('recovery'); - expect(action).not.toHaveProperty('coordination'); - expect(events.some(item => item.event === 'routes_idle')).toBe(false); - }); - - it('waits on a stalled plan when a task starts, then reopens planning on new feedback', async () => { - const fixture = create(true); - state.cooperation!.planVersion = (fixture as any).planVersion(); - const goal = state.cooperation!.tasks[0]; - setTaskStatus(goal, 'pending', 'reopened'); - const reason = new Error('math_plan_changed_original_target'); - (fixture as any).rejectPlan(reason); - const first = state.cooperation!.planRejection!; - expect(first.stalled).toBe(false); - - setTaskStatus(goal, 'running', 'dispatched'); - (fixture as any).rejectPlan(reason); - expect(state.cooperation!.planRejection).toMatchObject({ inputDigest: first.inputDigest, stalled: true }); - - const waiting = vi.spyOn(fixture as any, 'waitForDispatch'); - const lead = fixture.next(workers[0], budget); - expect(waiting).toHaveBeenCalledOnce(); - setTaskStatus(goal, 'blocked', 'rejected'); - goal.feedback = 'The saved proof exposed an unavailable premise.'; - (fixture as any).changed(); - await expect(lead).resolves.toMatchObject({ kind: 'lead' }); - }); - - it.each([ - { continuous: true, restored: false }, - { continuous: true, restored: true }, - { continuous: false, restored: false }, - { continuous: false, restored: true }, - ])('ends on repeated invalid plans with continuous=$continuous, restored=$restored', async ({ continuous, restored }) => { - let fixture = create(continuous); - state.cooperation!.planVersion = (fixture as any).planVersion(); - (fixture as any).rejectPlan(new Error('math_plan_changed_original_target')); - (fixture as any).rejectPlan(new Error('math_plan_changed_original_target')); - expect(state.cooperation!.planRejection?.stalled).toBe(true); - if (restored) { - await fixture.stop(); - state = JSON.parse(JSON.stringify(state)); - fixture = create(continuous); - await fixture.restore(); - } - - await expect(fixture.next(workers[0], budget)).resolves.toBeUndefined(); - - expect(events.some(item => item.event === (continuous ? 'routes_idle' : 'plan_stalled'))).toBe(true); - expect(state.cooperation!.planRejection?.stalled).toBe(true); - expect(modules.M1.open).not.toHaveBeenCalled(); expect(state.turns).toBe(0); - }); -}); diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts deleted file mode 100644 index 1062c6c2..00000000 --- a/tests/solverCooperativeCheckpoints.test.ts +++ /dev/null @@ -1,2110 +0,0 @@ -import fs from 'node:fs'; -import { spawnSync } from 'node:child_process'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { compileContextSections, leadResearchInputs } from '../src/solver/contextCompiler'; -import { observeGoalProgress } from '../src/solver/goalProgress'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { solverSourceDigest, type ProofCheck } from '../src/solver/modules/evidence'; -import { captureObligationSnapshot } from '../src/solver/obligationProgress'; -import { committedSource, commitSolverSources, git } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { DEFAULT_TACTIC_BATTERY_FAILURE_CACHE_ROOT } from '../src/solver/tacticBatteryFailureCache'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -// A Lead revision turn has one fixed decision slice; any slice that ends mid-request waits for it. -const LEAD_REVISION_MS = 10 * 60_000; - -describe('cooperative advisory scheduling checkpoints', () => { - let directory: string; - let controllers: AbortController[], running: Promise[]; - - beforeEach(() => { - vi.useFakeTimers(); - controllers = []; running = []; - // Exercise the ordinary explicit pulse/delivery path without advancing the unrelated poller 600 times. - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - }); - afterEach(async () => { - controllers.forEach(controller => controller.abort()); await Promise.allSettled(running); - vi.useRealTimers(); vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - }); - - function fixture(initial = false, projectRelative?: string, continuation?: 'lead' | 'lead-capacity' | 'custom-full' | 'peer', review = false) { - let cooperation: CooperativeResearch | undefined; - const activate = CooperativeResearch.prototype.activate; - vi.spyOn(CooperativeResearch.prototype, 'activate').mockImplementation(function (this: CooperativeResearch, ...args) { - cooperation = this; - return activate.apply(this, args); - }); - const example = localExample('solver-advisory-checkpoint-', 'lead'); - directory = example.directory; - if (projectRelative) { - git(example.workspace, ['mv', '--', example.problem.projectRelative, projectRelative]); - git(example.workspace, ['-c', 'user.name=Offline fixture', '-c', 'user.email=fixture@localhost', - 'commit', '--no-gpg-sign', '--quiet', '-m', 'Relocate disposable scheduling fixture']); - example.problem = { ...example.problem, projectRelative, baseCommit: git(example.workspace, ['rev-parse', 'HEAD']) }; - } - const { workspace, problem } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, initial ? 'engineer' : 'researcher', - { role: initial ? 'engineer' : continuation === 'lead-capacity' ? 'prover' : 'researcher' })]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index + 1}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, ...target, status: 'paused' })), - { id: 'investigate', kind: 'research', ownerId: 'researcher', objective: 'Resolve the precise missing construction.', - ...(review ? { reviewScope: 'feasibility' } : {}) }, - ] }); - const state = solverState(problem, workspace, { runId: 'advisory-checkpoint-fixture', phase: 'prepared', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - ...initial ? {} : { cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } } }); - if (continuation && continuation !== 'peer') { - state.cooperation!.error = 'offline_lead_replanning_required'; - state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.task.status = 'paused'; - if (continuation === 'lead-capacity') { - state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.task.status = 'active'; - for (const node of state.cooperation!.tasks.filter(node => node.task.kind === 'goal')) { - node.task.status = 'active'; node.task.dependsOn = ['investigate']; - } - } - } - const check = vi.fn(async () => { throw new Error('fixture_unexpected_proof_acceptance'); }); - const events: { event: string; details?: Record }[] = []; - const controller = new AbortController(); - controllers.push(controller); - const contextSettings = { instructionsSuffix: '', compactedDispatch: false }; - const modules = (open: (options: MathAgentOptions) => Promise): SolverModules => ({ - ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M2: { ...directSolverModules.M2, check, checkTask: check }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => { - const assignment = access.assignment!; - const current = { assignment, receipt: leadPlanDeliveryFile(assignment), - feedback: assignment.kind === 'task' ? _state.cooperation?.tasks.find(node => node.task.id === assignment.task.id)?.feedback : undefined, - inbox: _state.cooperation?.deliveries?.map(delivery => delivery.summary) ?? [] }; - return { - instructions: 'Offline scheduling fixture.' + contextSettings.instructionsSuffix + - (continuation && assignment.kind === 'lead' ? assignment.planNonce : ''), - message: continuation ? JSON.stringify({ ...current, mode: 'full', - exactTasks: state.cooperation!.tasks.map(node => node.task), sentinel: 'full-context-exact-types-'.repeat(300) }) - : JSON.stringify(assignment), - ...(continuation && continuation !== 'custom-full' ? { continuationMessage: JSON.stringify({ ...current, mode: 'short' }) } : {}), - ...(contextSettings.compactedDispatch ? { compileCompactedDispatch: () => compileContextSections({ - instructions: 'Offline scheduling fixture.', inlineManifest: false, mandatory: [{ id: 'compacted', kind: 'continuation', - text: JSON.stringify({ ...current, mode: 'compacted', exactTasks: state.cooperation!.tasks.map(node => node.task) }) }], - }) } : {}), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }; - } }, - }); - const run = (open: (options: MathAgentOptions) => Promise, maxTurns = 2, - onEvent?: (event: string, details?: Record) => void, - softSlice?: Parameters[0]['softSlice']) => { - const completion = runResearchWorkers({ - state, workers, modules: modules(open), access: workerAccess(workers, directory), - root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original targets.', - executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, - deadline: Infinity, maxTurnMs: Infinity, maxTurns, maxTotalTokens: 0, - // Checkpoint timing is under test; a goal-progress Lead review would need a Lead model turn. - goalProgressReviewMs: 24 * 3_600_000, - softSlice, - save: () => {}, emit: (event, details) => { events.push({ event, details }); onEvent?.(event, details); }, - }); - running.push(completion); return completion; - }; - return { state, workers, problem, check, events, controller, run, contextSettings, - pulse: (workerId: string) => cooperation!.pulse(workerId), - wake: () => cooperation!.modelBudgetChanged(), - requireReview: (candidate: ProofCheck) => cooperation!.requireReview(candidate) }; - } - - function heldAdvisoryTurns(count: number, taskIds = ['investigate'], lastInputTokens?: number) { - const started = Array.from({ length: count }, () => deferred()); - const done = Array.from({ length: count }, () => deferred()); - const actions: Extract[] = []; - let index = 0, active: ReturnType> | undefined; - const interrupt = vi.fn(async () => { active?.resolve('interrupted'); }); - const notify = vi.fn(async (_message: string) => {}); - const open = vi.fn(async (options: MathAgentOptions): Promise => ({ - threadId: options.threadId ?? 'persistent-backoff-thread', interrupt, notify, lastInputTokens, - close: async () => { active?.resolve('interrupted'); }, - run: async (message, _messageId, _workspace, onStarted) => { - const turn = index++; - if (turn >= count) throw new Error('fixture_unexpected_extra_turn'); - const action = JSON.parse(message) as CooperativeAction; - if (action.kind !== 'task' || !taskIds.includes(action.task.id)) throw new Error('fixture_unexpected_responsibility:' + action.kind); - actions.push(action); active = done[turn]; - onStarted(`backoff-turn-${turn}`); started[turn].resolve(); - // The advisory clock starts at the model's first produced item, not at turn admission. - options.onActivity?.({ event: 'reasoning' }); - return done[turn].promise; - }, - })); - const wait = (turn: number, completion: Promise) => Promise.race([started[turn].promise, - completion.then(() => { throw new Error('fixture_finished_before_expected_turn:' + turn); })]); - return { started, done, actions, interrupt, notify, open, wait }; - } - - async function reachBackoffCap(held: ReturnType, completion: Promise) { - await held.wait(0, completion); - for (const [turn, interval] of [120_000, 240_000, 480_000].entries()) { - await vi.advanceTimersByTimeAsync(interval); - await held.wait(turn + 1, completion); - } - } - - it('settles and preserves a running advisory draft for the fixed candidate review', async () => { - const { state, workers, problem, events, run, requireReview } = fixture(); - const held = heldAdvisoryTurns(1), handoff = deferred(); - const reviewStarted = deferred(), reviewDone = deferred(); - let activity: MathAgentOptions['onActivity']; - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const advisory = await held.open(options); - let reviewing = false; - return { - ...advisory, - run: async (message, messageId, workspace, onStarted) => { - const assignment = JSON.parse(message) as CooperativeAction; - if (assignment.kind === 'task') { - activity = options.onActivity; - return advisory.run(message, messageId, workspace, onStarted); - } - if (assignment.kind !== 'review') throw new Error('fixture_unexpected_assignment:' + assignment.kind); - reviewing = true; - onStarted?.('review-turn'); reviewStarted.resolve(); - return reviewDone.promise; - }, - close: async () => { await advisory.close(); if (reviewing) reviewDone.resolve('interrupted'); }, - }; - }); - const completion = run(open, 2, (event, details) => { - if (event === 'turn_checkpoint' && details?.workerId === 'researcher') handoff.resolve(); - }); - void completion.catch(() => {}); - await held.wait(0, completion); - const canonical = state.cooperation!.canonicalCommit!; - requireReview({ passed: true, commit: canonical, sourceDigest: solverSourceDigest(problem, workers[0].worktree), - verification: { schema: 'deepscientist.mathematics.verification-batch/v1', sessionId: 'fixture-review', - targetCommit: canonical, status: 'kernel_verified', results: [], events: [], startedAt: 0, checkedAt: 0, durationMs: 0 } }); - await vi.advanceTimersByTimeAsync(5); - expect(held.notify).toHaveBeenCalledOnce(); - expect(held.interrupt).not.toHaveBeenCalled(); - const notes = 'A saved alternative construction and its remaining gap.'; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); - await vi.advanceTimersByTimeAsync(30_000); - expect(held.interrupt).not.toHaveBeenCalled(); - activity?.({ event: 'item_completed', itemType: 'commandExecution' }); - await vi.advanceTimersByTimeAsync(1); - await Promise.race([handoff.promise, completion.then(() => { throw new Error('fixture_finished_before_advisory_handoff'); })]); - await Promise.race([reviewStarted.promise, completion.then(() => { throw new Error('fixture_finished_before_review'); })]); - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.status).toBe('pending'); - const draft = state.cooperation!.researchDrafts?.investigate; - expect(draft).toBeDefined(); - expect(committedSource(workers[1].worktree, draft!.commit, 'RESEARCH.md')).toBe(notes); - expect(events).toContainEqual({ event: 'turn_checkpoint', details: { - workerId: 'researcher', turn: 1, reason: 'math_final_review_handoff_checkpoint', - } }); - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak ?? 0).toBe(0); - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), JSON.stringify({ commit: canonical, verdict: 'changes_requested' })); - reviewDone.resolve('completed'); - await completion; - expect(state.cooperation!.review?.status).toBe('changes_requested'); - }); - - it.each([true, false])('routes ordinary peer updates through native advisory only when the session supports it (%s)', async nativeAdvisory => { - const { workers, controller, run } = fixture(); - const held = heldAdvisoryTurns(1), notify = vi.fn(async (_message: string, _options?: { waitForRequest?: boolean; mode?: 'advisory' }) => {}); - const open = async (options: MathAgentOptions): Promise => ({ ...await held.open(options), notify, - ...(nativeAdvisory ? { advisoryNotifications: 'native-history' as const } : {}) }); - const completion = run(open, 1); void completion.catch(() => {}); await held.wait(0, completion); - const active = vi.mocked(CooperativeResearch.prototype.activate).mock.calls.find(([worker]) => worker.id === workers[1].id)!; - await active[3]('A peer published a finding.', { mode: 'advisory' }); - expect(notify).toHaveBeenLastCalledWith('A peer published a finding.', nativeAdvisory ? { mode: 'advisory' } : { waitForRequest: true }); - await active[3]('A queued human instruction.', { requireTurn: true }); - expect(notify).toHaveBeenLastCalledWith('A queued human instruction.', { waitForRequest: false }); - expect(held.interrupt).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - it.each([false, true])('publishes the research reminder through research-observe (needs decision: %s)', async needsDecision => { - const { state, workers, check, controller, run, pulse } = fixture(); - const held = heldAdvisoryTurns(1), completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(90_000); - const message = held.notify.mock.calls[0]![0] as string; - expect(message).toContain('publish it with research-observe'); - const finding = { - summary: needsDecision - ? 'The saved search resolves the available identities but leaves the uniform norm estimate open; Lead must choose a different estimate.' - : 'The saved algebraic reduction supplies the exact identity needed by the consumer.', - conclusion: needsDecision ? 'inconclusive' : 'supporting', - remainingObligations: needsDecision ? ['Construct the uniform norm estimate.'] : [], - ...(needsDecision ? { needsDecision: true } : {}), - }; - const worktree = workers[1].worktree; - const file = path.join(worktree, '.scratch', 'finding.json'); - fs.mkdirSync(path.dirname(file), { recursive: true }); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), finding.summary + '\n'); - fs.writeFileSync(file, JSON.stringify(finding)); - const published = spawnSync('bun', ['bin/math.ts', 'research-observe', '--worktree', worktree, '--finding', file], - { encoding: 'utf8', timeout: 15_000 }); - expect(published.status, published.stdout || published.stderr).toBe(0); - const wakes = state.cooperation!.leadWakes!.requested; - await pulse(workers[1].id); - const delivery = state.cooperation!.deliveries!.find(item => item.taskId === held.actions[0].task.id && item.kind === 'research'); - expect(delivery).toMatchObject({ taskDigest: held.actions[0].assignment.taskDigest, - summary: finding.summary, status: needsDecision ? 'conditional' : 'advisory' }); - expect(JSON.parse(delivery!.finding!)).toMatchObject(finding); - expect(state.cooperation!.leadWakes!.requested).toBe(wakes + (needsDecision ? 1 : 0)); - if (needsDecision) expect(state.cooperation!.leadWakes!.recent!.at(-1)!.reason).toBe('research-finding'); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - expect(held.interrupt).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - function heldContinuationTurns(options: { saveNotes?: boolean; highContext?: boolean; deferFirstActivity?: boolean; count?: number; - nativeCompact?: 'success' | 'failure' } = {}) { - const count = options.count ?? 2; - const started = Array.from({ length: count }, () => deferred()), done = Array.from({ length: count }, () => deferred()); - const messages: { assignment: CooperativeAction; receipt?: string; mode: string; exactTasks?: unknown[]; sentinel?: string; - feedback?: string; inbox?: string[] }[] = []; - const threads: string[] = []; - let turns = 0, newThreads = 0, active: ReturnType> | undefined; - const interrupt = vi.fn(async () => { active?.resolve('interrupted'); }); - const close = vi.fn(async () => { active?.resolve('interrupted'); }); - const notify = vi.fn(async (_message: string) => {}); - const compact = vi.fn(); - const open = vi.fn(async (access: MathAgentOptions): Promise => { - const threadId = access.threadId ?? `continuation-thread-${++newThreads}`; - let inputTokens = options.highContext ? 100_000 : 0, running = false; - return { threadId, close, interrupt, notify, - get lastInputTokens() { return inputTokens; }, - ...(options.nativeCompact ? { compact: async () => { - compact(); expect(running).toBe(false); - if (options.nativeCompact === 'failure') throw new Error('fixture_compaction_failed'); - inputTokens = 12; - access.onUsage({ inputTokens: 12, outputTokens: 2, totalTokens: 14 }, { turnId: 'native-compact-turn' }); - } } : {}), - run: async (message, _messageId, _workspace, onStarted) => { - running = true; - const turn = turns++; - if (turn >= count) throw new Error('fixture_unexpected_extra_continuation_turn'); - messages.push(JSON.parse(message)); threads.push(threadId); active = done[turn]; - onStarted(`continuation-turn-${turn}`); - if (turn === 0 && options.saveNotes) - fs.writeFileSync(path.join(access.workspace, 'RESEARCH.md'), 'The current mathematical argument and exact unresolved inference are saved.\n'); - started[turn].resolve(); - // The advisory clock starts at the model's first produced item, not at turn admission. - if (!options.deferFirstActivity) access.onActivity?.({ event: 'reasoning' }); - try { return await done[turn].promise; } finally { running = false; } - } }; - }); - const wait = (turn: number, completion: Promise) => Promise.race([started[turn].promise, - completion.then(() => { throw new Error('fixture_finished_before_continuation:' + turn); })]); - return { open, close, interrupt, notify, compact, messages, threads, wait }; - } - - it('publishes a saved partial finding only after its scheduling checkpoint has stopped the writer', async () => { - const { state, workers, problem, check, run } = fixture(); - const held = heldAdvisoryTurns(1), stopping = deferred(), stopped = deferred(); - held.interrupt.mockImplementation(async () => { - stopping.resolve(); await stopped.promise; held.done[0].resolve('interrupted'); - }); - const completion = run(held.open, 1); void completion.catch(() => {}); - try { - await held.wait(0, completion); - const notes = 'The complete local derivation remains here.\n\n```math-result\n' + JSON.stringify({ - summary: 'The boundary case is established; uniform control remains unknown.', conclusion: 'inconclusive', - remainingObligations: ['Prove the uniform estimate using the exact original quantifiers.'], - }) + '\n```\n'; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); - await vi.advanceTimersByTimeAsync(90_000); - expect(held.notify.mock.calls[0][0]).toContain('publish it with research-observe'); - await vi.advanceTimersByTimeAsync(30_000); await stopping.promise; - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.researchDrafts?.investigate).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.status).toBe('running'); - stopped.resolve(); await completion; - const [delivery] = state.cooperation!.deliveries!.filter(record => record.kind === 'research'); - expect(delivery).toMatchObject({ taskId: 'investigate', researchRecord: { complete: false } }); - expect(leadResearchInputs([delivery], new Map(state.cooperation!.tasks.map(node => [node.task.id, node])))).toEqual([delivery]); - expect(committedSource(workers[0].worktree, delivery.commit!, 'RESEARCH.md')).toBe(notes); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.status).toBe('pending'); - expect(state.problem.receiptDigest).toBe(problem.receiptDigest); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - } finally { stopped.resolve(); } - }); - - it.each([{ event: 'reasoning' as const }, { event: 'item_started' as const, itemType: 'commandExecution' }])( - 'starts the work slice only at real model or tool activity (%j)', async firstActivity => { - const { state, events, controller, run } = fixture(false, undefined, 'lead'); - const held = heldContinuationTurns({ deferFirstActivity: true }), completion = run(held.open, Infinity); - void completion.catch(() => {}); await held.wait(0, completion); - delete state.cooperation!.error; - const activity = held.open.mock.calls[0][0].onActivity!; - activity({ event: 'item_started', itemType: 'userMessage' }); - activity({ event: 'item_completed', itemType: 'userMessage' }); - await vi.advanceTimersByTimeAsync(5 * 60_000); - expect(events.filter(item => item.event === 'cooperative_checkpoint_clock_started')).toEqual([]); - expect(held.notify).not.toHaveBeenCalled(); - expect(held.interrupt).not.toHaveBeenCalled(); - - activity(firstActivity); - expect(events.filter(item => item.event === 'cooperative_checkpoint_clock_started')).toHaveLength(1); - await vi.advanceTimersByTimeAsync(4 * 60_000 - 1); - expect(held.notify).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(held.notify).toHaveBeenCalledOnce(); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS - 4 * 60_000 - 1); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - if (firstActivity.itemType === 'commandExecution') { - expect(held.interrupt).not.toHaveBeenCalled(); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - } - await held.wait(1, completion); - expect(held.interrupt).toHaveBeenCalledOnce(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('keeps the independent silent-turn fallback despite input messages', async () => { - const { events, controller, run } = fixture(false, undefined, 'lead'); - const held = heldContinuationTurns({ deferFirstActivity: true }), completion = run(held.open, Infinity); - void completion.catch(() => {}); await held.wait(0, completion); - const activity = held.open.mock.calls[0][0].onActivity!; - activity({ event: 'item_started', itemType: 'userMessage' }); - await vi.advanceTimersByTimeAsync(14 * 60_000); - activity({ event: 'item_completed', itemType: 'userMessage' }); - await vi.advanceTimersByTimeAsync(60_000 - 1); - expect(events.filter(item => item.event === 'cooperative_checkpoint_clock_started')).toEqual([]); - expect(held.notify).not.toHaveBeenCalled(); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_clock_started', - details: expect.objectContaining({ itemType: 'none', silentMs: 15 * 60_000 }) }); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS - 1); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); await held.wait(1, completion); - expect(held.interrupt).toHaveBeenCalledOnce(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('pauses the Lead scheduling clock during compaction and resumes its remaining work slice', async () => { - const { events, controller, run, contextSettings } = fixture(false, undefined, 'lead'); - contextSettings.compactedDispatch = true; - const held = heldContinuationTurns({ saveNotes: true }), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(30_000); - const activity = held.open.mock.calls[0][0].onActivity!; - activity({ event: 'item_started', itemType: 'contextCompaction' }); - await vi.advanceTimersByTimeAsync(5 * 60_000); - expect(held.interrupt).not.toHaveBeenCalled(); - expect(held.open).toHaveBeenCalledOnce(); - activity({ event: 'item_completed', itemType: 'contextCompaction' }); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS - 30_001); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); await held.wait(1, completion); - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-1']); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'compacted']); - expect(events.some(item => item.event === 'context_compaction_completed')).toBe(true); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('gives each Lead revision one fixed decision slice with an early decide-now reminder', async () => { - const { events, controller, run } = fixture(false, undefined, 'lead'); - const held = heldContinuationTurns(), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(4 * 60_000 - 1); - expect(held.notify).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(held.notify).toHaveBeenCalledOnce(); - expect(held.notify.mock.calls[0]![0]).toMatch(/^Decide now, before further searches/u); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS - 4 * 60_000 - 1); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); await held.wait(1, completion); - expect(held.interrupt).toHaveBeenCalledOnce(); - // An unchanged cut does not stretch the next decision slice. - const slices = events.filter(item => item.event === 'cooperative_checkpoint_scheduled').map(item => item.details); - expect(slices).toEqual([expect.objectContaining({ checkpointAfterMs: LEAD_REVISION_MS, noticeAfterMs: 4 * 60_000 }), - expect.objectContaining({ checkpointAfterMs: LEAD_REVISION_MS, noticeAfterMs: 4 * 60_000, noProgressStreak: 1, backoffCapped: false })]); - expect(events.some(item => item.event === 'cooperative_checkpoint_deferred')).toBe(false); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['current', 'settled', 'replaced'] as const)( - 'rechecks the presented progress review when the queued Lead reminder is delivered (%s)', async status => { - const { state, events, controller, run } = fixture(false, undefined, 'lead'); - const tasks = state.cooperation!.tasks.map(node => ({ ...node, task: { ...node.task, status: 'active' as const } })); - const intervalMs = 24 * 3_600_000, now = Date.now(); - const input = { problemReceiptDigest: state.problem.receiptDigest, targets: state.problem.targets, tasks, - snapshot: captureObligationSnapshot(tasks), intervalMs, - activeTaskIds: new Set(tasks.filter(node => node.task.kind === 'goal').map(node => node.task.id)) }; - const observed = observeGoalProgress(undefined, { ...input, now: now - intervalMs }); - const progress = observeGoalProgress(observed.state, { ...input, now }).state; - const presented = structuredClone(progress.pending!); - expect(presented.goalIds.length).toBeGreaterThan(0); - state.cooperation!.goalProgress = progress; - const held = heldContinuationTurns(), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - delete state.cooperation!.error; - // emit runs after the timer fires and before the queued notify microtask. A peer may settle - // this review in that gap, so the reminder must not keep the timer's earlier obligation snapshot. - vi.spyOn(events, 'push').mockImplementation((...items) => { - if (items.some(item => item.event === 'cooperative_checkpoint_requested')) { - if (status === 'settled') delete state.cooperation!.goalProgress!.pending; - if (status === 'replaced') state.cooperation!.goalProgress!.pending = { ...presented, id: 'replacement-review' }; - } - return Array.prototype.push.apply(events, items); - }); - await vi.advanceTimersByTimeAsync(4 * 60_000); - expect(held.notify).toHaveBeenCalledOnce(); - const reminder = held.notify.mock.calls[0]![0]; - if (status === 'current') { - expect(reminder).toContain('Include progressReview with id ' + JSON.stringify(presented.id)); - expect(reminder).toContain('nextChecks covering every reviewed goal: ' + JSON.stringify(presented.goalIds)); - expect(reminder).not.toContain('return without a revision'); - } else { - expect(reminder).toContain('return without a revision'); - expect(reminder).not.toContain(presented.id); - expect(reminder).not.toContain('replacement-review'); - } - expect(held.interrupt).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['request-returned', 'wait-limit'] as const)( - 'lets a Lead revision slice that ends mid-request wait for that request (%s)', async boundary => { - const { state, events, controller, run } = fixture(false, undefined, 'lead'); - const held = heldContinuationTurns(), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - // This case has no required decision; required handoffs have their own regression fixtures. - delete state.cooperation!.error; - const activity = held.open.mock.calls[0][0].onActivity!; - // The model is still streaming one long request when the slice ends. - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS - 30_000); - activity({ event: 'reasoning' }); - await vi.advanceTimersByTimeAsync(30_000); - expect(held.interrupt).not.toHaveBeenCalled(); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_awaiting_request', - details: expect.objectContaining({ workerId: 'solver', maxWaitMs: 10 * 60_000, outputAgeMs: 30_000 }) }); - if (boundary === 'request-returned') { - await vi.advanceTimersByTimeAsync(3 * 60_000); - // A tool the request called is part of it: the cut waits until its result is recorded. - activity({ event: 'item_started', itemType: 'commandExecution' }); - await vi.advanceTimersByTimeAsync(60_000); - expect(held.interrupt).not.toHaveBeenCalled(); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - } else { - await vi.advanceTimersByTimeAsync(10 * 60_000 - 1); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - } - await held.wait(1, completion); - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', details: expect.objectContaining({ - workerId: 'solver', boundary, waitedMs: boundary === 'request-returned' ? 4 * 60_000 : 10 * 60_000 }) }); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['ready', 'ready-with-structured-draft', 'compacting', 'claimed-elsewhere', 'target-lost-at-boundary', - 'dispatch-mismatch', 'completed-with-ready-proof', 'completed-with-reassigned-proof'] as const)( - 'preserves drafts and completed findings during a typed proof handoff (%s)', async outcome => { - const { state, workers, check, events, controller, run, wake } = fixture(false, undefined, undefined, true); - const held = heldAdvisoryTurns(2, ['investigate', 'goal_1']); - const open = async (options: MathAgentOptions): Promise => ({ - ...await held.open(options), usageSource: 'upstream-requests', advisoryNotifications: 'native-history', - }); - const goal = state.cooperation!.tasks.find(node => node.task.id === 'goal_1')!; - const reassignGoal = () => { - goal.task = { ...goal.task, ownerId: 'a-different-worker' }; - wake(); - }; - const completion = run(open, Infinity, event => { - if (outcome === 'dispatch-mismatch' && event === 'advisory_yielded_for_typed_work') { - // A peer becomes responsible for the goal after the final handoff check and before dispatch. - reassignGoal(); - } - // Once the finding is published, this fixture with no available proof owner would wake the Lead. - if (outcome === 'completed-with-reassigned-proof' && event === 'research_delivered') - controller.abort(new Error('fixture_complete')); - }); - void completion.catch(() => {}); - await held.wait(0, completion); - const options = held.open.mock.calls[0][0]; - const activity = options.onActivity!; - const boundary = () => options.requestGate!.checkpoint!(); - goal.task = { ...goal.task, status: 'active', ownerId: 'researcher' }; - wake(); - // A ready proof cannot displace this advisory turn before the default protection window. - await vi.advanceTimersByTimeAsync(175_000); - expect(held.notify).not.toHaveBeenCalled(); - expect(boundary()).toBe(false); - if (outcome === 'compacting') { - activity({ event: 'item_started', itemType: 'contextCompaction' }); - await vi.advanceTimersByTimeAsync(5_000); - expect(held.notify).not.toHaveBeenCalled(); - activity({ event: 'item_completed', itemType: 'contextCompaction' }); - } - await vi.advanceTimersByTimeAsync(5_000); - expect(held.notify).toHaveBeenCalledWith(expect.stringContaining('A typed proof task is now ready'), { mode: 'advisory' }); - expect(boundary()).toBe(false); - const completedReview = outcome === 'completed-with-ready-proof' || outcome === 'completed-with-reassigned-proof'; - const notes = completedReview || outcome === 'ready-with-structured-draft' - ? JSON.stringify({ summary: 'The interface is feasible by the displayed construction.', conclusion: 'supporting', - evidenceRefs: ['construction:fixture'] }) - : 'Inspected the exact pinned input. The independent review is unfinished.\n'; - activity({ event: 'item_started', itemType: 'commandExecution' }); - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); - expect(boundary()).toBe(false); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - expect(held.interrupt).not.toHaveBeenCalled(); - - if (completedReview) { - if (outcome === 'completed-with-reassigned-proof') { reassignGoal(); expect(boundary()).toBe(false); } - held.done[0].resolve('completed'); - await vi.waitFor(() => expect(events.some(({ event }) => - event === 'research_delivered' || event === 'feasibility_review_checkpoint_saved')).toBe(true)); - const audit = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - expect(audit).toMatchObject({ status: 'completed', finding: expect.stringContaining('displayed construction') }); - expect(audit.researchCompletion).toBeDefined(); - expect(events).toContainEqual({ event: 'research_delivered', - details: expect.objectContaining({ taskId: 'investigate', complete: true }) }); - expect(events.some(({ event }) => event === 'turn_checkpoint')).toBe(false); - if (outcome === 'completed-with-ready-proof') { - await held.wait(1, completion); - expect(held.actions[1].task.id).toBe('goal_1'); - } - } else if (outcome === 'claimed-elsewhere') { - // The existing handoff is stale by the time the model asks for another request. - reassignGoal(); - expect(boundary()).toBe(false); - expect(events.some(item => item.event === 'turn_checkpoint')).toBe(false); - // Even if the model already saw the notice and returns, its incomplete draft is preserved. - held.done[0].resolve('completed'); - await held.wait(1, completion); - expect(held.actions[1].task.id).toBe('investigate'); - expect(events).toContainEqual({ event: 'proof_handoff_target_changed', - details: expect.objectContaining({ workerId: 'researcher', successorTaskId: 'goal_1' }) }); - } else { - expect(boundary()).toBe(true); - if (outcome === 'target-lost-at-boundary') reassignGoal(); - held.done[0].resolve('checkpoint'); - await held.wait(1, completion); - const mismatch = outcome === 'dispatch-mismatch' || outcome === 'target-lost-at-boundary'; - expect(held.actions[1].task.id).toBe(mismatch ? 'investigate' : 'goal_1'); - expect(events).toContainEqual({ event: outcome === 'target-lost-at-boundary' ? - 'proof_handoff_target_changed' : 'advisory_yielded_for_typed_work', - details: expect.objectContaining({ workerId: 'researcher', successorTaskId: 'goal_1' }) }); - if (mismatch) { - expect(events).toContainEqual({ event: 'cooperative_preemption_mismatch', - details: expect.objectContaining({ workerId: 'researcher', taskId: 'investigate', - targetTaskId: 'goal_1', assignedKind: 'research', assignedTaskId: 'investigate', - cooldownUntil: Date.now() + 10 * 60_000 }) }); - } else expect(events.some(item => item.event === 'cooperative_preemption_mismatch')).toBe(false); - } - if (!completedReview) { - const audit = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - const draft = state.cooperation!.researchDrafts!.investigate; - expect(audit.researchCompletion).toBeUndefined(); - expect(draft.feasibilityInputDigest).toBe(held.actions[0].assignment.feasibilityInputDigest); - expect(committedSource(workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(notes); - } - expect(held.interrupt).not.toHaveBeenCalled(); expect(check).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('lets an advisory research slice that ends mid-request save its handoff before its checkpoint', async () => { - const { state, workers, events, controller, run } = fixture(); - const held = heldAdvisoryTurns(2), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - const activity = held.open.mock.calls[0][0].onActivity!; - // A two-minute research slice usually ends inside one request; cutting there saves nothing. - await vi.advanceTimersByTimeAsync(120_000 - 30_000); - activity({ event: 'reasoning' }); - await vi.advanceTimersByTimeAsync(30_000); - expect(held.interrupt).not.toHaveBeenCalled(); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_awaiting_request', details: expect.objectContaining({ - workerId: 'researcher', checkpointAfterMs: 120_000, maxWaitMs: 10 * 60_000, outputAgeMs: 30_000 }) }); - await vi.advanceTimersByTimeAsync(5 * 60_000); - activity({ event: 'item_started', itemType: 'commandExecution' }); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - await vi.advanceTimersByTimeAsync(0); - expect(held.interrupt).not.toHaveBeenCalled(); - expect(events).toContainEqual({ event: 'research_handoff_requested', details: expect.objectContaining({ - workerId: 'researcher', taskId: 'investigate', remainingMs: 5 * 60_000 }) }); - await vi.advanceTimersByTimeAsync(30_000); - activity({ event: 'item_started', itemType: 'commandExecution' }); - const notes = 'The search leaves a precisely identified missing estimate; the attempted reduction is saved here.\n'; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - await held.wait(1, completion); - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', details: expect.objectContaining({ - workerId: 'researcher', boundary: 'request-returned', waitedMs: 5 * 60_000 + 30_000 }) }); - expect(state.cooperation!.researchCheckpoints?.investigate).toMatchObject({ count: 1, paused: false }); - expect(committedSource(workers[1].worktree, state.cooperation!.researchDrafts!.investigate.commit, 'RESEARCH.md')).toBe(notes); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('lets a queued save notice reach the model and its saved handoff finish before interrupting', async () => { - const { state, workers, events, run } = fixture(); - const held = heldAdvisoryTurns(1), notice = deferred(); - held.notify.mockImplementation(() => notice.promise); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); - const activity = held.open.mock.calls[0][0].onActivity!; - await vi.advanceTimersByTimeAsync(120_000); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_awaiting_request', details: expect.objectContaining({ - workerId: 'researcher', noticePending: true, maxWaitMs: 10 * 60_000 }) }); - await vi.advanceTimersByTimeAsync(3 * 60_000); - activity({ event: 'item_started', itemType: 'commandExecution' }); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - // This is the first request boundary where the queued turn/steer can arrive. Cutting - // here used to cancel the notice before the model could write its argument down. - expect(held.interrupt).not.toHaveBeenCalled(); - notice.resolve(); await vi.advanceTimersByTimeAsync(0); - activity({ event: 'reasoning' }); - await vi.advanceTimersByTimeAsync(29_999); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(60_000); - activity({ event: 'item_started', itemType: 'commandExecution' }); - const notes = 'The saved mathematical reduction and its exact remaining inference.\n'; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - await expect(completion).resolves.toBeUndefined(); - expect(held.notify).toHaveBeenCalledOnce(); expect(held.interrupt).toHaveBeenCalledOnce(); - expect(committedSource(workers[1].worktree, state.cooperation!.researchDrafts!.investigate.commit, 'RESEARCH.md')).toBe(notes); - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak).toBe(0); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.proof).toBeUndefined(); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['deadline', 'late-delivery', 'cancel'] as const)('bounds a pending save notice and cleans up after %s', async outcome => { - const { events, controller, run } = fixture(); - const held = heldAdvisoryTurns(1), notice = deferred(); - held.notify.mockImplementation(() => notice.promise); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); await vi.advanceTimersByTimeAsync(120_000); - if (outcome !== 'cancel') { - await vi.advanceTimersByTimeAsync(10 * 60_000 - 1); - expect(held.interrupt).not.toHaveBeenCalled(); - if (outcome === 'late-delivery') { notice.resolve(); await vi.advanceTimersByTimeAsync(0); } - await vi.advanceTimersByTimeAsync(1); - await expect(completion).resolves.toBeUndefined(); - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', details: expect.objectContaining({ - boundary: 'wait-limit', waitedMs: 10 * 60_000 }) }); - } else { - controller.abort(new Error('fixture_notice_cancelled')); - await expect(completion).rejects.toThrow('fixture_notice_cancelled'); - expect(held.interrupt).not.toHaveBeenCalled(); - } - const count = events.length; - notice.resolve(); await vi.advanceTimersByTimeAsync(30 * 60_000); - expect(events).toHaveLength(count); expect(held.notify).toHaveBeenCalledOnce(); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each([false, true])('keeps a failed save notice from extending the advisory turn (queued=%s)', async queued => { - const { events, run } = fixture(); - const held = heldAdvisoryTurns(1), notice = deferred(); - held.notify.mockImplementation(() => notice.promise); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(queued ? 120_000 : 90_000); - notice.reject(new Error('fixture_notice_rejected')); await vi.advanceTimersByTimeAsync(0); - if (!queued) { - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(30_000); - } - await expect(completion).resolves.toBeUndefined(); - expect(held.notify).toHaveBeenCalledOnce(); expect(held.interrupt).toHaveBeenCalledOnce(); - expect(events.filter(item => item.event === 'cooperative_checkpoint_notice_failed')).toHaveLength(1); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['checkpoint', 'ready', 'stop'] as const)('does not report a settled save-notice cancellation during %s as a failure', async stopping => { - const { events, run } = fixture(); - const held = heldAdvisoryTurns(1), notice = deferred(); - held.notify.mockImplementation(() => notice.promise); - held.interrupt.mockImplementation(async () => { - notice.reject(new Error('math_codex_notification_turn_settled')); - held.done[0].resolve('interrupted'); - }); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); await vi.advanceTimersByTimeAsync(120_000); - if (stopping === 'checkpoint') await vi.advanceTimersByTimeAsync(10 * 60_000); - else { - const activation = vi.mocked(CooperativeResearch.prototype.activate).mock.calls.find(([worker]) => worker.id === 'researcher')!; - await activation[stopping === 'ready' ? 4 : 2]!(); - } - await expect(completion).resolves.toBeUndefined(); - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(events.filter(item => item.event === 'cooperative_checkpoint_notice_failed')).toEqual([]); - if (stopping === 'checkpoint') expect(events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ boundary: 'wait-limit', waitedMs: 10 * 60_000 }) }); - expect(vi.getTimerCount()).toBe(0); - }); - - it('keeps a genuine queued-notice error during checkpoint interruption with a bounded diagnostic', async () => { - const { events, run } = fixture(); - const held = heldAdvisoryTurns(1), notice = deferred(); - const reason = 'math_codex_rpc_timeout:turn/steer:' + 'diagnostic '.repeat(200); - held.notify.mockImplementation(() => notice.promise); - held.interrupt.mockImplementation(async () => { - notice.reject(new Error(reason)); - held.done[0].resolve('interrupted'); - }); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); await vi.advanceTimersByTimeAsync(120_000 + 10 * 60_000); - await expect(completion).resolves.toBeUndefined(); - const failures = events.filter(item => item.event === 'cooperative_checkpoint_notice_failed'); - expect(failures).toHaveLength(1); - expect(failures[0].details).toMatchObject({ reason: reason.slice(0, 1000) }); - expect(held.interrupt).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0); - }); - - it('reports an unexpected settled-notice error before the turn starts stopping', async () => { - const { events, run } = fixture(); - const held = heldAdvisoryTurns(1), notice = deferred(); - held.notify.mockImplementation(() => notice.promise); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); await vi.advanceTimersByTimeAsync(120_000); - notice.reject(new Error('math_codex_notification_turn_settled')); - await vi.advanceTimersByTimeAsync(0); - await expect(completion).resolves.toBeUndefined(); - expect(events.filter(item => item.event === 'cooperative_checkpoint_notice_failed')).toEqual([ - { event: 'cooperative_checkpoint_notice_failed', details: expect.objectContaining({ reason: 'math_codex_notification_turn_settled' }) }, - ]); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', - details: expect.objectContaining({ boundary: 'notice-failed' }) }); - expect(held.interrupt).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0); - }); - - it.each([ - { failure: false, reason: 'math_codex_notification_turn_settled' }, - { failure: true, reason: 'math_codex_rpc_timeout:turn/steer:' + 'diagnostic '.repeat(200) }, - ])('distinguishes context-notice cancellation from genuine errors when the host stops (failure=$failure)', async ({ failure, reason }) => { - const { events, run } = fixture(); - const held = heldAdvisoryTurns(1, ['investigate'], 90_000), notice = deferred(); - held.notify.mockImplementation(() => notice.promise); - held.interrupt.mockImplementation(async () => { - notice.reject(new Error(reason)); - held.done[0].resolve('interrupted'); - }); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); - expect(held.notify).toHaveBeenCalledOnce(); - expect(events.some(item => item.event === 'context_checkpoint_requested')).toBe(true); - const activation = vi.mocked(CooperativeResearch.prototype.activate).mock.calls.find(([worker]) => worker.id === 'researcher')!; - await activation[2](); - await expect(completion).resolves.toBeUndefined(); - const failures = events.filter(item => item.event === 'context_checkpoint_notice_failed'); - expect(failures).toEqual(!failure ? [] : [ - { event: 'context_checkpoint_notice_failed', details: expect.objectContaining({ reason: reason.slice(0, 1000) }) }, - ]); - expect(held.interrupt).toHaveBeenCalledOnce(); expect(vi.getTimerCount()).toBe(0); - }); - - it('ignores a late context-notice rejection after its turn has finished', async () => { - const { events, run } = fixture(); - const held = heldAdvisoryTurns(1, ['investigate'], 90_000), notice = deferred(); - held.notify.mockImplementation(() => notice.promise); - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); expect(held.notify).toHaveBeenCalledOnce(); - held.done[0].resolve('interrupted'); - await expect(completion).resolves.toBeUndefined(); - const count = events.length; - notice.reject(new Error('math_codex_rpc_timeout:turn/steer')); - await vi.advanceTimersByTimeAsync(0); - expect(events).toHaveLength(count); expect(vi.getTimerCount()).toBe(0); - }); - - it('lets an initial-plan slice that ends mid-request wait for that request before the fallback plan', async () => { - const { state, events, controller, run } = fixture(true); - const leadStarted = deferred(), leadDone = deferred(), engineerStarted = deferred(); - const leadInterrupt = vi.fn(async () => { leadDone.resolve('interrupted'); }); - let leadActivity: MathAgentOptions['onActivity']; - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const lead = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID === 'solver'; - const done = lead ? leadDone : deferred(); - return { threadId: lead ? 'thread-solver' : 'thread-engineer', notify: vi.fn(async () => {}), - interrupt: lead ? leadInterrupt : vi.fn(async () => { done.resolve('interrupted'); }), - close: async () => { done.resolve('interrupted'); }, - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted(lead ? 'turn-solver' : 'turn-engineer'); - options.onActivity?.({ event: 'reasoning' }); - if (lead) { leadActivity = options.onActivity; leadStarted.resolve(); } else engineerStarted.resolve(); - return done.promise; - } }; - }); - const completion = run(open); void completion.catch(() => {}); - await leadStarted.promise; - // One long first-plan request is still streaming when the 20-minute slice ends. - await vi.advanceTimersByTimeAsync(20 * 60_000 - 30_000); - leadActivity!({ event: 'reasoning' }); - await vi.advanceTimersByTimeAsync(30_000); - expect(leadInterrupt).not.toHaveBeenCalled(); - expect(state.cooperation?.initialPlanFallback).toBeUndefined(); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_awaiting_request', details: expect.objectContaining({ - workerId: 'solver', checkpointAfterMs: 20 * 60_000, outputAgeMs: 30_000 }) }); - await vi.advanceTimersByTimeAsync(10 * 60_000); - await engineerStarted.promise; - expect(leadInterrupt).toHaveBeenCalledOnce(); - expect(events).toContainEqual({ event: 'cooperative_checkpoint_request_settled', details: expect.objectContaining({ - workerId: 'solver', boundary: 'wait-limit', waitedMs: 10 * 60_000 }) }); - expect(state.cooperation!.initialPlanFallback).toBeDefined(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('recovers a stalled compaction into a fresh thread while preserving the same assignment and draft', async () => { - const { state, workers, events, controller, run } = fixture(false, undefined, 'lead'); - const held = heldContinuationTurns({ saveNotes: true }), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - const saved = fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'utf8'); - held.open.mock.calls[0][0].onActivity!({ event: 'item_started', itemType: 'contextCompaction' }); - await vi.advanceTimersByTimeAsync(10 * 60_000 - 1); - expect(held.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); await held.wait(1, completion); - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-2']); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'full']); - expect(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'utf8')).toBe(saved); - expect(state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(events.some(item => item.event === 'context_compaction_recovery_requested')).toBe(true); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['lead', 'custom-full'] as const)( - 'keeps first Lead dispatch full and resumes %s with the current nonce and receipt', async mode => { - const { state, check, events, controller, run } = fixture(false, undefined, mode); - const held = heldContinuationTurns({ saveNotes: true }), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - expect(held.messages[0].assignment.kind).toBe('lead'); - expect(held.messages[0].mode).toBe('full'); - expect(held.messages[0].sentinel).toContain('full-context-exact-types'); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS); await held.wait(1, completion); - const [first, latest] = held.messages; - expect(latest.assignment.kind).toBe('lead'); - if (first.assignment.kind !== 'lead' || latest.assignment.kind !== 'lead') throw new Error('fixture_not_lead'); - expect(latest.assignment.planVersion).toBe(first.assignment.planVersion); - expect(latest.assignment.planNonce).not.toBe(first.assignment.planNonce); - expect(latest.receipt).toBe(leadPlanDeliveryFile(latest.assignment)); - expect(latest.receipt).not.toBe(first.receipt); - expect(JSON.stringify(latest)).not.toContain(first.assignment.planNonce); - expect(latest.mode).toBe(mode === 'lead' ? 'short' : 'full'); - expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-1']); - expect(held.open).toHaveBeenCalledTimes(2); - expect(held.open.mock.calls[1][0].threadId).toBe('continuation-thread-1'); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)) - .toEqual(['full', mode === 'lead' ? 'continuation' : 'full']); - expect(events.some(item => item.event === 'capacity_refill_assessed' || item.event === 'stagnation_recovery_assessed')).toBe(false); - expect(state.cooperation!.planPublication).toBeUndefined(); - expect(state.cooperation!.lastLeadInputDigest).toBeUndefined(); - expect(state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(held.open.mock.calls.every(([access]) => access.turnTimeoutMs === undefined)).toBe(true); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - controller.abort(new Error('fixture_complete')); - await expect(completion).rejects.toThrow('fixture_complete'); - expect(check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it('sends full context again after a saved Lead checkpoint rotates to a fresh thread', async () => { - const { state, workers, check, events, controller, run, pulse } = fixture(false, undefined, 'lead'); - const held = heldContinuationTurns({ saveNotes: true, highContext: true }); - const completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - held.open.mock.calls[0][0].onActivity!({ event: 'reasoning' }); - const request = state.workers![0].contextCheckpoint!; - // The Lead's checkpoint request supplies a complete command. - const instruction = held.notify.mock.calls.map(([message]) => message).find(message => message.includes(request.requestId!))!; - expect(instruction).toContain('a Lead publishes no findings'); - expect(instruction).toContain('checkpoint --worktree'); - expect(instruction).not.toContain('needsDecision'); - const log = held.messages[0].receipt!; - const acknowledged = spawnSync('bun', ['bin/math.ts', 'checkpoint', '--worktree', workers[0].worktree, - '--log', log, '--request-id', request.requestId!], { encoding: 'utf8', timeout: 15_000 }); - expect(acknowledged.status, acknowledged.stdout || acknowledged.stderr).toBe(0); - await pulse(workers[0].id); - await vi.advanceTimersByTimeAsync(5_000); await held.wait(1, completion); - expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-2']); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'full']); - expect(held.messages[1].sentinel).toContain('full-context-exact-types'); - expect(held.messages[1].exactTasks).toEqual(state.cooperation!.tasks.map(node => node.task)); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)).toEqual(['full', 'full']); - expect(events).toContainEqual({ event: 'context_restarted', details: expect.objectContaining({ workerId: 'solver', - previousThreadId: 'continuation-thread-1', reason: 'context' }) }); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - it.each(['success', 'failure', 'changed-plan'] as const)('restores exact task context after native compaction (%s)', async outcome => { - const { state, workers, check, events, controller, run, pulse, contextSettings } = fixture(false, undefined, 'lead'); - const nativeCompact = outcome === 'failure' ? 'failure' : 'success'; - contextSettings.compactedDispatch = true; - const held = heldContinuationTurns({ saveNotes: true, highContext: true, nativeCompact }); - const completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - held.open.mock.calls[0][0].onActivity!({ event: 'reasoning' }); - expect(held.compact).not.toHaveBeenCalled(); - const request = state.workers![0].contextCheckpoint!; - if (outcome === 'changed-plan') { - const next = CooperativeResearch.prototype.next; - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { - const action = await next.call(this, worker, budget); - if (action?.kind === 'lead') { - state.cooperation!.planVersion = 'compaction-revised-plan'; - state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.task.type = '∀ n : Nat, n = n'; - action.planVersion = state.cooperation!.planVersion; - } - return action; - }); - } - fs.appendFileSync(path.join(workers[0].worktree, held.messages[0].receipt!), JSON.stringify({ - kind: 'checkpoint', requestId: request.requestId, - notesDigest: mathDigest(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'))), - }) + '\n'); - await pulse(workers[0].id); await vi.advanceTimersByTimeAsync(5_000); await held.wait(1, completion); - expect(held.compact).toHaveBeenCalledOnce(); - expect(held.threads).toEqual(['continuation-thread-1', nativeCompact === 'success' ? 'continuation-thread-1' : 'continuation-thread-2']); - expect(held.messages[1].mode).toBe(outcome === 'success' ? 'compacted' : 'full'); - expect(held.messages[1].exactTasks).toEqual(state.cooperation!.tasks.map(node => node.task)); - const dispatches = events.filter(item => item.event === 'context_dispatched').map(item => item.details); - expect(dispatches.map(details => details?.mode)).toEqual(['full', outcome === 'success' ? 'compacted' : 'full']); - if (outcome === 'success') expect(dispatches[1]?.messageBytes).toBeLessThan(Number(dispatches[0]?.messageBytes) / 2); - expect(events.some(item => item.event === 'context_restarted')).toBe(nativeCompact === 'failure'); - expect(events.some(item => item.event === (nativeCompact === 'success' ? 'context_compaction_completed' : 'context_compaction_failed'))).toBe(true); - expect(state.workers![0].usageAccounting?.startedTurns).toBe(2); - if (nativeCompact === 'success') expect(state.workers![0].usage?.totalTokens).toBe(14); - expect(check).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - it('sends the complete revised mathematical graph when the Lead plan version changes in the same thread', async () => { - const { state, check, events, controller, run } = fixture(false, undefined, 'lead'); - const exactType = '∀ (n : Nat), ' + 'True ∧ '.repeat(250) + 'True'; - const next = CooperativeResearch.prototype.next; - let leadDispatches = 0; - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { - const action = await next.call(this, worker, budget); - if (action?.kind === 'lead' && ++leadDispatches === 2) { - // A scheduler graph replacement occurs between accepted dispatches, without rotating the model thread. - state.cooperation!.planVersion = 'revised-plan-version'; - state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.task.type = exactType; - action.planVersion = state.cooperation!.planVersion; - } - return action; - }); - const held = heldContinuationTurns({ saveNotes: true }), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS); await held.wait(1, completion); - const [first, revised] = held.messages; - expect(first.assignment.kind).toBe('lead'); expect(revised.assignment.kind).toBe('lead'); - if (first.assignment.kind !== 'lead' || revised.assignment.kind !== 'lead') throw new Error('fixture_not_lead'); - expect(revised.assignment.planVersion).not.toBe(first.assignment.planVersion); - expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-1']); - expect(revised.mode).toBe('full'); - expect(JSON.stringify(revised.exactTasks)).toContain(exactType); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)).toEqual(['full', 'full']); - expect(events.some(item => item.event === 'context_restarted')).toBe(false); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - it('resumes a same-thread advisory assignment with its current short message', async () => { - const { state, check, events, controller, run } = fixture(false, undefined, 'peer'); - const held = heldContinuationTurns(), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - expect(held.messages.every(message => message.assignment.kind === 'task')).toBe(true); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'short']); - expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-1']); - expect(held.open.mock.calls[0][0].hiddenRoots).toContain(DEFAULT_TACTIC_BATTERY_FAILURE_CACHE_ROOT); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)).toEqual(['full', 'continuation']); - expect(state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - it.each(['unchanged', 'compaction', 'environment', 'instructions', 'dependency', 'route', 'route-id', 'threshold'] as const)( - 'revisits A after B using its sent contract only while current (%s)', async change => { - const { state, events, controller, run, contextSettings } = fixture(false, undefined, 'peer'); - const first = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - const input = { task: { ...first.task, id: 'research-input', ownerId: 'solver', status: 'paused' as const }, - status: 'pending' as const, attempts: 0, finding: 'Original exact dependency finding.' }; - first.task.dependsOn = [input.task.id]; - const other = { task: { ...first.task, id: 'other-question', dependsOn: [] }, status: 'pending' as const, attempts: 0 }; - state.cooperation!.tasks.push(other, input); - if (change === 'route') { - other.task.groupId = 'another-route'; - state.cooperation!.groups!.push({ group: { id: other.task.groupId, objective: 'Try the alternative construction', - revision: 0, status: 'active' }, turns: 0 }); - } - if (change === 'threshold') { - const next = CooperativeResearch.prototype.next; - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { - const action = await next.call(this, worker, budget); - if (action?.kind === 'task' && action.task.id === other.task.id) state.workers![1].lastInputTokens = 94_000; - return action; - }); - } - if (change === 'route-id') { - const next = CooperativeResearch.prototype.next; - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { - const action = await next.call(this, worker, budget); - if (action?.kind === 'task' && action.task.id === other.task.id) - action.assignment.routeId = 'alternative-proof-route'; - return action; - }); - } - const held = heldContinuationTurns({ count: 3 }), completion = run(held.open, Infinity); - void completion.catch(() => {}); await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - if (change === 'compaction') { - // A completion can arrive even when this process did not observe the corresponding start. - held.open.mock.calls[0][0].onActivity!({ event: 'item_completed', itemType: 'contextCompaction' }); - } - if (change === 'environment') state.environmentDigest = mathDigest('new exact environment'); - if (change === 'instructions') contextSettings.instructionsSuffix = ' New exact instructions.'; - if (change === 'dependency') input.finding = 'New exact dependency finding under the same task contract.'; - first.feedback = 'Use the latest coercion lemma when returning to this question.'; - await vi.advanceTimersByTimeAsync(120_000); await held.wait(2, completion); - expect(held.messages.map(message => message.assignment.kind === 'task' && message.assignment.task.id)) - .toEqual(['investigate', 'other-question', 'investigate']); - const routeChanged = change === 'route' || change === 'route-id'; - const firstSwitchRotates = routeChanged || change === 'threshold'; - const secondSwitchRotates = routeChanged || change === 'environment' || change === 'instructions'; - expect(held.threads).toEqual(['continuation-thread-1', `continuation-thread-${firstSwitchRotates ? 2 : 1}`, - `continuation-thread-${1 + Number(firstSwitchRotates) + Number(secondSwitchRotates)}`]); - const secondMode = change === 'unchanged' ? 'continuation' : change === 'threshold' ? 'task-switch' : 'full'; - expect(held.messages.map(message => message.mode)) - .toEqual(['full', firstSwitchRotates ? 'full' : 'short', secondMode === 'full' ? 'full' : 'short']); - expect(held.messages[2].feedback).toContain('latest coercion lemma'); - expect(events.filter(event => event.event === 'context_dispatched').map(event => event.details?.mode)) - .toEqual(['full', firstSwitchRotates ? 'full' : 'task-switch', secondMode]); - const dispatches = events.filter(event => event.event === 'context_dispatched'); - if (!firstSwitchRotates) expect(dispatches[1].details?.messageBytes).toBeLessThan(Number(dispatches[0].details?.messageBytes) / 2); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('sends new feedback and inbox findings in a same-thread short advisory continuation', async () => { - const { state, check, events, controller, run } = fixture(false, undefined, 'peer'); - const next = CooperativeResearch.prototype.next; - let peerDispatches = 0; - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { - const action = await next.call(this, worker, budget); - if (action?.kind === 'task' && action.task.id === 'investigate' && ++peerDispatches === 2) { - const node = state.cooperation!.tasks.find(node => node.task.id === action.task.id)!; - node.feedback = 'Use the newly saved exact coercion lemma before another library search.'; - (state.cooperation!.deliveries ??= []).push({ id: 'fresh-peer-input', producer: 'solver', - taskId: node.task.id, taskDigest: action.assignment.taskDigest, kind: 'research', status: 'advisory', - summary: 'A saved finding identifies the exact missing library interface.', statement: '', premises: [], - dependencies: [], remainingObligations: [], evidenceRefs: [], createdAt: Date.now() }); - } - return action; - }); - const held = heldContinuationTurns(), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'short']); - expect(held.messages[1].feedback).toContain('newly saved exact coercion lemma'); - expect(held.messages[1].inbox).toContain('A saved finding identifies the exact missing library interface.'); - expect(held.threads).toEqual(['continuation-thread-1', 'continuation-thread-1']); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)).toEqual(['full', 'continuation']); - expect(check).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - it.each(['task', 'environment', 'seed', 'instructions'] as const)( - 'sends full advisory context when its %s responsibility changes', async change => { - const { state, workers, check, events, controller, run, contextSettings } = fixture(false, undefined, 'peer'); - const next = CooperativeResearch.prototype.next; - let peerDispatches = 0; - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { - const action = await next.call(this, worker, budget); - if (action?.kind === 'task' && action.task.id === 'investigate' && ++peerDispatches === 2) { - const node = state.cooperation!.tasks.find(node => node.task.id === action.task.id)!; - if (change === 'task') { - node.task = { ...node.task, objective: 'Resolve the distinct finite-dimensional construction.', revision: node.task.revision + 1 }; - action.task = node.task; action.assignment.taskDigest = taskVersion(node.task); - } - if (change === 'environment') state.environmentDigest = 'revised-offline-environment'; - if (change === 'seed') { - git(workers[1].worktree, ['-c', 'user.name=Offline fixture', '-c', 'user.email=fixture@localhost', - 'commit', '--allow-empty', '--no-gpg-sign', '--quiet', '-m', 'Revise disposable continuation seed']); - action.assignment.seedCommit = git(workers[1].worktree, ['rev-parse', 'HEAD']); - } - if (change === 'instructions') contextSettings.instructionsSuffix = ' Revised offline role instructions.'; - } - return action; - }); - const held = heldContinuationTurns(), completion = run(held.open, Infinity); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'full']); - expect(held.messages[1].sentinel).toContain('full-context-exact-types'); - expect(held.threads).toEqual(['continuation-thread-1', change === 'seed' ? 'continuation-thread-1' : 'continuation-thread-2']); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)).toEqual(['full', 'full']); - if (change === 'task') { - const revised = held.messages[1].assignment; - expect(revised.kind === 'task' && revised.task.objective).toContain('distinct finite-dimensional construction'); - } - if (change === 'seed') { - const first = held.messages[0].assignment, revised = held.messages[1].assignment; - expect(first.kind === 'task' && revised.kind === 'task' && revised.assignment.seedCommit).not.toBe( - first.kind === 'task' && first.assignment.seedCommit); - } - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - }); - - it.each(['acknowledged', 'stalled'] as const)( - 'checkpoints a %s advisory turn, resumes its exact draft and clears old timers before continuing', async interruptKind => { - const { state, workers, problem, check, events, run } = fixture(); - const firstStarted = deferred(), resumed = deferred(), interrupted = deferred(), finish = deferred(); - const teardown = deferred(); - const actions: Extract[] = []; - let turns = 0, active: ReturnType> | undefined, lastError: string | undefined; - const close = vi.fn(async () => { - lastError = 'math_codex_transport_closed'; active?.reject(new Error(lastError)); - if (interruptKind === 'stalled' && turns === 1) await teardown.promise; - }); - const interrupt = vi.fn(async () => { if (interruptKind === 'acknowledged') interrupted.resolve('interrupted'); }); - const notify = vi.fn(async () => {}); - const open = vi.fn(async (options: MathAgentOptions): Promise => ({ - threadId: options.threadId ?? 'saved-advisory-thread', close, interrupt, notify, - get lastError() { return lastError; }, - run: async (message, _messageId, _workspace, onStarted) => { - lastError = undefined; - const action = JSON.parse(message) as Extract; - actions.push(action); onStarted(`advisory-turn-${++turns}`); - options.onActivity?.({ event: 'reasoning' }); - const notes = path.join(options.workspace, 'RESEARCH.md'); - if (turns === 1) { - fs.writeFileSync(notes, 'A partial construction and its exact remaining quantitative gap.\n'); - active = interrupted; firstStarted.resolve(); - return interrupted.promise; - } - expect(fs.readFileSync(notes, 'utf8')).toContain('exact remaining quantitative gap'); - const draft = state.cooperation!.researchDrafts!.investigate; - expect(draft).toMatchObject({ workerId: 'researcher', assignmentId: actions[0].assignment.assignmentId }); - expect(committedSource(workers[1].worktree, draft.commit, 'RESEARCH.md')).toContain('partial construction'); - const node = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - expect(node.status).toBe('running'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - expect(state.check).toBeUndefined(); expect(check).not.toHaveBeenCalled(); - fs.writeFileSync(notes, 'A completed advisory construction with its precise assumptions and unresolved quantitative gap.\n'); - active = finish; resumed.resolve(); - return finish.promise; - }, - })); - const completion = run(open); void completion.catch(() => {}); - const stopped = completion.then(() => { throw new Error('fixture_stopped_before_next_checkpoint:' + JSON.stringify(events)); }); - void stopped.catch(() => {}); - await Promise.race([firstStarted.promise, stopped]); - expect(open.mock.calls[0][0].turnTimeoutMs).toBeUndefined(); - await vi.advanceTimersByTimeAsync(90_000); - expect(notify).toHaveBeenCalledOnce(); expect(interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(30_000); - expect(interrupt).toHaveBeenCalledOnce(); - if (interruptKind === 'stalled') { - expect(close).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(10_000); - expect(close).toHaveBeenCalledOnce(); expect(open).toHaveBeenCalledOnce(); - expect(state.cooperation!.researchDrafts?.investigate).toBeUndefined(); - expect(state.workers![1].candidate).toBeUndefined(); - teardown.resolve(); - } - await Promise.race([resumed.promise, stopped]); - expect(actions[1].assignment).toEqual(actions[0].assignment); - expect(open).toHaveBeenCalledTimes(interruptKind === 'stalled' ? 2 : 1); - if (interruptKind === 'stalled') expect(open.mock.calls[1][0].threadId).toBe('saved-advisory-thread'); - await vi.advanceTimersByTimeAsync(15_000); - expect(interrupt).toHaveBeenCalledOnce(); - expect(close).toHaveBeenCalledTimes(interruptKind === 'stalled' ? 1 : 0); - finish.resolve('completed'); await expect(completion).resolves.toBeUndefined(); - expect(vi.getTimerCount()).toBe(0); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - expect(state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(state.workers![1]).toMatchObject({ threadId: 'saved-advisory-thread', sessionTaskId: 'investigate' }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.status).toBe('completed'); - expect(state.cooperation!.deliveries?.some(delivery => delivery.kind === 'proof' || delivery.kind === 'failure')).toBeFalsy(); - expect(events).toContainEqual({ event: 'turn_checkpoint', details: { - workerId: 'researcher', turn: 1, reason: 'math_cooperative_scheduling_checkpoint', - } }); - expect(events.some(item => item.event === 'worker_failed' || item.event === 'turn_failed')).toBe(false); - for (const target of problem.targets) expect(committedSource(workers[0].worktree, - state.cooperation!.canonicalCommit!, path.join(problem.projectRelative, target.proofPath))).toContain('sorry'); - }); - - it('preserves project scratch through a scheduling checkpoint without committing it or changing the assignment', async () => { - const { state, workers, problem, check, events, run } = fixture(false, 'generated/project'); - const held = heldAdvisoryTurns(2), completion = run(held.open); void completion.catch(() => {}); - await held.wait(0, completion); - const worktree = workers[1].worktree; - const relative = path.join(problem.projectRelative, '.scratch', 'tmp', 'LibProbe.lean'); - const scratch = path.join(worktree, relative), notes = path.join(worktree, 'RESEARCH.md'); - const probe = '-- Advisory library probe, never accepted proof content.\n#check Nat.add_zero\n'; - fs.mkdirSync(path.dirname(scratch), { recursive: true }); fs.writeFileSync(scratch, probe); - fs.writeFileSync(notes, 'A saved construction with its exact remaining quantitative gap.\n'); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - - expect(held.interrupt).toHaveBeenCalledOnce(); expect(held.open).toHaveBeenCalledOnce(); - expect(held.actions[1].task.id).toBe(held.actions[0].task.id); - expect(held.actions[1].assignment).toEqual(held.actions[0].assignment); - expect(state.workers![1]).toMatchObject({ threadId: 'persistent-backoff-thread', sessionTaskId: 'investigate' }); - expect(fs.readFileSync(notes, 'utf8')).toContain('exact remaining quantitative gap'); - expect(fs.lstatSync(scratch).isFile()).toBe(true); expect(fs.readFileSync(scratch, 'utf8')).toBe(probe); - expect(git(worktree, ['ls-files', '--', relative])).toBe(''); - expect(git(worktree, ['ls-files', '--others', '--exclude-standard', '--', relative])).toBe(relative); - const draft = state.cooperation!.researchDrafts!.investigate; - expect(draft).toMatchObject({ workerId: 'researcher', assignmentId: held.actions[0].assignment.assignmentId }); - expect(committedSource(worktree, draft.commit, 'RESEARCH.md')).toContain('exact remaining quantitative gap'); - expect(git(worktree, ['ls-tree', '-r', '--name-only', draft.commit, '--', relative])).toBe(''); - const node = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - expect(node.status).toBe('running'); expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - - fs.writeFileSync(notes, 'A completed advisory investigation with the quantitative gap still explicit.\n'); - held.done[1].resolve('completed'); await expect(completion).resolves.toBeUndefined(); - expect(fs.readFileSync(scratch, 'utf8')).toBe(probe); - expect(git(worktree, ['ls-files', '--', relative])).toBe(''); - expect(git(worktree, ['ls-tree', '-r', '--name-only', 'HEAD', '--', relative])).toBe(''); - expect(git(workers[0].worktree, ['ls-tree', '-r', '--name-only', state.cooperation!.canonicalCommit!, '--', relative])).toBe(''); - expect(events).toContainEqual({ event: 'turn_checkpoint', details: { - workerId: 'researcher', turn: 1, reason: 'math_cooperative_scheduling_checkpoint', - } }); - expect(events.some(item => item.event === 'worker_failed' || item.event === 'turn_failed')).toBe(false); - expect(state.cooperation!.deliveries?.some(delivery => delivery.kind === 'proof' || delivery.kind === 'failure')).toBeFalsy(); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); expect(vi.getTimerCount()).toBe(0); - for (const target of problem.targets) expect(committedSource(workers[0].worktree, - state.cooperation!.canonicalCommit!, path.join(problem.projectRelative, target.proofPath))).toContain('sorry'); - }); - - it('keeps a genuine tool failure as a failure when it coincides with a scheduling interrupt', async () => { - const { check, events, run } = fixture(); - const started = deferred(), done = deferred(); - let lastError: string | undefined; - const open = async (options: MathAgentOptions): Promise => ({ threadId: 'failed-advisory-thread', - get lastError() { return lastError; }, close: async () => {}, - interrupt: async () => { lastError = 'math_model_tool_failed'; done.resolve('failed'); }, - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted('failed-turn'); started.resolve(); - options.onActivity?.({ event: 'reasoning' }); - return done.promise; - } }); - const completion = run(open, 1); void completion.catch(() => {}); - await started.promise; - await vi.advanceTimersByTimeAsync(120_000); - await expect(completion).rejects.toThrow('math_model_tool_failed'); - expect(events.some(item => item.event === 'turn_checkpoint')).toBe(false); - expect(events).toContainEqual({ event: 'turn_failed', details: { - workerId: 'researcher', reason: 'math_model_tool_failed', - } }); - expect(check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it('pauses unchanged advisory research after three scheduling checkpoints', async () => { - const { state, check, events, run } = fixture(); - const held = heldAdvisoryTurns(3), completion = run(held.open, 3); void completion.catch(() => {}); - await held.wait(0, completion); - for (const [turn, interval] of [120_000, 240_000, 480_000].entries()) { - await vi.advanceTimersByTimeAsync(interval); - if (turn < 2) await held.wait(turn + 1, completion); - } - await expect(completion).resolves.toBeUndefined(); - - expect(held.interrupt).toHaveBeenCalledTimes(3); - expect(state.workers![1].advisoryCheckpoint).toMatchObject({ noProgressStreak: 3 }); - expect(state.cooperation!.researchCheckpoints?.investigate).toMatchObject({ count: 3, paused: true }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')) - .toMatchObject({ status: 'blocked', feedback: expect.stringContaining('math_research_checkpoint_unchanged') }); - // The pause parks the input for the Lead instead of leaving it silently blocked; parking is advisory. - const parking = state.cooperation!.blockers!.find(record => record.mechanism === 'unchanged-research-checkpoint')!; - expect(parking.status).toBe('parked'); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.routeParking).toEqual([parking.id]); - expect(events.filter(item => item.event === 'route_parked')).toHaveLength(1); - expect(events.filter(item => item.event === 'cooperative_checkpoint_scheduled') - .map(item => item.details!.checkpointAfterMs)).toEqual([120_000, 240_000, 480_000]); - expect(events.some(item => item.event === 'worker_failed' || item.event === 'turn_failed')).toBe(false); - expect(held.open).toHaveBeenCalledOnce(); - expect(state.workers![1].threadId).toBe('persistent-backoff-thread'); - expect(held.actions).toHaveLength(3); - expect(held.actions.every(action => action.assignment.taskDigest === held.actions[0].assignment.taskDigest)).toBe(true); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['empty', 'missing'] as const)('keeps a disk-restored pause when worker notes are %s', async notes => { - const { state, workers, check, events, run } = fixture(); - const notesFile = path.join(workers[1].worktree, 'RESEARCH.md'); - fs.writeFileSync(notesFile, 'A saved mathematical reduction and its exact unresolved inference.\n'); - const held = heldAdvisoryTurns(3), completion = run(held.open, 3); void completion.catch(() => {}); - await held.wait(0, completion); - for (const [turn, interval] of [120_000, 240_000, 480_000].entries()) { - await vi.advanceTimersByTimeAsync(interval); - if (turn < 2) await held.wait(turn + 1, completion); - } - await expect(completion).resolves.toBeUndefined(); - const paused = structuredClone(state.cooperation!.researchCheckpoints!.investigate); - expect(paused).toMatchObject({ count: 3, paused: true }); - const checkpointFile = path.join(directory, 'paused-research-state.json'); - writeSolverRunState(checkpointFile, state); - if (notes === 'empty') fs.writeFileSync(notesFile, ''); - else fs.rmSync(notesFile); - commitSolverSources(state.problem, workers[1].worktree); - Object.assign(state, readSolverRunState(checkpointFile)); - const resumed = cooperativeResearch({ state, workers, retrievalRoot: directory, - emit: (event, details) => events.push({ event, details }) }); - try { (resumed as any).refreshResearchCheckpoints(); } - finally { await resumed.stop(); } - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.investigate).toEqual(paused); - expect(events.some(item => item.event === 'research_checkpoint_reopened')).toBe(false); - expect(held.actions).toHaveLength(3); expect(check).not.toHaveBeenCalled(); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each([false, true])('restores checkpoint backoff from disk and resets it when the task scope changes (%s)', async changeScope => { - const { state, workers, run } = fixture(); - const held = heldAdvisoryTurns(2), first = run(held.open, 1); void first.catch(() => {}); - await held.wait(0, first); await vi.advanceTimersByTimeAsync(120_000); - await expect(first).resolves.toBeUndefined(); - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak).toBe(1); - const checkpointFile = path.join(directory, 'backoff-state.json'); - writeSolverRunState(checkpointFile, state); - Object.assign(state, readSolverRunState(checkpointFile)); - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak).toBe(1); - if (changeScope) { - const task = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.task; - task.revision++; task.objective = 'Investigate the revised exact construction.'; - } - const second = run(held.open, 2); void second.catch(() => {}); - await held.wait(1, second); - expect(held.open.mock.calls[1][0].threadId).toBe(changeScope ? undefined : 'persistent-backoff-thread'); - if (!changeScope) { - await vi.advanceTimersByTimeAsync(120_000); - expect(held.interrupt).toHaveBeenCalledOnce(); - await vi.advanceTimersByTimeAsync(60_000); - expect(held.notify).toHaveBeenCalledTimes(2); - await vi.advanceTimersByTimeAsync(60_000); - } else await vi.advanceTimersByTimeAsync(120_000); - await expect(second).resolves.toBeUndefined(); - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak).toBe(changeScope ? 1 : 2); - expect(state.workers![1].threadId).toBe('persistent-backoff-thread'); - expect(held.interrupt).toHaveBeenCalledTimes(2); expect(vi.getTimerCount()).toBe(0); - expect(workers[1].role).toBe('researcher'); - }); - - it('keeps each investigation\'s backoff when one worker alternates between research tasks', async () => { - const { state, problem, events, run } = fixture(); - const second = parseCooperationPlan(problem, { tasks: [ - ...state.cooperation!.tasks.map(node => node.task), - { id: 'investigate_b', kind: 'research', ownerId: 'researcher', objective: 'Resolve the independent second construction.' }, - ] }).tasks.find(task => task.id === 'investigate_b')!; - state.cooperation!.tasks.push({ task: second, status: 'pending', attempts: 0 }); - const held = heldAdvisoryTurns(4, ['investigate', 'investigate_b']); - const completion = run(held.open, 4); void completion.catch(() => {}); - await held.wait(0, completion); - for (const [turn, interval] of [120_000, 120_000, 240_000, 240_000].entries()) { - await vi.advanceTimersByTimeAsync(interval); - if (turn < 3) await held.wait(turn + 1, completion); - } - await expect(completion).resolves.toBeUndefined(); - expect(held.actions.map(action => action.task.id)).toEqual(['investigate', 'investigate_b', 'investigate', 'investigate_b']); - expect(events.filter(item => item.event === 'cooperative_checkpoint_scheduled') - .map(item => item.details!.checkpointAfterMs)).toEqual([120_000, 120_000, 240_000, 240_000]); - expect(state.cooperation!.researchCheckpoints?.investigate.advisoryCheckpoint?.noProgressStreak).toBe(2); - expect(state.cooperation!.researchCheckpoints?.investigate_b.advisoryCheckpoint?.noProgressStreak).toBe(2); - expect(held.interrupt).toHaveBeenCalledTimes(4); expect(vi.getTimerCount()).toBe(0); - }); - - it('restores task backoff for another worker from the persisted research checkpoint', async () => { - const { state, workers, events, run } = fixture(); - const held = heldAdvisoryTurns(2), first = run(held.open, 1); void first.catch(() => {}); - await held.wait(0, first); await vi.advanceTimersByTimeAsync(120_000); - await expect(first).resolves.toBeUndefined(); - const checkpointFile = path.join(directory, 'reassigned-backoff-state.json'); - writeSolverRunState(checkpointFile, state); - Object.assign(state, readSolverRunState(checkpointFile)); - const original = workers[1]; - const replacement = { ...original, id: 'researcher-b', worktree: path.join(directory, 'researcher-b') }; - git(workers[0].worktree, ['worktree', 'add', '--quiet', '--detach', replacement.worktree, state.problem.baseCommit]); - workers[1] = replacement; - state.workers![1] = { ...replacement, phase: 'prepared', turns: 0 }; - const node = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - node.task.ownerId = replacement.id; node.assignment = undefined; - const second = run(held.open, 2); void second.catch(() => {}); - await held.wait(1, second); - expect(held.actions[1].assignment.workerId).toBe(replacement.id); - expect(events.filter(item => item.event === 'cooperative_checkpoint_scheduled').at(-1)?.details) - .toMatchObject({ workerId: replacement.id, checkpointAfterMs: 240_000, noProgressStreak: 1 }); - await vi.advanceTimersByTimeAsync(120_000); - expect(held.interrupt).toHaveBeenCalledOnce(); - await vi.advanceTimersByTimeAsync(120_000); - await expect(second).resolves.toBeUndefined(); - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak).toBe(2); - expect(held.interrupt).toHaveBeenCalledTimes(2); expect(vi.getTimerCount()).toBe(0); - }); - - it.each([false, true])('keeps unchanged A → B → A backoff across archived restarts (legacy=%s)', async legacy => { - const { state, problem, events, run, check } = fixture(); - const held = heldAdvisoryTurns(3, ['investigate', 'other']); - const first = run(held.open, 1); void first.catch(() => {}); - await held.wait(0, first); await vi.advanceTimersByTimeAsync(120_000); await first; - const firstOutput = state.cooperation!.researchDrafts!.investigate.outputDigest; - const aScope = state.workers![1].advisoryCheckpoint!.scope; - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak).toBe(1); - if (legacy) delete state.workers![1].advisoryCheckpoints; - const other = parseCooperationPlan(problem, { tasks: [ - ...state.cooperation!.tasks.map(node => node.task), - { id: 'other', kind: 'research', ownerId: 'researcher', objective: 'Investigate an independent quantitative question.' }, - ] }).tasks.find(task => task.id === 'other')!; - state.cooperation!.tasks.push({ task: other, status: 'pending', attempts: 0 }); - const file = path.join(directory, 'alternating-backoff-state.json'); - writeSolverRunState(file, state); Object.assign(state, readSolverRunState(file)); - - const second = run(held.open, 2); void second.catch(() => {}); - await held.wait(1, second); - expect(held.actions[1].task.id).toBe('other'); - expect(state.workers![1].advisoryCheckpoints?.[aScope].noProgressStreak).toBe(1); - await vi.advanceTimersByTimeAsync(120_000); await second; - const bScope = state.workers![1].advisoryCheckpoint!.scope; - writeSolverRunState(file, state); Object.assign(state, readSolverRunState(file)); - expect(state.workers![1].advisoryCheckpoints?.[aScope].noProgressStreak).toBe(1); - expect(state.workers![1].advisoryCheckpoints?.[bScope].noProgressStreak).toBe(1); - - const third = run(held.open, 3); void third.catch(() => {}); - await held.wait(2, third); - expect(held.actions.map(action => action.task.id)).toEqual(['investigate', 'other', 'investigate']); - expect(state.cooperation!.researchDrafts!.investigate.outputDigest).toBe(firstOutput); - expect(events.filter(event => event.event === 'cooperative_checkpoint_scheduled').at(-1)?.details) - .toMatchObject({ checkpointAfterMs: 240_000, noProgressStreak: 1 }); - await vi.advanceTimersByTimeAsync(120_000); expect(held.interrupt).toHaveBeenCalledTimes(2); - await vi.advanceTimersByTimeAsync(120_000); await third; - expect(state.workers![1].advisoryCheckpoint).toMatchObject({ scope: aScope, noProgressStreak: 2 }); - expect(state.workers![1].advisoryCheckpoints?.[bScope].noProgressStreak).toBe(1); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); expect(vi.getTimerCount()).toBe(0); - }); - - it('resets archived scoped backoff when the research environment changes', async () => { - const { state, events, run } = fixture(); - const held = heldAdvisoryTurns(2), first = run(held.open, 1); void first.catch(() => {}); - await held.wait(0, first); await vi.advanceTimersByTimeAsync(120_000); await first; - const scope = state.workers![1].advisoryCheckpoint!.scope; - expect(state.workers![1].advisoryCheckpoints?.[scope].noProgressStreak).toBe(1); - state.environmentDigest = mathDigest('a different fixed mathematical environment'); - const file = path.join(directory, 'changed-input-backoff-state.json'); - writeSolverRunState(file, state); Object.assign(state, readSolverRunState(file)); - const second = run(held.open, 2); void second.catch(() => {}); - await held.wait(1, second); - expect(events.filter(event => event.event === 'cooperative_checkpoint_scheduled').at(-1)?.details) - .toMatchObject({ checkpointAfterMs: 120_000, noProgressStreak: 0 }); - await vi.advanceTimersByTimeAsync(120_000); await second; - expect(state.workers![1].advisoryCheckpoint).toMatchObject({ scope, noProgressStreak: 1 }); - expect(vi.getTimerCount()).toBe(0); - }); - - it('retains other research backoff while a non-advisory helper owns the worker', async () => { - const { state, problem, controller, run } = fixture(); - const held = heldAdvisoryTurns(2, ['investigate', 'helper']); - const first = run(held.open, 1); void first.catch(() => {}); - await held.wait(0, first); await vi.advanceTimersByTimeAsync(120_000); await first; - const scope = state.workers![1].advisoryCheckpoint!.scope; - const helper = parseCooperationPlan(problem, { tasks: [ - ...state.cooperation!.tasks.map(node => node.task), - { id: 'helper', kind: 'lemma', ownerId: 'researcher', objective: 'Prove a closed helper for the construction.', - proofPath: problem.targets[0].proofPath, theoremName: 'checkpoint_helper', type: 'True' }, - ] }).tasks.find(task => task.id === 'helper')!; - state.cooperation!.tasks.push({ task: helper, status: 'pending', attempts: 0 }); - state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.task.status = 'paused'; - const second = run(held.open, 2); void second.catch(() => {}); - await held.wait(1, second); - expect(held.actions[1].task.id).toBe('helper'); - expect(state.workers![1].advisoryCheckpoint).toBeUndefined(); - expect(state.workers![1].advisoryCheckpoints?.[scope].noProgressStreak).toBe(1); - const file = path.join(directory, 'non-advisory-backoff-state.json'); - writeSolverRunState(file, state); - expect(readSolverRunState(file).workers![1].advisoryCheckpoints?.[scope].noProgressStreak).toBe(1); - controller.abort(new Error('fixture_complete')); await expect(second).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('resets bounded advisory backoff when new owned source is saved', async () => { - const { state, workers, problem, check, events, run } = fixture(); - const held = heldAdvisoryTurns(4), completion = run(held.open, 4); void completion.catch(() => {}); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - const relative = path.join(problem.projectRelative, 'Submission.lean'); - const source = path.join(workers[1].worktree, relative); - fs.writeFileSync(source, fs.readFileSync(source, 'utf8').replace('theorem add_zero', - 'lemma partial_construction : True := by trivial\ntheorem add_zero')); - await vi.advanceTimersByTimeAsync(240_000); await held.wait(2, completion); - expect(state.workers![1].advisoryCheckpoint?.noProgressStreak).toBe(0); - const draft = state.cooperation!.researchDrafts!.investigate; - expect(committedSource(workers[1].worktree, draft.commit, relative)).toContain('lemma partial_construction : True := by trivial'); - expect(events.filter(item => item.event === 'cooperative_checkpoint_scheduled').at(-1)?.details) - .toMatchObject({ checkpointAfterMs: 120_000, noProgressStreak: 0, protected: false }); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(3, completion); - await vi.advanceTimersByTimeAsync(240_000); await expect(completion).resolves.toBeUndefined(); - expect(held.interrupt).toHaveBeenCalledTimes(4); - expect(state.cooperation!.researchCheckpoints?.investigate).toMatchObject({ count: 3, paused: true }); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); expect(vi.getTimerCount()).toBe(0); - }); - - it.each([ - { initial: true, published: true, approval: false }, - { initial: true, published: true, approval: true }, - { initial: true, published: false, approval: false }, - { initial: false, published: true, approval: false }, - ])('reminds only unpublished Lead decisions (initial=$initial, published=$published, approval=$approval)', async ({ initial, published, approval }) => { - const { state, workers, check, events, controller, run, pulse } = fixture(initial, undefined, initial ? undefined : 'lead'); - if (approval) state.planApproval = true; - const leadStarted = deferred(), peerStarted = deferred(); - const sessions = new Map; notify: ReturnType }>(); - let leadAction: Extract; - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - const done = deferred(); - const interrupt = vi.fn(async () => { done.resolve('interrupted'); }), notify = vi.fn(async () => {}); - sessions.set(id, { interrupt, notify }); - return { threadId: `published-plan-${id}`, interrupt, notify, close: async () => { done.resolve('interrupted'); }, - run: async (message, _messageId, _workspace, onStarted) => { - const payload = JSON.parse(message); - const action: CooperativeAction = payload.assignment ?? payload; - onStarted(`published-plan-turn-${id}`); - options.onActivity?.({ event: 'reasoning' }); - if (id === 'solver') { - if (action.kind !== 'lead') throw new Error('fixture_expected_lead'); - leadAction = action; leadStarted.resolve(); - } else peerStarted.resolve(); - return done.promise; - } }; - }); - const completion = run(open); void completion.catch(() => {}); - await leadStarted.promise; - const tasks = initial ? state.problem.targets.map((target, index) => ({ - id: `goal_${index + 1}`, kind: 'goal', objective: `Prove ${target.theoremName}`, ...target, - })) : state.cooperation!.tasks.map(node => ({ ...node.task, - ...(node.task.id === 'investigate' ? { status: 'active' } : {}) })); - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(leadAction!)!), JSON.stringify({ - kind: 'plan', baseVersion: leadAction!.planVersion, - dispatchNonce: leadAction!.initialPlanNonce ?? leadAction!.planNonce, - summary: 'The original target and its assigned investigation are ready.', tasks: published ? tasks : [], - }) + '\n'); - await pulse(workers[0].id); - expect(Boolean(state.cooperation!.planPublication)).toBe(published); - if (published && !approval) await peerStarted.promise; - if (approval) { - expect(state.cooperation!.planApproval?.approvedAt).toBeUndefined(); - expect(sessions.has(workers[1].id)).toBe(false); - } - await vi.advanceTimersByTimeAsync(5 * 60_000); - const lead = sessions.get('solver')!; - expect(lead.notify.mock.calls.some(([message]) => /^If the first plan is still unpublished, publish it now/u.test(message))).toBe(!published); - expect(events.filter(item => item.event === 'cooperative_checkpoint_requested' && item.details?.workerId === 'solver')) - .toHaveLength(published ? 0 : 1); - expect(lead.interrupt).not.toHaveBeenCalled(); - // Publication suppresses a stale reminder; it neither ends the live Lead nor accepts a proof. - expect(events.some(item => item.event === 'cooperative_checkpoint_interrupted' && item.details?.workerId === 'solver')).toBe(false); - expect(state.check).toBeUndefined(); expect(check).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); - await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it('yields an unfinished Lead plan to original-goal work without a planning interrupt on the proof writer', async () => { - const { state, workers, check, events, controller, run } = fixture(true); - const leadStarted = deferred(), proofStarted = deferred(); - const leadDone = deferred(), proofDone = deferred(); - const sessions = new Map; notify: ReturnType }>(); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - const done = id === 'solver' ? leadDone : proofDone; - const interrupt = vi.fn(async () => { done.resolve('interrupted'); }), notify = vi.fn(async () => {}); - sessions.set(id, { interrupt, notify }); - return { threadId: `thread-${id}`, interrupt, notify, close: async () => { done.resolve('interrupted'); }, - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted(`turn-${id}`); - options.onActivity?.({ event: 'reasoning' }); - if (id === 'solver') { - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'The first construction is incomplete; a quantifier bridge remains open.\n'); - leadStarted.resolve(); - } else proofStarted.resolve(); - return done.promise; - } }; - }); - const completion = run(open, 2, undefined, { softSliceMs: 0 }); void completion.catch(() => {}); - await leadStarted.promise; - // Ask for executable work early while preserving the long writing slice. - await vi.advanceTimersByTimeAsync(90_000 - 1); - expect(sessions.get('solver')!.interrupt).not.toHaveBeenCalled(); - expect(events).toContainEqual(expect.objectContaining({ event: 'cooperative_checkpoint_scheduled', - details: expect.objectContaining({ workerId: 'solver', checkpointAfterMs: 20 * 60_000, noticeAfterMs: 90_000 }) })); - expect(sessions.get('solver')!.notify).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(sessions.get('solver')!.notify).toHaveBeenCalledOnce(); - expect(sessions.get('solver')!.notify.mock.calls[0]![0]).toMatch(/^If the first plan is still unpublished, publish it now/u); - expect(sessions.get('solver')!.notify.mock.calls[0]![0]).toContain('plan-apply --publish'); - expect(sessions.get('solver')!.interrupt).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(20 * 60_000 - 90_000); - await proofStarted.promise; - expect(sessions.get('solver')!.notify).toHaveBeenCalledOnce(); - expect(sessions.get('solver')!.interrupt).toHaveBeenCalledOnce(); - expect(state.cooperation!.initialPlanFallback).toBeDefined(); - expect(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'utf8')).toContain('a quantifier bridge remains open'); - expect(state.cooperation!.tasks.filter(node => node.task.kind === 'goal')).toHaveLength(state.problem.targets.length); - expect(state.check).toBeUndefined(); expect(check).not.toHaveBeenCalled(); - expect(workers[1].role).toBe('engineer'); - await vi.advanceTimersByTimeAsync(2 * 3_600_000); - // The goal writer is the only worker that can close the problem: it is reminded to keep a - // durable handoff, but its turn is never taken away and it never receives a yield notice. - expect(sessions.get('engineer')!.interrupt).not.toHaveBeenCalled(); - expect(sessions.get('engineer')!.notify).toHaveBeenCalledOnce(); - expect(sessions.get('engineer')!.notify.mock.calls[0]![0]).toMatch(/RESEARCH\.md/u); - expect(sessions.get('engineer')!.notify.mock.calls[0]![0]).toMatch(/no checkpoint will interrupt or end it/u); - expect(events).toContainEqual(expect.objectContaining({ event: 'cooperative_checkpoint_scheduled', - details: expect.objectContaining({ workerId: 'engineer', noticeOnly: true, checkpointAfterMs: 15 * 60_000 }) })); - expect(events.some(item => item.event === 'cooperative_checkpoint_interrupted' && item.details?.workerId === 'engineer')).toBe(false); - expect(open.mock.calls.every(([options]) => options.turnTimeoutMs === undefined)).toBe(true); - expect(events.some(item => item.event === 'turn_checkpoint' && - item.details?.reason === 'math_cooperative_scheduling_checkpoint')).toBe(true); - controller.abort(new Error('fixture_complete')); - await expect(completion).rejects.toThrow('fixture_complete'); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each([false, true])('yields a conditional goal without submitting unfinished code (ready at boundary: %s)', async ready => { - const { state, workers, problem, check, events, run } = fixture(); - state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.task.status = 'paused'; - const goal = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!; - goal.task = { ...goal.task, status: 'active', conditional: true, dependsOn: ['connection_input'] }; - const helper = parseCooperationPlan(problem, { tasks: [ - ...state.cooperation!.tasks.map(node => node.task), - { id: 'connection_input', kind: 'lemma', objective: 'Prove the missing input.', ownerId: 'solver', - theoremName: 'connection_input', type: 'True', proofPath: problem.targets[0].proofPath }, - ] }).tasks.find(task => task.id === 'connection_input')!; - state.cooperation!.tasks.push({ task: helper, status: 'pending', attempts: 0 }); - const held = heldAdvisoryTurns(1, [goal.task.id]); - if (ready) { - const interrupt = held.interrupt.getMockImplementation()!; - held.interrupt.mockImplementation(async () => { - fs.appendFileSync(path.join(workers[1].worktree, assignmentDeliveryFile(held.actions[0].assignment)), - JSON.stringify({ kind: 'ready', id: 'conditional-ready-at-boundary' }) + '\n'); - await interrupt(); - }); - } - const completion = run(held.open, 1); void completion.catch(() => {}); - await held.wait(0, completion); - expect(held.actions[0].assignment.connectionCheck).toBeDefined(); - const notes = 'The exact conditional application gap is saved; the input is still unproved.\n'; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); - await vi.advanceTimersByTimeAsync(120_000); - if (ready) { - await expect(completion).rejects.toThrow('math_writer_stop_unconfirmed'); - expect(state.workers![1].writerStopUnconfirmed).toBeDefined(); - expect(events.some(event => event.event === 'connection_checkpoint_saved')).toBe(false); - } else { - await completion; - const draft = state.cooperation!.researchDrafts![goal.task.id]; - expect(committedSource(workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(notes); - expect(goal.status).toBe('pending'); - expect(goal.proof).toBeUndefined(); expect(goal.integratedCheck).toBeUndefined(); - expect(events.some(event => event.event === 'connection_checkpoint_saved')).toBe(true); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - } - expect(held.interrupt).toHaveBeenCalledOnce(); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - expect(vi.getTimerCount()).toBe(0); - }); - - function connectionChain() { - const run = fixture(), { state, problem } = run; - state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.task.status = 'paused'; - const goal = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!; - goal.task = { ...goal.task, status: 'active', conditional: false, dependsOn: ['connection_consumer'] }; - const plan = parseCooperationPlan(problem, { tasks: [ - ...state.cooperation!.tasks.map(node => node.task), - { id: 'connection_consumer', kind: 'lemma', conditional: true, ownerId: 'researcher', - objective: 'Construct the conditional application.', dependsOn: ['connection_bridge'], - theoremName: 'connection_consumer', type: 'True', proofPath: problem.targets[0].proofPath }, - { id: 'connection_bridge', kind: 'lemma', ownerId: 'solver', objective: 'Connect the leaf to the consumer.', - dependsOn: ['connection_leaf'], theoremName: 'connection_bridge', type: 'True', proofPath: problem.targets[0].proofPath }, - { id: 'connection_leaf', kind: 'lemma', ownerId: 'researcher', objective: 'Prove the runnable upstream input.', - theoremName: 'connection_leaf', type: 'True', proofPath: problem.targets[0].proofPath }, - ] }); - state.cooperation!.tasks.push(...plan.tasks.filter(task => task.id.startsWith('connection_')) - .map(task => ({ task, status: 'pending' as const, attempts: 0 }))); - return run; - } - - it.each(['refuted', 'prose', 'jsonl', 'jsonl-context', 'restart', 'legacy-restart'] as const)( - 'waits for Lead to decide the proof checkpoint (%s)', async report => { - const { state: initialState, workers, problem, check, controller } = connectionChain(); - let state = initialState; - const producer = peerWorker({ directory, problem, workspace: workers[0].worktree }, 'producer', { role: 'prover' }); - workers.push(producer); - state.workers!.push({ ...producer, phase: 'prepared', turns: 0 }); - const bridge = state.cooperation!.tasks.find(node => node.task.id === 'connection_bridge')!; - bridge.task = { ...bridge.task, ownerId: producer.id, dependsOn: [] }; - state.cooperation!.tasks = state.cooperation!.tasks.filter(node => node.task.id !== 'connection_leaf'); - - const [lead, worker] = workers; - const restart = report === 'restart' || report === 'legacy-restart'; - const saved = path.join(directory, 'connection-wait.json'); - const create = (save?: () => void) => cooperativeResearch({ state, workers, retrievalRoot: directory, - signal: controller.signal, save, - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, check, checkTask: check, closeTask: undefined } } }); - let cooperation = create(() => { - if (restart && !fs.existsSync(saved) && state.cooperation!.deliveries?.some(record => record.kind === 'research')) - writeSolverRunState(saved, state); - }); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const consumer = async () => { - const action = await cooperation.next(worker, budget); - if (action?.kind !== 'task' || action.task.id !== 'connection_consumer') - throw new Error('fixture_expected_connection_consumer'); - expect(cooperation.started(worker, action)).toBe(true); - return action; - }; - const checkpoint = async (action: Awaited>, laterFindings = 0) => { - await cooperation.retainContextDraft(worker, action, commitSolverSources(problem, worker.worktree), - report === 'jsonl-context' ? 'context' : 'connection'); - if (laterFindings) { - cooperation.activate(worker, action, async () => {}, async () => {}); - const log = path.join(worker.worktree, assignmentDeliveryFile(action.assignment)); - for (let index = 0; index < laterFindings; index++) { - fs.appendFileSync(log, JSON.stringify({ kind: 'research', finding: { conclusion: 'inconclusive', - needsDecision: true, summary: 'A later advisory finding on the connection, ' + index } }) + '\n'); - } - await cooperation.pulse(worker.id); - cooperation.deactivate(worker); - } - cooperation.interrupted(worker, action); - }; - const inbox = () => leadResearchInputs(state.cooperation!.deliveries ?? [], - new Map(state.cooperation!.tasks.map(node => [node.task.id, node])), state.cooperation!.researchDecisions); - - const first = await consumer(); - const jsonl = report === 'jsonl' || report === 'jsonl-context'; - const laterCount = report === 'refuted' ? 8 : 0; - const value = { conclusion: 'refuted', summary: 'A witness refutes the proposed inference from the recorded premises.' }; - const notes = report === 'prose' ? 'The exact proposed inference and a candidate witness are saved here for review.\n' - : '\x60\x60\x60math-result\n' + JSON.stringify(value) + '\n\x60\x60\x60\n'; - if (jsonl) { - cooperation.activate(worker, first, async () => {}, async () => {}); - fs.appendFileSync(path.join(worker.worktree, assignmentDeliveryFile(first.assignment)), - JSON.stringify({ kind: 'research', finding: { ...value, needsDecision: true } }) + '\n'); - await cooperation.pulse(worker.id); - cooperation.deactivate(worker); - expect(inbox()).toHaveLength(1); - } else fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), notes); - // Fill the Lead inbox's eight-entry view with newer findings from the same - // assignment. They do not change the paused worker's mathematical inputs. - await checkpoint(first, laterCount); - if (report === 'prose') { - expect(inbox()).toHaveLength(0); - await checkpoint(await consumer()); - } - const [finding, ...laterFindings] = inbox(); - expect(laterFindings).toHaveLength(laterCount); - expect(finding.taskId).toBe('connection_consumer'); - expect(JSON.parse(finding.finding!)).toMatchObject({ conclusion: report === 'prose' ? 'inconclusive' : 'refuted', needsDecision: true }); - if (!jsonl) expect(committedSource(lead.worktree, finding.commit!, 'RESEARCH.md')).toBe(notes); - if (!restart) writeSolverRunState(saved, state); - const savedState = readSolverRunState(saved); - const savedConsumer = savedState.cooperation!.tasks.find(node => node.task.id === finding.taskId)!; - expect(savedConsumer.connectionCheckpoint?.leadDeliveryId).toBe(finding.id); - if (restart) { - expect(savedConsumer.status).toBe('running'); - // Reproduce the archive written by earlier versions before the wait was bound. - if (report === 'legacy-restart') delete savedConsumer.connectionCheckpoint; - await cooperation.stop(); - state = savedState; cooperation = create(() => {}); - await cooperation.restore(); - expect(inbox().map(record => record.id)).toEqual([finding.id]); - } - - let redispatched = false; - const resumed = consumer().then(action => { redispatched = true; return action; }); - void resumed.catch(() => {}); - const leadTurn = async () => { - const decision = await cooperation.next(lead, budget); - if (decision?.kind !== 'lead') throw new Error('fixture_expected_lead_decision'); - expect(cooperation.started(lead, decision)).toBe(true); - return decision; - }; - const answer = async (decision: Awaited>, deliveryIds: string[]) => { - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '\x60\x60\x60math-plan\n' + JSON.stringify({ - baseVersion: decision.planVersion, upsert: [], summary: 'Reviewed the presented findings.', - researchDecisions: deliveryIds.map(deliveryId => ({ deliveryId, outcome: 'decline', - reason: 'The proposed inference is not needed for the test route.' })), - }) + '\n\x60\x60\x60\n'); - await cooperation.deliver(lead, decision, commitSolverSources(problem, lead.worktree)); - }; - const firstDecision = await leadTurn(); - if (laterCount) { - const shown = laterFindings.map(item => item.id); - expect(cooperation.contextState(firstDecision, lead).leadResearchInputIds).toEqual(shown); - await answer(firstDecision, shown); - expect(state.cooperation!.error).toBeUndefined(); - } else { - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'The checkpoint still needs a decision.\n'); - await cooperation.deliver(lead, firstDecision, commitSolverSources(problem, lead.worktree), true, 'scheduling-checkpoint'); - } - await vi.advanceTimersByTimeAsync(0); - expect(inbox().map(item => item.id)).toEqual([finding.id]); - expect(redispatched).toBe(false); - const decision = await leadTurn(); - expect(cooperation.contextState(decision, lead).leadResearchInputIds).toEqual([finding.id]); - await answer(decision, [finding.id]); - expect(state.cooperation!.error).toBeUndefined(); - const next = await resumed; - expect(next.assignment.assignmentId).toBe(first.assignment.assignmentId); - expect(inbox()).toEqual([]); - await checkpoint(next); - expect(state.cooperation!.deliveries!.filter(record => record.kind === 'research')).toHaveLength(1 + laterFindings.length); - expect(check).not.toHaveBeenCalled(); - expect(state.cooperation!.tasks.find(node => node.task.id === finding.taskId)?.proof).toBeUndefined(); - await cooperation.stop(); - }); - - it('lets an unchanged connection checkpoint dispatch its owned transitive leaf with the consumer draft retained', async () => { - const { state, workers, problem, check, controller, events, run } = connectionChain(); - const held = heldAdvisoryTurns(3, ['connection_consumer', 'connection_leaf']); - const completion = run(held.open, 3); void completion.catch(() => {}); - await held.wait(0, completion); - expect(held.actions[0].task.id).toBe('connection_consumer'); - const notes = 'Saved the conditional application; the upstream finite argument is still missing.\n'; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), notes); - fs.appendFileSync(path.join(workers[1].worktree, problem.projectRelative, problem.targets[0].proofPath), - '\n-- Partial consumer derivation retained across the upstream task.\n'); - await vi.advanceTimersByTimeAsync(120_000); - await held.wait(1, completion); - expect(held.actions[1].task.id).toBe('connection_consumer'); - const consumer = state.cooperation!.tasks.find(node => node.task.id === 'connection_consumer')!; - expect(consumer.connectionCheckpoint).toBeUndefined(); // Fresh durable output earns another turn. - const assignment = consumer.assignment; - await vi.advanceTimersByTimeAsync(120_000); - await held.wait(2, completion); - expect(held.actions[2].task.id).toBe('connection_leaf'); - const draft = state.cooperation!.researchDrafts!.connection_consumer; - expect(draft.suspended).toBe(true); - expect(committedSource(workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(notes); - expect(committedSource(workers[1].worktree, draft.commit, `${problem.projectRelative}/${problem.targets[0].proofPath}`)) - .toContain('Partial consumer derivation retained'); - expect(consumer.assignment).toBe(assignment); - expect(consumer.connectionCheckpoint?.outputDigest).toBe(draft.outputDigest); - expect(events.filter(event => event.event === 'connection_checkpoint_saved')).toHaveLength(2); - const saved = path.join(directory, 'connection-yield.json'); - writeSolverRunState(saved, state); - expect(readSolverRunState(saved).cooperation!.tasks.find(node => node.task.id === consumer.task.id)?.connectionCheckpoint) - .toEqual(consumer.connectionCheckpoint); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it.each(['unchanged', 'new-input', 'new-output'] as const)( - 'restores a saved connection checkpoint and dispatches after %s', async change => { - const { state, workers, check, controller, run } = connectionChain(); - const held = heldAdvisoryTurns(2, ['connection_consumer', 'connection_leaf']); - const first = run(held.open, 1); void first.catch(() => {}); - await held.wait(0, first); - await vi.advanceTimersByTimeAsync(120_000); await first; - const consumer = state.cooperation!.tasks.find(node => node.task.id === 'connection_consumer')!; - expect(consumer.connectionCheckpoint).toBeDefined(); - if (change === 'new-input') { - // Relevant evidence can change without changing a task's statement or connection identity. - state.cooperation!.tasks.find(node => node.task.id === 'connection_leaf')!.finding = 'A new finite recurrence is available.'; - // Persist it as a source-bound canonical input, like newly integrated supporting code. - const file = path.join(workers[0].worktree, state.problem.projectRelative, state.problem.targets[0].proofPath); - fs.appendFileSync(file, '\n-- New canonical finite-recurrence source.\n'); - state.cooperation!.canonicalCommit = commitSolverSources(state.problem, workers[0].worktree); - } - if (change === 'new-output') { - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), 'A newly saved conditional derivation.\n'); - commitSolverSources(state.problem, workers[1].worktree); - } - const saved = path.join(directory, 'restored-connection-yield.json'); - writeSolverRunState(saved, state); Object.assign(state, readSolverRunState(saved)); - const second = run(held.open, 2); void second.catch(() => {}); - await held.wait(1, second); - expect(held.actions[1].task.id).toBe(change === 'unchanged' ? 'connection_leaf' : 'connection_consumer'); - if (change !== 'unchanged') expect(state.cooperation!.tasks.find(node => node.task.id === consumer.task.id)?.connectionCheckpoint) - .toBeUndefined(); - controller.abort(new Error('fixture_complete')); await expect(second).rejects.toThrow('fixture_complete'); - expect(check).not.toHaveBeenCalled(); expect(vi.getTimerCount()).toBe(0); - }); - - it('suppresses a stale reminder after the Lead publishes its first graph without interrupting peers', async () => { - const { state, check, controller, run, pulse } = fixture(true); - const leadStarted = deferred(), engineerStarted = deferred(); - const notifications = new Map>(); - const interrupts = new Map>(); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!, done = deferred(); - const notify = vi.fn(async () => {}), interrupt = vi.fn(async () => { done.resolve('interrupted'); }); - notifications.set(id, notify); interrupts.set(id, interrupt); - return { threadId: `thread-${id}`, notify, interrupt, close: async () => { done.resolve('interrupted'); }, - run: async (message, _messageId, _workspace, onStarted) => { - onStarted(`turn-${id}`); options.onActivity?.({ event: 'reasoning' }); - if (id === 'solver') { - const action = JSON.parse(message) as Extract; - fs.appendFileSync(path.join(options.workspace, leadPlanDeliveryFile(action)!), JSON.stringify({ - kind: 'plan', baseVersion: action.planVersion, - tasks: state.problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, ...target })), - }) + '\n'); - leadStarted.resolve(); - } else engineerStarted.resolve(); - return done.promise; - } }; - }); - const completion = run(open); void completion.catch(() => {}); - await leadStarted.promise; await pulse('solver'); await engineerStarted.promise; - expect(state.cooperation!.initialPlanPublication).toBeDefined(); - await vi.advanceTimersByTimeAsync(90_000); - expect(notifications.get('solver')).not.toHaveBeenCalled(); - expect(interrupts.get('solver')).not.toHaveBeenCalled(); - expect(interrupts.get('engineer')).not.toHaveBeenCalled(); - expect(state.cooperation!.initialPlanFallback).toBeUndefined(); - expect(check).not.toHaveBeenCalled(); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); - - it.each([ - { readyAfterInterrupt: false, completesAfterPublish: false }, - { readyAfterInterrupt: false, completesAfterPublish: true }, - { readyAfterInterrupt: true, completesAfterPublish: false }, - ])('preserves the proof freeze barrier with readiness=$readyAfterInterrupt and completed=$completesAfterPublish', async ({ readyAfterInterrupt, completesAfterPublish }) => { - const { state, workers, problem, check, events, controller, run, pulse } = fixture(); - workers[1].role = state.workers![1].role = 'engineer'; - state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.task.status = 'paused'; - for (const node of state.cooperation!.tasks.filter(node => node.task.kind === 'goal')) { - node.task.status = 'active'; node.task.ownerId = workers[1].id; - } - const started = [deferred(), deferred()], done = [deferred(), deferred()]; - const messages: Extract[] = [], threads: string[] = []; - let inputTokens = 0, turns = 0, readyWritten = false, active: ReturnType> | undefined; - const interrupt = vi.fn(async () => { - if (readyAfterInterrupt && !readyWritten) { - readyWritten = true; - fs.appendFileSync(path.join(workers[1].worktree, assignmentDeliveryFile(messages[0].assignment)), - JSON.stringify({ kind: 'ready', id: 'ready-after-context-interrupt' }) + '\n'); - } - active?.resolve('interrupted'); - }); - const close = vi.fn(async () => { active?.resolve('interrupted'); }); - const stopForFreeze = vi.fn(async () => ({ status: 'unconfirmed' as const, reason: 'process-group-active' as const })); - const notify = vi.fn(async () => {}); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const threadId = `proof-context-thread-${open.mock.calls.length}`; - return { threadId, interrupt, close, notify, ...(readyAfterInterrupt ? { stopForFreeze } : {}), - get lastInputTokens() { return inputTokens; }, - run: async (message, _messageId, _workspace, onStarted) => { - const turn = turns++; - if (turn > 1) throw new Error('fixture_unexpected_third_proof_turn'); - const action = JSON.parse(message) as CooperativeAction; - if (action.kind !== 'task' || action.task.kind !== 'goal') throw new Error('fixture_expected_proof_task'); - messages.push(action); threads.push(threadId); active = done[turn]; - onStarted(`proof-context-turn-${turn}`); started[turn].resolve(); return done[turn].promise; - } }; - }); - const completion = run(open, Infinity, undefined, { softSliceMs: 0 }); void completion.catch(() => {}); - const wait = (turn: number) => Promise.race([started[turn].promise, - completion.then(() => { throw new Error('fixture_proof_stopped_before_context_checkpoint:' + turn); })]); - await wait(0); - const notes = path.join(workers[1].worktree, 'RESEARCH.md'); - const source = path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'); - const originalSource = fs.readFileSync(source, 'utf8'); - inputTokens = 100_000; - open.mock.calls[0][0].onActivity!({ event: 'reasoning' }); - expect(state.workers![1].contextCheckpoint?.threadId).toBe(threads[0]); - expect(notify).toHaveBeenCalledWith(expect.stringContaining(state.workers![1].contextCheckpoint!.requestId!)); - await vi.advanceTimersByTimeAsync(2 * 3_600_000); - expect(interrupt).not.toHaveBeenCalled(); expect(close).not.toHaveBeenCalled(); - expect(open).toHaveBeenCalledOnce(); expect(check).not.toHaveBeenCalled(); - expect(state.workers![1].previousThreadIds).toBeUndefined(); - // Provider compaction can lower the visible token count before the saved handoff reaches the host. - inputTokens = 24_000; - open.mock.calls[0][0].onActivity!({ event: 'item_completed', itemType: 'contextCompaction' }); - fs.writeFileSync(notes, 'The exact current proof argument, attempted methods, and unresolved inference are saved.\n'); - const partialSource = originalSource.replace('by sorry', 'by\n -- Interrupted proof draft must survive context maintenance.\n sorry') + - '\nlemma checkpoint_support : True := by trivial\n'; - fs.writeFileSync(source, partialSource); - await vi.advanceTimersByTimeAsync(5_000); - expect(interrupt).not.toHaveBeenCalled(); - // Saving notes is only the first tool action. The following report must reach the host before yielding. - const log = path.join(workers[1].worktree, assignmentDeliveryFile(messages[0].assignment)); - fs.appendFileSync(log, JSON.stringify({ kind: 'progress', summary: 'The exact unresolved inference remains in this saved draft.' }) + '\n'); - const request = state.workers![1].contextCheckpoint!; - fs.appendFileSync(log, JSON.stringify({ kind: 'checkpoint', requestId: request.requestId, - notesDigest: mathDigest(fs.readFileSync(notes)) }) + '\n'); - await pulse(workers[1].id); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ kind: 'progress', - summary: 'The exact unresolved inference remains in this saved draft.' })); - if (completesAfterPublish) done[0].resolve('completed'); - else await vi.advanceTimersByTimeAsync(5_000); - if (readyAfterInterrupt) { - await expect(completion).rejects.toThrow('math_writer_stop_unconfirmed'); - expect(stopForFreeze).toHaveBeenCalledOnce(); expect(close).toHaveBeenCalledOnce(); - expect(open).toHaveBeenCalledOnce(); - expect(state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'failed', - reason: 'Freeze unconfirmed: process-group-active' }]); - expect(state.cooperation!.proofReadyRecords![0].snapshotCommit).toBeUndefined(); - expect(state.workers![1].writerStopUnconfirmed).toMatchObject({ reason: 'process-group-active' }); - expect(events.some(item => item.event === 'context_checkpoint_interrupted')).toBe(true); - expect(events.some(item => item.event === 'context_checkpoint_saved')).toBe(false); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - expect(vi.getTimerCount()).toBe(0); - return; - } - await wait(1); - expect(interrupt).toHaveBeenCalledTimes(completesAfterPublish ? 0 : 1); expect(close).toHaveBeenCalledOnce(); - expect(open).toHaveBeenCalledTimes(2); expect(open.mock.calls[1][0].threadId).toBeUndefined(); - expect(threads).toEqual(['proof-context-thread-1', 'proof-context-thread-2']); - expect(messages[1].assignment).toEqual(messages[0].assignment); - expect(state.workers![1].previousThreadIds).toEqual(['proof-context-thread-1']); - expect(state.workers![1].contextCheckpoint).toBeUndefined(); - expect(fs.readFileSync(notes, 'utf8')).toContain('exact current proof argument'); - expect(fs.readFileSync(source, 'utf8')).toBe(partialSource); - const snapshot = events.find(item => item.event === 'context_checkpoint_saved')!.details!; - expect(committedSource(workers[1].worktree, snapshot.commit as string, 'RESEARCH.md')).toContain('exact current proof argument'); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ kind: 'progress', status: 'advisory', - commit: snapshot.commit, artifacts: expect.objectContaining({ scope: 'advisory-unverified', - artifacts: expect.arrayContaining([expect.objectContaining({ declarations: expect.arrayContaining([ - expect.objectContaining({ name: 'checkpoint_support', draft: false }), - ]) })]) }) })); - expect(state.cooperation!.tasks.find(node => node.task.id === messages[0].task.id)).toMatchObject({ status: 'running' }); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(events.some(item => ['task_checked', 'task_failed_input_recorded', 'worker_failed', 'turn_failed'].includes(item.event))).toBe(false); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - expect(state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(open.mock.calls.every(([options]) => options.turnTimeoutMs === undefined)).toBe(true); - controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); - expect(vi.getTimerCount()).toBe(0); - }); -}); diff --git a/tests/solverDefinitionContractChecks.test.ts b/tests/solverDefinitionContractChecks.test.ts deleted file mode 100644 index 606d633d..00000000 --- a/tests/solverDefinitionContractChecks.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { buildResearchContext } from '../src/solver/modules/context'; -import { prepareNextCheckDecisions } from '../src/solver/nextChecks'; -import { queueResearchObservation } from '../src/solver/researchObservation'; -import { parseCooperationPlan } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ createSession: vi.fn() })); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const stop of cleanup.splice(0).reverse()) await stop(); - expect(host.createSession).not.toHaveBeenCalled(); host.createSession.mockReset(); -}); - -async function fixture() { - const example = localExample('definition-contract-flow-'); - const lead = leadWorker(example.problem, example.workspace); - const author = peerWorker(example, 'author'), checker = peerWorker(example, 'checker'); - const proofPath = example.problem.targets[0].proofPath; - const plan = parseCooperationPlan(example.problem, { tasks: [ - ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', - objective: 'Prove the original target.', ...(index ? { status: 'paused' } : { dependsOn: ['left', 'right'] }) })), - { id: 'witness', kind: 'lemma', declaration: 'definition', objective: 'Construct the shared witness.', - theoremName: 'sharedWitness', type: 'ℕ', proofPath, ownerId: author.id }, - ...['left', 'right'].map(id => ({ id, kind: 'lemma', objective: `Apply the witness to ${id}.`, - theoremName: `shared_${id}`, type: 'True', proofPath, dependsOn: ['witness'] })), - ] }); - const state = solverState(example.problem, example.workspace, { runId: 'contract-check-fixture', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const controller = new AbortController(), events: string[] = []; - const cooperation = cooperativeResearch({ state, workers: [lead, author, checker], retrievalRoot: example.directory, - signal: controller.signal, emit: event => events.push(event) }); - cleanup.push(async () => { controller.abort(); await cooperation.stop(); fs.rmSync(example.directory, { recursive: true, force: true }); }); - await cooperation.restore(); - return { ...example, state, lead, author, checker, plan, controller, cooperation, events }; -} - -it.each(['definition-paused', 'goal-paused', 'removed-path'])( - 'expires a pending check on %s and resumes the same record when its path returns', async scenario => { - const f = await fixture(); - const record = f.state.cooperation!.nextChecks![0]; - const acceptPlan = (plan: typeof f.plan) => (f.cooperation as unknown as { - acceptPlan(plan: typeof f.plan): Promise; - }).acceptPlan(plan); - const changed = structuredClone(f.plan); - if (scenario === 'definition-paused') changed.tasks.find(task => task.id === 'witness')!.status = 'paused'; - if (scenario === 'goal-paused') changed.tasks.find(task => task.id === 'goal_0')!.status = 'paused'; - if (scenario === 'removed-path') for (const id of ['left', 'right']) - changed.tasks.find(task => task.id === id)!.dependsOn = []; - await acceptPlan(changed); - expect(record.status).toBe('stale'); - expect(f.state.cooperation!.tasks.filter(node => node.nextCheckId === record.id && node.task.status !== 'stopped')).toEqual([]); - await acceptPlan(structuredClone(f.plan)); - expect(f.state.cooperation!.nextChecks).toHaveLength(1); - expect(record.status).toBe('pending'); - expect(f.state.cooperation!.tasks.filter(node => node.nextCheckId === record.id)).toHaveLength(1); - const action = await f.cooperation.next(f.checker, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind).toBe('task'); - if (action?.kind === 'task') expect(action.task.id).toBe(record.taskId); - expect(f.state.cooperation!.invalidTaskTransitions ?? []).toEqual([]); - expect(f.events).toContain('next_check_resumed'); - }); - -it('dispatches an independent definition check, returns negative evidence to Lead, and preserves it through restart', async () => { - const f = await fixture(); - const action = await f.cooperation.next(f.checker, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind).toBe('task'); - if (action?.kind !== 'task') throw new Error('missing check'); - const record = f.state.cooperation!.nextChecks![0]; - expect(record.origin).toBe('definition-contract'); - expect(action.task.id).toBe(record.taskId); - const view = f.cooperation.contextState(action, f.checker); - expect(view.nextChecks?.map(check => check.id)).toContain(record.id); - expect(f.cooperation.started(f.checker, action)).toBe(true); - f.cooperation.activate(f.checker, action, async () => {}, async () => {}); - fs.writeFileSync(path.join(f.checker.worktree, 'RESEARCH.md'), 'Scoped interface check: retained evidence for a rejected argument.\n'); - queueResearchObservation({ worktree: f.checker.worktree, finding: { - summary: 'The proposed construction argument uses the wrong function argument.', - checkOutcome: { checkId: record.id, conclusion: 'refuted', - summary: 'The scoped argument fails when the differentiated function is nonconstant.', evidenceRefs: ['RESEARCH.md'] } } }); - await f.cooperation.pulse(f.checker.id); - expect(record.status).toBe('awaiting-decision'); - expect(record.outcome?.conclusion).toBe('refuted'); - const identity = { problemReceiptDigest: f.problem.receiptDigest, environmentDigest: f.state.environmentDigest }; - expect(() => prepareNextCheckDecisions(f.state.cooperation!, identity, structuredClone(f.plan), [{ - checkId: record.id, outcomeDeliveryId: record.outcome!.deliveryId, action: 'continue', reason: 'Keep trying anyway.', - }])).toThrow('math_plan_next_check_counter_evidence_required'); - expect(f.state.cooperation!.tasks.some(node => node.proof || node.integratedCheck)).toBe(false); - const file = path.join(f.directory, 'state.json'); writeSolverRunState(file, f.state); - const restored = readSolverRunState(file); - f.controller.abort(); await f.cooperation.stop(); - const resumed = cooperativeResearch({ state: restored, workers: [f.lead, f.author, f.checker], retrievalRoot: f.directory }); - cleanup.push(() => resumed.stop()); - await resumed.restore(); - expect(restored.cooperation!.nextChecks).toHaveLength(1); - expect(restored.cooperation!.nextChecks![0]).toMatchObject({ id: record.id, status: 'awaiting-decision', origin: 'definition-contract' }); - expect(restored.cooperation!.tasks.filter(node => node.nextCheckId === record.id)).toHaveLength(1); - const leadAction = await resumed.next(f.lead, { maxTurns: Infinity, remainingMs: Infinity }); - if (leadAction?.kind !== 'lead') throw new Error('missing Lead decision after restore'); - const context = buildResearchContext(f.problem, { ...restored, cooperation: resumed.contextState(leadAction, f.lead) }, - { root: f.directory, worktree: f.workspace, environment: {}, retrievalRoot: f.directory, - taskText: 'Prove the original target.', assignment: leadAction, maxOptionalContextBytes: 0 }); - expect(JSON.stringify(context)).toContain('counterEvidenceDeliveryId'); - expect(f.events).toContain('next_check_outcome'); -}); diff --git a/tests/solverDependencyScheduling.test.ts b/tests/solverDependencyScheduling.test.ts deleted file mode 100644 index 289e8928..00000000 --- a/tests/solverDependencyScheduling.test.ts +++ /dev/null @@ -1,337 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { readHumanGuidance, queueHumanGuidance, type HumanGuidanceInput } from '../src/solver/humanGuidance'; -import { runInspectionSnapshot } from '../src/solver/inspection'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { captureObligationSnapshot } from '../src/solver/obligationProgress'; -import { TIMED_EXPLORATION_MIN_REMAINING_MS } from '../src/solver/capacityExploration'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { answeredGoalPathStall, cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => 'dependency-scheduling-fixture-tools', - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -const verified = (request: MathematicsVerifierBatchRequest) => verifiedBatch(request, { sessionId: 'dependency-scheduling-fixture' }); -type TaskAction = Extract; - -describe('critical-dependency scheduling during host work', () => { - let directory: string, problem: SolverProblem, state: SolverRunState; - let lead: ResearchWorker, first: ResearchWorker, second: ResearchWorker, engineer: ResearchWorker; - let cooperative: CooperativeResearch, controller: AbortController, action: TaskAction, modelAllowed: boolean; - let pending: Promise[], releases: (() => void)[]; - let events: { event: string; details?: Record }[]; - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - const record = (worker: ResearchWorker) => state.workers!.find(item => item.id === worker.id)!; - const refresh = () => (cooperative as any).changed(); - const overlays = () => state.cooperation!.tasks.filter(item => item.capacityExploration); - const track = (promise: Promise) => { pending.push(promise); void promise.catch(() => {}); return promise; }; - const flush = () => new Promise(resolve => setImmediate(resolve)); - const waitFor = async (worker: ResearchWorker, limits = budget) => { - let settled = false; - const waiting = track(cooperative.next(worker, limits)); - void waiting.then(() => { settled = true; }, () => { settled = true; }); - await flush(); expect(settled).toBe(false); - return { waiting }; - }; - const activate = (worker: ResearchWorker, work: CooperativeAction) => { - expect(cooperative.started(worker, work)).toBe(true); - cooperative.activate(worker, work, async () => {}, async () => {}); - }; - const idleFor = (worker: ResearchWorker, ms = 31 * 60_000) => { - record(worker).scheduling = { status: 'idle', since: Date.now() - ms }; - }; - const unanswered = (count = 2) => { - state.cooperation!.leadDecisionBasisAt = Date.now() - 90 * 60_000; - state.cooperation!.idlePeerWake = { at: Date.now() - 5 * 60_000, workerIds: [first.id, second.id], count }; - }; - const completeExploration = async (worker: ResearchWorker, work: CooperativeAction | undefined) => { - if (work?.kind !== 'task') throw new Error('fixture_expected_exploration'); - activate(worker, work); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), '```math-result\n' + JSON.stringify({ - taskId: work.task.id, conclusion: 'inconclusive', summary: 'The proposed decomposition leaves the original goal open.', - }) + '\n```\n'); - cooperative.deactivate(worker); - await cooperative.deliver(worker, work, commitSolverSources(problem, worker.worktree)); - expect(node(work.task.id).status).toBe('completed'); - }; - const holdProof = async () => { - const entered = deferred(), blocked = deferred(); - releases.push(blocked.resolve); - host.verify.mockImplementationOnce(async request => { entered.resolve(); await blocked.promise; return verified(request); }); - const source = path.join(engineer.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(source, fs.readFileSync(source, 'utf8').replace('end Tutorial', 'lemma busy_helper : True := by trivial\nend Tutorial')); - const commit = commitSolverSources(problem, engineer.worktree); - cooperative.deactivate(engineer); - const checking = track(cooperative.deliver(engineer, action, commit)); - await entered.promise; - return { checking, release: blocked.resolve, commit }; - }; - const guide = async (id: string, overrides: Partial = {}) => { - const stateFile = path.join(directory, 'state.json'); - writeSolverRunState(stateFile, state); - return queueHumanGuidance(stateFile, { id, recipient: { kind: 'lead', id: lead.id }, - text: 'Audit helper premises and explicitly connect each prerequisite to its consumer through a versioned plan.', - observationRef: { sequence: 1, stateDigest: runInspectionSnapshot(state).stateDigest }, ...overrides }); - }; - const guidance = () => readHumanGuidance(path.join(directory, 'state.json'), state.runId); - const unchangedLeadInputs = () => { - state.cooperation!.lastLeadInputDigest = (cooperative as any).planningInputDigest(); - state.cooperation!.lastLeadPauseInputDigest = (cooperative as any).leadPauseInputDigest(); - answeredGoalPathStall(state); - }; - - beforeEach(() => { - const example = localExample('solver-dependency-scheduling-', 'lead'); - ({ directory, problem } = example); - lead = leadWorker(problem, example.workspace); - first = peerWorker(example, 'researcher-1'); second = peerWorker(example, 'researcher-2'); - engineer = peerWorker(example, 'engineer', { role: 'engineer' }); - const workers = [lead, first, second, engineer]; - const plan = parseCooperationPlan(problem, { tasks: [ - { id: 'busy_helper', kind: 'lemma', ownerId: engineer.id, objective: 'Prove the exact original-goal prerequisite.', - proofPath: 'Submission.lean', theoremName: 'Tutorial.busy_helper', type: 'True' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', ownerId: engineer.id, - objective: `Prove ${target.theoremName}.`, theoremName: target.theoremName, - proofPath: target.proofPath, dependsOn: ['busy_helper'] })), - ], groups: [{ id: 'main', objective: 'Close the frozen original goals.', engineerId: engineer.id, maxConcurrent: 3 }] }); - state = solverState(problem, example.workspace, { runId: 'dependency-scheduling-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const envFile = path.join(directory, 'math.env'); fs.writeFileSync(envFile, ''); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - controller = new AbortController(); pending = []; releases = []; events = []; modelAllowed = true; - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, continuousResearch: true, - signal: controller.signal, access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory }])), - modelDispatchAllowed: () => modelAllowed, emit: (event, details) => events.push({ event, details }), - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, closeTask: undefined } } }); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - state.cooperation!.planEdited = true; (cooperative as any).syncPlanNotes(); - const busy = node('busy_helper'); - busy.assignment = { taskId: busy.task.id, taskDigest: taskVersion(busy.task), workerId: engineer.id, - seedCommit: problem.baseCommit, assignmentId: 'long-running-original-dependency' }; - Object.assign(busy, { status: 'running' }); - action = { kind: 'task', task: busy.task, assignment: busy.assignment }; - activate(engineer, action); - }); - afterEach(async () => { - releases.forEach(release => release()); controller.abort(); - await Promise.allSettled(pending); await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each([Infinity, 2 * 60 * 60_000])('supplies the two narrow methods to four workers with %s ms remaining without changing the mathematical plan', async remainingMs => { - const snapshot = captureObligationSnapshot(state.cooperation!.tasks, { groups: state.cooperation!.groups, - environmentDigest: state.environmentDigest }), version = state.cooperation!.planVersion; - idleFor(first); idleFor(second); unanswered(); - const decomposition = await cooperative.next(first, { ...budget, remainingMs }); - if (decomposition?.kind !== 'task') throw new Error('fixture_expected_exploration'); - activate(first, decomposition); - const construction = await cooperative.next(second, { ...budget, remainingMs }); - if (construction?.kind !== 'task') throw new Error('fixture_expected_exploration'); - expect(node(decomposition.task.id).capacityExploration).toMatchObject({ focus: 'decomposition', targetTaskId: 'busy_helper' }); - expect(node(construction.task.id).capacityExploration).toMatchObject({ focus: 'construction', targetTaskId: 'busy_helper' }); - expect(events.filter(item => item.event === 'capacity_exploration_requested').map(item => item.details?.gate)) - .toEqual(['timed-idle', 'timed-idle']); - expect(state.cooperation!.planVersion).toBe(version); - expect(captureObligationSnapshot(state.cooperation!.tasks, { groups: state.cooperation!.groups, - environmentDigest: state.environmentDigest })).toEqual(snapshot); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('preserves the wait interval and durable per-input method tombstones under an infinite deadline', async () => { - idleFor(first); unanswered(); - const decomposition = await cooperative.next(first, budget); - await completeExploration(first, decomposition); - const { waiting } = await waitFor(first); - expect(overlays()).toHaveLength(1); - idleFor(first); unanswered(); refresh(); - const construction = await waiting; - await completeExploration(first, construction); - idleFor(first); unanswered(); await waitFor(first); - expect(overlays().map(item => item.capacityExploration!.focus)).toEqual(['decomposition', 'construction']); - expect(state.cooperation!.capacityExplorationInputs).toHaveLength(2); - }); - - it.each([ - { name: 'less than thirty minutes idle', idle: 29 * 60_000 }, - { name: 'only one unanswered wake', wakes: 1 }, - { name: 'a finite turn budget', maxTurns: 50 }, - { name: 'less than the minimum solving time remaining', remainingMs: TIMED_EXPLORATION_MIN_REMAINING_MS - 1 }, - ])('keeps the narrow gate with $name', async scenario => { - idleFor(first, scenario.idle ?? 31 * 60_000); unanswered(scenario.wakes ?? 2); - await waitFor(first, { maxTurns: scenario.maxTurns ?? Infinity, remainingMs: scenario.remainingMs ?? Infinity }); - expect(overlays()).toHaveLength(0); expect(state.cooperation!.capacityExplorationInputs).toBeUndefined(); - }); - - it.each(['a deciding Lead after the wakes', 'a running Lead'] as const) - ('supplies advisory work to the same continuously idle peer alongside %s', async scenario => { - idleFor(first); unanswered(); - const version = state.cooperation!.planVersion, - snapshot = captureObligationSnapshot(state.cooperation!.tasks, { groups: state.cooperation!.groups, - environmentDigest: state.environmentDigest }); - let leadAction: CooperativeAction | undefined; - if (scenario === 'a deciding Lead after the wakes') state.cooperation!.leadDecisionBasisAt = Date.now() - 60_000; - else { - leadAction = (cooperative as any).leadDecision(lead, problem.baseCommit, (cooperative as any).planningInputDigest()); - activate(lead, leadAction!); - } - const exploration = await cooperative.next(first, budget); - if (exploration?.kind !== 'task') throw new Error('fixture_expected_exploration'); - expect(node(exploration.task.id).capacityExploration).toMatchObject({ focus: 'decomposition', targetTaskId: 'busy_helper' }); - expect(events.filter(item => item.event === 'capacity_exploration_requested')).toEqual([ - expect.objectContaining({ details: expect.objectContaining({ gate: 'timed-idle', evidenceStatus: 'advisory' }) }), - ]); - expect(state.cooperation!.planVersion).toBe(version); - expect(captureObligationSnapshot(state.cooperation!.tasks, { groups: state.cooperation!.groups, - environmentDigest: state.environmentDigest })).toEqual(snapshot); - if (leadAction) expect(cooperative.current(leadAction)).toBe(true); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('keeps a frozen host proof busy and goal-active, wakes the idle Lead, and releases occupancy on completion', async () => { - const { checking, release, commit } = await holdProof(); - expect(record(engineer).scheduling).toMatchObject({ status: 'working', action: 'task', taskId: 'busy_helper' }); - expect(state.cooperation!.goalProgress!.goals.every(goal => goal.active)).toBe(true); - expect(state.cooperation!.groups![0].busy).toBe(1); - const agents = JSON.parse(fs.readFileSync(path.join(lead.worktree, 'COOPERATION.json'), 'utf8')).agents; - expect(agents.find((agent: { id: string }) => agent.id === engineer.id)).toMatchObject({ status: 'working', work: { taskId: 'busy_helper' } }); - // An overlapping intake of the same frozen proof shares the original check. - const duplicate = track(cooperative.deliver(engineer, action, commit)); - idleFor(first); idleFor(second); idleFor(lead, 20 * 60_000); - for (const worker of [first, second]) record(worker).scheduling!.wait = { - stage: 'm3-no-ready', observedAt: Date.now() - 31 * 60_000, candidates: [], candidateCount: 0, omittedCandidates: 0 }; - state.cooperation!.leadDecisionBasisAt = Date.now() - 90 * 60_000; - unchangedLeadInputs(); - const decision = await cooperative.next(lead, budget); - expect(decision?.kind).toBe('lead'); - expect(events.find(item => item.event === 'lead_woken_for_idle_peers')?.details?.workerIds).toEqual([first.id, second.id]); - expect(host.verify).toHaveBeenCalledOnce(); - release(); await checking; await duplicate; - expect(node('busy_helper').status).toBe('integrated'); - expect(record(engineer).scheduling).toMatchObject({ status: 'idle' }); - expect(state.cooperation!.groups![0].busy).toBe(0); - expect(state.cooperation!.goalProgress!.goals.every(goal => !goal.active)).toBe(true); - }); - - it('does not issue exploration to a host checker, and keeps stale work occupied without counting goal effort', async () => { - const { checking, release } = await holdProof(); - idleFor(engineer); unanswered(); - expect(await (cooperative as any).requestCapacityExploration(engineer, budget, [])).toBe(false); - expect(overlays()).toHaveLength(0); - node('busy_helper').task = { ...node('busy_helper').task, revision: 1 }; - refresh(); - expect(cooperative.current(action)).toBe(false); - expect(record(engineer).scheduling).toMatchObject({ status: 'working', taskId: 'busy_helper' }); - expect(state.cooperation!.goalProgress!.goals.every(goal => !goal.active)).toBe(true); - release(); await checking; - expect(node('busy_helper').proof).toBeUndefined(); - expect(record(engineer).scheduling?.status).toBe('idle'); - }); - - it('holds the worker and group slot while a checked proof awaits canonical integration', async () => { - const entered = deferred(), blocked = deferred(); releases.push(blocked.resolve); - const integrate = (cooperative as any).integrateNow.bind(cooperative); - vi.spyOn(cooperative as any, 'integrateNow').mockImplementation(async (...args: unknown[]) => { - entered.resolve(); await blocked.promise; return integrate(...args); - }); - const { checking, release } = await holdProof(); - release(); await entered.promise; - expect(node('busy_helper').status).toBe('delivered'); - expect(record(engineer).scheduling).toMatchObject({ status: 'working', taskId: 'busy_helper' }); - expect(state.cooperation!.groups![0].busy).toBe(1); - expect(state.cooperation!.goalProgress!.goals.every(goal => goal.active)).toBe(true); - blocked.resolve(); await checking; - expect(record(engineer).scheduling?.status).toBe('idle'); - expect(state.cooperation!.groups![0].busy).toBe(0); - }); - - it('drains the existing host publication promises on stop and disables the goal clock', async () => { - const { checking, release } = await holdProof(); - let stopped = false; - const stopping = track(cooperative.stop().then(() => { stopped = true; })); - await flush(); expect(stopped).toBe(false); - expect(state.cooperation!.goalProgress!.goals.every(goal => !goal.active)).toBe(true); - release(); await checking; await stopping; - expect(stopped).toBe(true); expect(record(engineer).scheduling?.status).toBe('idle'); - }); - - it('wakes a waiting ordinary Lead for guidance despite unchanged rejected input, then delivers once', async () => { - unchangedLeadInputs(); - state.cooperation!.planRejection = { inputDigest: (cooperative as any).planningInputDigest(), - proposalDigest: (cooperative as any).proposedPlanDigest(), stalled: true } as any; - const { waiting } = await waitFor(lead); - await guide('repair-dependencies'); await cooperative.pulse(lead.id); - const decision = await waiting; - expect(decision?.kind).toBe('lead'); - expect(guidance()[0].status).toBe('deferred'); - const notify = vi.fn(async () => {}); - expect(cooperative.started(lead, decision!)).toBe(true); - cooperative.activate(lead, decision!, async () => {}, notify); - await cooperative.pulse(lead.id); await cooperative.pulse(lead.id); - expect(notify).toHaveBeenCalledOnce(); - expect(notify.mock.calls[0]).toEqual([expect.stringContaining('repair-dependencies'), { requireTurn: true }]); - expect(guidance()[0]).toMatchObject({ status: 'delivered', deliveredTo: [lead.id] }); - expect(state.cooperation!.tasks.map(item => item.task.id)).toEqual(['busy_helper', ...problem.targets.map((_, index) => `goal_${index}`)]); - }); - - it('finds a previously deferred Lead note without another record-status transition', async () => { - await guide('restored-guidance'); await cooperative.pulse(lead.id); - expect(guidance()[0].status).toBe('deferred'); - unchangedLeadInputs(); - const decision = await cooperative.next(lead, budget); - expect(decision?.kind).toBe('lead'); - }); - - it.each(['time', 'turns', 'model', 'review', 'statement-review', 'synchronization'] as const)('does not let ordinary guidance bypass the %s gate', async gate => { - unchangedLeadInputs(); await guide(`gate-${gate}`); - if (gate === 'turns') state.turns = 1; - if (gate === 'model') modelAllowed = false; - if (gate === 'review') state.cooperation!.review = { status: 'pending', commit: problem.baseCommit, sourceDigest: 'fixture' } as any; - if (gate === 'statement-review') vi.spyOn(cooperative as any, 'pendingFixedStatementReviews').mockReturnValue(true); - if (gate === 'synchronization') vi.spyOn(cooperative as any, 'synchronizationPending').mockReturnValue(true); - await waitFor(lead, { maxTurns: gate === 'turns' ? 1 : Infinity, remainingMs: gate === 'time' ? 0 : Infinity }); - expect(guidance()[0].status).toBe('queued'); - }); - - it('retains the approval revision protocol and keeps peers gated after a Lead note', async () => { - state.planApproval = true; refresh(); await guide('approval-revision'); - const decision = await cooperative.next(lead, budget); - expect(decision?.kind).toBe('lead'); - expect(state.cooperation!.planApproval?.guidanceIds).toEqual(['approval-revision']); - activate(lead, decision!); - await cooperative.pulse(lead.id); await cooperative.pulse(lead.id); - await waitFor(first); - expect(guidance()[0]).toMatchObject({ status: 'delivered', deliveredTo: [lead.id] }); - expect(cooperative.current(decision!)).toBe(true); - expect(record(first).scheduling?.wait?.stage).toBe('plan-approval'); - expect(events.filter(item => item.event === 'plan_approval_revision')).toHaveLength(1); - }); - - it('keeps task-scoped Lead notes deferred instead of reopening an unrelated plan turn', async () => { - unchangedLeadInputs(); - await guide('task-scoped', { taskRef: { id: 'busy_helper', version: taskVersion(node('busy_helper').task) } }); - await cooperative.pulse(lead.id); await waitFor(lead); - expect(guidance()[0].status).toBe('deferred'); - expect(host.verify).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/solverDispatch.test.ts b/tests/solverDispatch.test.ts deleted file mode 100644 index 2b5a6eb1..00000000 --- a/tests/solverDispatch.test.ts +++ /dev/null @@ -1,115 +0,0 @@ -import fs from 'node:fs'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { parseCooperationPlan } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -describe.each(['lead', 'peer'] as const)('%s dispatch wakeups', role => { - let directory: string, state: SolverRunState, lead: ResearchWorker, peer: ResearchWorker; - let cooperative: CooperativeResearch, controller: AbortController; - const budget = { maxTurns: 1, remainingMs: Infinity }; - const worker = () => role === 'peer' ? peer : lead; - - beforeEach(() => { - const example = localExample('solver-dispatch-', 'lead'), { workspace, problem } = example; - directory = example.directory; - lead = leadWorker(problem, workspace); - peer = peerWorker(example, 'peer'); - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, proofPath: target.proofPath, - theoremName: target.theoremName, status: 'paused' })), - { id: 'investigation', kind: 'research', objective: 'Investigate a concrete route.', ownerId: peer.id }, - ] }); - state = solverState(problem, workspace, { runId: 'dispatch-fixture', phase: 'running', turns: 1, - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture', cooperation: { canonicalCommit: problem.baseCommit, error: 'Reassess the saved mathematical input.', - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - controller = new AbortController(); - const unexpectedModel = () => { throw new Error('fixture_models_forbidden'); }; - cooperative = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: directory, signal: controller.signal, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: unexpectedModel } } }); - }); - afterEach(async () => { - await cooperative.stop(); - vi.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('rechecks a same-microtask turn refund without charging the assignment', async () => { - cooperative.reserveTurn(peer); - const next = cooperative.next(worker(), budget); - queueMicrotask(() => { - state.turns--; - cooperative.settleTurn(peer); - }); - const action = await next; - expect(action?.kind).toBe(role === 'peer' ? 'task' : 'lead'); - expect(state.turns).toBe(0); - expect(state.cooperation!.groups!.every(group => group.turns === 0)).toBe(true); - expect(state.cooperation!.tasks.every(node => node.attempts === 0)).toBe(true); - expect(cooperative.started(worker(), action!)).toBe(true); - expect(state.cooperation!.groups![0].turns).toBe(role === 'peer' ? 1 : 0); - }); - - it('stops waiting when an outstanding reservation becomes charged', async () => { - cooperative.reserveTurn(peer); - const next = cooperative.next(worker(), budget); - queueMicrotask(() => cooperative.settleTurn(peer)); - await expect(next).resolves.toBeUndefined(); - expect(state.turns).toBe(1); - expect(state.cooperation!.tasks.every(node => node.status === 'pending')).toBe(true); - }); - - it('propagates cancellation while awaiting a possible refund', async () => { - cooperative.reserveTurn(peer); - const next = cooperative.next(worker(), budget); - queueMicrotask(() => controller.abort(new Error('fixture_dispatch_aborted'))); - await expect(next).rejects.toThrow('fixture_dispatch_aborted'); - expect(state.cooperation!.tasks.every(node => node.status === 'pending')).toBe(true); - }); - - it.each(['stopping', 'worker-stopped', 'lead-stopped'] as const)( - 'declines a selected action after %s before model admission', async change => { - state.turns = 0; - const next = cooperative.next(worker(), budget); - const changed = Promise.resolve().then(async () => { - if (change === 'stopping') await cooperative.stop(); - else cooperative.stopped(change === 'worker-stopped' ? worker() : lead); - }); - const action = await next; - await changed; - expect(action).toBeDefined(); - expect(cooperative.started(worker(), action!)).toBe(false); - expect(state.cooperation!.groups!.every(group => group.turns === 0)).toBe(true); - expect(state.cooperation!.tasks.every(node => node.attempts === 0)).toBe(true); - }); - - if (role !== 'peer') it.each(['canonical-changed', 'not-ready', 'synchronizing', 'lead-stopped', 'stopping'] as const)( - 'invalidates a queued assembly after %s', async change => { - const archive = state.cooperation!; - for (const node of archive.tasks) if (node.task.kind === 'goal') node.status = 'integrated'; - archive.review = { commit: archive.canonicalCommit!, sourceDigest: 'fixture-source', status: 'accepted' }; - const action = await cooperative.next(lead, budget); - expect(action?.kind).toBe('assemble'); - expect(cooperative.current(action!)).toBe(true); - const canonical = archive.canonicalCommit; - const goal = archive.tasks.find(node => node.task.kind === 'goal')!; - if (change === 'canonical-changed') archive.canonicalCommit = 'a'.repeat(40); - else if (change === 'not-ready') { - archive.review = undefined; - goal.status = 'pending'; - } else if (change === 'synchronizing') goal.pendingValidation = { - id: 'fixture-validation', taskDigest: 'fixture-task', canonicalCommit: canonical!, - environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, - }; - else if (change === 'lead-stopped') cooperative.stopped(lead); - else await cooperative.stop(); - try { expect(cooperative.current(action!)).toBe(false); } - finally { archive.canonicalCommit = canonical; } - }); -}); diff --git a/tests/solverDispatchWait.test.ts b/tests/solverDispatchWait.test.ts deleted file mode 100644 index 5e04fdc2..00000000 --- a/tests/solverDispatchWait.test.ts +++ /dev/null @@ -1,229 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { taskVersion } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -describe('recorded dispatch waits', () => { - const budget = { maxTurns: 10, remainingMs: 60_000 }; - let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; - let controller: AbortController, modules: SolverModules, emit: ReturnType, pending: Promise[]; - const node = (id = 'helper') => state.cooperation!.tasks.find(item => item.task.id === id)!; - const wait = (worker = workers[2]) => state.workers!.find(item => item.id === worker.id)!.scheduling?.wait; - const track = (promise: Promise) => { pending.push(promise); void promise.catch(() => {}); return promise; }; - const tick = () => new Promise(resolve => setImmediate(resolve)); - const events = (name: string) => emit.mock.calls.filter(([event]) => event === name).map(([, details]) => details); - const refresh = () => (cooperative as any).changed(); - - beforeEach(() => { - const example = localExample('solver-dispatch-wait-', 'lead'); - directory = example.directory; - workers = [leadWorker(example.problem, example.workspace, 'lead'), - ...['busy', 'idle', 'observer'].map(id => peerWorker(example, id))]; - const plan = parseCooperationPlan(example.problem, { tasks: [ - { id: 'helper', kind: 'lemma', ownerId: 'busy', objective: 'Prove an independently useful helper.', - theoremName: 'Tutorial.helper', type: 'True', proofPath: 'Submission.lean' }, - { id: 'ongoing', kind: 'research', ownerId: 'busy', objective: 'Investigate a separate construction.' }, - ...example.problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: 'Original target', theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ] }); - state = solverState(example.problem, example.workspace, { runId: 'dispatch-wait-fixture', phase: 'running', - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - node('ongoing').status = 'running'; - node('ongoing').assignment = { taskId: 'ongoing', taskDigest: taskVersion(node('ongoing').task), workerId: 'busy', - seedCommit: example.problem.baseCommit, assignmentId: 'ongoing-assignment' }; - pending = []; controller = new AbortController(); emit = vi.fn(); - modules = { ...directSolverModules, M1: { ...directSolverModules.M1, - open: vi.fn(() => { throw new Error('fixture_real_models_forbidden'); }) }, M5: { ...directSolverModules.M5 } }; - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, emit, modules }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ current: () => true, - result: { status: 'elaborated', inputDigest: 'fixture-input', taskDigest: taskVersion(input.task), - reason: 'fixture type elaboration', evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } })); - }); - afterEach(async () => { - controller.abort(); - await Promise.allSettled(pending); - await cooperative.stop(); - expect(modules.M1.open).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('records owner congestion once, then dispatches after an explicit complete plan makes the helper shared', async () => { - const busyAssignment = node('ongoing').assignment, version = taskVersion(node().task); - const next = track(cooperative.next(workers[2], budget)); - await tick(); - const observed = wait(); - expect(observed).toMatchObject({ stage: 'm5-no-selection', candidateCount: 1, omittedCandidates: 0, - candidates: [{ taskId: 'helper', taskDigest: version, reason: 'owner' }] }); - for (let index = 0; index < 3; index++) { refresh(); await tick(); } - expect(wait()).toBe(observed); expect(events('dispatch_wait')).toHaveLength(1); - - const archive = state.cooperation!; - await (cooperative as any).acceptPlan(parseCooperationPlan(state.problem, { - tasks: archive.tasks.map(item => item.task.id === 'helper' ? { ...item.task, ownerId: undefined } : item.task), - groups: archive.groups!.map(item => item.group), - })); - expect(await next).toMatchObject({ kind: 'task', task: { id: 'helper' }, assignment: { workerId: 'idle' } }); - expect(taskVersion(node().task)).toBe(version); - expect(node('ongoing').assignment).toBe(busyAssignment); - expect(wait()).toBeUndefined(); - expect(events('dispatch_wait_ended')).toContainEqual(expect.objectContaining({ workerId: 'idle', - observedAt: observed!.observedAt, reason: 'selected' })); - expect(node().proof).toBeUndefined(); expect(node().attempts).toBe(0); - }); - - it('records actual unavailable dependency inputs when M3 has no ready tasks', async () => { - const helper = node(); - helper.task = { ...helper.task, ownerId: 'idle', dependsOn: ['ongoing'] }; - const next = track(cooperative.next(workers[2], budget)); - await vi.waitFor(() => expect(wait()).toMatchObject({ stage: 'dependency-blocked', candidateCount: 1, - candidates: [{ taskId: 'helper', taskDigest: taskVersion(helper.task), reason: 'dependency' }] })); - expect(helper.assignment).toBeUndefined(); - controller.abort(); await Promise.allSettled([next]); - }); - - it('waits on concrete live producers and resumes an unresolved episode immediately when they stop without delivery', async () => { - const helper = node(), producer = node('ongoing'); - helper.task = { ...helper.task, ownerId: 'idle', dependsOn: ['ongoing'] }; - const action = { kind: 'task', task: producer.task, assignment: producer.assignment! } as const; - const active = (cooperative as any).active as Map; - active.set('busy', { action, interrupt: async () => {}, notify: async () => {} }); refresh(); - track(cooperative.next(workers[2], budget)); - await vi.waitFor(() => expect(wait()).toMatchObject({ stage: 'dependency-running', - candidates: [{ taskId: 'ongoing', taskDigest: taskVersion(producer.task), reason: 'dependency' }] })); - const scheduling = state.workers!.find(worker => worker.id === 'idle')!.scheduling!; - const since = scheduling.since; - active.delete('busy'); producer.status = 'pending'; refresh(); - await vi.waitFor(() => expect(wait()?.stage).toBe('dependency-blocked')); - expect(state.workers!.find(worker => worker.id === 'idle')!.scheduling!.since).toBe(since); - }); - - it('does not treat a saved old assignment as live while its worker checks a different task', async () => { - const helper = node(), producer = node('ongoing'); - const old = { ...helper, task: { ...helper.task, id: 'old', ownerId: 'busy' }, status: 'blocked' as const, - assignment: { taskId: 'old', workerId: 'busy', taskDigest: '', seedCommit: state.problem.baseCommit } }; - old.assignment.taskDigest = taskVersion(old.task); - state.cooperation!.tasks.push(old); - helper.task = { ...helper.task, ownerId: 'idle', dependsOn: ['old'] }; - const action = { kind: 'task', task: producer.task, assignment: producer.assignment! } as const; - (cooperative as any).active.set('busy', { action, interrupt: async () => {}, notify: async () => {} }); - (cooperative as any).deliveryChecks.set('busy', Promise.resolve()); refresh(); - track(cooperative.next(workers[2], budget)); - await vi.waitFor(() => expect(wait()?.stage).toBe('dependency-blocked')); - expect(wait()?.candidates).toEqual([{ taskId: 'helper', taskDigest: taskVersion(helper.task), reason: 'dependency' }]); - (cooperative as any).deliveryChecks.delete('busy'); - }); - - it('retains a saved assignment when ownerId is removed and records its actual reservation', async () => { - const helper = node(); helper.task = { ...helper.task, ownerId: undefined }; - helper.assignment = { taskId: helper.task.id, taskDigest: taskVersion(helper.task), workerId: 'busy', - seedCommit: state.problem.baseCommit, assignmentId: 'saved-draft' }; - const assignment = helper.assignment; - track(cooperative.next(workers[2], budget)); await tick(); - expect(wait()?.candidates).toEqual([{ taskId: helper.task.id, taskDigest: taskVersion(helper.task), reason: 'saved-assignment' }]); - expect(helper.assignment).toBe(assignment); expect(helper.status).toBe('pending'); - }); - - it('records an explicit route pause without inventing a dependency or an unanswered planning demand', async () => { - node().task = { ...node().task, status: 'paused' }; - track(cooperative.next(workers[2], budget)); await tick(); - expect(wait()).toMatchObject({ stage: 'route-paused', candidateCount: 0, candidates: [], omittedCandidates: 0 }); - expect(node().assignment).toBeUndefined(); - }); - - it('records an unknown policy exclusion when a custom M5 declines otherwise eligible work', async () => { - node().task = { ...node().task, ownerId: undefined }; - modules.M5.assign = vi.fn(() => undefined); - track(cooperative.next(workers[2], budget)); await tick(); - expect(wait()).toMatchObject({ stage: 'm5-no-selection', candidates: [{ taskId: 'helper', reason: 'policy-no-selection' }] }); - expect(modules.M5.assign).toHaveBeenCalledOnce(); - expect(node().assignment).toBeUndefined(); - }); - - it('rejects a custom M5 that ignores ownership instead of treating its suggestion as dispatch authority', async () => { - modules.M5.assign = vi.fn(() => node()); - await expect(cooperative.next(workers[2], budget)).rejects.toThrow('math_task_assignment_invalid'); - expect(node().assignment).toBeUndefined(); expect(events('task_assigned')).toHaveLength(0); - }); - - it('rechecks ownership before opening a task turn even when its mathematical digest is unchanged', async () => { - const helper = node(); helper.task = { ...helper.task, ownerId: undefined }; - const action = await cooperative.next(workers[2], budget); - expect(action?.kind).toBe('task'); - const version = taskVersion(helper.task); - helper.task = { ...helper.task, ownerId: 'busy' }; - expect(taskVersion(helper.task)).toBe(version); - expect(cooperative.started(workers[2], action!)).toBe(false); - expect(helper.attempts).toBe(0); expect(state.cooperation!.groups![0].turns).toBe(0); - helper.task = { ...helper.task, ownerId: undefined }; - expect(cooperative.started(workers[2], action!)).toBe(true); - expect(helper.attempts).toBe(1); - }); - - it('explains host preparation while another eligible worker waits and prevents a duplicate claim', async () => { - node().task = { ...node().task, ownerId: undefined }; - let finish!: () => void; - vi.mocked(TaskTypePreflightCache.prototype.check).mockImplementation(input => new Promise(resolve => { - finish = () => resolve({ current: () => true, result: { status: 'elaborated', inputDigest: 'held-input', - taskDigest: taskVersion(input.task), reason: 'fixture type elaboration', - evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } }); - })); - const preparing = track(cooperative.next(workers[2], budget)); - track(cooperative.next(workers[3], budget)); await tick(); - expect(wait(workers[3])).toMatchObject({ stage: 'host-filtered', candidates: [{ taskId: 'helper', reason: 'preparing-type' }] }); - expect(node().assignment).toBeUndefined(); - finish(); expect(await preparing).toMatchObject({ kind: 'task', assignment: { workerId: 'idle' } }); - await tick(); - expect(wait(workers[3])?.stage).toBe('m3-no-ready'); - expect(events('task_assigned').filter(event => event.taskId === 'helper')).toHaveLength(1); - }); - - it.each(['time-limit', 'model-disabled', 'turn-limit'] as const)('records %s without changing terminal budget behavior', async gate => { - const dispatchBudget = { ...budget, ...(gate === 'time-limit' ? { remainingMs: 0 } : {}), - ...(gate === 'turn-limit' ? { maxTurns: 0 } : {}) }; - (cooperative as any).input.modelDispatchAllowed = () => gate !== 'model-disabled'; - expect(await cooperative.next(workers[2], dispatchBudget)).toBeUndefined(); - expect(wait()).toMatchObject({ stage: 'budget-gated', gate, candidateCount: 0 }); - cooperative.stopped(workers[2]); - expect(wait()).toMatchObject({ stage: 'budget-gated', gate, endedAt: expect.any(Number) }); - cooperative.stopped(workers[2]); await cooperative.stop(); - expect(events('dispatch_wait_ended')).toEqual([expect.objectContaining({ workerId: 'idle', reason: 'stopped' })]); - }); - - it('records Lead unavailability without dispatching a peer turn', async () => { - cooperative.stopped(workers[0], 'fixture Lead unavailable'); - expect(await cooperative.next(workers[2], budget)).toBeUndefined(); - expect(wait()).toMatchObject({ stage: 'lead-unavailable', candidateCount: 0 }); - expect(events('task_assigned')).toHaveLength(0); - }); - - it('bounds observations and preserves omitted counts in archives and scoped worker views', async () => { - const helper = node(); - state.cooperation!.tasks.push(...Array.from({ length: 18 }, (_, index) => ({ - task: { ...helper.task, id: `hidden_${index}`, theoremName: `Tutorial.hidden_${index}`, - objective: `Private helper ${index}`, groupId: 'private', sharing: 'group' as const }, - status: 'pending' as const, attempts: 0, - }))); - state.cooperation!.groups!.push({ group: { id: 'private', objective: 'Private route', status: 'active', revision: 0 }, turns: 0 }); - state.workers!.find(worker => worker.id === 'observer')!.sessionTaskId = helper.task.id; - track(cooperative.next(workers[2], budget)); await tick(); - expect(wait()).toMatchObject({ candidateCount: 19, omittedCandidates: 3 }); - expect(wait()!.candidates).toHaveLength(16); - const view = JSON.parse(fs.readFileSync(path.join(workers[3].worktree, 'COOPERATION.json'), 'utf8')); - const scoped = view.dispatchWaits.find((record: { workerId: string }) => record.workerId === 'idle'); - expect(scoped.candidates.map((candidate: { taskId: string }) => candidate.taskId)).toEqual(['helper']); - expect(scoped).toMatchObject({ candidateCount: 19, omittedCandidates: 18 }); - expect(JSON.stringify(scoped)).not.toContain('hidden_'); - const leadView = JSON.parse(fs.readFileSync(path.join(workers[0].worktree, 'COOPERATION.json'), 'utf8')); - expect(leadView.dispatchWaits[0].candidates).toHaveLength(16); - }); -}); diff --git a/tests/solverFamilyAssembly.test.ts b/tests/solverFamilyAssembly.test.ts deleted file mode 100644 index 105d9a61..00000000 --- a/tests/solverFamilyAssembly.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_STATEMENT } from '../src/math/localExample'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources } from '../src/solver/problem'; -import type { SolverRunState } from '../src/solver/archive'; -import { familyAssemblyProof, familyType } from '../src/solver/taskFamilies'; -import { taskVersion } from '../src/solver/tasks'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { conditionalExpectedType } from '../src/solver/conditionalProjection'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), model: vi.fn(), lean: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'family-fixture-tools', -})); -vi.mock('../src/math/mathProofEnvironment', async importOriginal => ({ - ...await importOriginal(), resolveMathProofEnvironment: () => undefined, -})); -vi.mock('../src/math/leanTypeDiagnostics', async importOriginal => ({ - ...await importOriginal(), checkLeanType: host.lean, -})); - -describe('host family assembly before model dispatch', () => { - let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; - let controller: AbortController, emit: ReturnType; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const family = { lo: 0, hi: 7, chunk: 3, predicate: 'Tutorial.Good' }; - const memberIds = ['table_c0', 'table_c1', 'table_c2']; - const node = (id = 'table') => state.cooperation!.tasks.find(item => item.task.id === id)!; - const next = () => cooperative.next(workers[1], budget); - const verified = (request: MathematicsVerifierBatchRequest) => verifiedBatch(request, { sessionId: 'family-fixture', checks: true }); - const events = () => emit.mock.calls.filter(call => call[0] === 'task_family_assembly').map(call => call[1]); - const canonical = () => committedSource(workers[0].worktree, state.cooperation!.canonicalCommit!, - `${state.problem.projectRelative}/Submission.lean`); - const preflight = () => vi.mocked(TaskTypePreflightCache.prototype.check); - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.model.mockReset().mockImplementation(() => { throw new Error('fixture_models_forbidden'); }); - // The battery must not close anything here: a closed member or family would hide the assembly path. - host.lean.mockReset().mockImplementation(async () => ({ status: 'failed', timedOut: false, - artifact: { path: '.lake/type-diagnostics/fixture/manifest.json', digest: 'b'.repeat(64) } })); - const example = localExample('solver-family-assembly-'), { workspace, problem } = example; - directory = example.directory; - workers = [leadWorker(problem, workspace), peerWorker(example, 'proof')]; - const plan = parseCooperationPlan(problem, { tasks: [ - { id: 'table', kind: 'lemma', objective: 'Check the residue table', theoremName: 'Tutorial.table', - proofPath: 'Submission.lean', family, ownerId: 'proof' }, - { id: 'followup', kind: 'research', objective: 'Observe dependency readiness', dependsOn: ['table'], ownerId: 'proof' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', objective: 'Original goal', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ], groups: [{ id: 'main', objective: 'Original problem', status: 'active', maxConcurrent: 1 }] }); - // Members wait, so the family is assembled while all of them are unproved. - const tasks = plan.tasks.map(task => task.familyMember ? { ...task, status: 'paused' as const } : task); - state = solverState(problem, workspace, { runId: 'family-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, groups: plan.groups.map(group => ({ group, turns: 0 })), - tasks: tasks.map(task => ({ task, attempts: 0, status: 'pending' })) } }); - fs.writeFileSync(path.join(workers[0].worktree, state.problem.projectRelative, 'Submission.lean'), LOCAL_EXAMPLE_STATEMENT); - state.cooperation!.canonicalCommit = commitSolverSources(state.problem, workers[0].worktree); - const envFile = path.join(directory, 'math.env'); fs.writeFileSync(envFile, ''); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - controller = new AbortController(); emit = vi.fn(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, emit, - access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory }])), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: host.model, execute: host.model } } }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ current: () => !input.signal?.aborted, - result: { taskDigest: taskVersion(input.task), inputDigest: 'fixture', evidence: 'advisory-type-elaboration', - proofAcceptance: 'not-assessed', status: 'elaborated', reason: 'fixture', context: 'Tutorial.add_zero', type: input.task.type } })); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.model).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('checks the assembled family with every unproved member bound as a hypothesis, before any model turn', async () => { - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls[0][1].expectedDeclarationType).toBe(conditionalExpectedType('Tutorial.table', - familyType(0, 7, 'Tutorial.Good'), memberIds.map((id, index) => ({ theoremName: `Tutorial.${id}`, - type: familyType(index * 3, Math.min(7, index * 3 + 3), 'Tutorial.Good') })))); - expect(node()).toMatchObject({ status: 'conditional', attempts: 0, proof: { passed: true, - conditions: memberIds.map(taskId => ({ taskId, taskDigest: taskVersion(node(taskId).task) })) } }); - expect(events()).toEqual([expect.objectContaining({ taskId: 'table', workerId: 'proof', status: 'committed', reason: 'family-assembled', - assumedInputs: memberIds, passed: true, verificationStatus: 'kernel_verified', commit: expect.any(String) })]); - expect(committedSource(workers[1].worktree, events()[0].commit, `${state.problem.projectRelative}/Submission.lean`)) - .toContain(`theorem table : ${familyType(0, 7, 'Tutorial.Good')}\n := ${familyAssemblyProof('Tutorial.table', family)}\n`); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ taskId: 'table', kind: 'proof', status: 'conditional', - summary: expect.stringContaining('binds its 3 lemma input(s) as explicit hypotheses') })); - // The type preflight of a family does not wait for its own members to exist in source. - expect(preflight().mock.calls.find(call => call[0].task.id === 'table')![0].dependencies).toEqual([]); - expect(host.lean).not.toHaveBeenCalled(); expect(state.turns).toBe(0); - expect(canonical()).toBe(LOCAL_EXAMPLE_STATEMENT); - for (const id of memberIds) expect(node(id)).toMatchObject({ status: 'pending', attempts: 0 }); - }); - - it('falls through to model work when the kernel rejects the assembly, and does not reassemble the same contract', async () => { - host.verify.mockImplementationOnce(async request => failedBatch(verified(request), - { stdoutPreview: () => 'Submission.lean:3:1: error: unknown constant' })); - const first = await next(); - expect(first).toMatchObject({ kind: 'task', task: { id: 'table' } }); - expect(events()).toEqual([expect.objectContaining({ status: 'committed', passed: false, verificationStatus: 'failed' })]); - expect(state.cooperation!.deliveries ?? []).toEqual([]); expect(node().proof).toBeUndefined(); - if (first?.kind !== 'task') throw new Error('expected_task_assignment'); - cooperative.release(workers[1], first); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'table' } }); - expect(events()).toHaveLength(1); expect(host.verify).toHaveBeenCalledOnce(); - }); - - it.each(['disabled', 'saved-assignment', 'no-context'] as const)('does not assemble for %s work', async kind => { - if (kind === 'disabled') (cooperative as any).input.modules.M2 = { ...directSolverModules.M2, assembleFamily: undefined }; - if (kind === 'saved-assignment') node().assignment = { taskId: 'table', taskDigest: taskVersion(node().task), - workerId: workers[1].id, seedCommit: state.cooperation!.canonicalCommit!, assignmentId: 'saved', - dependencies: memberIds.map(taskId => ({ taskId, taskDigest: taskVersion(node(taskId).task) })) }; - if (kind === 'no-context') preflight().mockImplementation(async input => ({ current: () => true, - result: { taskDigest: taskVersion(input.task), inputDigest: 'fixture', evidence: 'advisory-type-elaboration', - proofAcceptance: 'not-assessed', status: 'elaborated', reason: 'fixture' } })); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'table' } }); - expect(events()).toEqual([]); expect(host.verify).not.toHaveBeenCalled(); - }); - - it('leaves an unconditional family waiting for its members', async () => { - node().task = { ...node().task, conditional: false }; - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(events()).toEqual([]); expect(node()).toMatchObject({ status: 'pending', attempts: 0 }); - }); -}); diff --git a/tests/solverFinalReviewScope.test.ts b/tests/solverFinalReviewScope.test.ts deleted file mode 100644 index 6fb9b83a..00000000 --- a/tests/solverFinalReviewScope.test.ts +++ /dev/null @@ -1,304 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_PROOF } from '../src/math/localExample'; -import type { LeanDeclarationReferences } from '../src/math/leanReferences'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import { checkSolverProof, hasFreshSolverCheck, type ProofCheck } from '../src/solver/modules/evidence'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { isStatementAction, statementSnapshot, writeStatementSnapshot, type StatementReview } from '../src/solver/statementReview'; -import { taskVersion, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -describe('fixed-candidate statement review scope', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch, controller: AbortController, check: ProofCheck; - let reports: Map; - let events: { event: string; details?: Record }[]; - let pending: Promise[]; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - - const track = (promise: Promise) => { - pending.push(promise); void promise.catch(() => {}); return promise; - }; - const review = (taskId: string) => state.cooperation!.statementReviews!.find(item => item.taskId === taskId)!; - const task = (taskId: string) => state.cooperation!.tasks.find(item => item.task.id === taskId)!; - const scope = () => events.findLast(item => item.event === 'final_statement_review_scope')!.details!; - const freshCheck = async () => { - check = await checkSolverProof(problem, workspace, {}, controller.signal); - expect(hasFreshSolverCheck(check)).toBe(true); - return check; - }; - const create = () => cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }), modules: directSolverModules }); - const addReview = (node: TaskRecord) => { - const snapshot = statementSnapshot(problem, node.task, workspace, check.commit, state.environmentDigest, []); - const reviewWorkspace = path.join(directory, 'statements', node.task.id); - const value: StatementReview = { id: `review-${node.task.id}`, taskId: node.task.id, taskDigest: taskVersion(node.task), - snapshotDigest: snapshot.snapshotDigest, environmentDigest: state.environmentDigest, commit: check.commit, - leanStatement: snapshot.input.leanStatement, intendedStatement: node.task.informalStatement!, premises: [], dependencies: [], - workspace: reviewWorkspace, files: writeStatementSnapshot(reviewWorkspace, snapshot), status: 'pending' }; - (state.cooperation!.statementReviews ??= []).push(value); - }; - const completeStatement = async (expectedTaskId: string) => { - for (const kind of ['backtranslate', 'statement-review'] as const) { - const action = await cooperative.next(workers[1]!, budget); - expect(action).toMatchObject({ kind, taskId: expectedTaskId }); - if (!action || !isStatementAction(action)) throw new Error('missing_statement_assignment'); - expect(cooperative.current(action)).toBe(true); - expect(cooperative.started(workers[1]!, action)).toBe(true); - fs.writeFileSync(path.join(action.workspace, 'RESEARCH.md'), JSON.stringify({ reviewId: action.reviewId, - snapshotDigest: action.snapshotDigest, ...(kind === 'backtranslate' ? { mathematics: 'The stated proposition holds.' } : { verdict: 'accepted' }) })); - await cooperative.deliverStatement(workers[1]!, action); - } - expect(review(expectedTaskId).status).toBe('accepted'); - }; - const completeFinalReview = async () => { - const action = await cooperative.next(workers[1]!, budget); - expect(action).toMatchObject({ kind: 'review', seedCommit: check.commit }); - if (action?.kind !== 'review') throw new Error('missing_final_review'); - expect(cooperative.started(workers[1]!, action)).toBe(true); - fs.writeFileSync(path.join(workers[1]!.worktree, 'RESEARCH.md'), JSON.stringify({ commit: action.seedCommit, verdict: 'accepted' })); - await cooperative.deliver(workers[1]!, action, commitSolverSources(problem, workers[1]!.worktree)); - expect(state.cooperation!.review!.status).toBe('accepted'); - }; - - beforeEach(async () => { - events = []; pending = []; controller = new AbortController(); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest, options) => { - expect(options.collectDeclarationReferences).toBe(true); - const result = verifiedBatch(request, { sessionId: 'final-review-scope-fixture', receipt: 'scope', checks: true }); - return { ...result, results: result.results.map(receipt => ({ ...receipt, - ...(reports.get(receipt.theoremName) ? { declarationReferences: reports.get(receipt.theoremName) } : {}) })) }; - }); - const example = localExample('solver-final-review-scope-'); - ({ directory, workspace, problem } = example); - fs.writeFileSync(path.join(workspace, problem.projectRelative, 'Submission.lean'), LOCAL_EXAMPLE_PROOF.replace('theorem add_zero', - 'lemma used : True := by trivial\nlemma transitive : True := by trivial\nlemma unused : True := by trivial\ntheorem add_zero')); - const canonicalCommit = commitSolverSources(problem, workspace); - workers = [leadWorker(problem, workspace), peerWorker(example, 'reviewer', { name: 'peer', commit: canonicalCommit })]; - reports = new Map(problem.targets.map(target => [target.theoremName, { statement: [], proof: [] }])); - state = solverState(problem, workspace, { runId: 'final-review-scope-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [...['used', 'transitive', 'unused'].map(id => ({ task: { id, kind: 'lemma' as const, - objective: `Establish ${id}.`, theoremName: `Tutorial.${id}`, proofPath: 'Submission.lean', type: 'True', - dependsOn: [], revision: 0, statementReview: true, informalStatement: 'Truth holds.', status: 'paused' as const }, - status: 'pending' as const, attempts: 0 })), ...problem.targets.map((target, index) => ({ task: { - id: `goal_${index}`, kind: 'goal' as const, objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: [], revision: 0 }, - status: 'integrated' as const, attempts: 1 }))] } }); - await freshCheck(); - for (const node of state.cooperation!.tasks.filter(node => node.task.statementReview)) addReview(node); - cooperative = create(); - }); - - afterEach(async () => { - controller.abort(); - await Promise.allSettled(pending); - await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['paused', 'stopped', 'parked'] as const)('accepts the fixed proof without an unused %s alternative review', async control => { - if (control === 'parked') { task('unused').task = { ...task('unused').task, status: 'active' }; task('unused').routeParking = ['local-obstruction']; } - else task('unused').task = { ...task('unused').task, status: control }; - cooperative.requireReview(check); - expect(scope()).toMatchObject({ referenceCoverage: 'complete', requiredTaskIds: [], unusedTaskIds: ['used', 'transitive', 'unused'] }); - await completeFinalReview(); - expect(cooperative.reviewed(check)).toBe(true); - expect(state.cooperation!.statementReviews!.every(item => item.status === 'pending')).toBe(true); - }); - - it('waits for the nonauthor to be available before assigning review of the fixed proof', async () => { - const example = { directory, workspace, problem }; - const canonical = check.commit; - const author = peerWorker(example, 'engineer', { role: 'engineer', commit: canonical }); - const secondAuthor = peerWorker(example, 'prover', { role: 'prover', commit: canonical }); - workers.push(author, secondAuthor); - task('goal_0').assignment = { workerId: author.id, taskId: 'goal_0', taskDigest: taskVersion(task('goal_0').task), seedCommit: canonical }; - state.cooperation!.landedHelpers = [{ producer: secondAuthor.id, file: 'Submission.lean', qualifiedName: 'Tutorial.used', - type: 'True', commit: canonical }]; - reports.set(problem.targets[0]!.theoremName, { statement: [], proof: [{ name: 'Tutorial.used', file: 'Submission.lean' }] }); - await freshCheck(); - cooperative = create(); - const nonauthor = workers[1]!; - const occupied = { kind: 'lead' as const, seedCommit: canonical }; - cooperative.activate(nonauthor, occupied, async () => {}, async () => {}); - cooperative.requireReview(check); - track(cooperative.next(author, budget)); - track(cooperative.next(secondAuthor, budget)); - await Promise.resolve(); - expect(events.filter(event => event.event === 'review_assigned')).toEqual([]); - cooperative.deactivate(nonauthor); - await completeFinalReview(); - expect(events.find(event => event.event === 'review_assigned')?.details) - .toMatchObject({ workerId: nonauthor.id, independent: true }); - expect(state.cooperation!.review!.producerIds).toEqual([author.id, secondAuthor.id].sort()); - }); - - it('labels a fresh-session review by the only available author as non-independent', async () => { - const author = workers[1]!; - task('goal_0').assignment = { workerId: author.id, taskId: 'goal_0', taskDigest: taskVersion(task('goal_0').task), seedCommit: check.commit }; - cooperative.requireReview(check); - const action = await cooperative.next(author, budget); - expect(action).toMatchObject({ kind: 'review', independent: false }); - expect(events.find(event => event.event === 'review_assigned')?.details).toMatchObject({ workerId: author.id, independent: false }); - }); - - it.each(['paused', 'stopped', 'parked', 'group-paused', 'group-exhausted'] as const) - ('dispatches both necessary review stages for a %s helper without reopening its proof work', async control => { - reports.set(problem.targets[0]!.theoremName, { statement: [], proof: [{ name: 'Tutorial.used', file: 'Submission.lean' }] }); - await freshCheck(); - if (control === 'parked') { task('used').task = { ...task('used').task, status: 'active' }; task('used').routeParking = ['local-obstruction']; } - else if (control.startsWith('group-')) { - const group = state.cooperation!.groups![0]!; - group.group = { ...group.group, ...(control === 'group-paused' ? { status: 'paused' as const } : { maxTurns: 0 }) }; - } else task('used').task = { ...task('used').task, status: control }; - const savedTask = task('used').task, groupTurns = state.cooperation!.groups![0]!.turns; - cooperative.requireReview(check); - expect(scope()).toMatchObject({ referenceCoverage: 'complete', requiredTaskIds: ['used'] }); - await completeStatement('used'); - expect(task('used').task).toBe(savedTask); - expect(task('used').status).toBe('pending'); - expect(state.cooperation!.groups![0]!.turns).toBe(groupTurns); - await completeFinalReview(); - expect(cooperative.reviewed(check)).toBe(true); - }); - - it('requires original goals and the union of statement and transitive proof references across all targets', async () => { - task('goal_0').task = { ...task('goal_0').task, statementReview: true, informalStatement: 'Adding zero leaves a number unchanged.', status: 'paused' }; - addReview(task('goal_0')); - reports.set(problem.targets[0]!.theoremName, { statement: [{ name: 'Tutorial.used', file: 'Submission.lean' }], proof: [] }); - reports.set(problem.targets[1]!.theoremName, { statement: [], proof: [{ name: 'Tutorial.used', file: 'Submission.lean' }, - { name: 'Tutorial.transitive', file: 'Submission.lean' }] }); - await freshCheck(); cooperative.requireReview(check); - expect(scope()).toMatchObject({ referenceCoverage: 'complete', requiredTaskIds: ['used', 'transitive', 'goal_0'], unusedTaskIds: ['unused'] }); - for (const id of ['used', 'transitive', 'goal_0']) await completeStatement(id); - await completeFinalReview(); - expect(cooperative.reviewed(check)).toBe(true); - }); - - it('conservatively completes every configured review if any original target lacks reference coverage', async () => { - reports.delete(problem.targets[1]!.theoremName); - await freshCheck(); cooperative.requireReview(check); - expect(scope()).toMatchObject({ referenceCoverage: 'unknown', requiredTaskIds: ['used', 'transitive', 'unused'], unusedTaskIds: [] }); - for (const id of ['used', 'transitive', 'unused']) await completeStatement(id); - await completeFinalReview(); - expect(cooperative.reviewed(check)).toBe(true); - }); - - it.each(['serialized', 'modified'] as const)('does not let %s verification metadata narrow the required reviews', async provenance => { - const untrusted = provenance === 'serialized' ? JSON.parse(JSON.stringify(check)) as ProofCheck : check; - if (provenance === 'modified') untrusted.verification.results[0]!.declarationReferences = { - statement: [{ name: 'Tutorial.used', file: 'Submission.lean' }], proof: [] }; - expect(hasFreshSolverCheck(untrusted)).toBe(false); - cooperative.requireReview(untrusted); - state.cooperation!.review!.status = 'accepted'; - expect(scope()).toMatchObject({ referenceCoverage: 'unknown', requiredTaskIds: ['used', 'transitive', 'unused'] }); - expect(cooperative.reviewed(untrusted)).toBe(false); - }); - - it('waits for required statements before assembling after the fixed proof review was accepted', async () => { - reports.set(problem.targets[0]!.theoremName, { statement: [], proof: [{ name: 'Tutorial.used', file: 'Submission.lean' }] }); - await freshCheck(); - cooperative.requireReview(check); state.cooperation!.review!.status = 'accepted'; - let settled = false; - const nextLead = track(cooperative.next(workers[0]!, budget).then(action => { settled = true; return action; })); - await Promise.resolve(); - expect(settled).toBe(false); - await completeStatement('used'); - expect(await nextLead).toMatchObject({ kind: 'assemble', seedCommit: check.commit }); - expect(cooperative.reviewed(check)).toBe(true); - }); - - it.each([false, true])('retains only a necessary in-flight statement reviewer (used: %s)', async used => { - task('used').task = { ...task('used').task, status: 'active' }; - const action = await cooperative.next(workers[1]!, budget); - if (!action || !isStatementAction(action)) throw new Error('missing_active_statement'); - const interrupt = vi.fn(async () => {}); - cooperative.activate(workers[1]!, action, interrupt, async () => {}); - if (used) reports.set(problem.targets[0]!.theoremName, { statement: [], - proof: [{ name: 'Tutorial.used', file: 'Submission.lean' }] }); - await freshCheck(); cooperative.requireReview(check); - expect(cooperative.current(action)).toBe(used); - expect(interrupt).toHaveBeenCalledTimes(used ? 0 : 1); - expect(review('used').status).toBe(used ? 'translating' : 'pending'); - cooperative.deactivate(workers[1]!); - if (!used) await completeFinalReview(); - }); - - it.each(['changes-requested', 'candidate-source'] as const)('resumes waiting advisory work after %s', async reason => { - const idle = peerWorker({ directory, workspace, problem }, 'engineer', { role: 'engineer', commit: check.commit }); - workers.push(idle); - state.workers = workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })); - state.cooperation!.tasks.push({ task: { id: 'investigate', kind: 'research', objective: 'Investigate another construction.', - dependsOn: [], revision: 0, ownerId: idle.id }, status: 'pending', attempts: 0 }); - cooperative = create(); - cooperative.requireReview(check); - const reviewer = workers[1]!; - const reviewAction = await cooperative.next(reviewer, budget); - expect(reviewAction).toMatchObject({ kind: 'review' }); - if (reviewAction?.kind !== 'review') throw new Error('missing_final_review'); - expect(cooperative.started(reviewer, reviewAction)).toBe(true); - const waiting = track(cooperative.next(idle, budget)); - expect(events).toContainEqual({ event: 'dispatch_wait', - details: expect.objectContaining({ workerId: idle.id, stage: 'final-review' }) }); - expect(task('investigate')).toMatchObject({ status: 'pending', attempts: 0 }); - if (reason === 'changes-requested') { - fs.writeFileSync(path.join(reviewer.worktree, 'RESEARCH.md'), - JSON.stringify({ commit: check.commit, verdict: 'changes_requested' })); - await cooperative.deliver(reviewer, reviewAction, commitSolverSources(problem, reviewer.worktree)); - expect(state.cooperation!.review?.status).toBe('changes_requested'); - } else { - state.cooperation!.canonicalCommit = problem.baseCommit; - cooperative.workerAvailabilityChanged(); - } - expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'investigate' } }); - }); - - it('does not start a reserved review after its candidate changes', async () => { - cooperative.requireReview(check); - const reviewer = workers[1]!; - const action = await cooperative.next(reviewer, budget); - expect(action).toMatchObject({ kind: 'review' }); - state.cooperation!.canonicalCommit = problem.baseCommit; - expect(cooperative.started(reviewer, action!)).toBe(false); - expect(state.turns).toBe(0); - }); - - it.each(['environment', 'task-contract', 'candidate-source'] as const)('invalidates selective review scope after a changed %s', async change => { - cooperative.requireReview(check); state.cooperation!.review!.status = 'accepted'; - expect(cooperative.reviewed(check)).toBe(true); - if (change === 'environment') state.environmentDigest = 'new-environment'; - else if (change === 'task-contract') task('unused').task = { ...task('unused').task, type: 'True ∧ True' }; - else state.cooperation!.canonicalCommit = problem.baseCommit; - expect(cooperative.reviewed(check)).toBe(false); - }); - - it('does not retain a selective scope when a cooperation archive is reconstructed', async () => { - cooperative.requireReview(check); state.cooperation!.review!.status = 'accepted'; - expect(cooperative.reviewed(check)).toBe(true); - await cooperative.stop(); state = JSON.parse(JSON.stringify(state)); cooperative = create(); - expect(cooperative.reviewed(check)).toBe(false); - cooperative.requireReview(check); - expect(cooperative.reviewed(check)).toBe(true); - }); -}); diff --git a/tests/solverHumanEditRecovery.test.ts b/tests/solverHumanEditRecovery.test.ts deleted file mode 100644 index dac850e6..00000000 --- a/tests/solverHumanEditRecovery.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch, HumanEditRecord } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { git, type SolverProblem } from '../src/solver/problem'; -import { parseCooperationPlan, taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ capture: vi.fn() })); -vi.mock('../src/solver/statementReview', async importOriginal => ({ - ...await importOriginal(), - captureStatementContexts: host.capture, -})); - -describe('human edit recovery', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, cooperative: CooperativeResearch; - let controller: AbortController; - let exclusive: (check: () => Promise) => Promise; - let events: { event: string; details?: Record }[]; - let snapshots: NonNullable[]; - let prepare: ReturnType; - const route = (revision: number): CooperativeTask => ({ id: 'route', kind: 'research', - objective: `Investigate route revision ${revision}.`, dependsOn: [], revision }); - const plan = (revision: number) => parseCooperationPlan(problem, { tasks: [route(revision)] }); - const version = (revision: number) => mathDigest(canonicalMathJson(plan(revision))); - const editsFile = () => path.join(directory, 'edits.jsonl'); - const save = () => snapshots.push(JSON.parse(JSON.stringify(state.cooperation))); - const append = (id: string, revision: number, baseVersion = state.cooperation!.planVersion) => { - fs.appendFileSync(editsFile(), JSON.stringify({ id, baseVersion, ...plan(revision) }) + '\n'); - return fs.statSync(editsFile()).size; - }; - const record = (id: string) => state.cooperation!.edits?.find(edit => edit.id === id); - const create = (peers: ResearchWorker[] = []) => { - const instance = cooperativeResearch({ state, retrievalRoot: directory, - workers: [{ id: 'lead', role: 'lead', worktree: path.join(directory, 'lead'), ownedFiles: [] }, ...peers], - access: new Map([['lead', { environment: {}, retrievalRoot: directory }]]), - signal: controller.signal, save, emit: (event, details) => events.push({ event, details }), exclusiveCheck: check => exclusive(check) }); - // This fixture tests control records rather than worker-context file projections. - vi.spyOn(instance as any, 'changed').mockImplementation((edit: unknown) => { - const current = edit as HumanEditRecord | undefined; - if (current?.status === 'applied') current.planVersion = state.cooperation!.planVersion; - save(); - }); - prepare = vi.spyOn(instance as any, 'prepareStatementContexts').mockReturnValue(undefined); - state.cooperation!.planVersion ??= (instance as any).planVersion(); - return instance; - }; - const resume = () => { - state = JSON.parse(JSON.stringify(state)); - controller = new AbortController(); exclusive = async check => check(); cooperative = create(); - }; - - beforeEach(() => { - host.capture.mockReset().mockImplementation(async (_problem: unknown, tasks: readonly CooperativeTask[]) => - new Map(tasks.map(task => [task.id, { type: 'True', constants: [], omitted: [] }]))); - directory = temporaryDirectory('solver-human-edit-recovery-'); - fs.mkdirSync(path.join(directory, 'lead')); - problem = { kind: 'example', workspace: path.join(directory, 'lead'), projectRelative: 'generated/p', - baseCommit: 'a'.repeat(40), receiptDigest: 'human-edit-fixture', ownedFiles: [], targets: [], trustedFiles: {}, - declarations: {}, sourceStructure: {}, contract: { assumptions: [], formalStatement: 'Fixture research.' } } as unknown as SolverProblem; - const initial = plan(0); - state = solverState(problem, path.join(directory, 'lead'), { runId: 'human-edit-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, - tasks: initial.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: initial.groups.map(group => ({ group, turns: 0 })) } }); - events = []; snapshots = []; controller = new AbortController(); exclusive = async check => check(); - cooperative = create(); - }); - afterEach(() => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - - it('rechecks the base version after waiting for exclusive ownership', async () => { - const entered = deferred(), release = deferred(); - append('queued-v1', 1); - exclusive = async check => { entered.resolve(); await release.promise; return check(); }; - const pending = cooperative.pulse(); - try { - await entered.promise; - await (cooperative as any).acceptPlan(plan(2)); - expect(state.cooperation!.planVersion).toBe(version(2)); - } finally { release.resolve(); } - await pending; - expect(record('queued-v1')).toMatchObject({ status: 'rejected', reason: 'math_edit_version_conflict' }); - expect(state.cooperation!.planVersion).toBe(version(2)); - expect(state.cooperation!.tasks[0].task).toEqual(route(2)); - expect(state.cooperation!.history).toHaveLength(1); - expect(events.filter(event => event.event === 'edit_applied')).toEqual([]); - }); - - it.each(['abort', 'storage'] as const)('preserves an edit interrupted by %s before entering the lock', async failure => { - append('retry-after-lock-failure', 1); - const error = Object.assign(new Error('Transient control storage failure'), { code: 'EIO' }); - exclusive = async () => { - if (failure === 'abort') { controller.abort(); controller.signal.throwIfAborted(); } - throw error; - }; - await expect(cooperative.pulse()).rejects.toMatchObject({ name: failure === 'abort' ? 'AbortError' : 'Error' }); - expect(record('retry-after-lock-failure')).toMatchObject({ status: 'received' }); - expect(state.cooperation!.cursors?.edits ?? 0).toBe(0); - expect(state.cooperation!.planVersion).toBe(version(0)); - expect(state.cooperation!.tasks[0].task).toEqual(route(0)); - expect(events.some(event => event.event === 'edit_rejected')).toBe(false); - resume(); - await cooperative.pulse(); - expect(record('retry-after-lock-failure')).toMatchObject({ status: 'applied', planVersion: version(1) }); - expect(state.cooperation!.cursors?.edits).toBe(fs.statSync(editsFile()).size); - expect(state.cooperation!.history).toHaveLength(1); - expect(events.filter(event => event.event === 'edit_received')).toHaveLength(1); - }); - - it('accepts an unrelated research edit without preparing statement contexts', async () => { - append('research-only', 1); - await cooperative.pulse(); - expect(prepare).not.toHaveBeenCalled(); - expect(record('research-only')).toMatchObject({ status: 'applied', planVersion: version(1) }); - expect(state.cooperation!.planVersion).toBe((cooperative as any).planVersion()); - expect(state.cooperation!.tasks[0].task).toEqual(route(1)); - expect(state.cooperation!.history).toHaveLength(1); - expect(state.cooperation!.cursors?.edits).toBe(fs.statSync(editsFile()).size); - expect(events.some(event => event.event === 'edit_rejected')).toBe(false); - }); - - it('persists a successful prefix without replaying it when the following edit must retry', async () => { - const prefixEnd = append('prefix', 1); - append('following-retry', 2, version(1)); - const accepted = vi.spyOn(cooperative as any, 'acceptPlan'); - const error = Object.assign(new Error('Temporary lock EIO'), { code: 'EIO' }); - let turns = 0; - exclusive = async check => { if (++turns === 2) throw error; return check(); }; - await expect(cooperative.pulse()).rejects.toBe(error); - expect(record('prefix')).toMatchObject({ status: 'applied', planVersion: version(1) }); - expect(record('following-retry')).toMatchObject({ status: 'received' }); - expect(state.cooperation!.cursors?.edits).toBe(prefixEnd); - expect(snapshots.at(-1)?.cursors?.edits).toBe(prefixEnd); - exclusive = async check => check(); - await cooperative.pulse(); - expect(accepted.mock.calls.map(([, edit]) => (edit as HumanEditRecord).id)).toEqual(['prefix', 'following-retry']); - expect(record('following-retry')).toMatchObject({ status: 'applied', planVersion: version(2) }); - expect(state.cooperation!.tasks[0].task).toEqual(route(2)); - expect(state.cooperation!.history).toHaveLength(2); - expect(events.filter(event => event.event === 'edit_applied' && event.details?.id === 'prefix')).toHaveLength(1); - }); - - it('resumes review synchronization after an applied edit without applying its graph again', async () => { - append('sync-retry', 1); - const error = Object.assign(new Error('Statement review synchronization EIO'), { code: 'EIO' }); - vi.spyOn(cooperative as any, 'syncStatementReviews').mockImplementationOnce(() => { throw error; }); - await expect(cooperative.pulse()).rejects.toBe(error); - expect(record('sync-retry')).toMatchObject({ status: 'applied', planVersion: version(1) }); - expect(state.cooperation!.planVersion).toBe(version(1)); - expect(state.cooperation!.tasks[0].task).toEqual(route(1)); - expect(state.cooperation!.history).toHaveLength(1); - expect(state.cooperation!.cursors?.edits ?? 0).toBe(0); - expect(snapshots.at(-1)?.edits?.find(edit => edit.id === 'sync-retry')).toMatchObject({ status: 'applied' }); - resume(); - const sync = vi.spyOn(cooperative as any, 'syncStatementReviews'); - const accept = vi.spyOn(cooperative as any, 'acceptPlan'); - await cooperative.pulse(); await cooperative.pulse(); - expect(sync).toHaveBeenCalledOnce(); - expect(accept).not.toHaveBeenCalled(); - expect(record('sync-retry')).toMatchObject({ status: 'applied', planVersion: version(1) }); - expect(state.cooperation!.history).toHaveLength(1); - expect(state.cooperation!.cursors?.edits).toBe(fs.statSync(editsFile()).size); - expect(events.filter(event => event.event === 'edit_applied' && event.details?.id === 'sync-retry')).toHaveLength(1); - expect(events.some(event => event.event === 'edit_rejected')).toBe(false); - }); - - it.each(['new-route', 'owner-transfer'] as const)('uses the committed dependency graph for statement context caching after %s', async change => { - const workspace = path.join(directory, 'lead'), project = path.join(workspace, 'generated/p'); - fs.mkdirSync(project, { recursive: true }); - fs.writeFileSync(path.join(project, 'Submission.lean'), 'theorem g : True := by sorry\n'); - git(workspace, ['init', '--quiet']); git(workspace, ['add', '.']); - git(workspace, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--quiet', '-m', 'Fixture']); - const commit = git(workspace, ['rev-parse', 'HEAD']); - problem = { ...problem, baseCommit: commit, ownedFiles: ['Submission.lean'], - targets: [{ proofPath: 'Submission.lean', theoremName: 'g', declarationHash: 'fixture' }], - declarations: { 'Submission.lean': [{ name: 'g', header: 'g : True' }] } }; - const helper = (id: string, dependsOn: string[] = []) => ({ id, kind: 'lemma', objective: `Prove ${id}.`, - proofPath: 'Submission.lean', theoremName: id, type: 'True', dependsOn }); - const tasks = [ - { id: 'g', kind: 'goal', objective: 'Prove g.', proofPath: 'Submission.lean', theoremName: 'g', - ...(change === 'owner-transfer' ? { ownerId: 'old' } : {}) }, - helper('p'), helper('c', ['p']), helper('q'), helper('d', ['q']), - { ...helper('h', ['g']), statementReview: true, informalStatement: 'True.' }, - ]; - const routes = [ - { id: 'route-b', targetTaskId: 'g', prerequisiteTaskIds: ['q'], closingTaskId: 'd' }, - { id: 'route-a', targetTaskId: 'g', prerequisiteTaskIds: ['p'], closingTaskId: 'c' }, - ]; - const initial = parseCooperationPlan(problem, { tasks, - ...(change === 'owner-transfer' ? { proofRoutes: routes } : {}) }); - state = { ...state, problem, cooperation: { canonicalCommit: commit, - tasks: initial.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: initial.groups.map(group => ({ group, turns: 0 })), proofRoutes: initial.proofRoutes } }; - const peers: ResearchWorker[] = ['old', 'new'].map(id => { - const worktree = path.join(directory, id); fs.mkdirSync(worktree); - return { id, role: 'researcher', worktree, ownedFiles: ['Submission.lean'] }; - }); - cooperative = create(peers); prepare.mockRestore(); - const interrupted = vi.fn(async () => {}); - let oldAction: Parameters[0] | undefined; - if (change === 'owner-transfer') { - const node = state.cooperation!.tasks.find(item => item.task.id === 'g')!; - node.status = 'running'; - node.assignment = { taskId: 'g', taskDigest: taskVersion(node.task), workerId: 'old', seedCommit: commit, routeId: 'route-a' }; - oldAction = { kind: 'task', task: node.task, assignment: node.assignment }; - cooperative.activate(peers[0], oldAction, interrupted, async () => {}); - } - const proposed = parseCooperationPlan(problem, { - tasks: tasks.map(task => task.id === 'g' && change === 'owner-transfer' ? { ...task, ownerId: 'new' } : task), - proofRoutes: change === 'new-route' ? [routes[1]] : routes, - }); - fs.appendFileSync(editsFile(), JSON.stringify({ id: 'cache-update', baseVersion: state.cooperation!.planVersion, ...proposed }) + '\n'); - await cooperative.pulse(); - await (cooperative as any).schedulePlanSynchronization(); - expect(record('cache-update')).toMatchObject({ status: 'applied' }); - expect(host.capture).toHaveBeenCalledOnce(); - const review = state.cooperation!.statementReviews!.find(item => item.taskId === 'h')!; - const saved = JSON.parse(fs.readFileSync(path.join(review.workspace, 'STATEMENT.json'), 'utf8')); - expect(saved.dependencies.map((dependency: { taskId: string }) => dependency.taskId)).toEqual( - change === 'new-route' ? ['g', 'p', 'c'] : ['g', 'q', 'd']); - expect(saved.elaboration).toEqual({ type: 'True', constants: [], omitted: [] }); - if (oldAction) { - expect(interrupted).toHaveBeenCalledOnce(); - expect(cooperative.current(oldAction)).toBe(false); - expect(state.cooperation!.tasks.find(item => item.task.id === 'g')).toMatchObject({ status: 'pending', assignment: undefined }); - } - }); - - it('still rejects deterministic invalid edits once and accepts the following valid control', async () => { - fs.appendFileSync(editsFile(), '{broken\n'); - fs.appendFileSync(editsFile(), JSON.stringify({ id: 'invalid-cycle', baseVersion: state.cooperation!.planVersion, - tasks: [{ ...route(1), dependsOn: ['route'] }] }) + '\n'); - append('valid-after-invalid', 1); - await cooperative.pulse(); await cooperative.pulse(); - expect(record('invalid-cycle')).toMatchObject({ status: 'rejected', reason: expect.stringMatching(/^math_plan_dependency_cycle: /u) }); - expect(record('valid-after-invalid')).toMatchObject({ status: 'applied', planVersion: version(1) }); - expect(events.filter(event => event.event === 'edit_rejected')).toHaveLength(2); - expect(state.cooperation!.cursors?.edits).toBe(fs.statSync(editsFile()).size); - }); -}); diff --git a/tests/solverIncrementalHelperLanding.test.ts b/tests/solverIncrementalHelperLanding.test.ts deleted file mode 100644 index 96f6f46d..00000000 --- a/tests/solverIncrementalHelperLanding.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { landVerifiedHelpers } from '../src/solver/incrementalHelpers'; -import { checkSolverProof } from '../src/solver/modules/evidence'; -import { commitSolverSources, commitSolverProjection, git, readSolverProblem } from '../src/solver/problem'; -import { assignmentDeliveryFile, parseCooperationPlan } from '../src/solver/tasks'; -import { cooperativeResearch, workerDeliveryModules } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { leadWorker, solverState } from './helpers/solver'; - -const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); -const original = 'namespace Incremental\ndef frozen : Nat := 7\ntheorem target : frozen = 7 := by sorry\nend Incremental\n'; -const file = 'Submission.lean'; -const helpers = 'theorem first : frozen = 7 := by rfl\n' + - 'theorem second : frozen = 7 := first\n'; - -function fixture(statement = original) { - const directory = temporaryDirectory('incremental-helpers-'); roots.push(directory); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { source: statement, task: 'Show frozen equals seven.' }); - const worktree = receipt.workspaceRoot, problem = readSolverProblem(worktree, receipt.activeProblemPath); - const sourceWorktree = path.join(directory, 'peer-a'); - git(worktree, ['worktree', 'add', '--quiet', '--detach', sourceWorktree, problem.baseCommit]); - const source = (root: string) => path.join(root, problem.projectRelative, file); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); - const env = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - const state = solverState(problem, worktree, { runId: 'incremental-helpers-fixture', phase: 'running', - environmentDigest: mathDigest('real lean standard environment') }); - const input = { state, worktree, sourceWorktree, seedCommit: problem.baseCommit, expectedCommit: problem.baseCommit, - env, signal: new AbortController().signal, timeoutMs: 30_000 }; - const snapshot = (text: string, valid = true) => { - fs.writeFileSync(source(sourceWorktree), text); - return valid ? commitSolverSources(problem, sourceWorktree) : commitSolverProjection(problem, sourceWorktree, 'Invalid helper fixture'); - }; - return { input, problem, worktree, source, snapshot, directory }; -} - -describe('incrementally land standalone helpers with real Lean', () => { - it('publishes an assignment-log helper batch before either original goal is solved', async () => { - const statement = original.replace('end Incremental', 'theorem consumer : frozen = 7 := by sorry\nend Incremental'); - const f = fixture(statement); - const { state } = f.input, seedCommit = f.problem.baseCommit; - const lead = leadWorker(f.problem, f.worktree); - const producer = { ...lead, id: 'producer', role: 'researcher' as const, worktree: f.input.sourceWorktree }; - const peer = { ...producer, id: 'peer', worktree: path.join(f.directory, 'peer-b') }; - git(f.worktree, ['worktree', 'add', '--quiet', '--detach', peer.worktree, seedCommit]); - const workers = [lead, producer, peer]; - const plan = parseCooperationPlan(f.problem, { tasks: f.problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, proofPath: target.proofPath, - theoremName: target.theoremName, ownerId: workers[index + 1].id, - })) }); - state.workers = workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })); - state.cooperation = { canonicalCommit: seedCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) }; - const controller = new AbortController(); - const cooperation = cooperativeResearch({ state, workers, retrievalRoot: f.directory, modules: workerDeliveryModules, - signal: controller.signal, access: new Map(workers.map(worker => - [worker.id, { environment: f.input.env, retrievalRoot: f.directory }])), timeoutMs: 30_000 }); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - try { - const action = await cooperation.next(producer, budget); - if (action?.kind !== 'task') throw new Error('fixture did not assign the producer'); - expect(cooperation.started(producer, action)).toBe(true); - const notify = vi.fn(async () => {}), interrupt = vi.fn(async () => {}); - cooperation.activate(producer, action, interrupt, notify); - fs.writeFileSync(f.source(producer.worktree), statement.replace('theorem target', helpers + 'theorem target')); - const log = path.join(producer.worktree, assignmentDeliveryFile(action.assignment)); - fs.appendFileSync(log, JSON.stringify({ kind: 'helpers', summary: 'Two reusable claims.', - declarations: [{ file, name: 'Incremental.first' }, { file, name: 'Incremental.second' }] }) + '\n'); - await cooperation.pulse(producer.id); - expect(state.cooperation.landedHelpers?.map(helper => helper.qualifiedName)).toEqual(['Incremental.first', 'Incremental.second']); - expect(state.cooperation.canonicalCommit).not.toBe(seedCommit); - expect(state.cooperation.tasks.map(task => task.status)).toEqual(['running', 'pending']); - expect(notify).toHaveBeenCalledWith(expect.stringContaining('Incremental.second :'), { mode: 'advisory' }); - expect(interrupt).not.toHaveBeenCalled(); - const dispatch = await cooperation.next(peer, budget); - expect(dispatch).toMatchObject({ kind: 'task' }); - expect(fs.readFileSync(f.source(peer.worktree), 'utf8')).toBe(statement.replace('theorem target', helpers + 'theorem target')); - const inbox = fs.readFileSync(path.join(peer.worktree, 'COOPERATION.json'), 'utf8'); - expect(inbox).toContain('Incremental.second'); - } finally { - controller.abort(); - await cooperation.stop(); - } - }, 60_000); - - it('checks two helper lemmas, keeps the original goal open, and gives the next peer a proof it can use', async () => { - const f = fixture(); - const sourceCommit = f.snapshot(original.replace('end Incremental', helpers + - 'def unrelated : Nat := by sorry\nend Incremental')); - const declarations = [{ file, name: 'Incremental.first' }, { file, name: 'Incremental.second', type: 'Incremental.frozen = 7' }]; - const result = await landVerifiedHelpers({ ...f.input, sourceCommit, declarations }); - expect(result.helpers.map(item => item.qualifiedName)).toEqual(['Incremental.first', 'Incremental.second']); - expect(result.helpers.every(item => item.commit === result.commit && item.type.includes(item.qualifiedName))).toBe(true); - expect(fs.readFileSync(f.source(f.worktree), 'utf8')).toEqual(original); - expect(git(f.worktree, ['rev-parse', `${result.commit}^`])).toBe(f.problem.baseCommit); - const peer = path.join(f.directory, 'peer-b'); - git(f.worktree, ['worktree', 'add', '--quiet', '--detach', peer, result.commit]); - const peerSource = fs.readFileSync(f.source(peer), 'utf8'); - expect(peerSource).toBe(original.replace('theorem target', helpers + 'theorem target')); - expect((await checkSolverProof(f.problem, peer, f.input.env)).passed).toBe(false); - fs.writeFileSync(f.source(peer), peerSource.replace('by sorry', 'by exact second')); - expect((await checkSolverProof(f.problem, peer, f.input.env)).passed).toBe(true); - const duplicate = await landVerifiedHelpers({ ...f.input, expectedCommit: result.commit, sourceCommit, declarations }); - expect(duplicate).toMatchObject({ commit: result.commit, helpers: [], changes: [] }); - const conflicting = f.snapshot(original.replace('end Incremental', helpers.replace('by rfl', 'by exact rfl') + 'end Incremental')); - await expect(landVerifiedHelpers({ ...f.input, expectedCommit: result.commit, sourceCommit: conflicting, declarations })) - .rejects.toThrow('math_incremental_helper_conflicting_definition'); - }, 60_000); - - it('includes a named same-file closure dependency and refuses any draft or original goal dependency', async () => { - const f = fixture(); - const declaration = { file, name: 'Incremental.second' }; - const sourceCommit = f.snapshot(original.replace('end Incremental', helpers + 'end Incremental')); - const landed = await landVerifiedHelpers({ ...f.input, sourceCommit, declarations: [declaration] }); - expect(landed.helpers.map(item => item.qualifiedName)).toEqual(['Incremental.first', 'Incremental.second']); - for (const text of [helpers.replace('by rfl', 'by sorry'), helpers.replace(':= first', ':= target')]) { - const sourceCommit = f.snapshot(original.replace('end Incremental', text + 'end Incremental')); - await expect(landVerifiedHelpers({ ...f.input, sourceCommit, declarations: [declaration] })) - .rejects.toThrow('math_incremental_helper_kernel_rejected'); - } - expect(git(f.worktree, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit); - }, 60_000); - - it('refuses a changed frozen declaration and a nomination of the original target', async () => { - const f = fixture(); - const sourceCommit = f.snapshot(original.replace(':= 7', ':= 8').replace('end Incremental', helpers + 'end Incremental'), false); - await expect(landVerifiedHelpers({ ...f.input, sourceCommit, declarations: [{ file, name: 'Incremental.first' }] })) - .rejects.toThrow('math_original_declaration_changed'); - await expect(landVerifiedHelpers({ ...f.input, sourceCommit: f.problem.baseCommit, declarations: [{ file, name: 'Incremental.target' }] })) - .rejects.toThrow('math_incremental_helper_original_declaration'); - }); - - it('rejects a tactic that implicitly uses an unfinished original goal in canonical source', async () => { - const statement = 'namespace Incremental\ndef token : Nat := 1\n' + - '@[simp]\ntheorem unavailable : token = 0 := by sorry\n' + - 'def limit : Nat := token\ntheorem target : token = limit := by sorry\nend Incremental\n'; - const f = fixture(statement); - const helper = 'theorem implicit : ∃ n, limit = n := by\n' + - ' first\n | exact ⟨0, by simpa [limit]⟩\n | exact ⟨limit, rfl⟩\n'; - const sourceCommit = f.snapshot(statement.replace('end Incremental', helper + 'end Incremental')); - await expect(landVerifiedHelpers({ ...f.input, sourceCommit, declarations: [{ file, name: 'Incremental.implicit' }] })) - .rejects.toThrow(/math_incremental_helper_kernel_rejected:.*sorryAx/u); - }, 60_000); -}); diff --git a/tests/solverInitialPlan.test.ts b/tests/solverInitialPlan.test.ts deleted file mode 100644 index 8ce3f9be..00000000 --- a/tests/solverInitialPlan.test.ts +++ /dev/null @@ -1,291 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, git, type SolverProblem } from '../src/solver/problem'; -import { ResearchUsage } from '../src/solver/researchUsage'; -import { initialPlanDeliveryFile, type CooperativeAction } from '../src/solver/tasks'; -import { buildTokenBudget, initializeUsageAccounting } from '../src/solver/usageBudget'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -describe('explicit initial Lead plan publication', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, lead: ResearchWorker, peer: ResearchWorker; - let events: { event: string; details?: Record }[]; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let interrupt: ReturnType; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const plan = (suffix = '') => ({ tasks: problem.targets.map((target, index) => ({ - id: `goal_${index + 1}${suffix}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, - })) }); - const create = (additionalPeers: ResearchWorker[] = []) => { - const controller = new AbortController(); - const cooperative = cooperativeResearch({ state, workers: [lead, peer, ...additionalPeers], retrievalRoot: directory, - signal: controller.signal, emit: (event, details) => events.push({ event, details }) }); - instances.push({ cooperative, controller }); - return cooperative; - }; - const startLead = async (cooperative: CooperativeResearch) => { - const action = await cooperative.next(lead, budget); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead'); - expect(initialPlanDeliveryFile(action)).toMatch(/^DELIVERIES-[a-f0-9]{64}\.jsonl$/u); - expect(cooperative.started(lead, action)).toBe(true); - cooperative.activate(lead, action, interrupt, async () => {}); - return action; - }; - const file = (action: CooperativeAction) => path.join(lead.worktree, initialPlanDeliveryFile(action)!); - const event = (action: CooperativeAction, value = plan()) => JSON.stringify({ - kind: 'plan', baseVersion: action.kind === 'lead' ? action.planVersion : undefined, - summary: 'The direct original-goal tasks are ready for independent workers.', ...value, - }); - const publish = async (cooperative: CooperativeResearch, action: CooperativeAction, line = event(action)) => { - fs.appendFileSync(file(action), line + '\n'); - await cooperative.pulse(); - }; - - beforeEach(() => { - const example = localExample('solver-initial-plan-', 'lead'); - ({ directory, problem } = example); - lead = leadWorker(problem, example.workspace); - peer = peerWorker(example, 'engineer', { role: 'engineer' }); - state = solverState(problem, example.workspace, { runId: 'initial-plan-fixture', phase: 'prepared', - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture' }); - instances = []; events = []; interrupt = vi.fn(async () => {}); - }); - afterEach(async () => { - for (const instance of instances) instance.controller.abort(); - await Promise.allSettled(instances.map(instance => instance.cooperative.stop())); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('starts a waiting peer while the same Lead remains active at its frozen dispatch identity', async () => { - const cooperative = create(), action = await startLead(cooperative); - const originalAction = structuredClone(action), head = git(lead.worktree, ['rev-parse', 'HEAD']); - const relative = path.join(problem.projectRelative, 'Submission.lean'); - const originalSource = fs.readFileSync(path.join(lead.worktree, relative), 'utf8'); - const unpublishedSource = originalSource.replace('n + 0 = n := by sorry', 'n + 0 = n := by exact Nat.add_zero n'); - expect(unpublishedSource).not.toBe(originalSource); - fs.writeFileSync(path.join(lead.worktree, relative), unpublishedSource); - const waiting = cooperative.next(peer, budget); - void waiting.catch(() => {}); - await publish(cooperative, action); - const assigned = await waiting; - expect(assigned).toMatchObject({ kind: 'task', task: { id: 'goal_1' } }); - expect(cooperative.current(action)).toBe(true); - expect(action).toEqual(originalAction); - expect(cooperative.hasLeadPublication(action)).toBe(true); - expect(state.cooperation!.initialPlanPublication).toMatchObject({ nonce: action.initialPlanNonce, - baseVersion: originalAction.planVersion, planVersion: state.cooperation!.planVersion }); - expect(interrupt).not.toHaveBeenCalled(); - expect(git(lead.worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(fs.readFileSync(path.join(lead.worktree, relative), 'utf8')).toBe(unpublishedSource); - expect(fs.readFileSync(path.join(peer.worktree, relative), 'utf8')).toBe(originalSource); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('leaves ordinary notes and a partial JSONL event unpublished', async () => { - const cooperative = create(), action = await startLead(cooperative), line = event(action); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(plan('_draft')) + '\n```'); - await cooperative.pulse(); - expect(state.cooperation!.tasks).toEqual([]); - fs.appendFileSync(file(action), line.slice(0, line.length / 2)); - await cooperative.pulse(); - expect(state.cooperation!.tasks).toEqual([]); - expect(state.cooperation!.initialPlanPublication).toBeUndefined(); - fs.appendFileSync(file(action), line.slice(Math.floor(line.length / 2))); - await cooperative.pulse(); - expect(state.cooperation!.tasks).toEqual([]); - fs.appendFileSync(file(action), '\n'); - await cooperative.pulse(); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - }); - - it('starts distinct goal and open-inference work from a small first graph before the Lead returns', async () => { - const researcher: ResearchWorker = { id: 'researcher', role: 'researcher', - worktree: path.join(directory, 'researcher'), ownedFiles: problem.ownedFiles }; - git(lead.worktree, ['worktree', 'add', '--quiet', '--detach', researcher.worktree, problem.baseCommit]); - const cooperative = create([researcher]), action = await startLead(cooperative); - const directGoals = plan().tasks.map(task => ({ ...task, ownerId: peer.id })); - const research = { id: 'open_inference', kind: 'research', ownerId: researcher.id, - objective: 'Determine the existing addition lemma and its exact hypotheses for the original goal.', - dependsOn: [directGoals[0].id], consumerGoalIds: [directGoals[0].id] }; - const goalWaiting = cooperative.next(peer, budget), researchWaiting = cooperative.next(researcher, budget); - void goalWaiting.catch(() => {}); void researchWaiting.catch(() => {}); - await publish(cooperative, action, JSON.stringify({ kind: 'plan', baseVersion: action.planVersion, - tasks: [...directGoals, research] })); - expect(await goalWaiting).toMatchObject({ kind: 'task', task: { id: 'goal_1', kind: 'goal', dependsOn: [] } }); - expect(await researchWaiting).toMatchObject({ kind: 'task', task: { id: 'open_inference', kind: 'research' } }); - expect(cooperative.current(action)).toBe(true); - expect(interrupt).not.toHaveBeenCalled(); - expect(state.cooperation!.tasks.filter(node => node.status === 'running')).toHaveLength(2); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('ignores an older dispatch log and rejects malformed or stale events before accepting a valid one', async () => { - const cooperative = create(), action = await startLead(cooperative); - fs.appendFileSync(file({ ...action, initialPlanNonce: 'old-dispatch' }), event(action) + '\n'); - await cooperative.pulse(); - expect(state.cooperation!.tasks).toEqual([]); - await publish(cooperative, action, '{bad JSON'); - await publish(cooperative, action, JSON.stringify({ kind: 'plan', baseVersion: 'stale', ...plan() })); - await publish(cooperative, action, event(action, { tasks: [] })); - expect(state.cooperation!.tasks).toEqual([]); - expect(events.filter(item => item.event === 'initial_plan_rejected')).toHaveLength(3); - await publish(cooperative, action); - expect(state.cooperation!.tasks).toHaveLength(problem.targets.length); - }); - - it('accepts one frozen event and keeps duplicate or later events from rewriting it', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - const receipt = structuredClone(state.cooperation!.initialPlanPublication); - await publish(cooperative, action); - await publish(cooperative, action, event(action, plan('_second'))); - expect(state.cooperation!.initialPlanPublication).toEqual(receipt); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(events.filter(item => item.event === 'initial_plan_published')).toHaveLength(1); - expect(events.filter(item => item.event === 'plan_updated')).toHaveLength(1); - }); - - it('keeps later human edits above the original Lead self-publication', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'new-direction', - baseVersion: state.cooperation!.planVersion, ...plan('_human') }) + '\n'); - await cooperative.pulse(); - expect(state.cooperation!.edits?.[0].status).toBe('applied'); - expect(cooperative.current(action)).toBe(false); - expect(cooperative.started(lead, action)).toBe(false); - expect(cooperative.hasLeadPublication(action)).toBe(false); - expect(interrupt).toHaveBeenCalledOnce(); - }); - - it('leaves the current Lead running for a stale edit or an accepted unchanged graph', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - const version = state.cooperation!.planVersion; - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'stale-edit', - baseVersion: 'obsolete-version', ...plan('_stale') }) + '\n'); - await cooperative.pulse(); - expect(state.cooperation!.edits?.[0]).toMatchObject({ status: 'rejected', reason: 'math_edit_version_conflict' }); - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'unchanged-edit', baseVersion: version, - tasks: state.cooperation!.tasks.map(item => item.task), groups: state.cooperation!.groups!.map(item => item.group) }) + '\n'); - await cooperative.pulse(); - expect(state.cooperation!.edits?.[1].status).toBe('applied'); - expect(state.cooperation!.planVersion).toBe(version); - expect(cooperative.current(action)).toBe(true); - expect(interrupt).not.toHaveBeenCalled(); - }); - - it.each([false, true])('restores the accepted graph without importing a newer unpublished valid notes draft (finalized: %s)', async finalized => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - if (finalized) { - cooperative.deactivate(lead); - await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree)); - expect(state.cooperation!.initialPlanPublication?.finalized).toBe(true); - } - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(plan('_unpublished')) + '\n```'); - const stateFile = path.join(directory, 'state.json'); - writeSolverRunState(stateFile, state); state = readSolverRunState(stateFile); - expect(state.cooperation!.initialPlanPublication?.nonce).toBe(action.initialPlanNonce); - const restored = create(); - await restored.restore(); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(cooperative.current({ ...action })).toBe(false); - }); - - it.each([false, true])('keeps a published plan when the final notes include illustrative JSON (request failure: %s)', async recovering => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'The peers can work while the next mathematical route is investigated.\n\n' + - '```json\n{"example":{"tasks":["check the boundary case"]}}\n```\n'); - cooperative.deactivate(lead); - const delivered = await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree), recovering, 'request-failure'); - expect(delivered).toEqual({ checkWhole: false, ...(recovering ? { savedPlan: true } : {}) }); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(state.cooperation!.initialPlanPublication?.finalized).toBe(recovering ? undefined : true); - expect(events.filter(item => item.event === 'plan_rejected')).toEqual([]); - expect(events.filter(item => item.event === 'plan_updated')).toHaveLength(1); - }); - - it('validates a later explicit replacement plan through ordinary final delivery', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(plan('_final')) + '\n```'); - cooperative.deactivate(lead); - await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree)); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1_final', 'goal_2_final']); - expect(state.cooperation!.initialPlanPublication?.finalized).toBe(true); - expect(events.filter(item => item.event === 'plan_updated')).toHaveLength(2); - const version = state.cooperation!.planVersion; - expect(version).not.toBe(state.cooperation!.initialPlanPublication?.planVersion); - const stateFile = path.join(directory, 'final-replacement-state.json'); - writeSolverRunState(stateFile, state); state = readSolverRunState(stateFile); - const restored = create(); await restored.restore(); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1_final', 'goal_2_final']); - expect(state.cooperation!.planVersion).toBe(version); - }); - - it('reports an invalid final plan without losing an earlier published plan', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '```math-plan\n{"tasks":[]}\n```'); - cooperative.deactivate(lead); - const delivered = await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree), true, 'request-failure'); - expect(delivered).toEqual({ checkWhole: false, savedPlan: true }); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(state.cooperation!.error).toBe('math_plan_invalid'); - expect(state.cooperation!.initialPlanPublication?.finalized).toBeUndefined(); - expect(events.filter(item => item.event === 'plan_rejected')).toHaveLength(1); - }); - - it('still checks changed Lead proof sources through the ordinary integration path', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - const sourceFile = path.join(lead.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(sourceFile, fs.readFileSync(sourceFile, 'utf8').replace('n + 0 = n := by sorry', - 'n + 0 = n := by exact Nat.add_zero n')); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'The saved proof requires host integration.\n'); - const merge = vi.spyOn(cooperative as any, 'mergeLeadSources').mockRejectedValue(new Error('fixture_integration_rejected')); - cooperative.deactivate(lead); - await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree)); - expect(merge).toHaveBeenCalledOnce(); - expect(state.cooperation!.error).toBe('fixture_integration_rejected'); - expect(state.cooperation!.canonicalCommit).not.toBe(git(lead.worktree, ['rev-parse', 'HEAD'])); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('retains the finite shared budget and pending usage while leaving initial planning after publication', async () => { - const cooperative = create(), action = await startLead(cooperative); - initializeUsageAccounting(state); - state.tokenBudget = buildTokenBudget(1000, [state], 'provider-observed-upstream-request-limit'); - const controller = instances[0].controller; - const usage = new ResearchUsage({ state, research: state, maxTotalTokens: 1000, - signal: controller.signal, remainingMs: () => Infinity, - changed: () => { state.tokenBudget = buildTokenBudget(1000, [state], 'provider-observed-upstream-request-limit'); }, - emit: (name, details) => events.push({ event: name, details }) }); - const callbacks = usage.bindSession('fixture-session', () => undefined); - usage.sessionOpened({ threadId: 'fixture-thread', usageSource: 'upstream-requests', run: async () => 'completed', - close: async () => {}, interrupt: async () => {} }); - usage.begin(action); - const first = callbacks.requestGate!(), second = callbacks.requestGate!(); - if (!first.allowed || !second.allowed) throw new Error('fixture_request_not_admitted'); - first.settle({ usage: { totalTokens: 20, inputTokens: 15, outputTokens: 5 }, complete: true }); - await publish(cooperative, action); - expect(state.requestUsageAccounting!.pendingRequests).toBe(1); - expect(state.usageAccounting).toMatchObject({ pending: true, reportedTurns: 0 }); - const third = callbacks.requestGate!(); - expect(third.allowed).toBe(true); - if (!third.allowed) throw new Error('fixture_publication_did_not_leave_initial_planning'); - second.settle({ usage: { totalTokens: 500, inputTokens: 450, outputTokens: 50 }, complete: true }); - third.settle({ usage: { totalTokens: 500, inputTokens: 450, outputTokens: 50 }, complete: true }); - expect(callbacks.requestGate!()).toEqual({ allowed: false, reason: 'math_total_token_limit' }); - usage.finish(true); - expect(state.requestUsageAccounting).toMatchObject({ reportedRequests: 3, pendingRequests: 0, incomplete: false }); - expect(events.some(item => item.event === 'planning_budget_stopped')).toBe(false); - }); -}); diff --git a/tests/solverIntegrationBatch.test.ts b/tests/solverIntegrationBatch.test.ts deleted file mode 100644 index 92a1c453..00000000 --- a/tests/solverIntegrationBatch.test.ts +++ /dev/null @@ -1,858 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LAKE_CONFIGURATION_FILES, mathLocalModuleBuildOrder } from '../src/math/mathConstructionSources'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import { LEAN_MEMORY_LIMIT_ERROR, LEAN_STACK_LIMIT_ERROR, type MathematicsVerifierBatchRequest, type MathematicsVerifierBatchResult } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { checkTaskProofs, type TaskProof } from '../src/solver/cooperativeProof'; -import { captureDeliveryArtifacts } from '../src/solver/deliveryArtifacts'; -import type { KnowledgeContextSnapshot } from '../src/solver/knowledgeContext'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git, type SolverProblem } from '../src/solver/problem'; -import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask, type TaskAssignment, type TaskRecord } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), check: vi.fn(), identity: vi.fn(), tools: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: host.tools, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/math/leanTypeDiagnostics', async importOriginal => ({ - ...await importOriginal(), checkLeanType: host.check, -})); -vi.mock('../src/math/leanResidualGoals', async importOriginal => ({ - ...await importOriginal(), leanDiagnosticEnvironmentIdentity: host.identity, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -type Fault = 'unavailable' | 'abort' | 'storage' | 'cleanup' | 'corrupt-receipt'; - -describe('same-layer checked task integration batches', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch, controller: AbortController; - let access: ReturnType; - let receipts: MathematicsVerifierBatchResult[], sequence: number, releases: (() => void)[], pending: Promise[]; - let events: { event: string; details?: Record }[]; - - const node = (id = 'first') => state.cooperation!.tasks.find(item => item.task.id === id)!; - const canonicalSource = () => committedSource(workspace, state.cooperation!.canonicalCommit!, - `${problem.projectRelative}/Submission.lean`); - const calls = () => host.verify.mock.calls.map(([request]) => request as MathematicsVerifierBatchRequest); - const track = (promise: Promise) => { - pending.push(promise); void promise.catch(() => {}); return promise; - }; - const verified = (request: MathematicsVerifierBatchRequest): MathematicsVerifierBatchResult => { - const sessionId = `integration-batch-${++sequence}`; - const batch: MathematicsVerifierBatchResult = { - schema: 'deepscientist.mathematics.verification-batch/v1', status: 'kernel_verified', - targetCommit: request.targetCommit!, sessionId, events: [], startedAt: sequence * 10, - checkedAt: sequence * 10 + 2, durationMs: 2, - results: request.items.map((item, index) => ({ ...item, sourceDeclarationHash: item.expectedSourceDeclarationHash, - checkId: item.id?.trim() || `check-${index + 1}`, sessionId, checkedAt: sequence * 10 + 2, - receiptId: `${sessionId}-${item.theoremName}`, targetCommit: request.targetCommit, - status: 'kernel_verified', claim: 'statement' })) as MathematicsVerifierBatchResult['results'], - }; - receipts.push(batch); return batch; - }; - const writeLemma = (worker: ResearchWorker, declarations: string) => { - const file = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', declarations + '\ntheorem add_zero')); - return commitSolverSources(problem, worker.worktree); - }; - const changeTask = (id: string, change: Partial) => { - const record = node(id); - record.task = { ...record.task, ...change }; - record.assignment = { ...record.assignment!, taskDigest: taskVersion(record.task) }; - }; - const prepare = async (id = 'first', declarations = `lemma batch_${id} : True := by trivial`) => { - const record = node(id), worker = workers.find(item => item.id === record.assignment!.workerId)!; - const commit = writeLemma(worker, declarations); - const proof = await (cooperative as any).check(record.task, record.assignment, worker.worktree, commit); - expect(proof.passed).toBe(true); - Object.assign(record, { status: 'delivered', proof }); - return proof; - }; - const preparePair = async () => { - const proofs = await Promise.all([prepare('first'), prepare('second')]); - host.verify.mockClear(); receipts = []; return proofs; - }; - const enableProofCache = () => { - host.tools.mockReturnValue('fixture-cache-tools'); - for (const value of access.values()) value.environment = { - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'math.env'), PATH: '/usr/bin:/bin', - }; - }; - const prepareDependentDelivery = async () => { - enableProofCache(); - await prepare('second'); await integrate('second'); - const canonical = state.cooperation!.canonicalCommit!, record = node(); - changeTask('first', { dependsOn: ['second'] }); - record.assignment = { ...record.assignment!, seedCommit: canonical, - dependencies: [{ taskId: 'second', taskDigest: taskVersion(node('second').task) }] }; - const worker = workers.find(item => item.id === record.assignment!.workerId)!; - git(worker.worktree, ['reset', '--hard', canonical]); - return await prepare('first', 'lemma batch_first : True := by exact batch_second'); - }; - const integrate = (id = 'first') => track((cooperative as any).integrateNow(node(id)) as Promise); - const drain = () => track((cooperative as any).integrateReady() as Promise); - const gateBatch = (resultFor: (request: MathematicsVerifierBatchRequest) => MathematicsVerifierBatchResult = verified) => { - const entered = deferred(), result = deferred(); - let held: MathematicsVerifierBatchRequest | undefined; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - if (request.items.length < 2 || held) return verified(request); - held = request; entered.resolve(request); return result.promise; - }); - const release = () => { if (held) result.resolve(resultFor(held)); }; - releases.push(release); return { entered: entered.promise, release }; - }; - const failVerifier = (failure: Fault, error: Error, cleanupError: string) => - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - if (failure === 'abort' || failure === 'storage') throw error; - const batch = verified(request); - if (failure === 'unavailable') { - batch.status = 'unavailable'; batch.results = batch.results.map(item => ({ ...item, status: 'unavailable', error: error.message })); - } else if (failure === 'cleanup') { - batch.status = 'failed'; - batch.results = batch.results.map(item => ({ ...item, status: 'failed', error: 'Lean exited with status 1.', - stdoutPreview: 'Submission.lean:3:1: error: Fixture cleanup failure.', cleanupError })); - } else batch.results = batch.results.map(item => ({ ...item, targetCommit: '0'.repeat(40) })); - return batch; - }); - const expectNoFailure = () => { - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(state.cooperation!.blockers ?? []).toEqual([]); - expect(state.cooperation!.deliveries?.filter(item => item.status === 'failed') ?? []).toEqual([]); - }; - - beforeEach(() => { - receipts = []; sequence = 0; releases = []; pending = []; events = []; - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.tools.mockReset().mockReturnValue(undefined); - host.check.mockReset().mockImplementation(() => { throw new Error('fixture_unexpected_knowledge_check'); }); - host.identity.mockReset().mockReturnValue({ environmentDigest: mathDigest('diagnostic-environment'), toolIdentity: mathDigest('fixture-tools') }); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('solver-integration-batch-'); - ({ directory, workspace, problem } = example); - workers = [leadWorker(problem, workspace), ...['first', 'second', 'independent'].map(id => peerWorker(example, id))]; - const tasks: TaskRecord[] = ['first', 'second'].map(id => { - const task: CooperativeTask = { id, kind: 'lemma', objective: `Prove independent helper ${id}.`, - theoremName: `Tutorial.batch_${id}`, proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - const assignment: TaskAssignment = { taskId: id, taskDigest: taskVersion(task), workerId: id, - seedCommit: problem.baseCommit, assignmentId: `batch-dispatch-${id}`, dependencies: [] }; - return { task, assignment, status: 'running', attempts: 1 }; - }); - state = solverState(problem, workspace, { runId: 'integration-batch-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [...tasks, ...problem.targets.map((target, index) => ({ - task: { id: `goal_${index}`, kind: 'goal' as const, objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: [], revision: 0, status: 'paused' as const }, - status: 'pending' as const, attempts: 0, - }))] } }); - controller = new AbortController(); - let queue = Promise.resolve(); - access = workerAccess(workers, directory); - cooperative = cooperativeResearch({ state, workers, access, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }), - exclusiveCheck: async check => { - const previous = queue, { promise, resolve } = deferred(); - queue = promise; - await previous; - try { return await check(); } finally { resolve(); } - } }); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - }); - afterEach(async () => { - for (const release of releases) release(); - controller.abort(); await Promise.allSettled(pending); await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['integration', 'restored recheck'] as const) - ('reuses an unchanged dependent delivery during %s', async phase => { - const delivery = await prepareDependentDelivery(); - host.verify.mockClear(); - let receipt: TaskProof | undefined; - if (phase === 'integration') { - await integrate(); - expect(node().status).toBe('integrated'); - receipt = node().integratedCheck; - } else { - const tasks = state.cooperation!.tasks.map(record => record === node() - ? { ...record, status: 'integrated' as const, integratedCheck: structuredClone(delivery) } : { ...record }); - await expect(track((cooperative as any).recheckIntegrated(delivery.commit, false, { - tasks, ids: new Set(['first']), environment: access.get(workers[0]!.id)!.environment, - environmentDigest: state.environmentDigest, current: () => true, - }))).resolves.toBe(true); - expect(tasks.find(record => record.task.id === 'first')!.status).toBe('integrated'); - receipt = tasks.find(record => record.task.id === 'first')!.integratedCheck; - } - expect(calls()).toHaveLength(0); - expect(receipt!.verification.sessionId).toBe(delivery.verification.sessionId); - expectNoFailure(); - }); - - it('checks a dependent delivery again after an input version changes with identical Lean source', async () => { - const delivery = await prepareDependentDelivery(), dependency = node('second'); - changeTask('second', { revision: dependency.task.revision + 1 }); - const canonical = state.cooperation!.canonicalCommit!; - dependency.integratedCheck = await (cooperative as any).check(dependency.task, { - taskId: dependency.task.id, taskDigest: taskVersion(dependency.task), workerId: workers[0]!.id, - seedCommit: canonical, dependencies: [], - }, workspace, canonical, []); - host.verify.mockClear(); - - await integrate(); - - expect(node().status).toBe('integrated'); - expect(calls()).toHaveLength(1); - expect(node().integratedCheck!.verification.sessionId).not.toBe(delivery.verification.sessionId); - expectNoFailure(); - }); - - it('reuses a checked shared projection with the same current dependency versions during batch integration', async () => { - enableProofCache(); - const task: CooperativeTask = { id: 'input', kind: 'lemma', objective: 'Prove the shared input.', - theoremName: 'Tutorial.batch_input', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - state.cooperation!.tasks.push({ task, status: 'running', attempts: 1, assignment: { - taskId: task.id, taskDigest: taskVersion(task), workerId: workers[3]!.id, - seedCommit: problem.baseCommit, dependencies: [], - } }); - await prepare('input'); await integrate('input'); - const canonical = state.cooperation!.canonicalCommit!; - const dependencies = [{ taskId: task.id, taskDigest: taskVersion(task) }]; - for (const id of ['first', 'second']) { - changeTask(id, { dependsOn: [task.id] }); - node(id).assignment = { ...node(id).assignment!, seedCommit: canonical, dependencies }; - git(workers.find(worker => worker.id === node(id).assignment!.workerId)!.worktree, ['reset', '--hard', canonical]); - await prepare(id, `lemma batch_${id} : True := by exact batch_input`); - } - git(workers[3]!.worktree, ['reset', '--hard', canonical]); - const candidate = writeLemma(workers[3]!, ['first', 'second'].map(id => - `lemma batch_${id} : True := by exact batch_input`).join('\n')); - const checked = await checkTaskProofs(problem, workers[3]!.worktree, candidate, ['first', 'second'].map(id => ({ - task: node(id).task, retainedGoals: [], assignment: { taskId: id, taskDigest: taskVersion(node(id).task), - workerId: workers[3]!.id, seedCommit: candidate, dependencies }, - })), access.get(workers[0]!.id)!.environment, controller.signal, undefined, state.environmentDigest, - (cooperative as any).taskProofCache); - host.verify.mockClear(); - - await integrate(); - - expect(calls()).toHaveLength(0); - for (const [index, id] of ['first', 'second'].entries()) { - expect(node(id).status).toBe('integrated'); - expect(node(id).integratedCheck!.verification.sessionId).toBe(checked[index]!.verification.sessionId); - } - expect(events.some(item => item.event === 'task_integration_batch_started')).toBe(true); - expectNoFailure(); - }); - - it('checks a ready pair once and preserves each target\'s original receipt while publishing the union', async () => { - const proofs = await preparePair(); - - await integrate(); - - expect(calls()).toHaveLength(1); - expect(calls()[0]!.items.map(item => item.theoremName).sort()).toEqual(['Tutorial.batch_first', 'Tutorial.batch_second']); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('integrated'); - expect(node().proof).toBe(proofs[0]); expect(node('second').proof).toBe(proofs[1]); - expect(canonicalSource()).toContain('lemma batch_first : True := by trivial'); - expect(canonicalSource()).toContain('lemma batch_second : True := by trivial'); - for (const record of [node(), node('second')]) { - const check = record.integratedCheck!, raw = receipts[0]!; - expect(check.passed).toBe(true); - expect(check.verification.sessionId).toBe(raw.sessionId); - expect(check.verification.targetCommit).toBe(raw.targetCommit); - expect(check.verification.checkedAt).toBe(raw.checkedAt); - expect(check.verification.results).toEqual([raw.results.find(item => item.theoremName === record.task.theoremName)]); - expect(check.commit).toBe(state.cooperation!.canonicalCommit); - expect(events.find(item => item.event === 'task_integrated' && item.details?.taskId === record.task.id)?.details) - .toMatchObject({ taskId: record.task.id, taskDigest: taskVersion(record.task), - assignmentKey: assignmentDeliveryFile(record.assignment!), workerId: record.assignment!.workerId, - seedCommit: record.assignment!.seedCommit, commit: check.commit, sourceDigest: check.sourceDigest, - receiptIds: check.verification.results.map(result => result.receiptId) }); - } - await drain(); await drain(); - expect(calls()).toHaveLength(1); - expect(state.cooperation!.deliveries?.filter(item => item.kind === 'proof' && item.status === 'verified')).toHaveLength(2); - for (const delivery of state.cooperation!.deliveries!.filter(item => item.kind === 'proof' && item.status === 'verified')) - expect(events.find(item => item.event === 'delivery_published' && item.details?.deliveryId === delivery.id)?.details) - .toMatchObject({ deliveryId: delivery.id, producer: delivery.producer, workerId: delivery.producer, - taskId: delivery.taskId, taskDigest: delivery.taskDigest, assignmentKey: delivery.assignmentKey, - commit: delivery.commit, sourceDigest: delivery.sourceDigest, - receiptIds: delivery.evidence!.verification.results.map(result => result.receiptId) }); - expect(events.filter(item => item.event === 'task_integrated')).toHaveLength(2); - expectNoFailure(); - }); - - it('clears stale feedback for every successfully integrated batch member before publishing', async () => { - await preparePair(); - for (const id of ['first', 'second']) node(id).feedback = `Old ${id} proof failure: unknown identifier stale_proof`; - - await integrate(); - - expect(calls()).toHaveLength(1); - for (const id of ['first', 'second']) { - expect(node(id).status).toBe('integrated'); - expect(node(id).feedback).toBeUndefined(); - } - await drain(); - const accepted = state.cooperation!.deliveries!.filter(record => record.kind === 'proof' && record.status === 'verified'); - expect(accepted).toHaveLength(2); - expect(accepted.every(record => !record.summary.includes('stale_proof'))).toBe(true); - expectNoFailure(); - }); - - it('retains fresh original inputs through definition chains when batching newly delivered helpers', async () => { - const file = path.join(workspace, problem.projectRelative, 'Submission.lean'); - const chains = ['first', 'second'].map(id => - `def ${id}_witness (n : Nat) : n + 0 = n := add_zero n\n` + - `def ${id}_chain (n : Nat) : n + 0 = n := ${id}_witness n\n`).join('\n'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('by sorry', 'by rfl') - .replace('end Tutorial', chains + '\nend Tutorial')); - const canonical = commitSolverSources(problem, workspace); - state.cooperation!.canonicalCommit = canonical; - const missingContexts: { targets: string[]; originalPresent: boolean; missingDefinitions: string[] }[] = []; - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const projected = committedSource(workspace, request.targetCommit!, `${problem.projectRelative}/Submission.lean`); - const helpers = request.items.filter(item => ['Tutorial.batch_first', 'Tutorial.batch_second'].includes(item.theoremName!)); - const required = helpers.flatMap(item => { - const id = item.theoremName!.endsWith('first') ? 'first' : 'second'; - return [`def ${id}_witness`, `def ${id}_chain`]; - }); - const originalPresent = projected.includes('theorem add_zero (n : Nat) : n + 0 = n := by rfl'); - const missingDefinitions = required.filter(declaration => !projected.includes(declaration)); - const result = verified(request); - if (helpers.length && (!originalPresent || missingDefinitions.length)) { - missingContexts.push({ targets: helpers.map(item => item.theoremName!), originalPresent, missingDefinitions }); - result.status = 'failed'; - result.results = result.results.map(item => ({ ...item, status: 'failed', error: 'Lean exited with status 1.', - stdoutPreview: 'Submission.lean:3:1: error: unknown identifier ' + (missingDefinitions[0]?.slice(4) ?? 'add_zero') })); - } - return result; - }); - // Establish fresh host acceptance of the original before either new helper exists in canonical. - const original = node('goal_0'); - const originalAssignment: TaskAssignment = { taskId: original.task.id, taskDigest: taskVersion(original.task), - workerId: workers[0]!.id, seedCommit: canonical, dependencies: [] }; - const accepted = await (cooperative as any).check(original.task, originalAssignment, workspace, canonical); - expect(accepted.passed).toBe(true); - Object.assign(original, { status: 'integrated', integratedCheck: accepted }); - const proofs = []; - for (const id of ['first', 'second']) { - const record = node(id), worker = workers.find(item => item.id === id)!; - git(worker.worktree, ['reset', '--hard', canonical]); - record.assignment = { ...record.assignment!, seedCommit: canonical }; - expect(record.task.dependsOn).toEqual([]); - const target = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(target, fs.readFileSync(target, 'utf8').replace('end Tutorial', - `lemma batch_${id} : True := by\n have h : 1 + 0 = 1 := ${id}_chain 1\n trivial\nend Tutorial`)); - const commit = commitSolverSources(problem, worker.worktree); - const proof = await (cooperative as any).check(record.task, record.assignment, worker.worktree, commit); - expect(proof.passed).toBe(true); - proofs.push(proof); Object.assign(record, { status: 'delivered', proof }); - } - expect(canonicalSource()).not.toContain('lemma batch_'); - expect(missingContexts).toEqual([]); - host.verify.mockClear(); receipts = []; - - await integrate(); - - expect(missingContexts).toEqual([]); - expect(calls()).toHaveLength(1); - expect(calls()[0]!.items.map(item => item.theoremName).sort()).toEqual(['Tutorial.batch_first', 'Tutorial.batch_second']); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('integrated'); - expect(node().proof).toBe(proofs[0]); expect(node('second').proof).toBe(proofs[1]); - expect(events.filter(item => item.event === 'task_integration_batch_started')).toHaveLength(1); - expect(events.some(item => item.event === 'task_integration_batch_fallback')).toBe(false); - expect(canonicalSource()).toContain('lemma batch_first'); expect(canonicalSource()).toContain('lemma batch_second'); - expect(canonicalSource()).toContain(chains); - expectNoFailure(); - }); - - it('preserves a batched peer\'s incremental and direct metadata while publishing its knowledge once', async () => { - const first = node(), second = node('second'), firstWorker = workers[1]!, secondWorker = workers[2]!; - const firstAction: Extract = { kind: 'task', task: first.task, assignment: first.assignment! }; - const secondAction: typeof firstAction = { kind: 'task', task: second.task, assignment: second.assignment! }; - const knowledge = { digest: 'batch-pinned-catalog', base: { entries: [{ id: 'saved-theorem' }] } } as KnowledgeContextSnapshot; - for (const value of access.values()) value.environment = { PATH: '/usr/bin:/bin', ELAN_HOME: '', LEAN_PATH: '', LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - access.get(secondWorker.id)!.knowledgeSnapshot = knowledge; - fs.writeFileSync(path.join(secondWorker.worktree, 'RESEARCH.md'), JSON.stringify({ summary: 'Second helper with selected experience.', - knowledgeUses: [{ id: 'saved-theorem', catalogDigest: knowledge.digest, - declaration: { name: 'Tutorial.batch_second', file: 'Submission.lean' }, - application: { expression: 'True.intro', expectedType: 'True', - context: { file: 'Submission.lean', declaration: second.task.theoremName } } }] })); - const firstCommit = writeLemma(firstWorker, 'lemma batch_first : True := by trivial'); - const secondCommit = writeLemma(secondWorker, 'lemma batch_second : True := by trivial'); - const artifacts = captureDeliveryArtifacts({ problem, worktree: secondWorker.worktree, commit: secondCommit, assignment: second.assignment! }); - type DiagnosticInput = Parameters[0]; - host.check.mockImplementation(async (input: DiagnosticInput) => { - const files = [...mathLocalModuleBuildOrder(input.projectRoot, input.file).map(module => module.file), - ...LAKE_CONFIGURATION_FILES.filter(file => fs.existsSync(path.join(input.projectRoot, file)))] - .map(file => ({ file, digest: mathDigest(fs.readFileSync(path.join(input.projectRoot, file))) })); - const contents = canonicalMathJson({ files, expression: input.expression, type: input.type }); - const artifact = { path: '.lake/batch-knowledge-application.json', digest: mathDigest(contents) }; - fs.mkdirSync(path.join(input.projectRoot, '.lake'), { recursive: true }); - fs.writeFileSync(path.join(input.projectRoot, artifact.path), contents); - return { status: 'elaborated', exitCode: 0, timedOut: false, sourceFiles: files, artifact, - sourceSnapshotDigest: mathDigest(canonicalMathJson(files)), projectionDigest: mathDigest('batch-application-projection'), - environment: host.identity(), type: input.type, constants: ['True.intro'], stdout: '', stderr: '' }; - }); - const firstCheck = deferred(), secondCheck = deferred(); - const firstEntered = deferred(), secondEntered = deferred(); - const checking = new Set(); - host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { - const name = request.items.length === 1 ? request.items[0]!.theoremName : undefined; - if (name && name === first.task.theoremName && !checking.has(name)) { - checking.add(name); firstEntered.resolve(request); return firstCheck.promise; - } - if (name && name === second.task.theoremName && !checking.has(name)) { - checking.add(name); secondEntered.resolve(request); return secondCheck.promise; - } - return Promise.resolve(verified(request)); - }); - releases.push(() => { - const firstRequest = calls().find(request => request.items.length === 1 && request.items[0]!.theoremName === first.task.theoremName); - const secondRequest = calls().find(request => request.items.length === 1 && request.items[0]!.theoremName === second.task.theoremName); - if (firstRequest) firstCheck.resolve(verified(firstRequest)); - if (secondRequest) secondCheck.resolve(verified(secondRequest)); - }); - const log = path.join(secondWorker.worktree, assignmentDeliveryFile(second.assignment!)); - fs.writeFileSync(log, JSON.stringify({ id: 'incremental-second', kind: 'proof', commit: secondCommit, - summary: 'Second helper incremental evidence.', evidenceRefs: ['second-evidence-reference'] }) + '\n'); - state.workers = workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, - phase: 'running', turns: 0 })); - const canonical = deferred(), releaseCanonical = () => canonical.resolve(); - releases.push(releaseCanonical); - const heldCanonical = track((cooperative as any).queueIntegration(() => canonical.promise)); - cooperative.activate(secondWorker, secondAction, async () => {}, async () => {}); - const incremental = track(cooperative.pulse(secondWorker.id)); - const secondRequest = await secondEntered.promise; - const direct = track(cooperative.deliver(secondWorker, secondAction, secondCommit)); - const firstDelivery = track(cooperative.deliver(firstWorker, firstAction, firstCommit)); - const firstRequest = await firstEntered.promise; - // Queue the first worker before the incremental peer, then let the real queue integrate the ready pair. - firstCheck.resolve(verified(firstRequest)); - await vi.waitFor(() => expect(state.workers!.find(worker => worker.id === firstWorker.id)?.scheduling?.wait?.stage) - .toBe('integration-queue')); - secondCheck.resolve(verified(secondRequest)); - await vi.waitFor(() => expect(state.workers!.find(worker => worker.id === secondWorker.id)?.scheduling?.wait?.stage) - .toBe('integration-queue')); - releaseCanonical(); - await Promise.all([heldCanonical, firstDelivery, incremental, direct]); - - expect(calls().map(request => request.items.length)).toEqual([1, 1, 2]); - expect(events.filter(item => item.event === 'task_integration_batch_started').map(item => item.details?.taskIds)) - .toEqual([['first', 'second']]); - expect(canonicalSource()).toContain('lemma batch_first : True := by trivial'); - expect(canonicalSource()).toContain('lemma batch_second : True := by trivial'); - const records = () => state.cooperation!.deliveries?.filter(item => item.kind === 'proof' && item.taskId === second.task.id) ?? []; - expect(records()).toHaveLength(1); - expect(records()[0]).toMatchObject({ status: 'verified', submissionId: 'incremental-second', - assignmentKey: assignmentDeliveryFile(second.assignment!), artifacts, evidenceRefs: ['second-evidence-reference'], - knowledgeUses: [{ consumer: { taskId: second.task.id, taskDigest: taskVersion(second.task) }, - application: { check: { status: 'elaborated', proofAcceptance: 'not-assessed' } } }] }); - expect(host.check).toHaveBeenCalledTimes(1); - expect(events.filter(item => item.event === 'knowledge_use_observed' && item.details?.taskId === second.task.id)).toHaveLength(1); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.taskId === second.task.id)).toHaveLength(1); - const queueStarts = events.flatMap((item, index) => item.event === 'integration_queue_started' ? [index] : []); - expect(queueStarts).toHaveLength(3); - // The first operation publishes its batched peer before that peer's own canonical turn. - expect(events.findIndex(item => item.event === 'delivery_published' && item.details?.taskId === second.task.id)).toBeLessThan(queueStarts[2]!); - - await track(cooperative.pulse(secondWorker.id)); - await track(cooperative.deliver(secondWorker, secondAction, secondCommit)); - - expect(records()).toHaveLength(1); expect(host.check).toHaveBeenCalledTimes(1); - expect(events.filter(item => item.event === 'knowledge_use_observed' && item.details?.taskId === second.task.id)).toHaveLength(1); - expect(state.cooperation!.cursors?.[`${secondWorker.id}/${assignmentDeliveryFile(second.assignment!)}`]).toBe(fs.statSync(log).size); - expectNoFailure(); - }); - - it.each(['different-group', 'paused', 'dependency', 'unchecked'] as const) - ('excludes a %s candidate from the ready batch', async exclusion => { - if (exclusion === 'different-group') { - changeTask('second', { groupId: 'other' }); - state.cooperation!.groups!.push({ group: { id: 'other', objective: 'Other route.', status: 'active', revision: 0 }, turns: 0 }); - } else if (exclusion === 'dependency') { - changeTask('second', { dependsOn: ['first'] }); - node('second').assignment!.dependencies = [{ taskId: 'first', taskDigest: taskVersion(node().task) }]; - } - await preparePair(); - if (exclusion === 'paused') changeTask('second', { status: 'paused' }); - if (exclusion === 'unchecked') node('second').proof = structuredClone(node('second').proof); - - await integrate(); - - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(1); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('delivered'); - expect(canonicalSource()).toContain('lemma batch_first'); expect(canonicalSource()).not.toContain('lemma batch_second'); - }); - - it('keeps overlapping declaration changes in individual integrations', async () => { - await prepare('first', 'lemma shared_helper : True := by trivial\nlemma batch_first : True := by trivial'); - await prepare('second', 'lemma shared_helper : True := by trivial\nlemma batch_second : True := by trivial'); - host.verify.mockClear(); receipts = []; - - await integrate(); - - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(1); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('delivered'); - await drain(); - expect(calls()).toHaveLength(2); expect(calls().every(request => request.items.length === 1)).toBe(true); - expect(node('second').status).toBe('integrated'); expectNoFailure(); - }); - - it('checks individual trees when two targets require different complete source projections', async () => { - // The mock kernel permits this source so the host's projection grouping is exercised independently. - await prepare('first', 'lemma batch_first : True := by have _ := Tutorial.add_zero; trivial'); - await prepare('second'); - host.verify.mockClear(); receipts = []; - - await integrate(); - - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(1); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('delivered'); - expect(node().integratedCheck!.verification.results).toHaveLength(1); - }); - - it('preserves a custom M2 checker instead of replacing it with the default batch verifier', async () => { - await preparePair(); - const original = directSolverModules.M2.checkTask; - const custom = vi.fn((...args: Parameters) => original(...args)); - (cooperative as any).input.modules = { ...directSolverModules, M2: { ...directSolverModules.M2, checkTask: custom } }; - - await integrate(); - - expect(custom).toHaveBeenCalledTimes(1); - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(1); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('delivered'); - }); - - it('falls back to individual fresh trees after a mixed deterministic batch failure', async () => { - await preparePair(); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - if (request.items.length === 1) return batch; - batch.status = 'failed'; - batch.results[1] = { ...batch.results[1]!, status: 'failed', error: 'Lean exited with status 1.', - stdoutPreview: 'Submission.lean:3:1: error: Fixture failure only in the combined projection.' }; - return batch; - }); - - await integrate(); await drain(); - - expect(calls().map(request => request.items.length)).toEqual([2, 1, 1]); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('integrated'); - expect(node().integratedCheck!.verification.sessionId).not.toBe(receipts[0]!.sessionId); - expect(node('second').integratedCheck!.verification.sessionId).not.toBe(receipts[0]!.sessionId); - expect(node().integratedCheck!.verification.targetCommit).not.toBe(receipts[0]!.targetCommit); - expectNoFailure(); - }); - - it.each([true, false])('checks the untouched canonical conflict and still integrates an independent task (canonical passed: %s)', async canonicalPassed => { - await preparePair(); - const canonical = writeLemma(workers[3]!, 'lemma batch_first : True := by exact True.intro'); - state.cooperation!.canonicalCommit = canonical; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - if (!canonicalPassed && request.items.some(item => item.theoremName === 'Tutorial.batch_first')) { - batch.status = 'failed'; - batch.results = batch.results.map(item => ({ ...item, status: 'failed', error: 'Lean exited with status 1.', - stdoutPreview: 'Submission.lean:3:1: error: Fixture canonical proof rejection.' })); - } - return batch; - }); - - await integrate(); await drain(); - - expect(node().status).toBe(canonicalPassed ? 'integrated' : 'blocked'); - expect(node('second').status).toBe('integrated'); - expect(calls().map(request => request.items.map(item => item.theoremName))) - .toEqual([['Tutorial.batch_first'], ['Tutorial.batch_second']]); - const firstSource = committedSource(workspace, calls()[0]!.targetCommit!, `${problem.projectRelative}/Submission.lean`); - expect(firstSource).toContain('lemma batch_first : True := by exact True.intro'); - expect(firstSource).not.toContain('lemma batch_first : True := by trivial'); - if (canonicalPassed) expect(node().integratedCheck).toMatchObject({ passed: true, commit: canonical, - seedCommit: canonical, taskDigest: taskVersion(node().task), changes: [] }); - else { - expect(node().integratedCheck).toBeUndefined(); - expect(node().feedback).toContain('math_task_integration_conflict'); - } - expect(canonicalSource()).toContain('lemma batch_first : True := by exact True.intro'); - expect(canonicalSource()).toContain('lemma batch_second : True := by trivial'); - }); - - it('does not repeat a failed mathematical batch for the same canonical and checked inputs', async () => { - await preparePair(); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - batch.status = 'failed'; - batch.results = batch.results.map(item => ({ ...item, status: 'failed', error: 'Lean exited with status 1.', - stdoutPreview: 'Submission.lean:3:1: error: Fixture deterministic check failure.' })); - return batch; - }); - await integrate(); - expect(node().status).toBe('blocked'); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - Object.assign(node(), { status: 'delivered', feedback: undefined, integratedCheck: undefined }); - - await integrate(); - - expect(calls().map(request => request.items.length)).toEqual([2, 1, 1]); - expect(node().status).toBe('blocked'); expect(node('second').status).toBe('delivered'); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - }); - - it('falls back when Lean reveals that a batch member actually uses another batch member', async () => { - await preparePair(); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - if (request.items.length > 1) batch.results[0] = { ...batch.results[0]!, declarationReferences: { - statement: [], proof: [{ name: 'Tutorial.batch_second', file: 'Submission.lean' }], - } }; - return batch; - }); - - await integrate(); await drain(); - - expect(calls().map(request => request.items.length)).toEqual([2, 1, 1]); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('integrated'); - expect(node().integratedCheck!.verification.sessionId).not.toBe(receipts[0]!.sessionId); - expect(node('second').integratedCheck!.verification.sessionId).not.toBe(receipts[0]!.sessionId); - expectNoFailure(); - }); - - it('discards the entire pending union after a concurrent task revision', async () => { - await preparePair(); - const gate = gateBatch(), operation = integrate(); await gate.entered; - const revised = node('second'); - revised.task = { ...revised.task, revision: revised.task.revision + 1, type: 'True ∧ True' }; - revised.status = 'pending'; delete revised.proof; delete revised.assignment; - (cooperative as any).changed(); - - gate.release(); await operation; - - expect(node('second')).toBe(revised); expect(node('second').integratedCheck).toBeUndefined(); - expect(canonicalSource()).not.toContain('lemma batch_second'); - expect(node().integratedCheck?.verification.sessionId).not.toBe(receipts[0]!.sessionId); - expectNoFailure(); - }); - - it('rechecks the complete pair after canonical advancement and preserves the added declaration', async () => { - await preparePair(); - const gate = gateBatch(), operation = integrate(), original = await gate.entered; - const advanced = writeLemma(workers[3]!, 'lemma independent_lemma : True := by trivial'); - state.cooperation!.canonicalCommit = advanced; (cooperative as any).changed(); - - gate.release(); await operation; - - expect(calls().map(request => request.items.length)).toEqual([2, 2]); - expect(calls()[1]!.targetCommit).not.toBe(original.targetCommit); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('integrated'); - expect(canonicalSource()).toContain('lemma independent_lemma : True := by trivial'); - expect(canonicalSource()).toContain('lemma batch_first'); expect(canonicalSource()).toContain('lemma batch_second'); - expectNoFailure(); - }); - - it.each(['pause', 'maxConcurrent'] as const) - ('discards the pending shared receipt after a concurrent group %s edit', async control => { - await preparePair(); - const gate = gateBatch(), operation = integrate(); await gate.entered; - const group = state.cooperation!.groups![0]!; - group.group = control === 'pause' ? { ...group.group, status: 'paused' } : { ...group.group, maxConcurrent: 2 }; - (cooperative as any).changed(); - - gate.release(); await operation; - - if (control === 'pause') { - expect(calls().map(request => request.items.length)).toEqual([2]); - expect(node().status).toBe('delivered'); expect(node('second').status).toBe('delivered'); - expect(node().integratedCheck).toBeUndefined(); expect(node('second').integratedCheck).toBeUndefined(); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - } else { - expect(calls().map(request => request.items.length)).toEqual([2, 2]); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('integrated'); - expect(node().integratedCheck!.verification.sessionId).not.toBe(receipts[0]!.sessionId); - expect(node('second').integratedCheck!.verification.sessionId).not.toBe(receipts[0]!.sessionId); - } - expectNoFailure(); - }); - - it.each(['unavailable', 'abort', 'storage', 'cleanup', 'corrupt-receipt'] as const) - ('propagates a batch %s fault without expanding it into per-task verifier retries', async failure => { - const proofs = await preparePair(); - const error = failure === 'abort' ? new DOMException('Fixture aborted.', 'AbortError') : failure === 'storage' - ? Object.assign(new Error('Fixture storage failure.'), { code: 'EIO' }) : new Error('math_verifier_unavailable'); - failVerifier(failure, error, 'EIO removing scratch directory.'); - - await expect(integrate()).rejects.toBeInstanceOf(Error); - - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(2); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(node().status).toBe('delivered'); expect(node('second').status).toBe('delivered'); - expect(node().proof).toBe(proofs[0]); expect(node('second').proof).toBe(proofs[1]); - expect(node().integratedCheck).toBeUndefined(); expect(node('second').integratedCheck).toBeUndefined(); - expectNoFailure(); - }); - - it.each(['passed', 'failed', 'unavailable'] as const) - ('discards a stale shared recheck after its %s result settles without per-task retries', async outcome => { - await preparePair(); await integrate(); - const canonical = state.cooperation!.canonicalCommit!, tasks = structuredClone(state.cooperation!.tasks); - const before = structuredClone(tasks), accepted = structuredClone(state.cooperation!.tasks); - host.verify.mockClear(); receipts = []; events = []; - const gate = gateBatch(request => { - const batch = verified(request); - if (outcome !== 'passed') { - batch.status = outcome === 'failed' ? 'failed' : 'unavailable'; - batch.results = batch.results.map(item => ({ ...item, status: batch.status, - error: outcome === 'failed' ? 'Lean exited with status 1.' : 'math_verifier_unavailable', - ...(outcome === 'failed' ? { stdoutPreview: 'Submission.lean:3:1: error: unsolved goals' } : {}) })); - } - return batch; - }); - const check = vi.spyOn(cooperative as any, 'check'); - let current = true; - const rechecking = track((cooperative as any).recheckIntegrated(canonical, false, { - tasks, ids: new Set(['first', 'second']), environment: {}, environmentDigest: state.environmentDigest, - current: () => current, - }) as Promise); - await gate.entered; current = false; gate.release(); - - if (outcome === 'unavailable') await expect(rechecking).rejects.toThrow('math_verifier_unavailable'); - else await expect(rechecking).resolves.toBe(false); - - expect(calls().map(request => request.items.length)).toEqual([2]); - expect(check).not.toHaveBeenCalled(); - expect(tasks).toEqual(before); expect(state.cooperation!.tasks).toEqual(accepted); - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect(events.some(item => ['task_recheck_batch_fallback', 'task_recheck_finished'].includes(item.event))).toBe(false); - expectNoFailure(); - }); - - it.each(['unavailable', 'abort', 'storage', 'cleanup', 'corrupt-receipt'] as const) - ('preserves restored accepted tasks after a shared recheck %s fault without per-task retries', async failure => { - await preparePair(); await integrate(); - const canonical = state.cooperation!.canonicalCommit!; - for (const record of [node(), node('second')]) { - record.proof = structuredClone(record.proof); - record.integratedCheck = structuredClone(record.integratedCheck); - } - const before = [node(), node('second')].map(record => structuredClone(record)); - host.verify.mockClear(); receipts = []; - const error = failure === 'abort' ? new DOMException('Fixture recheck interrupted.', 'AbortError') : failure === 'storage' - ? Object.assign(new Error('Fixture recheck storage failure.'), { code: 'EIO' }) : new Error('math_verifier_unavailable'); - failVerifier(failure, error, 'EIO removing recheck checkout.'); - - await expect(track((cooperative as any).recheckIntegrated(canonical, false))).rejects.toBeInstanceOf(Error); - - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(2); - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect([node(), node('second')]).toEqual(before); - expectNoFailure(); - }); - - it.each(['corrupt-receipt', 'no-diagnostic-failure'] as const) - ('preserves a single checked delivery after a %s result instead of recording a mathematical blocker', async failure => { - const proofs = await preparePair(); - changeTask('second', { status: 'paused' }); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - if (failure === 'corrupt-receipt') batch.results = batch.results.map(item => ({ ...item, targetCommit: '0'.repeat(40) })); - else { - batch.status = 'failed'; - batch.results = batch.results.map(item => ({ ...item, status: 'failed', error: 'Verifier failed without a Lean diagnostic.' })); - } - return batch; - }); - - await expect(integrate()).rejects.toThrow('math_verifier_unavailable'); - - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(1); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(node().status).toBe('delivered'); expect(node().proof).toBe(proofs[0]); - expect(node().integratedCheck).toBeUndefined(); expect(node().feedback).toBeUndefined(); - expectNoFailure(); - }); - - it('keeps a bound real draft-source rejection available as mathematical feedback', async () => { - const record = node(), worker = workers.find(item => item.id === record.assignment!.workerId)!; - const commit = writeLemma(worker, 'lemma batch_first : True := by sorry'); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - expect(fs.readFileSync(path.join(request.projectRoot, request.items[0]!.proofPath), 'utf8')).toContain('by sorry'); - batch.status = 'failed'; - batch.results = batch.results.map(item => ({ ...item, status: 'failed', sorryCount: 1, admitCount: 0, - axioms: [], error: 'Proof source contains sorry or admit.' })); - return batch; - }); - - const delivered = await cooperative.deliver(worker, { kind: 'task', task: record.task, assignment: record.assignment! }, commit); - - expect(delivered.check?.passed).toBe(false); expect(record.status).toBe('pending'); - expect(record.feedback).toContain('Proof source contains sorry or admit.'); - expect(record.proof).toBe(delivered.check); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(state.cooperation!.deliveries?.filter(item => item.kind === 'proof')).toMatchObject([{ status: 'failed', commit }]); - expect(events).toContainEqual(expect.objectContaining({ event: 'task_repair_requested', - details: expect.objectContaining({ taskId: 'first', workerId: 'first' }) })); - expect(calls()).toHaveLength(1); expect(calls()[0]!.items).toHaveLength(1); - }); - - it.each([LEAN_MEMORY_LIMIT_ERROR, LEAN_STACK_LIMIT_ERROR]) - ('returns a single-target sandbox limit failure to its worker without aborting the run: %s', async error => { - const record = node(), worker = workers.find(item => item.id === record.assignment!.workerId)!; - const commit = writeLemma(worker, 'lemma batch_first : True := by trivial'); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - batch.status = 'failed'; - batch.results = batch.results.map(item => ({ ...item, status: 'failed', error })); - return batch; - }); - const action = { kind: 'task' as const, task: record.task, assignment: record.assignment! }; - - const delivered = await cooperative.deliver(worker, action, commit); - - expect(delivered.check?.passed).toBe(false); expect(record.status).toBe('pending'); - expect(record.feedback).toContain(error); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - // The same input is not rechecked; a later run cannot reach a different verdict under the same limits. - await expect((cooperative as any).check(record.task, record.assignment, worker.worktree, commit, undefined, undefined, true)) - .rejects.toThrow('math_task_repeated_failed_input'); - expect(calls()).toHaveLength(1); - }); - - it('integrates members separately after their merged check exhausts the sandbox memory limit', async () => { - await preparePair(); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = verified(request); - if (request.items.length > 1) { - batch.status = 'failed'; - batch.results = batch.results.map(item => ({ ...item, status: 'failed', error: LEAN_MEMORY_LIMIT_ERROR })); - } - return batch; - }); - - await integrate(); await drain(); - - expect(calls()[0]!.items).toHaveLength(2); - expect(calls().slice(1).every(request => request.items.length === 1)).toBe(true); - expect(events).toContainEqual(expect.objectContaining({ event: 'task_integration_batch_fallback', - details: expect.objectContaining({ reason: 'math_task_batch_resource_limit' }) })); - expect(node().status).toBe('integrated'); expect(node('second').status).toBe('integrated'); - expect(canonicalSource()).toContain('lemma batch_first'); expect(canonicalSource()).toContain('lemma batch_second'); - expectNoFailure(); - }); -}); diff --git a/tests/solverIntegrationConcurrency.test.ts b/tests/solverIntegrationConcurrency.test.ts deleted file mode 100644 index e53bb11b..00000000 --- a/tests/solverIntegrationConcurrency.test.ts +++ /dev/null @@ -1,516 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathematicsVerifierBatchRequest, MathematicsVerifierBatchResult } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => undefined, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const verified = (request: MathematicsVerifierBatchRequest) => - verifiedBatch(request, { sessionId: 'integration-concurrency-fixture', checks: true }); -const settled = (request: MathematicsVerifierBatchRequest, status: 'failed' | 'unavailable' | 'blocked'): MathematicsVerifierBatchResult => { - const batch = verified(request); - return status === 'failed' ? failedBatch(batch, { stdoutPreview: () => 'Submission.lean:3:1: error: Fixture merged proof failure.' }) - : { ...batch, status, results: batch.results.map(item => ({ ...item, status, error: 'Fixture merged check failure.' })) }; -}; -type TaskAction = Extract; -type Failure = 'abort' | 'storage' | 'unavailable'; -type EarlierTurn = 'transport-only' | 'consumed-repair'; - -describe('task integration with concurrent host control', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch, controller: AbortController, action: TaskAction; - let exclusive: (check: () => Promise) => Promise, lockHeld: boolean; - let pending: Promise[], releases: (() => void)[]; - let events: { event: string; details?: Record }[]; - - const node = () => state.cooperation!.tasks.find(item => item.task.id === action.task.id)!; - const records = () => state.cooperation!.deliveries ?? []; - const canonicalSource = () => committedSource(workspace, state.cooperation!.canonicalCommit!, - `${problem.projectRelative}/Submission.lean`); - const track = (promise: Promise) => { - pending.push(promise); void promise.catch(() => {}); return promise; - }; - const writeLemma = (worker: ResearchWorker, declaration: string) => { - const file = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', declaration + '\ntheorem add_zero')); - return commitSolverSources(problem, worker.worktree); - }; - const gateCheck = (call: number) => { - const entered = deferred(), result = deferred(); - let request: MathematicsVerifierBatchRequest | undefined, heldAtEntry: boolean | undefined, count = 0; - host.verify.mockImplementation(async (input: MathematicsVerifierBatchRequest) => { - if (++count !== call) return verified(input); - request = input; heldAtEntry = lockHeld; entered.resolve(input); return result.promise; - }); - const release = () => { if (request) result.resolve(verified(request)); }; - releases.push(release); - return { entered: entered.promise, release, fail: (error: unknown) => result.reject(error), - finish: (status: 'kernel_verified' | 'failed' | 'unavailable') => result.resolve(status === 'kernel_verified' - ? verified(request!) : settled(request!, status)), heldAtEntry: () => heldAtEntry }; - }; - const edit = (id: string, change: (task: CooperativeTask) => CooperativeTask, group = (value: object): object => value) => { - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id, baseVersion: state.cooperation!.planVersion, - tasks: state.cooperation!.tasks.map(item => change(item.task)), groups: state.cooperation!.groups!.map(item => group(item.group)), - }) + '\n'); - return track(cooperative.pulse(workers[0].id)); - }; - const expectNoMathematicalFailure = () => { - expect(records().filter(record => record.kind === 'failure' || record.status === 'failed')).toEqual([]); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(state.cooperation!.blockers ?? []).toEqual([]); - expect(events.filter(item => item.event === 'delivery_rejected')).toEqual([]); - }; - const startNextAuthorTurn = async () => { - const next = await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity }); - if (next?.kind !== 'task') throw new Error('fixture_expected_resumed_task'); - expect(next.assignment).toBe(action.assignment); - expect(cooperative.started(workers[1], next)).toBe(true); - action = next; - }; - const startSecondTurn = async (earlier: EarlierTurn) => { - if (earlier === 'transport-only') { - await cooperative.deliver(workers[1], action, problem.baseCommit, true, 'request-failure'); - expect(node().sourceRepair).toBeUndefined(); - expect(records()).toEqual([]); - } else { - cooperative.rejected(action, 'math_original_context_changed'); - expect(node().sourceRepair?.pending).toBe(true); - } - expect(node().status).toBe('pending'); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - await startNextAuthorTurn(); - expect(node()).toMatchObject({ status: 'running', attempts: 2 }); - if (earlier === 'consumed-repair') expect(node().sourceRepair?.pending).toBe(false); - expect(host.verify).not.toHaveBeenCalled(); - }; - const expectUnacceptedSourceRejection = (commit: string) => { - const rejected = records().filter(record => record.commit === commit); - expect(rejected.length).toBeGreaterThan(0); - for (const record of rejected) { - expect(record).toMatchObject({ kind: 'failure', status: 'failed' }); - expect(record.evidence).toBeUndefined(); - expect(record.actualReferences).toBeUndefined(); - } - for (const event of events.filter(item => item.event === 'delivery_published' && item.details?.commit === commit)) { - expect(event.details).toMatchObject({ kind: 'failure', status: 'failed' }); - expect(event.details?.receiptIds).toBeUndefined(); - } - }; - const finishRepairBudget = async (earlier: EarlierTurn, commit: string) => { - expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - const failure = state.cooperation!.failedTaskInputs![0]; - if (earlier === 'transport-only') { - expect(failure.repair?.pending).toBe(true); - const checked = host.verify.mock.calls.length; - await startNextAuthorTurn(); - expect(failure.repair?.pending).toBe(false); - await (cooperative as any).receive(workers[1], action, - { id: 'same-input-after-local-repair', kind: 'proof', commit, summary: 'The target is still missing.' }, true); - expect(host.verify).toHaveBeenCalledTimes(checked); - } else { - expect(node().sourceRepair?.pending).toBe(false); - expect(failure.repair).toBeUndefined(); - } - expect(node().status).toBe('blocked'); - expect(events.filter(item => item.event === 'task_repair_requested')).toHaveLength(1); - expectUnacceptedSourceRejection(commit); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('solver-integration-concurrency-'); - ({ directory, workspace, problem } = example); - workers = [leadWorker(problem, workspace), ...['author', 'independent'].map(id => peerWorker(example, id))]; - const task: CooperativeTask = { id: 'integration', kind: 'lemma', objective: 'Prove a reusable integration lemma.', - theoremName: 'Tutorial.integration_lemma', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - action = { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: workers[1].id, - seedCommit: problem.baseCommit, assignmentId: 'integration-dispatch', dependencies: [] } }; - state = solverState(problem, workspace, { runId: 'integration-concurrency-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [{ task, assignment: action.assignment, status: 'running', attempts: 1 }, ...problem.targets.map((target, index) => ({ - task: { id: `goal_${index}`, kind: 'goal' as const, objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: [], revision: 0, status: 'paused' as const }, - status: 'pending' as const, attempts: 0, - }))] } }); - events = []; pending = []; releases = []; lockHeld = false; controller = new AbortController(); - let queue = Promise.resolve(); - exclusive = async check => { - const previous = queue; - let release!: () => void; - queue = new Promise(resolve => { release = resolve; }); - await previous; lockHeld = true; - try { return await check(); } finally { lockHeld = false; release(); } - }; - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }), exclusiveCheck: check => exclusive(check) }); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - }); - afterEach(async () => { - for (const release of releases) release(); - controller.abort(); await Promise.allSettled(pending); await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['unavailable', 'blocked'] as const) - ('keeps an earlier passing delivery when a later candidate returns %s', async outcome => { - const firstCommit = writeLemma(workers[1], 'lemma integration_lemma : True := by trivial'); - const gate = gateCheck(2), first = track(cooperative.deliver(workers[1], action, firstCommit)); - await gate.entered; - const accepted = node().proof; - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true, commit: firstCommit } }); - const file = path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace( - 'lemma integration_lemma : True := by trivial', 'lemma integration_lemma : True := by exact True.intro')); - const laterCommit = commitSolverSources(problem, workers[1].worktree); - host.verify.mockImplementation(async request => settled(request, outcome)); - - await expect(track(cooperative.deliver(workers[1], action, laterCommit))).rejects.toThrow('math_verifier_unavailable'); - - expect(node().proof).toBe(accepted); - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true, commit: firstCommit } }); - expectNoMathematicalFailure(); - host.verify.mockImplementation(async request => verified(request)); - gate.release(); await first; - - expect(node().proof).toBe(accepted); - expect(node()).toMatchObject({ status: 'integrated', proof: { passed: true, commit: firstCommit }, integratedCheck: { passed: true } }); - expect(canonicalSource()).toContain('lemma integration_lemma : True := by trivial'); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ status: 'verified', commit: node().integratedCheck!.commit }]); - expect(records().some(record => record.commit === laterCommit)).toBe(false); - expectNoMathematicalFailure(); - }); - - it.each(['transport-only', 'consumed-repair'] as const) - ('does not publish an obsolete successful proof as failed after another submission is rejected (earlier: %s)', async earlier => { - await startSecondTurn(earlier); - const declaration = 'lemma integration_lemma : True := by trivial'; - const firstCommit = writeLemma(workers[1], declaration); - const gate = gateCheck(2), first = track(cooperative.deliver(workers[1], action, firstCommit)); - await gate.entered; - const accepted = node().proof; - expect(accepted?.passed).toBe(true); - const file = path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(declaration + '\n', '')); - const laterCommit = commitSolverSources(problem, workers[1].worktree); - - await (cooperative as any).receive(workers[1], action, - { id: 'later-missing-target', kind: 'proof', commit: laterCommit, summary: 'The new candidate is ready.' }, true); - - expect(node().status).toBe(earlier === 'consumed-repair' ? 'blocked' : 'pending'); - expect(node().proof).toBe(accepted); - expect(state.cooperation!.failedTaskInputs).toEqual([expect.objectContaining({ - taskId: action.task.id, targetDigest: 'declaration-count:0', feedback: expect.stringContaining('math_task_missing_declaration'), - })]); - const failure = records().find(record => record.kind === 'failure' && record.commit === laterCommit); - expect(failure).toMatchObject({ status: 'failed', summary: expect.stringContaining('math_task_missing_declaration') }); - expectUnacceptedSourceRejection(laterCommit); - gate.release(); await first; - - expect(node().proof).toBe(accepted); - expect(node().integratedCheck).toBeUndefined(); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(records().filter(record => record.kind === 'proof')).toEqual([]); - expect(events.filter(item => item.event === 'task_integrated')).toEqual([]); - expect(records()).toContain(failure); - expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - await (cooperative as any).publishProofDelivery(node()); - expect(records().filter(record => record.kind === 'proof')).toEqual([]); - await finishRepairBudget(earlier, laterCommit); - expect(node().integratedCheck).toBeUndefined(); - expect(records().filter(record => record.kind === 'proof')).toEqual([]); - }); - - it.each(['transport-only', 'consumed-repair'] as const) - ('does not reuse a later rejection when publication waits after a successful integration (earlier: %s)', async earlier => { - await startSecondTurn(earlier); - const declaration = 'lemma integration_lemma : True := by trivial'; - const firstCommit = writeLemma(workers[1], declaration); - const entered = deferred(), released = deferred(); - releases.push(() => released.resolve()); - const publish = (cooperative as any).publishProofDelivery.bind(cooperative); - vi.spyOn(cooperative as any, 'publishProofDelivery').mockImplementationOnce(async (...args: unknown[]) => { - entered.resolve(); await released.promise; - return publish(...args); - }); - const first = track(cooperative.deliver(workers[1], action, firstCommit)); - await entered.promise; - expect(node()).toMatchObject({ status: 'integrated', proof: { passed: true, commit: firstCommit }, integratedCheck: { passed: true } }); - const accepted = node().proof, integrated = node().integratedCheck, canonical = state.cooperation!.canonicalCommit; - const file = path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(declaration + '\n', '')); - const laterCommit = commitSolverSources(problem, workers[1].worktree); - - await (cooperative as any).receive(workers[1], action, - { id: 'missing-target-before-publication', kind: 'proof', commit: laterCommit, summary: 'The new candidate is ready.' }, true); - - expect(node().status).toBe(earlier === 'consumed-repair' ? 'blocked' : 'pending'); - expect(node().proof).toBe(accepted); - expectUnacceptedSourceRejection(laterCommit); - released.resolve(); await first; - - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect(node().integratedCheck).toBe(integrated); - expect(canonicalSource()).toContain(declaration); - expect(records().filter(record => record.kind === 'proof' && record.commit === firstCommit)).toEqual([]); - expect(records().filter(record => record.kind === 'failure' && record.commit === laterCommit)).toMatchObject([ - { status: 'failed', commit: laterCommit, summary: expect.stringContaining('math_task_missing_declaration') }, - ]); - await finishRepairBudget(earlier, laterCommit); - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect(node().integratedCheck).toBe(integrated); - expect(records().filter(record => record.kind === 'proof')).toEqual([]); - expect(events.filter(item => item.event === 'task_integrated')).toHaveLength(1); - }); - - it.each(['transport-only', 'consumed-repair'] as const) - ('keeps a merged failure distinct from a later source rejection during publication (earlier: %s)', async earlier => { - await startSecondTurn(earlier); - const declaration = 'lemma integration_lemma : True := by trivial'; - const firstCommit = writeLemma(workers[1], declaration); - const gate = gateCheck(2), first = track(cooperative.deliver(workers[1], action, firstCommit)); - await gate.entered; - const entered = deferred(), released = deferred(); - releases.push(() => released.resolve()); - const publish = (cooperative as any).publishProofDelivery.bind(cooperative); - vi.spyOn(cooperative as any, 'publishProofDelivery').mockImplementationOnce(async (...args: unknown[]) => { - entered.resolve(); await released.promise; - return publish(...args); - }); - gate.finish('failed'); await entered.promise; - const accepted = node().proof, mergedFailure = node().integratedCheck; - expect(node()).toMatchObject({ status: 'blocked', proof: { passed: true, commit: firstCommit }, - integratedCheck: { passed: false }, feedback: expect.stringContaining('math_task_merged_proof_failed') }); - const file = path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(declaration + '\n', '')); - const laterCommit = commitSolverSources(problem, workers[1].worktree); - - await (cooperative as any).receive(workers[1], action, - { id: 'missing-target-after-merged-failure', kind: 'proof', commit: laterCommit, summary: 'The new candidate is ready.' }, true); - - expect(node().feedback).toContain('math_task_missing_declaration'); - expect(node().status).toBe(earlier === 'consumed-repair' ? 'blocked' : 'pending'); - expect(node().proof).toBe(accepted); - expect(node().integratedCheck).toBe(mergedFailure); - expectUnacceptedSourceRejection(laterCommit); - released.resolve(); await first; - - const proofFailures = () => records().filter(record => record.kind === 'proof' && record.commit === firstCommit); - if (earlier === 'consumed-repair') { - expect(proofFailures()).toMatchObject([{ status: 'failed', summary: expect.stringContaining('math_task_merged_proof_failed') }]); - expect(proofFailures()[0].summary).toContain('Fixture merged proof failure.'); - expect(proofFailures()[0].summary).not.toContain('math_task_missing_declaration'); - expect(proofFailures()[0].evidence?.verification.targetCommit).toBe(accepted!.verification.targetCommit); - expect(proofFailures()[0].evidence?.verification.results).toEqual( - accepted!.verification.results.map(({ receiptId }) => ({ receiptId }))); - } else expect(proofFailures()).toEqual([]); - const failures = [...proofFailures()]; - expect(records().filter(record => record.kind === 'failure' && record.commit === laterCommit)).toMatchObject([ - { status: 'failed', commit: laterCommit, summary: expect.stringContaining('math_task_missing_declaration') }, - ]); - expect(state.cooperation!.failedTaskInputs).toHaveLength(1); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - - await (cooperative as any).publishProofDelivery(node()); - expect(proofFailures()).toEqual(failures); - await finishRepairBudget(earlier, laterCommit); - await (cooperative as any).publishProofDelivery(node()); - expect(proofFailures()).toEqual(failures); - expect(node().proof).toBe(accepted); - expect(node().integratedCheck).toBe(mergedFailure); - expect(records().some(record => record.kind === 'proof' && record.status === 'verified')).toBe(false); - expect(events.filter(item => item.event === 'task_integrated')).toEqual([]); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - }); - - it.each([ - { change: 'pause', verdict: 'kernel_verified' }, { change: 'pause', verdict: 'failed' }, - { change: 'revise', verdict: 'kernel_verified' }, { change: 'revise', verdict: 'failed' }, - ] as const)('applies a $change edit before the pending merged $verdict check finishes and discards its stale result', async ({ change, verdict }) => { - const commit = writeLemma(workers[1], 'lemma integration_lemma : True := by trivial'); - const gate = gateCheck(2), delivery = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true, commit } }); - const checked = node().proof; - - let applied = false; - const pulse = edit('control-during-merge', task => task.id !== action.task.id ? task : change === 'pause' - ? { ...task, status: 'paused' } : { ...task, revision: task.revision + 1, type: 'True ∧ True' }); - void pulse.then(() => { applied = true; }); - await vi.waitFor(() => { - expect(state.cooperation!.edits).toContainEqual(expect.objectContaining({ id: 'control-during-merge', status: 'applied' })); - expect(applied).toBe(true); - }); - expect(gate.heldAtEntry()).toBe(false); - expect(cooperative.current(action)).toBe(false); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - const current = node(), snapshot = JSON.parse(JSON.stringify(current)); - - gate.finish(verdict); await delivery; - - expect(node()).toBe(current); - expect(node()).toEqual(snapshot); - expect(node().integratedCheck).toBeUndefined(); - if (change === 'pause') expect(node().proof).toBe(checked); - else expect(node().proof).toBeUndefined(); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(canonicalSource()).not.toContain('lemma integration_lemma'); - expect(records().filter(record => record.kind === 'proof' && ['verified', 'failed'].includes(record.status))).toEqual([]); - expect(events.filter(item => item.event === 'task_integrated')).toEqual([]); - expectNoMathematicalFailure(); - }); - - it.each(['maxConcurrent', 'maxTurns'] as const) - ('rechecks a delivered proof after a concurrent group %s control change without publishing a failure', async control => { - const commit = writeLemma(workers[1], 'lemma integration_lemma : True := by trivial'); - const gate = gateCheck(2), delivery = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - const delivered = node(), checked = delivered.proof; - const editId = `group-${control}-during-merge`; - let applied = false; - const pulse = edit(editId, task => task, group => ({ ...group, [control]: 2 })); - void pulse.then(() => { applied = true; }); - await vi.waitFor(() => { - expect(state.cooperation!.edits).toContainEqual(expect.objectContaining({ id: editId, status: 'applied' })); - expect(applied).toBe(true); - }); - expect(gate.heldAtEntry()).toBe(false); - expect(cooperative.current(action)).toBe(true); - expect(node()).toBe(delivered); - expect(node().proof).toBe(checked); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expectNoMathematicalFailure(); - - gate.release(); await delivery; - - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(node().proof).toBe(checked); - expect(canonicalSource()).toContain('lemma integration_lemma : True := by trivial'); - expect(host.verify).toHaveBeenCalledTimes(3); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([ - { taskId: action.task.id, status: 'verified', commit: node().integratedCheck!.commit }, - ]); - expect(events.filter(item => item.event === 'task_integrated')).toHaveLength(1); - expect(events.find(item => item.event === 'task_integrated')?.details).toMatchObject({ - taskId: action.task.id, taskDigest: action.assignment.taskDigest, workerId: action.assignment.workerId, - assignmentKey: assignmentDeliveryFile(action.assignment), seedCommit: action.assignment.seedCommit, - commit: node().integratedCheck!.commit, sourceDigest: node().integratedCheck!.sourceDigest, - receiptIds: node().integratedCheck!.verification.results.map(result => result.receiptId), - }); - expectNoMathematicalFailure(); - }); - - it('remerges and rechecks after canonical advancement without losing an independent declaration', async () => { - const commit = writeLemma(workers[1], 'lemma integration_lemma : True := by trivial'); - const gate = gateCheck(2), delivery = track(cooperative.deliver(workers[1], action, commit)); - const originalMerged = await gate.entered; - // This independent source checkpoint is not represented as a checked task or accepted proof. - const independent = writeLemma(workers[2], 'lemma independent_lemma : True := by trivial'); - let advanced = false; - const advance = track(exclusive(async () => { - state.cooperation!.canonicalCommit = independent; (cooperative as any).changed(); advanced = true; - })); - await vi.waitFor(() => expect(advanced).toBe(true)); await advance; - expect(gate.heldAtEntry()).toBe(false); - expect(canonicalSource()).toContain('lemma independent_lemma : True := by trivial'); - - gate.release(); await delivery; - - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(state.cooperation!.canonicalCommit).not.toBe(independent); - expect(canonicalSource()).toContain('lemma integration_lemma : True := by trivial'); - expect(canonicalSource()).toContain('lemma independent_lemma : True := by trivial'); - expect(host.verify).toHaveBeenCalledTimes(3); - expect(host.verify.mock.calls[2][0].targetCommit).not.toBe(originalMerged.targetCommit); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([ - { taskId: action.task.id, status: 'verified', commit: node().integratedCheck!.commit }, - ]); - expectNoMathematicalFailure(); - }); - - it('shares an in-flight exact proof delivery so concurrent duplicates do not repeat verification', async () => { - const commit = writeLemma(workers[1], 'lemma integration_lemma : True := by trivial'); - const gate = gateCheck(1), first = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - const duplicate = track(cooperative.deliver(workers[1], action, commit)); - await Promise.resolve(); await Promise.resolve(); - expect(host.verify).toHaveBeenCalledTimes(1); - - gate.release(); await Promise.all([first, duplicate]); - await cooperative.deliver(workers[1], action, commit); - - expect(node()).toMatchObject({ status: 'integrated', proof: { passed: true, commit }, integratedCheck: { passed: true } }); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([ - { taskId: action.task.id, status: 'verified', commit: node().integratedCheck!.commit }, - ]); - expect(events.filter(item => item.event === 'task_integrated')).toHaveLength(1); - expectNoMathematicalFailure(); - }); - - it('records a worker waiting on the real canonical integration queue and clears it on entry', async () => { - state.workers = workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, - phase: 'running', turns: 0 })); - const held = deferred(), release = () => held.resolve(); releases.push(release); - const first = track((cooperative as any).queueIntegration(() => held.promise)); - const commit = writeLemma(workers[1], 'lemma integration_lemma : True := by trivial'); - const delivery = track(cooperative.deliver(workers[1], action, commit)); - const worker = state.workers[1]; - await vi.waitFor(() => expect(worker.scheduling?.wait).toMatchObject({ stage: 'integration-queue', - candidates: [{ taskId: action.task.id, reason: 'integration-queue' }] })); - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true } }); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - release(); await Promise.all([first, delivery]); - expect(worker.scheduling?.wait).toBeUndefined(); - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(events.some(item => item.event === 'dispatch_wait_ended' && item.details?.stage === 'integration-queue')).toBe(true); - }); - - it.each(['abort', 'storage', 'unavailable'] as const) - ('retains the checked delivery after a merged %s fault and retries only integration', async (failure: Failure) => { - const commit = writeLemma(workers[1], 'lemma integration_lemma : True := by trivial'); - const gate = gateCheck(2), delivery = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - const checked = node().proof; - const error = failure === 'abort' ? new DOMException('Merged check interrupted.', 'AbortError') : - failure === 'storage' ? Object.assign(new Error('Transient integration storage failure.'), { code: 'EIO' }) : - new Error('math_verifier_unavailable'); - if (failure === 'unavailable') gate.finish('unavailable'); - else gate.fail(error); - - await expect(delivery).rejects.toMatchObject({ name: error.name, message: error.message }); - - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true, commit } }); - expect(node().proof).toBe(checked); - expect(node().integratedCheck).toBeUndefined(); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(records()).toEqual([]); - expectNoMathematicalFailure(); - - await cooperative.deliver(workers[1], action, commit); - - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(node().proof).toBe(checked); - expect(host.verify).toHaveBeenCalledTimes(3); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ status: 'verified', commit: node().integratedCheck!.commit }]); - expectNoMathematicalFailure(); - }); -}); diff --git a/tests/solverIntegrationRecovery.test.ts b/tests/solverIntegrationRecovery.test.ts deleted file mode 100644 index ef80db1c..00000000 --- a/tests/solverIntegrationRecovery.test.ts +++ /dev/null @@ -1,653 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathematicsVerifierBatchRequest, MathematicsVerifierBatchResult } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => undefined, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const verified = (request: MathematicsVerifierBatchRequest) => - verifiedBatch(request, { sessionId: 'integration-recovery-fixture', checks: true }); - -type TaskAction = Extract; -type Failure = 'abort' | 'storage' | 'unavailable'; -const failureError = (failure: Failure) => failure === 'abort' ? new DOMException('Merged check interrupted.', 'AbortError') : - failure === 'storage' ? Object.assign(new Error('Transient integration storage failure.'), { code: 'EIO' }) : - new Error('math_verifier_unavailable'); -const unavailableBatch = (request: MathematicsVerifierBatchRequest): MathematicsVerifierBatchResult => { - const batch = verified(request); - return { ...batch, status: 'unavailable', - results: batch.results.map(item => ({ ...item, status: 'unavailable', error: 'Fixture merged check failure.' })) }; -}; - -describe('checked task integration recovery', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch, controller: AbortController, action: TaskAction; - let cursors: Record, snapshots: Record[]; - let events: { event: string; details?: Record }[]; - - const node = (id = 'recovery') => state.cooperation!.tasks.find(item => item.task.id === id)!; - const records = () => state.cooperation!.deliveries ?? []; - const log = () => path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)); - const key = () => `${workers[1].id}/${assignmentDeliveryFile(action.assignment)}`; - const poll = () => (cooperative as any).readWorkerDeliveries(workers[1], action, cursors) as Promise; - const append = (value: unknown) => fs.appendFileSync(log(), JSON.stringify(value) + '\n'); - const canonicalSource = () => committedSource(workspace, state.cooperation!.canonicalCommit!, - `${problem.projectRelative}/Submission.lean`); - const writeLemma = (worker: ResearchWorker, declaration: string) => { - const file = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', declaration + '\ntheorem add_zero')); - return commitSolverSources(problem, worker.worktree); - }; - const assign = (task: CooperativeTask, worker: ResearchWorker, dependencies: TaskAction['assignment']['dependencies'] = []): TaskAction => ({ - kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: worker.id, - seedCommit: problem.baseCommit, assignmentId: `dispatch-${task.id}`, dependencies }, - }); - const proofLog = (commit: string) => { - append({ summary: 'Accepted prefix.' }); - const prefixEnd = fs.statSync(log()).size; - append({ id: 'proof', kind: 'proof', commit, summary: 'A checked recovery lemma.' }); - append({ summary: 'Accepted suffix.' }); - return prefixEnd; - }; - const failMergedOnce = (failure: Failure) => { - const error = failureError(failure); - let calls = 0; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - if (++calls === 2) { - if (failure === 'unavailable') return unavailableBatch(request); - throw error; - } - return verified(request); - }); - return error; - }; - const conditionalParent = async (running: boolean) => { - const childTask: CooperativeTask = { id: 'child', kind: 'lemma', objective: 'Prove the child.', - theoremName: 'Tutorial.recovery_child', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - const child = assign(childTask, workers[2]); - const parentTask = { ...action.task, dependsOn: ['child'], conditional: true }; - action = assign(parentTask, workers[1], [{ taskId: childTask.id, taskDigest: taskVersion(childTask) }]); - Object.assign(node(), { task: parentTask, assignment: action.assignment }); - state.cooperation!.tasks.push(running ? { task: childTask, assignment: child.assignment, status: 'running', attempts: 1 } - : { task: childTask, status: 'pending', attempts: 0 }); - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by exact recovery_child'); - proofLog(commit); await poll(); - return { child, commit }; - }; - const expectNoMathematicalFailure = (feedback?: string) => { - expect(records().filter(record => record.kind === 'failure' || record.status === 'failed')).toEqual([]); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(state.cooperation!.blockers ?? []).toEqual([]); - expect(node().feedback).toBe(feedback); - expect(events.filter(item => item.event === 'delivery_rejected')).toEqual([]); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('solver-integration-recovery-'); - ({ directory, workspace, problem } = example); - workers = [leadWorker(problem, workspace), ...['parent', 'child'].map(id => peerWorker(example, id))]; - const task: CooperativeTask = { id: 'recovery', kind: 'lemma', objective: 'Prove a reusable recovery lemma.', - theoremName: 'Tutorial.recovery_lemma', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - action = assign(task, workers[1]); - state = solverState(problem, workspace, { runId: 'integration-recovery-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [{ task, assignment: action.assignment, status: 'running', attempts: 1 }, ...problem.targets.map((target, index) => ({ - task: { id: `goal_${index}`, kind: 'goal' as const, objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: [], revision: 0, status: 'paused' as const }, - status: 'pending' as const, attempts: 0, - }))] } }); - cursors = {}; snapshots = []; events = []; controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - save: () => snapshots.push({ ...cursors }), emit: (event, details) => events.push({ event, details }) }); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each([false, true])('clears an earlier proof failure after a corrected delivery (conditional=%s)', async conditional => { - let child: TaskAction | undefined; - if (conditional) { - const task: CooperativeTask = { id: 'child', kind: 'lemma', objective: 'Prove the child.', - theoremName: 'Tutorial.recovery_child', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - child = assign(task, workers[2]); - const parent = { ...action.task, dependsOn: ['child'], conditional: true }; - action = assign(parent, workers[1], [{ taskId: task.id, taskDigest: taskVersion(task) }]); - Object.assign(node(), { task: parent, assignment: action.assignment }); - state.cooperation!.tasks.push({ task, assignment: child.assignment, status: 'running', attempts: 1 }); - } - const badDeclaration = 'lemma recovery_lemma : True := by exact missing_recovery_proof'; - const failedCommit = writeLemma(workers[1], badDeclaration); - host.verify.mockImplementation(async request => failedBatch(verified(request), { - stdoutPreview: () => 'Submission.lean:3:1: error: unknown identifier missing_recovery_proof', - })); - - await cooperative.deliver(workers[1], action, failedCommit); - - const failure = records().find(record => record.kind === 'proof' && record.status === 'failed')!; - const failedInput = state.cooperation!.failedTaskInputs![0]; - expect(node().feedback).toContain('missing_recovery_proof'); - expect(failure.summary).toContain('missing_recovery_proof'); - expect(failedInput.repair).toMatchObject({ pending: true }); - node().status = 'running'; // The same worker has claimed its pending local repair. - expect(cooperative.started(workers[1], action)).toBe(true); - expect(failedInput.repair).toMatchObject({ pending: false, startedAttempt: node().attempts }); - const file = path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(badDeclaration, - `lemma recovery_lemma : True := by ${conditional ? 'exact recovery_child' : 'trivial'}`)); - const correctedCommit = commitSolverSources(problem, workers[1].worktree); - host.verify.mockImplementation(async request => verified(request)); - if (!conditional) { - const error = failMergedOnce('unavailable'); - await expect(cooperative.deliver(workers[1], action, correctedCommit)).rejects.toMatchObject({ name: error.name, message: error.message }); - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true, commit: correctedCommit } }); - expect(node().feedback).toBeUndefined(); - host.verify.mockImplementation(async request => verified(request)); - } - - await cooperative.deliver(workers[1], action, correctedCommit); - - expect(node().status).toBe(conditional ? 'conditional' : 'integrated'); - expect(node().feedback).toBeUndefined(); - expect(failedInput.repair?.startedAttempt).toBeUndefined(); - const accepted = records().find(record => record.kind === 'proof' && record.status === (conditional ? 'conditional' : 'verified'))!; - expect(accepted.summary).toBe(conditional ? 'Fixed declaration checked; unresolved lemma assumptions remain obligations.' : - 'Checked proof integrated with freshly validated dependencies.'); - if (child) { - const commit = writeLemma(workers[2], 'lemma recovery_child : True := by trivial'); - await cooperative.deliver(workers[2], child, commit); - expect(node().status).toBe('integrated'); expect(node().feedback).toBeUndefined(); - const integrated = records().find(record => record.taskId === 'recovery' && record.status === 'verified')!; - expect(integrated.summary).not.toContain('missing_recovery_proof'); - } - expect(records()).toContain(failure); - expect(failure.summary).toContain('missing_recovery_proof'); - expect(state.cooperation!.failedTaskInputs).toEqual([failedInput]); - expect(failedInput.feedback).toContain('missing_recovery_proof'); - }); - - it('clears obsolete feedback after restoring a conditional proof with a fresh successful check', async () => { - await conditionalParent(false); - node().feedback = 'Old proof failure before the successful conditional check.'; - node().proof = JSON.parse(JSON.stringify(node().proof)); - const restored = node().proof; - - await (cooperative as any).recheckConditional(); - - expect(node()).toMatchObject({ status: 'conditional', proof: { passed: true } }); - expect(node().proof).not.toBe(restored); - expect(node().feedback).toBeUndefined(); - expect(host.verify).toHaveBeenCalledTimes(2); - }); - - it.each([false, true])('dispatches a different same-type declaration after an exhausted proof failure (legacy=%s)', async legacy => { - state.workers = workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })); - Object.assign(state.workers[1], { sessionTaskId: action.task.id, sessionTaskVersion: taskVersion(action.task) }); - const failedCommit = writeLemma(workers[1], 'lemma recovery_lemma : True := by exact missing_recovery_proof'); - host.verify.mockImplementation(async request => failedBatch(verified(request), { - stdoutPreview: () => 'Submission.lean:3:1: error: unknown identifier missing_recovery_proof', - })); - await cooperative.deliver(workers[1], action, failedCommit); - expect(node().status).toBe('pending'); - node().status = 'running'; - expect(cooperative.started(workers[1], action)).toBe(true); - await cooperative.deliver(workers[1], action, failedCommit); - expect(node().status).toBe('blocked'); - const [failure] = state.cooperation!.failedTaskInputs!; - if (legacy) delete failure.declarationDigest; - - const nextTask: CooperativeTask = { ...action.task, id: 'independent_fact', objective: 'Prove a different fact.', - theoremName: 'Tutorial.independent_fact', ownerId: workers[1].id }; - state.cooperation!.tasks.push({ task: nextTask, status: 'pending', attempts: 0 }); - const goal = node('goal_0'); - goal.task = { ...goal.task, status: 'active', dependsOn: [nextTask.id], conditional: false }; - const refresh = () => (cooperative as any).refreshFailedTaskInputs(); - refresh(); - expect(node(nextTask.id)).toMatchObject({ status: 'pending', attempts: 0 }); - - // Another waiting worker may refresh dispatch while the host has reseeded this worktree for its next declaration. - const observationStart = events.length; - const preflight = vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => { - refresh(); - return { current: () => true, result: { status: 'deferred', inputDigest: 'offline-fixture', taskDigest: taskVersion(input.task), - reason: 'fixture-deferred', evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } }; - }); - const next = await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity }); - expect(next).toMatchObject({ kind: 'task', task: { id: nextTask.id } }); - expect(preflight).toHaveBeenCalledOnce(); - expect(node().status).toBe('blocked'); - expect(events.slice(observationStart)).not.toContainEqual(expect.objectContaining({ - event: 'task_failed_input_reopened', details: expect.objectContaining({ taskId: action.task.id }), - })); - }); - - it.each(['conditional', 'verified'] as const)('publishes a %s proof without using inherited failed feedback as its summary', async status => { - if (status === 'conditional') await conditionalParent(false); - else { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - proofLog(commit); await poll(); - } - // A recovered accepted proof can still owe publication after an interrupted save. - state.cooperation!.deliveries = records().filter(record => record.kind !== 'proof'); - node().feedback = 'Obsolete failure: unknown identifier missing_recovery_proof'; - const checks = host.verify.mock.calls.length; - - await (cooperative as any).publishProofDelivery(node()); - - const published = records().find(record => record.kind === 'proof')!; - expect(published.status).toBe(status); - expect(published.summary).not.toContain('missing_recovery_proof'); - expect(host.verify).toHaveBeenCalledTimes(checks); - }); - - it('clears obsolete feedback when a current integrated receipt is reused during recheck', async () => { - host.verify.mockImplementation(async request => { - const batch = verified(request); - return { ...batch, results: batch.results.map(item => ({ ...item, declarationReferences: { statement: [], proof: [] } })) }; - }); - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - proofLog(commit); await poll(); - node().feedback = 'Old proof failure before canonical acceptance.'; - const receipt = node().integratedCheck, checks = host.verify.mock.calls.length; - - await (cooperative as any).recheckIntegrated(state.cooperation!.canonicalCommit, true); - - expect(node().status).toBe('integrated'); expect(node().integratedCheck).toBe(receipt); - expect(events.some(item => item.event === 'task_check_reused')).toBe(true); - expect(host.verify).toHaveBeenCalledTimes(checks); - expect(node().feedback).toBeUndefined(); - }); - - it.each(['abort', 'storage', 'unavailable'] as const) - ('retains a checked proof and the reader prefix after a merged %s failure, then retries only integration', async failure => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - const prefixEnd = proofLog(commit), error = failMergedOnce(failure); - - await expect(poll()).rejects.toMatchObject({ name: error.name, message: error.message }); - - const checked = node().proof; - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true, commit } }); - expect(node().integratedCheck).toBeUndefined(); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(cursors[key()]).toBe(prefixEnd); - expect(snapshots.at(-1)?.[key()]).toBe(prefixEnd); - expect(records().map(record => record.summary)).toEqual(['Accepted prefix.']); - expect(host.verify).toHaveBeenCalledTimes(2); - expectNoMathematicalFailure(); - - await poll(); await poll(); - - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(node().proof).toBe(checked); - expect(canonicalSource()).toContain('lemma recovery_lemma : True := by trivial'); - expect(records().map(record => [record.kind, record.status, record.summary])).toEqual([ - ['progress', 'advisory', 'Accepted prefix.'], ['proof', 'verified', 'Checked proof integrated with freshly validated dependencies.'], - ['progress', 'advisory', 'Accepted suffix.'], - ]); - expect(cursors[key()]).toBe(fs.statSync(log()).size); - expect(host.verify).toHaveBeenCalledTimes(3); - expectNoMathematicalFailure(); - }); - - it.each(['abort', 'storage'] as const) - ('preserves canonical acceptance when statement preparation has a %s failure and completes the publication on replay', async failure => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - const prefixEnd = proofLog(commit), error = failureError(failure); - const prepare = vi.spyOn(cooperative as any, 'prepareStatementContexts').mockRejectedValueOnce(error); - - await expect(poll()).rejects.toBe(error); - - const accepted = state.cooperation!.canonicalCommit, receipt = node().integratedCheck, proof = node().proof; - expect(accepted).not.toBe(problem.baseCommit); - expect(node()).toMatchObject({ status: 'integrated', proof: { passed: true }, integratedCheck: { passed: true } }); - expect(canonicalSource()).toContain('lemma recovery_lemma : True := by trivial'); - expect(cursors[key()]).toBe(prefixEnd); - expect(records().map(record => record.summary)).toEqual(['Accepted prefix.']); - expect(host.verify).toHaveBeenCalledTimes(2); - expectNoMathematicalFailure(); - - await poll(); await poll(); - - expect(state.cooperation!.canonicalCommit).toBe(accepted); - expect(node().proof).toBe(proof); expect(node().integratedCheck).toBe(receipt); - expect(prepare).toHaveBeenCalledTimes(2); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(records().filter(record => record.kind === 'proof')).toHaveLength(1); - expect(records().find(record => record.kind === 'proof')).toMatchObject({ status: 'verified', commit: receipt!.commit }); - expect(records().map(record => record.summary)).toEqual(['Accepted prefix.', - 'Checked proof integrated with freshly validated dependencies.', 'Accepted suffix.']); - expect(cursors[key()]).toBe(fs.statSync(log()).size); - expectNoMathematicalFailure(); - }); - - it.each(['verified', 'failed'] as const) - ('reuses the %s core record when its first save fails and the same submission is replayed', async status => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - const prefixEnd = proofLog(commit), error = failureError('storage'); - if (status === 'failed') host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => - failedBatch(verified(request), { stdoutPreview: () => 'Submission.lean:3:1: error: Fixture proof failure.' })); - const input = (cooperative as any).input, save = input.save; - let interrupted = false; - vi.spyOn(input, 'save').mockImplementation(() => { - if (!interrupted && records().some(record => record.kind === 'proof')) { - interrupted = true; throw error; - } - save(); - }); - - await expect(poll()).rejects.toBe(error); - - const core = records().find(record => record.kind === 'proof')!, checked = node().proof; - expect(core).toMatchObject({ status, submissionId: 'proof', commit: status === 'verified' ? node().integratedCheck!.commit : commit }); - expect(node().status).toBe(status === 'verified' ? 'integrated' : 'pending'); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.kind === 'proof')).toHaveLength(0); - expect(cursors[key()]).toBe(prefixEnd); - expect(snapshots.at(-1)?.[key()]).toBe(prefixEnd); - const checks = host.verify.mock.calls.length; - - await poll(); await poll(); - - expect(records().filter(record => record.kind === 'proof')).toEqual([core]); - expect(node().proof).toBe(checked); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.kind === 'proof')) - .toMatchObject([{ details: { deliveryId: core.id, status } }]); - expect(host.verify).toHaveBeenCalledTimes(checks); - expect(cursors[key()]).toBe(fs.statSync(log()).size); - expect(records().filter(record => record.summary === 'Accepted suffix.')).toHaveLength(1); - }); - - it.each(['task', 'group'] as const) - ('restores an accepted unpublished proof after its %s is paused', async paused => { - (cooperative as any).input.access.get(workers[1].id).knowledgeSnapshot = { - digest: 'recovery-catalog', base: { entries: [{ id: 'saved-theorem' }] }, - }; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), JSON.stringify({ - knowledgeUses: [{ id: 'saved-theorem', catalogDigest: 'recovery-catalog', - declaration: { name: 'Tutorial.recovery_lemma', file: 'Submission.lean' } }], - })); - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - proofLog(commit); - const error = failureError('storage'); - vi.spyOn(cooperative as any, 'prepareStatementContexts').mockRejectedValueOnce(error); - await expect(poll()).rejects.toBe(error); - const source = canonicalSource(); - expect(records().filter(record => record.kind === 'proof')).toHaveLength(0); - if (paused === 'task') node().task.status = 'paused'; - else state.cooperation!.groups![0].group.status = 'paused'; - // Restored submitted proofs have no process-local receipt authority. - node().proof = JSON.parse(JSON.stringify(node().proof)); - - await cooperative.restore(); - - expect(canonicalSource()).toBe(source); - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ status: 'verified' }]); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.kind === 'proof')).toHaveLength(1); - expect(events.filter(item => item.event === 'knowledge_use_observed')).toHaveLength(0); - expect(records().find(record => record.kind === 'proof')?.knowledgeUses).toMatchObject([{ id: 'saved-theorem' }]); - expectNoMathematicalFailure(); - }); - - it('rolls back unsaved attachment metadata so the same accepted record can be retried', async () => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - proofLog(commit); await poll(); - const core = records().find(record => record.kind === 'proof')!, checked = node().proof; - const input = (cooperative as any).input, save = input.save, error = failureError('storage'); - const checks = host.verify.mock.calls.length; - expect(core.artifacts).toBeUndefined(); - let interrupted = false; - vi.spyOn(input, 'save').mockImplementation(() => { - if (!interrupted && core.artifacts) { interrupted = true; throw error; } - save(); - }); - - await expect(cooperative.deliver(workers[1], action, commit)).rejects.toBe(error); - - expect(core.artifacts).toBeUndefined(); - expect(node().proof).toBe(checked); - - await cooperative.deliver(workers[1], action, commit); - - expect(core.artifacts).toMatchObject({ commit }); - expect(core.submissionId).toBe('proof'); - expect(records().filter(record => record.kind === 'proof')).toEqual([core]); - expect(host.verify).toHaveBeenCalledTimes(checks); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.kind === 'proof')).toHaveLength(1); - }); - - it('consumes an old assignment duplicate without retrying an unrelated unavailable integration', async () => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - proofLog(commit); await poll(); - const childTask: CooperativeTask = { id: 'child', kind: 'lemma', objective: 'Prove an independent lemma.', - theoremName: 'Tutorial.recovery_child', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - const child = assign(childTask, workers[2]); - state.cooperation!.tasks.push({ task: childTask, assignment: child.assignment, status: 'running', attempts: 1 }); - const childCommit = writeLemma(workers[2], 'lemma recovery_child : True := by trivial'); - host.verify.mockImplementationOnce(async request => verified(request)).mockRejectedValue(failureError('unavailable')); - await expect(cooperative.deliver(workers[2], child, childCommit)).rejects.toThrow('math_verifier_unavailable'); - expect(node('child').status).toBe('delivered'); - const checks = host.verify.mock.calls.length; - node().assignment = { ...action.assignment, assignmentId: 'replacement-assignment' }; - append({ id: 'proof', kind: 'proof', commit, summary: 'An old assignment replay.' }); - - await poll(); - - expect(cursors[key()]).toBe(fs.statSync(log()).size); - expect(node('child').status).toBe('delivered'); - expect(host.verify).toHaveBeenCalledTimes(checks); - expect(events.filter(item => item.event === 'delivery_rejected')).toHaveLength(0); - }); - - it('retries an automatically published parent core after its save fails, without publishing a second record', async () => { - const { child } = await conditionalParent(true); - const childCommit = writeLemma(workers[2], 'lemma recovery_child : True := by trivial'); - const input = (cooperative as any).input, save = input.save, error = failureError('storage'); - let interrupted = false; - vi.spyOn(input, 'save').mockImplementation(() => { - if (!interrupted && records().some(record => record.taskId === 'recovery' && record.status === 'verified')) { - interrupted = true; throw error; - } - save(); - }); - - await expect(cooperative.deliver(workers[2], child, childCommit)).rejects.toBe(error); - - const core = records().find(record => record.taskId === 'recovery' && record.status === 'verified')!; - const accepted = state.cooperation!.canonicalCommit, checked = node().integratedCheck; - const checks = host.verify.mock.calls.length; - expect(core).toBeDefined(); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.deliveryId === core.id)).toHaveLength(0); - - await cooperative.deliver(workers[2], child, childCommit); - - expect(state.cooperation!.canonicalCommit).toBe(accepted); - expect(node().integratedCheck).toBe(checked); - expect(records().filter(record => record.taskId === 'recovery' && record.status === 'verified')).toEqual([core]); - expect(host.verify).toHaveBeenCalledTimes(checks); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.deliveryId === core.id)).toHaveLength(1); - expectNoMathematicalFailure(); - }); - - it.each(['abort', 'storage', 'unavailable'] as const) - ('propagates a direct delivery %s failure without rejecting the proved task and recovers on retry', async failure => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - const error = failMergedOnce(failure), rejected = vi.spyOn(cooperative, 'rejected'); - - await expect(cooperative.deliver(workers[1], action, commit)).rejects.toMatchObject({ name: error.name, message: error.message }); - - const checked = node().proof; - expect(node()).toMatchObject({ status: 'delivered', proof: { passed: true } }); - expect(rejected).not.toHaveBeenCalled(); expectNoMathematicalFailure(); - - await cooperative.deliver(workers[1], action, commit); - - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(node().proof).toBe(checked); - expect(host.verify).toHaveBeenCalledTimes(3); - expect(records().filter(record => record.kind === 'proof')).toHaveLength(1); - expect(records().find(record => record.kind === 'proof')?.status).toBe('verified'); - expect(rejected).not.toHaveBeenCalled(); expectNoMathematicalFailure(); - }); - - it.each(['abort', 'storage', 'unavailable'] as const) - ('keeps the assignment pending after an initial %s check failure stops its worker', async failure => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - const error = failureError(failure), rejected = vi.spyOn(cooperative, 'rejected'); - host.verify.mockImplementationOnce(async (request: MathematicsVerifierBatchRequest) => { - if (failure === 'unavailable') return unavailableBatch(request); - throw error; - }); - - await expect(cooperative.deliver(workers[1], action, commit)).rejects.toMatchObject({ name: error.name, message: error.message }); - - expect(node().status).toBe('running'); - const checkpoint = node().proof; - expect(rejected).not.toHaveBeenCalled(); expectNoMathematicalFailure(); - - cooperative.stopped(workers[1], error.message); - - expect(node()).toMatchObject({ status: 'pending', attempts: 1, feedback: error.message }); - expect(node().assignment).toBe(action.assignment); - expect(node().proof).toBe(checkpoint); - expect(cooperative.current(action)).toBe(true); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(node().integratedCheck).toBeUndefined(); - expect(host.verify).toHaveBeenCalledTimes(1); - expect(rejected).not.toHaveBeenCalled(); expectNoMathematicalFailure(error.message); - }); - - it('records a conditional proof once across incremental and direct delivery of the same assignment commit', async () => { - const { commit } = await conditionalParent(false); - const checked = node().proof, accepted = [...records()]; - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ - status: 'conditional', assignmentKey: assignmentDeliveryFile(action.assignment), submissionId: 'proof', commit, - }]); - - const result = await cooperative.deliver(workers[1], action, commit); - - expect(result.check).toBe(checked); - expect(node()).toMatchObject({ status: 'conditional', proof: { passed: true } }); - expect(node().proof).toBe(checked); - expect(records()).toEqual(accepted); - expect(records().filter(record => record.kind === 'proof')).toHaveLength(1); - expect(host.verify).toHaveBeenCalledTimes(1); - expectNoMathematicalFailure(); - }); - - it('continues ready parent integration when an already recorded conditional proof is replayed', async () => { - const { child, commit: parentCommit } = await conditionalParent(true); - expect(node()).toMatchObject({ status: 'conditional', proof: { passed: true, conditions: [{ taskId: 'child' }] } }); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ status: 'conditional', submissionId: 'proof' }]); - const checked = node().proof; - const childCommit = writeLemma(workers[2], 'lemma recovery_child : True := by trivial'); - const error = failureError('storage'); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - if (host.verify.mock.calls.length === 4) throw error; - return verified(request); - }); - - await expect(cooperative.deliver(workers[2], child, childCommit)).rejects.toBe(error); - - expect(node('child').status).toBe('integrated'); expect(node().status).toBe('conditional'); - const acceptedChild = state.cooperation!.canonicalCommit; - expect(canonicalSource()).toContain('lemma recovery_child : True := by trivial'); - expect(canonicalSource()).not.toContain('lemma recovery_lemma'); - expectNoMathematicalFailure(); - - append({ id: 'proof', kind: 'proof', commit: parentCommit, summary: 'A checked recovery lemma.' }); - append({ summary: 'Parent recovery finished.' }); - await poll(); await poll(); - - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(node().integratedCheck!.conditions ?? []).toEqual([]); - expect(node().proof).toBe(checked); - expect(state.cooperation!.canonicalCommit).not.toBe(acceptedChild); - expect(canonicalSource()).toContain('lemma recovery_child : True := by trivial'); - expect(canonicalSource()).toContain('lemma recovery_lemma : True := by exact recovery_child'); - expect(host.verify).toHaveBeenCalledTimes(5); - expect(records().filter(record => record.taskId === 'recovery' && record.kind === 'proof').map(record => record.status)) - .toEqual(['conditional', 'verified']); - expect(records().filter(record => record.summary === 'Accepted prefix.')).toHaveLength(1); - expect(cursors[key()]).toBe(fs.statSync(log()).size); - expectNoMathematicalFailure(); - }); - - it('finishes an accepted parent publication when replaying the child after statement preparation failed', async () => { - const { child } = await conditionalParent(true); - const childCommit = writeLemma(workers[2], 'lemma recovery_child : True := by trivial'); - const childFile = path.join(workers[2].worktree, assignmentDeliveryFile(child.assignment)); - const childKey = `${workers[2].id}/${assignmentDeliveryFile(child.assignment)}`; - fs.writeFileSync(childFile, JSON.stringify({ summary: 'Accepted child prefix.' }) + '\n'); - const prefixEnd = fs.statSync(childFile).size; - fs.appendFileSync(childFile, JSON.stringify({ id: 'child-proof', kind: 'proof', commit: childCommit, - summary: 'The accepted child proof.' }) + '\n'); - fs.appendFileSync(childFile, JSON.stringify({ summary: 'Accepted child suffix.' }) + '\n'); - const pollChild = () => (cooperative as any).readWorkerDeliveries(workers[2], child, cursors) as Promise; - const error = failureError('storage'); - const prepare = vi.spyOn(cooperative as any, 'prepareStatementContexts').mockImplementationOnce(() => undefined) - .mockRejectedValueOnce(error); - - await expect(pollChild()).rejects.toBe(error); - - const accepted = state.cooperation!.canonicalCommit, receipt = node().integratedCheck; - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(node('child')).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(canonicalSource()).toContain('lemma recovery_child : True := by trivial'); - expect(canonicalSource()).toContain('lemma recovery_lemma : True := by exact recovery_child'); - expect(cursors[childKey]).toBe(prefixEnd); - expect(records().filter(record => record.kind === 'proof').map(record => [record.taskId, record.status])) - .toEqual([['recovery', 'conditional'], ['child', 'verified']]); - expect(host.verify).toHaveBeenCalledTimes(4); - expectNoMathematicalFailure(); - - await pollChild(); await pollChild(); - - expect(state.cooperation!.canonicalCommit).toBe(accepted); - expect(node().integratedCheck).toBe(receipt); - expect(prepare).toHaveBeenCalledTimes(3); - expect(host.verify).toHaveBeenCalledTimes(4); - expect(records().filter(record => record.kind === 'proof').map(record => [record.taskId, record.status])) - .toEqual([['recovery', 'conditional'], ['child', 'verified'], ['recovery', 'verified']]); - expect(records().filter(record => record.summary === 'Accepted child prefix.')).toHaveLength(1); - expect(records().filter(record => record.summary === 'Accepted child suffix.')).toHaveLength(1); - expect(cursors[childKey]).toBe(fs.statSync(childFile).size); - expectNoMathematicalFailure(); - }); - - it('still consumes an explicit merged proof failure as mathematical feedback', async () => { - const commit = writeLemma(workers[1], 'lemma recovery_lemma : True := by trivial'); - proofLog(commit); - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => - host.verify.mock.calls.length === 2 ? failedBatch(verified(request), - { stdoutPreview: () => 'Submission.lean:3:1: error: Fixture merged proof failure.' }) : verified(request)); - - await poll(); await poll(); - - expect(node()).toMatchObject({ status: 'blocked', proof: { passed: true }, integratedCheck: { passed: false }, - feedback: expect.stringContaining('math_task_merged_proof_failed') }); - expect(state.cooperation!.canonicalCommit).toBe(problem.baseCommit); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ status: 'failed', commit }]); - expect(cursors[key()]).toBe(fs.statSync(log()).size); - expect(host.verify).toHaveBeenCalledTimes(2); - }); -}); diff --git a/tests/solverKnowledgeConcurrency.test.ts b/tests/solverKnowledgeConcurrency.test.ts deleted file mode 100644 index 84b067f4..00000000 --- a/tests/solverKnowledgeConcurrency.test.ts +++ /dev/null @@ -1,435 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LAKE_CONFIGURATION_FILES, mathLocalModuleBuildOrder } from '../src/math/mathConstructionSources'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { KnowledgeContextSnapshot } from '../src/solver/knowledgeContext'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), check: vi.fn(), identity: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => undefined, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/math/leanTypeDiagnostics', async importOriginal => ({ - ...await importOriginal(), checkLeanType: host.check, -})); -vi.mock('../src/math/leanResidualGoals', async importOriginal => ({ - ...await importOriginal(), leanDiagnosticEnvironmentIdentity: host.identity, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -type TaskAction = Extract; -type DiagnosticInput = Parameters[0]; -const knowledge = { digest: 'pinned-catalog', base: { entries: [{ id: 'saved-theorem' }] } } as KnowledgeContextSnapshot; - -describe('proof delivery with concurrent knowledge application checks', () => { - let directory: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch, controller: AbortController, action: TaskAction; - let pending: Promise[], releases: (() => void)[], lockHeld: boolean; - let events: { event: string; details?: Record }[]; - let onSave: () => void; - - const node = () => state.cooperation!.tasks.find(item => item.task.id === action.task.id)!; - const records = () => state.cooperation!.deliveries ?? []; - const track = (promise: Promise) => { - pending.push(promise); void promise.catch(() => {}); return promise; - }; - const commitProof = ({ application = true, rejectedUse = false } = {}) => { - const worker = workers[1], file = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', - 'lemma knowledge_lemma : True := by trivial\ntheorem add_zero')); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), JSON.stringify({ summary: 'A checked reusable lemma.', - knowledgeUses: [{ id: 'saved-theorem', catalogDigest: knowledge.digest, - declaration: { name: 'Tutorial.knowledge_lemma', file: 'Submission.lean' }, - ...(application ? { application: { expression: 'True.intro', expectedType: 'True', - context: { file: 'Submission.lean', declaration: action.task.theoremName } } } : {}) }, - ...(rejectedUse ? [{ id: 'not-in-the-pinned-catalog' }] : [])] })); - return commitSolverSources(problem, worker.worktree); - }; - const secondProof = (dependsOnKnowledge = false) => { - const worker = workers[2]; - const task: CooperativeTask = { id: 'independent', kind: 'lemma', objective: 'Prove another reusable lemma.', - theoremName: 'Tutorial.second_lemma', proofPath: 'Submission.lean', type: 'True', revision: 0, - dependsOn: dependsOnKnowledge ? [action.task.id] : [], ...(dependsOnKnowledge ? { conditional: true } : {}) }; - const second: TaskAction = { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), - workerId: worker.id, seedCommit: problem.baseCommit, assignmentId: 'second-dispatch', - dependencies: dependsOnKnowledge ? [{ taskId: action.task.id, taskDigest: taskVersion(action.task) }] : [] } }; - const record = state.cooperation!.tasks.find(item => item.task.id === task.id)!; - Object.assign(record, { task, assignment: second.assignment, status: 'running', attempts: 1 }); - const file = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', - `lemma second_lemma : True := by ${dependsOnKnowledge ? 'exact knowledge_lemma' : 'trivial'}\ntheorem add_zero`)); - return { action: second, node: record, commit: commitSolverSources(problem, worker.worktree) }; - }; - const canonicalSource = () => committedSource(workers[0].worktree, state.cooperation!.canonicalCommit!, - `${problem.projectRelative}/Submission.lean`); - const diagnosticResult = (input: DiagnosticInput) => { - const files = [...mathLocalModuleBuildOrder(input.projectRoot, input.file).map(module => module.file), - ...LAKE_CONFIGURATION_FILES.filter(file => fs.existsSync(path.join(input.projectRoot, file)))] - .map(file => ({ file, digest: mathDigest(fs.readFileSync(path.join(input.projectRoot, file))) })); - const contents = canonicalMathJson({ files, expression: input.expression, type: input.type }); - const artifact = { path: '.lake/knowledge-application-fixture.json', digest: mathDigest(contents) }; - fs.mkdirSync(path.join(input.projectRoot, '.lake'), { recursive: true }); - fs.writeFileSync(path.join(input.projectRoot, artifact.path), contents); - return { status: 'elaborated', exitCode: 0, timedOut: false, sourceFiles: files, artifact, - sourceSnapshotDigest: mathDigest(canonicalMathJson(files)), projectionDigest: mathDigest('application-projection'), - environment: host.identity(), type: input.type, constants: ['True.intro'], stdout: '', stderr: '' }; - }; - const gateKnowledge = () => { - const entered = deferred(), released = deferred(), aborted = deferred(); - let heldAtEntry: boolean | undefined; - let cleaned = false; - host.check.mockImplementation(async (input: DiagnosticInput) => { - const result = diagnosticResult(input); - input.signal?.addEventListener('abort', () => aborted.resolve(), { once: true }); - heldAtEntry = lockHeld; entered.resolve(input); - try { await released.promise; return result; } - finally { cleaned = true; } - }); - const release = () => released.resolve(); releases.push(release); - return { entered: entered.promise, aborted: aborted.promise, release, heldAtEntry: () => heldAtEntry, cleaned: () => cleaned }; - }; - const edit = (id: string, change: (task: CooperativeTask) => CooperativeTask) => { - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id, baseVersion: state.cooperation!.planVersion, - tasks: state.cooperation!.tasks.map(item => change(item.task)), - groups: state.cooperation!.groups!.map(item => item.group), - }) + '\n'); - return track(cooperative.pulse(workers[0].id)); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest) => - verifiedBatch(request, { sessionId: 'knowledge-concurrency-fixture', checks: true })); - host.check.mockReset().mockImplementation(async (input: DiagnosticInput) => diagnosticResult(input)); - host.identity.mockReset().mockReturnValue({ environmentDigest: mathDigest('diagnostic-environment'), toolIdentity: mathDigest('fixture-tools') }); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('solver-knowledge-concurrency-'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), ...['author', 'independent'].map(id => peerWorker(example, id))]; - const task: CooperativeTask = { id: 'knowledge', kind: 'lemma', objective: 'Prove a reusable lemma.', - theoremName: 'Tutorial.knowledge_lemma', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - action = { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: workers[1].id, - seedCommit: problem.baseCommit, assignmentId: 'knowledge-dispatch', dependencies: [] } }; - state = solverState(problem, example.workspace, { runId: 'knowledge-concurrency-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [{ task, assignment: action.assignment, status: 'running', attempts: 1 }, - { task: { id: 'independent', kind: 'research', objective: 'Find another useful approach.', dependsOn: [], revision: 0 }, - status: 'pending', attempts: 0 }, ...problem.targets.map((target, index) => ({ - task: { id: `goal_${index}`, kind: 'goal' as const, objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: [], revision: 0, status: 'paused' as const }, - status: 'pending' as const, attempts: 0, - }))] } }); - events = []; pending = []; releases = []; lockHeld = false; onSave = () => {}; controller = new AbortController(); - let queue = Promise.resolve(); - const exclusive = async (check: () => Promise): Promise => { - const previous = queue; let release!: () => void; - queue = new Promise(resolve => { release = resolve; }); - await previous; lockHeld = true; - try { return await check(); } finally { lockHeld = false; release(); } - }; - const access = workerAccess(workers, directory); - for (const value of access.values()) value.environment = { PATH: '/usr/bin:/bin', ELAN_HOME: '', LEAN_PATH: '', LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; - access.get(workers[1].id)!.knowledgeSnapshot = knowledge; - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, access, signal: controller.signal, - save: () => onSave(), emit: (event, details) => events.push({ event, details }), exclusiveCheck: exclusive }); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - }); - afterEach(async () => { - for (const release of releases) release(); - controller.abort(); await Promise.allSettled(pending); await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('applies an independent plan edit before a selected application check finishes', async () => { - const commit = commitProof(), gate = gateKnowledge(); - const delivery = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - - let applied = false; - const pulse = edit('independent-during-knowledge', task => task.id === 'independent' - ? { ...task, objective: 'Find a sharper independent approach.', revision: task.revision + 1 } : task); - void pulse.then(() => { applied = true; }, () => {}); - await vi.waitFor(() => { - expect(state.cooperation!.edits).toContainEqual(expect.objectContaining({ id: 'independent-during-knowledge', status: 'applied' })); - expect(applied).toBe(true); - }); - expect(gate.heldAtEntry()).toBe(false); - - gate.release(); await delivery; - - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ taskId: action.task.id, status: 'verified', - commit: node().integratedCheck!.commit, - knowledgeUses: [{ consumer: { taskId: action.task.id, taskDigest: taskVersion(action.task) }, - application: { check: { status: 'elaborated', proofAcceptance: 'not-assessed', commit } } }] }]); - expect(node().proof!.commit).toBe(commit); - expect(host.check).toHaveBeenCalledTimes(1); - }); - - it('publishes normalized reference uses without starting an optional Lean application check', async () => { - const commit = commitProof({ application: false }); - - await track(cooperative.deliver(workers[1], action, commit)); - - expect(node()).toMatchObject({ status: 'integrated', integratedCheck: { passed: true } }); - expect(records().filter(record => record.kind === 'proof')).toMatchObject([{ taskId: action.task.id, status: 'verified', - knowledgeUses: [{ id: 'saved-theorem', catalogDigest: knowledge.digest, - consumer: { taskId: action.task.id, taskDigest: taskVersion(action.task) } }] }]); - expect(records()[0].knowledgeUses![0].application).toBeUndefined(); - expect(host.check).not.toHaveBeenCalled(); - expect(events.filter(item => item.event === 'knowledge_use_observed')).toHaveLength(1); - }); - - it('integrates an independent proof while the first delivery still awaits its application check', async () => { - const second = secondProof(), commit = commitProof(), gate = gateKnowledge(); - const first = track(cooperative.deliver(workers[1], action, commit)); - let firstSettled = false; - void first.then(() => { firstSettled = true; }, () => { firstSettled = true; }); - await gate.entered; - const core = records().find(record => record.kind === 'proof' && record.taskId === action.task.id)!; - expect(core).toMatchObject({ status: 'verified', commit: node().integratedCheck!.commit }); - expect(node().proof!.commit).toBe(commit); - - const independent = track(cooperative.deliver(workers[2], second.action, second.commit)); - await vi.waitFor(() => expect(second.node.status).toBe('integrated'), { timeout: 5000 }); - await independent; - - expect(canonicalSource()).toContain('lemma knowledge_lemma : True := by trivial'); - expect(canonicalSource()).toContain('lemma second_lemma : True := by trivial'); - expect(records().filter(record => record.kind === 'proof')).toHaveLength(2); - expect(firstSettled).toBe(false); - expect(gate.cleaned()).toBe(false); - expect(host.check).toHaveBeenCalledTimes(1); - - gate.release(); await first; - - expect(records().find(record => record.id === core.id)).toBe(core); - expect(core.knowledgeUses).toMatchObject([{ application: { check: { status: 'elaborated', commit } } }]); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.deliveryId === core.id)).toHaveLength(1); - }); - - it('integrates a ready conditional parent before its child application check finishes', async () => { - const parent = secondProof(true); - await track(cooperative.deliver(workers[2], parent.action, parent.commit)); - expect(parent.node).toMatchObject({ status: 'conditional', proof: { passed: true, - conditions: [{ taskId: action.task.id, taskDigest: taskVersion(action.task) }] } }); - const conditionalProof = parent.node.proof; - const commit = commitProof(), gate = gateKnowledge(); - const child = track(cooperative.deliver(workers[1], action, commit)); - let childSettled = false; - void child.then(() => { childSettled = true; }, () => { childSettled = true; }); - await gate.entered; - - await vi.waitFor(() => expect(parent.node.status).toBe('integrated'), { timeout: 5000 }); - - expect(parent.node.proof).toBe(conditionalProof); - expect(parent.node.integratedCheck).toMatchObject({ passed: true }); - expect(parent.node.integratedCheck?.conditions ?? []).toEqual([]); - expect(canonicalSource()).toContain('lemma second_lemma : True := by exact knowledge_lemma'); - expect(records().filter(record => record.kind === 'proof' && record.taskId === parent.action.task.id).map(record => record.status)) - .toEqual(['conditional', 'verified']); - expect(childSettled).toBe(false); - expect(gate.cleaned()).toBe(false); - - gate.release(); await child; - - expect(records().find(record => record.kind === 'proof' && record.taskId === action.task.id)?.knowledgeUses) - .toMatchObject([{ application: { check: { status: 'elaborated', commit } } }]); - }); - - it('does not publish an old application result after its task contract changes', async () => { - const commit = commitProof({ rejectedUse: true }), gate = gateKnowledge(); - const delivery = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - const accepted = node().integratedCheck!; - expect(node().proof!.commit).toBe(commit); - - let applied = false; - const pulse = edit('revise-during-knowledge', task => task.id === action.task.id - ? { ...task, type: 'True ∧ True', revision: task.revision + 1 } : task); - void pulse.then(() => { applied = true; }, () => {}); - await vi.waitFor(() => { - expect(state.cooperation!.edits).toContainEqual(expect.objectContaining({ id: 'revise-during-knowledge', status: 'applied' })); - expect(applied).toBe(true); - }); - expect(cooperative.current(action)).toBe(false); - const current = node(), snapshot = JSON.parse(JSON.stringify(current)); - const historical = records().filter(record => record.kind === 'proof' && record.taskDigest === action.assignment.taskDigest); - expect(historical).toHaveLength(1); - expect(historical[0]).toMatchObject({ status: 'superseded', commit: accepted.commit }); - const recordedKnowledge = structuredClone(historical[0].knowledgeUses); - const beforeCompletion = events.length; - - gate.release(); await delivery; - - expect(node()).toBe(current); expect(node()).toEqual(snapshot); - expect(records().filter(record => record.kind === 'proof' && record.taskDigest === action.assignment.taskDigest)).toEqual(historical); - expect(historical[0].knowledgeUses).toEqual(recordedKnowledge); - expect(events.slice(beforeCompletion).filter(item => ['knowledge_use_observed', 'knowledge_use_rejected'].includes(item.event) && - item.details?.commit === commit)).toEqual([]); - expect(host.check).toHaveBeenCalledTimes(1); - }); - - it.each(['status', 'assignment', 'proof', 'integratedCheck', 'environment', 'problem receipt', 'removed'] as const) - ('preserves the core record and drops late knowledge results after its %s changes', async change => { - const commit = commitProof({ rejectedUse: true }), gate = gateKnowledge(); - const delivery = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - const delivered = node(); - const core = records().find(record => record.kind === 'proof' && record.taskId === action.task.id)!; - expect(core).toMatchObject({ status: 'verified', commit: delivered.integratedCheck!.commit }); - expect(delivered.proof!.commit).toBe(commit); - const coreBeforeCompletion = structuredClone(core); - - switch (change) { - case 'status': delivered.status = 'pending'; break; - case 'assignment': delivered.assignment = { ...delivered.assignment! }; break; - case 'proof': delivered.proof = structuredClone(delivered.proof); break; - case 'integratedCheck': delivered.integratedCheck = structuredClone(delivered.integratedCheck); break; - case 'environment': state.environmentDigest = 'changed-environment'; break; - case 'problem receipt': state.problem.receiptDigest = 'changed-problem-receipt'; break; - case 'removed': state.cooperation!.tasks = state.cooperation!.tasks.filter(record => record !== delivered); break; - } - const tasksBeforeCompletion = structuredClone(state.cooperation!.tasks); - const environmentBeforeCompletion = state.environmentDigest, receiptBeforeCompletion = state.problem.receiptDigest; - const beforeCompletion = events.length; - - gate.release(); await delivery; - - expect(records().filter(record => record.kind === 'proof')).toEqual([core]); - expect(core).toEqual(coreBeforeCompletion); - expect(state.cooperation!.tasks).toEqual(tasksBeforeCompletion); - expect(state.environmentDigest).toBe(environmentBeforeCompletion); - expect(state.problem.receiptDigest).toBe(receiptBeforeCompletion); - expect(events.slice(beforeCompletion).filter(item => ['knowledge_use_observed', 'knowledge_use_rejected'].includes(item.event) && - item.details?.commit === commit)).toEqual([]); - expect(host.check).toHaveBeenCalledTimes(1); - }); - - it('checks and publishes a selected application once for duplicate proof deliveries', async () => { - const commit = commitProof(), gate = gateKnowledge(); - const first = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - const duplicate = track(cooperative.deliver(workers[1], action, commit)); - let settled = 0; - for (const delivery of [first, duplicate]) void delivery.then(() => { settled++; }, () => { settled++; }); - await Promise.resolve(); await Promise.resolve(); - expect(host.check).toHaveBeenCalledTimes(1); - expect(records().filter(record => record.kind === 'proof')).toHaveLength(1); - expect(settled).toBe(0); - - gate.release(); await Promise.all([first, duplicate]); - await track(cooperative.deliver(workers[1], action, commit)); - - expect(host.check).toHaveBeenCalledTimes(1); - expect(records().filter(record => record.kind === 'proof')).toHaveLength(1); - expect(records()[0]).toMatchObject({ taskId: action.task.id, status: 'verified', commit: node().integratedCheck!.commit, - knowledgeUses: [{ application: { check: { status: 'elaborated', commit } } }] }); - expect(node().proof!.commit).toBe(commit); - expect(events.filter(item => item.event === 'knowledge_use_observed')).toHaveLength(1); - }); - - it('retries an annotation save failure on the accepted proof when a duplicate log line changes its commit', async () => { - const commit = commitProof(), file = path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)); - const key = `${workers[1].id}/${assignmentDeliveryFile(action.assignment)}`, cursors: Record = {}; - const prefix = JSON.stringify({ summary: 'Accepted prefix.' }) + '\n'; - const suffix = JSON.stringify({ summary: 'Accepted suffix.' }) + '\n'; - const submission = { id: 'knowledge-proof', kind: 'proof', commit, summary: 'A checked reusable lemma.' }; - fs.writeFileSync(file, prefix + JSON.stringify(submission) + '\n' + suffix); - const prefixEnd = Buffer.byteLength(prefix), snapshots: Record[] = []; - const failure = Object.assign(new Error('Transient annotation save failure.'), { code: 'EIO' }); - let failedOnce = false; - onSave = () => { - snapshots.push({ ...cursors }); - if (!failedOnce && records().some(record => record.kind === 'proof' && record.taskId === action.task.id && - record.knowledgeUses?.some(use => use.application?.check))) { - failedOnce = true; throw failure; - } - }; - const poll = () => track((cooperative as any).readWorkerDeliveries(workers[1], action, cursors) as Promise); - - await expect(poll()).rejects.toBe(failure); - - const core = records().find(record => record.kind === 'proof' && record.taskId === action.task.id)!; - expect(core).toMatchObject({ status: 'verified', commit: node().integratedCheck!.commit, submissionId: submission.id }); - expect(node().proof!.commit).toBe(commit); - expect(core.knowledgeUses).toHaveLength(1); - expect(core.knowledgeUses![0].application?.check).toBeUndefined(); - expect(cursors[key]).toBe(prefixEnd); - expect(snapshots.at(-1)?.[key]).toBe(prefixEnd); - expect(records().map(record => record.summary)).toEqual(['Accepted prefix.', - 'Checked proof integrated with freshly validated dependencies.']); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.deliveryId === core.id)).toHaveLength(1); - expect(events.filter(item => item.event === 'knowledge_use_observed')).toEqual([]); - expect(host.check).toHaveBeenCalledTimes(1); - const proof = node().proof, integratedCheck = node().integratedCheck, canonical = state.cooperation!.canonicalCommit; - const verifications = host.verify.mock.calls.length; - - expect(problem.baseCommit).not.toBe(commit); - fs.writeFileSync(file, prefix + JSON.stringify({ ...submission, commit: problem.baseCommit }) + '\n' + suffix); - await poll(); await poll(); - - expect(records().filter(record => record.kind === 'proof')).toEqual([core]); - expect(records().find(record => record.id === core.id)).toBe(core); - expect(core).toMatchObject({ status: 'verified', commit: integratedCheck!.commit, submissionId: submission.id, - knowledgeUses: [{ application: { check: { status: 'elaborated', commit } } }] }); - expect(node().proof).toBe(proof); - expect(node().integratedCheck).toBe(integratedCheck); - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect(host.verify).toHaveBeenCalledTimes(verifications); - expect(host.check).toHaveBeenCalledTimes(2); - expect(cursors[key]).toBe(fs.statSync(file).size); - expect(snapshots.at(-1)?.[key]).toBe(fs.statSync(file).size); - expect(records().map(record => record.summary)).toEqual(['Accepted prefix.', - 'Checked proof integrated with freshly validated dependencies.', 'Accepted suffix.']); - expect(events.filter(item => item.event === 'delivery_published' && item.details?.deliveryId === core.id)).toHaveLength(1); - expect(events.filter(item => item.event === 'knowledge_use_observed' && item.details?.commit === commit)).toHaveLength(1); - }); - - it('waits for cancelled application cleanup before stopping and publishes no late knowledge observations', async () => { - const commit = commitProof({ rejectedUse: true }), gate = gateKnowledge(); - const delivery = track(cooperative.deliver(workers[1], action, commit)); - await gate.entered; - const core = records().find(record => record.kind === 'proof' && record.taskId === action.task.id)!; - const accepted = node().integratedCheck!; - expect(core).toMatchObject({ status: 'verified', commit: accepted.commit }); - expect(node().proof!.commit).toBe(commit); - const recordedKnowledge = structuredClone(core.knowledgeUses); - const beforeCancellation = events.length; - - controller.abort(); await gate.aborted; - const stopped = track(cooperative.stop()); - let stopSettled = false, deliverySettled = false; - void stopped.then(() => { stopSettled = true; }, () => { stopSettled = true; }); - void delivery.then(() => { deliverySettled = true; }, () => { deliverySettled = true; }); - await Promise.resolve(); await Promise.resolve(); - - expect(gate.cleaned()).toBe(false); - expect(stopSettled).toBe(false); - expect(deliverySettled).toBe(false); - - gate.release(); await Promise.allSettled([delivery, stopped]); - - expect(gate.cleaned()).toBe(true); - expect(stopSettled).toBe(true); - expect(records().filter(record => record.kind === 'proof')).toEqual([core]); - expect(core).toMatchObject({ status: 'verified', commit: accepted.commit }); - expect(core.knowledgeUses).toEqual(recordedKnowledge); - expect(events.slice(beforeCancellation).filter(item => ['knowledge_use_observed', 'knowledge_use_rejected'].includes(item.event) && - item.details?.commit === commit)).toEqual([]); - }); -}); diff --git a/tests/solverLeadCheckpointSemantics.test.ts b/tests/solverLeadCheckpointSemantics.test.ts deleted file mode 100644 index 40acda1a..00000000 --- a/tests/solverLeadCheckpointSemantics.test.ts +++ /dev/null @@ -1,443 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; -import { parseLeadPlan } from '../src/solver/cooperationShared'; -import { committedSource, commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { advisoryCheckpointScope } from '../src/solver/research'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -type Lead = Extract; -const lead = (fields: Partial = {}): Lead => ({ kind: 'lead', seedCommit: 'seed-a', planVersion: 'graph-a', responsibilityDigest: 'responsibility-a', - planNonce: 'nonce-a', planningInputDigest: 'operational-input-a', ...fields }); - -describe('semantic advisory checkpoint inputs', () => { - it('preserves the same scope across nonce, seed and planning input changes', () => { - const original = lead(); - const replay = lead({ planNonce: 'nonce-b', seedCommit: 'seed-b', planningInputDigest: 'operational-input-b' }); - expect(advisoryCheckpointScope(replay)).toBe(advisoryCheckpointScope(original)); - }); - - it.each([ - ['planning input', { planningInputDigest: 'operational-input-b' }], - ['new base graph presentation', { planVersion: 'graph-b' }], - ] as const)('keeps new %s from resetting the same responsibility guard', (_label, change) => { - expect(advisoryCheckpointScope(lead(change as Partial))).toBe(advisoryCheckpointScope(lead())); - }); - - it('gives a changed mathematical responsibility a fresh scope', () => { - expect(advisoryCheckpointScope(lead({ responsibilityDigest: 'responsibility-b' }))).not.toBe(advisoryCheckpointScope(lead())); - }); - - it('distinguishes initial planning without using the initial dispatch nonce', () => { - const original = lead({ initialPlanNonce: 'initial-a' }); - expect(advisoryCheckpointScope(lead({ initialPlanNonce: 'initial-b' }))).toBe(advisoryCheckpointScope(original)); - expect(advisoryCheckpointScope(lead())).not.toBe(advisoryCheckpointScope(original)); - }); - - it('keeps non-Lead research scoped to its exact task contract and excludes proof work', () => { - const task: CooperativeTask = { id: 'question', kind: 'research', objective: 'Find the missing construction.', dependsOn: [], revision: 0 }; - const assignment = { taskId: task.id, taskDigest: 'task-a', workerId: 'worker-a', seedCommit: 'seed-a', assignmentId: 'first' }; - const action: CooperativeAction = { kind: 'task', task, assignment }; - const original = advisoryCheckpointScope(action); - expect(advisoryCheckpointScope({ ...action, assignment: { ...assignment, assignmentId: 'second', workerId: 'worker-b', seedCommit: 'seed-b' } })).toBe(original); - expect(advisoryCheckpointScope({ ...action, assignment: { ...assignment, taskDigest: 'task-b' } })).not.toBe(original); - expect(advisoryCheckpointScope({ ...action, task: { ...task, kind: 'lemma' } })).toBeUndefined(); - expect(advisoryCheckpointScope(undefined)).toBeUndefined(); - }); -}); - -describe('Lead scheduling checkpoint control responses', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - let directory: string, problem: SolverProblem, workers: ResearchWorker[], state: SolverRunState; - let cooperative: CooperativeResearch, controller: AbortController; - let events: { event: string; details?: Record }[]; - let notify: ReturnType Promise>>; - let proposal: CooperativeTask; - // Current research deliveries whose exact lemma proposals are not yet in the plan. - const pendingProposals = () => (state.cooperation!.deliveries ?? []).filter(delivery => delivery.kind === 'research' && - delivery.status !== 'superseded' && delivery.lemmaRequests?.some(task => !state.cooperation!.tasks.some(node => node.task.id === task.id))); - const graph = () => ({ tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(route => route.group) }); - const notes = () => path.join(workers[0].worktree, 'RESEARCH.md'); - const planText = (response: unknown) => '```math-plan\n' + JSON.stringify(response) + '\n```\n'; - const write = (response: unknown) => fs.writeFileSync(notes(), planText(response)); - // A validated plan answers each shown research finding. - const decide = (outcome: 'adopt' | 'decline') => ({ researchDecisions: [{ deliveryId: 'proposal-delivery', outcome, - reason: outcome === 'adopt' ? 'The typed bridge closes the route.' : 'The bridge is not needed yet.', - ...(outcome === 'adopt' ? { taskIds: ['bridge'] } : {}) }] }); - const start = async (baseline?: string | null) => { - if (baseline === null) fs.rmSync(notes(), { force: true }); - else if (baseline === undefined) write(graph()); - else fs.writeFileSync(notes(), baseline); - const action = await cooperative.next(workers[0], budget); - if (action?.kind !== 'lead' || !action.planNonce) throw new Error('fixture_expected_revision_dispatch'); - expect(cooperative.started(workers[0], action)).toBe(true); - cooperative.activate(workers[0], action, async () => {}, notify); - return action; - }; - const checkpoint = (action: Lead) => { - const commit = commitSolverSources(problem, workers[0].worktree); - cooperative.deactivate(workers[0]); - return cooperative.deliver(workers[0], action, commit, true, 'scheduling-checkpoint'); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(() => { throw new Error('fixture_unexpected_proof_acceptance'); }); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('lead-checkpoint-semantics-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'researcher')]; - const question: CooperativeTask = { id: 'question', kind: 'research', objective: 'Find a bridge.', dependsOn: [], revision: 0 }; - proposal = { id: 'bridge', kind: 'lemma', objective: 'Prove the missing exact bridge.', theoremName: 'Tutorial.bridge', - proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - const parsed = parseCooperationPlan(problem, { tasks: [question, ...problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, - }))] }); - state = solverState(problem, example.workspace, { runId: 'lead-checkpoint-semantics', phase: 'running', - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'checking', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: parsed.tasks.map(task => ({ task, status: task.id === question.id ? 'completed' : 'pending', attempts: 0 })), - groups: parsed.groups.map(group => ({ group, turns: 0 })), - deliveries: [{ id: 'proposal-delivery', producer: workers[1].id, taskId: question.id, taskDigest: taskVersion(question), - kind: 'research', status: 'advisory', summary: 'A typed bridge needs a Lead decision.', statement: '', premises: [], - dependencies: [], remainingObligations: [], evidenceRefs: [], createdAt: 1, lemmaRequests: [proposal] }] } }); - events = []; controller = new AbortController(); notify = vi.fn(async (_message: string) => {}); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }) }); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.verify).not.toHaveBeenCalled(); expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('reports a saved incomplete Lead decision at checkpoint handoff without publishing the draft', async () => { - const action = await start(), before = structuredClone(state.cooperation!.tasks); - await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); // The inherited accepted graph is still just the dispatch seed. - write({ ...graph(), tasks: [...graph().tasks, proposal] }); - await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); - expect(cooperative.leadCheckpointHandoff(action)?.reason).toContain('math_plan_research_decisions_missing'); - expect(cooperative.leadCheckpointInstruction(action)).toContain('proposal-delivery'); - expect(state.cooperation!.tasks).toEqual(before); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - expect(state.cooperation!.planPublication).toBeUndefined(); - expect(state.cooperation!.planRejection).toBeUndefined(); - write({ ...graph(), tasks: [...graph().tasks, proposal], ...decide('adopt') }); - expect(cooperative.leadCheckpointHandoff(action)).toBeUndefined(); - expect(state.cooperation!.tasks).toEqual(before); - await checkpoint(action); - expect(state.cooperation!.tasks.find(node => node.task.id === proposal.id)?.status).toBe('pending'); - expect(state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'proposal-delivery', outcome: 'adopt' })); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('ignores a missing, partial or prose-only draft while the Lead is still writing', async () => { - await start(); - fs.rmSync(notes()); await cooperative.pulse(); - for (const text of ['A mathematical argument under construction.', '```math-plan\n{"tasks":[', - '```math-plan\n{"tasks":[\n```']) { - fs.writeFileSync(notes(), text); await cooperative.pulse(); - } - expect(notify).not.toHaveBeenCalled(); - }); - - it('ignores an unpublished draft after its dispatch has already published a valid decision', async () => { - const action = await start(); - const response = { ...graph(), tasks: [...graph().tasks, proposal], ...decide('adopt') }; - write({ ...graph(), tasks: [...graph().tasks, proposal] }); - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(action)!), JSON.stringify({ - ...response, kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, - }) + '\n'); - await cooperative.pulse(); await cooperative.pulse(); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: action.planNonce }); - expect(state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'proposal-delivery', outcome: 'adopt' })); - expect(notify).not.toHaveBeenCalled(); - }); - - it('does not notify a deactivated Lead or require a research decision already settled by a peer', async () => { - await start(); - write({ ...graph(), tasks: [...graph().tasks, proposal] }); - const delivery = state.cooperation!.deliveries!.find(record => record.id === 'proposal-delivery')!; - state.cooperation!.researchDecisions = [{ deliveryId: delivery.id, taskDigest: delivery.taskDigest, - findingDigest: delivery.findingDigest, outcome: 'decline', - reason: 'A peer settled this finding in the accepted plan.', at: 1, planVersion: state.cooperation!.planVersion! }]; - await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); - state.cooperation!.researchDecisions = []; - cooperative.deactivate(workers[0]); - await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); - expect(pendingProposals()).toHaveLength(1); - }); - - it.each([false, true])('retains an unanswered research decision in an unchanged control draft (prose-only: %s)', async prose => { - const action = await start(), before = structuredClone(state.cooperation!.tasks), base = state.cooperation!.planVersion; - const pending = pendingProposals().map(item => item.id); - if (prose) fs.appendFileSync(notes(), '\nA still unfinished mathematical investigation.\n'); - await expect(checkpoint(action)).resolves.toEqual({ checkWhole: false }); - expect(state.cooperation!.error).toContain('math_plan_research_decisions_missing'); - expect(state.cooperation!.planRejection).toMatchObject({ stalled: false }); - expect(state.cooperation!.lastLeadPauseInputDigest).toBeUndefined(); - expect(events.some(item => item.event === 'lead_draft_preserved')).toBe(true); - expect(events.some(item => item.event === 'plan_updated')).toBe(false); - expect(state.cooperation!.tasks).toEqual(before); - expect(state.cooperation!.planVersion).toBe(base); - expect(pending).toEqual(['proposal-delivery']); - expect(pendingProposals().map(item => item.id)).toEqual(pending); - expect(fs.readFileSync(notes(), 'utf8')).toContain(prose ? 'unfinished mathematical' : 'math-plan'); - }); - - it.each(['ordinary Markdown with no control response', null])('preserves an incomplete draft and its required feedback: %s', async baseline => { - const action = await start(baseline); - await checkpoint(action); - expect(events.some(item => item.event === 'lead_draft_preserved')).toBe(true); - expect(events.some(item => item.event === 'plan_rejected')).toBe(true); - expect(state.cooperation!.lastLeadPauseInputDigest).toBeUndefined(); - expect(pendingProposals()).toHaveLength(1); - }); - - it.each(['control', 'Markdown', null])('preserves an unchanged draft without a required decision: %s', async baseline => { - state.cooperation!.deliveries = []; - const action = await start(baseline === 'control' ? undefined : baseline); - await checkpoint(action); - expect(events.some(item => item.event === 'lead_checkpoint_saved')).toBe(true); - expect(events.some(item => item.event === 'plan_rejected')).toBe(false); - expect(state.cooperation!.lastLeadPauseInputDigest).toBeDefined(); - }); - - it('answers a research finding from a checkpoint without changing the graph', async () => { - const action = await start(planText({ ...graph(), ...decide('decline') })); - const reminder = cooperative.leadCheckpointInstruction(action); - expect(reminder).toContain('researchDecisions: ["proposal-delivery"]'); - expect(reminder).toContain('task graph stays unchanged'); - expect(JSON.parse(reminder.match(/Current response template[^\n]*\n([^\n]+)\n/u)![1])).toMatchObject({ - baseVersion: action.planVersion, upsert: [], - }); - expect(reminder).not.toContain('return without a revision'); - await checkpoint(action); - expect(state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'proposal-delivery', outcome: 'decline' })); - expect(state.cooperation!.lastLeadInputDigest).toBeDefined(); - expect(state.cooperation!.lastLeadPauseInputDigest).toBeUndefined(); - expect(state.cooperation!.error).toBeUndefined(); - expect(events.some(item => item.event === 'lead_checkpoint_saved')).toBe(false); - expect(cooperative.leadCheckpointInstruction(action)).toContain('return without a revision'); - }); - - it('accepts a nested research decision through the live plan intake without inventing proof progress', async () => { - const action = await start(), planVersion = state.cooperation!.planVersion; - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(action)!), JSON.stringify({ - kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, - tasks: { baseVersion: action.planVersion, upsert: [], ...decide('decline') }, - }) + '\n'); - await cooperative.pulse(); - expect(state.cooperation!.planVersion).toBe(planVersion); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: action.planNonce }); - expect(state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'proposal-delivery', outcome: 'decline' })); - expect(state.cooperation!.tasks.some(node => node.task.id === proposal.id)).toBe(false); - expect(state.cooperation!.tasks.some(node => node.status === 'integrated')).toBe(false); - expect(state.cooperation!.error).toBeUndefined(); - expect(events.some(item => item.event === 'plan_publication_rejected')).toBe(false); - }); - - it('does not add a later research publication to the old dispatch checkpoint obligations', async () => { - const later = state.cooperation!.deliveries!.splice(0)[0]!; - const action = await start(); - state.cooperation!.deliveries!.push(later); - const reminder = cooperative.leadCheckpointInstruction(action); - expect(reminder).toContain('return without a revision'); - expect(reminder).not.toContain(later.id); - }); - - it('drops only the exact source decision already being merged from the checkpoint reminder', async () => { - const action = await start(), delivery = state.cooperation!.deliveries![0]!; - const merging = { deliveryId: delivery.id, taskDigest: delivery.taskDigest, findingDigest: delivery.findingDigest }; - (cooperative as any).pendingSourceResearchDecisions.set(action, [{ ...merging, findingDigest: 'different-finding' }]); - expect(cooperative.leadCheckpointInstruction(action)).toContain('researchDecisions'); - (cooperative as any).pendingSourceResearchDecisions.set(action, [merging]); - expect(cooperative.leadCheckpointInstruction(action)).toContain('return without a revision'); - }); - - it('requires current host feedback to be repaired before returning from the checkpoint', async () => { - state.cooperation!.deliveries = []; - const action = await start(); - state.cooperation!.error = 'math_plan_progress_review_goal_unanswered: goal_0'; - const reminder = cooperative.leadCheckpointInstruction(action); - expect(reminder).toContain('Repair the current host plan validation feedback'); - expect(reminder).not.toContain('return without a revision'); - delete state.cooperation!.error; - expect(cooperative.leadCheckpointInstruction(action)).toContain('return without a revision'); - }); - - it('bounds repeated incomplete checkpoints even when each saves different draft prose', async () => { - for (const node of state.cooperation!.tasks) node.task.status = 'paused'; - for (let attempt = 0; attempt < 2; attempt++) { - const action = await start(); - fs.appendFileSync(notes(), `\nUnfinished draft slice ${attempt}.\n`); - await checkpoint(action); - } - expect(state.cooperation!.planRejection).toMatchObject({ stalled: true, - error: expect.stringContaining('math_plan_research_decisions_missing') }); - expect(state.cooperation!.lastLeadPauseInputDigest).toBeUndefined(); - expect(await cooperative.next(workers[0], budget)).toBeUndefined(); - expect(events.some(item => item.event === 'plan_stalled')).toBe(true); - expect(pendingProposals()).toHaveLength(1); - }); - - it('reopens a stalled graph when only its decision response is corrected', async () => { - for (const node of state.cooperation!.tasks) node.task.status = 'paused'; - state.cooperation!.deliveries!.push({ ...state.cooperation!.deliveries![0], id: 'second-delivery' }); - const incomplete = (reason: string) => ({ ...graph(), researchDecisions: [{ - deliveryId: 'proposal-delivery', outcome: 'decline', reason, - }] }); - const first = await start(planText(incomplete('The proposed bridge does not yet apply.'))); - await checkpoint(first); - expect(state.cooperation!.planRejection).toMatchObject({ stalled: false, - error: 'math_plan_research_decisions_missing: second-delivery' }); - const correction = incomplete('The proposed bridge needs an additional uniformity hypothesis.'); - const second = await start(planText(correction)); - await checkpoint(second); - // A changed decision is not deduplicated merely because the graph and remaining error are unchanged. - expect(state.cooperation!.planRejection).toMatchObject({ stalled: false }); - const repeated = await start(planText(correction)); - await checkpoint(repeated); - expect(state.cooperation!.planRejection).toMatchObject({ stalled: true }); - expect(await cooperative.next(workers[0], budget)).toBeUndefined(); - write({ ...correction, researchDecisions: [...correction.researchDecisions, { - deliveryId: 'second-delivery', outcome: 'decline', reason: 'This independent finding has the same missing hypothesis.', - }] }); - const resumed = await cooperative.next(workers[0], budget); - if (resumed?.kind !== 'lead') throw new Error('fixture_expected_corrected_decision_dispatch'); - expect(cooperative.started(workers[0], resumed)).toBe(true); - cooperative.activate(workers[0], resumed, async () => {}, notify); - await checkpoint(resumed); - expect(state.cooperation!.researchDecisions?.map(record => record.deliveryId)).toEqual(['proposal-delivery', 'second-delivery']); - expect(state.cooperation!.error).toBeUndefined(); - expect(state.cooperation!.planRejection).toBeUndefined(); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('presents simultaneous current research and progress answers in one mandatory response object', async () => { - const action = await start(); - const progress = state.cooperation!.goalProgress!; - progress.pending = { id: 'current-progress-review', at: Date.now(), - goalKeys: progress.goals.map(goal => goal.key), goalIds: progress.goals.map(goal => goal.taskId!) }; - (cooperative as any).presentedGoalProgress.set(action, progress.pending.id); - const context = buildResearchContext(problem, { ...state, cooperation: cooperative.contextState(action, workers[0]) }, { - root: directory, worktree: workers[0].worktree, environment: {}, taskText: 'Prove the frozen original targets.', - retrievalRoot: directory, maxOptionalContextBytes: 0, assignment: action, - frozenContexts: Object.fromEntries(problem.ownedFiles.filter(file => file.endsWith('.lean')).map(file => - [file, fs.readFileSync(path.join(workers[0].worktree, problem.projectRelative, file), 'utf8')])), - }); - for (const continuation of [false, true]) { - const dispatch = finalizeResearchDispatch(context, { continuation }); - const matched = dispatch.message.match(/Current response template[^\n]*\n([^\n]+)\n/u); - expect(matched).not.toBeNull(); - const response = JSON.parse(matched![1]); - expect(response).toMatchObject({ baseVersion: action.planVersion, upsert: [], - researchDecisions: [{ deliveryId: 'proposal-delivery' }], - progressReview: { id: progress.pending.id, nextChecks: [{ - action: expect.any(String), objective: expect.any(String), expectedEvidence: expect.any(String), targetTaskId: expect.any(String), - }] } }); - expect(response.researchDecisions[0].outcome).toContain(' parseLeadPlan(problem, response, (cooperative as any).planPatchBase())).toThrow('math_plan_progress_review_invalid'); - expect(dispatch.manifest.included).toContainEqual(expect.objectContaining({ id: 'lead-decision-requirements', required: true })); - expect(dispatch.manifest.optionalBytes).toBe(0); - } - write({ ...graph(), ...decide('decline') }); - await cooperative.pulse(); - expect(cooperative.leadCheckpointHandoff(action)?.reason).toContain('math_plan_progress_review_missing'); - expect(state.cooperation!.goalProgress!.pending?.id).toBe(progress.pending.id); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - }); - - it('does not let a saved pause or completed-input digest hide an unanswered finding', async () => { - write(graph()); - // A restored pre-fix archive can contain both markers despite never answering this publication. - state.cooperation!.lastLeadInputDigest = (cooperative as any).planningInputDigest(); - state.cooperation!.lastLeadPauseInputDigest = (cooperative as any).leadPauseInputDigest(); - state.cooperation!.leadWakes = { requested: 1, consumed: 0, settled: 0 }; - const action = await start(); - expect(cooperative.contextState(action, workers[0]).leadResearchInputIds).toEqual(['proposal-delivery']); - expect(cooperative.contextState(action, workers[0]).leadDecisionInstruction) - .toBe(cooperative.leadCheckpointInstruction(action)); - expect(cooperative.contextState(action, workers[0]).leadDecisionInstruction) - .toContain('researchDecisions: ["proposal-delivery"]'); - }); - - it('keeps initial dispatch response validation even if an existing graph is present', async () => { - const action = await start(planText({ ...graph(), ...decide('decline') })); - action.initialPlanNonce = 'initial-dispatch-with-bootstrap-graph'; - await checkpoint(action); - // Ordinary validation accepts the inherited graph; the unchanged-draft shortcut is not taken. - expect(events.some(item => item.event === 'plan_updated')).toBe(true); - expect(events.some(item => item.event === 'lead_checkpoint_saved')).toBe(false); - }); - - it.each(['final', 'request-failure', 'checkpoint'] as const)('still validates an inherited graph delivered as %s', async kind => { - const action = await start(planText({ ...graph(), ...decide('decline') })), commit = commitSolverSources(problem, workers[0].worktree); - cooperative.deactivate(workers[0]); - const result = await cooperative.deliver(workers[0], action, commit, kind !== 'final', kind === 'final' ? 'checkpoint' : kind); - expect(result).toEqual({ checkWhole: false, ...(kind === 'request-failure' ? { savedPlan: true } : {}) }); - expect(events.some(item => item.event === 'plan_updated')).toBe(true); - expect(events.some(item => item.event === 'lead_checkpoint_saved')).toBe(false); - // The declined proposal is not added to the plan. - expect(pendingProposals()).toHaveLength(1); - }); - - it('accepts a changed complete checkpoint plan as a new unproved obligation', async () => { - const action = await start(); - write({ ...graph(), tasks: [...graph().tasks, proposal], ...decide('adopt') }); - await checkpoint(action); - expect(state.cooperation!.tasks.find(node => node.task.id === proposal.id)).toMatchObject({ status: 'pending', task: proposal }); - expect(state.cooperation!.tasks.find(node => node.task.id === proposal.id)?.integratedCheck).toBeUndefined(); - expect(pendingProposals()).toEqual([]); - expect(events.some(item => item.event === 'lead_checkpoint_saved' || item.event === 'plan_rejected')).toBe(false); - }); - - it('keeps an already published graph when a checkpoint retains the inherited old notes', async () => { - const action = await start(), inherited = fs.readFileSync(notes(), 'utf8'); - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(action)!), JSON.stringify({ - kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, - ...graph(), tasks: [...graph().tasks, proposal], ...decide('adopt'), - }) + '\n'); - await cooperative.pulse(); - expect(state.cooperation!.planPublication).toBeDefined(); - fs.writeFileSync(notes(), inherited); - await checkpoint(action); - expect(state.cooperation!.tasks.some(node => node.task.id === proposal.id)).toBe(true); - expect(pendingProposals()).toEqual([]); - expect(events.some(item => item.event === 'lead_checkpoint_saved' || item.event === 'plan_rejected')).toBe(false); - }); - - it('merges saved Lean sources despite an unchanged control block and still requests whole-proof checking', async () => { - const action = await start(), file = path.join(workers[0].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', 'lemma checkpoint_draft : True := by trivial\ntheorem add_zero')); - await expect(checkpoint(action)).resolves.toEqual({ checkWhole: true }); - const canonical = state.cooperation!.canonicalCommit!; - expect(committedSource(workers[0].worktree, canonical, `${problem.projectRelative}/Submission.lean`)).toContain('lemma checkpoint_draft : True'); - expect(events.some(item => item.event === 'lead_draft_preserved')).toBe(true); - expect(state.cooperation!.error).toContain('math_plan_research_decisions_missing'); - expect(pendingProposals()).toHaveLength(1); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); -}); diff --git a/tests/solverLeadInheritedDraftCorrection.test.ts b/tests/solverLeadInheritedDraftCorrection.test.ts deleted file mode 100644 index 3494d0cf..00000000 --- a/tests/solverLeadInheritedDraftCorrection.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { parseCooperationPlan, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -type Lead = Extract; - -describe('correction of inherited rejected Lead drafts', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - let directory: string, problem: SolverProblem, workers: ResearchWorker[], state: SolverRunState; - let cooperative: CooperativeResearch, controller: AbortController; - let notify: ReturnType Promise>>; - let proposal: CooperativeTask; - const graph = () => ({ tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(route => route.group) }); - const notes = () => path.join(workers[0].worktree, 'RESEARCH.md'); - const write = (response: unknown) => fs.writeFileSync(notes(), '```math-plan\n' + JSON.stringify(response) + '\n```\n'); - const decision = () => ({ researchDecisions: [{ deliveryId: 'unanswered-finding', outcome: 'decline', - reason: 'The accepted route uses a different exact construction.' }] }); - const start = async () => { - const action = await cooperative.next(workers[0], budget); - if (action?.kind !== 'lead' || !action.planNonce) throw new Error('fixture_expected_lead_revision'); - expect(cooperative.started(workers[0], action)).toBe(true); - cooperative.activate(workers[0], action, async () => {}, notify); - return action; - }; - const checkpoint = async (action: Lead) => { - const commit = commitSolverSources(problem, workers[0].worktree); - cooperative.deactivate(workers[0]); - return cooperative.deliver(workers[0], action, commit, true, 'scheduling-checkpoint'); - }; - const rejectForRetry = async () => { - const action = await start(); - await checkpoint(action); - expect(state.cooperation!.error).toContain('math_plan_research_decisions_missing'); - expect(state.cooperation!.planRejection?.stalled).toBe(false); - return start(); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(() => { throw new Error('fixture_unexpected_proof_acceptance'); }); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('lead-inherited-draft-correction-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'researcher')]; - const question: CooperativeTask = { id: 'question', kind: 'research', objective: 'Find an exact bridge.', dependsOn: [], revision: 0 }; - proposal = { id: 'bridge', kind: 'lemma', objective: 'Prove the exact bridge.', theoremName: 'Tutorial.bridge', - proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - const plan = parseCooperationPlan(problem, { tasks: [question, ...problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, status: 'paused', - }))] }); - state = solverState(problem, example.workspace, { runId: 'inherited-draft-correction', phase: 'running', - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'checking', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, attempts: 0, status: task.id === question.id ? 'completed' : 'pending' })), - groups: plan.groups.map(group => ({ group, turns: 0 })), - deliveries: [{ id: 'unanswered-finding', producer: workers[1].id, taskId: question.id, taskDigest: taskVersion(question), - kind: 'research', status: 'advisory', summary: 'An exact bridge awaits the Lead decision.', statement: '', premises: [], - dependencies: [], remainingObligations: [], evidenceRefs: [], createdAt: 1, lemmaRequests: [proposal] }] } }); - controller = new AbortController(); notify = vi.fn(async (_message: string) => {}); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal }); - write(graph()); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.verify).not.toHaveBeenCalled(); expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('reports a previously rejected inherited draft at checkpoint handoff without publishing it', async () => { - const action = await rejectForRetry(), before = structuredClone(state.cooperation!.tasks); - await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); - expect(cooperative.leadCheckpointHandoff(action)?.reason).toContain('math_plan_research_decisions_missing'); - expect(cooperative.leadCheckpointInstruction(action)).toContain('unanswered-finding'); - expect(state.cooperation!.tasks).toEqual(before); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - expect(state.cooperation!.planPublication).toBeUndefined(); - write({ ...graph(), ...decision() }); - expect(cooperative.leadCheckpointHandoff(action)).toBeUndefined(); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - expect(state.cooperation!.planPublication).toBeUndefined(); - expect(state.cooperation!.error).toContain('math_plan_research_decisions_missing'); - await checkpoint(action); - expect(state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'unanswered-finding', outcome: 'decline' })); - expect(state.cooperation!.error).toBeUndefined(); - }); - - it('requests the decision without diagnosing an ordinary accepted baseline as a rejected draft', async () => { - const action = await start(); - expect(cooperative.leadCheckpointHandoff(action)).toEqual({ reason: undefined }); - expect(state.cooperation!.planRejection).toBeUndefined(); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - }); - - it('does not mistake an accepted baseline for a different previously rejected draft', async () => { - const action = await start(); - write({ ...graph(), tasks: [...graph().tasks, proposal] }); - await checkpoint(action); - expect(state.cooperation!.planRejection?.error).toContain('math_plan_research_decisions_missing'); - write(graph()); - const retry = await start(); - expect(cooperative.leadCheckpointHandoff(retry)).toEqual({ reason: undefined }); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - }); - - it('does not correct a missing research decision already settled by other accepted evidence', async () => { - const action = await rejectForRetry(); - const finding = state.cooperation!.deliveries!.find(record => record.id === 'unanswered-finding')!; - state.cooperation!.researchDecisions = [{ deliveryId: finding.id, taskDigest: finding.taskDigest, - findingDigest: finding.findingDigest, outcome: 'decline', reason: 'An accepted decision already settled this finding.', - at: 1, planVersion: state.cooperation!.planVersion! }]; - expect(cooperative.leadCheckpointHandoff(action)?.reason).toBeUndefined(); - expect(state.cooperation!.planPublication).toBeUndefined(); - }); -}); diff --git a/tests/solverLibraryRequest.test.ts b/tests/solverLibraryRequest.test.ts index b1974ed7..f76d68b1 100644 --- a/tests/solverLibraryRequest.test.ts +++ b/tests/solverLibraryRequest.test.ts @@ -10,9 +10,9 @@ import { agentLibrary, LibraryInstallationRequested, LIBRARY_REQUEST_FILE } from import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; import { directSolverModules, type SolverModules } from '../src/solver/modules'; import { committedSource, git, readSolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { runResearchLead } from '../src/solver/research'; import { deferred } from './helpers/async'; -import { workerAccess } from './helpers/cooperation'; +import { workerAccess } from './helpers/solver'; import { temporaryDirectory } from './helpers/files'; import { leadWorker, solverState } from './helpers/solver'; import { failedBatch, verifiedBatch } from './helpers/verifier'; @@ -87,7 +87,7 @@ function fixture({ parallel = false, previous = false } = {}) { message: 'Inspect the pinned catalog and save an installation request when required.', scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } }) }, }; - const completion = runResearchWorkers({ state, workers, modules, access, root: directory, + const completion = runResearchLead({ state, modules, access: access.get('solver')!, root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original identity.', executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, deadline: Infinity, maxTurns: state.turns + workers.length, maxTurnMs: Infinity, maxTotalTokens: 1000, @@ -108,63 +108,6 @@ function reportUsage(options: MathAgentOptions) { } describe('solver library installation handoff', () => { - it('waits for every writer to close, retains cumulative usage and never accepts the request as a proof', async () => { - const f = fixture({ parallel: true, previous: true }); - const bothStarted = gate(), requestClosing = gate(), peerClosing = gate(); - const releaseRequest = gate(), releasePeer = gate(), peerTurn = gate(); - const closes = [vi.fn(), vi.fn()]; - const draft = challenge.replace('by sorry', 'by\n -- The saved draft still needs its library dependency.\n sorry'); - let started = 0; - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const index = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID === 'solver' ? 0 : 1; - return { threadId: `library-request-${index}`, usageSource: 'upstream-requests', - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted(`turn-${index}`); reportUsage(options); - if (++started === 2) bothStarted.resolve(); - await bothStarted.promise; - if (index) return peerTurn.promise; - fs.writeFileSync(path.join(options.workspace, f.problem.projectRelative, 'Submission.lean'), draft); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'Saved work needs Catalog.identity.\n'); - expect(f.request(options.workspace)).toMatchObject({ status: 'queued' }); - return 'completed'; - }, interrupt: async () => {}, close: async () => { - closes[index](); - if (index) { peerClosing.resolve(); peerTurn.resolve('interrupted'); await releasePeer.promise; } - else { requestClosing.resolve(); await releaseRequest.promise; } - } }; - }); - let settled = false; - const result = f.run(open).then(value => ({ value }), error => ({ error })); - void result.then(() => { settled = true; }); - await requestClosing.promise; - expect(settled).toBe(false); expect(closes[1]).not.toHaveBeenCalled(); - expect(f.check).not.toHaveBeenCalled(); - releaseRequest.resolve(); await peerClosing.promise; - expect(settled).toBe(false); - releasePeer.resolve(); - const outcome = await result; - expect(outcome).toHaveProperty('error'); - const error = 'error' in outcome ? outcome.error : undefined; - expect(error).toBeInstanceOf(LibraryInstallationRequested); - expect(error).toMatchObject({ worktree: f.workers[0].worktree, request: { - names: ['Catalog.identity'], catalogDigest: f.catalog.digest, problemReceiptDigest: f.problem.receiptDigest, - } }); - for (const close of closes) expect(close).toHaveBeenCalledOnce(); - expect(open).toHaveBeenCalledTimes(2); expect(f.state.turns).toBe(4); - expect(f.state.usage).toEqual({ inputTokens: 132, outputTokens: 88, totalTokens: 220 }); - expect(f.state.tokenBudget).toMatchObject({ reportedTotalTokens: 220, usageComplete: true, status: 'available' }); - for (const worker of f.state.workers!) expect(worker).toMatchObject({ turns: 2, phase: 'finished', - usageAccounting: { startedTurns: 2, reportedTurns: 2, pending: false, incomplete: false }, - requestUsageAccounting: { startedRequests: 2, reportedRequests: 2, pendingRequests: 0, incomplete: false } }); - expect(f.state.check).toBeUndefined(); expect(f.state.candidate).toBeUndefined(); - expect(f.state.winningWorker).toBeUndefined(); expect(f.state.error).toBeUndefined(); - expect(f.check).not.toHaveBeenCalled(); expect(host.verify).not.toHaveBeenCalled(); - expect(committedSource(f.workers[0].worktree, git(f.workers[0].worktree, ['rev-parse', 'HEAD']), - path.join(f.problem.projectRelative, 'Submission.lean'))).toBe(draft); - expect(fs.existsSync(path.join(f.workers[0].worktree, f.problem.projectRelative, moduleFile))).toBe(false); - expect(f.events.filter(item => item.event === 'library_installation_requested')).toHaveLength(1); - }); - it.each(['catalog', 'problem', 'seed', 'name', 'json'] as const)( 'rejects an invalid %s request and continues ordinary proof checking without installation', async kind => { const f = fixture(), close = vi.fn(async () => {}); @@ -194,36 +137,4 @@ describe('solver library installation handoff', () => { expect(fs.existsSync(path.join(f.workers[0].worktree, f.problem.projectRelative, moduleFile))).toBe(false); }); - it('returns an accepted winner when a peer finishes its pending request during winner cleanup', async () => { - const f = fixture({ parallel: true }); - host.verify.mockImplementation(async request => verifiedBatch(request, { sessionId: 'library-request-winner' })); - const bothStarted = gate(), requestClosing = gate(), releaseRequest = gate(); - const closes = [vi.fn(), vi.fn()]; - let started = 0; - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const index = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID === 'solver' ? 0 : 1; - return { threadId: `winner-request-${index}`, usageSource: 'upstream-requests', - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted(`winner-turn-${index}`); reportUsage(options); - if (++started === 2) bothStarted.resolve(); - await bothStarted.promise; - if (index) { f.request(options.workspace); return 'completed'; } - await requestClosing.promise; - fs.writeFileSync(path.join(options.workspace, f.problem.projectRelative, 'Submission.lean'), - challenge.replace('by sorry', 'by rfl')); - return 'completed'; - }, interrupt: async () => {}, close: async () => { - closes[index](); - if (index) { requestClosing.resolve(); await releaseRequest.promise; } - } }; - }); - const winner = await f.run(open, event => { if (event === 'candidate_selected') releaseRequest.resolve(); }); - expect(winner).toMatchObject({ worktree: f.workers[0].worktree, check: { passed: true } }); - expect(f.state.winningWorker).toBe('solver'); expect(f.state.check).toBe(winner!.check); - expect(f.check).toHaveBeenCalledOnce(); expect(host.verify).toHaveBeenCalledOnce(); - for (const close of closes) expect(close).toHaveBeenCalledOnce(); - expect(f.state.turns).toBe(2); expect(f.state.usage).toEqual({ inputTokens: 120, outputTokens: 80, totalTokens: 200 }); - expect(f.state.tokenBudget).toMatchObject({ reportedTotalTokens: 200, usageComplete: true }); - expect(f.state.error).toBeUndefined(); - }); }); diff --git a/tests/solverLivenessRecovery.test.ts b/tests/solverLivenessRecovery.test.ts deleted file mode 100644 index 0d374bb6..00000000 --- a/tests/solverLivenessRecovery.test.ts +++ /dev/null @@ -1,543 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { MAX_RESEARCH_NOTES_BYTES } from '../src/solver/deliveries'; -import { IDLE_PEER_WAKE_MS } from '../src/solver/leadInbox'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { runResearchWorkers } from '../src/solver/research'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -const SEEDED_DECISION = 'The exact route choice needs a Lead decision.'; -// A Lead revision turn has one fixed decision slice. -const LEAD_REVISION_MS = 10 * 60_000; - -describe('Lead planning liveness across checkpoints and restore', () => { - let directory: string; - let controllers: AbortController[], running: Promise[]; - - beforeEach(() => { - vi.useFakeTimers(); - controllers = []; running = []; - // Intake is pulsed explicitly; advancing hours must not run the unrelated 200 ms file poller. - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - }); - afterEach(async () => { - controllers.forEach(controller => controller.abort()); - await Promise.allSettled(running); - vi.useRealTimers(); vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - }); - - function fixture({ seedDecision = true } = {}) { - const example = localExample('solver-liveness-recovery-', 'lead'); - directory = example.directory; - const { problem, workspace } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'idle-prover', { role: 'prover' }), - peerWorker(example, 'researcher')]; - const plan = parseCooperationPlan(problem, { tasks: [ - { id: 'investigate', kind: 'research', ownerId: 'researcher', objective: 'Find the precise missing construction.' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, ...target, dependsOn: ['investigate'] })), - ] }); - const check = vi.fn(async () => { throw new Error('fixture_unexpected_proof_acceptance'); }); - // Decision tests start with an unanswered request; pause and thread-reuse - // tests start with an ordinary finding and its real one-shot planning wake. - const investigate = plan.tasks.find(task => task.id === 'investigate')!; - const summary = seedDecision ? SEEDED_DECISION : 'The saved construction still leaves both original goals unproved.'; - const decision = JSON.stringify({ taskId: investigate.id, summary, conclusion: 'inconclusive', needsDecision: seedDecision }); - const fixture = { - state: solverState(problem, workspace, { runId: 'liveness-recovery-fixture', phase: 'prepared', - environmentDigest: mathDigest('offline-liveness-environment'), - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })), - ...(!seedDecision ? { leadWakes: { requested: 1, consumed: 0, settled: 0, - recent: [{ seq: 1, reason: 'research-finding' as const, at: 1 }] } } : {}), - deliveries: [{ id: 'route-decision', producer: 'researcher', taskId: investigate.id, taskDigest: taskVersion(investigate), - kind: 'research' as const, status: 'advisory' as const, finding: decision, findingDigest: mathDigest(decision), - summary, statement: '', premises: [], dependencies: [], remainingObligations: [], evidenceRefs: [], - createdAt: 1 }] } }), - workers, check, - }; - const start = (behavior: { saveResearchProgress?: boolean; saveLeadProgress?: boolean } = {}) => { - const controller = new AbortController(); controllers.push(controller); - const events: { event: string; details?: Record; at: number }[] = []; - const messages: { assignment: CooperativeAction; inbox: string[]; threadId: string; researchInputIds?: string[]; - progressReview?: { id: string }; eventCount: number }[] = []; - const notifications: { workerId: string; message: string }[] = []; - const sessionInterrupts: { workerId: string; threadId: string }[] = [], sessionCloses: typeof sessionInterrupts = []; - const firstLead = deferred(), firstResearch = deferred(); - const leadReturns = new Map>>(); - let cooperation: CooperativeResearch | undefined; - const dispatched = new Map(); - const actual = (action: CooperativeAction) => action.kind === 'lead' - ? dispatched.get(action.planNonce ?? action.initialPlanNonce!) ?? action : action; - const next = CooperativeResearch.prototype.next; - const capture = vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function(worker, budget) { - cooperation = this; - const action = await next.call(this, worker, budget); - if (action?.kind === 'lead') dispatched.set(action.planNonce ?? action.initialPlanNonce!, action); - return action; - }); - let sessionsOpened = 0, researchSlices = 0, leadSlices = 0; - const open = vi.fn(async (options: MathAgentOptions): Promise => { - let active: ReturnType> | undefined; - const threadId = options.threadId ?? `${path.basename(options.workspace)}-offline-thread-${++sessionsOpened}`; - const workerId = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - return { threadId, - interrupt: async () => { - sessionInterrupts.push({ workerId, threadId }); - if (behavior.saveLeadProgress && workerId === workers[0].id) - fs.appendFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), - `Lead construction ${++leadSlices}: a new exact inference is saved for continuation.\n`); - // Keep the research peer active without publishing a new Lead input on every slice. - if (behavior.saveResearchProgress && workerId === workers[2].id && ++researchSlices % 2 === 0) - fs.appendFileSync(path.join(workers[2].worktree, 'RESEARCH.md'), - `Construction candidate ${researchSlices / 2}: the draft is saved; its exact remaining case is unproved.\n`); - active?.resolve('interrupted'); - }, - close: async () => { sessionCloses.push({ workerId, threadId }); active?.resolve('interrupted'); }, notify: async message => { - notifications.push({ workerId: options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!, message }); - }, - run: async (message, _messageId, _workspace, onStarted) => { - const parsed = JSON.parse(message) as (typeof messages)[number]; - messages.push({ ...parsed, threadId, eventCount: events.length }); active = deferred(); - onStarted(`offline-turn-${messages.length}`); - // The advisory clock measures mathematical work, so a turn arms it once the model produces - // its first item. This offline writer produces one immediately; only provider latency waits. - options.onActivity?.({ event: 'reasoning' }); - if (parsed.assignment.kind === 'lead') { - leadReturns.set(parsed.assignment.planNonce ?? parsed.assignment.initialPlanNonce!, active); - firstLead.resolve(); - } - else if (parsed.assignment.kind === 'task' && parsed.assignment.task.id === 'investigate') firstResearch.resolve(); - else throw new Error('fixture_unexpected_assignment'); - return active.promise; - } }; - }); - const modules: SolverModules = { ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M2: { ...directSolverModules.M2, check, checkTask: check }, - M4: { ...directSolverModules.M4, build: (_problem, state, access) => { - const message = JSON.stringify({ assignment: access.assignment, - inbox: state.cooperation?.deliveries?.map(delivery => delivery.summary) ?? [], - ...(access.assignment?.kind === 'lead' ? { researchInputIds: state.cooperation?.leadResearchInputIds ?? [] } : {}), - ...(access.assignment?.kind === 'lead' && state.cooperation?.goalProgress?.pending - ? { progressReview: { id: state.cooperation.goalProgress.pending.id } } : {}) }); - return { instructions: 'Offline coordination fixture.', message, continuationMessage: message, - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } }; - } } }; - const completion = runResearchWorkers({ state: fixture.state, workers, modules, - access: workerAccess(workers, directory), root: directory, buildFile: path.join(directory, 'unused-build.json'), - taskText: 'Prove the frozen original targets.', executable: 'offline-fixture', profile: 'offline-fixture', - signal: controller.signal, deadline: Infinity, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens: 0, - save: () => {}, emit: (event, details) => events.push({ event, details, at: Date.now() }) }); - running.push(completion); void completion.catch(() => {}); - const leads = () => messages.filter(message => message.assignment.kind === 'lead'); - const expectScheduledLeadTurns = (after: number) => { - const turns = leads(); - for (let index = after; index < turns.length; index++) { - const turn = turns[index], previous = turns[index - 1]; - const triggers = events.slice(previous.eventCount, turn.eventCount); - const reviews = triggers.filter(item => item.event === 'goal_progress_review_dispatched'); - const idleWakes = triggers.filter(item => item.event === 'lead_woken_for_idle_peers'); - // A pending review can share an idle wake turn; count the turn once and verify its exact presented ID. - expect(reviews.length > 0 || idleWakes.length > 0).toBe(true); - if (turn.progressReview) { - expect(reviews).toHaveLength(1); - expect(reviews[0].details?.id).toBe(turn.progressReview.id); - expect(events.slice(0, turn.eventCount)).toContainEqual(expect.objectContaining({ - event: 'goal_progress_review_requested', details: expect.objectContaining({ id: turn.progressReview.id }), - })); - } else expect(reviews).toHaveLength(0); - } - return turns.slice(after); - }; - const latestLead = () => { - const message = leads().at(-1)!; - if (message.assignment.kind !== 'lead') throw new Error('fixture_expected_lead'); - return { ...message, assignment: message.assignment }; - }; - const waitForLead = async (previousNonce: string | undefined) => { - for (let tick = 0; tick < 20 && latestLead().assignment.planNonce === previousNonce; tick++) - await vi.advanceTimersByTimeAsync(1_000); - expect(latestLead().assignment.planNonce, JSON.stringify({ - workers: fixture.state.workers?.map(({ id, phase, scheduling, error }) => ({ id, phase, scheduling, error })), - error: fixture.state.cooperation?.error, events: events.slice(-12), - })).not.toBe(previousNonce); - expect(cooperation!.current(actual(latestLead().assignment))).toBe(true); - }; - const publish = async (summary: string, needsDecision = false) => { - const action = messages.findLast(message => message.assignment.kind === 'task')!.assignment; - if (action.kind !== 'task') throw new Error('fixture_expected_research'); - fs.appendFileSync(path.join(workers[2].worktree, assignmentDeliveryFile(action.assignment)), JSON.stringify({ - kind: 'research', finding: { summary, conclusion: 'inconclusive', needsDecision, - remainingObligations: ['The exact missing construction still needs a proof.'], evidenceRefs: [] }, - }) + '\n'); - await cooperation!.pulse(workers[2].id); - expect(fixture.state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ - kind: 'research', summary, producer: workers[2].id })); - }; - /** Publish an unchanged complete plan as the Lead's answer to its dispatched planning input. */ - const answer = async (action = latestLead().assignment, upsert?: { id: string; objective: string }[]) => { - const presented = leads().find(message => message.assignment.kind === 'lead' && - message.assignment.planNonce === action.planNonce); - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(action)!), JSON.stringify({ - kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, - ...(upsert ? { upsert } : { tasks: fixture.state.cooperation!.tasks.map(node => node.task), - groups: fixture.state.cooperation!.groups!.map(route => route.group) }), - researchDecisions: (presented?.researchInputIds ?? []).map(deliveryId => ({ deliveryId, - outcome: 'decline', reason: 'The current evidence does not establish a sound change to this route.' })), - ...(presented?.progressReview ? { progressReview: { id: presented.progressReview.id, - reason: 'Continue the researcher\'s missing-construction investigation: no checked fact is available yet; the next check is a precise construction for the remaining case.', - nextChecks: [{ action: 'construction-check', targetTaskId: 'investigate', - objective: 'Construct the remaining case required by both original goals.', - expectedEvidence: 'An exact construction or a concrete obstruction in the remaining case.' }] } } : {}), - }) + '\n'); - await cooperation!.pulse(workers[0].id); - expect(fixture.state.cooperation!.lastLeadInputDigest).toBeTruthy(); - }; - const stop = async () => { - controller.abort(new Error('fixture_complete')); - await expect(completion).rejects.toThrow('fixture_complete'); - capture.mockRestore(); - }; - const finishLead = (action = latestLead().assignment) => { - const response = leadReturns.get(action.planNonce ?? action.initialPlanNonce!); - if (!response) throw new Error('fixture_unknown_lead_turn'); - response.resolve('completed'); - }; - return { completion, controller, events, messages, notifications, sessionInterrupts, sessionCloses, - leads, expectScheduledLeadTurns, latestLead, waitForLead, publish, answer, finishLead, stop, open, - planningInputDigest: () => (cooperation as unknown as { planningInputDigest: () => string }).planningInputDigest(), - current: (action: CooperativeAction) => cooperation!.current(actual(action)), - ready: ({ research = true } = {}) => Promise.race([Promise.all(research - ? [firstLead.promise, firstResearch.promise] : [firstLead.promise]), completion.then(() => { - throw new Error('fixture_finished_before_dispatch: ' + JSON.stringify({ - workers: fixture.state.workers?.map(({ id, phase, error }) => ({ id, phase, error })), - events: events.slice(-8), - })); - })]) }; - }; - return { ...fixture, get state() { return fixture.state; }, set state(value) { fixture.state = value; }, start }; - } - - it('clears peer recovery after the first acknowledged scheduling checkpoint', async () => { - const fixtureState = fixture({ seedDecision: false }); - const peer = fixtureState.state.workers![2]; - peer.recovery = { phase: 'retrying', reason: 'math_model_request_failed', cycles: 6, - startedAt: Date.now() - 2_000_000, nextRetryAt: Date.now(), waitedMs: 1_320_000 }; - const run = fixtureState.start({ saveResearchProgress: true }); - try { - await run.ready(); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS); - expect(run.events.filter(e => e.event === 'turn_checkpoint' && e.details?.workerId === peer.id).length).toBeGreaterThan(1); - expect(run.events.filter(e => e.event === 'worker_recovered' && e.details?.workerId === peer.id)).toHaveLength(1); - expect(peer.recovery).toMatchObject({ phase: 'recovered', cycles: 6 }); - } finally { await run.stop(); } - }); - - it('replaces a legacy coordination thread once, preserves its draft and resumes the planning thread', async () => { - const fixtureState = fixture({ seedDecision: false }), lead = fixtureState.state.workers![0]; - lead.threadId = 'legacy-mathematical-coordination'; lead.sessionRole = 'lead'; lead.sessionLeadMode = 'coordination'; - const draft = path.join(lead.worktree, 'RESEARCH.md'); - fs.writeFileSync(draft, 'Saved mathematical construction and precise unresolved inference.\n'); - const run = fixtureState.start({ saveLeadProgress: true, saveResearchProgress: true }); await run.ready(); - const first = run.latestLead().threadId; - expect(first).not.toBe('legacy-mathematical-coordination'); - expect(lead.previousThreadIds).toContain('legacy-mathematical-coordination'); - expect(lead.sessionLeadMode).toBe('planning'); - expect(fs.readFileSync(draft, 'utf8')).toContain('Saved mathematical construction'); - await vi.advanceTimersByTimeAsync(3.5 * LEAD_REVISION_MS); - expect(run.leads().length).toBeGreaterThanOrEqual(4); - expect(new Set(run.leads().map(item => item.threadId))).toEqual(new Set([first])); - expect(new Set(run.leads().map(item => (item.assignment as Extract).planNonce)).size) - .toBe(run.leads().length); - expect(run.events.filter(item => item.event === 'context_restarted' && item.details?.workerId === lead.id && - item.details?.reason === 'responsibility')).toHaveLength(1); - const saved = path.join(directory, 'legacy-coordination-state.json'); - writeSolverRunState(saved, fixtureState.state); - await run.stop(); fixtureState.state = readSolverRunState(saved); - expect(fixtureState.state.workers![0].sessionLeadMode).toBe('planning'); - const resumed = fixtureState.start({ saveResearchProgress: true }); await resumed.ready({ research: false }); - expect(resumed.latestLead().threadId).toBe(first); - expect(resumed.events.some(item => item.event === 'context_restarted' && item.details?.workerId === lead.id && - item.details?.reason === 'responsibility')).toBe(false); - expect(fs.readFileSync(draft, 'utf8')).toContain('Saved mathematical construction'); - expect(fixtureState.check).not.toHaveBeenCalled(); - await resumed.stop(); - }); - - it('keeps ordinary Lead planning with new saved inferences on its fixed decision slice and reuses a legacy planning thread', async () => { - const fixtureState = fixture(), lead = fixtureState.state.workers![0]; - lead.threadId = 'legacy-planning'; lead.sessionRole = 'lead'; - const run = fixtureState.start({ saveLeadProgress: true }); await run.ready(); - await vi.advanceTimersByTimeAsync(3 * LEAD_REVISION_MS); - expect(run.leads()).toHaveLength(4); - expect(new Set(run.leads().map(item => item.threadId))).toEqual(new Set(['legacy-planning'])); - expect(lead.previousThreadIds ?? []).toEqual([]); expect(lead.sessionLeadMode).toBe('planning'); - const slices = run.events.filter(item => item.event === 'cooperative_checkpoint_scheduled' && - item.details?.workerId === lead.id).map(item => item.details!.checkpointAfterMs); - expect(slices).toEqual(Array(4).fill(LEAD_REVISION_MS)); - expect(fixtureState.check).not.toHaveBeenCalled(); await run.stop(); - }); - - it('saves oversized Lead notes across a checkpoint and accepts the next plan through the dispatch log', async () => { - const fixtureState = fixture(), run = fixtureState.start(); - try { - await run.ready(); - const lead = fixtureState.workers[0], first = run.latestLead().assignment; - const notes = path.join(lead.worktree, 'RESEARCH.md'); - const line = 'Partial mathematical argument.\n'; - const draft = line.repeat(Math.ceil(MAX_RESEARCH_NOTES_BYTES / Buffer.byteLength(line)) + 1); - fs.writeFileSync(notes, draft); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS); - await run.waitForLead(first.planNonce); - expect(run.events).toContainEqual(expect.objectContaining({ event: 'lead_checkpoint_saved', - details: expect.objectContaining({ reason: 'oversized-notes-draft' }) })); - expect(run.events.some(item => item.event === 'worker_failed')).toBe(false); - const second = run.latestLead().assignment; - const edits = [{ id: 'investigate', objective: 'Check the precise remaining inference.' }]; - await run.answer(second, edits); - run.finishLead(second); - await vi.advanceTimersByTimeAsync(1_000); - expect(fixtureState.state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.task.objective) - .toBe(edits[0].objective); - expect(fixtureState.state.cooperation!.planPublication).toMatchObject({ nonce: second.planNonce, finalized: true }); - expect(fs.readFileSync(notes, 'utf8')).toBe(draft); - expect(run.events.some(item => item.event === 'worker_failed')).toBe(false); - expect(fixtureState.check).not.toHaveBeenCalled(); - } finally { await run.stop(); } - }); - - it('waits for hours after an unchanged checkpoint, then wakes for new evidence until a plan answers it', async () => { - const fixtureState = fixture({ seedDecision: false }), run = fixtureState.start({ saveResearchProgress: true }); await run.ready(); - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS + 60_000); - const pausedTurns = run.leads().length; - expect(fixtureState.state.cooperation!.lastLeadPauseInputDigest).toBeTruthy(); - expect(fixtureState.state.cooperation!.lastLeadInputDigest).toBeUndefined(); - await vi.advanceTimersByTimeAsync(3 * 60 * 60_000); - // The pause itself wakes nothing: each further turn answers an idle peer or a dispatched goal progress review. - const idleWakes = run.events.filter(item => item.event === 'lead_woken_for_idle_peers'); - expect(idleWakes.length).toBeLessThanOrEqual(4); - expect(run.expectScheduledLeadTurns(pausedTurns).some(turn => turn.progressReview)).toBe(true); - const nonces = run.leads().map(message => (message.assignment as Extract).planNonce); - expect(new Set(nonces).size).toBe(nonces.length); - expect(fixtureState.state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.status).toBe('running'); - expect(fixtureState.state.cooperation!.researchCheckpoints?.investigate?.paused).not.toBe(true); - - const previousLead = run.latestLead().assignment, - leadWasWorking = fixtureState.state.workers![0].scheduling?.status === 'working'; - const summary = 'An independent saved construction changes the unanswered planning input.'; - await run.publish(summary, true); - if (leadWasWorking) { - // An already dispatched progress review keeps its frozen input. Finish its - // valid answer and model response before the later finding gets a turn. - await run.answer(previousLead); - run.finishLead(previousLead); - } - await run.waitForLead(previousLead.planNonce); - expect(run.latestLead().inbox).toContain(summary); - await run.answer(); - expect(fixtureState.state.cooperation!.lastLeadInputDigest).toBe(run.planningInputDigest()); - // A real Lead returns after its validated publication; a published plan must - // not be kept active forever by this offline session's unresolved promise. - run.finishLead(); - const answeredTurns = run.leads().length; - await vi.advanceTimersByTimeAsync(60 * 60_000); - const reviews = run.expectScheduledLeadTurns(answeredTurns); - expect(reviews.length).toBeGreaterThan(0); - expect(reviews.every(turn => turn.progressReview)).toBe(true); - const laterWakes = run.events.filter(item => item.event === 'lead_woken_for_idle_peers'); - // This plan answered the research input, but gave the prover no executable work. - expect(laterWakes.length).toBeGreaterThan(idleWakes.length); - expect(laterWakes.at(-1)!.at - laterWakes.at(-2)!.at).toBeGreaterThanOrEqual(8 * IDLE_PEER_WAKE_MS); - expect(fixtureState.state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(run.open.mock.calls.every(([options]) => options.turnTimeoutMs === undefined)).toBe(true); - expect(fixtureState.check).not.toHaveBeenCalled(); expect(fixtureState.state.check).toBeUndefined(); - expect(fixtureState.state.cooperation!.tasks.every(node => !['integrated', 'conditional'].includes(node.status))).toBe(true); - await run.stop(); - }, 30_000); // Four virtual hours include enough isolated Git snapshots to exceed 15 s under load. - - it('wakes as soon as a long Lead turn settles and preserves unresolved peer episodes across unchanged accepted plans', async () => { - const fixtureState = fixture({ seedDecision: false }), run = fixtureState.start({ saveResearchProgress: true }); await run.ready(); - const cooperation = () => fixtureState.state.cooperation!; - const idleWakes = () => run.events.filter(item => item.event === 'lead_woken_for_idle_peers'); - const oldNonce = run.latestLead().assignment.planNonce; - const prover = fixtureState.state.workers!.find(worker => worker.id === 'idle-prover')!; - for (let tick = 0; tick < 20 && prover.scheduling?.wait?.stage !== 'm3-no-ready'; tick++) - await vi.advanceTimersByTimeAsync(1_000); - expect(prover.scheduling).toMatchObject({ status: 'idle', wait: { stage: 'm3-no-ready' } }); - const idleSince = prover.scheduling!.since; - // The peer's own idle clock keeps running while an undecided Lead uses its slice. Once that - // slice pauses, an already-mature peer is due immediately; pausing does not restart its clock. - for (let minute = 0; minute < 60 && !idleWakes().length; minute++) - await vi.advanceTimersByTimeAsync(60_000); - expect(cooperation().lastLeadPauseInputDigest).toBeTruthy(); - // The prover has had nothing ready since before the Lead's first turn, but that turn was cut without a decision, - // so it has not answered the idle peer: the paused Lead is owed one turn once the peer has waited. - expect(cooperation().leadDecisionBasisAt).toBeUndefined(); - expect(idleWakes().map(item => item.details?.workerIds)).toEqual([['idle-prover']]); - expect(idleWakes()[0].at).toBeGreaterThanOrEqual(idleSince + IDLE_PEER_WAKE_MS); - expect(run.latestLead().assignment.planNonce).not.toBe(oldNonce); - // Each woken turn is cut unchanged again; the same peer is re-owed after a doubling delay, never sooner. - for (let minute = 0; minute < 120 && idleWakes().length < 3; minute++) await vi.advanceTimersByTimeAsync(60_000); - const at = idleWakes().map(item => item.at); - expect(at).toHaveLength(3); - expect(at[1] - at[0]).toBeGreaterThanOrEqual(2 * IDLE_PEER_WAKE_MS); - expect(at[2] - at[1]).toBeGreaterThanOrEqual(4 * IDLE_PEER_WAKE_MS); - expect(cooperation().idlePeerWake).toMatchObject({ workerIds: ['idle-prover'], count: 3, - episodes: { 'idle-prover': { since: idleSince, at: at[2], count: 3 } } }); - expect(run.current(run.latestLead().assignment)).toBe(true); - // Accepting the unchanged graph answers its research input but leaves the peer without work. - await run.answer(); - expect(cooperation().leadDecisionBasisAt).toBeGreaterThanOrEqual(at[2]); - expect(cooperation().idlePeerWake?.episodes?.['idle-prover']).toMatchObject({ since: prover.scheduling!.since, count: 3 }); - const answeredTurns = run.leads().length; - await vi.advanceTimersByTimeAsync(3 * 60 * 60_000); - const reviews = run.expectScheduledLeadTurns(answeredTurns); - expect(reviews.length).toBeGreaterThan(0); - expect(idleWakes().length).toBeGreaterThan(3); - expect(idleWakes()[3].at - at[2]).toBeGreaterThanOrEqual(8 * IDLE_PEER_WAKE_MS); - expect(fixtureState.check).not.toHaveBeenCalled(); await run.stop(); - }, 30_000); // Several simulated hours still perform real disposable Git work at each checkpoint. - - it('routes a needs-decision finding arriving during a Lead plan to the next Lead slice instead of letting that plan swallow it', async () => { - const fixtureState = fixture(), run = fixtureState.start({ saveResearchProgress: true }); await run.ready(); - const running = run.latestLead().assignment; - const summary = 'The new scoped obstruction requires an explicit route decision.'; - await run.publish(summary, true); - // A finding does not interrupt the running planning turn; its answer covers only the frozen input. - expect(run.current(running)).toBe(true); - await run.answer(running); - expect(fixtureState.state.cooperation!.lastLeadInputDigest).toBe(running.planningInputDigest); - expect(fixtureState.state.cooperation!.lastLeadInputDigest).not.toBe(run.planningInputDigest()); - // The next slice starts when the answered turn reaches its fixed decision checkpoint. - await vi.advanceTimersByTimeAsync(LEAD_REVISION_MS); - await run.waitForLead(running.planNonce); - expect(run.latestLead().inbox).toContain(summary); - await run.answer(); - expect(fixtureState.state.cooperation!.lastLeadInputDigest).toBe(run.planningInputDigest()); - const settledTurns = run.leads().length; - await vi.advanceTimersByTimeAsync(60 * 60_000); - const reviews = run.expectScheduledLeadTurns(settledTurns); - expect(reviews.length).toBeGreaterThan(0); - expect(reviews.every(turn => turn.progressReview)).toBe(true); - expect(fixtureState.state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(fixtureState.check).not.toHaveBeenCalled(); expect(fixtureState.state.check).toBeUndefined(); - await run.stop(); - }); - - it.each([false, true])('restores an unanswered decision request without losing a newly arrived finding (%s)', async newFinding => { - const fixtureState = fixture(), first = fixtureState.start(); await first.ready(); - const summary = 'Saved external evidence remains unanswered when the process stops.'; - if (newFinding) await first.publish(summary); - const saved = path.join(directory, 'pending-decision-state.json'); - writeSolverRunState(saved, fixtureState.state); - await first.stop(); - fixtureState.state = readSolverRunState(saved); - expect(fixtureState.state.cooperation!.lastLeadInputDigest).toBeUndefined(); - const resumed = fixtureState.start(); await resumed.ready(); - expect(resumed.latestLead().inbox).toContain(SEEDED_DECISION); - if (newFinding) expect(resumed.latestLead().inbox).toContain(summary); - await resumed.answer(); - expect(fixtureState.state.cooperation!.lastLeadInputDigest).toBe(resumed.planningInputDigest()); - expect(fixtureState.state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(fixtureState.check).not.toHaveBeenCalled(); expect(fixtureState.state.check).toBeUndefined(); - await resumed.stop(); - }); -}); - -describe('Lead dispatch responsiveness while peers are working', () => { - let directory: string; - let controller: AbortController; - let cooperation: CooperativeResearch; - - afterEach(async () => { - controller?.abort(new Error('fixture_finished')); - await cooperation?.stop(); - vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - }); - - function waitingLead() { - const example = localExample('solver-dispatch-responsiveness-', 'lead'); - directory = example.directory; - const lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'researcher'); - const plan = parseCooperationPlan(example.problem, { tasks: [ - { id: 'investigate', kind: 'research', objective: 'Construct the exact missing input.' }, - ...example.problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, ...target, dependsOn: ['investigate'] })), - ] }); - const state = solverState(example.problem, example.workspace, { - runId: 'responsive-dispatch-fixture', phase: 'running', - workers: [lead, peer].map(worker => ({ ...worker, phase: 'running', turns: 1 })), - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) }, - }); - const investigating = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - investigating.status = 'running'; investigating.attempts = 1; - investigating.assignment = { taskId: investigating.task.id, taskDigest: taskVersion(investigating.task), - workerId: peer.id, seedCommit: example.problem.baseCommit, assignmentId: 'in-flight-research' }; - controller = new AbortController(); - cooperation = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: directory, signal: controller.signal }); - const scheduler = cooperation as any; - scheduler.changed(); - // A previous deciding turn answered this graph; a later cut saved a pause baseline before - // the Lead's notes changed. These existing durable identities can coexist across checkpoints. - state.cooperation!.lastLeadInputDigest = scheduler.planningInputDigest(); - state.cooperation!.lastLeadPauseInputDigest = scheduler.leadPauseInputDigest(); - fs.appendFileSync(path.join(lead.worktree, 'RESEARCH.md'), 'A later saved Lead draft still needs the working peer.\n'); - expect(scheduler.planningInputDigest()).toBe(state.cooperation!.lastLeadInputDigest); - expect(scheduler.leadPauseInputDigest()).not.toBe(state.cooperation!.lastLeadPauseInputDigest); - // Bound a broken immediate-retry loop so the regression itself cannot starve the test runner. - // Eligibility, digest computation and the dispatch method remain the real implementation. - const nextLead = scheduler.nextLead.bind(cooperation); - const dispatches = vi.spyOn(scheduler, 'nextLead').mockImplementation(async (...args: unknown[]) => { - if (dispatches.mock.calls.length > 4) throw new Error('fixture_dispatch_spun_without_waiting'); - return nextLead(...args); - }); - return { lead, peer, state, investigating, scheduler, dispatches, - budget: { maxTurns: Infinity, remainingMs: 60_000 } }; - } - - it('lets a timer abort a Lead waiting on unchanged planning input and a changed pause draft', async () => { - const { lead, budget, dispatches } = waitingLead(); - let timerHandled = false; - const stop = setTimeout(() => { timerHandled = true; controller.abort(new Error('fixture_stop_requested')); }, 0); - try { - await expect(cooperation.next(lead, budget)).rejects.toThrow('fixture_stop_requested'); - expect(timerHandled).toBe(true); - expect(dispatches).toHaveBeenCalledTimes(1); - } finally { clearTimeout(stop); } - }); - - it('reconsiders a real peer completion delivered by the event loop instead of spinning on old input', async () => { - const { lead, budget, state, investigating, scheduler, dispatches } = waitingLead(); - let peerHandled = false; - const complete = setTimeout(() => { - peerHandled = true; - investigating.status = 'completed'; - investigating.finding = 'The exact construction is now saved; the original proof can use it.'; - scheduler.changed(); - }, 0); - try { - const action = await cooperation.next(lead, budget); - expect(peerHandled).toBe(true); - expect(action).toMatchObject({ kind: 'lead' }); - expect(dispatches).toHaveBeenCalledTimes(2); - expect(state.cooperation!.lastLeadInputDigest).not.toBe(scheduler.planningInputDigest()); - expect(state.cooperation!.tasks.every(node => !['integrated', 'conditional'].includes(node.status))).toBe(true); - } finally { clearTimeout(complete); } - }); -}); diff --git a/tests/solverMathematicalContext.test.ts b/tests/solverMathematicalContext.test.ts index acec1350..17291e5a 100644 --- a/tests/solverMathematicalContext.test.ts +++ b/tests/solverMathematicalContext.test.ts @@ -1,7 +1,7 @@ import { expect, it } from 'vitest'; import { mathToolsUsageInstruction, type MathTools } from '../src/math/mathTools'; import type { SolverRunState } from '../src/solver/archive'; -import type { CooperationState } from '../src/solver/cooperation'; +import type { CooperationState } from '../src/solver/cooperationShared'; import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; import type { SolverProblem } from '../src/solver/problem'; import { taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; @@ -21,56 +21,6 @@ const tools: MathTools = { root: '/tools', digest: 'tools-digest', tools: [ { name: 'references', version: '1', purpose: 'Reference lookup.', commands: ['reference-search'] }, ] }; -it.each(['lead', 'researcher', 'engineer'] as const)('retains mathematical interface and correction rules in full and warm %s dispatches', role => { - const task = role === 'researcher' ? research : goal; - const action: CooperativeAction = role === 'lead' ? { kind: 'lead', seedCommit: 'fixed', planVersion: 'plan', planNonce: 'nonce' } : - { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: role, seedCommit: 'fixed' } }; - const cooperation: CooperationState = { tasks: [goal, research].map(task => ({ task, status: 'pending', attempts: 0 })) }; - const context = buildResearchContext(problem, { cooperation } as unknown as SolverRunState, - { root: '/runtime', worktree, environment: { DEEPSCIENTIST_MATH_TOOLS_SHA256: tools.digest }, mathTools: tools, - taskText: 'Prove target.', retrievalRoot: '/library', maxOptionalContextBytes: 0, assignment: action, - frozenContexts: { 'Submission.lean': 'theorem target : True := /- body omitted -/' } }); - for (const continuation of [false, true]) { - const dispatch = finalizeResearchDispatch(context, { continuation }); - const text = continuation ? dispatch.message : dispatch.instructions; - expect(text).toContain('quantifier order, uniform constants'); - expect(text).toContain('semilinear scalar maps'); - expect(text).toContain('quantitative moment or L² estimate'); - expect(text).toContain('linearity and continuity do not imply norm preservation'); - expect(text).toContain('every continuous linear equivalence or every equivalent norm'); - expect(text).toContain('record the exact missing premise and its consumer for a Lead route decision'); - expect(text).toContain('check integrability of its local model'); - expect(text).toContain('infinite value on a null set does not by itself have an infinite integral'); - expect(text).toContain('old immutable commit or finding digest'); - expect(text).toContain(role === 'lead' ? 'answer the affected shown research deliveries through researchDecisions' : - 'Publish the correction through the current research-finding protocol'); - expect(text).toContain('Use math-python for the installed NumPy, SciPy, SymPy and PySAT'); - expect(text).toContain("reference-search --run-dir '/proof/worker'\\''s directory/.scratch/reference-search' search"); - expect(text).toContain("reference-search --run-dir '/proof/worker'\\''s directory/.scratch/reference-search' read REF-"); - expect(text).toContain('find REF --term'); - expect(text).toContain('open REF --start-line'); - expect(text).toContain('search-batch PLAN.json --workers 2'); - expect(text).toContain('follow REF --direction references --limit 4'); - expect(text).toContain('--retry-failed'); - expect(text).toContain('Provider errors are failed retrievals'); - if (role === 'researcher') { - const contractText = [dispatch.instructions, dispatch.message].join('\n'); - expect(contractText).toContain('proactively search permitted public literature'); - expect(contractText).toContain('omit internal task IDs, OAI namespaces and local paths'); - expect(contractText).toContain('Read the relevant proof section and check assumptions'); - expect(contractText).toContain('advisory-reference-requiring-current-consumer-check'); - } - expect(text).toContain('save stdout separately from stderr progress'); - expect(text).toContain('--file is relative to --workspace'); - expect(text).not.toContain('Use /usr/bin/python3 for Python on this host'); - if (role !== 'lead') { - expect(text).toContain('without writing shared package caches'); - expect(text).toContain('Use this entry point for saved-file checks and temporary #check/#synth probes'); - expect(text).toContain('Remove temporary probe commands before proof delivery'); - } - } -}); - it('offers stateful reference commands only when the frozen tool set includes reference-search', () => { const unavailable = { ...tools, tools: tools.tools.filter(tool => !tool.commands.includes('reference-search')) }; const text = mathToolsUsageInstruction(unavailable, worktree); diff --git a/tests/solverMathematicalGaps.test.ts b/tests/solverMathematicalGaps.test.ts deleted file mode 100644 index a16ff7a2..00000000 --- a/tests/solverMathematicalGaps.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import * as knowledgeApplications from '../src/solver/knowledgeApplications'; -import { MATHEMATICAL_GAP_CONTEXT_MAX_BYTES, mathematicalGapContext, type MathematicalGap } from '../src/solver/mathematicalGaps'; -import { buildResearchContext } from '../src/solver/modules/context'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources } from '../src/solver/problem'; -import { taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { importKnowledgeRuns } from '../src/solver/theoremKnowledgeRuns'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; -let controller: AbortController, action: Extract; -const create = () => cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal }); -const gap = (): MathematicalGap => { - const consumer = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.task; - return { consumer: { taskId: consumer.id, taskDigest: taskVersion(consumer) }, previousGap: 'Need a uniform nondegenerate count', - reduced: 'Only a degenerate count established', remaining: 'PRIVATE_GAP_REMAINDER: c > 0 independent of q for arbitrary k', - evidenceScope: 'A local advisory argument only', reconsiderWhen: ['An exact uniform removal input becomes available'] }; -}; -const publish = (value: unknown) => (cooperative as any).receive(workers[1], action, value, true); -const complete = async (extra: Record = {}, render: (value: Record) => string = JSON.stringify) => { - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), render({ summary: 'Retained exact mathematical gap', - conclusion: 'inconclusive', mathematicalGap: gap(), ...extra })); - const commit = commitSolverSources(state.problem, workers[1].worktree); - await cooperative.deliver(workers[1], action, commit); -}; -const leadContext = () => buildResearchContext(state.problem, { ...state, cooperation: cooperative.contextState() }, { - taskText: 'Frozen original problem', root: directory, worktree: workers[0].worktree, environment: {}, retrievalRoot: directory, - assignment: { kind: 'lead', seedCommit: state.problem.baseCommit }, maxOptionalContextBytes: 0, - frozenContexts: Object.fromEntries(state.problem.ownedFiles.filter(file => file.endsWith('.lean')).map(file => [file, - committedSource(workers[0].worktree, state.problem.baseCommit, `${state.problem.projectRelative}/${file}`)])), -}); -const otherAction = (): Extract => { - const task = state.cooperation!.tasks.find(node => node.task.id === 'other')!.task; - return { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: workers[2].id, - seedCommit: state.problem.baseCommit } }; -}; - -beforeEach(() => { - const example = localExample('solver-gap-', 'lead'), { workspace, problem } = example; - directory = example.directory; - workers = [leadWorker(problem, workspace, 'lead'), ...['proof', 'other'].map(id => peerWorker(example, id))]; - const parsed = parseCooperationPlan(problem, { tasks: [{ id: 'core', kind: 'research', objective: 'Public uniform-count investigation', sharing: 'problem' }, - { id: 'other', kind: 'research', objective: 'Independent route', groupId: 'other' }, - ...problem.targets.map((target, index) => ({ id: `original_goal_${index + 1}`, kind: 'goal', - objective: 'PRIVATE_CONSUMER_CONTRACT', theoremName: target.theoremName, proofPath: target.proofPath, - status: 'paused', sharing: 'problem' }))], - groups: [{ id: 'main', objective: 'Main route' }, { id: 'other', objective: 'Other route' }] }); - const task = parsed.tasks[0]; - action = { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: workers[1].id, - seedCommit: problem.baseCommit, assignmentId: 'gap-assignment', dependencies: [] } }; - state = solverState(problem, workspace, { runId: 'gap-fixture', phase: 'running', cooperation: { canonicalCommit: problem.baseCommit, - groups: parsed.groups.map(group => ({ group, turns: 0 })), tasks: parsed.tasks.map(task => ({ task, attempts: 1, - status: task.id === 'core' ? 'running' : 'pending', ...(task.id === 'core' ? { assignment: action.assignment } : {}) })) } }); - controller = new AbortController(); cooperative = create(); -}); -afterEach(async () => { - controller.abort(); await cooperative.stop(); vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); -}); - -it('publishes a gap through the host and restores its mandatory mathematical scope after a route revision', async () => { - await publish({ kind: 'research', finding: { summary: 'Exact current gap', conclusion: 'inconclusive', mathematicalGap: gap() } }); - const delivery = state.cooperation!.deliveries![0]; - expect(cooperative.contextState().mathematicalGaps?.[0]).toMatchObject({ deliveryId: delivery.id, - scopeStatus: 'current-contracts', evidence: 'model-reported-advisory' }); - const context = leadContext(); - expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'mathematical-gaps', required: true })); - expect(context.message).toContain('independent of q for arbitrary k'); - expect(state.cooperation!.tasks[0].proof).toBeUndefined(); - await cooperative.stop(); - state.cooperation!.tasks[0].task = { ...action.task, objective: 'A revised route', revision: 1 }; - const checkpoint = path.join(directory, 'state.json'); writeSolverRunState(checkpoint, state); state = readSolverRunState(checkpoint); - cooperative = create(); - const history = cooperative.contextState().mathematicalGaps!; - expect(history[0]).toMatchObject({ deliveryId: delivery.id, scopeStatus: 'historical-scope', - remaining: 'PRIVATE_GAP_REMAINDER: c > 0 independent of q for arbitrary k' }); - expect(leadContext().message).toContain('historical-scope'); - (cooperative as any).changed(); - const file = JSON.parse(fs.readFileSync(path.join(workers[0].worktree, 'COOPERATION.json'), 'utf8')); - expect(file.mathematicalGaps[0].scope.source.revision).toBe(0); -}); - -it.each(['recorded-private', 'currently-private'] as const)('hides %s consumers from peer deliveries, findings, history, files and imports', async privacy => { - const consumer = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!; - if (privacy === 'recorded-private') consumer.task = { ...consumer.task, sharing: 'group' }; - await complete(); - expect(state.cooperation!.tasks[0].status).toBe('completed'); - state.cooperation!.history = [{ task: action.task, finding: state.cooperation!.tasks[0].finding }]; - if (privacy === 'currently-private') { - state.cooperation!.history.push({ task: consumer.task }); - consumer.task = { ...consumer.task, sharing: 'group', revision: 1 }; - } - const scoped = cooperative.contextState(otherAction(), workers[2]); - expect(scoped.mathematicalGaps).toEqual([]); expect(scoped.deliveries).toEqual([]); - expect(scoped.tasks.find(node => node.task.id === action.task.id)?.finding).toBeUndefined(); - expect(scoped.history?.find(node => node.task.id === action.task.id)?.finding).toBeUndefined(); - expect(JSON.stringify(scoped)).not.toContain('PRIVATE_GAP_REMAINDER'); - expect(cooperative.contextState(undefined, workers[2]).mathematicalGaps).toEqual([]); - (cooperative as any).changed(); - expect(fs.readFileSync(path.join(workers[2].worktree, 'COOPERATION.json'), 'utf8')).not.toContain('PRIVATE_CONSUMER_CONTRACT'); - expect(fs.readFileSync(path.join(workers[2].worktree, 'COOPERATION.json'), 'utf8')).not.toContain('PRIVATE_GAP_REMAINDER'); - const checkpoint = path.join(directory, 'state.json'); writeSolverRunState(checkpoint, state); - const imported = importKnowledgeRuns([checkpoint], { includeFindings: true }); - expect(imported.findings).toEqual([]); - expect(imported.skipped.some(item => item.reason === 'math_knowledge_run_finding_private')).toBe(true); -}); - -it.each(['adopted', 'unadopted'] as const) -('projects a %s proposal to a late public duplicate without publishing its private gap or source', async status => { - const archive = state.cooperation!, consumer = archive.tasks.find(node => node.task.kind === 'goal')!; - consumer.task = { ...consumer.task, sharing: 'group' }; - await publish({ kind: 'research', finding: { summary: 'Exact bridge with private consumer context', - mathematicalGap: gap(), lemmaRequests: [{ id: 'public_bridge', kind: 'lemma', objective: 'Prove the public bridge', - theoremName: 'Tutorial.public_bridge', proofPath: 'Submission.lean', type: 'True', sharing: 'problem', - dependsOn: [], revision: 0 }] } }); - const original = archive.deliveries![0], proposal = original.lemmaRequests![0]; - if (status === 'adopted') { - const plan = parseCooperationPlan(state.problem, { groups: archive.groups!.map(item => item.group), - tasks: [...archive.tasks.map(node => node.task.id === 'other' ? { ...node.task, dependsOn: [proposal.id] } : node.task), proposal] }); - const records = new Map(archive.tasks.map(node => [node.task.id, node])); - archive.tasks = plan.tasks.map(task => ({ ...(records.get(task.id) ?? { status: 'pending' as const, attempts: 0 }), task })); - } - await complete({ summary: 'Public final bridge request', mathematicalGap: undefined, lemmaRequests: [proposal] }); - const duplicate = archive.deliveries!.find(item => item.id !== original.id)!; - expect(archive.tasks[0].status).toBe('completed'); - expect(archive.deliveries).toHaveLength(2); - expect(archive.tasks.some(node => node.task.id === proposal.id)).toBe(status === 'adopted'); - - const scoped = cooperative.contextState(otherAction(), workers[2]); - expect(scoped.deliveries!.map(item => item.id)).toEqual([duplicate.id]); - expect(scoped.deliveries![0].lemmaRequests).toMatchObject([{ id: proposal.id }]); - for (const privateValue of [original.id, original.commit!, 'PRIVATE_GAP_REMAINDER', 'PRIVATE_CONSUMER_CONTRACT']) - expect(JSON.stringify(scoped)).not.toContain(privateValue); -}); - -it('keeps original-problem deliveries visible to idle workers while applying separate gap privacy', () => { - const delivery = (cooperative as any).record(workers[0], undefined, 'progress', 'advisory', 'Original problem update'); - expect(cooperative.contextState(undefined, workers[2]).deliveries?.map(item => item.id)).toContain(delivery.id); - expect(cooperative.contextState(otherAction(), workers[2]).deliveries?.map(item => item.id)).not.toContain(delivery.id); -}); - -it('imports a public consumer contract from immutable finding evidence and rejects detached gap metadata', async () => { - await complete(); - const checkpoint = path.join(directory, 'state.json'); writeSolverRunState(checkpoint, state); - const imported = importKnowledgeRuns([checkpoint], { includeFindings: true }); - expect(imported.skipped).toEqual([]); - expect(imported.findings?.[0]).toMatchObject({ mathematicalGap: gap(), - scope: { originalConsumer: { kind: 'goal', statementKind: 'source-header' } } }); - state.cooperation!.deliveries![0].mathematicalGap = { ...gap(), remaining: 'Forged independent metadata' }; - writeSolverRunState(checkpoint, state); - expect(importKnowledgeRuns([checkpoint], { includeFindings: true }).skipped[0].reason).toBe('math_knowledge_run_finding_gap_scope_invalid'); -}); - -it.each(['json', 'math-result'] as const)('imports host-normalized %s findings from immutable notes with the same admission rules', async format => { - const fence = String.fromCharCode(96).repeat(3); - await complete({ mathematicalGap: { ...gap(), reduced: ' Only a degenerate count established ' } }, value => format === 'json' - ? JSON.stringify(value) - : 'Explanation and an illustrative JSON object:\n' + fence + 'json\n{"example":true}\n' + fence + '\n\n' + - fence + 'math-result\n' + JSON.stringify(value) + '\n' + fence); - const delivery = state.cooperation!.deliveries![0], normalized = state.cooperation!.tasks[0].finding!; - const notes = committedSource(workers[1].worktree, delivery.commit!, 'RESEARCH.md'); - expect(notes).not.toContain(action.assignment.taskDigest); - expect(JSON.parse(normalized)).toMatchObject({ taskDigest: action.assignment.taskDigest, mathematicalGap: gap() }); - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), 'A changed live journal must not be imported.'); - const checkpoint = path.join(directory, 'state.json'); writeSolverRunState(checkpoint, state); - const imported = importKnowledgeRuns([checkpoint], { includeFindings: true }); - expect(imported.skipped).toEqual([]); - expect(imported.findings).toMatchObject([{ finding: normalized, notes, mathematicalGap: gap(), - provenance: { findingDigest: mathDigest(normalized), notesDigest: mathDigest(notes), sourceCommit: delivery.commit } }]); -}); - -it.each(['summary', 'taskDigest', 'extra-field'] as const)('rejects a forged normalized finding %s even with a recomputed finding digest', async field => { - await complete(); - const node = state.cooperation!.tasks[0], delivery = state.cooperation!.deliveries![0]; - const finding = JSON.parse(node.finding!); - if (field === 'summary') finding.summary = 'Forged independently edited evidence'; - else if (field === 'taskDigest') finding.taskDigest = 'f'.repeat(64); - else finding.unrecordedEvidence = 'This claim was never present in immutable notes'; - node.finding = JSON.stringify(finding); delivery.finding = node.finding; delivery.findingDigest = mathDigest(node.finding); - const checkpoint = path.join(directory, 'state.json'); writeSolverRunState(checkpoint, state); - const imported = importKnowledgeRuns([checkpoint], { includeFindings: true }); - expect(imported.findings).toEqual([]); - expect(imported.skipped).toMatchObject([{ reason: 'math_knowledge_run_finding_source_mismatch' }]); -}); - -it('rejects an invalid progress consumer before writing a blocker or delivery', async () => { - await expect(publish({ kind: 'progress', summary: 'Invalid binding', - mathematicalGap: { ...gap(), consumer: { ...gap().consumer, taskDigest: 'f'.repeat(64) } }, - blockers: [{ mechanism: 'Spurious blocker', scope: 'A claimed local obstruction', evidenceRefs: [] }] })).rejects.toThrow('gap_consumer'); - expect(state.cooperation!.blockers ?? []).toEqual([]); - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.tasks[0].status).toBe('running'); -}); - -it('revalidates the consumer after asynchronous knowledge checks before mutating research publication state', async () => { - const ready = deferred(), waiting = deferred(); - const checkApplications = knowledgeApplications.checkKnowledgeApplications; - vi.spyOn(knowledgeApplications, 'checkKnowledgeApplications').mockImplementationOnce(async (...input) => { - ready.resolve(); await waiting.promise; return checkApplications(...input); - }); - const pending = publish({ kind: 'research', finding: { summary: 'Consumer changed during verification', - conclusion: 'inconclusive', mathematicalGap: gap(), - blockers: [{ mechanism: 'Must not persist', scope: 'A claimed local obstruction', evidenceRefs: [] }] } }); - await ready.promise; - const consumer = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!; - consumer.task = { ...consumer.task, objective: 'Revised original consumer', revision: 1 }; - expect(cooperative.current(action)).toBe(true); - waiting.resolve(); - await expect(pending).rejects.toThrow('gap_consumer'); - expect(state.cooperation!.blockers ?? []).toEqual([]); - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.tasks[0].status).toBe('running'); - expect(state.cooperation!.tasks[0].finding).toBeUndefined(); -}); - -it('retains long valid evidence by reference while mandatory context stays within its byte budget', async () => { - const reference = 'x'.repeat(800_000); - await complete({ evidenceRefs: [reference] }); - const scoped = cooperative.contextState(); - const packet = mathematicalGapContext(scoped.mathematicalGaps!); - expect(Buffer.byteLength(JSON.stringify(packet))).toBeLessThanOrEqual(MATHEMATICAL_GAP_CONTEXT_MAX_BYTES); - expect(packet.entries[0]).toMatchObject({ complete: false, - evidenceRefs: [{ complete: false, bytes: 800_000 }], read: { file: 'COOPERATION.json', collection: 'mathematicalGaps' } }); - const context = leadContext(); - expect(context.manifest!.usedBytes).toBeLessThanOrEqual(context.manifest!.maxBytes); - expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'mathematical-gaps', required: true })); - const file = JSON.parse(fs.readFileSync(path.join(workers[0].worktree, 'COOPERATION.json'), 'utf8')); - expect(file.mathematicalGaps[0].evidenceRefs[0]).toBe(reference); -}); diff --git a/tests/solverNextCheckPlanLifecycle.test.ts b/tests/solverNextCheckPlanLifecycle.test.ts deleted file mode 100644 index 29b87e8e..00000000 --- a/tests/solverNextCheckPlanLifecycle.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, expect, it, vi } from 'vitest'; -import { currentNextCheck } from '../src/solver/nextChecks'; -import { commitSolverSources } from '../src/solver/problem'; -import { parseCooperationPlan, taskVersion } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ createSession: vi.fn() })); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); -const cleanup: (() => Promise)[] = []; -afterEach(async () => { - for (const stop of cleanup.splice(0).reverse()) await stop(); - expect(host.createSession).not.toHaveBeenCalled(); host.createSession.mockReset(); -}); - -async function fixture(routes = false) { - const example = localExample('next-check-plan-lifecycle-'); - const lead = leadWorker(example.problem, example.workspace); - const author = peerWorker(example, 'author'), checker = peerWorker(example, 'checker'); - const proofPath = example.problem.targets[0].proofPath; - const plan = parseCooperationPlan(example.problem, { tasks: [ - ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', - objective: 'Prove the original target.', ...(index ? { status: 'paused' } : { dependsOn: routes ? [] : ['left', 'right'] }) })), - { id: 'witness', kind: 'lemma', declaration: 'definition', objective: 'Construct the shared witness.', - theoremName: 'sharedWitness', type: 'ℕ', proofPath, ownerId: author.id }, - ...['left', 'right'].map(id => ({ id, kind: 'lemma', objective: `Apply the witness to ${id}.`, - theoremName: `shared_${id}`, type: 'True', proofPath, dependsOn: ['witness'] })), - ], ...(routes ? { proofRoutes: ['left', 'right'].map(id => ({ id: `${id}_route`, targetTaskId: 'goal_0', - closingTaskId: id, prerequisiteTaskIds: ['witness'] })) } : {}) }); - const state = solverState(example.problem, example.workspace, { runId: 'next-check-plan-fixture', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, proofRoutes: plan.proofRoutes, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const controller = new AbortController(), events: string[] = []; - const cooperation = cooperativeResearch({ state, workers: [lead, author, checker], retrievalRoot: example.directory, - signal: controller.signal, emit: event => events.push(event) }); - cleanup.push(async () => { controller.abort(); await cooperation.stop(); fs.rmSync(example.directory, { recursive: true, force: true }); }); - await cooperation.restore(); - const acceptPlan = (next: typeof plan) => (cooperation as unknown as { - acceptPlan(plan: typeof next): Promise; - }).acceptPlan(next); - const identity = { problemReceiptDigest: example.problem.receiptDigest, environmentDigest: state.environmentDigest }; - return { state, plan, cooperation, lead, checker, problem: example.problem, acceptPlan, identity, events }; -} - -it('requires the presented check outcome decision even when a checkpoint inherits an unchanged graph', async () => { - const f = await fixture(), archive = f.state.cooperation!, record = archive.nextChecks![0]; - record.status = 'awaiting-decision'; - record.outcome = { checkId: record.id, deliveryId: 'definition-outcome', conclusion: 'inconclusive', - summary: 'The definition still needs its characterizing estimate.', evidenceRefs: ['retained-check-notes'] }; - archive.tasks.find(node => node.task.id === record.taskId)!.status = 'completed'; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const start = async () => { - const action = await f.cooperation.next(f.lead, budget); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead_decision'); - f.cooperation.contextState(action, f.lead); - expect(f.cooperation.started(f.lead, action)).toBe(true); - f.cooperation.activate(f.lead, action, async () => {}, async () => {}); - return action; - }; - const notes = path.join(f.lead.worktree, 'RESEARCH.md'); - fs.writeFileSync(notes, '```math-plan\n' + JSON.stringify(f.plan) + '\n```\n'); - const first = await start(); - const reminder = f.cooperation.leadCheckpointInstruction(first); - expect(reminder).toContain('nextCheckDecisions'); - expect(reminder).toContain(JSON.stringify({ checkId: record.id, outcomeDeliveryId: record.outcome.deliveryId })); - expect(reminder).not.toContain('return without a revision'); - const shownOutcome = record.outcome; - record.outcome = { ...shownOutcome, deliveryId: 'later-definition-outcome' }; - expect(f.cooperation.leadCheckpointInstruction(first)).not.toContain('nextCheckDecisions'); - record.outcome = shownOutcome; - await f.cooperation.deliver(f.lead, first, first.seedCommit, true, 'scheduling-checkpoint'); - f.cooperation.deactivate(f.lead); - expect(archive.error).toContain('math_plan_next_check_decision_required'); - expect(archive.lastLeadPauseInputDigest).toBeUndefined(); - expect(record.status).toBe('awaiting-decision'); - const next = await start(); - fs.writeFileSync(notes, '```math-plan\n' + JSON.stringify({ baseVersion: next.planVersion, upsert: [], - nextCheckDecisions: [{ checkId: record.id, outcomeDeliveryId: record.outcome.deliveryId, - action: 'continue', reason: 'Continue the separately assigned estimate while retaining the unresolved check.' }] }) + '\n```\n'); - await f.cooperation.deliver(f.lead, next, commitSolverSources(f.problem, f.lead.worktree), true, 'scheduling-checkpoint'); - f.cooperation.deactivate(f.lead); - expect(record.status).toBe('decided'); - expect(archive.error).toBeUndefined(); - expect(archive.lastLeadPauseInputDigest).toBeUndefined(); - expect(f.cooperation.leadCheckpointInstruction(next)).toContain('return without a revision'); -}); - -it('preserves the host check and its dispatch identity across a group revision', async () => { - const f = await fixture(), record = f.state.cooperation!.nextChecks![0]; - const changed = structuredClone(f.plan); - changed.groups[0].revision++; - await f.acceptPlan(changed); - expect(f.state.cooperation!.nextChecks).toHaveLength(1); - expect(record.status).toBe('pending'); - expect(currentNextCheck(record, f.state.cooperation!, f.identity)).toBe(true); - expect(f.state.cooperation!.tasks.filter(node => node.task.id === record.taskId)) - .toEqual([expect.objectContaining({ nextCheckId: record.id, status: 'pending' })]); - const action = await f.cooperation.next(f.checker, { maxTurns: Infinity, remainingMs: Infinity }); - expect(action?.kind === 'task' && action.task.id).toBe(record.taskId); - expect(action && f.cooperation.started(f.checker, action)).toBe(true); - expect(f.events).not.toContain('next_check_expired'); - expect(f.state.cooperation!.invalidTaskTransitions ?? []).toEqual([]); -}); - -it('redispatches an unfinished gap check from a fresh report after a group revision', async () => { - const example = localExample('next-check-gap-lifecycle-'); - const lead = leadWorker(example.problem, example.workspace); - const author = peerWorker(example, 'author'), checker = peerWorker(example, 'checker'), prover = peerWorker(example, 'prover'); - const plan = parseCooperationPlan(example.problem, { tasks: [ - ...example.problem.targets.map((target, index) => ({ ...target, id: `goal_${index}`, kind: 'goal', - objective: 'Prove the original target.', ownerId: prover.id })), - { id: 'survey', kind: 'research', objective: 'Study the missing step.', ownerId: author.id }, - ] }); - const state = solverState(example.problem, example.workspace, { runId: 'next-check-gap-fixture', phase: 'running', - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const controller = new AbortController(); - const cooperation = cooperativeResearch({ state, workers: [lead, author, checker, prover], retrievalRoot: example.directory, - signal: controller.signal }); - cleanup.push(async () => { controller.abort(); await cooperation.stop(); fs.rmSync(example.directory, { recursive: true, force: true }); }); - await cooperation.restore(); - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const archive = state.cooperation!, target = plan.tasks.find(task => task.id === 'goal_0')!; - const mathematicalGap = { - consumer: { taskId: target.id, taskDigest: taskVersion(target) }, previousGap: 'Missing the main inference.', - remaining: 'Connect the estimates.', reduced: 'The estimates are stated.', evidenceScope: 'Current goal.', - reconsiderWhen: [], nextCheck: { action: 'feasibility', objective: 'Check the remaining inference.', - expectedEvidence: 'Find an exact missing premise.' }, - }; - const report = async (summary: string) => { - const action = await cooperation.next(author, budget); - if (action?.kind !== 'task' || action.task.id !== 'survey') throw new Error('fixture_expected_survey'); - expect(cooperation.started(author, action)).toBe(true); - fs.writeFileSync(path.join(author.worktree, 'RESEARCH.md'), JSON.stringify({ summary, conclusion: 'inconclusive', mathematicalGap })); - await cooperation.deliver(author, action, commitSolverSources(example.problem, author.worktree)); - return archive.deliveries!.at(-1)!; - }; - - const firstDelivery = await report('First delivery.'); - const record = archive.nextChecks![0]; - expect(record).toMatchObject({ status: 'pending', gapDeliveryId: firstDelivery.id }); - const firstAssignment = await cooperation.next(checker, budget); - if (firstAssignment?.kind !== 'task') throw new Error('fixture_expected_gap_check'); - expect(firstAssignment.task.id).toBe(record.taskId); - const revised = structuredClone(plan); - revised.groups[0].revision++; - await (cooperation as unknown as { acceptPlan(plan: typeof revised): Promise }).acceptPlan(revised); - expect(firstDelivery.status).toBe('superseded'); - expect(record.status).toBe('stale'); - - const freshDelivery = await report('Updated notes on the same question.'); - expect(archive.nextChecks).toHaveLength(1); - expect(record).toMatchObject({ status: 'pending', gapDeliveryId: freshDelivery.id }); - const reassignment = await cooperation.next(checker, budget); - expect(reassignment).toMatchObject({ kind: 'task', task: { id: record.taskId } }); - expect(reassignment?.kind === 'task' && reassignment.assignment.assignmentId).not.toBe(firstAssignment.assignment.assignmentId); - expect(archive.invalidTaskTransitions ?? []).toEqual([]); -}); - -it('expires a changed exact definition contract without leaving an ordinary orphan task', async () => { - const f = await fixture(), previous = f.state.cooperation!.nextChecks![0]; - const changed = structuredClone(f.plan), target = changed.tasks.find(task => task.id === 'witness')!; - target.type = 'ℤ'; target.revision++; - await f.acceptPlan(changed); - expect(previous.status).toBe('stale'); - expect(currentNextCheck(previous, f.state.cooperation!, f.identity)).toBe(false); - expect(f.state.cooperation!.tasks.some(node => node.task.id === previous.taskId)).toBe(false); - const current = f.state.cooperation!.nextChecks!.filter(record => record.status === 'pending'); - expect(current).toHaveLength(1); - expect(current[0].id).not.toBe(previous.id); - expect(currentNextCheck(current[0], f.state.cooperation!, f.identity)).toBe(true); - expect(f.state.cooperation!.tasks.filter(node => node.nextCheckId)).toHaveLength(1); - expect(f.state.cooperation!.invalidTaskTransitions ?? []).toEqual([]); -}); - -it('uses the proposed group status and resumes one record when the group reopens', async () => { - const f = await fixture(), record = f.state.cooperation!.nextChecks![0]; - const paused = structuredClone(f.plan); paused.groups[0].status = 'paused'; - await f.acceptPlan(paused); - expect(record.status).toBe('stale'); - expect(f.state.cooperation!.tasks.some(node => node.task.id === record.taskId)).toBe(false); - await f.acceptPlan(structuredClone(f.plan)); - expect(record.status).toBe('pending'); - expect(f.state.cooperation!.nextChecks).toHaveLength(1); - expect(f.state.cooperation!.tasks.filter(node => node.task.id === record.taskId)) - .toEqual([expect.objectContaining({ nextCheckId: record.id, status: 'pending' })]); - expect(currentNextCheck(record, f.state.cooperation!, f.identity)).toBe(true); - expect(f.state.cooperation!.invalidTaskTransitions ?? []).toEqual([]); -}); - -it('expires a pending check when the accepted plan removes its only proof routes', async () => { - const f = await fixture(true), record = f.state.cooperation!.nextChecks![0]; - const changed = structuredClone(f.plan); changed.proofRoutes = []; - await f.acceptPlan(changed); - expect(record.status).toBe('stale'); - expect(currentNextCheck(record, f.state.cooperation!, f.identity)).toBe(false); - expect(f.state.cooperation!.tasks.some(node => node.task.id === record.taskId)).toBe(false); - expect(f.state.cooperation!.nextChecks).toHaveLength(1); - expect(f.state.cooperation!.invalidTaskTransitions ?? []).toEqual([]); -}); diff --git a/tests/solverOriginalDefinitionGoals.test.ts b/tests/solverOriginalDefinitionGoals.test.ts deleted file mode 100644 index 7ed9e6c0..00000000 --- a/tests/solverOriginalDefinitionGoals.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { createTaskSourceProjector, projectedGoalInputs } from '../src/solver/cooperativeProof'; -import { committedSource, commitSolverSources, git, readSolverProblem } from '../src/solver/problem'; -import { freshlyAccepted, taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { cooperativeResearch } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { newestLeanBinary } from './helpers/lean'; -import { leadWorker, solverState } from './helpers/solver'; -import { failedBatch, receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), model: vi.fn() })); -vi.mock('../src/math/verifier', async original => ({ ...await original(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'native-original-definition-tools', -})); -vi.mock('../src/math/mathProofEnvironment', async original => ({ - ...await original(), resolveMathProofEnvironment: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.model })); -const lean = newestLeanBinary(); -const instances: { directory: string; controller: AbortController; cooperative: CooperativeResearch }[] = []; -afterEach(async () => { - for (const instance of instances.splice(0)) { - instance.controller.abort(); await instance.cooperative.stop(); - fs.rmSync(instance.directory, { recursive: true, force: true }); - } - expect(host.model).not.toHaveBeenCalled(); vi.restoreAllMocks(); -}); - -const source = [ - 'namespace Original', - 'abbrev E := Nat', - 'def shifted (n : E) : E := n + 1', - 'abbrev alias (n : E) : E := shifted n', - 'theorem unfinished : False := by sorry', - 'end Original', '', -].join('\n'); -const helper: CooperativeTask = { id: 'helper', kind: 'lemma', objective: 'Use the checked original definitions.', - proofPath: 'Submission.lean', theoremName: 'Original.helper', type: '∀ n : Original.E, Original.alias n = n + 1', - dependsOn: [], revision: 0, ownerId: 'proof' }; - -function fixture(input = source, definitions = ['Original.E', 'Original.shifted', 'Original.alias'], includeHelper = true) { - host.model.mockReset().mockImplementation(() => { throw new Error('fixture_models_forbidden'); }); - const directory = temporaryDirectory('solver-original-definitions-'); - const receipt = bootstrapLeanTask(path.join(directory, 'workspace'), { - source: input, definitionTargets: definitions, task: 'Check original inputs and prove the remaining goal.', - }); - const workspace = receipt.workspaceRoot, problem = readSolverProblem(workspace, receipt.activeProblemPath); - if (includeHelper) fs.writeFileSync(path.join(receipt.projectRoot, 'Submission.lean'), input.replace('theorem unfinished', - 'theorem helper (n : E) : alias n = n + 1 := by rfl\ntheorem unfinished')); - const canonical = commitSolverSources(problem, workspace), proofWorktree = path.join(directory, 'proof'); - git(workspace, ['worktree', 'add', '--quiet', '--detach', proofWorktree, canonical]); - const workers = [leadWorker(problem, workspace), { id: 'proof', role: 'researcher' as const, - worktree: proofWorktree, ownedFiles: problem.ownedFiles }]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map(target => ({ id: target.theoremName.split('.').at(-1)!, kind: 'goal', objective: 'Check original target.', - theoremName: target.theoremName, proofPath: target.proofPath, ownerId: 'proof', - ...(target.theoremName === 'Original.unfinished' ? { status: 'paused' } : {}) })), - ...(includeHelper ? [helper] : []), - { id: 'observe', kind: 'research', objective: 'Observe checked inputs.', ownerId: 'proof', - dependsOn: [...definitions.map(name => name.split('.').at(-1)!), ...(includeHelper ? ['helper'] : [])] }, - ], groups: [{ id: 'main', objective: 'Original problem.', status: 'active', maxConcurrent: 1 }] }); - const state = solverState(problem, workspace, { runId: 'original-definitions', phase: 'running', - cooperation: { canonicalCommit: canonical, groups: plan.groups.map(group => ({ group, turns: 0 })), - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })) } }); - const envFile = path.join(directory, 'fixture.env'); fs.writeFileSync(envFile, ''); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - const controller = new AbortController(), events: { event: string; details: any }[] = []; - const cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory }])), - emit: (event, details) => events.push({ event, details }) }); - instances.push({ directory, controller, cooperative }); - const nativeChecks: { theorem: string; source: string; output: string; exitCode: number | null }[] = []; - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest, - options?: { expectedDeclarationType?: string }) => { - const projected = committedSource(workspace, request.targetCommit!, `${problem.projectRelative}/Submission.lean`); - const commands = request.items.flatMap(item => [`#print ${item.theoremName}`, `#print axioms ${item.theoremName}`, - ...(options?.expectedDeclarationType ? [`example : ${options.expectedDeclarationType} := ${item.theoremName}`] : [])]); - const file = path.join(directory, `Native-${nativeChecks.length}.lean`); - fs.writeFileSync(file, projected + '\n' + commands.join('\n') + '\n'); - const result = spawnSync(lean!, [file], { encoding: 'utf8', timeout: 20_000 }); - expect(result.error).toBeUndefined(); - const output = `${result.stdout}${result.stderr}`; - request.items.forEach(item => nativeChecks.push({ theorem: item.theoremName!, source: projected, output, exitCode: result.status })); - const batch = receiptBatch(request, { sessionId: 'native-original-definition', - receiptId: (_, name) => `native-${request.targetCommit}-${name}` }); - return result.status === 0 && !output.includes('sorryAx') && !/\b(?:sorry|admit)\b/u.test(projected) - ? batch : failedBatch(batch, { stdoutPreview: () => output }); - }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ current: () => !input.signal?.aborted, - result: { taskDigest: taskVersion(input.task), inputDigest: 'fixture', evidence: 'advisory-type-elaboration', - proofAcceptance: 'not-assessed', status: 'deferred', reason: 'fixture' } })); - const records = state.cooperation!.tasks; - const node = (id: string) => records.find(record => record.task.id === id)!; - const next = () => cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: 60_000 }); - const write = (text: string) => { - fs.writeFileSync(path.join(receipt.projectRoot, 'Submission.lean'), text); - state.cooperation!.canonicalCommit = commitSolverSources(problem, workspace); - return state.cooperation!.canonicalCommit!; - }; - return { directory, receipt, problem, workspace, state, workers, cooperative, records, node, next, write, nativeChecks, events }; -} - -describe.skipIf(!lean)('original definition goals with native Lean checks', () => { - it('checks complete def and abbrev inputs before model dispatch and retains their chain for a helper', async () => { - const f = fixture(); - expect(await f.next()).toMatchObject({ kind: 'task', task: { id: 'observe' } }); - for (const name of ['E', 'shifted', 'alias', 'helper']) { - const node = f.node(name); - expect(node.status, node.feedback).toBe('integrated'); - expect(freshlyAccepted(node, taskVersion(node.task))).toBe(true); - expect(node.attempts).toBe(0); expect(node.proof?.changes).toEqual([]); - } - expect(f.state.turns).toBe(0); - const check = f.nativeChecks.find(item => item.theorem === 'Original.helper')!; - expect(check.exitCode, check.output).toBe(0); - for (const declaration of ['abbrev E', 'def shifted', 'abbrev alias']) expect(check.source).toContain(declaration); - expect(check.source).not.toContain('theorem unfinished'); expect(check.output).not.toContain('sorryAx'); - expect(f.node('unfinished').status).toBe('pending'); expect(f.node('unfinished').integratedCheck).toBeUndefined(); - expect(f.problem.targets).toHaveLength(4); - expect(committedSource(f.workspace, f.state.cooperation!.canonicalCommit!, 'generated/problem/Submission.lean')) - .toContain('theorem unfinished : False := by sorry'); - }); - - it.each([['abbrev E', 'def E', 'E'], ['def shifted', 'abbrev shifted', 'shifted']] as const) - ('rejects changing original %s into %s', (before, after, id) => { - const f = fixture(), commit = f.write(source.replace(before, after)); - const project = createTaskSourceProjector(f.problem, f.workspace, commit); - expect(() => project(f.node(id).task, [])).toThrow('math_task_requires_theorem'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it.each(['parameter', 'result'] as const)('rejects a changed original abbrev %s contract', change => { - const f = fixture(), replacement = change === 'parameter' - ? 'abbrev alias (n : E) (extra : True) : E := shifted n' - : 'abbrev alias (n : E) : Bool := true'; - expect(() => f.write(source.replace('abbrev alias (n : E) : E := shifted n', replacement))) - .toThrow('math_original_declaration_changed'); - }); - - it('does not accept an apparently complete abbrev whose input has a proof hole', async () => { - const input = 'namespace Original\ndef unfinishedInput : Nat := by sorry\nabbrev E : Nat := unfinishedInput\n' + - 'theorem unfinished : False := by sorry\nend Original\n'; - const f = fixture(input, ['Original.E'], false), action = await f.next(); - expect(action).toMatchObject({ kind: 'task', task: { id: 'E' } }); - expect(f.node('E').status).not.toBe('integrated'); expect(f.node('E').integratedCheck).toBeUndefined(); - expect(f.node('E').assignment?.canonicalProbe).toMatchObject({ proofAcceptance: 'not-accepted', verificationStatus: 'failed' }); - expect(f.nativeChecks).not.toHaveLength(0); expect(f.nativeChecks.some(check => check.output.includes('sorryAx'))).toBe(true); - }); - - it('preserves independent source observations when a different original input has an invalid declaration', () => { - const f = fixture(), commit = f.write(source - .replace('abbrev alias (n : E) : E := shifted n', 'theorem alias (n : E) : E := shifted n') - .replace('theorem unfinished', 'theorem helper (n : E) : alias n = shifted n := by rfl\ntheorem unfinished')); - const project = createTaskSourceProjector(f.problem, f.workspace, commit), unavailable = vi.fn(); - const found = projectedGoalInputs(project, helper, f.records, [], unavailable); - expect(found.map(node => node.task.id)).toContain('shifted'); - expect(found.map(node => node.task.id)).toContain('E'); - expect(unavailable).toHaveBeenCalledWith(expect.objectContaining({ id: 'alias' }), expect.any(Error)); - expect((f.cooperative as any).sourceGoalInputs(helper, f.records, f.workspace, commit).map((node: TaskRecord) => node.task.id)) - .toContain('E'); - expect(f.events).toContainEqual(expect.objectContaining({ event: 'task_source_input_unavailable', - details: expect.objectContaining({ taskId: 'helper', sourceTaskId: 'alias' }) })); - expect(f.records.every(node => !node.integratedCheck)).toBe(true); - }); -}); diff --git a/tests/solverPlanApproval.test.ts b/tests/solverPlanApproval.test.ts deleted file mode 100644 index 9935bd17..00000000 --- a/tests/solverPlanApproval.test.ts +++ /dev/null @@ -1,398 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { MAX_DELIVERY_LINE_BYTES } from '../src/solver/deliveries'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { planApprovalInspection, planApprovalLog } from '../src/solver/planApproval'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { leadPlanDeliveryFile, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { ExecutionDeadline } from '../src/runtime/executionDeadline'; -import * as statementReview from '../src/solver/statementReview'; - -describe('plan approval before dispatch (--plan-approval)', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, lead: ResearchWorker, peer: ResearchWorker; - let events: { event: string; details?: Record }[]; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let pending: Promise[]; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const plan = (suffix = '') => ({ tasks: problem.targets.map((target, index) => ({ id: `goal_${index + 1}${suffix}`, kind: 'goal', - objective: `Prove ${target.theoremName}.`, theoremName: target.theoremName, proofPath: target.proofPath })) }); - const create = (onPlanApprovalWaiting?: (waiting: boolean) => void, - exclusiveCheck?: ConstructorParameters[0]['exclusiveCheck']) => { - const controller = new AbortController(); - const cooperative = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: directory, - signal: controller.signal, onPlanApprovalWaiting, ...(exclusiveCheck ? { exclusiveCheck } : {}), - emit: (event, details) => events.push({ event, details }) }); - instances.push({ cooperative, controller }); - return cooperative; - }; - const track = (promise: Promise) => { pending.push(promise); void promise.catch(() => {}); return promise; }; - const settled = async (promise: Promise) => { - let done = false; void promise.then(() => { done = true; }, () => { done = true; }); - for (let index = 0; index < 5; index++) await new Promise(resolve => setImmediate(resolve)); - return done; - }; - const named = (name: string) => events.filter(item => item.event === name).map(item => item.details); - const wait = (worker: ResearchWorker) => state.workers!.find(item => item.id === worker.id)!.scheduling?.wait; - const startLead = async (cooperative: CooperativeResearch) => { - const action = await cooperative.next(lead, budget); - if (action?.kind !== 'lead') throw new Error('fixture_expected_lead'); - expect(cooperative.started(lead, action)).toBe(true); - cooperative.activate(lead, action, async () => {}, async () => {}); - return action; - }; - const publish = async (cooperative: CooperativeResearch, action: CooperativeAction, suffix = '', response: Record = {}) => { - if (action.kind !== 'lead') throw new Error('fixture_expected_lead'); - fs.appendFileSync(path.join(lead.worktree, leadPlanDeliveryFile(action)!), JSON.stringify({ kind: 'plan', - baseVersion: action.planVersion, ...(action.planNonce ? { dispatchNonce: action.planNonce } : {}), - summary: 'One task per original goal.', ...plan(suffix), ...response }) + '\n'); - await cooperative.pulse(); - }; - const approve = async (cooperative: CooperativeResearch, id: string, planVersion = state.cooperation!.planVersion!) => { - fs.appendFileSync(planApprovalLog(path.join(directory, 'state.json')), JSON.stringify({ id, planVersion }) + '\n'); - await cooperative.pulse(); - }; - /** A note to the Lead as queueHumanGuidance stores it. */ - const guideLead = (id: string) => { - const file = path.join(directory, 'human-guidance.json'), now = new Date().toISOString(); - const store = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) - : { schema: 'theorem-os.human-guidance.v1', runId: state.runId, records: [] }; - store.records.push({ id, recipient: { kind: 'lead' }, text: 'Split the first goal into a helper lemma.', - observationRef: { sequence: 1, stateDigest: 'a'.repeat(64) }, status: 'queued', createdAt: now, updatedAt: now }); - fs.writeFileSync(file, JSON.stringify(store)); - }; - const guidance = (id: string) => JSON.parse(fs.readFileSync(path.join(directory, 'human-guidance.json'), 'utf8')) - .records.find((record: { id: string }) => record.id === id); - - beforeEach(() => { - const example = localExample('solver-plan-approval-', 'lead'); - ({ directory, problem } = example); - lead = leadWorker(problem, example.workspace); - peer = peerWorker(example, 'engineer', { role: 'engineer' }); - state = solverState(problem, example.workspace, { runId: 'plan-approval-fixture', phase: 'prepared', - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture', planApproval: true, - workers: [lead, peer].map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'running', turns: 0 })) }); - instances = []; events = []; pending = []; - }); - afterEach(async () => { - for (const instance of instances) instance.controller.abort(); - await Promise.allSettled(pending); - await Promise.allSettled(instances.map(instance => instance.cooperative.stop())); - vi.useRealTimers(); vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - it('holds every worker after the first plan until the exact version is approved', async () => { - const cooperative = create(), action = await startLead(cooperative); - expect(planApprovalInspection(state)).toMatchObject({ required: true, status: 'awaiting-plan', leadRevising: false }); - const waiting = track(cooperative.next(peer, budget)); - await publish(cooperative, action); - const version = state.cooperation!.planVersion!; - expect(await settled(waiting)).toBe(false); - expect(wait(peer)).toMatchObject({ stage: 'plan-approval', planVersion: version }); - expect(named('plan_approval_requested')).toEqual([{ planVersion: version }]); - // The Lead turn that published the plan is still running, but it is not a revision for the owner. - expect(planApprovalInspection(state)).toMatchObject({ status: 'pending', planVersion: version, - requestedAt: expect.any(Number), rejections: [], leadRevising: false }); - - await approve(cooperative, 'stale', 'obsolete-version'); - expect(await settled(waiting)).toBe(false); - expect(named('plan_approval_rejected')).toEqual([expect.objectContaining({ id: 'stale', - reason: 'math_plan_approval_version_conflict', planVersion: 'obsolete-version' })]); - - await approve(cooperative, 'owner'); - expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'goal_1' } }); - expect(named('plan_approved')).toEqual([{ id: 'owner', planVersion: version }]); - expect(planApprovalInspection(state)).toMatchObject({ status: 'approved', approvedId: 'owner', - approvedVersion: version, approvedAt: expect.any(Number) }); - expect(events.find(item => item.event === 'dispatch_wait_ended' && item.details?.workerId === peer.id && - item.details.stage === 'plan-approval')).toMatchObject({ details: { planVersion: version, reason: 'selected' } }); - - // The same approval read twice is a no-op; a different one after approval is reported, not applied. - await approve(cooperative, 'owner'); - await approve(cooperative, 'second'); - expect(named('plan_approved')).toHaveLength(1); - expect(state.cooperation!.planApproval!.rejections!.map(item => [item.id, item.reason])).toEqual([ - ['stale', 'math_plan_approval_version_conflict'], ['second', 'math_plan_approval_already_approved']]); - expect(state.cooperation!.planApproval!.approvedId).toBe('owner'); - }); - - it('rejects an approval that arrives before any plan and leaves dispatch untouched without the flag', async () => { - const cooperative = create(); - await approve(cooperative, 'early', 'anything'); - expect(state.cooperation!.planApproval!.rejections).toEqual([expect.objectContaining({ id: 'early', - reason: 'math_plan_approval_plan_unavailable' })]); - expect(planApprovalInspection(state).status).toBe('awaiting-plan'); - - state.planApproval = undefined; - const action = await startLead(cooperative), waiting = track(cooperative.next(peer, budget)); - await publish(cooperative, action); - expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'goal_1' } }); - expect(named('plan_approval_requested')).toEqual([]); - expect(planApprovalInspection(state)).toMatchObject({ required: false, status: 'not-required' }); - }); - - it.each([false, true])('applies queued edits before checking an approval of the old plan (oversized entry: %s)', async oversized => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - const read = state.cooperation!.planVersion!; - const edits = path.join(directory, 'edits.jsonl'); - if (oversized) fs.writeFileSync(edits, 'x'.repeat(MAX_DELIVERY_LINE_BYTES + 1) + '\n'); - fs.appendFileSync(edits, JSON.stringify({ id: 'owner-edit', baseVersion: read, ...plan('_edited') }) + '\n'); - await approve(cooperative, 'owner', read); - expect(state.cooperation!.edits?.at(-1)).toMatchObject({ id: 'owner-edit', status: 'applied' }); - expect(named('edit_rejected').map(event => event?.reason)).toEqual(oversized ? ['math_delivery_line_too_large'] : []); - expect(state.cooperation!.cursors?.edits).toBe(fs.statSync(edits).size); - expect(state.cooperation!.planVersion).not.toBe(read); - expect(state.cooperation!.planApproval!.rejections).toEqual([expect.objectContaining({ id: 'owner', - reason: 'math_plan_approval_version_conflict', planVersion: read })]); - expect(planApprovalInspection(state)).toMatchObject({ status: 'pending', planVersion: state.cooperation!.planVersion }); - - const waiting = track(cooperative.next(peer, budget)); - await approve(cooperative, 'owner-again'); - expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'goal_1_edited' } }); - }); - - it('continues reading approvals after a shortened log across restart', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - const log = planApprovalLog(path.join(directory, 'state.json')); - const version = state.cooperation!.planVersion!; - await approve(cooperative, 'stale', 'obsolete-version'); - const oldOffset = state.cooperation!.cursors!.planApprovals; - fs.writeFileSync(log, '{"id":"ignored","planVersion":"'); - expect(fs.statSync(log).size).toBeLessThan(oldOffset); - await cooperative.pulse(); - expect(named('plan_approval_rejected').map(event => event?.reason)) - .toEqual(['math_plan_approval_version_conflict', 'math_delivery_log_rewritten']); - expect(planApprovalInspection(state).status).toBe('pending'); - - const stateFile = path.join(directory, 'state.json'); - writeSolverRunState(stateFile, state); - state = readSolverRunState(stateFile); - const resumed = create(); - fs.appendFileSync(log, version + '"}\n'); - await approve(resumed, 'owner', version); - expect(named('plan_approved')).toEqual([{ id: 'owner', planVersion: version }]); - expect(named('plan_approval_rejected')).toHaveLength(2); - }); - it('gives the Lead one revision turn per owner note while the plan waits', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - cooperative.deactivate(lead); - await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree)); - const first = state.cooperation!.planVersion!; - const idle = track(cooperative.next(lead, budget)); - expect(await settled(idle)).toBe(false); - - guideLead('note-1'); - await cooperative.pulse(); - // No Lead is running to hear it, so the note waits and wakes a revision turn. - expect(guidance('note-1')).toMatchObject({ status: 'deferred' }); - const revision = await idle; - expect(revision).toMatchObject({ kind: 'lead', planVersion: first, planNonce: expect.any(String) }); - expect(named('plan_approval_revision')).toEqual([{ guidanceIds: ['note-1'], planVersion: first }]); - expect(state.cooperation!.planApproval).toMatchObject({ guidanceIds: ['note-1'], revisionAt: expect.any(Number) }); - expect(planApprovalInspection(state).leadRevising).toBe(false); - expect(cooperative.started(lead, revision!)).toBe(true); - cooperative.activate(lead, revision!, async () => {}, async () => {}); - expect(planApprovalInspection(state)).toMatchObject({ status: 'pending', leadRevising: true }); - await cooperative.pulse(); - expect(guidance('note-1')).toMatchObject({ status: 'delivered', deliveredTo: [lead.id] }); - - await publish(cooperative, revision!, '_revised', { guidanceDecisions: [{ guidanceId: 'note-1', status: 'accepted', - reason: 'The revised tasks reflect this direction.', evidenceRefs: [] }] }); - const revised = state.cooperation!.planVersion!; - expect(revised).not.toBe(first); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1_revised', 'goal_2_revised']); - cooperative.deactivate(lead); - expect(planApprovalInspection(state)).toMatchObject({ status: 'pending', planVersion: revised, leadRevising: false }); - - // The answered note does not earn a second turn; only the owner's approval releases the team. - const after = track(cooperative.next(lead, budget)), waiting = track(cooperative.next(peer, budget)); - expect(await settled(after)).toBe(false); - expect(named('plan_approval_revision')).toHaveLength(1); - await approve(cooperative, 'owner'); - expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'goal_1_revised' } }); - }); - - it.each(['checkpoint', 'scheduling-checkpoint', 'request-failure'] as const)( - 'resumes delivered undecided guidance after a %s and restart without claiming adoption', async recoveryKind => { - const cooperative = create(), initial = await startLead(cooperative); - await publish(cooperative, initial); - cooperative.deactivate(lead); - await cooperative.deliver(lead, initial, commitSolverSources(problem, lead.worktree)); - const version = state.cooperation!.planVersion!; - guideLead('unfinished-note'); await cooperative.pulse(); - const revision = await cooperative.next(lead, budget); - if (revision?.kind !== 'lead') throw new Error('fixture_expected_guidance_revision'); - expect(cooperative.started(lead, revision)).toBe(true); - const notify = vi.fn(async () => {}); - cooperative.activate(lead, revision, async () => {}, notify); await cooperative.pulse(); - expect(notify).toHaveBeenCalledOnce(); - cooperative.deactivate(lead); - await cooperative.deliver(lead, revision, commitSolverSources(problem, lead.worktree), true, recoveryKind); - expect(state.cooperation!.planVersion).toBe(version); - expect(guidance('unfinished-note')).toMatchObject({ status: 'delivered', deliveredTo: [lead.id] }); - expect(guidance('unfinished-note').decision).toBeUndefined(); - - const stateFile = path.join(directory, 'state.json'); - writeSolverRunState(stateFile, state); state = readSolverRunState(stateFile); - const restored = create(); await restored.restore(); - const retry = await restored.next(lead, budget); - if (retry?.kind !== 'lead') throw new Error('fixture_expected_unanswered_revision_retry'); - expect(retry.planVersion).toBe(version); - expect(restored.contextState(retry, lead).humanGuidance).toEqual([expect.objectContaining({ id: 'unfinished-note', status: 'delivered' })]); - expect(state.cooperation!.planApproval!.guidanceIds).toEqual(['unfinished-note']); - expect(restored.started(lead, retry)).toBe(true); - restored.activate(lead, retry, async () => {}, notify); await restored.pulse(); - expect(notify).toHaveBeenCalledOnce(); - fs.writeFileSync(path.join(lead.worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ - baseVersion: version, upsert: [], guidanceDecisions: [{ guidanceId: 'unfinished-note', status: 'needs-info', - reason: 'Which exact helper statement should the plan use?', evidenceRefs: [] }], - }) + '\n```\n'); - restored.deactivate(lead); - await restored.deliver(lead, retry, commitSolverSources(problem, lead.worktree)); - expect(guidance('unfinished-note').decision).toMatchObject({ status: 'needs-info', workerId: lead.id, sourcePlanVersion: version }); - expect(state.cooperation!.tasks.every(node => node.status === 'pending' && !node.proof)).toBe(true); - expect(planApprovalInspection(state).status).toBe('pending'); - expect(await settled(track(restored.next(lead, budget)))).toBe(false); - }); - - it('keeps an unanswered revision within the shared dispatch budget', async () => { - const cooperative = create(), initial = await startLead(cooperative); - await publish(cooperative, initial); cooperative.deactivate(lead); - guideLead('budgeted-note'); await cooperative.pulse(); - const revision = await cooperative.next(lead, budget); - if (revision?.kind !== 'lead') throw new Error('fixture_expected_guidance_revision'); - cooperative.activate(lead, revision, async () => {}, async () => {}); await cooperative.pulse(); - cooperative.deactivate(lead); - await cooperative.deliver(lead, revision, commitSolverSources(problem, lead.worktree), true, 'scheduling-checkpoint'); - expect(guidance('budgeted-note').decision).toBeUndefined(); - expect(await cooperative.next(lead, { maxTurns: state.turns, remainingMs: Infinity })).toBeUndefined(); - expect(await cooperative.next(lead, { maxTurns: Infinity, remainingMs: 0 })).toBeUndefined(); - }); - - it('keeps approvals and rejections across a restart without rereading the log', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - await approve(cooperative, 'stale', 'obsolete-version'); - const stateFile = path.join(directory, 'state.json'); - writeSolverRunState(stateFile, state); state = readSolverRunState(stateFile); - expect(state.cooperation!.cursors!.planApprovals).toBe(fs.statSync(planApprovalLog(stateFile)).size); - - const restored = create(); - await restored.restore(); - await restored.pulse(); - expect(state.cooperation!.planApproval!.rejections!.map(item => item.id)).toEqual(['stale']); - expect(planApprovalInspection(state).status).toBe('pending'); - expect(named('plan_approval_requested')).toHaveLength(1); - await approve(restored, 'owner'); - expect(planApprovalInspection(state)).toMatchObject({ status: 'approved', approvedId: 'owner' }); - }); - - it('preserves execution time while a person reads, rejects a stale approval, and continues the same run', async () => { - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }); - const expire = vi.fn(), clock = new ExecutionDeadline(1_000, expire); - const cooperative = create(waiting => clock.setWaiting(waiting)), action = await startLead(cooperative); - await vi.advanceTimersByTimeAsync(200); - await publish(cooperative, action); - expect(clock.waiting).toBe(false); // A published plan does not waive the remainder of the running Lead turn. - cooperative.deactivate(lead); - expect(clock.waiting).toBe(true); - const runId = state.runId, problemReceiptDigest = state.problem.receiptDigest; - await vi.advanceTimersByTimeAsync(600_000); - await approve(cooperative, 'old-version', 'obsolete'); - expect(clock.waiting).toBe(true); - expect(clock.remainingMs()).toBe(800); - expect(expire).not.toHaveBeenCalled(); - const waiting = track(cooperative.next(peer, { maxTurns: Infinity, remainingMs: clock.remainingMs() })); - await approve(cooperative, 'owner'); - expect(await waiting).toMatchObject({ kind: 'task', task: { id: 'goal_1' } }); - expect(clock.waiting).toBe(false); - expect(state.runId).toBe(runId); - expect(state.problem.receiptDigest).toBe(problemReceiptDigest); - await vi.advanceTimersByTimeAsync(799); - expect(expire).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(expire).toHaveBeenCalledOnce(); - clock.stop(); - }); - - it('counts owner-requested model revisions, then freezes again when the revision finishes', async () => { - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }); - const clock = new ExecutionDeadline(1_000, vi.fn()); - const cooperative = create(waiting => clock.setWaiting(waiting)), action = await startLead(cooperative); - await publish(cooperative, action); - cooperative.deactivate(lead); - await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree)); - expect(clock.waiting).toBe(true); - await vi.advanceTimersByTimeAsync(60_000); - guideLead('revision-note'); await cooperative.pulse(); - const revision = await cooperative.next(lead, { maxTurns: Infinity, remainingMs: clock.remainingMs() }); - if (!revision) throw new Error('expected_owner_revision'); - cooperative.reserveTurn(lead); - expect(clock.waiting).toBe(false); - expect(cooperative.started(lead, revision)).toBe(true); - cooperative.activate(lead, revision, async () => {}, async () => {}); - cooperative.settleTurn(lead); - await vi.advanceTimersByTimeAsync(250); - await publish(cooperative, revision, '_revised'); - cooperative.deactivate(lead); - expect(clock.waiting).toBe(true); - expect(clock.remainingMs()).toBe(750); - await vi.advanceTimersByTimeAsync(60_000); - expect(clock.remainingMs()).toBe(750); - clock.stop(); - }); - - it('charges host rechecks of a human-edited plan before returning to idle approval waiting', async () => { - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }); - vi.spyOn(statementReview, 'captureStatementContexts').mockImplementation(async (_problem, tasks) => - new Map(tasks.map(task => [task.id, { type: 'True', constants: [], omitted: [] }]))); - const clock = new ExecutionDeadline(1_000, vi.fn()); - let hold = false, release!: () => void, checking!: () => void; - const released = new Promise(resolve => { release = resolve; }); - const started = new Promise(resolve => { checking = resolve; }); - const cooperative = create(waiting => clock.setWaiting(waiting), async check => { - if (hold && state.cooperation!.tasks.some(node => node.pendingValidation)) { - hold = false; checking(); await released; - } - return check(); - }); - try { - const action = await startLead(cooperative); - await publish(cooperative, action); - cooperative.deactivate(lead); - await cooperative.deliver(lead, action, commitSolverSources(problem, lead.worktree)); - expect(clock.waiting).toBe(true); - await vi.advanceTimersByTimeAsync(60_000); - hold = true; - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'owner-edit', - baseVersion: state.cooperation!.planVersion, tasks: plan('_edited').tasks.map(task => - ({ ...task, statementReview: true, informalStatement: 'The stated equality holds.' })) }) + '\n'); - const pulse = track(cooperative.pulse()); - await started; - expect(clock.waiting).toBe(false); - await vi.advanceTimersByTimeAsync(300); - expect(clock.remainingMs()).toBe(700); - release(); await pulse; - for (let index = 0; index < 5; index++) await new Promise(resolve => setImmediate(resolve)); - expect(clock.waiting).toBe(true); - await vi.advanceTimersByTimeAsync(60_000); - expect(clock.remainingMs()).toBe(700); - } finally { release(); clock.stop(); } - }); - - it('reports an unanswered plan at stop and respects an already exhausted execution allowance', async () => { - const cooperative = create(), action = await startLead(cooperative); - await publish(cooperative, action); - cooperative.deactivate(lead); - expect(await cooperative.next(peer, { maxTurns: Infinity, remainingMs: 0 })).toBeUndefined(); - expect(await cooperative.next(lead, { maxTurns: Infinity, remainingMs: 0 })).toBeUndefined(); - await cooperative.stop(); - expect(named('plan_approval_unanswered')).toEqual([{ planVersion: state.cooperation!.planVersion }]); - }); -}); diff --git a/tests/solverPlanApprovalProcess.test.ts b/tests/solverPlanApprovalProcess.test.ts deleted file mode 100644 index 7acd9d20..00000000 --- a/tests/solverPlanApprovalProcess.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawn } from 'node:child_process'; -import { setTimeout as delay } from 'node:timers/promises'; -import { expect, it } from 'vitest'; -import { parseCooperationPlan } from '../src/solver/tasks'; -import { planApprovalLog } from '../src/solver/planApproval'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -it('keeps a CLI approval wait alive with no model sessions, then exits after approving the same run', async () => { - const example = localExample('solver-plan-approval-process-', 'lead'); - const lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'engineer', { role: 'engineer' }); - const plan = parseCooperationPlan(example.problem, { tasks: example.problem.targets.map((target, index) => ({ - id: `goal_${index + 1}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath })) }); - const state = solverState(example.problem, example.workspace, { runId: 'approval-process-fixture', phase: 'running', - planApproval: true, cooperation: { canonicalCommit: example.problem.baseCommit, planVersion: 'plan-v1', - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const input = path.join(example.directory, 'input.json'), script = path.join(example.directory, 'wait.ts'); - fs.writeFileSync(input, JSON.stringify({ state, workers: [lead, peer], retrievalRoot: example.directory })); - fs.writeFileSync(script, ` - import fs from 'node:fs'; - import { cooperativeResearch } from ${JSON.stringify(path.resolve('tests/helpers/cooperation.ts'))}; - import { ExecutionDeadline } from ${JSON.stringify(path.resolve('src/runtime/executionDeadline.ts'))}; - const input = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); - const clock = new ExecutionDeadline(1000, () => { throw new Error('execution_allowance_expired'); }); - let announced = false; - const cooperative = cooperativeResearch({ ...input, onPlanApprovalWaiting: waiting => { - clock.setWaiting(waiting); - if (waiting && !announced) { announced = true; process.stdout.write('ready\\n'); } - } }); - cooperative.modelBudgetChanged(); - cooperative.start(); - const action = await cooperative.next(input.workers[1], { maxTurns: Infinity, remainingMs: clock.remainingMs() }); - clock.stop(); await cooperative.stop(); - process.stdout.write(JSON.stringify({ runId: input.state.runId, approved: input.state.cooperation.planApproval.approvedId, - taskId: action?.kind === 'task' ? action.task.id : null }) + '\\n'); - `); - const child = spawn('bun', [script, input], { stdio: ['ignore', 'pipe', 'pipe'] }); - let stdout = '', stderr = ''; - child.stderr.on('data', chunk => { stderr += chunk; }); - const exited = new Promise(resolve => child.once('close', code => resolve(code))); - try { - await new Promise((resolve, reject) => { - const timer = setTimeout(() => finish(new Error(`approval_wait_not_ready: ${stderr}`)), 5_000); - const finish = (error?: Error) => { clearTimeout(timer); error ? reject(error) : resolve(); }; - child.once('error', finish); - child.once('exit', () => { if (!stdout.includes('ready\n')) finish(new Error(`approval_wait_exited: ${stderr}`)); }); - child.stdout.on('data', chunk => { stdout += chunk; if (stdout.includes('ready\n')) finish(); }); - }); - await delay(1_200); - expect(child.exitCode, stderr).toBeNull(); - fs.appendFileSync(planApprovalLog(path.join(example.directory, 'state.json')), - JSON.stringify({ id: 'owner', planVersion: 'plan-v1' }) + '\n'); - expect(await exited, stderr).toBe(0); - expect(JSON.parse(stdout.trim().split('\n').at(-1)!)).toEqual({ runId: state.runId, approved: 'owner', taskId: 'goal_1' }); - } finally { - if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); - await exited; - fs.rmSync(example.directory, { recursive: true, force: true }); - } -}); diff --git a/tests/solverPlanConcurrency.test.ts b/tests/solverPlanConcurrency.test.ts deleted file mode 100644 index 8a700d3a..00000000 --- a/tests/solverPlanConcurrency.test.ts +++ /dev/null @@ -1,481 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathematicsVerifierBatchRequest, MathematicsVerifierBatchResult } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import { taskDependenciesReady } from '../src/solver/modules/search'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git, type SolverProblem } from '../src/solver/problem'; -import { taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn(), captureStatements: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => 'plan-concurrency-fixture-tools', - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); -vi.mock('../src/solver/statementReview', async importOriginal => ({ - ...await importOriginal(), - captureStatementContexts: host.captureStatements, -})); - -function verified(request: MathematicsVerifierBatchRequest, passed = true): MathematicsVerifierBatchResult { - const batch = verifiedBatch(request, { sessionId: 'plan-concurrency-fixture', checks: true }); - return passed ? batch : failedBatch(batch, { stdoutPreview: () => 'Submission.lean:1:0: error: fixture obsolete recheck failure' }); -} -const budget = { maxTurns: 20, remainingMs: Infinity }; -type TaskAction = Extract; - -describe('plan synchronization with concurrent host control', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let workers: ResearchWorker[], cooperative: CooperativeResearch, controller: AbortController; - let lockHeld: boolean, exclusive: (check: () => Promise) => Promise; - let pending: Promise[], releases: (() => void)[]; - let events: { event: string; details?: Record }[]; - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - const track = (promise: Promise) => { pending.push(promise); void promise.catch(() => {}); return promise; }; - const create = () => cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }), exclusiveCheck: check => exclusive(check) }); - const source = () => committedSource(workspace, state.cooperation!.canonicalCommit!, `${problem.projectRelative}/Submission.lean`); - const writeLemma = (worker: ResearchWorker, name: string) => { - const file = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', `lemma ${name} : True := by trivial\ntheorem add_zero`)); - return commitSolverSources(problem, worker.worktree); - }; - const gateCheck = () => { - const entered = deferred(), result = deferred(); - let request: MathematicsVerifierBatchRequest | undefined, heldAtEntry: boolean | undefined; - host.verify.mockImplementationOnce(async (input: MathematicsVerifierBatchRequest) => { - request = input; heldAtEntry = lockHeld; entered.resolve(input); return result.promise; - }); - const release = (passed = true) => { if (request) result.resolve(verified(request, passed)); }; - releases.push(release); - const waitFor = (delivery: Promise) => Promise.race([entered.promise, delivery.then(() => { - throw new Error(`Delivery completed before the expected verifier check: ${JSON.stringify(events.slice(-5))}`); - })]); - return { entered: entered.promise, waitFor, release, heldAtEntry: () => heldAtEntry }; - }; - const edit = (id: string, change: (task: CooperativeTask) => CooperativeTask) => { - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id, baseVersion: state.cooperation!.planVersion, - tasks: state.cooperation!.tasks.map(item => change(item.task)), groups: state.cooperation!.groups!.map(item => item.group) }) + '\n'); - return track(cooperative.pulse(workers[0].id)); - }; - const writeLeadPlan = () => fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ - tasks: state.cooperation!.tasks.map(item => item.task), groups: state.cooperation!.groups!.map(item => item.group), - }) + '\n```\n'); - const sync = () => track((cooperative as any).schedulePlanSynchronization() as Promise); - const integrateA = async () => { - const current = node('a'); - const action: TaskAction = { kind: 'task', task: current.task, assignment: current.assignment! }; - await cooperative.deliver(workers[1], action, writeLemma(workers[1], 'a')); - expect(node('a').status).toBe('integrated'); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - host.captureStatements.mockReset().mockImplementation(() => { throw new Error('fixture_statement_capture_forbidden'); }); - const example = localExample('solver-plan-concurrency-'); - ({ directory, workspace, problem } = example); - workers = [leadWorker(problem, workspace, 'lead'), ...['author', 'consumer', 'independent'].map(id => peerWorker(example, id))]; - const lemma = (id: string, ownerId: string, dependsOn: string[] = []): CooperativeTask => ({ id, ownerId, kind: 'lemma', - objective: `Prove ${id}.`, proofPath: 'Submission.lean', theoremName: `Tutorial.${id}`, type: 'True', dependsOn, revision: 0 }); - const a = lemma('a', 'author'); - state = solverState(problem, workspace, { runId: 'plan-concurrency-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [{ task: a, status: 'running', attempts: 1, - assignment: { taskId: 'a', taskDigest: taskVersion(a), workerId: 'author', seedCommit: problem.baseCommit, - assignmentId: 'a-dispatch', dependencies: [] } }, - ...[lemma('b', 'consumer', ['a']), lemma('c', 'independent')].map(task => ({ task, status: 'pending' as const, attempts: 0 })), - ...problem.targets.map((target, index) => ({ task: { id: `goal_${index}`, kind: 'goal' as const, - objective: `Prove ${target.theoremName}.`, theoremName: target.theoremName, proofPath: target.proofPath, - dependsOn: ['b'], revision: 0, status: 'paused' as const }, status: 'pending' as const, attempts: 0 }))] } }); - events = []; pending = []; releases = []; lockHeld = false; controller = new AbortController(); - let queue = Promise.resolve(); - exclusive = async check => { - const previous = queue, { promise, resolve } = deferred(); - queue = promise; - await previous; lockHeld = true; - try { return await check(); } finally { lockHeld = false; resolve(); } - }; - cooperative = create(); state.cooperation!.planVersion = (cooperative as any).planVersion(); - }); - afterEach(async () => { - for (const release of releases) release(); - controller.abort(); await Promise.allSettled(pending); await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('keeps a running assignment when a revision only re-spaces its objective, and supersedes it for new wording', async () => { - const running = node('a'), version = state.cooperation!.planVersion; - const action: TaskAction = { kind: 'task', task: running.task, assignment: running.assignment! }; - await edit('respace-a', task => task.id === 'a' ? { ...task, objective: ' Prove a.\n' } : task); - expect(state.cooperation!.edits?.at(-1)).toMatchObject({ status: 'applied', affectedTasks: [] }); - expect(node('a')).toMatchObject({ status: 'running', task: { objective: 'Prove a.' }, assignment: { assignmentId: 'a-dispatch' } }); - expect(state.cooperation!.planVersion).toBe(version); - expect(cooperative.current(action)).toBe(true); - await edit('reword-a', task => task.id === 'a' ? { ...task, objective: 'Prove a directly.' } : task); - expect(node('a').task.objective).toBe('Prove a directly.'); - expect(cooperative.current(action)).toBe(false); - }); - - it('advances the edit cursor and allows independent work while keeping a revalidated dependency unavailable', async () => { - await integrateA(); - const gate = gateCheck(); - await edit('describe-a', task => task.id === 'a' ? { ...task, revision: 1, objective: 'Clarify the same theorem.' } : task); - await gate.entered; - expect(gate.heldAtEntry()).toBe(false); - expect(node('a').pendingValidation).toMatchObject({ taskDigest: taskVersion(node('a').task), proof: true }); - expect(state.cooperation!.cursors!.edits).toBe(fs.statSync(path.join(directory, 'edits.jsonl')).size); - expect(taskDependenciesReady(node('b').task, state.cooperation!.tasks)).toBe(false); - expect(directSolverModules.M3.ready(state.cooperation!.tasks, state.cooperation!.groups).map(item => item.task.id)).not.toContain('b'); - const independent = await cooperative.next(workers[3], budget); - expect(independent).toMatchObject({ kind: 'task', task: { id: 'c' } }); - expect(cooperative.started(workers[3], independent!)).toBe(true); - const waiting = node('b'); - waiting.assignment = { taskId: 'b', taskDigest: taskVersion(waiting.task), workerId: 'consumer', seedCommit: state.cooperation!.canonicalCommit! }; - expect(cooperative.started(workers[2], { kind: 'task', task: waiting.task, assignment: waiting.assignment })).toBe(false); - await edit('pause-consumer', task => task.id === 'b' ? { ...task, status: 'paused' } : task); - expect(state.cooperation!.edits).toContainEqual(expect.objectContaining({ id: 'pause-consumer', status: 'applied' })); - gate.release(); await sync(); - expect(node('a').pendingValidation).toBeUndefined(); - expect(node('a').integratedCheck?.taskDigest).toBe(taskVersion(node('a').task)); - expect(state.cooperation!.edits!.every(item => !item.pendingSync)).toBe(true); - }); - - it('reclaims a stale Lead while preserving integrated proof and active peer work and waking a waiting peer', async () => { - await integrateA(); - const acceptedProof = structuredClone(node('a').proof), acceptedCheck = structuredClone(node('a').integratedCheck); - const running = await cooperative.next(workers[3], budget); - expect(running).toMatchObject({ kind: 'task', task: { id: 'c' } }); - expect(cooperative.started(workers[3], running!)).toBe(true); - const peerInterrupt = vi.fn(async () => {}); - cooperative.activate(workers[3], running!, peerInterrupt, async () => {}); - const peerAssignment = node('c').assignment; - const oldLead: CooperativeAction = { kind: 'lead', seedCommit: state.cooperation!.canonicalCommit!, - planVersion: state.cooperation!.planVersion! }; - const leadInterrupt = vi.fn(async () => {}); - cooperative.activate(workers[0], oldLead, leadInterrupt, async () => {}); - const oldPlan = state.cooperation!.tasks.map(item => item.task); - - const waiting = track(cooperative.next(workers[1], budget)); - const task: CooperativeTask = { id: 'new_frontier', ownerId: 'author', kind: 'lemma', - objective: 'Prove the newly identified independent frontier lemma.', proofPath: 'Submission.lean', - theoremName: 'Tutorial.new_frontier', type: 'True', dependsOn: [], revision: 0 }; - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'add-frontier', - baseVersion: state.cooperation!.planVersion, - tasks: [...state.cooperation!.tasks.map(item => item.task), task], - groups: state.cooperation!.groups!.map(item => item.group) }) + '\n'); - await cooperative.pulse(workers[0].id); - const assigned = await waiting; - - expect(assigned).toMatchObject({ kind: 'task', task: { id: 'new_frontier' }, assignment: { workerId: 'author' } }); - expect(node('a').status).toBe('integrated'); - expect(node('a').proof).toEqual(acceptedProof); - expect(node('a').integratedCheck).toEqual(acceptedCheck); - expect(node('c').status).toBe('running'); - expect(node('c').assignment).toBe(peerAssignment); - expect(cooperative.current(running!)).toBe(true); - expect(peerInterrupt).not.toHaveBeenCalled(); - expect(leadInterrupt).toHaveBeenCalledOnce(); - expect(cooperative.current(oldLead)).toBe(false); - expect(cooperative.started(workers[0], oldLead)).toBe(false); - - // An interrupted session can still flush its old response; it must not replace the accepted graph. - const version = state.cooperation!.planVersion; - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ - tasks: oldPlan, groups: state.cooperation!.groups!.map(item => item.group), - }) + '\n```\n'); - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], oldLead, commitSolverSources(problem, workspace)); - expect(state.cooperation!.planVersion).toBe(version); - expect(node('new_frontier').assignment).toBe(assigned!.kind === 'task' ? assigned!.assignment : undefined); - expect(events.some(item => item.event === 'lead_decision_superseded')).toBe(true); - const freshLead = await cooperative.next(workers[0], budget); - expect(freshLead).toMatchObject({ kind: 'lead', planVersion: version }); - expect(cooperative.current(freshLead!)).toBe(true); - expect(leadInterrupt).toHaveBeenCalledOnce(); - }); - - it.each([true, false])('discards an obsolete %s recheck after a mathematical revision without publishing a failure', async passed => { - await integrateA(); const gate = gateCheck(); - const prepare = vi.spyOn(cooperative as any, 'prepareStatementContexts').mockReturnValue(undefined); - await edit('old-description', task => task.id === 'a' ? { ...task, revision: 1, objective: 'Describe a.' } : task); - await gate.entered; - await edit('new-mathematics', task => task.id === 'a' ? { ...task, revision: 2, type: 'True ∧ True' } : task); - const current = node('a'), saved = JSON.parse(JSON.stringify(current)); - gate.release(passed); await sync(); - expect(node('a')).toBe(current); expect(node('a')).toEqual(saved); - expect(node('a').proof).toBeUndefined(); expect(node('a').integratedCheck).toBeUndefined(); - expect(prepare.mock.calls.some(([tasks]) => tasks.some((item: { task: CooperativeTask }) => - item.task.id === 'a' && item.task.revision === 1))).toBe(false); - expect(prepare.mock.calls.some(([tasks]) => tasks.some((item: { task: CooperativeTask }) => - item.task.id === 'a' && item.task.revision === 2))).toBe(true); - expect(state.cooperation!.deliveries?.some(item => item.kind === 'failure' || item.status === 'failed')).not.toBe(true); - expect(events.some(item => item.event === 'delivery_rejected')).toBe(false); - }); - - it.each(['passed', 'failed', 'rejected', 'unavailable'] as const)('stops obsolete rechecks after an in-flight %s result settles', async result => { - await integrateA(); - const tasks = ['a', 'b', 'c'].map(id => ({ ...node(id), status: 'integrated' as const, integratedCheck: undefined })); - const baseline = structuredClone(tasks); - const entered = deferred(), release = deferred(); - releases.push(() => release.resolve()); - const receipt = { ...node('a').proof!, passed: result === 'passed' }; - const check = vi.spyOn(cooperative as any, 'check').mockImplementationOnce(async () => { - entered.resolve(); await release.promise; - if (result === 'unavailable') throw new Error('math_verifier_unavailable'); - if (result === 'rejected') throw new Error('math_task_missing_declaration'); - return receipt; - }).mockResolvedValue(receipt); - let current = true; - const rechecking = track((cooperative as any).recheckIntegrated(state.cooperation!.canonicalCommit!, true, { - tasks, ids: new Set(tasks.map(item => item.task.id)), environment: {}, environmentDigest: state.environmentDigest, - current: () => current, - }) as Promise); - await entered.promise; current = false; release.resolve(); - if (result === 'unavailable') await expect(rechecking).rejects.toThrow('math_verifier_unavailable'); - else await rechecking; - expect(check.mock.calls.map(([task]) => task.id)).toEqual(['a']); - if (result !== 'unavailable') await expect(rechecking).resolves.toBe(false); - expect(tasks).toEqual(baseline); - expect(events.filter(item => item.event === 'task_recheck_finished')).toHaveLength(0); - expect(state.cooperation!.recheck).toMatchObject({ completed: 0, taskId: 'a' }); - expect((cooperative as any).failure).toBeUndefined(); - }); - - it('keeps newer progress when an identical task receives a new validation identity', async () => { - await integrateA(); - const saved: { progress: NonNullable['recheck']>; locked: boolean }[] = []; - vi.spyOn((cooperative as any).input, 'save').mockImplementation(() => { - const progress = state.cooperation!.recheck; - if (progress) saved.push({ progress: { ...progress }, locked: lockHeld }); - }); - const gate = gateCheck(); - await edit('describe-for-progress', task => task.id === 'a' ? { ...task, revision: 1, objective: 'Describe a.' } : task); - await gate.entered; - expect(state.cooperation!.recheck).toMatchObject({ total: 1, completed: 0, taskId: 'a' }); - const previous = node('a').pendingValidation!; - const newer = { ...previous, id: 'new-validation-for-identical-mathematics' }; - const newerProgress = { ...state.cooperation!.recheck! }; - await exclusive(async () => { - node('a').pendingValidation = newer; - state.cooperation!.recheck = newerProgress; - }); - expect(newer.taskDigest).toBe(previous.taskDigest); - const prepared = deferred(), release = deferred(); - releases.push(() => release.resolve()); - const recheck = (cooperative as any).recheckIntegrated.bind(cooperative); - vi.spyOn(cooperative as any, 'recheckIntegrated').mockImplementationOnce(async (...args) => { - prepared.resolve(); await release.promise; return recheck(...args); - }); - const savesBeforeCompletion = saved.length; - gate.release(); await prepared.promise; - expect(state.cooperation!.recheck).toBe(newerProgress); - expect(saved).toHaveLength(savesBeforeCompletion); - expect(node('a').pendingValidation).toBe(newer); - release.resolve(); await sync(); - expect(state.cooperation!.recheck).toMatchObject({ total: 1, completed: 1 }); - expect(node('a').pendingValidation).toBeUndefined(); - expect(saved.every(item => item.locked)).toBe(true); - expect(saved.some(item => item.progress.completed === 1)).toBe(true); - }); - - it('keeps every target pending when only one validation identity changes during a shared snapshot', async () => { - await integrateA(); - const action = await cooperative.next(workers[3], budget); - expect(action).toMatchObject({ kind: 'task', task: { id: 'c' } }); - await cooperative.deliver(workers[3], action!, writeLemma(workers[3], 'c')); - const gate = gateCheck(); - const prepare = vi.spyOn(cooperative as any, 'prepareStatementContexts').mockReturnValue(undefined); - await edit('describe-independent-pair', task => ['a', 'c'].includes(task.id) - ? { ...task, revision: 1, objective: `Clarify ${task.id}.` } : task); - await gate.entered; - const first = node('a').pendingValidation!, second = { ...node('c').pendingValidation!, id: 'newer-c-validation' }; - const checks = [node('a').integratedCheck, node('c').integratedCheck]; - await exclusive(async () => { node('c').pendingValidation = second; }); - const entered = deferred(), release = deferred(); releases.push(() => release.resolve()); - const recheck = (cooperative as any).recheckIntegrated.bind(cooperative); - vi.spyOn(cooperative as any, 'recheckIntegrated').mockImplementationOnce(async (...args) => { - entered.resolve(); await release.promise; return recheck(...args); - }); - const calls = host.verify.mock.calls.length; - gate.release(); await entered.promise; - expect(host.verify.mock.calls).toHaveLength(calls); - expect(node('a').pendingValidation).toBe(first); expect(node('c').pendingValidation).toBe(second); - expect(node('a').integratedCheck).toBe(checks[0]); expect(node('c').integratedCheck).toBe(checks[1]); - expect(prepare).not.toHaveBeenCalled(); - release.resolve(); await sync(); - for (const id of ['a', 'c']) { - expect(node(id).pendingValidation).toBeUndefined(); - expect(node(id).integratedCheck?.taskDigest).toBe(taskVersion(node(id).task)); - expect(node(id).status).toBe('integrated'); - } - }); - - it('rebases validation after an independent proof integrates and retains both declarations', async () => { - await integrateA(); const gate = gateCheck(); - const canonical = state.cooperation!.canonicalCommit!; - const prepare = vi.spyOn(cooperative as any, 'prepareStatementContexts').mockReturnValue(undefined); - await edit('describe-before-integration', task => task.id === 'a' ? { ...task, revision: 1, objective: 'Describe a.' } : task); - const old = await gate.entered; - const action = await cooperative.next(workers[3], budget); - expect(action).toMatchObject({ kind: 'task', task: { id: 'c' } }); - await cooperative.deliver(workers[3], action!, writeLemma(workers[3], 'c')); - expect(node('c').status).toBe('integrated'); - expect(source()).toContain('lemma c : True := by trivial'); - gate.release(); await sync(); - expect(node('a').pendingValidation).toBeUndefined(); - expect(node('a').status).toBe('integrated'); expect(node('c').status).toBe('integrated'); - expect(source()).toContain('lemma a : True := by trivial'); expect(source()).toContain('lemma c : True := by trivial'); - expect(prepare.mock.calls.some(([, commit]) => commit === canonical)).toBe(false); - expect(events).toContainEqual(expect.objectContaining({ event: 'plan_recheck_rebased' })); - expect(node('a').integratedCheck!.commit).not.toBe(old.targetCommit); - }); - - it('restores pending validation independently of an already advanced input cursor', async () => { - await integrateA(); const oldGate = gateCheck(); - await edit('resume-description', task => task.id === 'a' ? { ...task, revision: 1, objective: 'Describe a.' } : task); - await oldGate.entered; - const saved = JSON.parse(JSON.stringify(state)); - controller.abort(); oldGate.release(); await Promise.allSettled([(cooperative as any).planSynchronization]); await cooperative.stop(); - state = saved; controller = new AbortController(); cooperative = create(); - const gate = gateCheck(), restoring = track(cooperative.restore()); - await gate.entered; - expect(gate.heldAtEntry()).toBe(false); - expect(taskDependenciesReady(node('b').task, state.cooperation!.tasks)).toBe(false); - expect(state.cooperation!.edits).toHaveLength(1); - gate.release(); await restoring; - expect(node('a').pendingValidation).toBeUndefined(); expect(node('a').status).toBe('integrated'); - expect(state.cooperation!.edits![0]).toMatchObject({ status: 'applied' }); - expect(state.cooperation!.edits![0].recheck!.tasks.find(item => item.taskId === 'a')!.status).toBe('passed'); - expect(state.cooperation!.edits![0].pendingSync).toBeUndefined(); - expect(state.cooperation!.history ?? []).toHaveLength(saved.cooperation.history?.length ?? 0); - expect(state.cooperation!.cursors!.edits).toBe(fs.statSync(path.join(directory, 'edits.jsonl')).size); - }); - - it.each([true, false])('preserves a newer Lead draft after source validation (concurrent control: %s)', async control => { - await integrateA(); - // Legacy receipts without a reference footprint must be checked after source changes. - delete node('a').integratedCheck!.references; - const canonical = state.cooperation!.canonicalCommit!; - // A Lead journal makes its source seed a distinct commit even within one clock tick. - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), 'Lead journal before canonical source synchronization.\n'); - commitSolverSources(problem, workspace); - const seed = (cooperative as any).seed(workers[0], canonical) as string; - expect(seed).not.toBe(canonical); - writeLeadPlan(); - const commit = writeLemma(workers[0], 'lead_helper'); - const action: CooperativeAction = { kind: 'lead', seedCommit: seed, planVersion: state.cooperation!.planVersion }; - const gate = gateCheck(), delivery = track(cooperative.deliver(workers[0], action, commit)); - await gate.waitFor(delivery); - expect(gate.heldAtEntry()).toBe(false); - if (control) await edit('pause-during-lead-check', task => task.id === 'b' ? { ...task, status: 'paused' } : task); - const newerDraft = writeLemma(workers[0], 'newer_draft'); - gate.release(); await delivery; await sync(); - expect(git(workspace, ['rev-parse', 'HEAD'])).toBe(newerDraft); - expect(fs.readFileSync(path.join(workspace, problem.projectRelative, 'Submission.lean'), 'utf8')).toContain('lemma newer_draft'); - expect(source()).toContain('lemma lead_helper'); - expect(source()).not.toContain('lemma newer_draft'); - if (control) { - expect(node('b').task.status).toBe('paused'); - expect(state.cooperation!.edits!.find(item => item.id === 'pause-during-lead-check')!.status).toBe('applied'); - } - }); - - it('persists a preparation failure after accepting an edit and retries it on restore without replaying the plan', async () => { - await integrateA(); - const error = Object.assign(new Error('Statement context storage EIO'), { code: 'EIO' }); - vi.spyOn(cooperative as any, 'prepareStatementContexts').mockRejectedValueOnce(error); - await edit('statement-preparation-retry', task => task.id === 'a' ? { ...task, statementReview: true, informalStatement: 'True.' } : task); - await expect(sync()).rejects.toBe(error); - expect(node('a').pendingValidation).toBeDefined(); - expect(state.cooperation!.edits![0]).toMatchObject({ status: 'applied', pendingSync: true }); - const saved = JSON.parse(JSON.stringify(state)); - expect(saved.cooperation.cursors.edits).toBe(fs.statSync(path.join(directory, 'edits.jsonl')).size); - expect(events.some(item => item.event === 'edit_rejected')).toBe(false); - controller.abort(); await cooperative.stop(); - state = saved; controller = new AbortController(); cooperative = create(); - vi.spyOn(cooperative as any, 'prepareStatementContexts').mockReturnValue(undefined); - const accept = vi.spyOn(cooperative as any, 'acceptPlan'); - await cooperative.restore(); await cooperative.pulse(); - expect(accept.mock.calls.every(([, appliedEdit]) => appliedEdit === undefined)).toBe(true); - expect(node('a').pendingValidation).toBeUndefined(); - expect(state.cooperation!.edits).toHaveLength(1); - expect(state.cooperation!.history ?? []).toHaveLength(saved.cooperation.history?.length ?? 0); - expect(state.cooperation!.edits![0]).toMatchObject({ status: 'applied' }); - expect(state.cooperation!.edits![0].pendingSync).toBeUndefined(); - expect(state.cooperation!.statementReviews).toContainEqual(expect.objectContaining({ taskId: 'a', status: 'pending' })); - }); - - it('allows independent work and another edit while preparing a fixed statement context', async () => { - await integrateA(); - const entered = deferred(), release = deferred(); - releases.push(() => release.resolve()); - vi.spyOn(cooperative as any, 'prepareStatementContexts').mockImplementationOnce(() => { - expect(lockHeld).toBe(false); entered.resolve(); return release.promise; - }).mockReturnValue(undefined); - await edit('prepare-statement', task => task.id === 'a' ? { ...task, statementReview: true, informalStatement: 'True.' } : task); - await entered.promise; - expect(node('a').pendingValidation).toBeDefined(); - expect(taskDependenciesReady(node('b').task, state.cooperation!.tasks)).toBe(false); - const independent = await cooperative.next(workers[3], budget); - expect(independent).toMatchObject({ kind: 'task', task: { id: 'c' } }); - await edit('control-during-statement', task => task.id === 'b' ? { ...task, status: 'paused' } : task); - expect(state.cooperation!.edits!.find(item => item.id === 'control-during-statement')!.status).toBe('applied'); - release.resolve(); await sync(); - expect(node('a').pendingValidation).toBeUndefined(); - expect(state.cooperation!.statementReviews).toContainEqual(expect.objectContaining({ taskId: 'a', status: 'pending' })); - }); - - it('skips obsolete statement preparation after waiting for an earlier preparation to settle', async () => { - await integrateA(); - const tasks = state.cooperation!.tasks.map(item => ({ ...item, task: item.task.id === 'a' - ? { ...item.task, statementReview: true, informalStatement: 'True.' } : item.task })); - const release = deferred(); releases.push(() => release.resolve()); - const earlier = release.promise.finally(() => { (cooperative as any).preparingStatements = undefined; }); - (cooperative as any).preparingStatements = earlier; - let current = true; - const preparing = track((cooperative as any).prepareStatementContexts(tasks, state.cooperation!.canonicalCommit!, { - environment: {}, digest: state.environmentDigest, current: () => current, - }) as Promise); - expect(host.captureStatements).not.toHaveBeenCalled(); - current = false; release.resolve(); - await preparing; - expect(host.captureStatements).not.toHaveBeenCalled(); - expect((cooperative as any).preparingStatementTasks.size).toBe(0); - expect((cooperative as any).preparingStatements).toBeUndefined(); - }); - - it('integrates a previously delivered consumer once its source dependency finishes validation', async () => { - await integrateA(); - const consumer = await cooperative.next(workers[2], budget); - expect(consumer).toMatchObject({ kind: 'task', task: { id: 'b' } }); - const consumerCommit = writeLemma(workers[2], 'b'); - const canonical = state.cooperation!.canonicalCommit!; - const seed = (cooperative as any).seed(workers[0], canonical) as string; - writeLeadPlan(); - delete node('a').integratedCheck!.references; - const commit = writeLemma(workers[0], 'lead_helper'); - const gate = gateCheck(), delivery = track(cooperative.deliver(workers[0], { - kind: 'lead', seedCommit: seed, planVersion: state.cooperation!.planVersion, - }, commit)); - await gate.waitFor(delivery); - await cooperative.deliver(workers[2], consumer!, consumerCommit); - expect(node('b').status).toBe('delivered'); - expect(source()).not.toContain('lemma b : True := by trivial'); - gate.release(); await delivery; await sync(); - expect(node('b').status).toBe('integrated'); expect(source()).toContain('lemma b : True := by trivial'); - expect(state.cooperation!.deliveries!.filter(item => item.taskId === 'b' && item.kind === 'proof' && item.status === 'verified')).toHaveLength(1); - }); -}); diff --git a/tests/solverPlanPatch.test.ts b/tests/solverPlanPatch.test.ts deleted file mode 100644 index 1d0a877f..00000000 --- a/tests/solverPlanPatch.test.ts +++ /dev/null @@ -1,235 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { readMathResponse } from '../src/solver/deliveries'; -import { leadPlanDeliveryFile, parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -type LeadAction = Extract; - -describe('Lead plan revisions in a cooperative run', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - let cooperative: CooperativeResearch, controller: AbortController; - let events: { event: string; details?: Record }[]; - const notes = () => path.join(workers[0].worktree, 'RESEARCH.md'); - const ids = () => state.cooperation!.tasks.map(node => node.task.id); - const helper = (id: string) => ({ id, kind: 'lemma' as const, objective: `Prove the independent step ${id}.`, - theoremName: `Tutorial.${id}`, proofPath: 'Submission.lean', type: 'True', dependsOn: [] }); - const start = async () => { - const action = await cooperative.next(workers[0], budget); - if (action?.kind !== 'lead' || !action.planNonce) throw new Error('fixture_expected_revision_dispatch'); - expect(cooperative.started(workers[0], action)).toBe(true); - cooperative.activate(workers[0], action, vi.fn(async () => {}), async () => {}); - return action; - }; - const publish = async (action: LeadAction, revision: Record) => { - fs.appendFileSync(path.join(workers[0].worktree, leadPlanDeliveryFile(action)!), JSON.stringify({ kind: 'plan', - dispatchNonce: action.planNonce, baseVersion: action.planVersion, summary: 'Adopt one independent step.', ...revision }) + '\n'); - await cooperative.pulse(); - }; - const finish = async (action: LeadAction) => { - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], action, commitSolverSources(problem, workers[0].worktree)); - }; - const patchFence = (value: Record) => '```math-plan\n' + JSON.stringify(value) + '\n```\n'; - - beforeEach(() => { - const example = localExample('solver-plan-patch-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'engineer', { role: 'engineer' })]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, - })) }); - state = solverState(problem, example.workspace, { runId: 'plan-patch-fixture', phase: 'running', - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'checking', turns: 0 })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })), error: 'fixture_request_new_plan' } }); - events = []; controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }) }); - }); - afterEach(async () => { - controller.abort(); - await Promise.allSettled([cooperative.stop()]); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('publishes a small revision live and shows the complete accepted graph to the next dispatch', async () => { - const action = await start(), goals = ids(); - await publish(action, { upsert: [helper('patched_bridge')] }); - expect(ids()).toEqual([...goals, 'patched_bridge']); - expect(events.filter(event => event.event === 'plan_published')).toHaveLength(1); - const argument = 'A notes-only final response.\n\n' + 'An intermediate estimate with details.\n'.repeat(250) + - '\n```json\n{"example":{"tasks":["compare two cases"]}}\n```\n\nThe remaining inference is at the boundary.\n'; - fs.writeFileSync(notes(), argument); - await finish(action); - expect(state.cooperation!.planPublication?.finalized).toBe(true); - expect(state.cooperation!.planEdited).toBe(true); - (cooperative as any).syncPlanNotes(); - const text = fs.readFileSync(notes(), 'utf8'); - expect(readMathResponse(workers[0].worktree, 'math-plan').tasks.map((task: { id: string }) => task.id)).toEqual(ids()); - expect(text.split('\n').filter(line => line.startsWith(' {"id":"'))).toHaveLength(ids().length + 1); - expect(text).toContain(argument); - }); - - it('accepts a live revision nested under tasks as the same top-level revision', async () => { - // 2026-10-28 HoneycombFreeEnergy: two Lead decisions were rejected as a bare math_plan_invalid for this shape. - const action = await start(), goals = ids(); - await publish(action, { tasks: { baseVersion: action.planVersion, upsert: [helper('nested_bridge')] } }); - expect(ids()).toEqual([...goals, 'nested_bridge']); - expect(events.filter(event => event.event === 'plan_published')).toHaveLength(1); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - }); - - it('publishes new pending helpers as unproved work without confusing their host and plan statuses', async () => { - // BoundedRecovery, 2026-11-09: four new helper definitions carried status: pending. - const action = await start(), goals = ids(); - await publish(action, { upsert: ['spectral', 'monotone', 'subsequence', 'limit'].map(id => ({ - ...helper(id), status: 'pending', - })) }); - expect(ids()).toEqual([...goals, 'spectral', 'monotone', 'subsequence', 'limit']); - expect(state.cooperation!.tasks.slice(-4).map(node => ({ status: node.status, taskStatus: node.task.status, - proof: node.proof, integratedCheck: node.integratedCheck }))).toEqual(Array.from({ length: 4 }, () => ({ - status: 'pending', taskStatus: undefined, proof: undefined, integratedCheck: undefined, - }))); - expect(events.filter(event => event.event === 'plan_published')).toHaveLength(1); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - }); - - it('accepts a corrected changed plan saved at a scheduling checkpoint after rejecting its live event', async () => { - const action = await start(); - await publish(action, { upsert: [{ ...helper('repaired_bridge'), status: 'integrated' }] }); - expect(state.cooperation!.planPublicationRejection?.reason).toContain('field":"status'); - expect(ids()).not.toContain('repaired_bridge'); - fs.writeFileSync(notes(), patchFence({ baseVersion: action.planVersion, - upsert: [{ ...helper('repaired_bridge'), status: 'pending' }] })); - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], action, commitSolverSources(problem, workers[0].worktree), true, 'scheduling-checkpoint'); - expect(ids()).toContain('repaired_bridge'); - expect(state.cooperation!.tasks.find(node => node.task.id === 'repaired_bridge')).toMatchObject({ status: 'pending', attempts: 0 }); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(events.some(event => event.event === 'plan_rejected')).toBe(false); - }); - - it('rejects a live revision against a stale base without changing the graph', async () => { - const action = await start(), before = ids(); - await publish(action, { baseVersion: 'stale-version', upsert: [helper('stale_bridge')] }); - expect(ids()).toEqual(before); - expect(state.cooperation!.planPublicationRejection?.reason).toContain('math_plan_publication_version_conflict'); - await publish(action, { remove: ['missing_task'] }); - expect(state.cooperation!.planPublicationRejection?.reason).toContain('math_plan_patch_unknown_task'); - expect(state.cooperation!.planPublication).toBeUndefined(); - }); - - it('accepts a final revision in RESEARCH.md and replaces it with the complete graph', async () => { - const action = await start(), goals = ids(); - fs.writeFileSync(notes(), 'Route: one bridge closes the target.\n\n' + - patchFence({ baseVersion: action.planVersion, upsert: [helper('final_bridge')] })); - await finish(action); - expect(ids()).toEqual([...goals, 'final_bridge']); - expect(events.some(event => event.event === 'plan_rejected')).toBe(false); - (cooperative as any).syncPlanNotes(); - const text = fs.readFileSync(notes(), 'utf8'); - expect(text).not.toContain('"upsert"'); - expect(text).toContain('Route: one bridge closes the target.'); - expect(readMathResponse(workers[0].worktree, 'math-plan').tasks.map((task: { id: string }) => task.id)).toEqual(ids()); - }); - - it('treats the published revision repeated in final notes as already applied', async () => { - const action = await start(), revision = { upsert: [helper('published_bridge')] }; - await publish(action, revision); - const version = state.cooperation!.planVersion; - fs.writeFileSync(notes(), patchFence({ baseVersion: action.planVersion, ...revision })); - await finish(action); - expect(events.some(event => event.event === 'plan_rejected')).toBe(false); - expect(ids().filter(id => id === 'published_bridge')).toHaveLength(1); - expect(state.cooperation!.planVersion).toBe(version); - }); - - it.each(['final', 'scheduling-checkpoint'] as const) - ('keeps a new pending task publication when the same revision is repeated at %s', async mode => { - const action = await start(), revision = { upsert: [{ ...helper('pending_bridge'), status: 'pending' }] }; - await publish(action, revision); - const version = state.cooperation!.planVersion; - fs.writeFileSync(notes(), patchFence({ baseVersion: action.planVersion, ...revision })); - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], action, commitSolverSources(problem, workers[0].worktree), - mode !== 'final', mode === 'final' ? 'checkpoint' : mode); - expect(events.some(event => event.event === 'plan_rejected')).toBe(false); - expect(ids().filter(id => id === 'pending_bridge')).toHaveLength(1); - expect(state.cooperation!.planVersion).toBe(version); - const node = state.cooperation!.tasks.find(node => node.task.id === 'pending_bridge')!; - expect(node.status).toBe('pending'); - expect(node.task.status).toBeUndefined(); - expect(node.proof).toBeUndefined(); - expect(node.integratedCheck).toBeUndefined(); - }); - - it('rejects a final revision written against an older plan', async () => { - const action = await start(), before = ids(); - fs.writeFileSync(notes(), patchFence({ baseVersion: 'older-plan', upsert: [helper('late_bridge')] })); - await finish(action); - expect(ids()).toEqual(before); - expect(events.find(event => event.event === 'plan_rejected')?.details?.error).toContain('math_plan_patch_version_conflict'); - }); - - it('keeps a live revision when the next final notes only inherit the host-synced graph', async () => { - const first = await start(); - await publish(first, { upsert: [helper('first_bridge')] }); - fs.writeFileSync(notes(), 'First route notes.\n'); - await finish(first); - state.cooperation!.error = 'fixture_request_second_revision'; - (cooperative as any).wakeLead('assembly-failed'); - const second = await start(); - expect(readMathResponse(workers[0].worktree, 'math-plan').tasks.map((task: { id: string }) => task.id)).toEqual(ids()); - await publish(second, { upsert: [helper('second_bridge')] }); - const version = state.cooperation!.planVersion; - await finish(second); - expect(ids()).toContain('second_bridge'); - expect(state.cooperation!.planVersion).toBe(version); - expect(events.some(event => event.event === 'plan_rejected')).toBe(false); - }); - - it('reports peer changes since the previous started Lead turn in the next Lead context', async () => { - const first = await cooperative.next(workers[0], budget); - if (first?.kind !== 'lead') throw new Error('fixture_expected_lead_dispatch'); - expect(cooperative.contextState(first, workers[0]).leadInbox).toBeUndefined(); - expect(cooperative.started(workers[0], first)).toBe(true); - expect(state.cooperation!.leadInboxBasis?.statuses).toEqual(Object.fromEntries(ids().map(id => [id, 'pending']))); - cooperative.activate(workers[0], first, vi.fn(async () => {}), async () => {}); - await publish(first, { upsert: [helper('inbox_bridge')] }); - fs.writeFileSync(notes(), 'Notes.\n'); - await finish(first); - state.cooperation!.deliveries = [...state.cooperation!.deliveries ?? [], { id: 'peer-finding', kind: 'research', producer: workers[1].id, - taskId: 'goal_0', taskDigest: 'digest', status: 'advisory', statement: '', premises: [], dependencies: [], remainingObligations: [], - summary: 'A peer found the missing bridge.', evidenceRefs: [], createdAt: Date.now() }]; - state.workers![1].scheduling = { status: 'idle', since: Date.now() - 60_000 }; - state.cooperation!.error = 'fixture_request_second_revision'; - (cooperative as any).wakeLead('assembly-failed'); - const second = await cooperative.next(workers[0], budget); - if (second?.kind !== 'lead') throw new Error('fixture_expected_second_lead_dispatch'); - const inbox = cooperative.contextState(second, workers[0]).leadInbox!; - expect(inbox.planChanged).toBe(true); - expect(inbox.deliveries.map(item => item.id)).toEqual(['peer-finding']); - expect(inbox.statusChanges).toEqual([{ taskId: 'inbox_bridge', to: 'pending' }]); - expect(inbox.idleWorkers).toMatchObject([{ workerId: workers[1].id, role: 'engineer' }]); - }); - - it('collapses inherited plan fences into one readable accepted graph', () => { - fs.writeFileSync(notes(), 'Prose before.\n\n```math\n{"tasks":[]}\n```\n\nMiddle prose.\n\n' + - patchFence({ baseVersion: 'old', upsert: [] }) + '\n```lean\ntheorem kept : True := trivial\n```\n'); - state.cooperation!.planEdited = true; - (cooperative as any).syncPlanNotes(); - const text = fs.readFileSync(notes(), 'utf8'); - expect(text.match(/```math/gu)).toHaveLength(1); - expect(text).toContain('Prose before.'); expect(text).toContain('Middle prose.'); - expect(text).toContain('theorem kept : True := trivial'); - expect(readMathResponse(workers[0].worktree, 'math-plan').tasks.map((task: { id: string }) => task.id)).toEqual(ids()); - }); -}); diff --git a/tests/solverPlanPublication.test.ts b/tests/solverPlanPublication.test.ts deleted file mode 100644 index 71c67638..00000000 --- a/tests/solverPlanPublication.test.ts +++ /dev/null @@ -1,234 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { requestLeadWake } from '../src/solver/leadWakes'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { publishCooperationPlanFile } from '../src/solver/planTool'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { leadPlanDeliveryFile, parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { integratedProof } from './helpers/taskProof'; - -describe('live replacement plan publication', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - let cooperative: CooperativeResearch, interrupt: ReturnType; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let events: { event: string; details?: Record }[], pending: Promise[]; - const graph = () => ({ tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(route => route.group) }); - const create = (exclusiveCheck: (check: () => Promise) => Promise = async check => check()) => { - const controller = new AbortController(); - const result = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - exclusiveCheck, emit: (event, details) => events.push({ event, details }) }); - instances.push({ cooperative: result, controller }); - return result; - }; - const start = async () => { - const action = await cooperative.next(workers[0], budget); - if (action?.kind !== 'lead' || !action.planNonce) throw new Error('fixture_expected_revision_dispatch'); - expect(cooperative.started(workers[0], action)).toBe(true); - cooperative.activate(workers[0], action, interrupt, async () => {}); - return action; - }; - const file = (action: CooperativeAction) => path.join(workers[0].worktree, leadPlanDeliveryFile(action)!); - const line = (action: Extract, plan = graph()) => JSON.stringify({ - kind: 'plan', dispatchNonce: action.planNonce, baseVersion: action.planVersion, - summary: 'A complete next mathematical step is ready for an idle writer.', ...plan, - }); - const publish = async (action: Extract, value = line(action)) => { - fs.appendFileSync(file(action), value + '\n'); await cooperative.pulse(); - }; - const helper = (id: string) => ({ id, kind: 'lemma' as const, objective: `Prove the independent step ${id}.`, - theoremName: `Tutorial.${id}`, proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }); - const withHelper = (id: string) => ({ ...graph(), tasks: [...graph().tasks, helper(id)] }); - - beforeEach(() => { - const example = localExample('solver-plan-publication-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'engineer', { role: 'engineer' }), - peerWorker(example, 'prover', { role: 'prover' })]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, ...target, - })) }); - state = solverState(problem, example.workspace, { runId: 'replacement-publication-fixture', phase: 'running', - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, - phase: 'checking', turns: 0 })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })), error: 'fixture_request_new_plan' } }); - events = []; instances = []; pending = []; interrupt = vi.fn(async () => {}); - cooperative = create(); - }); - afterEach(async () => { - instances.forEach(instance => instance.controller.abort()); - await Promise.allSettled(pending); - await Promise.allSettled(instances.map(instance => instance.cooperative.stop())); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('starts newly published work without invalidating the publishing Lead or unrelated running writers', async () => { - const running = await cooperative.next(workers[1], budget); - if (running?.kind !== 'task') throw new Error('fixture_expected_goal'); - const peerInterrupt = vi.fn(async () => {}); - cooperative.activate(workers[1], running, peerInterrupt, async () => {}); - const action = await start(), original = structuredClone(action); - const waiting = cooperative.next(workers[2], budget); pending.push(waiting); void waiting.catch(() => {}); - await publish(action, line(action, withHelper('first_bridge'))); - const next = await waiting; - expect(next).toMatchObject({ kind: 'task', task: { id: 'first_bridge' } }); - expect(cooperative.current(action)).toBe(true); - expect(cooperative.current(running)).toBe(true); - expect(action).toEqual(original); - expect(interrupt).not.toHaveBeenCalled(); expect(peerInterrupt).not.toHaveBeenCalled(); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: action.planNonce, baseVersion: original.planVersion }); - expect(state.cooperation!.initialPlanPublication).toBeUndefined(); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('accepts only one complete immutable event in a revision dispatch', async () => { - const action = await start(), value = line(action, withHelper('first_bridge')); - fs.appendFileSync(file(action), value); - await cooperative.pulse(); - expect(state.cooperation!.planPublication).toBeUndefined(); - fs.appendFileSync(file(action), '\n'); await cooperative.pulse(); - const accepted = structuredClone(state.cooperation!.planPublication); - await publish(action, value); - await publish(action, line(action, withHelper('second_bridge'))); - expect(state.cooperation!.planPublication).toEqual(accepted); - expect(state.cooperation!.tasks.some(node => node.task.id === 'second_bridge')).toBe(false); - expect(events.filter(event => event.event === 'plan_published')).toHaveLength(1); - }); - - it('closes the publish command after a publication that leaves the plan version unchanged', async () => { - const action = await start(), workspace = workers[0].worktree; - await publish(action); - expect(state.cooperation!.planPublication?.planVersion).toBe(action.planVersion); - const acceptedLog = fs.readFileSync(file(action)); - expect(publishCooperationPlanFile({ workspace, text: JSON.stringify(withHelper('second_bridge')) })) - .toMatchObject({ ok: false, error: 'math_plan_publication_unavailable' }); - expect(fs.readFileSync(file(action))).toEqual(acceptedLog); - }); - - it('requires both the dispatch nonce and current base version before accepting a replacement', async () => { - const action = await start(), value = JSON.parse(line(action, withHelper('bridge'))); - await publish(action, JSON.stringify({ ...value, dispatchNonce: 'different-dispatch' })); - await publish(action, JSON.stringify({ ...value, baseVersion: 'stale-version' })); - expect(state.cooperation!.planPublication).toBeUndefined(); - expect(events.filter(event => event.event === 'plan_publication_rejected')).toHaveLength(2); - await publish(action, JSON.stringify(value)); - expect(state.cooperation!.tasks.some(node => node.task.id === 'bridge')).toBe(true); - }); - - it('lets a concurrent human edit supersede the Lead without later resurrecting its plan', async () => { - const action = await start(), proposal = line(action, withHelper('stale_bridge')); - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'new-human-plan', - baseVersion: state.cooperation!.planVersion, ...withHelper('human_bridge') }) + '\n'); - await publish(action, proposal); - expect(state.cooperation!.edits![0].status).toBe('applied'); - expect(cooperative.current(action)).toBe(false); - expect(interrupt).toHaveBeenCalledOnce(); - expect(state.workers![0].scheduling?.status).toBe('stopping'); - expect(state.cooperation!.tasks.some(node => node.task.id === 'human_bridge')).toBe(true); - expect(state.cooperation!.tasks.some(node => node.task.id === 'stale_bridge')).toBe(false); - }); - - it('rejects a publication still waiting for exclusive access when the run stops', async () => { - const waiting = deferred(), release = deferred(); - let pause = false; - cooperative = create(async check => { - if (pause) { waiting.resolve(); await release.promise; } - return check(); - }); - const action = await start(), before = graph(); - pause = true; - const polling = publish(action, line(action, withHelper('late_bridge'))); - await Promise.race([waiting.promise, polling]); - const stopped = cooperative.stop(); - release.resolve(); - await Promise.all([polling, stopped]); - - expect(graph()).toEqual(before); - expect(state.cooperation!.planPublication).toBeUndefined(); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(events).toContainEqual(expect.objectContaining({ event: 'plan_publication_rejected', - details: expect.objectContaining({ reason: 'math_plan_publication_superseded' }) })); - }); - - it.each([false, true])('keeps a live graph when inherited plan notes remain in a notes-only final (append prose: %s)', async append => { - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(graph()) + '\n```'); - const action = await start(); - await publish(action, line(action, withHelper('published_bridge'))); - if (append) fs.appendFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), '\nA new mathematical observation with the exact remaining gap.\n'); - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], action, commitSolverSources(problem, workers[0].worktree)); - expect(state.cooperation!.tasks.some(node => node.task.id === 'published_bridge')).toBe(true); - expect(state.cooperation!.planPublication?.finalized).toBe(true); - expect(events.filter(event => event.event === 'plan_updated')).toHaveLength(1); - expect(state.workers![0].scheduling?.status).toBe('idle'); - expect(state.workers![0].phase).toBe('checking'); - }); - - it('restores the published revision while leaving a newer unpublished graph unaccepted', async () => { - const action = await start(); await publish(action, line(action, withHelper('published_bridge'))); - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(withHelper('unpublished_bridge')) + '\n```'); - const stateFile = path.join(directory, 'state.json'); writeSolverRunState(stateFile, state); - state = readSolverRunState(stateFile); - const restored = create(); await restored.restore(); - expect(state.cooperation!.planPublication?.nonce).toBe(action.planNonce); - expect(state.cooperation!.tasks.some(node => node.task.id === 'published_bridge')).toBe(true); - expect(state.cooperation!.tasks.some(node => node.task.id === 'unpublished_bridge')).toBe(false); - expect(restored.current(action)).toBe(false); - }); - - it('accepts an explicit final plan written immediately after its event, before the host polls', async () => { - const action = await start(), published = withHelper('published_bridge'); - const final = { ...published, tasks: [...published.tasks, helper('final_bridge')] }; - fs.appendFileSync(file(action), line(action, published) + '\n'); - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(final) + '\n```'); - await cooperative.pulse(); - expect(state.cooperation!.tasks.some(node => node.task.id === 'final_bridge')).toBe(false); - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], action, commitSolverSources(problem, workers[0].worktree)); - expect(state.cooperation!.tasks.some(node => node.task.id === 'final_bridge')).toBe(true); - expect(state.cooperation!.planPublication?.finalized).toBe(true); - }); - - it('publishes and claims three successive proof waves while a long original-goal writer keeps its assignment', async () => { - delete state.cooperation!.error; cooperative = create(); - const goal = await cooperative.next(workers[1], budget); - if (goal?.kind !== 'task') throw new Error('fixture_expected_long_goal'); - const goalInterrupt = vi.fn(async () => {}); - cooperative.activate(workers[1], goal, goalInterrupt, async () => {}); - for (let wave = 1; wave <= 3; wave++) { - // Stand in for an ordinary planning input; each wave is one Lead plan turn. - requestLeadWake(state.cooperation!.leadWakes!, 'research-finding'); - const action = await start(), id = `wave_${wave}`; - await publish(action, line(action, withHelper(id))); - const task = await cooperative.next(workers[2], budget); - if (task?.kind !== 'task' || task.task.id !== id) throw new Error('fixture_expected_next_wave'); - cooperative.activate(workers[2], task, async () => {}, async () => {}); - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'The complete published graph is executable.\n'); - cooperative.deactivate(workers[0]); - await cooperative.deliver(workers[0], action, commitSolverSources(problem, workers[0].worktree)); - // This scheduler fixture supplies an explicit mock kernel receipt; real integration is tested separately. - integratedProof(state.cooperation!.tasks.find(node => node.task.id === id)!, { - sourceCommit: state.cooperation!.canonicalCommit, environmentDigest: state.environmentDigest, - }); - cooperative.deactivate(workers[2]); - expect(cooperative.current(goal)).toBe(true); - expect(goalInterrupt).not.toHaveBeenCalled(); - } - let dispatched = false; - const waiting = cooperative.next(workers[0], budget); pending.push(waiting); - void waiting.then(() => { dispatched = true; }, () => {}); - for (let poll = 0; poll < 6; poll++) { await cooperative.pulse(); await Promise.resolve(); } - expect(dispatched).toBe(false); - expect(events.filter(event => event.event === 'plan_published')).toHaveLength(3); - expect(state.cooperation!.tasks.filter(node => node.task.id.startsWith('wave_') && node.status === 'integrated')).toHaveLength(3); - expect(state.check).toBeUndefined(); - }); -}); diff --git a/tests/solverPlanPublicationFeedback.test.ts b/tests/solverPlanPublicationFeedback.test.ts deleted file mode 100644 index 8ad2ae57..00000000 --- a/tests/solverPlanPublicationFeedback.test.ts +++ /dev/null @@ -1,443 +0,0 @@ -import fs from 'node:fs'; -import { spawnSync } from 'node:child_process'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import type { SolverProblem } from '../src/solver/problem'; -import { leadPlanDeliveryFile, parseCooperationPlan, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -type Lead = Extract; -type Publication = 'initial' | 'replacement'; - -describe('live Lead publication correction feedback', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - let cooperative: CooperativeResearch, completePlan: ReturnType; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let events: { event: string; details?: Record }[]; - let notify: ReturnType Promise>>; - const savedFile = () => path.join(directory, 'state.json'); - const json = (worker = workers[0]) => JSON.parse(fs.readFileSync(path.join(worker.worktree, 'COOPERATION.json'), 'utf8')); - const nonce = (action: Lead) => action.initialPlanNonce ?? action.planNonce!; - const log = (action: Lead) => leadPlanDeliveryFile(action)!; - const cursor = (action: Lead) => `${workers[0].id}/${log(action)}`; - const rejected = () => events.filter(item => ['initial_plan_rejected', 'plan_publication_rejected'].includes(item.event)); - const helper: CooperativeTask = { id: 'bridge', kind: 'lemma', objective: 'Prove the exact independent bridge.', - theoremName: 'Tutorial.bridge', proofPath: 'Submission.lean', type: 'True', dependsOn: [], revision: 0 }; - const create = () => { - const controller = new AbortController(), currentState = state; - const instance = cooperativeResearch({ state: currentState, workers, retrievalRoot: directory, signal: controller.signal, - save: () => writeSolverRunState(savedFile(), currentState), emit: (event, details) => events.push({ event, details }) }); - instances.push({ cooperative: instance, controller }); - return instance; - }; - const prepare = (kind: Publication = 'replacement') => { - state.cooperation = { canonicalCommit: problem.baseCommit, - tasks: kind === 'initial' ? [] : completePlan.tasks.map(task => ({ task, attempts: 0, status: 'pending' })), - groups: completePlan.groups.map(group => ({ group, turns: 0 })), - ...(kind === 'initial' ? {} : { error: 'fixture_request_new_plan' }), - }; - cooperative = create(); - }; - const start = async () => { - const action = await cooperative.next(workers[0], budget); - if (action?.kind !== 'lead' || !leadPlanDeliveryFile(action)) throw new Error('fixture_expected_publication_dispatch'); - expect(cooperative.started(workers[0], action)).toBe(true); - cooperative.activate(workers[0], action, async () => {}, notify); - return action; - }; - const event = (action: Lead, kind: Publication = 'replacement'): Record => { - const base = { dispatchNonce: nonce(action), baseVersion: action.planVersion }; - return { ...base, kind: 'plan', groups: completePlan.groups, - tasks: [...completePlan.tasks, ...(kind === 'replacement' ? [helper] : [])] }; - }; - const invalid = (action: Lead, kind: Publication = 'replacement') => kind === 'initial' ? '{broken JSON' : - JSON.stringify({ ...event(action, kind), baseVersion: 'stale-version' }); - const publish = async (action: Lead, value: Record | string) => { - fs.appendFileSync(path.join(workers[0].worktree, log(action)), (typeof value === 'string' ? value : JSON.stringify(value)) + '\n'); - await cooperative.pulse(); - }; - const expectCorrection = (message: string, _action: Lead, reason: string) => { - expect(message).toContain(reason); - expect(message).toContain('plan-apply --publish'); - }; - const submitDraft = async (action: Lead, draft: object) => { - const result = spawnSync('bun', ['bin/math.ts', 'plan-apply', '--publish', '--workspace', workers[0].worktree], - { input: JSON.stringify(draft), encoding: 'utf8', timeout: 15_000 }); - expect(result.status, result.stdout || result.stderr).toBe(0); - expect(JSON.parse(result.stdout)).toMatchObject({ status: 'queued', file: log(action) }); - await cooperative.pulse(); - }; - const context = (action: Lead) => directSolverModules.M4.build(problem, - { ...state, cooperation: cooperative.contextState(action, workers[0]) }, - { root: directory, worktree: workers[0].worktree, retrievalRoot: directory, environment: {}, - taskText: 'Decide the exact current mathematical obligations.', assignment: action, maxOptionalContextBytes: 0 }); - const requestCheckpoint = () => { - const research = state.workers![0]; - research.threadId = 'lead-checkpoint-thread'; - research.contextCheckpoint = { threadId: research.threadId, requestId: 'lead-checkpoint-request', requestedAt: 1 }; - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), - 'The exact current argument and its unresolved construction are saved before handing back writing.\n'); - return research; - }; - const checkpoint = (requestId: string, correct = false) => ({ kind: 'checkpoint', requestId, - notesDigest: correct ? mathDigest(fs.readFileSync(path.join(workers[0].worktree, 'RESEARCH.md'))) : '0'.repeat(64) }); - const expectCheckpointCorrection = (message: string, action: Lead, requestId: string, reason: string) => { - for (const detail of [requestId, reason, log(action), '--request-id', '--log']) expect(message).toContain(detail); - expect(message).toContain('rerun checkpoint'); - expect(message).not.toContain('dispatchNonce'); - expect(message).not.toContain('"kind":"plan"'); - }; - - beforeEach(() => { - const example = localExample('solver-publication-feedback-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'engineer', { role: 'engineer' }), - peerWorker(example, 'researcher')]; - completePlan = parseCooperationPlan(problem, { tasks: [ - { id: 'question', kind: 'research', ownerId: workers[2].id, objective: 'Find the exact missing construction.' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}.`, ...target, dependsOn: ['question'] })), - ] }); - state = solverState(problem, example.workspace, { runId: 'publication-feedback-fixture', phase: 'running', - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, - phase: 'checking', turns: 0 })) }); - events = []; instances = []; notify = vi.fn(async (_message: string) => {}); - }); - afterEach(async () => { - instances.forEach(instance => instance.controller.abort()); - await Promise.allSettled(instances.map(instance => instance.cooperative.stop())); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['initial', 'replacement'] as const)( - 'saves and notifies a rejected %s before accepting its same-dispatch correction', async kind => { - prepare(kind); - const action = await start(), before = structuredClone(state.cooperation), originalAction = structuredClone(action); - let savedAtNotification: SolverRunState | undefined, rejectedOffset: number | undefined; - notify.mockImplementation(async message => { - savedAtNotification = readSolverRunState(savedFile()); - const feedback = savedAtNotification.cooperation!.planPublicationRejection!; - expect(feedback.reason).toBe(rejected().at(-1)!.details!.reason); - expect(feedback.file).toBe(log(action)); - expectCorrection(message, action, feedback.reason); - const currentLog = path.join(workers[0].worktree, feedback.file); - rejectedOffset = fs.statSync(currentLog).size; - fs.appendFileSync(currentLog, JSON.stringify(event(action, kind)) + '\n'); - }); - await publish(action, invalid(action, kind)); - const reason = rejected().at(-1)!.details!.reason as string; - const rejection = { nonce: nonce(action), file: log(action), baseVersion: action.planVersion, - offset: rejectedOffset, reason }; - expect(state.cooperation!.planPublicationRejection).toEqual(rejection); - expect(state.cooperation!.tasks).toEqual(before!.tasks); - expect(state.cooperation!.planVersion).toBe(before!.planVersion); - expect(state.cooperation!.error).toBe(before!.error); - expect(cooperative.current(action)).toBe(true); - expect(action).toEqual(originalAction); - expect(notify).toHaveBeenCalledOnce(); - expectCorrection(notify.mock.calls[0][0], action, reason); - expect(savedAtNotification!.cooperation!.planPublicationRejection).toEqual(rejection); - expect(savedAtNotification!.cooperation!.cursors![cursor(action)]).toBe(rejection.offset); - expect(json().planPublicationRejection).toEqual(rejection); - expect(json(workers[1]).planPublicationRejection).toBeUndefined(); - expect(cooperative.contextState(undefined, workers[1]).planPublicationRejection).toBeUndefined(); - await cooperative.pulse(); - expect(rejected()).toHaveLength(1); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(json().planPublicationRejection).toBeUndefined(); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: nonce(action) }); - expect(state.check).toBeUndefined(); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it.each(['initial', 'replacement'] as const)( - 'binds a bare %s graph or patch to the active dispatch', async kind => { - prepare(kind); - const action = await start(), before = structuredClone(state.cooperation); - const graph = kind === 'initial' ? { tasks: completePlan.tasks, groups: completePlan.groups } - : { baseVersion: action.planVersion, upsert: [helper] }; - await publish(action, graph); - expect(rejected()).toHaveLength(1); - expect(rejected()[0].details!.reason).toBe(kind === 'initial' - ? 'math_initial_plan_invalid: kind must be "plan", baseVersion must be the current plan version' - : 'math_plan_publication_invalid: kind must be "plan", dispatchNonce must match this Lead dispatch'); - expect(state.cooperation!.tasks).toEqual(before!.tasks); - expect(state.cooperation!.planPublication).toBeUndefined(); - const message = notify.mock.calls[0][0]; - expect(message).toContain('plan-apply --publish'); - const { baseVersion: _base, ...draft } = graph as typeof graph & { baseVersion?: string }; - await submitDraft(action, draft); - expect(rejected()).toHaveLength(1); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: nonce(action) }); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual( - [...completePlan.tasks, ...(kind === 'replacement' ? [helper] : [])].map(task => task.id)); - expect(state.check).toBeUndefined(); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('includes the current research decision template in a rejected event notice and accepts its same-dispatch correction', async () => { - prepare(); - const question = state.cooperation!.tasks.find(node => node.task.id === 'question')!; - question.status = 'completed'; - state.cooperation!.deliveries = [{ id: 'current-research-finding', producer: workers[2].id, - taskId: question.task.id, taskDigest: taskVersion(question.task), kind: 'research', status: 'advisory', - summary: 'The exact bridge awaits a Lead decision.', statement: '', premises: [], dependencies: [], - remainingObligations: [], evidenceRefs: [], createdAt: 1, lemmaRequests: [helper] }]; - const action = await start(); - await publish(action, event(action)); - expect(rejected()).toHaveLength(1); - expect(rejected()[0].details!.reason).toContain('math_plan_research_decisions_missing'); - expect(notify).toHaveBeenCalledOnce(); - const message = notify.mock.calls[0][0]; - expect(message).toContain('Current response template'); - const template = JSON.parse(message.split('the template itself is not a valid submission):\n')[1].split('\n')[0]); - expect(template).toMatchObject({ baseVersion: action.planVersion, upsert: [], - researchDecisions: [{ deliveryId: 'current-research-finding' }] }); - expect(template).not.toHaveProperty('file'); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - expect(state.cooperation!.planPublication).toBeUndefined(); - await submitDraft(action, { ...template, upsert: [helper], researchDecisions: [{ deliveryId: 'current-research-finding', - outcome: 'adopt', taskIds: [helper.id], reason: 'This exact helper closes the consumer obligation.' }] }); - expect(notify).toHaveBeenCalledOnce(); - expect(rejected()).toHaveLength(1); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: nonce(action) }); - expect(state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ - deliveryId: 'current-research-finding', outcome: 'adopt' })); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('names the malformed decision field before allowing another event in the same dispatch', async () => { - prepare(); - const action = await start(); - await publish(action, { ...event(action), nextCheckDecisions: [{ checkId: 'a'.repeat(64), - outcomeDeliveryId: 'a-current-outcome', action: 'pause', reason: 'Review this outcome.' }] }); - const reason = rejected()[0].details!.reason as string; - expect(reason).toContain('math_plan_next_check_decisions_invalid: nextCheckDecisions[0].action:'); - expectCorrection(notify.mock.calls[0][0], action, reason); - expect(state.cooperation!.planPublication).toBeUndefined(); - await publish(action, event(action)); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: nonce(action) }); - }); - - it('retries a failed notice without rereading the rejected event or changing its saved cursor', async () => { - prepare(); - const action = await start(); - notify.mockRejectedValueOnce(new Error('transport unavailable')); - await publish(action, invalid(action)); - const rejection = structuredClone(state.cooperation!.planPublicationRejection); - const offset = state.cooperation!.cursors![cursor(action)]; - expect(notify).toHaveBeenCalledOnce(); - await cooperative.pulse(); - expect(notify).toHaveBeenCalledTimes(2); - expect(state.cooperation!.planPublicationRejection).toEqual(rejection); - expect(state.cooperation!.cursors![cursor(action)]).toBe(offset); - expect(rejected()).toHaveLength(1); - await cooperative.pulse(); - expect(notify).toHaveBeenCalledTimes(2); - await publish(action, event(action)); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - }); - - it('accepts the next valid event while a rejection notice is still pending', async () => { - prepare(); - const action = await start(); - let release!: () => void; - const held = new Promise(resolve => { release = resolve; }); - notify.mockImplementation(() => held); - let intakeSettled = false; - const firstPulse = publish(action, invalid(action)).then(() => { intakeSettled = true; }); - try { - await vi.waitFor(() => expect(intakeSettled).toBe(true), { timeout: 500 }); - expect(notify).toHaveBeenCalledOnce(); - expect(readSolverRunState(savedFile()).cooperation!.planPublicationRejection).toBeDefined(); - await publish(action, event(action)); - expect(state.cooperation!.planPublication).toMatchObject({ nonce: nonce(action) }); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(notify).toHaveBeenCalledOnce(); - } finally { release(); await firstPulse; } - }); - - it.each(['initial', 'replacement'] as const)( - 'retains a rejected %s across JSON restore and supplies the new dispatch in full and short context', async kind => { - prepare(kind); - if (kind === 'replacement') fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), - '```math-plan\n' + JSON.stringify({ tasks: completePlan.tasks, groups: completePlan.groups }) + - '\n```\nThe exact missing construction is still unresolved; preserve this argument while correcting publication.\n'); - const previous = await start(); - await publish(previous, invalid(previous, kind)); - const rejection = structuredClone(state.cooperation!.planPublicationRejection); - expect(rejection).toBeDefined(); - state = readSolverRunState(savedFile()); - cooperative = create(); await cooperative.restore(); - const action = await start(); - expect(action.planVersion).toBe(previous.planVersion); - expect(nonce(action)).not.toBe(nonce(previous)); - expect(log(action)).not.toBe(log(previous)); - expect(state.cooperation!.planPublicationRejection).toEqual(rejection); - expect(json().planPublicationRejection).toEqual(rejection); - const compiled = context(action); - expect(compiled.manifest!.included).toContainEqual(expect.objectContaining({ id: 'plan-publication-rejection', required: true })); - expect(compiled.manifest).toMatchObject({ maxOptionalBytes: 0, optionalBytes: 0 }); - for (const message of [compiled.message, compiled.continuationMessage!]) expectCorrection(message, action, rejection!.reason); - await publish(action, event(action, kind)); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - }); - - it.each(['initial', 'replacement'] as const)( - 'keeps an accepted %s when its log is rewritten below the cursor and keeps reading later events', async kind => { - prepare(kind); - const action = await start(); - await publish(action, event(action, kind)); - const accepted = structuredClone(state.cooperation), file = path.join(workers[0].worktree, log(action)); - notify.mockClear(); - fs.writeFileSync(file, JSON.stringify({ ...event(action, kind), groups: [] }) + '\n'); - await expect(cooperative.pulse()).resolves.toBeUndefined(); - expect(rejected().map(item => item.details!.reason)).toEqual(['math_delivery_log_rewritten']); - expect(state.cooperation!.cursors![cursor(action)]).toBe(fs.statSync(file).size); - expect(state.cooperation!.tasks).toEqual(accepted!.tasks); - expect(state.cooperation!.planPublication).toEqual(accepted!.planPublication); - expect(events.some(item => item.event === 'cooperation_poll_failed')).toBe(false); - await publish(action, '{broken JSON'); - expect(rejected()).toHaveLength(2); - expect(rejected()[1].details!.reason).toMatch(/invalid_json$/u); - expect(notify).not.toHaveBeenCalled(); - }); - - it('keeps later rejected events audit-only once the replacement dispatch has succeeded', async () => { - const kind = 'replacement'; - prepare(kind); - const action = await start(); - await publish(action, invalid(action, kind)); - await publish(action, event(action, kind)); - notify.mockClear(); - const accepted = structuredClone(state.cooperation); - await publish(action, '{broken JSON'); - await publish(action, { ...event(action, kind), summary: 'An additional event cannot replace this accepted dispatch.' }); - expect(rejected()).toHaveLength(3); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(state.cooperation!.tasks).toEqual(accepted!.tasks); - expect(state.cooperation!.planPublication).toEqual(accepted!.planPublication); - expect(notify).not.toHaveBeenCalled(); - }); - - it('clears correction feedback when a human plan supersedes its dispatch and ignores its late event', async () => { - prepare(); - const action = await start(); - await publish(action, invalid(action)); - const reason = state.cooperation!.planPublicationRejection!.reason; - notify.mockClear(); - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'human-replacement', - baseVersion: action.planVersion, tasks: [...completePlan.tasks, { ...helper, id: 'human_bridge', theoremName: 'Tutorial.human_bridge' }], - groups: completePlan.groups }) + '\n'); - await publish(action, event(action)); - expect(state.cooperation!.edits).toMatchObject([{ status: 'applied' }]); - expect(cooperative.current(action)).toBe(false); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(json().planPublicationRejection).toBeUndefined(); - expect(state.cooperation!.tasks.some(node => node.task.id === 'human_bridge')).toBe(true); - expect(state.cooperation!.tasks.some(node => node.task.id === helper.id)).toBe(false); - expect(notify.mock.calls.every(([message]) => !message.includes(reason))).toBe(true); - }); - - it('corrects a checkpoint through its notice after the same active Lead has already published an initial plan', async () => { - prepare('initial'); - const action = await start(); - await publish(action, event(action, 'initial')); - const accepted = structuredClone({ tasks: state.cooperation!.tasks, planVersion: state.cooperation!.planVersion, - publication: state.cooperation!.planPublication }); - expect(cooperative.current(action)).toBe(true); - const research = requestCheckpoint(), requestId = research.contextCheckpoint!.requestId!; - let savedAtNotification: SolverRunState | undefined; - notify.mockImplementation(async message => { - savedAtNotification = readSolverRunState(savedFile()); - const feedback = savedAtNotification.workers![0].contextCheckpoint!.rejection!; - expectCheckpointCorrection(message, action, requestId, feedback.reason); - expect(savedAtNotification.cooperation!.cursors![cursor(action)]).toBe(feedback.offset); - fs.appendFileSync(path.join(workers[0].worktree, feedback.file), JSON.stringify(checkpoint(requestId, true)) + '\n'); - }); - await publish(action, checkpoint(requestId)); - const rejection = cooperative.contextState(action, workers[0]).contextCheckpointRejection; - expect(rejection).toMatchObject({ threadId: research.threadId, requestId, file: log(action), reason: 'math_delivery_invalid' }); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - expect(notify).toHaveBeenCalledOnce(); - expect(savedAtNotification!.workers![0].contextCheckpoint!.rejection).toEqual({ - file: rejection!.file, offset: rejection!.offset, reason: rejection!.reason }); - expect(json().contextCheckpointRejection).toEqual(rejection); - await cooperative.pulse(); - expect(research.contextCheckpoint).toMatchObject({ publishedNotesDigest: checkpoint(requestId, true).notesDigest }); - expect(research.contextCheckpoint!.rejection).toBeUndefined(); - expect(cooperative.contextState(action, workers[0]).contextCheckpointRejection).toBeUndefined(); - expect(json().contextCheckpointRejection).toBeUndefined(); - expect({ tasks: state.cooperation!.tasks, planVersion: state.cooperation!.planVersion, - publication: state.cooperation!.planPublication }).toEqual(accepted); - expect(state.check).toBeUndefined(); - expect(state.cooperation!.tasks.every(node => !node.proof && !node.integratedCheck)).toBe(true); - }); - - it('keeps plan and checkpoint corrections independent in live feedback and both context forms', async () => { - prepare(); - const action = await start(); - await publish(action, invalid(action)); - const planRejection = structuredClone(state.cooperation!.planPublicationRejection); - expect(planRejection).toBeDefined(); - const research = requestCheckpoint(), requestId = research.contextCheckpoint!.requestId!; - notify.mockClear(); - await publish(action, checkpoint(requestId)); - const rejection = cooperative.contextState(action, workers[0]).contextCheckpointRejection; - expect(rejection).toMatchObject({ threadId: research.threadId, requestId, file: log(action), reason: 'math_delivery_invalid' }); - expect(state.cooperation!.planPublicationRejection).toEqual(planRejection); - expect(notify).toHaveBeenCalledOnce(); - expectCheckpointCorrection(notify.mock.calls[0][0], action, requestId, rejection!.reason); - expect(json().contextCheckpointRejection).toEqual(rejection); - expect(json(workers[1]).contextCheckpointRejection).toBeUndefined(); - expect(cooperative.contextState(undefined, workers[1]).contextCheckpointRejection).toBeUndefined(); - const compiled = context(action); - for (const id of ['plan-publication-rejection', 'context-checkpoint-rejection']) - expect(compiled.manifest!.included).toContainEqual(expect.objectContaining({ id, required: true })); - for (const message of [compiled.message, compiled.continuationMessage!]) { - for (const detail of [requestId, rejection!.reason, log(action), '--request-id', '--log', planRejection!.reason]) - expect(message).toContain(detail); - } - await publish(action, checkpoint(requestId, true)); - expect(research.contextCheckpoint).toMatchObject({ publishedNotesDigest: checkpoint(requestId, true).notesDigest }); - expect(research.contextCheckpoint!.rejection).toBeUndefined(); - expect(cooperative.contextState(action, workers[0]).contextCheckpointRejection).toBeUndefined(); - expect(state.cooperation!.planPublicationRejection).toEqual(planRejection); - expect(context(action).manifest!.included).not.toContainEqual(expect.objectContaining({ id: 'context-checkpoint-rejection' })); - await publish(action, event(action)); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - }); - - it('stops exposing or retrying checkpoint diagnostics when its request or thread is replaced', async () => { - prepare(); - const action = await start(), research = requestCheckpoint(); - for (const next of [{ threadId: research.threadId!, requestId: 'next-checkpoint-request' }, - { threadId: 'next-checkpoint-thread', requestId: 'next-checkpoint-request' }]) { - notify.mockRejectedValueOnce(new Error('transport unavailable')); - await publish(action, checkpoint(research.contextCheckpoint!.requestId!)); - expect(cooperative.contextState(action, workers[0]).contextCheckpointRejection).toMatchObject({ threadId: research.threadId, - requestId: research.contextCheckpoint!.requestId, file: log(action) }); - notify.mockClear(); - research.threadId = next.threadId; - research.contextCheckpoint = { ...next, requestedAt: 2 }; - cooperative.activate(workers[0], action, async () => {}, notify); - await cooperative.pulse(); - expect(notify).not.toHaveBeenCalled(); - expect(cooperative.contextState(action, workers[0]).contextCheckpointRejection).toBeUndefined(); - expect(json().contextCheckpointRejection).toBeUndefined(); - const compiled = context(action); - expect(compiled.manifest!.included).not.toContainEqual(expect.objectContaining({ id: 'context-checkpoint-rejection' })); - expect(compiled.continuationMessage).not.toContain('math_delivery_invalid'); - expect(state.cooperation!.planPublicationRejection).toBeUndefined(); - } - }); -}); diff --git a/tests/solverPortfolioGate.test.ts b/tests/solverPortfolioGate.test.ts deleted file mode 100644 index 60097e23..00000000 --- a/tests/solverPortfolioGate.test.ts +++ /dev/null @@ -1,285 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLocalExample } from '../src/math/localExample'; -import { isMathPathWithin } from '../src/math/paths'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; -import { prepareHarnessProcess } from '../src/runtime/harnessProcess'; -import { assertResearchHarnessCurrent, bindResearchHarness } from '../src/runtime/researchHarness'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { buildRunInspection } from '../src/solver/inspection'; -import { configurePortfolioExploration, evaluatePortfolioGate, portfolioPhase2Guidance, - runPortfolioExploration, type PortfolioScoutReport } from '../src/solver/portfolioExploration'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { localExample, solverState } from './helpers/solver'; -import { deferred } from './helpers/async'; - -const roots: string[] = []; -afterEach(() => { vi.useRealTimers(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); - -const foundation = { id: 'base-change-of-variables', proofPath: 'Submission.lean', theoremName: 'Portfolio.sharedBase', - type: '∀ (n : Nat), n + 0 = n', objective: 'Prove the shared change of variables separately.' }; -const proposal = (profile: PortfolioScoutReport['profile'], fields: Partial = {}): PortfolioScoutReport => ({ - profile, routeId: profile, status: 'proposed', blueprintSummary: 'Reduce to a one-dimensional identity.', - keyTransformations: ['Use the same parameter for both integrals.'], proposedFoundationLemmas: [foundation], - falsificationEvidence: [], obstructions: [], probeRefs: [], ...fields, -}); -const structural = proposal('structural-symmetry', { obstructions: ['Endpoint symmetry fails.'] }); -const constructive = proposal('explicit-constructive', { blueprintSummary: 'Construct a rational witness.' }); -const refutation = proposal('falsification-obstruction', { - routeId: 'structural-symmetry', status: 'refuted', proposedFoundationLemmas: [], - falsificationEvidence: [{ kind: 'counterexample', claim: 'The map preserves the endpoint.', probe: 'Evaluate map(0).', result: 'map(0) = 1.' }], - probeRefs: ['witness.py'], -}); -const assignment = (options: MathAgentOptions) => options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!.slice('portfolio-'.length) as - PortfolioScoutReport['profile']; -const withoutProfile = ({ profile: _, ...result }: PortfolioScoutReport) => result; - -function mountFixture(directory: string) { - roots.push(directory); - const workspace = path.join(directory, 'worktree'); - const { activeProblemPath } = bootstrapLocalExample(workspace); - return { directory, workspace, problem: readSolverProblem(workspace, activeProblemPath) }; -} - -function fixture(durationMs = 1000, capacity = 3, example = localExample('portfolio-gate-')) { - const { directory, workspace, problem } = example; - if (!roots.includes(directory)) roots.push(directory); - const state = solverState(problem, workspace, { phase: 'prepared', runId: 'portfolio-fixture', workerCount: capacity }); - state.portfolioExploration = configurePortfolioExploration(undefined, { enable: true, durationMs, capacity, startedResearch: false }); - const stateFile = path.join(directory, 'state.json'); - const events: { event: string; details?: Record }[] = []; - const profile = path.join(directory, 'codex'); - fs.mkdirSync(profile, { mode: 0o700 }); - const input = { state, taskText: 'Prove the original statement.', executable: 'offline', profile, maxTurns: 4, - maxTurnMs: Infinity, maxTotalTokens: 1000, remainingMs: () => Infinity, signal: new AbortController().signal, - prepareWorkspace: (workspace: string) => ({ project: path.join(workspace, problem.projectRelative), environment: {} }), - emit: (event: string, details?: Record) => { events.push({ event, details }); }, - save: () => writeSolverRunState(stateFile, state) }; - return { state, stateFile, events, input }; -} - -function session(options: MathAgentOptions, reports: PortfolioScoutReport[], beforeReport = () => Promise.resolve()): MathAgentSession { - return { - threadId: 'fixture-thread', close: async () => {}, interrupt: async () => {}, - stopForFreeze: async () => ({ status: 'stopped' }), - run: async (_message, _id, workspace, start) => { - start('fixture-turn'); - await beforeReport(); - if (reports.some(report => report.probeRefs.includes('witness.py'))) - fs.writeFileSync(path.join(workspace, '.scratch', 'portfolio', 'witness.py'), 'assert 0 + 1 == 1\n'); - fs.writeFileSync(path.join(workspace, 'PORTFOLIO.json'), JSON.stringify({ reports: reports.map(withoutProfile) })); - options.onUsage({ totalTokens: 20 }, { turnId: 'fixture-turn' }); - return 'completed'; - }, - }; -} - -describe('portfolio exploration gate', () => { - it('retires evidence-backed alternatives and ranks a primary and at most one backup', () => { - const fallback = proposal('falsification-obstruction', { obstructions: ['Requires a preliminary smoothness bound.'] }); - const unsupported = proposal('falsification-obstruction', { routeId: 'explicit-constructive', status: 'refuted' }); - const gate = evaluatePortfolioGate([structural, constructive, fallback, refutation, unsupported], 42); - expect(gate).toEqual({ primaryRouteId: 'explicit-constructive', backupRouteId: 'falsification-obstruction', - retiredRoutes: [{ routeId: 'structural-symmetry', reason: 'The map preserves the endpoint.: map(0) = 1.', - retiredAt: 42, source: 'portfolio', evidenceRefs: ['portfolio:falsification-obstruction/structural-symmetry', - 'portfolio:falsification-obstruction/witness.py'] }], foundationLemmas: [foundation] }); - expect(evaluatePortfolioGate([refutation]).primaryRouteId).toBeUndefined(); - expect(evaluatePortfolioGate([{ ...constructive, proposedFoundationLemmas: [] }, - { ...structural, obstructions: [] }]).primaryRouteId).toBe('structural-symmetry'); - }); - - it.each([true, false])('runs concurrent scouts and hands off checked artifact metadata (native advisory: %s)', async nativeAdvisory => { - const { state, stateFile, input, events } = fixture(5000); - const opened: MathAgentOptions[] = []; - let release!: () => void, attacksReady!: () => void; - const available = new Promise(resolve => { release = resolve; }); - const attackTargets = new Promise(resolve => { attacksReady = resolve; }); - const notify = vi.fn(async (text: string) => { if (text.includes('Construct a rational witness.')) attacksReady(); }); - await runPortfolioExploration({ ...input, open: async options => { - opened.push(options); - if (opened.length === 3) release(); - const profile = assignment(options); - const scout = session(options, [profile === 'structural-symmetry' ? structural - : profile === 'explicit-constructive' ? constructive : refutation], - () => profile === 'falsification-obstruction' ? attackTargets : available); - return profile === 'falsification-obstruction' - ? { ...scout, notify, advisoryNotifications: nativeAdvisory ? 'native-history' : undefined } : scout; - } }); - expect(opened.map(assignment)).toEqual(['structural-symmetry', 'explicit-constructive', 'falsification-obstruction']); - expect(new Set(opened.map(options => options.workspace)).size).toBe(3); - expect(opened.every(options => options.isolateProcess && options.workspace !== state.worktree && !fs.existsSync(options.workspace))).toBe(true); - const parent = path.join(path.dirname(state.worktree), 'portfolio-worktrees'); - for (const { workspace, isolatedWorkspaceParent } of opened) { - expect(path.dirname(workspace)).toBe(parent); - expect(isolatedWorkspaceParent).toBe(parent); - } - expect(fs.existsSync(parent)).toBe(false); - expect(opened[0].instructions).toContain('symmetries'); - expect(opened[1].instructions).toContain('rational bound'); - expect(opened[2].instructions).toContain('counterexamples'); - expect(notify).toHaveBeenCalledWith(expect.stringContaining('Construct a rational witness.'), - nativeAdvisory ? { mode: 'advisory' } : { waitForRequest: true }); - expect(state.tokenBudget?.reportedTotalTokens).toBe(60); - expect(events.filter(event => event.event === 'portfolio_scout_started')).toHaveLength(3); - const restored = readSolverRunState(stateFile), persisted = restored.portfolioExploration; - expect(buildRunInspection(restored)).toMatchObject({ turns: 3, usage: { totalTokens: 60 }, - tokenBudget: { reportedTotalTokens: 60, usageComplete: true } }); - expect(persisted).toEqual(state.portfolioExploration); - expect(persisted?.gate?.retiredRoutes[0].routeId).toBe('structural-symmetry'); - expect(persisted?.scouts[2].probes).toMatchObject([{ ref: 'witness.py', text: 'assert 0 + 1 == 1\n' }]); - expect(portfolioPhase2Guidance(persisted)).toContain('Construct a rational witness.'); - expect(portfolioPhase2Guidance(persisted)).toContain(foundation.type); - expect(state.check).toBeUndefined(); - const open = vi.fn(); - await runPortfolioExploration({ ...input, state: readSolverRunState(stateFile), open }); - expect(open).not.toHaveBeenCalled(); - }); - - it.skipIf(process.platform !== 'linux' || !fs.existsSync('/usr/bin/bwrap'))( - 'masks /tmp and scout peers in the launch, then unregisters even a failed startup', async () => { - // Match the worker image layout, where the run and profile are both outside /tmp. - const directory = fs.mkdtempSync(path.join(fs.realpathSync(process.cwd()), '.portfolio-mount-test-')); - const { state, input, events } = fixture(5000, 2, mountFixture(directory)); - const profile = input.profile, catalog = path.join(profile, 'models.json'); - const config = `model_provider = "web_provider"\nmodel_catalog_json = ${JSON.stringify(catalog)}\n`; - fs.writeFileSync(catalog, '{"models":[]}'); - fs.writeFileSync(path.join(profile, 'config.toml'), config); - const identity = bindResearchHarness('codex', '/bin/true', profile, {}, state.model); - const parent = path.join(directory, 'portfolio-worktrees'); - const profilesRoot = path.join(directory, 'portfolio-profiles'); - const worktreesBefore = git(state.worktree, ['worktree', 'list', '--porcelain']); - const launches: ReturnType[] = []; - const opened: MathAgentOptions[] = []; - const modes: number[] = []; - const bothOpened = deferred(); - await runPortfolioExploration({ ...input, profile, open: async options => { - modes.push(fs.statSync(parent).mode & 0o777); - opened.push(options); - if (opened.length === 2) bothOpened.resolve(); - await bothOpened.promise; - expect(fs.statSync(options.profile).mode & 0o777).toBe(0o700); - expect(fs.readFileSync(path.join(options.profile, 'config.toml'), 'utf8')).toBe(config); - const runtime = path.join(options.profile, 'runtime'); - fs.mkdirSync(runtime, { mode: 0o700 }); - launches.push(prepareHarnessProcess({ ...options, profile: runtime }, '/bin/true', [])); - fs.writeFileSync(path.join(runtime, 'state_5.sqlite'), options.workspace, { flag: 'wx' }); - expect(fs.readFileSync(path.join(runtime, 'state_5.sqlite'), 'utf8')).toBe(options.workspace); - throw new Error('math_codex_rpc_failed:-32603:thread/start:private startup diagnostic'); - } }); - expect(modes).toEqual([0o700, 0o700]); - expect(launches).toHaveLength(2); - expect(new Set(opened.map(options => options.profile)).size).toBe(2); - for (const [index, launch] of launches.entries()) { - const options = opened[index], runtime = path.join(options.profile, 'runtime'); - expect(path.dirname(path.dirname(options.profile))).toBe(profilesRoot); - expect(isMathPathWithin(parent, options.profile)).toBe(false); - expect(isMathPathWithin(profile, options.profile)).toBe(false); - expect(launch.isolationReceipt.hiddenRoots).toEqual(expect.arrayContaining(['/tmp', parent])); - expect(launch.args.slice(launch.args.indexOf('/tmp') - 1, launch.args.indexOf('/tmp') + 1)).toEqual(['--tmpfs', '/tmp']); - expect(launch.args.slice(launch.args.indexOf(parent) - 1, launch.args.indexOf(parent) + 1)).toEqual(['--tmpfs', parent]); - expect(launch.isolationReceipt.writableDirectories).toEqual([options.workspace, runtime]); - expect(launch.env.XDG_STATE_HOME).toBe(path.join(runtime, 'xdg', 'state')); - expect(launch.isolationReceipt.hiddenRoots).not.toContain(profile); - } - expect(git(state.worktree, ['worktree', 'list', '--porcelain'])).toBe(worktreesBefore); - expect(fs.existsSync(parent)).toBe(false); - expect(fs.existsSync(profilesRoot)).toBe(false); - expect(fs.readdirSync(profile).sort()).toEqual(['config.toml', 'models.json']); - expect(() => assertResearchHarnessCurrent(identity, {}, state.model)).not.toThrow(); - expect(state.turns).toBe(0); - expect(events.filter(event => event.event === 'portfolio_scout_unavailable').map(event => event.details?.reason)) - .toEqual(['math_codex_rpc_failed', 'math_codex_rpc_failed']); - expect(JSON.stringify(events)).not.toContain('private startup diagnostic'); - }); - - it('requests wrap-up before the deadline and salvages only valid saved reports after abort', async () => { - vi.useFakeTimers(); - const { input, events, state } = fixture(60_000, 2); - const notices = vi.fn(); - const running = deferred(); - let started = 0; - const completion = runPortfolioExploration({ ...input, open: async options => { - const profile = assignment(options); - expect(options.instructions).toContain('60 seconds'); - expect(options.instructions).toContain('Write an initial valid PORTFOLIO.json by halfway'); - expect(options.instructions).toContain('renaming it over the report'); - return { ...session(options, []), advisoryNotifications: 'native-history', - notify: async (notice, mode) => { - notices(profile, notice, mode); - const file = path.join(options.workspace, 'PORTFOLIO.json'); - fs.writeFileSync(file + '.tmp', profile === 'structural-symmetry' - ? JSON.stringify({ reports: [withoutProfile(structural)] }) : '{"reports":[]}'); - fs.renameSync(file + '.tmp', file); - }, - run: async (_message, _id, _workspace, begin) => { - begin('scout-turn'); - if (++started === 2) running.resolve(); - return new Promise((_resolve, reject) => options.signal!.addEventListener('abort', - () => reject(new Error('math_codex_transport_closed:forced')), { once: true })); - } }; - } }); - await Promise.race([running.promise, completion.then(() => { throw new Error('scouts did not start'); })]); - await vi.advanceTimersByTimeAsync(41_999); - expect(notices).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); - expect(notices).toHaveBeenCalledTimes(2); - expect(notices).toHaveBeenCalledWith('structural-symmetry', expect.stringContaining('finalize PORTFOLIO.json now'), { mode: 'advisory' }); - await vi.advanceTimersByTimeAsync(18_000); - await completion; - expect(state.portfolioExploration).toMatchObject({ phase: 'completed', scouts: [ - { status: 'reported', reports: [structural] }, { status: 'timed-out' }], gate: { primaryRouteId: 'structural-symmetry' } }); - expect(events.filter(event => event.event === 'portfolio_scout_unavailable')).toEqual([ - { event: 'portfolio_scout_unavailable', details: expect.objectContaining({ reason: 'math_portfolio_scout_timed_out' }) }, - ]); - expect(vi.getTimerCount()).toBe(0); - }); - - it('resumes only unfinished scouts within the saved deadline', async () => { - const { state, stateFile, input } = fixture(4000, 2); - const first = state.portfolioExploration!.scouts[0]; - first.status = 'reported'; - first.reports = [structural]; - state.portfolioExploration!.deadlineAt = Date.now() + 3000; - input.save(); - const resumed = readSolverRunState(stateFile), deadline = resumed.portfolioExploration!.deadlineAt; - const open = vi.fn(async options => session(options, [constructive])); - await runPortfolioExploration({ ...input, state: resumed, open }); - expect(open).toHaveBeenCalledOnce(); - expect(open.mock.calls[0][0].turnTimeoutMs).toBeLessThanOrEqual(3000); - expect(resumed.portfolioExploration).toMatchObject({ phase: 'completed', deadlineAt: deadline, - gate: { primaryRouteId: 'explicit-constructive', backupRouteId: 'structural-symmetry' } }); - }); - - it('closes an expired stage without spending a model turn and preserves direct and skip behavior', async () => { - const { state, input } = fixture(100); - const open = vi.fn(); - expect(configurePortfolioExploration(undefined, { capacity: 1, startedResearch: true })).toBeUndefined(); - expect(configurePortfolioExploration(undefined, { capacity: 1, startedResearch: false, skip: true })).toBeUndefined(); - expect(() => configurePortfolioExploration(undefined, { capacity: 1, startedResearch: false, enable: true })) - .toThrow('requires at least two workers'); - const skipped = configurePortfolioExploration(state.portfolioExploration, { capacity: 3, startedResearch: false, skip: true }); - expect(skipped?.phase).toBe('skipped'); - await runPortfolioExploration({ ...input, state: { ...state, portfolioExploration: skipped }, open }); - await runPortfolioExploration({ ...input, state: { ...state, portfolioExploration: undefined }, open }); - state.portfolioExploration!.deadlineAt = Date.now() - 1; - await runPortfolioExploration({ ...input, open }); - expect(open).not.toHaveBeenCalled(); - expect(state.portfolioExploration).toMatchObject({ phase: 'completed', - scouts: Array.from({ length: 3 }, () => expect.objectContaining({ status: 'timed-out' })) }); - }); - - it('reserves a proof turn and does not start an undersized portfolio', async () => { - const { state, input } = fixture(5000); - const open = vi.fn(); - await runPortfolioExploration({ ...input, maxTurns: 2, open }); - expect(open).not.toHaveBeenCalled(); - expect(state.turns).toBe(0); - const enabled = configurePortfolioExploration(undefined, { enable: true, capacity: 3, startedResearch: false }); - state.portfolioExploration = enabled; - const scout = vi.fn(async options => session(options, [proposal(assignment(options))])); - await runPortfolioExploration({ ...input, maxTurns: 3, open: scout }); - expect(scout).toHaveBeenCalledTimes(2); - expect(state.turns).toBe(2); - }); -}); diff --git a/tests/solverProjectionPreparation.test.ts b/tests/solverProjectionPreparation.test.ts deleted file mode 100644 index 476bc107..00000000 --- a/tests/solverProjectionPreparation.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLocalExample, LOCAL_EXAMPLE_PROOF } from '../src/math/localExample'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import * as proofApi from '../src/solver/cooperativeProof'; -import { committedSource, commitSolverSources, readSolverProblem, type SolverProblem } from '../src/solver/problem'; -import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { leadWorker, solverState } from './helpers/solver'; -import { receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => 'projection-preparation-fixture-tools', - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/math/mathProofEnvironment', async importOriginal => ({ - ...await importOriginal(), resolveMathProofEnvironment: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const verified = (request: MathematicsVerifierBatchRequest) => receiptBatch(request, - { sessionId: 'projection-preparation-fixture', receiptId: (_, theoremName) => `receipt-${request.targetCommit}-${theoremName}` }); - -type Projector = ReturnType; -type Preparation = { commit: string; worktree: string; targets: string[]; project: Projector }; - -describe('integrated task projection preparation', () => { - let directory: string, workspace: string, file: string, problem: SolverProblem, state: SolverRunState; - let cooperative: CooperativeResearch | undefined, controller: AbortController, preparations: Preparation[]; - let events: { event: string; details?: Record }[]; - - const helpers = () => state.cooperation!.tasks.filter(node => node.task.kind === 'lemma'); - const recheck = (commit = state.cooperation!.canonicalCommit!) => (cooperative as any).recheckIntegrated(commit) as Promise; - const prepare = (count: number) => { - const receipt = bootstrapLocalExample(workspace); - problem = readSolverProblem(workspace, receipt.activeProblemPath); - file = path.join(receipt.projectRoot, 'Submission.lean'); - fs.writeFileSync(file, LOCAL_EXAMPLE_PROOF); - commitSolverSources(problem, workspace); - const tasks: CooperativeTask[] = Array.from({ length: count }, (_, index) => ({ id: `helper_${index}`, - kind: 'lemma', objective: `Prove helper ${index}.`, proofPath: 'Submission.lean', - theoremName: `Tutorial.helper_${index}`, type: 'True', dependsOn: [], revision: 0 })); - const declarations = tasks.map(task => `lemma ${task.id} : True := by trivial`).join('\n'); - fs.writeFileSync(file, LOCAL_EXAMPLE_PROOF.replace('theorem add_zero', `${declarations}\n\ntheorem add_zero`)); - const canonical = commitSolverSources(problem, workspace); - state = solverState(problem, workspace, { runId: 'projection-preparation-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: canonical, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [...tasks.map(task => ({ task, status: 'integrated' as const, attempts: 1 })), - ...problem.targets.map((target, index) => ({ - task: { id: `goal_${index}`, kind: 'goal' as const, objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: [], revision: 0, status: 'paused' as const }, - status: 'pending' as const, attempts: 0, - }))] } }); - const lead = leadWorker(problem, workspace); - cooperative = cooperativeResearch({ state, workers: [lead], retrievalRoot: directory, - access: new Map([[lead.id, { environment: { PATH: '/usr/bin:/bin', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'math.env') }, retrievalRoot: directory }]]), - signal: controller.signal, emit: (event, details) => events.push({ event, details }), exclusiveCheck: check => check() }); - return canonical; - }; - const expectVerified = (canonical: string) => { - for (const node of helpers()) { - expect(node, node.feedback).toMatchObject({ status: 'integrated', integratedCheck: { - passed: true, commit: canonical, seedCommit: canonical, taskDigest: taskVersion(node.task), - verification: { status: 'kernel_verified', results: [{ theoremName: node.task.theoremName, - proofPath: node.task.proofPath, statementHash: taskVersion(node.task), leanStatementHash: taskVersion(node.task) }] }, - } }); - expect(node.integratedCheck!.verification.results).toHaveLength(1); - } - expect(state.cooperation!.recheck).toMatchObject({ canonicalCommit: canonical, total: helpers().length, completed: helpers().length }); - expect(events.filter(item => item.event === 'task_recheck_batch_fallback')).toEqual([]); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - directory = temporaryDirectory('solver-projection-preparation-'); - workspace = path.join(directory, 'workspace'); - preparations = []; events = []; controller = new AbortController(); cooperative = undefined; - const original = proofApi.createTaskSourceProjector; - vi.spyOn(proofApi, 'createTaskSourceProjector').mockImplementation((problem, worktree, commit, options) => { - const project = original(problem, worktree, commit, options), targets: string[] = []; - const wrapped: Projector = (task, retainedGoals, conditions) => { - targets.push(task.id); - return project(task, retainedGoals, conditions); - }; - const complete = Object.assign(wrapped, { dependencyHints: project.dependencyHints, possibleContextGoals: project.possibleContextGoals }); - preparations.push({ commit, worktree, targets, project: complete }); - return complete; - }); - }); - afterEach(async () => { - controller.abort(); await cooperative?.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('reuses both projection modes across normal and compact checks without rebuilding either snapshot', () => { - const canonical = prepare(2), task = helpers()[0]!.task; - const project = (compact: boolean): Projector => (cooperative as any).sourceProjector(workspace, canonical, compact); - const normal = project(false), normalSources = normal(task, []); - expect(project(false)).toBe(normal); - const compact = project(true), compactSources = compact(task, []); - expect(compact).not.toBe(normal); - expect(project(true)).toBe(compact); - expect(project(false)).toBe(normal); - expect(project(false)(task, [])).toEqual(normalSources); - expect(project(true)(task, [])).toEqual(compactSources); - expect(proofApi.createTaskSourceProjector).toHaveBeenCalledTimes(2); - }); - - it.each(['commit', 'worktree', 'problem', 'preserved'] as const)( - 'refreshes each projection mode after its %s identity changes', changed => { - let canonical = prepare(1), checkout = workspace; - let preserved: { file: string; name: string }[] = []; - const project = (compact: boolean): Projector => (cooperative as any).sourceProjector(checkout, canonical, compact, preserved); - const initial = [project(false), project(true)]; - if (changed === 'commit') { - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('helper_0 : True := by trivial', - 'helper_0 : True := by exact True.intro')); - canonical = commitSolverSources(problem, workspace); - } else if (changed === 'worktree') checkout = `${workspace}/`; - else if (changed === 'problem') state.problem.receiptDigest += '-updated'; - else preserved = [{ file: 'Submission.lean', name: 'Tutorial.helper_0' }]; - - const refreshed = [project(false), project(true)]; - expect(refreshed[0]).not.toBe(initial[0]); - expect(refreshed[1]).not.toBe(initial[1]); - expect(project(false)).toBe(refreshed[0]); - expect(project(true)).toBe(refreshed[1]); - expect(proofApi.createTaskSourceProjector).toHaveBeenCalledTimes(4); - }); - - it.each([{ count: 64, oldGroupingCalls: 96 }, { count: 128, oldGroupingCalls: 320 }]) - ('reuses one prepared snapshot to group and validate $count helpers', async ({ count, oldGroupingCalls }) => { - const canonical = prepare(count); - - await recheck(); - - expectVerified(canonical); - // This spy observes the cooperation cache. The proof checker also constructs - // its own isolated projection through a module-local factory call. - expect(proofApi.createTaskSourceProjector).toHaveBeenCalledOnce(); - expect(preparations.map(item => [item.worktree, item.commit])).toEqual([[workspace, canonical]]); - const targetIds = helpers().map(node => node.task.id); - // One projection per target for grouping, and one for receipt validation. - // Batching must not repeatedly project every remaining grouping candidate. - expect(preparations[0]!.targets.toSorted()).toEqual([...targetIds, ...targetIds].toSorted()); - expect(preparations[0]!.targets.length - count).toBeLessThan(oldGroupingCalls); - expect(host.verify).toHaveBeenCalledTimes(count / 32); - const requests = host.verify.mock.calls.map(([request]) => request as MathematicsVerifierBatchRequest); - expect(requests.map(request => request.items.length)).toEqual(Array(count / 32).fill(32)); - expect(requests.flatMap(request => request.items.map(item => item.theoremName))).toEqual(helpers().map(node => node.task.theoremName)); - }); - - it('reuses host preparation for the same canonical commit and rebuilds it after proof bytes change', async () => { - const canonical = prepare(4), targetIds = helpers().map(node => node.task.id); - await recheck(); - expectVerified(canonical); - const firstHost = preparations[0]!; - await recheck(); - - expectVerified(canonical); - expect(preparations).toHaveLength(1); - expect(firstHost.targets.toSorted()).toEqual(Array(4).fill(targetIds).flat().toSorted()); - expect(host.verify).toHaveBeenCalledOnce(); - const firstTargets = [...firstHost.targets]; - - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('helper_0 : True := by trivial', 'helper_0 : True := by exact True.intro')); - const changed = commitSolverSources(problem, workspace); - state.cooperation!.canonicalCommit = changed; - await recheck(); - - expect(changed).not.toBe(canonical); - expectVerified(changed); - expect(preparations).toHaveLength(2); - expect(preparations[1]).toMatchObject({ worktree: workspace, commit: changed }); - expect(preparations[1]!.targets.toSorted()).toEqual([...targetIds, ...targetIds].toSorted()); - expect(firstHost.targets).toEqual(firstTargets); - expect(host.verify).toHaveBeenCalledTimes(2); - const request = host.verify.mock.calls[1]![0] as MathematicsVerifierBatchRequest; - expect(committedSource(workspace, request.targetCommit!, `${problem.projectRelative}/Submission.lean`)) - .toContain('helper_0 : True := by exact True.intro'); - }); -}); diff --git a/tests/solverProjectionReuse.test.ts b/tests/solverProjectionReuse.test.ts deleted file mode 100644 index 133491dd..00000000 --- a/tests/solverProjectionReuse.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_PROOF } from '../src/math/localExample'; -import type { MathematicsVerifierBatchRequest, MathematicsVerifierBatchResult } from '../src/math/verifier'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { checkTaskProof, TaskProofCache, trustedTaskProjectionReuse, type TaskProof } from '../src/solver/cooperativeProof'; -import { commitSolverSources, git, type SolverProblem } from '../src/solver/problem'; -import { taskVersion, type CooperativeTask, type TaskAssignment } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, solverState } from './helpers/solver'; -import { failedBatch, receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'projection-reuse-fixture-tools', -})); -vi.mock('../src/math/mathProofEnvironment', async importOriginal => ({ - ...await importOriginal(), resolveMathProofEnvironment: () => undefined, -})); - -describe('host validation of content-equivalent task projections', () => { - let directory: string, workspace: string, problem: SolverProblem, task: CooperativeTask, assignment: TaskAssignment; - let cooperative: CooperativeResearch, controller: AbortController, raw: TaskProof, sourceCommit: string; - let environment: NodeJS.ProcessEnv; - const check = (proof: TaskProof) => (cooperative as any).check(task, assignment, workspace, sourceCommit, [], proof) as Promise; - - beforeEach(async () => { - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest): Promise => { - const sessionId = 'original-projection-check'; - return { schema: 'deepscientist.mathematics.verification-batch/v1', status: 'kernel_verified', - targetCommit: request.targetCommit!, sessionId, events: [], startedAt: 1, checkedAt: 2, durationMs: 1, - results: request.items.map((item, index) => ({ ...item, sourceDeclarationHash: item.expectedSourceDeclarationHash, - status: 'kernel_verified', targetCommit: request.targetCommit!, claim: 'statement', - checkId: `check-${index + 1}`, receiptId: `original-receipt-${index}`, sessionId, checkedAt: 2, - declarationReferences: { statement: [], proof: [] } })) as MathematicsVerifierBatchResult['results'] }; - }); - const example = localExample('host-projection-reuse-'), receipt = example.receipt; - ({ directory, workspace, problem } = example); - const file = path.join(receipt.projectRoot, 'Submission.lean'); - fs.writeFileSync(file, LOCAL_EXAMPLE_PROOF); - const seedCommit = commitSolverSources(problem, workspace); - fs.writeFileSync(file, LOCAL_EXAMPLE_PROOF.replace('theorem add_zero', 'lemma helper : True := by trivial\ntheorem add_zero')); - const first = commitSolverSources(problem, workspace); - task = { id: 'helper', kind: 'lemma', objective: 'Prove the current helper.', proofPath: 'Submission.lean', - theoremName: 'Tutorial.helper', type: 'True', dependsOn: [], revision: 0 }; - assignment = { taskId: task.id, taskDigest: taskVersion(task), seedCommit, workerId: 'solver' }; - controller = new AbortController(); - const envFile = path.join(directory, 'math.env'); - fs.writeFileSync(envFile, ''); - environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - const cache = new TaskProofCache(); - await checkTaskProof(problem, workspace, first, task, assignment, [], environment, controller.signal, Infinity, [], 'environment', cache); - git(workspace, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--allow-empty', '--no-gpg-sign', '--quiet', '-m', 'Same content, new source commit']); - sourceCommit = git(workspace, ['rev-parse', 'HEAD']); - raw = await checkTaskProof(problem, workspace, sourceCommit, task, assignment, [], environment, controller.signal, Infinity, [], 'environment', cache); - expect(host.verify).toHaveBeenCalledOnce(); - expect(trustedTaskProjectionReuse(raw)).toBeDefined(); - const state = solverState(problem, workspace, { runId: 'projection-reuse-fixture', phase: 'running', - cooperation: { canonicalCommit: seedCommit, tasks: [{ task, assignment, status: 'delivered', proof: raw, attempts: 1 }] } }); - const worker = leadWorker(problem, workspace); - cooperative = cooperativeResearch({ state, workers: [worker], retrievalRoot: workspace, - access: new Map([[worker.id, { environment, retrievalRoot: workspace }]]), signal: controller.signal, exclusiveCheck: operation => operation() }); - }); - afterEach(() => { controller?.abort(); vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - - it('validates and pins both projections while keeping the checked receipt unchanged', async () => { - const receipt = structuredClone(raw.verification), reuse = trustedTaskProjectionReuse(raw)!; - const checked = await check(raw); - expect(checked.passed).toBe(true); - expect(checked.commit).toBe(sourceCommit); - expect(checked.verification).toEqual(receipt); - expect(checked.verification.targetCommit).toBe(reuse.checkedProjectionCommit); - expect(reuse.projectionCommit).not.toBe(reuse.checkedProjectionCommit); - expect(git(workspace, ['rev-parse', `${reuse.projectionCommit}^{tree}`])).toBe(reuse.projectionTree); - expect(git(workspace, ['rev-parse', `${reuse.checkedProjectionCommit}^{tree}`])).toBe(reuse.projectionTree); - expect((cooperative as any).pinned.has(reuse.projectionCommit)).toBe(true); - expect((cooperative as any).pinned.has(reuse.checkedProjectionCommit)).toBe(true); - expect(host.verify).toHaveBeenCalledOnce(); - }); - - it('rechecks each member independently after a restored integration batch fails', async () => { - const file = path.join(workspace, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', - 'lemma broken : True := by trivial\ntheorem add_zero')); - const canonical = commitSolverSources(problem, workspace); - const broken = { ...task, id: 'broken', theoremName: 'Tutorial.broken', objective: 'Check the broken helper' }; - const archive = (cooperative as any).archive; - archive.canonicalCommit = canonical; - archive.tasks = [task, broken].map(task => ({ task, status: 'integrated', attempts: 1, - integratedCheck: { ...raw, taskDigest: taskVersion(task) } })); - host.verify.mockReset().mockImplementation((request: MathematicsVerifierBatchRequest) => { - const receipts = receiptBatch(request, { sessionId: 'restored-check', receiptId: (_, name) => `restore-${name}` }); - return request.items.length > 1 || request.items.some(item => item.theoremName === broken.theoremName) - ? failedBatch(receipts, { stdoutPreview: file => `${file}:4:1: error: unsolved goals` }) : receipts; - }); - await (cooperative as any).recheckIntegrated(canonical); - expect(host.verify.mock.calls[0][0].items).toHaveLength(2); - expect(host.verify.mock.calls.slice(1).every(([request]) => request.items.length === 1)).toBe(true); - expect(archive.tasks.map(node => [node.task.id, node.status])).toEqual([['helper', 'integrated'], ['broken', 'blocked']]); - }); - - it.each(['recover', 'still-fails', 'no-fresh-goal', 'goal-already-checked'] as const) - ('bounds restored recheck context recovery: %s', async mode => { - const archive = (cooperative as any).archive; - archive.canonicalCommit = sourceCommit; - const goal: CooperativeTask = { id: 'original-goal', kind: 'goal', objective: 'Check the original.', - proofPath: problem.targets[0]!.proofPath, theoremName: problem.targets[0]!.theoremName, - dependsOn: ['no-fresh-goal', 'goal-already-checked'].includes(mode) ? [] : [task.id], revision: 0 }; - // Persisted receipts deliberately do not enter checkedDeliveries in this process. - archive.tasks = [task, ...(mode === 'no-fresh-goal' ? [] : [goal])].map(task => ({ task, - status: 'integrated', attempts: 1, integratedCheck: { ...raw, taskDigest: taskVersion(task) } })); - if (mode === 'goal-already-checked') archive.tasks.reverse(); - const expectedStatus = ['recover', 'goal-already-checked'].includes(mode) ? 'integrated' : 'blocked'; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - const helperContexts: boolean[] = []; - host.verify.mockReset().mockImplementation((request: MathematicsVerifierBatchRequest) => { - const receipts = receiptBatch(request, { sessionId: 'context-recheck', - receiptId: (_, name) => 'context-' + request.targetCommit + '-' + name }); - // Missing reference coverage preserves the explicit dependency contract. - for (const result of receipts.results) if (result.theoremName === goal.theoremName) - delete result.declarationReferences; - if (!request.items.some(item => item.theoremName === task.theoremName)) return receipts; - const source = fs.readFileSync(path.join(request.projectRoot, 'Submission.lean'), 'utf8'); - const retained = source.includes('theorem add_zero'); helperContexts.push(retained); - return ['recover', 'goal-already-checked'].includes(mode) && retained ? receipts : failedBatch(receipts, - { stdoutPreview: file => file + ':4:1: error: unknown identifier from omitted original context' }); - }); - await (cooperative as any).recheckIntegrated(sourceCommit); - expect(archive.tasks.find((node: any) => node.task.id === task.id).status).toBe(expectedStatus); - if (mode !== 'no-fresh-goal') expect(archive.tasks.find((node: any) => node.task.id === goal.id).status).toBe(expectedStatus); - const retries = emit.mock.calls.filter(([event]) => event === 'task_recheck_context_retry'); - expect(retries).toHaveLength(mode === 'no-fresh-goal' ? 0 : 1); - expect(helperContexts).toContain(false); - if (mode !== 'no-fresh-goal') expect(helperContexts).toContain(true); - expect(archive.recheck.completed).toBe(archive.tasks.length); - expect(archive.recheck.completed).toBeLessThanOrEqual(archive.recheck.total); - }); - - it.each(['clone', 'json', 'changed-map', 'removed-map', 'changed-reference'] as const) - ('rejects %s evidence before adding host annotations', async kind => { - if (kind === 'clone') raw = structuredClone(raw); - else if (kind === 'json') raw = JSON.parse(JSON.stringify(raw)); - else if (kind === 'changed-map') raw.projectionReuse = { ...raw.projectionReuse!, inputDigest: 'f'.repeat(64) }; - else if (kind === 'removed-map') delete raw.projectionReuse; - else raw.references!.sourceCommit = 'e'.repeat(40); - expect(trustedTaskProjectionReuse(raw)).toBeUndefined(); - await expect(check(raw)).rejects.toThrow('math_task_check_identity_changed'); - expect((cooperative as any).checkedDeliveries.has(raw)).toBe(false); - expect(host.verify).toHaveBeenCalledOnce(); - }); -}); diff --git a/tests/solverProofImport.test.ts b/tests/solverProofImport.test.ts deleted file mode 100644 index 75607ef1..00000000 --- a/tests/solverProofImport.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { applyTaskChanges } from '../src/solver/cooperativeProof'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { committedSource, git } from '../src/solver/problem'; -import { importAssignedProof, proofFragmentChanges, queueProofImport, syncProofImports } from '../src/solver/proofImport'; -import type { ProofImportRequest } from '../src/solver/proofImportRecord'; -import { runResearchWorkers } from '../src/solver/research'; -import { parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { WorkerProofLifecycle } from '../src/solver/workerProofLifecycle'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn() })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); -vi.mock('../src/math/verifier', async original => ({ ...await original(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => undefined, - resolveMathematicsLakePackagesCache: () => undefined, -})); -type TaskAction = Extract; - -describe('deterministic host proof imports', () => { - const fixtures: ReturnType[] = []; - const batch = (request: Parameters[0]) => receiptBatch(request, { - sessionId: 'proof-import-fixture', receiptId: (_, name) => `import-${request.targetCommit}-${name}` }); - beforeEach(() => { host.verify.mockReset().mockImplementation(async request => batch(request)); }); - afterEach(async () => { - for (const current of fixtures.splice(0)) { - current.controller.abort(); await Promise.allSettled(current.instances.map(value => value.stop())); - fs.rmSync(current.directory, { recursive: true, force: true }); - } - vi.restoreAllMocks(); - }); - - function fixture() { - const example = localExample('solver-proof-import-', 'lead'); - const { directory, problem, workspace } = example, writer = peerWorker(example, 'writer', { role: 'engineer' }); - const workers = [leadWorker(problem, workspace, 'lead'), writer]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', ...target, - objective: 'Original target', status: 'paused' })), - { id: 'helper', kind: 'lemma', type: 'True', theoremName: 'Tutorial.helper', - proofPath: 'Submission.lean', objective: 'Prove the helper', ownerId: 'writer' }, - ] }); - let state = solverState(problem, workspace, { runId: 'proof-import', phase: 'prepared', failures: [], - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const stateFile = path.join(directory, 'state.json'), fragmentFile = path.join(directory, 'external.lean'); - fs.writeFileSync(fragmentFile, 'lemma helper : True := by trivial\n'); - const controller = new AbortController(), instances: CooperativeResearch[] = []; - const events: { event: string; details?: Record }[] = []; - const emit = (event: string, details?: Record) => events.push({ event, details }); - const save = () => writeSolverRunState(stateFile, state); - const create = () => { - const value = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, save, emit }); - instances.push(value); return value; - }; - let cooperation = create(); state.cooperation!.planVersion = (cooperation as any).planVersion(); save(); - const sourceFile = path.join(writer.worktree, problem.projectRelative, 'Submission.lean'); - const original = fs.readFileSync(sourceFile, 'utf8'); - const queue = (input: Partial[1]> = {}, dryRun = false) => queueProofImport(stateFile, { - taskId: 'helper', fragmentFile, sha256: mathDigest(fs.readFileSync(fragmentFile)), - baseVersion: state.cooperation!.planVersion!, ...input }, dryRun); - const assign = async () => { - const action = await cooperation.next(writer, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_missing_assignment'); - return action; - }; - const close = vi.fn(async () => {}); - const lifecycle = () => new WorkerProofLifecycle({ state, research: state.workers![1], worker: writer, - cooperation, close, save, emit, checked: () => {} }); - const consume = (action: TaskAction, value: Pick = lifecycle()) => importAssignedProof({ - state, directory, worker: writer, action, cooperation, lifecycle: value, close, save, emit }); - const reload = () => { state = readSolverRunState(stateFile); cooperation = create(); }; - const current = { ...example, workers, writer, stateFile, fragmentFile, sourceFile, original, - controller, instances, events, save, queue, assign, close, lifecycle, consume, reload, - get state() { return state; }, get cooperation() { return cooperation; } }; - fixtures.push(current); return current; - } - - it('rejects a wrong hash and stale CAS without changing the checkpoint or creating an intake log', async () => { - const f = fixture(), before = fs.readFileSync(f.stateFile); - await expect(f.queue({ sha256: '0'.repeat(64) })).rejects.toThrow('math_proof_import_hash_mismatch'); - await expect(f.queue({ baseVersion: 'stale' })).rejects.toThrow('math_proof_import_version_conflict'); - expect(fs.readFileSync(f.stateFile)).toEqual(before); - expect(fs.existsSync(path.join(f.directory, 'proof-imports.jsonl'))).toBe(false); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('captures immutable bytes, provides idempotence, and rejects a conflicting id or second pending import', async () => { - const f = fixture(), before = fs.readFileSync(f.stateFile); - expect(await f.queue({ id: 'one' }, true)).toMatchObject({ status: 'validated' }); - expect(await f.queue({ id: 'one' })).toMatchObject({ status: 'queued' }); - expect(await f.queue({ id: 'one' })).toMatchObject({ status: 'already_queued' }); - await expect(f.queue({ id: 'two' })).rejects.toThrow('math_proof_import_task_queued'); - fs.writeFileSync(f.fragmentFile, 'lemma helper : True := by exact True.intro\n'); - await expect(f.queue({ id: 'one' })).rejects.toThrow('math_proof_import_id_conflict'); - expect(fs.readFileSync(f.stateFile)).toEqual(before); - const request = JSON.parse(fs.readFileSync(path.join(f.directory, 'proof-imports.jsonl'), 'utf8')); - expect(request.fragment).toBe('lemma helper : True := by trivial\n'); - expect(request.fragmentSha256).toBe(mathDigest(request.fragment)); - await f.assign(); f.save(); - await expect(f.queue({ id: 'busy' })).rejects.toThrow('math_proof_import_task_busy'); - }); - - it('exposes a working standalone import-proof CLI', () => { - const f = fixture(), bun = process.env.BUN_EXEC_PATH ?? 'bun'; - const result = spawnSync(bun, ['bin/math.ts', 'import-proof', '--run', f.stateFile, '--task', 'helper', - '--fragment', f.fragmentFile, '--sha256', mathDigest(fs.readFileSync(f.fragmentFile)), - '--base-version', f.state.cooperation!.planVersion!], { encoding: 'utf8', timeout: 10_000 }); - expect(result.status, result.stderr).toBe(0); expect(JSON.parse(result.stdout)).toMatchObject({ status: 'queued', taskId: 'helper' }); - expect(f.state.cooperation!.proofImports).toBeUndefined(); - }); - - it('appends multiple lemmas through the existing source merger without changing original declarations', () => { - const f = fixture(), fragment = 'lemma first : True := by trivial\n\nlemma helper : True := by exact first\n'; - const prepared = proofFragmentChanges(f.original, { fragment, proofPath: 'Submission.lean', theoremName: 'Tutorial.helper' }); - applyTaskChanges(f.problem, f.writer.worktree, prepared.changes); - const source = fs.readFileSync(f.sourceFile, 'utf8'); - expect(source).toBe(prepared.source); expect(source.replace(/lemma first[\s\S]*?(?=end Tutorial)/u, '')).toBe(f.original); - expect(proofFragmentChanges(source, { fragment, proofPath: 'Submission.lean', theoremName: 'Tutorial.helper' }).changes).toEqual([]); - expect(() => proofFragmentChanges(source, { fragment: 'lemma helper : True := by exact True.intro\n', - proofPath: 'Submission.lean', theoremName: 'Tutorial.helper' })).toThrow('math_proof_import_declaration_conflict'); - }); - - it('places a helper before its earlier consumer and preserves the consumer doc comment', () => { - const f = fixture(); - const source = f.original.replace('theorem add_zero', '/-- The original consumer. -/\ntheorem add_zero'); - const prepared = proofFragmentChanges(source, { fragment: 'lemma helper : True := by trivial\n', - proofPath: 'Submission.lean', theoremName: 'Tutorial.helper', beforeTheorem: 'Tutorial.add_zero' }); - expect(prepared.source).toContain('lemma helper : True := by trivial\n/-- The original consumer. -/\ntheorem add_zero'); - expect(prepared.source.indexOf('lemma helper')).toBeLessThan(prepared.source.indexOf('theorem add_zero')); - fs.writeFileSync(f.sourceFile, source); - applyTaskChanges(f.problem, f.writer.worktree, prepared.changes); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(prepared.source); - expect(prepared.source.replace('lemma helper : True := by trivial\n', '')).toBe(source); - }); - - it('rejects a missing or differently scoped insertion anchor before creating an import log', async () => { - const f = fixture(); - await expect(f.queue({ beforeTheorem: 'Tutorial.absent' })).rejects.toThrow('math_proof_import_invalid_anchor'); - expect(fs.existsSync(path.join(f.directory, 'proof-imports.jsonl'))).toBe(false); - const source = 'namespace Tutorial\nnamespace Nested\ntheorem consumer : True := by trivial\nend Nested\nend Tutorial\n'; - expect(() => proofFragmentChanges(source, { fragment: 'lemma helper : True := by trivial\n', - proofPath: 'Submission.lean', theoremName: 'Tutorial.helper', beforeTheorem: 'Tutorial.Nested.consumer' })) - .toThrow('math_proof_import_invalid_anchor'); - }); - - it.each([ - 'import Mathlib\nlemma helper : True := by trivial\n', - 'namespace Tutorial\nlemma helper : True := by trivial\nend Tutorial\n', - 'set_option maxRecDepth 0\nlemma helper : True := by trivial\n', - '@[simp] lemma helper : True := by trivial\n', - 'def helper : True := by trivial\n', - 'lemma helper : True := by sorry\n', - 'axiom helper : True\n', - ])('rejects source commands and incomplete declarations: %s', fragment => { - const f = fixture(); - expect(() => proofFragmentChanges(f.original, { fragment, proofPath: 'Submission.lean', theoremName: 'Tutorial.helper' })).toThrow(/math_proof_import_/u); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(f.original); - }); - - it.each([undefined, 'Tutorial.add_zero'])('checks and merges captured bytes without model turns (anchor: %s)', async beforeTheorem => { - const f = fixture(); await f.queue({ beforeTheorem }); fs.rmSync(f.fragmentFile); const action = await f.assign(); - expect(await f.consume(action)).toBe(true); - const record = f.state.cooperation!.proofImports![0], node = f.state.cooperation!.tasks.find(node => node.task.id === 'helper')!; - expect(record).toMatchObject({ status: 'checked', snapshotCommit: expect.any(String), readyId: expect.any(String) }); - expect(node).toMatchObject({ status: 'integrated', attempts: 0, proof: { passed: true }, integratedCheck: { passed: true } }); - expect(f.state.cooperation!.proofReadyRecords![0]).toMatchObject({ status: 'checked', receiptIds: [expect.any(String)] }); - expect(host.verify.mock.calls.length).toBeGreaterThanOrEqual(2); - const source = committedSource(f.workspace, f.state.cooperation!.canonicalCommit!, `${f.problem.projectRelative}/Submission.lean`); - expect(source).toContain('lemma helper'); - if (beforeTheorem) expect(source.indexOf('lemma helper')).toBeLessThan(source.indexOf('theorem add_zero')); - expect(f.state.check).toBeUndefined(); expect(f.state.cooperation!.tasks[0].integratedCheck).toBeUndefined(); - expect(f.state.turns).toBe(0); expect(f.state.workers!.every(worker => worker.turns === 0)).toBe(true); - }); - - it('supersedes a frozen import if its task changes during the independent check', async () => { - const f = fixture(); await f.queue(); const action = await f.assign(); - const checking = deferred(), release = deferred(); - host.verify.mockImplementation(async request => { checking.resolve(); await release.promise; return batch(request); }); - const pending = f.consume(action); await checking.promise; - await (f.cooperation as any).acceptPlan(parseCooperationPlan(f.problem, { tasks: f.state.cooperation!.tasks.map(({ task }) => - task.id === 'helper' ? { ...task, type: 'False' } : task) })); - release.resolve(); expect(await pending).toBe(true); - expect(f.state.cooperation!.proofImports![0].status).toBe('superseded'); - expect(f.state.cooperation!.canonicalCommit).toBe(f.problem.baseCommit); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'helper')!.integratedCheck).toBeUndefined(); - }); - - it('restores a frozen snapshot after restart, links interrupted progress, and ignores later mutable files', async () => { - const f = fixture(); await f.queue(); let action = await f.assign(); - await f.consume(action, { resumeFrozen: async () => false }); - const snapshot = f.state.cooperation!.proofImports![0].snapshotCommit!; - delete f.state.cooperation!.proofImports![0].readyId; f.state.cooperation!.proofImports![0].status = 'received'; f.save(); - f.reload(); await f.cooperation.restore(); action = await f.assign(); - fs.writeFileSync(f.fragmentFile, 'lemma helper : False := by sorry\n'); fs.appendFileSync(f.sourceFile, '\n-- later live edit\n'); - expect(await f.lifecycle().resumeFrozen(action)).toBe(true); syncProofImports(f.state); f.save(); - expect(f.state.cooperation!.proofImports![0]).toMatchObject({ status: 'checked', snapshotCommit: snapshot, readyId: expect.any(String) }); - expect(committedSource(f.writer.worktree, snapshot, `${f.problem.projectRelative}/Submission.lean`)).not.toContain('later live edit'); - expect(f.state.turns).toBe(0); - }); - - it('resumes an exactly prepared source after interruption before the commit checkpoint', async () => { - const f = fixture(); await f.queue(); const action = await f.assign(); - const request = JSON.parse(fs.readFileSync(path.join(f.directory, 'proof-imports.jsonl'), 'utf8')) as ProofImportRequest; - const prepared = proofFragmentChanges(f.original, request); fs.writeFileSync(f.sourceFile, prepared.source); - f.state.cooperation!.proofImports = [{ id: request.id, requestDigest: mathDigest(canonicalMathJson(request)), - taskId: request.taskId, taskDigest: request.taskDigest, fragmentSha256: request.fragmentSha256, status: 'received', receivedAt: 1 }]; - f.save(); expect(await f.consume(action)).toBe(true); - expect(f.state.cooperation!.proofImports[0].status).toBe('checked'); - expect(fs.readFileSync(f.sourceFile, 'utf8').match(/lemma helper/gu)).toHaveLength(1); - }); - - it('records an independently failed proof without canonical adoption or original-goal acceptance', async () => { - const f = fixture(); await f.queue(); const action = await f.assign(); - host.verify.mockImplementation(async request => failedBatch(batch(request), { - stdoutPreview: () => 'Submission.lean:1:1: error: unsolved goals', goalsRemaining: 1 })); - expect(await f.consume(action)).toBe(true); - expect(f.state.cooperation!.proofImports![0].status).toBe('failed'); - expect(f.state.cooperation!.canonicalCommit).toBe(f.problem.baseCommit); expect(f.state.check).toBeUndefined(); - expect(f.state.cooperation!.tasks[0].integratedCheck).toBeUndefined(); - }); - - it('imports through the real runner before M1 opens and without charging model attempts', async () => { - const f = fixture(); await f.queue(); - const selected = deferred(), open = vi.fn(() => { throw new Error('model_must_not_open'); }); - const next = CooperativeResearch.prototype.next; - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function (this: CooperativeResearch, worker, budget) { - if (worker.role === 'lead') { await selected.promise; return undefined; } - return next.call(this, worker, budget); - }); - const modules: SolverModules = { ...directSolverModules, M1: { ...directSolverModules.M1, open } }; - const completion = runResearchWorkers({ state: f.state, workers: f.workers, access: workerAccess(f.workers, f.directory), - modules, root: f.directory, buildFile: path.join(f.directory, 'build.json'), taskText: 'Offline import', - executable: 'unused', profile: 'unused', signal: f.controller.signal, deadline: Infinity, maxTurns: Infinity, - maxTurnMs: Infinity, maxTotalTokens: 0, save: f.save, emit: (event, details) => { - f.events.push({ event, details }); if (event === 'proof_import_completed') { selected.resolve(); f.controller.abort(); } - } }); - await expect(completion).rejects.toThrow(); - expect(open).not.toHaveBeenCalled(); expect(f.state.turns).toBe(0); - expect(f.state.cooperation!.proofImports![0].status).toBe('checked'); - expect(f.state.cooperation!.tasks.find(node => node.task.id === 'helper')!.attempts).toBe(0); - expect(git(f.writer.worktree, ['rev-parse', 'HEAD'])).toBe(f.state.cooperation!.proofImports![0].snapshotCommit); - }); -}); diff --git a/tests/solverProofReady.test.ts b/tests/solverProofReady.test.ts deleted file mode 100644 index 0a16cfdf..00000000 --- a/tests/solverProofReady.test.ts +++ /dev/null @@ -1,372 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { committedSource, commitSolverSources, git } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import { assignmentDeliveryFile, parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn() })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => undefined, - resolveMathematicsLakePackagesCache: () => undefined, -})); - -type TaskAction = Extract; -type StopReceipt = Awaited>>; - -describe('runner proof readiness freeze barrier', () => { - const fixtures: ReturnType[] = []; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => receiptBatch(request, { - sessionId: 'proof-ready-runner-fixture', receiptId: (_, name) => 'ready-receipt-' + request.targetCommit + '-' + name, - })); - }); - afterEach(async () => { - for (const current of fixtures.splice(0)) { - current.controller.abort(); current.stopResult.resolve({ status: 'stopped' }); - current.turns.forEach(turn => turn.done.resolve('interrupted')); - await Promise.allSettled([current.completion]); - fs.rmSync(current.directory, { recursive: true, force: true }); - } - vi.useRealTimers(); vi.restoreAllMocks(); - }); - - function fixture(options: { stop?: 'missing' | 'unconfirmed' | 'throw'; closeRejects?: boolean } = {}) { - const example = localExample('solver-proof-ready-runner-', 'lead'); - const { directory, workspace, problem } = example; - const writer = peerWorker(example, 'writer', { role: 'engineer' }); - const workers = [leadWorker(problem, workspace, 'lead'), writer]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: 'goal_' + index, kind: 'goal', ...target, objective: 'Prove ' + target.theoremName, - status: index === 0 ? 'active' : 'paused', ownerId: 'writer', - })) }); - const state = solverState(problem, workspace, { runId: 'proof-ready-runner', phase: 'prepared', failures: [], - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) }, - }); - let cooperation!: CooperativeResearch; - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(function (this: CooperativeResearch) { cooperation = this; }); - const controller = new AbortController(), started = deferred(), stopping = deferred(); - const stopResult = deferred(); - const turns: { action: CooperativeAction; done: ReturnType> }[] = []; - const events: { event: string; details?: Record }[] = []; - const eventWaiters = new Map>(); - const interrupt = vi.fn(async () => {}); - const notify = vi.fn(async (_message: string) => {}); - const closed = vi.fn(); - const save = vi.fn(); - const stopForFreeze = vi.fn(async () => { - stopping.resolve(); - if (options.stop === 'throw') throw new Error('fixture_shutdown_failed'); - return options.stop === 'unconfirmed' ? { status: 'unconfirmed' as const, reason: 'process-group-active' as const } : stopResult.promise; - }); - const open = vi.fn(async (access: MathAgentOptions): Promise => { - if (access.environment.DEEPSCIENTIST_MATH_WORKER_ID !== writer.id) throw new Error('fixture_unexpected_lead_dispatch'); - let active: ReturnType> | undefined; - return { threadId: access.threadId ?? 'proof-ready-thread', interrupt, notify, - close: async () => { closed(); active?.resolve('interrupted'); if (options.closeRejects) throw new Error('fixture_close_failed'); }, - ...(options.stop === 'missing' ? {} : { stopForFreeze }), - run: async (message, _id, _workspace, onStarted) => { - const action = JSON.parse(message) as CooperativeAction; - active = deferred(); turns.push({ action, done: active }); - onStarted('ready-turn-' + turns.length); started.resolve(); return active.promise; - }, - }; - }); - const modules: SolverModules = { ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Offline proof readiness runner fixture.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }) }, - }; - const completion = runResearchWorkers({ state, workers, access: workerAccess(workers, directory), modules, root: directory, - buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original goals.', executable: 'offline-fixture', - profile: 'offline-fixture', signal: controller.signal, deadline: Infinity, maxTurns: Infinity, maxTurnMs: Infinity, - maxTotalTokens: 0, save, emit: (event, details) => { - events.push({ event, details }); eventWaiters.get(event)?.resolve(); - }, - }); - void completion.catch(() => {}); - const wait = async (promise: Promise) => Promise.race([promise, completion.then(() => { - throw new Error('fixture_runner_finished_before_expected_checkpoint'); - })]); - const waitEvent = (event: string) => { - if (events.some(item => item.event === event)) return Promise.resolve(); - const pending = eventWaiters.get(event) ?? deferred(); eventWaiters.set(event, pending); return wait(pending.promise); - }; - const action = () => { - const value = turns[0]?.action; if (value?.kind !== 'task') throw new Error('fixture_missing_proof_task'); return value; - }; - const sourceFile = path.join(writer.worktree, problem.projectRelative, 'Submission.lean'); - const writeProof = () => fs.writeFileSync(sourceFile, fs.readFileSync(sourceFile, 'utf8').replace('by sorry', 'by rfl')); - const appendReady = () => fs.appendFileSync(path.join(writer.worktree, assignmentDeliveryFile(action().assignment)), - JSON.stringify({ kind: 'ready', id: 'ready-runner-submission' }) + '\n'); - const current = { directory, problem, state, workers, modules, writer, controller, stopResult, turns, events, interrupt, notify, stopForFreeze, - open, closed, save, completion, action, writeProof, appendReady, waitEvent, wait, started, stopping, - pulse: () => cooperation.pulse(writer.id), head: () => git(writer.worktree, ['rev-parse', 'HEAD']), - }; - fixtures.push(current); return current; - } - - it('waits for settled turn and confirmed process stop before freezing one checked snapshot', async () => { - const current = fixture(); await current.wait(current.started.promise); - const before = current.head(); current.writeProof(); current.appendReady(); await current.pulse(); - expect(current.interrupt).toHaveBeenCalledOnce(); - expect(current.stopForFreeze).not.toHaveBeenCalled(); - expect(current.head()).toBe(before); expect(host.verify).not.toHaveBeenCalled(); - expect(current.state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'awaiting-freeze' }]); - - current.turns[0].done.resolve('interrupted'); await current.wait(current.stopping.promise); - expect(current.head()).toBe(before); expect(host.verify).not.toHaveBeenCalled(); - expect(current.state.cooperation!.proofReadyRecords![0].snapshotCommit).toBeUndefined(); - current.stopResult.resolve({ status: 'stopped' }); await current.waitEvent('proof_ready_checked'); - - const ready = current.state.cooperation!.proofReadyRecords![0]; - expect(ready).toMatchObject({ status: 'checked', evidence: 'unconditional', conditions: [], receiptIds: [expect.any(String)] }); - expect(ready.snapshotCommit).not.toBe(before); expect(ready.snapshotCommit).toBe(current.head()); - expect(host.verify).toHaveBeenCalled(); - const request = host.verify.mock.calls[0][0]; - // M2 verifies an isolated declaration projection while retaining its frozen source commit. - expect(current.state.cooperation!.tasks[0].proof?.commit).toBe(ready.snapshotCommit); - expect(committedSource(current.writer.worktree, request.targetCommit, current.problem.projectRelative + '/Submission.lean')) - .toContain('by rfl'); - expect(current.state.cooperation!.tasks[0].proof?.passed).toBe(true); - const taskIdentity = { taskId: ready.taskId, taskDigest: ready.taskDigest, workerId: ready.workerId, - assignmentKey: ready.assignmentKey, seedCommit: ready.seedCommit }; - expect(current.events.find(item => item.event === 'task_assigned')?.details).toMatchObject(taskIdentity); - expect(current.events.find(item => item.event === 'turn_started')?.details).toMatchObject({ - ...taskIdentity, turnId: 'ready-turn-1', threadId: 'proof-ready-thread' }); - expect(current.events.filter(item => item.event === 'proof_ready_frozen')).toMatchObject([{ details: { - ...taskIdentity, readyId: ready.id, commit: ready.snapshotCommit, sourceDigest: ready.sourceDigest, frozenAt: ready.frozenAt, - } }]); - const receiptIds = current.state.cooperation!.tasks[0].proof!.verification.results.map(result => result.receiptId); - expect(current.events.find(item => item.event === 'proof_ready_checked')?.details).toMatchObject({ - ...taskIdentity, receiptId: ready.id, readyId: ready.id, receiptIds, - commit: ready.snapshotCommit, sourceDigest: ready.sourceDigest }); - expect(current.state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - expect(current.open.mock.calls.every(([access]) => access.turnTimeoutMs === undefined)).toBe(true); - }); - - it('clears and persists the previous check when a ready snapshot changes the frozen declaration', async () => { - const current = fixture(); await current.wait(current.started.promise); - current.writeProof(); current.appendReady(); await current.pulse(); - current.turns[0].done.resolve('interrupted'); await current.wait(current.stopping.promise); - const research = current.state.workers![1]; - research.check = { passed: true, commit: 'old-commit', sourceDigest: 'old-source' } as NonNullable; - const file = path.join(current.writer.worktree, current.problem.projectRelative, 'Submission.lean'); - const name = current.problem.targets[0].theoremName.split('.').at(-1)!; - const source = fs.readFileSync(file, 'utf8'), renamed = source.replace(name, name + '_changed'); - expect(renamed).not.toBe(source); fs.writeFileSync(file, renamed); - const savedBefore = current.save.mock.calls.length; - current.stopResult.resolve({ status: 'stopped' }); await current.waitEvent('source_rejected'); - expect(research.check).toBeUndefined(); - expect(current.save.mock.calls.length).toBeGreaterThan(savedBefore); - expect(current.state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'failed', - reason: expect.stringContaining('math_original_declaration_changed') }]); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('hands a completed declaration to the existing ready flow during a pending context checkpoint', async () => { - const current = fixture(); await current.wait(current.started.promise); - current.writeProof(); - fs.writeFileSync(path.join(current.writer.worktree, 'RESEARCH.md'), 'DONE locally; independent host checking is still required.\n'); - current.state.workers![1].lastInputTokens = 100_000; - current.open.mock.calls[0][0].onActivity!({ event: 'reasoning' }); - const request = current.state.workers![1].contextCheckpoint!; - expect(request.requestId).toBeDefined(); - const instruction = current.notify.mock.calls.map(([message]) => message).find(message => message.includes(request.requestId!))!; - const ready = instruction.match(/Append one complete JSON line to ("(?:\\.|[^"])*"): (\{"kind":"ready".*?\})\./iu); - expect(ready).not.toBeNull(); - expect(instruction).toContain('Use ready instead of checkpoint'); - expect(instruction).toContain('including their existing sorry bodies'); - await current.pulse(); - expect(current.state.cooperation!.proofReadyRecords ?? []).toEqual([]); - expect(host.verify).not.toHaveBeenCalled(); - expect(current.interrupt).not.toHaveBeenCalled(); - - const log = JSON.parse(ready![1]) as string; - expect(log).toBe(path.join(current.writer.worktree, assignmentDeliveryFile(current.action().assignment))); - fs.appendFileSync(log, JSON.stringify(JSON.parse(ready![2])) + '\n'); await current.pulse(); - expect(current.interrupt).toHaveBeenCalledOnce(); - expect(host.verify).not.toHaveBeenCalled(); - current.turns[0].done.resolve('interrupted'); await current.wait(current.stopping.promise); - expect(host.verify).not.toHaveBeenCalled(); - current.stopResult.resolve({ status: 'stopped' }); await current.waitEvent('proof_ready_checked'); - - const receipt = current.state.cooperation!.proofReadyRecords![0]; - expect(receipt).toMatchObject({ status: 'checked', evidence: 'unconditional' }); - expect(current.state.cooperation!.tasks[0].integratedCheck?.passed).toBe(true); - expect(committedSource(current.writer.worktree, receipt.snapshotCommit!, current.problem.projectRelative + '/Submission.lean')) - .toContain('theorem zero_add (n : Nat) : 0 + n = n := by sorry'); - expect(host.verify.mock.calls[0][0].items).toEqual([expect.objectContaining({ theoremName: current.action().task.theoremName })]); - expect(current.events.some(item => item.event === 'context_checkpoint_saved')).toBe(false); - expect(current.state.check).toBeUndefined(); - }); - - it.each(['missing', 'unconfirmed', 'throw'] as const)('quarantines the writer without freezing, checking or reopening when process stop is %s', async stop => { - const current = fixture({ stop }); await current.wait(current.started.promise); - const before = current.head(); current.writeProof(); current.appendReady(); await current.pulse(); - current.turns[0].done.resolve('interrupted'); await current.waitEvent('proof_ready_freeze_deferred'); - expect(current.head()).toBe(before); expect(host.verify).not.toHaveBeenCalled(); - expect(current.state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'failed', - reason: expect.stringContaining(stop === 'missing' ? 'writer-stop-confirmation-unavailable' : - stop === 'unconfirmed' ? 'process-group-active' : 'shutdown-failed') }]); - expect(current.state.cooperation!.proofReadyRecords![0].snapshotCommit).toBeUndefined(); - await expect(current.completion).rejects.toThrow('math_writer_stop_unconfirmed'); - expect(current.open).toHaveBeenCalledOnce(); expect(current.turns).toHaveLength(1); - expect(current.state.workers!.find(worker => worker.id === current.writer.id)?.writerStopUnconfirmed) - .toMatchObject({ reason: expect.any(String) }); - const archive = path.join(current.directory, 'quarantined-state.json'); - writeSolverRunState(archive, current.state); - const restored = readSolverRunState(archive); - const reopened = vi.fn(async () => { throw new Error('fixture_must_not_reopen_quarantined_writer'); }); - await expect(runResearchWorkers({ state: restored, workers: current.workers, - access: workerAccess(current.workers, current.directory), - modules: { ...current.modules, M1: { ...current.modules.M1, open: reopened } }, root: current.directory, - buildFile: path.join(current.directory, 'build.json'), taskText: 'Prove the original goals.', executable: 'offline-fixture', - profile: 'offline-fixture', signal: new AbortController().signal, deadline: Infinity, maxTurns: Infinity, maxTurnMs: Infinity, - maxTotalTokens: 0, save: () => {}, emit: () => {}, - })).rejects.toThrow('math_writer_stop_unconfirmed'); - expect(reopened).not.toHaveBeenCalled(); - }); - - it('quarantines before a failing close when writer stop is unconfirmed', async () => { - const current = fixture({ stop: 'unconfirmed', closeRejects: true }); await current.wait(current.started.promise); - const before = current.head(); current.writeProof(); current.appendReady(); await current.pulse(); - current.turns[0].done.resolve('interrupted'); await current.waitEvent('proof_ready_freeze_deferred'); - expect(current.head()).toBe(before); - expect(current.state.workers!.find(worker => worker.id === current.writer.id)?.writerStopUnconfirmed) - .toMatchObject({ reason: 'process-group-active' }); - await expect(current.completion).rejects.toThrow('math_writer_stop_unconfirmed'); - expect(host.verify).not.toHaveBeenCalled(); - expect(current.state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'failed' }]); - const archive = path.join(current.directory, 'failed-close-state.json'); - writeSolverRunState(archive, current.state); - const reopened = vi.fn(async () => { throw new Error('fixture_must_not_reopen_quarantined_writer'); }); - await expect(runResearchWorkers({ state: readSolverRunState(archive), workers: current.workers, - access: workerAccess(current.workers, current.directory), - modules: { ...current.modules, M1: { ...current.modules.M1, open: reopened } }, root: current.directory, - buildFile: path.join(current.directory, 'build.json'), taskText: 'Prove the original goals.', executable: 'offline-fixture', - profile: 'offline-fixture', signal: new AbortController().signal, deadline: Infinity, maxTurns: Infinity, maxTurnMs: Infinity, - maxTotalTokens: 0, save: () => {}, emit: () => {}, - })).rejects.toThrow('math_writer_stop_unconfirmed'); - expect(reopened).not.toHaveBeenCalled(); - }); - - it('closes an acknowledged ready turn that never settles and still waits for a confirmed process stop', async () => { - vi.useFakeTimers(); - const current = fixture(); await current.wait(current.started.promise); - const before = current.head(); current.writeProof(); current.appendReady(); await current.pulse(); - expect(current.interrupt).toHaveBeenCalledOnce(); - await vi.advanceTimersByTimeAsync(9_999); - expect(current.closed).not.toHaveBeenCalled(); expect(current.stopForFreeze).not.toHaveBeenCalled(); - expect(current.head()).toBe(before); expect(host.verify).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(1); await current.wait(current.stopping.promise); - expect(current.closed).toHaveBeenCalledOnce(); - expect(current.events).toContainEqual({ event: 'proof_ready_session_closed', - details: expect.objectContaining({ workerId: 'writer', reason: 'interrupt-not-settled' }) }); - expect(current.head()).toBe(before); expect(host.verify).not.toHaveBeenCalled(); - current.stopResult.resolve({ status: 'stopped' }); await current.waitEvent('proof_ready_checked'); - expect(current.state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'checked' }]); - expect(host.verify).toHaveBeenCalled(); - expect(current.state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - current.controller.abort(); await Promise.allSettled([current.completion]); - expect(vi.getTimerCount()).toBe(0); - }); - - it('consumes readiness written at natural completion through the final pulse', async () => { - const current = fixture(); await current.wait(current.started.promise); - current.writeProof(); current.appendReady(); current.turns[0].done.resolve('completed'); - await current.wait(current.stopping.promise); - expect(host.verify).not.toHaveBeenCalled(); current.stopResult.resolve({ status: 'stopped' }); - await current.waitEvent('proof_ready_checked'); - expect(current.state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'checked' }]); - expect(host.verify).toHaveBeenCalled(); - }); - - it('restores a frozen snapshot without opening a writer and ignores subsequent live source edits', async () => { - const example = localExample('solver-proof-ready-restored-', 'lead'); - const { directory, workspace, problem } = example; - const writer = peerWorker(example, 'writer', { role: 'engineer' }); - const workers = [leadWorker(problem, workspace, 'lead'), writer]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: 'goal_' + index, kind: 'goal', ...target, objective: 'Prove ' + target.theoremName, - status: index === 0 ? 'active' : 'paused', ownerId: writer.id, - })) }); - let state = solverState(problem, workspace, { runId: 'proof-ready-restored', phase: 'prepared', failures: [], - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) }, - }); - const preparedController = new AbortController(), controller = new AbortController(); - const prepared = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: preparedController.signal }); - let completion: Promise | undefined; - try { - const action = await prepared.next(writer, { maxTurns: Infinity, remainingMs: Infinity }); - if (action?.kind !== 'task') throw new Error('fixture_missing_restore_assignment'); - expect(prepared.started(writer, action)).toBe(true); - prepared.activate(writer, action, async () => {}, async () => {}, async () => {}); - const sourceFile = path.join(writer.worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(sourceFile, fs.readFileSync(sourceFile, 'utf8').replace('by sorry', 'by rfl')); - fs.appendFileSync(path.join(writer.worktree, assignmentDeliveryFile(action.assignment)), - JSON.stringify({ kind: 'ready', id: 'persisted-ready' }) + '\n'); - await prepared.pulse(writer.id); - const snapshot = commitSolverSources(problem, writer.worktree); - expect(prepared.proofReadyFrozen(writer, action, snapshot)?.status).toBe('frozen'); - prepared.deactivate(writer); preparedController.abort(); await prepared.stop(); - const archive = path.join(directory, 'frozen-state.json'); writeSolverRunState(archive, state); - state = readSolverRunState(archive); - fs.writeFileSync(sourceFile, fs.readFileSync(sourceFile, 'utf8').replace('by rfl', 'by exact rfl')); - const liveCommit = commitSolverSources(problem, writer.worktree); - expect(liveCommit).not.toBe(snapshot); - const open = vi.fn(async () => { throw new Error('fixture_restored_snapshot_must_not_open_model'); }); - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - completion = runResearchWorkers({ state, workers, access: workerAccess(workers, directory), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, root: directory, - buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original goals.', executable: 'offline-fixture', - profile: 'offline-fixture', signal: controller.signal, deadline: Infinity, maxTurns: Infinity, maxTurnMs: Infinity, - maxTotalTokens: 0, save: () => {}, emit: event => { if (event === 'proof_ready_checked') controller.abort(); }, - }); - await Promise.allSettled([completion]); - expect(open).not.toHaveBeenCalled(); - expect(state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'checked', snapshotCommit: snapshot }]); - expect(state.cooperation!.tasks[0].proof).toMatchObject({ passed: true, commit: snapshot }); - expect(host.verify).toHaveBeenCalled(); - const request = host.verify.mock.calls[0][0]; - expect(committedSource(writer.worktree, request.targetCommit, problem.projectRelative + '/Submission.lean')) - .toContain('by rfl'); - expect(committedSource(writer.worktree, request.targetCommit, problem.projectRelative + '/Submission.lean')) - .not.toContain('by exact rfl'); - expect(state.turns).toBe(0); - expect(state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - } finally { - preparedController.abort(); controller.abort(); await prepared.stop(); - if (completion) await Promise.allSettled([completion]); - fs.rmSync(directory, { recursive: true, force: true }); - } - }); - - it.each(['environment', 'task'] as const)('does not freeze old readiness after the %s changes during process shutdown', async change => { - const current = fixture(); await current.wait(current.started.promise); - const before = current.head(); current.writeProof(); current.appendReady(); await current.pulse(); - current.turns[0].done.resolve('interrupted'); await current.wait(current.stopping.promise); - if (change === 'environment') current.state.environmentDigest = 'replacement-environment'; - else current.state.cooperation!.tasks[0].task.revision++; - current.stopResult.resolve({ status: 'stopped' }); - await vi.waitFor(() => expect(current.state.cooperation!.proofReadyRecords![0].status).toBe('superseded')); - expect(current.head()).toBe(before); expect(host.verify).not.toHaveBeenCalled(); - expect(current.state.cooperation!.proofReadyRecords![0].snapshotCommit).toBeUndefined(); - }); -}); diff --git a/tests/solverProofReadyIntake.test.ts b/tests/solverProofReadyIntake.test.ts deleted file mode 100644 index 9f2714e0..00000000 --- a/tests/solverProofReadyIntake.test.ts +++ /dev/null @@ -1,231 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { parseCooperationPlan } from '../src/solver/tasks'; -import { assignmentDeliveryFile, type CooperativeAction } from '../src/solver/tasks'; -import { commitSolverSources, git, type SolverProblem } from '../src/solver/problem'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { proofReadyRecordSchema } from '../src/solver/proofReady'; -import { setWorkerResearchPhase, WorkerProofLifecycle } from '../src/solver/workerProofLifecycle'; -import { cooperativeResearch, workerDeliveryModules } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; -import { deferred } from './helpers/async'; - -const host = vi.hoisted(() => ({ verify: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => 'ready-intake-fixture', resolveMathematicsLakePackagesCache: () => undefined, -})); -type TaskAction = Extract; - -describe('host-owned proof readiness intake', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - let cooperative: CooperativeResearch, action: TaskAction, callback: ReturnType; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[], saves: SolverRunState[]; - let events: { event: string; details?: Record }[]; - const create = () => { - const controller = new AbortController(); - const value = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - modules: workerDeliveryModules, - save: () => saves.push(structuredClone(state)), emit: (event, details) => events.push({ event, details }) }); - instances.push({ cooperative: value, controller }); return value; - }; - const source = () => path.join(workers[1].worktree, problem.projectRelative, 'Submission.lean'); - const append = (value: unknown = { kind: 'ready' }) => fs.appendFileSync( - path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)), JSON.stringify(value) + '\n'); - const activate = () => cooperative.activate(workers[1], action, async () => {}, async () => {}, callback); - const reload = () => { - const file = path.join(directory, 'ready-state.json'); writeSolverRunState(file, state); - state = readSolverRunState(file); cooperative = create(); - const node = state.cooperation!.tasks.find(node => node.task.id === 'helper')!; - action = { kind: 'task', task: node.task, assignment: node.assignment! }; activate(); - }; - const saveHelper = () => { - fs.writeFileSync(source(), fs.readFileSync(source(), 'utf8').replace('end Tutorial', - 'lemma helper : True := by trivial\nend Tutorial')); - return commitSolverSources(problem, workers[1].worktree); - }; - - beforeEach(async () => { - const example = localExample('proof-ready-intake-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace, 'lead'), peerWorker(example, 'writer')]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', objective: 'Original target', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - { id: 'helper', kind: 'lemma', type: 'True', theoremName: 'Tutorial.helper', proofPath: 'Submission.lean', - objective: 'Prove the helper', ownerId: 'writer' }, - ] }); - state = solverState(problem, example.workspace, { runId: 'ready-intake', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - instances = []; saves = []; events = []; callback = vi.fn(async () => {}); - host.verify.mockReset().mockImplementation(async request => verifiedBatch(request, { sessionId: 'ready-intake' })); - cooperative = create(); - state.cooperation!.planVersion = (cooperative as any).planVersion(); - const assigned = await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity }); - if (assigned?.kind !== 'task') throw new Error('fixture_missing_assignment'); - action = assigned; expect(cooperative.started(workers[1], action)).toBe(true); activate(); - }); - afterEach(async () => { - for (const instance of instances) { instance.controller.abort(); await instance.cooperative.stop(); } - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('records ready before requesting turn settlement without reading or committing active sources', async () => { - const head = git(workers[1].worktree, ['rev-parse', 'HEAD']), waiting = deferred(); - callback.mockImplementation(() => waiting.promise); - fs.appendFileSync(source(), '\n-- still writer-owned\n'); - const read = vi.spyOn(fs, 'readFileSync'); - append(); await cooperative.pulse(workers[1].id); - expect(callback).toHaveBeenCalledOnce(); - expect(read.mock.calls.some(([file]) => file === source())).toBe(false); - expect(git(workers[1].worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(host.verify).not.toHaveBeenCalled(); - expect(saves.some(save => save.cooperation?.proofReadyRecords?.[0]?.status === 'awaiting-freeze')).toBe(true); - expect(cooperative.pendingProofReady(workers[1], action)).toMatchObject({ status: 'awaiting-freeze' }); - waiting.resolve(); - }); - - it('freezes and checks one immutable snapshot and never rechecks duplicate completed ready events', async () => { - expect(events.find(item => item.event === 'task_assigned')?.details).toMatchObject({ - taskId: action.task.id, taskDigest: action.assignment.taskDigest, - assignmentKey: assignmentDeliveryFile(action.assignment), planVersion: state.cooperation!.planVersion, - }); - append(); await cooperative.pulse(workers[1].id); - const commit = saveHelper(); - expect(cooperative.proofReadyFrozen(workers[1], action, commit)).toMatchObject({ status: 'frozen', snapshotCommit: commit }); - expect(cooperative.proofReadyFrozen(workers[1], action, commit)?.snapshotCommit).toBe(commit); - const delivered = await cooperative.deliver(workers[1], action, commit); - cooperative.proofReadyCompleted(workers[1], action, delivered.check); - expect(state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'checked', evidence: 'unconditional', - snapshotCommit: commit, conditions: [], receiptIds: [expect.any(String)] }]); - const calls = host.verify.mock.calls.length; - append(); await cooperative.pulse(workers[1].id); - expect(host.verify).toHaveBeenCalledTimes(calls); expect(callback).toHaveBeenCalledOnce(); - expect(cooperative.pendingProofReady(workers[1], action)).toBeUndefined(); - }); - - it.each([false, true])('restores a checking worker after a frozen check settles (failure: %s)', async failed => { - state.workers = workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })); - append(); await cooperative.pulse(workers[1].id); - cooperative.proofReadyFrozen(workers[1], action, saveHelper()); - const pending = deferred(); - const original = cooperative.deliver.bind(cooperative); - vi.spyOn(cooperative, 'deliver').mockImplementationOnce(async (...args) => { - await pending.promise; return original(...args); - }); - const lifecycle = new WorkerProofLifecycle({ state, research: state.workers[1], worker: workers[1], - cooperation: cooperative, close: async () => {}, save: () => saves.push(structuredClone(state)), - emit: () => {}, checked: () => {} }); - const check = lifecycle.resumeFrozen(action); - const result = failed ? expect(check).rejects.toThrow('fixture_check_failed') : expect(check).resolves.toBe(true); - await vi.waitFor(() => expect(state.workers![1].phase).toBe('checking')); - expect(state.phase).toBe('checking'); - if (failed) pending.reject(new Error('fixture_check_failed')); else pending.resolve(); - await result; - expect(state.workers[1].phase).toBe('running'); expect(state.phase).toBe('running'); - expect(saves.at(-1)?.workers?.[1].phase).toBe('running'); - }); - - it('retains the root checking phase only while another worker still checks', () => { - state.workers = workers.map(worker => ({ ...worker, phase: 'checking', turns: 0 })); - setWorkerResearchPhase(state, state.workers[1], 'running'); - expect(state.workers[1].phase).toBe('running'); expect(state.phase).toBe('checking'); - setWorkerResearchPhase(state, state.workers[0], 'running'); - expect(state.phase).toBe('running'); - setWorkerResearchPhase(state, state, 'checking'); - setWorkerResearchPhase(state, state, 'running'); - expect(state.phase).toBe('running'); - }); - - it('requires a newly consumed ready event before freezing an unfrozen request after restart', async () => { - append(); await cooperative.pulse(workers[1].id); reload(); - expect(cooperative.pendingProofReady(workers[1], action)).toBeUndefined(); - const before = callback.mock.calls.length; - append(); await cooperative.pulse(workers[1].id); - expect(callback).toHaveBeenCalledTimes(before + 1); - expect(cooperative.pendingProofReady(workers[1], action)).toMatchObject({ status: 'awaiting-freeze' }); - expect(state.cooperation!.proofReadyRecords).toHaveLength(1); - }); - - it('records conditional Lean receipts without accepting the original goal or retaining the Engineer', async () => { - const tasks = state.cooperation!.tasks.map(({ task }) => task.id === 'helper' - ? { ...task, conditional: true, dependsOn: ['input'] } : task); - tasks.push({ id: 'input', kind: 'lemma', type: 'True', theoremName: 'Tutorial.input', - proofPath: 'Submission.lean', objective: 'An unfinished input' }); - await (cooperative as any).acceptPlan(parseCooperationPlan(problem, { tasks })); - cooperative.deactivate(workers[1]); - const assigned = await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity }); - if (assigned?.kind !== 'task' || assigned.task.id !== 'helper') throw new Error('fixture_missing_conditional_assignment'); - action = assigned; expect(cooperative.started(workers[1], action)).toBe(true); activate(); - fs.writeFileSync(source(), fs.readFileSync(source(), 'utf8').replace('end Tutorial', - 'lemma helper : True := by exact Tutorial.input\nend Tutorial')); - append(); await cooperative.pulse(workers[1].id); - const commit = commitSolverSources(problem, workers[1].worktree); - cooperative.proofReadyFrozen(workers[1], action, commit); - const delivered = await cooperative.deliver(workers[1], action, commit); - cooperative.proofReadyCompleted(workers[1], action, delivered.check); - cooperative.deactivate(workers[1]); - expect(state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'checked', evidence: 'conditional', - snapshotCommit: commit, conditions: [{ taskId: 'input', taskDigest: expect.any(String) }], - receiptIds: [expect.any(String)] }]); - expect(state.cooperation!.tasks.find(node => node.task.id === 'helper')).toMatchObject({ status: 'conditional' }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'goal_0')!.integratedCheck).toBeUndefined(); - expect(state.cooperation!.tasks.some(node => node.status === 'running' && node.assignment?.workerId === workers[1].id)).toBe(false); - }); - - it('restores a fixed snapshot independently of later live edits and refuses to replace its commit', async () => { - append(); await cooperative.pulse(workers[1].id); const commit = saveHelper(); - const frozen = cooperative.proofReadyFrozen(workers[1], action, commit)!; - expect(frozen.frozenAt).toEqual(expect.any(Number)); - const frozenAt = frozen.frozenAt; - reload(); - fs.appendFileSync(source(), '\n-- a later live edit\n'); - const now = vi.spyOn(Date, 'now').mockReturnValue(frozenAt! + 1000); - expect(cooperative.proofReadyFrozen(workers[1], action, commit)).toMatchObject({ - status: 'frozen', snapshotCommit: commit, frozenAt }); - now.mockRestore(); - expect(events.filter(item => item.event === 'proof_ready_frozen')).toEqual([{ event: 'proof_ready_frozen', details: { - readyId: frozen.id, taskId: action.task.id, taskDigest: action.assignment.taskDigest, workerId: workers[1].id, - assignmentKey: assignmentDeliveryFile(action.assignment), seedCommit: action.assignment.seedCommit, - commit, snapshotCommit: commit, sourceDigest: frozen.sourceDigest, frozenAt, - } }]); - expect(() => cooperative.proofReadyFrozen(workers[1], action, problem.baseCommit)).toThrow('math_proof_ready_snapshot_changed'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('supersedes readiness when the environment or task identity changes', async () => { - append(); await cooperative.pulse(workers[1].id); state.environmentDigest = 'new-environment'; - expect(cooperative.pendingProofReady(workers[1], action)).toBeUndefined(); - expect(state.cooperation!.proofReadyRecords![0].status).toBe('superseded'); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('preserves a failed freeze and requires a new submission to retry', async () => { - append(); await cooperative.pulse(workers[1].id); - cooperative.proofReadyFailedFreeze(workers[1], action, 'process-exit-unconfirmed'); - append(); await cooperative.pulse(workers[1].id); - expect(callback).toHaveBeenCalledOnce(); expect(cooperative.pendingProofReady(workers[1], action)).toBeUndefined(); - append({ kind: 'ready', id: 'retry-after-stop-confirmed' }); await cooperative.pulse(workers[1].id); - expect(callback).toHaveBeenCalledTimes(2); - expect(state.cooperation!.proofReadyRecords).toMatchObject([{ status: 'failed' }, { status: 'awaiting-freeze' }]); - }); - - it('rejects caller-provided commits and target lists without granting freeze permission', async () => { - append({ kind: 'ready', commit: problem.baseCommit }); append({ kind: 'ready', targets: ['other'] }); - await cooperative.pulse(workers[1].id); - expect(state.cooperation!.deliveryReceipts).toHaveLength(2); - expect(state.cooperation!.deliveryReceipts!.map(receipt => [receipt.code, receipt.issues.map(issue => issue.path)])) - .toEqual([['math_delivery_invalid', ['commit']], ['math_delivery_invalid', ['targets']]]); - expect(state.cooperation!.deliveryReceipts![1].issues[0].message).toMatch(/^Omit targets from a ready event/u); - expect(state.cooperation!.proofReadyRecords ?? []).toEqual([]); expect(callback).not.toHaveBeenCalled(); - }); - - it('rejects malformed checked archives without a fixed snapshot and Lean receipts', () => { - expect(proofReadyRecordSchema.safeParse({ status: 'checked', evidence: 'unconditional' }).success).toBe(false); - }); -}); diff --git a/tests/solverProverRoles.test.ts b/tests/solverProverRoles.test.ts index 64f00ca4..cbe33d83 100644 --- a/tests/solverProverRoles.test.ts +++ b/tests/solverProverRoles.test.ts @@ -109,17 +109,6 @@ describe('proof-writing context', () => { } as unknown as SolverRunState, { root: '/runtime', worktree: '/proof', environment: {}, taskText: 'Prove the target', retrievalRoot: '/library', frozenContexts: { 'Submission.lean': 'theorem target : True := /- body omitted -/' }, assignment: action }); - it('tells a typed helper writer to save a proof and keeps its exact interface mandatory', () => { - const action: CooperativeAction = { kind: 'task', task: helper.task, - assignment: { taskId: helper.task.id, taskDigest: taskVersion(helper.task), workerId: 'prover-1', seedCommit: 'seed' } }; - const context = build(action); - expect(context.instructions).toContain('You are a Lean Prover.'); - expect(context.instructions).toContain('The host freezes the saved sources and independently checks and integrates them'); - expect(context.instructions).not.toContain('You are a Mathematical Researcher.'); - expect(context.message).toContain('Your role: prover'); - expect(context.message).toContain(JSON.stringify(helper.task.type)); - }); - it('gives Lead the actual proof roster and the expanded route capacity', () => { const context = build({ kind: 'lead', seedCommit: 'seed' }); expect(context.instructions).toContain('"id":"prover-4","role":"prover"'); diff --git a/tests/solverRecheckReuse.test.ts b/tests/solverRecheckReuse.test.ts deleted file mode 100644 index 28ac18a6..00000000 --- a/tests/solverRecheckReuse.test.ts +++ /dev/null @@ -1,268 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { committedSource, commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { taskReferenceDependencies, taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, solverState } from './helpers/solver'; -import { failedBatch, receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => undefined, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const verified = (request: MathematicsVerifierBatchRequest) => { - const batch = receiptBatch(request, { sessionId: 'recheck-reuse-fixture', - receiptId: (_, name) => 'receipt-' + request.targetCommit + '-' + name }); - for (const result of batch.results) result.declarationReferences = { statement: [], - proof: [{ file: 'Submission.lean', name: result.theoremName + '._proof_1' }] }; - return batch; -}; - -describe('process-local reuse of unchanged integrated projections', () => { - let directory: string, workspace: string, file: string, problem: SolverProblem, state: SolverRunState; - let cooperative: CooperativeResearch, controller: AbortController; - let events: { event: string; details?: Record }[]; - const node = (id: string) => state.cooperation!.tasks.find(item => item.task.id === id)!; - const source = () => committedSource(workspace, state.cooperation!.canonicalCommit!, problem.projectRelative + '/Submission.lean'); - const update = (change: (source: string) => string) => { - fs.writeFileSync(file, change(source())); - state.cooperation!.canonicalCommit = commitSolverSources(problem, workspace); - }; - const synchronize = async () => { - const selected = state.cooperation!.tasks.filter(item => item.status === 'integrated'); - (cooperative as any).markPendingValidation(selected, new Set(selected.map(item => item.task.id))); - await (cooperative as any).schedulePlanSynchronization(); - }; - const recheck = () => (cooperative as any).recheckIntegrated(state.cooperation!.canonicalCommit!, true) as Promise; - const checkedNames = () => host.verify.mock.calls.flatMap(([request]: [MathematicsVerifierBatchRequest]) => - request.items.map(item => item.theoremName)); - const reusedIds = () => events.filter(item => item.event === 'task_check_reused').map(item => item.details?.taskId); - const finishLastGoal = () => update(text => text.replace('by sorry', 'by exact Nat.zero_add n')); - - beforeEach(async () => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - const example = localExample('solver-recheck-reuse-'); - ({ directory, workspace, problem } = example); - file = path.join(workspace, problem.projectRelative, 'Submission.lean'); - const initial = fs.readFileSync(file, 'utf8').replace('theorem add_zero', 'lemma helper : True := by trivial\n\ntheorem add_zero') - .replace('by sorry', 'by rfl'); - fs.writeFileSync(file, initial); - const canonical = commitSolverSources(problem, workspace), lead = leadWorker(problem, workspace); - const helper: CooperativeTask = { id: 'helper', kind: 'lemma', objective: 'Prove the helper.', type: 'True', - proofPath: 'Submission.lean', theoremName: 'Tutorial.helper', dependsOn: [], revision: 0 }; - const goals: CooperativeTask[] = problem.targets.map((target, index) => ({ id: 'goal_' + index, kind: 'goal', - objective: 'Prove ' + target.theoremName + '.', proofPath: target.proofPath, theoremName: target.theoremName, - dependsOn: index === 0 ? ['helper'] : [], revision: 0 })); - state = solverState(problem, workspace, { runId: 'recheck-reuse-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: canonical, - groups: [{ group: { id: 'main', objective: 'Prove the original problem.', status: 'active', revision: 0 }, turns: 0 }], - tasks: [helper, ...goals].map(task => ({ task, status: task.id === 'goal_1' ? 'pending' : 'integrated', attempts: 0 })) } }); - events = []; controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers: [lead], retrievalRoot: directory, signal: controller.signal, - emit: (event, details) => events.push({ event, details }) }); - for (const current of [node('helper'), node('goal_0')]) { - current.integratedCheck = await (cooperative as any).check(current.task, - { taskId: current.task.id, taskDigest: taskVersion(current.task), workerId: lead.id, seedCommit: canonical }, workspace, canonical); - expect(current.integratedCheck!.references!.inputs.some(input => !input.name)).toBe(true); - expect(taskReferenceDependencies(current)).toBeUndefined(); - } - host.verify.mockClear(); events = []; - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('keeps receipts for unchanged helpers and goals when Lead completes only the last goal', async () => { - const helper = node('helper').integratedCheck, goal = node('goal_0').integratedCheck; - finishLastGoal(); - - await synchronize(); - - expect(host.verify).not.toHaveBeenCalled(); - expect(reusedIds()).toEqual(['helper', 'goal_0']); - expect(node('helper').integratedCheck).toBe(helper); - expect(node('goal_0').integratedCheck).toBe(goal); - expect(node('helper').pendingValidation).toBeUndefined(); - expect(node('goal_0').pendingValidation).toBeUndefined(); - expect(state.cooperation!.recheck).toMatchObject({ total: 2, completed: 2 }); - expect(source()).toContain('by exact Nat.zero_add n'); - }); - - it.each([false, true])('reuses a fresh compact receipt with whole-module references and changed sibling=%s', async changed => { - update(text => text.replace('theorem add_zero', 'lemma inherited_unused : True := by trivial\ntheorem add_zero')); - const seedCommit = state.cooperation!.canonicalCommit!; - if (changed) update(text => text.replace('theorem add_zero', 'lemma changed_sibling : True := by trivial\ntheorem add_zero')); - const canonical = state.cooperation!.canonicalCommit!, helper = node('helper'); - helper.integratedCheck = await (cooperative as any).check(helper.task, - { taskId: helper.task.id, taskDigest: taskVersion(helper.task), workerId: 'solver', - seedCommit: changed ? seedCommit : canonical }, workspace, canonical); - expect(helper.integratedCheck!.projectionMode).toBe('compact'); - expect(helper.integratedCheck!.changes.some(change => change.name === 'changed_sibling')).toBe(changed); - expect(helper.integratedCheck!.references!.inputs.some(input => !input.name)).toBe(true); - expect(taskReferenceDependencies(helper)).toBeUndefined(); - const proof = helper.integratedCheck; - host.verify.mockClear(); events = []; - - await recheck(); - - expect(checkedNames()).not.toContain('Tutorial.helper'); - expect(reusedIds()).toContain('helper'); - expect(helper.integratedCheck).toBe(proof); - }); - - it('checks changed-only targets with the same full projection in one independent verifier batch', async () => { - const extra: CooperativeTask = { id: 'extra', kind: 'lemma', objective: 'Prove another helper.', type: 'True', - proofPath: 'Submission.lean', theoremName: 'Tutorial.extra', dependsOn: [], revision: 0 }; - update(text => text.replace('theorem add_zero', 'lemma extra : True := by trivial\n\ntheorem add_zero')); - state.cooperation!.tasks.splice(1, 0, { task: extra, status: 'integrated', attempts: 0 }); - finishLastGoal(); - const check = vi.spyOn(cooperative as any, 'check'); - - await recheck(); - - expect(host.verify).toHaveBeenCalledTimes(2); - expect(host.verify.mock.calls.map(([request]) => request.items.map(item => item.theoremName))) - .toEqual([['Tutorial.helper', 'Tutorial.extra'], ['Tutorial.add_zero']]); - expect(events.filter(item => item.event === 'task_recheck_batch_started')).toMatchObject([ - { details: { taskIds: ['helper', 'extra'] } }, - ]); - expect(check).toHaveBeenCalledTimes(3); - for (const current of [node('helper'), node('extra'), node('goal_0')]) { - expect(current.integratedCheck).toMatchObject({ passed: true, commit: state.cooperation!.canonicalCommit, - verification: { results: [{ theoremName: current.task.theoremName }] } }); - expect(current.integratedCheck!.verification.results).toHaveLength(1); - } - }); - - it('rechecks a consumer separately after its retained goal dependency becomes invalid', async () => { - const consumer: CooperativeTask = { id: 'consumer', kind: 'lemma', objective: 'Consume the checked goal.', type: 'True', - proofPath: 'Submission.lean', theoremName: 'Tutorial.consumer', dependsOn: ['goal_0'], revision: 0 }; - update(text => text.replace('theorem add_zero', 'lemma consumer : True := by trivial\n\ntheorem add_zero')); - state.cooperation!.tasks.push({ task: consumer, status: 'integrated', attempts: 0 }); - node('helper').status = 'blocked'; - - await expect(recheck()).resolves.toBe(true); - - expect(host.verify.mock.calls.map(([request]) => request.items.map(item => item.theoremName))) - .toEqual([['Tutorial.add_zero'], ['Tutorial.consumer']]); - for (const id of ['goal_0', 'consumer']) expect(node(id)).toMatchObject({ - status: 'blocked', feedback: 'math_task_dependency_invalidated', - integratedCheck: { passed: true, commit: state.cooperation!.canonicalCommit }, - }); - const requests = host.verify.mock.calls.map(([request]: [MathematicsVerifierBatchRequest]) => request); - expect(committedSource(workspace, requests[0].targetCommit!, problem.projectRelative + '/Submission.lean')) - .toContain('theorem add_zero'); - // The original was independently checked in this phase, so its concrete source can - // remain in the consumer check while the invalidated graph still blocks both tasks. - expect(committedSource(workspace, requests[1].targetCommit!, problem.projectRelative + '/Submission.lean')) - .toContain('theorem add_zero (n : Nat) : n + 0 = n := by rfl'); - expect(node('consumer').integratedCheck!.verification.targetCommit).toBe(requests[1].targetCommit); - }); - - it('rechecks a restored receipt without forcing an unchanged live receipt through the verifier', async () => { - node('helper').integratedCheck = structuredClone(node('helper').integratedCheck); - const goal = node('goal_0').integratedCheck; - finishLastGoal(); - - await synchronize(); - - expect(checkedNames()).toEqual(['Tutorial.helper']); - expect(reusedIds()).toEqual(['goal_0']); - expect(node('goal_0').integratedCheck).toBe(goal); - expect(node('helper').integratedCheck!.commit).toBe(state.cooperation!.canonicalCommit); - }); - - it('never reuses receipts restored from JSON even when every projection is unchanged', async () => { - for (const current of [node('helper'), node('goal_0')]) current.integratedCheck = structuredClone(current.integratedCheck); - finishLastGoal(); - - await synchronize(); - - expect(checkedNames()).toEqual(['Tutorial.helper', 'Tutorial.add_zero']); - expect(reusedIds()).toEqual([]); - }); - - it('keeps an unchanged goal blocked when its required dependency is invalidated', async () => { - node('helper').status = 'blocked'; - finishLastGoal(); - - await recheck(); - - expect(checkedNames()).toEqual(['Tutorial.add_zero']); - expect(reusedIds()).toEqual([]); - expect(node('goal_0')).toMatchObject({ status: 'blocked', feedback: 'math_task_dependency_invalidated' }); - }); - - it.each(['source', 'environment', 'task', 'receipt'] as const) - ('rechecks integrated proofs after their %s changes', async change => { - finishLastGoal(); - if (change === 'source') update(text => text.replace('helper : True := by trivial', 'helper : True := by exact True.intro')); - if (change === 'environment') state.environmentDigest = 'changed-environment'; - if (change === 'task') node('helper').task = { ...node('helper').task, revision: 1, objective: 'Clarify the helper.' }; - if (change === 'receipt') node('helper').integratedCheck!.verification.results[0]!.receiptId = 'changed-receipt'; - - await synchronize(); - - expect(checkedNames()).toContain('Tutorial.helper'); - expect(reusedIds()).not.toContain('helper'); - if (['source', 'environment'].includes(change)) { - expect(checkedNames()).toContain('Tutorial.add_zero'); - expect(reusedIds()).toEqual([]); - } - for (const current of [node('helper'), node('goal_0')]) expect(current).toMatchObject({ - status: 'integrated', integratedCheck: { passed: true, taskDigest: taskVersion(current.task) }, - }); - }); - it.each(['live', 'restored', 'new-reference'] as const) - ('blocks an actual-reference consumer when its later producer fails recheck (%s)', async mode => { - const peer: CooperativeTask = { id: 'peer', kind: 'lemma', objective: 'Prove peer.', type: 'True', - proofPath: 'Submission.lean', theoremName: 'Tutorial.peer', dependsOn: [], revision: 0 }; - update(text => text.replace('theorem add_zero', 'lemma peer : True := by trivial\n\ntheorem add_zero')); - state.cooperation!.tasks.push({ task: peer, status: 'integrated', attempts: 0 }); - if (mode !== 'new-reference') update(text => text.replace('by rfl', 'by have := peer; rfl')); - let rechecking = false; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = receiptBatch(request, { sessionId: 'actual-order-fixture', receiptId: (_, name) => 'receipt-' + name }); - for (const result of batch.results) result.declarationReferences = { statement: [], proof: result.theoremName === 'Tutorial.add_zero' && - (mode !== 'new-reference' || rechecking) - ? [{ file: 'Submission.lean', name: 'Tutorial.peer' }] : [] }; - return batch; - }); - for (const current of [node('peer'), node('goal_0')]) current.integratedCheck = await (cooperative as any).check(current.task, - { taskId: current.task.id, taskDigest: taskVersion(current.task), workerId: 'lead', seedCommit: state.cooperation!.canonicalCommit! }, - workspace, state.cooperation!.canonicalCommit!); - expect(taskReferenceDependencies(node('goal_0'))).toEqual(mode === 'new-reference' ? [] : - [{ taskId: 'peer', taskDigest: taskVersion(peer) }]); - if (mode === 'restored') for (const current of [node('peer'), node('goal_0')]) current.integratedCheck = structuredClone(current.integratedCheck); - update(text => text.replace('peer : True := by trivial', 'peer : True := by exact True.intro')); - if (mode === 'new-reference') update(text => text.replace('by rfl', 'by have := peer; rfl')); - rechecking = true; - const previous = host.verify.getMockImplementation()!; - host.verify.mockImplementation(async (request: MathematicsVerifierBatchRequest) => { - const batch = await previous(request); - return request.items.some(item => item.theoremName === 'Tutorial.peer') ? failedBatch(batch, { - selected: result => result.theoremName === 'Tutorial.peer', stdoutPreview: () => 'Submission.lean:5:0: error: unsolved goals' }) : batch; - }); - await synchronize(); - expect(node('peer').status).toBe('blocked'); - expect(node('peer').pendingValidation).toBeUndefined(); - expect(node('goal_0').pendingValidation).toBeUndefined(); - expect(node('goal_0')).toMatchObject({ status: 'blocked', feedback: 'math_task_dependency_invalidated' }); - expect(node('goal_0').integratedCheck!.references!.tasks).toEqual([{ taskId: 'peer', taskDigest: taskVersion(peer) }]); - expect(node('helper').status).toBe('integrated'); - expect(node('goal_1').status).toBe('pending'); - expect(state.cooperation!.recheck).toMatchObject({ total: 3, completed: 3 }); - }); -}); diff --git a/tests/solverResearchBasisDispatch.test.ts b/tests/solverResearchBasisDispatch.test.ts deleted file mode 100644 index 44b04b3a..00000000 --- a/tests/solverResearchBasisDispatch.test.ts +++ /dev/null @@ -1,350 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import type { ContextManifest } from '../src/solver/contextCompiler'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { committedSource, commitSolverSources } from '../src/solver/problem'; -import { researchSourceDigest, restoreResearch } from '../src/solver/researchRecords'; -import { runResearchWorkers } from '../src/solver/research'; -import { parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -describe('research basis at actual model dispatch', () => { - let directory: string, controllers: AbortController[], running: Promise[], releases: (() => void)[]; - - beforeEach(() => { - vi.useFakeTimers(); controllers = []; running = []; releases = []; - // Drive the ordinary dispatch/checkpoint loop without an unrelated delivery poller. - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - }); - afterEach(async () => { - controllers.forEach(controller => controller.abort()); - releases.forEach(release => release()); - await Promise.allSettled(running); - vi.useRealTimers(); vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - }); - - function fixture() { - const example = localExample('solver-research-basis-dispatch-', 'lead'); - directory = example.directory; - const { workspace, problem } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'researcher')]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index + 1}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, ...target, status: 'paused' })), - { id: 'prior', kind: 'research', objective: 'Identify the exact input.', status: 'paused' }, - { id: 'investigate', kind: 'research', ownerId: 'researcher', dependsOn: ['prior'], - objective: 'Resolve the precise remaining construction.' }, - ] }); - const state = solverState(problem, workspace, { runId: 'research-basis-dispatch-fixture', phase: 'prepared', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: task.id === 'prior' ? 'completed' : 'pending', attempts: 0, - ...(task.id === 'prior' ? { finding: 'Exact dependency finding A.' } : {}) })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const investigate = () => state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - const prior = () => state.cooperation!.tasks.find(node => node.task.id === 'prior')!; - const sourcesAt = (commit: string) => researchSourceDigest(Object.fromEntries(problem.ownedFiles.map(file => [file, - committedSource(workers[1].worktree, commit, `${problem.projectRelative}/${file}`)]))); - const advanceCanonical = () => { - const file = path.join(workers[0].worktree, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem add_zero', - 'lemma canonical_helper : True := by trivial\ntheorem add_zero')); - const commit = commitSolverSources(problem, workers[0].worktree); - state.cooperation!.canonicalCommit = commit; - return commit; - }; - const check = vi.fn(async () => { throw new Error('fixture_unexpected_proof_acceptance'); }); - const contexts: { assignment: CooperativeAction; dependencyFinding?: string }[] = []; - const settings = { omitFinding: false, realContext: false, maxOptionalContextBytes: 0 }; - const manifests: ContextManifest[] = []; - const events: { event: string; details?: Record }[] = []; - const controller = new AbortController(); controllers.push(controller); - const run = (open: (options: MathAgentOptions) => Promise, maxTurns = 1) => { - const modules: SolverModules = { ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M2: { ...directSolverModules.M2, check, checkTask: check }, - M4: { ...directSolverModules.M4, build: (_problem, view, access) => { - const inputs = { assignment: access.assignment!, - dependencyFinding: settings.omitFinding ? undefined : view.cooperation!.tasks.find(node => node.task.id === 'prior')?.finding }; - contexts.push(structuredClone(inputs)); - if (settings.realContext) { - const compiled = directSolverModules.M4.build(_problem, view, - { ...access, maxOptionalContextBytes: settings.maxOptionalContextBytes }); - manifests.push(compiled.manifest!); - return compiled; - } - const manifest: ContextManifest | undefined = settings.omitFinding ? { - schema: 'theorem-os.task-context.v1', evidence: 'recorded-not-replayed', contentDigest: 'omitted-finding-fixture', - maxBytes: 4096, usedBytes: 100, mandatoryBytes: 100, maxOptionalBytes: 0, optionalBytes: 0, - requiredTaskIds: ['investigate', 'prior'], included: [], - omitted: [{ id: 'finding:prior', kind: 'finding', reason: 'optional-budget' }], - } : undefined; - return { instructions: 'Offline research dispatch fixture.', - message: JSON.stringify({ ...inputs, inbox: view.cooperation!.deliveries?.map(record => record.summary), mode: 'full' }), - continuationMessage: JSON.stringify({ ...inputs, inbox: view.cooperation!.deliveries?.map(record => record.summary), mode: 'short' }), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - ...(manifest ? { manifest } : {}) }; - } } }; - const completion = runResearchWorkers({ state, workers, modules, access: workerAccess(workers, directory), - root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original targets.', - executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, - deadline: Infinity, maxTurnMs: Infinity, maxTurns, maxTotalTokens: 0, - save: () => {}, emit: (event, details) => events.push({ event, details }) }); - running.push(completion); void completion.catch(() => {}); - return completion; - }; - return { state, workers, contexts, manifests, events, settings, controller, run, check, investigate, prior, sourcesAt, advanceCanonical }; - } - - function heldResearchTurns(count: number) { - const started = Array.from({ length: count }, () => deferred()); - const done = Array.from({ length: count }, () => deferred()); - releases.push(() => done.forEach(turn => turn.resolve('interrupted'))); - const messages: string[] = [], threads: string[] = []; - let nextThread = 0, active: ReturnType> | undefined; - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const threadId = options.threadId ?? `real-context-thread-${++nextThread}`; - return { threadId, close: async () => { active?.resolve('interrupted'); }, - interrupt: async () => { active?.resolve('interrupted'); }, notify: async () => {}, - run: async (message, _id, worktree, onStarted) => { - const index = messages.length; - if (index >= count) throw new Error('fixture_unexpected_real_context_turn'); - messages.push(message); threads.push(threadId); active = done[index]; - onStarted(`real-context-turn-${index}`); - // The advisory clock measures produced work, so this writing turn arms it immediately. - options.onActivity?.({ event: 'reasoning' }); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), `An unfinished derivation retains its exact remaining inference at step ${index}.\n`); - started[index].resolve(); return done[index].promise; - } }; - }); - const wait = (turn: number, completion: Promise) => Promise.race([started[turn].promise, - completion.then(() => { throw new Error('fixture_finished_before_real_context_turn:' + turn); })]); - return { open, messages, threads, done, wait }; - } - - it('continues omitted real-context input briefly and dispatches newly visible evidence in full before consuming it', async () => { - const { state, settings, manifests, events, run, check, investigate, prior, sourcesAt } = fixture(); - settings.realContext = true; - const held = heldResearchTurns(4), completion = run(held.open, 4); - await held.wait(0, completion); - const finding = prior().finding!; - expect(manifests.at(-1)!.omitted).toContainEqual({ id: 'finding:prior', kind: 'finding', reason: 'optional-budget' }); - expect(held.messages[0]).not.toContain(finding); - expect(investigate().assignment!.researchBasis).toBeUndefined(); - - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - expect(held.messages[1]).toContain('Continue the current task responsibility'); - expect(held.messages[1]).not.toContain(finding); - expect(investigate().assignment!.researchBasis).toBeUndefined(); - - settings.maxOptionalContextBytes = 64 * 1024; - await vi.advanceTimersByTimeAsync(120_000); await held.wait(2, completion); - expect(manifests.at(-1)!.included).toContainEqual(expect.objectContaining({ id: 'finding:prior' })); - expect(held.messages[2]).toContain(finding); - const visibleBasis = investigate().assignment!.researchBasis!; - expect(visibleBasis.dependencies).toContainEqual(expect.objectContaining({ taskId: 'prior', findingDigest: mathDigest(finding) })); - - await vi.advanceTimersByTimeAsync(120_000); await held.wait(3, completion); - expect(held.messages[3]).toContain('Continue the current task responsibility'); - expect(investigate().assignment!.researchBasis).toBe(visibleBasis); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)) - .toEqual(['full', 'continuation', 'full', 'continuation']); - expect(held.open).toHaveBeenCalledOnce(); - held.done[3].resolve('completed'); await expect(completion).resolves.toBeUndefined(); - expect(restoreResearch(investigate().researchCompletion, investigate().task, { - sourceDigest: sourcesAt(investigate().assignment!.seedCommit), problemReceiptDigest: state.problem.receiptDigest, - environmentDigest: state.environmentDigest, tasks: state.cooperation!.tasks, - deliveries: state.cooperation!.deliveries }, investigate().finding).status).toBe('completed'); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - }); - - it('notifies a changed hidden dependency once without claiming it was consumed', async () => { - const { state, settings, events, run, check, investigate, prior, sourcesAt } = fixture(); - settings.realContext = true; - const held = heldResearchTurns(4), completion = run(held.open, 4); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - prior().finding = 'A new hidden dependency construction requires its complete saved argument.'; - await vi.advanceTimersByTimeAsync(120_000); await held.wait(2, completion); - expect(held.messages[2]).not.toContain(prior().finding!); - expect(investigate().assignment!.researchBasis).toBeUndefined(); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(3, completion); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)) - .toEqual(['full', 'continuation', 'full', 'continuation']); - expect(investigate().assignment!.researchBasis).toBeUndefined(); - held.done[3].resolve('completed'); await expect(completion).resolves.toBeUndefined(); - expect(restoreResearch(investigate().researchCompletion, investigate().task, { - sourceDigest: sourcesAt(investigate().assignment!.seedCommit), problemReceiptDigest: state.problem.receiptDigest, - environmentDigest: state.environmentDigest, tasks: state.cooperation!.tasks, - deliveries: state.cooperation!.deliveries }, investigate().finding).status).toBe('pending'); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - }); - - it('sends full real context after rotating an omitted-input thread', async () => { - const { settings, events, run, check, investigate } = fixture(); - settings.realContext = true; - const held = heldResearchTurns(3), completion = run(held.open, 3); - await held.wait(0, completion); - await vi.advanceTimersByTimeAsync(120_000); await held.wait(1, completion); - held.open.mock.calls[0][0].onActivity!({ event: 'item_started', itemType: 'contextCompaction' }); - await vi.advanceTimersByTimeAsync(10 * 60_000); await held.wait(2, completion); - expect(held.threads).toEqual(['real-context-thread-1', 'real-context-thread-1', 'real-context-thread-2']); - expect(events.filter(item => item.event === 'context_dispatched').map(item => item.details?.mode)) - .toEqual(['full', 'continuation', 'full']); - expect(investigate().assignment!.researchBasis).toBeUndefined(); - held.done[2].resolve('completed'); await expect(completion).resolves.toBeUndefined(); - expect(check).not.toHaveBeenCalled(); - }); - - it('settles the exact context prepared before a session opens and freezes its basis only when the request starts', async () => { - const { state, workers, contexts, run, check, investigate, prior, sourcesAt, advanceCanonical } = fixture(); - const opening = deferred(), opened = deferred(), started = deferred(), done = deferred(); - const session: MathAgentSession = { threadId: 'basis-open-thread', close: async () => { done.resolve('interrupted'); }, - interrupt: async () => { done.resolve('interrupted'); }, notify: async () => {}, - run: async (message, _id, _workspace, onStarted) => { - expect(investigate().assignment!.researchBasis).toBeUndefined(); - expect(JSON.parse(message)).toMatchObject({ dependencyFinding: 'Exact dependency finding A.' }); - expect(message).not.toContain('researchBasis'); - onStarted('basis-open-turn'); started.resolve(); return done.promise; - } }; - releases.push(() => { opened.resolve(session); done.resolve('interrupted'); }); - const completion = run(async () => { opening.resolve(); return opened.promise; }); - await opening.promise; - const seed = investigate().assignment!.seedCommit; - expect(investigate().assignment!.researchBasis).toBeUndefined(); - expect(contexts[0].dependencyFinding).toBe('Exact dependency finding A.'); - prior().finding = 'Exact dependency finding B.'; - const canonical = advanceCanonical(); - opened.resolve(session); await started.promise; - const basis = investigate().assignment!.researchBasis!; - expect(basis.dependencies).toContainEqual(expect.objectContaining({ taskId: 'prior', findingDigest: mathDigest(contexts[0].dependencyFinding!) })); - expect(basis.sourceDigest).toBe(sourcesAt(seed)); expect(basis.sourceDigest).not.toBe(sourcesAt(canonical)); - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), 'The exact derivation and its precise remaining scope are saved.\n'); - done.resolve('completed'); await expect(completion).resolves.toBeUndefined(); - expect(investigate().researchCompletion).toMatchObject({ complete: true, basis, seedCommit: seed }); - expect(state.cooperation!.deliveries!.find(record => record.taskId === 'investigate' && record.kind === 'research')!.researchRecord) - .toBe(investigate().researchCompletion); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - }); - - it('refreshes changed input in full context, keeps the same seed and resumes unchanged input with a short prompt', async () => { - const { state, workers, contexts, events, run, check, investigate, prior, sourcesAt, advanceCanonical } = fixture(); - const entered = [deferred(), deferred(), deferred()], started = [deferred(), deferred(), deferred()]; - const done = [deferred(), deferred(), deferred()], startSecond = deferred(); - releases.push(() => { startSecond.resolve(); done.forEach(turn => turn.resolve('interrupted')); }); - const messages: { mode: string; assignment: CooperativeAction; dependencyFinding?: string }[] = []; - let turn = 0, active = done[0]; - const open = vi.fn(async (options: MathAgentOptions): Promise => ({ - threadId: options.threadId ?? 'same-research-thread', close: async () => { active.resolve('interrupted'); }, - interrupt: async () => { active.resolve('interrupted'); }, notify: async () => {}, - run: async (message, _id, _workspace, onStarted) => { - const index = turn++; - if (index > 2) throw new Error('fixture_unexpected_fourth_turn'); - messages.push(JSON.parse(message)); active = done[index]; entered[index].resolve(); - if (index === 1) await startSecond.promise; - onStarted(`basis-continuation-${index}`); started[index].resolve(); - // A writing turn arms the advisory clock at its first produced item. - options.onActivity?.({ event: 'reasoning' }); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), index === 0 - ? 'The unfinished derivation and exact remaining inference are retained.\n' - : 'The completed advisory derivation retains all quantified hypotheses.\n'); - return done[index].promise; - } })); - const completion = run(open, 3); - await started[0].promise; - const firstBasis = investigate().assignment!.researchBasis!, seed = investigate().assignment!.seedCommit; - prior().finding = 'A new exact dependency finding for the next prompt.'; - await vi.advanceTimersByTimeAsync(120_000); await entered[1].promise; - expect(investigate().researchCompletion).toBeUndefined(); expect(investigate().finding).toBeUndefined(); - expect(state.cooperation!.researchDrafts?.investigate).toBeDefined(); - expect(investigate().assignment!.researchBasis).toBe(firstBasis); - const canonical = advanceCanonical(); - startSecond.resolve(); await started[1].promise; - const nextBasis = investigate().assignment!.researchBasis!; - expect(nextBasis).not.toBe(firstBasis); - expect(nextBasis.dependencies).toContainEqual(expect.objectContaining({ taskId: 'prior', findingDigest: mathDigest(contexts[1].dependencyFinding!) })); - expect(contexts[1].dependencyFinding).toBe('A new exact dependency finding for the next prompt.'); - expect(nextBasis.sourceDigest).toBe(sourcesAt(seed)); expect(nextBasis.sourceDigest).not.toBe(sourcesAt(canonical)); - expect(messages.map(message => message.mode)).toEqual(['full', 'full']); - const unrelated = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.task; - (state.cooperation!.deliveries ??= []).push({ id: 'unrelated-peer-progress', taskId: unrelated.id, - taskDigest: taskVersion(unrelated), kind: 'progress', status: 'advisory', producer: workers[0].id, - summary: 'Unrelated original-goal activity.', statement: unrelated.objective, premises: [], dependencies: [], - remainingObligations: [], evidenceRefs: [], createdAt: Date.now() }); - await vi.advanceTimersByTimeAsync(120_000); await started[2].promise; - expect(investigate().researchCompletion).toBeUndefined(); - expect(investigate().assignment!.researchBasis).toEqual(nextBasis); - expect(messages.map(message => message.mode)).toEqual(['full', 'full', 'short']); - expect(JSON.stringify(messages)).not.toContain('researchBasis'); - expect(JSON.stringify(messages[2])).toContain('Unrelated original-goal activity.'); - expect(events.filter(event => event.event === 'context_dispatched').map(event => event.details?.mode)).toEqual(['full', 'full', 'continuation']); - expect(open).toHaveBeenCalledOnce(); expect(state.workers![1].threadId).toBe('same-research-thread'); - done[2].resolve('completed'); await expect(completion).resolves.toBeUndefined(); - expect(investigate().researchCompletion).toMatchObject({ basis: nextBasis, complete: true }); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - }); - - it('does not manufacture an input basis when opening a session is cancelled before dispatch', async () => { - const { state, run, controller, investigate, check } = fixture(); - const opening = deferred(), opened = deferred(); - const request = vi.fn(async () => { throw new Error('fixture_unstarted_request_must_not_run'); }); - const close = vi.fn(async () => {}); - const session: MathAgentSession = { threadId: 'unstarted-thread', run: request, close, interrupt: async () => {}, notify: async () => {} }; - releases.push(() => opened.resolve(session)); - const completion = run(async () => { opening.resolve(); return opened.promise; }); - await opening.promise; - expect(investigate().assignment!.researchBasis).toBeUndefined(); - controller.abort(new Error('fixture_cancel_before_start')); - opened.resolve(session); - await expect(completion).rejects.toThrow('fixture_cancel_before_start'); - expect(investigate().assignment?.researchBasis).toBeUndefined(); expect(investigate().researchCompletion).toBeUndefined(); - expect(state.cooperation!.deliveries ?? []).toEqual([]); expect(request).not.toHaveBeenCalled(); - expect(close).toHaveBeenCalledOnce(); expect(state.turns).toBe(0); expect(check).not.toHaveBeenCalled(); - }); - - it.each([false, true])('does not claim consumption of an omitted dependency finding (previous basis: %s)', async previous => { - const { state, settings, run, check, investigate, prior, sourcesAt } = fixture(); - const started = [deferred(), deferred()], done = [deferred(), deferred()]; - releases.push(() => done.forEach(turn => turn.resolve('interrupted'))); - let turn = 0, active = done[0]; - if (!previous) settings.omitFinding = true; - const completion = run(async (options): Promise => ({ threadId: 'omitted-finding-thread', - close: async () => { active.resolve('interrupted'); }, interrupt: async () => { active.resolve('interrupted'); }, notify: async () => {}, - run: async (message, _id, worktree, onStarted) => { - const index = turn++; active = done[index]; - if (settings.omitFinding) expect(JSON.parse(message).dependencyFinding).toBeUndefined(); - onStarted(`omitted-finding-turn-${index}`); started[index].resolve(); - // A writing turn arms the advisory clock at its first produced item. - options.onActivity?.({ event: 'reasoning' }); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), index === 0 && previous - ? 'An unfinished derivation using the supplied first dependency finding.\n' - : 'An advisory derivation based on the dependency findings actually supplied.\n'); - return done[index].promise; - } }), previous ? 2 : 1); - await started[0].promise; - const oldBasis = investigate().assignment!.researchBasis; - if (previous) { - expect(oldBasis).toBeDefined(); - prior().finding = 'New dependency finding omitted from the model context.'; - settings.omitFinding = true; - await vi.advanceTimersByTimeAsync(120_000); await started[1].promise; - } - expect(investigate().assignment!.researchBasis).toBe(oldBasis); - if (!previous) expect(oldBasis).toBeUndefined(); - done[previous ? 1 : 0].resolve('completed'); await expect(completion).resolves.toBeUndefined(); - const node = investigate(); - expect(node.researchCompletion?.basis).toEqual(oldBasis); - expect(restoreResearch(node.researchCompletion, node.task, { sourceDigest: sourcesAt(node.assignment!.seedCommit), - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, - tasks: state.cooperation!.tasks, deliveries: state.cooperation!.deliveries }, node.finding).status).toBe('pending'); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - }); -}); diff --git a/tests/solverResearchDrafts.test.ts b/tests/solverResearchDrafts.test.ts deleted file mode 100644 index d9569e9c..00000000 --- a/tests/solverResearchDrafts.test.ts +++ /dev/null @@ -1,932 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { leadResearchInputs } from '../src/solver/contextCompiler'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { leadWakePending } from '../src/solver/leadWakes'; -import * as knowledgeApplications from '../src/solver/knowledgeApplications'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git, type SolverProblem } from '../src/solver/problem'; -import * as problemSource from '../src/solver/problem'; -import { assignmentDeliveryFile, taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { taskConnectionCheckCurrent } from '../src/solver/taskConnections'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { captureResearchBasis, researchSourceDigest } from '../src/solver/researchRecords'; -import { cooperativeResearch } from './helpers/cooperation'; -import { deferred } from './helpers/async'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -describe('isolated advisory research drafts', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, cooperative: CooperativeResearch; - let lead: ResearchWorker, peer: ResearchWorker, sequence: number; - let inputWorkers: ResearchWorker[]; - const instances: CooperativeResearch[] = []; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const notes = () => path.join(peer.worktree, 'RESEARCH.md'); - const source = (worker = peer) => path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - const node = (id: string) => state.cooperation!.tasks.find(node => node.task.id === id)!; - // Current research deliveries whose exact lemma proposals are not yet in the plan. - const pendingProposals = () => (state.cooperation!.deliveries ?? []).filter(delivery => delivery.kind === 'research' && - delivery.status !== 'superseded' && delivery.lemmaRequests?.some(task => !state.cooperation!.tasks.some(node => node.task.id === task.id))); - const write = (worker: ResearchWorker, value: unknown, code = '') => fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), - '```math\n' + JSON.stringify(value) + '\n```\n' + code); - const finding = () => ({ conclusion: 'supporting', summary: 'FIRST_ROUTE_FINDING', - leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['Candidate.probe'] }], - lemmaRequests: [{ id: 'bridge', kind: 'lemma', objective: 'Prove the proposed bridge', - theoremName: 'Candidate.bridge', type: 'True', proofPath: 'Submission.lean' }] }); - const leanProbe = '```lean\nnamespace Candidate\nlemma probe : True := by trivial\nend Candidate\n```\n'; - const saveFinding = () => write(peer, finding(), leanProbe); - const create = (current = state, save?: (state: SolverRunState) => void) => { - const instance = cooperativeResearch({ state: current, workers: [lead, peer, ...inputWorkers], retrievalRoot: directory, - save: () => save?.(current), - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, - check: async () => { throw new Error('fixture_unexpected_verifier'); }, - checkTask: async () => { throw new Error('fixture_unexpected_verifier'); } } } }); - instances.push(instance); return instance; - }; - const task = async () => { - const action = await cooperative.next(peer, budget); - if (action?.kind !== 'task') throw new Error('fixture_expected_task'); - expect(cooperative.started(peer, action)).toBe(true); - Object.assign(state.workers![1], { sessionRole: 'researcher', sessionTaskId: action.task.id, - sessionTaskVersion: taskVersion(action.task), sessionGroupId: action.task.groupId ?? 'main' }); - return action; - }; - const saveDraft = async () => { - const action = await task(); saveFinding(); - const commit = commitSolverSources(problem, peer.worktree); - // Isolate draft recovery from the scheduler's partial-publication protocol. - await cooperative.deliver(peer, action, commit, true, 'request-failure'); - return { action, commit }; - }; - const edit = async (statuses: Record) => { - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: `edit_${++sequence}`, - baseVersion: state.cooperation!.planVersion, - tasks: state.cooperation!.tasks.map(node => ({ ...node.task, status: statuses[node.task.id] ?? node.task.status })), - groups: state.cooperation!.groups!.map(route => route.group) }) + '\n'); - await cooperative.pulse(); - expect(state.cooperation!.edits!.at(-1)!.status, JSON.stringify(state.cooperation!.edits!.at(-1))).toBe('applied'); - }; - const switchTask = async () => { - await edit({ first_route: 'paused', second_route: 'active' }); - const other = await task(); expect(other.task.id).toBe('second_route'); - expect(fs.readFileSync(notes(), 'utf8')).not.toContain('FIRST_ROUTE_FINDING'); - write(peer, { summary: 'SECOND_ROUTE_FINDING', conclusion: 'inconclusive' }); - await cooperative.deliver(peer, other, commitSolverSources(problem, peer.worktree)); - await edit({ first_route: 'active', second_route: 'paused' }); - }; - const restart = async () => { - const file = path.join(directory, 'saved-state.json'); fs.writeFileSync(file, JSON.stringify(state)); - state = readSolverRunState(file); cooperative = create(); await cooperative.restore(); - }; - const advanceCanonical = async () => { - const previous = state.cooperation!.canonicalCommit!; - fs.writeFileSync(source(lead), fs.readFileSync(source(lead), 'utf8').replace('by sorry', 'by rfl')); - write(lead, { tasks: state.cooperation!.tasks.map(node => node.task), groups: state.cooperation!.groups!.map(route => route.group) }); - await cooperative.deliver(lead, { kind: 'lead', seedCommit: previous, planVersion: state.cooperation!.planVersion }, - commitSolverSources(problem, lead.worktree)); - }; - const duringRestore = (commit: string, hook: () => Promise) => { - const original = problemSource.withSolverWorktree; - let armed = true; - vi.spyOn(problemSource, 'withSolverWorktree').mockImplementation(async (worktree: string, version: string, - run: (checkout: string) => Promise): Promise => { - const selected = armed && version === commit; - if (selected) armed = false; - try { return await original(worktree, version, run); } - finally { if (selected) await hook(); } - }); - }; - const connectionTask = async (kind: 'goal' | 'lemma') => { - const worktree = path.join(directory, 'input_prover'); - git(lead.worktree, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const input: ResearchWorker = { id: 'input_prover', role: 'prover', worktree, ownedFiles: problem.ownedFiles }; - inputWorkers.push(input); - state.workers!.push({ ...input, phase: 'running', turns: 0 }); - node('first_route').task = { ...node('first_route').task, kind: 'lemma', objective: 'Prove the connection input', - groupId: 'main', ownerId: input.id, theoremName: 'Tutorial.helper', type: 'True', proofPath: 'Submission.lean' }; - for (const target of state.cooperation!.tasks.filter(item => item.task.kind === 'goal')) - target.task = { ...target.task, status: target.task.id === 'goal_1' ? 'active' : 'paused', - groupId: 'main', ownerId: peer.id }; - if (kind === 'lemma') { - const consumer: CooperativeTask = { id: 'consumer', kind: 'lemma', objective: 'Connect the unfinished input', - type: 'True', theoremName: 'Tutorial.consumer', proofPath: 'Submission.lean', dependsOn: ['first_route'], - groupId: 'main', ownerId: peer.id, revision: 0 }; - state.cooperation!.tasks.push({ task: consumer, status: 'pending', attempts: 0 }); - node('goal_1').task = { ...node('goal_1').task, dependsOn: [consumer.id], conditional: false }; - } - write(lead, { tasks: state.cooperation!.tasks.map(item => item.task), groups: state.cooperation!.groups!.map(item => item.group) }); - cooperative = create(); await cooperative.restore(); - return kind === 'goal' ? 'goal_1' : 'consumer'; - }; - const connectionDraft = async (kind: 'goal' | 'lemma') => { - const id = await connectionTask(kind), action = await task(); - expect(action.task.id).toBe(id); - expect(taskConnectionCheckCurrent(action.task, action.assignment, state.cooperation!.tasks, - { environmentDigest: state.environmentDigest, problemReceiptDigest: problem.receiptDigest })).toBe(true); - const support = 'lemma connection_support : True := by\n exact Tutorial.helper\n'; - let draftSource = fs.readFileSync(source(), 'utf8').replace('theorem add_zero', support + - (kind === 'lemma' ? 'lemma consumer : True := by\n have input : True := Tutorial.helper\n sorry\n' : '') + 'theorem add_zero'); - if (kind === 'goal') draftSource = draftSource.replace('n + 0 = n := by sorry', - 'n + 0 = n := by\n have input : True := Tutorial.helper\n sorry'); - const draftNotes = `Connection draft for ${id}: preserve the exact application and the remaining obligation.\n` + - '```lean\nlemma probe : True := by exact Tutorial.helper\n```\n'; - fs.writeFileSync(source(), draftSource); fs.writeFileSync(notes(), draftNotes); - const commit = commitSolverSources(problem, peer.worktree); - cooperative.retainContextDraft(peer, action, commit, 'connection'); - cooperative.interrupted(peer, action); - expect(node(id).status).toBe('pending'); - expect(state.cooperation!.researchDrafts![id]).toMatchObject({ commit, - assignmentId: action.assignment.assignmentId, taskDigest: taskVersion(action.task) }); - expect(state.cooperation!.researchCheckpoints?.[id]).toBeUndefined(); - return { id, action, commit, draftSource, draftNotes }; - }; - const switchConnectionTask = async (id: string) => { - await edit({ [id]: 'paused', second_route: 'active' }); - const other = await task(); expect(other.task.id).toBe('second_route'); - expect(fs.readFileSync(source(), 'utf8')).not.toContain('connection_support'); - write(peer, { summary: 'SECOND_ROUTE_FINDING', conclusion: 'inconclusive' }); - await cooperative.deliver(peer, other, commitSolverSources(problem, peer.worktree), true); - await edit({ [id]: 'active', second_route: 'paused' }); - }; - beforeEach(async () => { - sequence = 0; inputWorkers = []; - const example = localExample('solver-research-drafts-', 'lead'); - ({ directory, problem } = example); - lead = leadWorker(problem, example.workspace); peer = peerWorker(example, 'researcher'); - state = solverState(problem, example.workspace, { runId: 'research-drafts-fixture', phase: 'running', - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture', - workers: [lead, peer].map(worker => ({ ...worker, phase: 'running', turns: 0 })) }); - write(lead, { tasks: [ - { id: 'first_route', kind: 'research', objective: 'Investigate the first route', groupId: 'a', sharing: 'problem' }, - { id: 'second_route', kind: 'research', objective: 'Investigate the second route', groupId: 'b', status: 'paused' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index + 1}`, kind: 'goal', - objective: target.theoremName, proofPath: target.proofPath, theoremName: target.theoremName, dependsOn: ['first_route'] })), - ], groups: ['main', 'a', 'b'].map(id => ({ id, objective: id })) }); - cooperative = create(); await cooperative.restore(); - }); - afterEach(async () => { - for (const instance of instances.splice(0)) await instance.stop(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['research', 'sketch'] as const)('delivers a structured %s checkpoint to the Lead without completing its assignment', async kind => { - node('first_route').task = { ...node('first_route').task, kind }; - const action = await task(); - action.assignment.researchBasis = captureResearchBasis(action.task, { problemReceiptDigest: problem.receiptDigest, - environmentDigest: state.environmentDigest, tasks: state.cooperation!.tasks, - sourceDigest: researchSourceDigest(Object.fromEntries(problem.ownedFiles.map(file => [file, - committedSource(peer.worktree, action.assignment.seedCommit, `${problem.projectRelative}/${file}`)]))) }); - saveFinding(); - const fullNotes = fs.readFileSync(notes(), 'utf8'); - const commit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, commit, true, 'scheduling-checkpoint'); - const [delivery] = state.cooperation!.deliveries!.filter(record => record.kind === 'research'); - expect(delivery).toMatchObject({ taskId: 'first_route', taskDigest: taskVersion(action.task), commit, - summary: 'FIRST_ROUTE_FINDING', lemmaRequests: [{ id: 'bridge' }], - artifacts: { scope: 'advisory-unverified', commit }, researchRecord: { complete: false, basis: action.assignment.researchBasis } }); - expect(JSON.parse(delivery.finding!)).toMatchObject({ needsDecision: true, conclusion: 'supporting' }); - expect(committedSource(lead.worktree, commit, 'RESEARCH.md')).toBe(fullNotes); - expect(fs.readFileSync(notes(), 'utf8')).toBe(fullNotes); - expect(node('first_route')).toMatchObject({ status: 'pending', assignment: action.assignment }); - expect(node('first_route').finding).toBeUndefined(); - expect(node('first_route').researchCompletion).toBeUndefined(); - expect(node('first_route').proof).toBeUndefined(); expect(state.check).toBeUndefined(); - expect(state.cooperation!.researchDrafts!.first_route.commit).toBe(commit); - expect(leadWakePending(state.cooperation!.leadWakes!)).toBe(true); - const leadAction = await cooperative.next(lead, budget); - expect(leadAction?.kind).toBe('lead'); - expect(cooperative.contextState(leadAction!, lead).leadResearchInputIds).toContain(delivery.id); - const resumed = await task(); - expect(resumed.assignment).toBe(action.assignment); - expect(fs.readFileSync(notes(), 'utf8')).toBe(fullNotes); - }); - - it('includes a scoped checkpoint finding in live notices to its consumers', async () => { - const example = { directory, workspace: lead.worktree, problem }; - const consumer = peerWorker(example, 'consumer', { role: 'engineer' }); - const other = peerWorker(example, 'other'); - inputWorkers.push(consumer, other); - state.workers!.push(...inputWorkers.map(worker => ({ ...worker, phase: 'running' as const, turns: 0 }))); - const goal = node('goal_1'), research = node('first_route'), unrelated = node('second_route'); - research.task = { ...research.task, consumerGoalIds: [goal.task.id], ownerId: peer.id }; - goal.task = { ...goal.task, dependsOn: [], ownerId: consumer.id }; - unrelated.task = { ...unrelated.task, status: 'active', ownerId: other.id }; - cooperative = create(); - const action = await task(); - const activate = async (worker: ResearchWorker, taskId: string) => { - const work = await cooperative.next(worker, budget); - expect(work).toMatchObject({ kind: 'task', task: { id: taskId } }); - expect(cooperative.started(worker, work!)).toBe(true); - const notify = vi.fn(async () => {}); - cooperative.activate(worker, work!, async () => {}, notify); - return notify; - }; - const consumerNotice = await activate(consumer, goal.task.id); - const otherNotice = await activate(other, unrelated.task.id); - write(peer, { summary: 'FIRST_ROUTE_FINDING', conclusion: 'supporting', remainingObligations: ['Exact missing inequality'] }); - await cooperative.deliver(peer, action, commitSolverSources(problem, peer.worktree), true, 'scheduling-checkpoint'); - - const delivery = state.cooperation!.deliveries?.find(record => record.kind === 'research'); - expect(delivery, JSON.stringify(state.cooperation!.deliveryReceipts)).toMatchObject({ - taskId: 'first_route', status: 'conditional', summary: 'FIRST_ROUTE_FINDING', - }); - const notice = `Cooperation update: research ${delivery!.id}, task first_route, status conditional.`; - expect(consumerNotice).toHaveBeenCalledWith(expect.stringContaining( - '{"summary":"FIRST_ROUTE_FINDING","remainingObligations":["Exact missing inequality"]}'), { mode: 'advisory' }); - expect(otherNotice).toHaveBeenCalledWith(expect.stringContaining(notice), { mode: 'advisory' }); - expect(otherNotice.mock.calls.flat().join(' ')).not.toContain('FIRST_ROUTE_FINDING'); - }); - - it.each([ - 'The local boundary case is proved; the uniform inference is still unknown.', - 'Illustrative graph only.\n```json\n{"nodes":["boundary","uniform"]}\n```\n', - '```math-result\n{"summary":\n```\n', - '```math-plan\n{"tasks":[]}\n```\n', - ])('retains an unstructured or unfinished checkpoint without publishing it: %s', async text => { - const action = await task(); fs.writeFileSync(notes(), text); - const commit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, commit, true); - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(node('first_route')).toMatchObject({ status: 'pending', assignment: action.assignment }); - expect(state.cooperation!.researchDrafts!.first_route.commit).toBe(commit); - expect(committedSource(peer.worktree, commit, 'RESEARCH.md')).toBe(text); - }); - - it('deduplicates the same finding and Lean evidence despite note formatting and offset changes', async () => { - const action = await task(); saveFinding(); - await cooperative.deliver(peer, action, commitSolverSources(problem, peer.worktree), true); - const previous = state.cooperation!.deliveries!.filter(record => record.kind === 'research'); - const wakes = state.cooperation!.leadWakes!.requested; - const resumed = await task(); - const reversed = Object.fromEntries(Object.entries(finding()).reverse()); - write(peer, reversed, leanProbe); - fs.writeFileSync(notes(), '# Expanded explanation before the same finding.\n\n' + fs.readFileSync(notes(), 'utf8')); - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree), true); - expect(state.cooperation!.deliveries!.filter(record => record.kind === 'research')).toEqual(previous); - expect(state.cooperation!.leadWakes!.requested).toBe(wakes); - expect(node('first_route').status).toBe('pending'); - }); - - it('ignores a merged research submission ID on replay after restart', async () => { - const snapshot = path.join(directory, 'before-delivery-cursor.json'); - let replay: { key: string; offset: number } | undefined; - cooperative = create(state, current => { - if (replay && current.cooperation?.cursors?.[replay.key] === replay.offset) - writeSolverRunState(snapshot, current); - }); - const action = await task(); - cooperative.activate(peer, action, async () => {}, async () => {}); - const file = assignmentDeliveryFile(action.assignment), log = path.join(peer.worktree, file); - const value = { kind: 'research', finding: { conclusion: 'inconclusive', needsDecision: true, - summary: 'The same boundary finding delivered twice.' } }; - const append = (id: string, finding = value.finding) => fs.appendFileSync(log, JSON.stringify({ ...value, id, finding }) + '\n'); - const published = () => state.cooperation!.deliveries!.filter(record => record.kind === 'research'); - append('first_submission'); - await cooperative.pulse(peer.id); - expect(published()).toHaveLength(1); - const [delivery] = published(); - replay = { key: `${peer.id}/${file}`, offset: fs.statSync(log).size }; - append('merged_submission'); - await cooperative.pulse(peer.id); - expect(published().map(record => record.id)).toEqual([delivery.id]); - - // Recover from the save that preceded advancing past the second JSONL entry. - state = readSolverRunState(snapshot); - expect(state.cooperation!.cursors![replay.key]).toBe(replay.offset); - cooperative = create(); await cooperative.restore(); - const resumed = await task(); - expect(assignmentDeliveryFile(resumed.assignment)).toBe(file); - cooperative.activate(peer, resumed, async () => {}, async () => {}); - const freeze = vi.spyOn(problemSource, 'withSolverWorktree'); - await cooperative.pulse(peer.id); - expect(state.cooperation!.cursors![replay.key]).toBe(fs.statSync(log).size); - - append('merged_submission', { ...value.finding, summary: 'Changed text under the same submission ID.' }); - await cooperative.pulse(peer.id); - expect.soft(freeze).not.toHaveBeenCalled(); - expect(published().map(record => [record.id, record.summary])).toEqual([[delivery.id, value.finding.summary]]); - }); - - it.each([{ needsDecision: true }, {}])('deduplicates a checkpoint finding across both submission paths after restart (%j)', async decision => { - const value = { ...finding(), ...decision }; - const action = await task(); - action.assignment.researchBasis = captureResearchBasis(action.task, { problemReceiptDigest: problem.receiptDigest, - environmentDigest: state.environmentDigest, tasks: state.cooperation!.tasks, - sourceDigest: researchSourceDigest(Object.fromEntries(problem.ownedFiles.map(file => [file, - committedSource(peer.worktree, action.assignment.seedCommit, `${problem.projectRelative}/${file}`)]))) }); - write(peer, value, leanProbe); - const checkpointCommit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, checkpointCommit, true, 'scheduling-checkpoint'); - const published = () => state.cooperation!.deliveries!.filter(record => record.kind === 'research' && record.status !== 'superseded'); - const inbox = () => leadResearchInputs(published(), new Map(state.cooperation!.tasks.map(node => [node.task.id, node])), - state.cooperation!.researchDecisions); - const [checkpoint] = published(); - expect(checkpoint.researchRecord?.complete).toBe(false); - expect(inbox()).toEqual([checkpoint]); - - await restart(); - const resumed = await task(); - expect(resumed.assignment.assignmentId).toBe(action.assignment.assignmentId); - const wakes = state.cooperation!.leadWakes!.requested; - cooperative.activate(peer, resumed, async () => {}, async () => {}); - fs.appendFileSync(path.join(peer.worktree, assignmentDeliveryFile(resumed.assignment)), - JSON.stringify({ kind: 'research', finding: value, commit: checkpointCommit }) + '\n'); - await cooperative.pulse(peer.id); - expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); - expect(published()).toHaveLength(1); - expect(inbox().map(record => record.id)).toEqual([checkpoint.id]); - expect(state.cooperation!.leadWakes!.requested).toBe(wakes); - expect(node('first_route').status).toBe('running'); - - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree)); - expect(node('first_route')).toMatchObject({ status: 'completed', researchCompletion: { complete: true } }); - expect(published()).toHaveLength(1); - expect(published()[0]).toMatchObject({ id: checkpoint.id, findingDigest: checkpoint.findingDigest }); - expect(published()[0].researchRecord).toEqual(node('first_route').researchCompletion); - expect(inbox()).toHaveLength(1); - expect(state.cooperation!.leadWakes!.requested).toBe(wakes); - }); - - it.each(['refuted', 'supporting'] as const)('reuses the explicit %s finding when a later checkpoint requests Lead review', async conclusion => { - const value = { conclusion, summary: 'The exact local case and its probe.', - leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['Candidate.probe'] }] }; - const action = await task(); - write(peer, value, leanProbe); - const commit = commitSolverSources(problem, peer.worktree); - const archive = () => state.cooperation!; - const published = () => (archive().deliveries ?? []).filter(record => record.kind === 'research' && record.status !== 'superseded'); - const inbox = () => leadResearchInputs(published(), new Map(archive().tasks.map(node => [node.task.id, node])), - archive().researchDecisions).map(record => record.id); - - cooperative.activate(peer, action, async () => {}, async () => {}); - fs.appendFileSync(path.join(peer.worktree, assignmentDeliveryFile(action.assignment)), - JSON.stringify({ kind: 'research', finding: value, commit }) + '\n'); - await cooperative.pulse(peer.id); - expect(archive().deliveryReceipts ?? []).toEqual([]); - expect(published()).toHaveLength(1); - const { id, finding, findingDigest, commit: publicationCommit } = published()[0]; - expect(inbox()).toEqual(conclusion === 'refuted' ? [id] : []); - const wakes = archive().leadWakes!.requested; - cooperative.deactivate(peer); - - await cooperative.deliver(peer, action, commit, true, 'scheduling-checkpoint'); - expect(published()).toHaveLength(1); - expect(published()[0]).toMatchObject({ id, finding, findingDigest, commit: publicationCommit }); - expect(inbox()).toEqual([id]); - expect(archive().leadWakes!.requested).toBe(wakes + (conclusion === 'supporting' ? 1 : 0)); - expect(node('first_route').status).toBe('pending'); - - await restart(); - expect(inbox()).toEqual([id]); - const resumed = await task(); - const resumedWakes = archive().leadWakes!.requested; - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree), true, 'scheduling-checkpoint'); - expect(published()).toHaveLength(1); - expect(inbox()).toEqual([id]); - expect(archive().leadWakes!.requested).toBe(resumedWakes); - }); - - it('keeps checkpoint publications scoped and deduplicated through task switches and process recovery', async () => { - const value = { summary: 'Exact boundary established; uniform inference remains open.', conclusion: 'inconclusive', - remainingObligations: ['Prove the uniform implication or request a narrower typed helper.'] }; - const first = await task(); write(peer, value); - await cooperative.deliver(peer, first, commitSolverSources(problem, peer.worktree), true); - await edit({ first_route: 'paused', second_route: 'active' }); - const second = await task(); expect(second.task.id).toBe('second_route'); - expect(fs.readFileSync(notes(), 'utf8')).not.toContain(value.summary); - write(peer, value); - await cooperative.deliver(peer, second, commitSolverSources(problem, peer.worktree), true); - expect(state.cooperation!.deliveries!.filter(record => record.kind === 'research').map(record => record.taskId)) - .toEqual(['first_route', 'second_route']); - await edit({ first_route: 'active', second_route: 'paused' }); await restart(); - const resumed = await task(); expect(resumed.task.id).toBe('first_route'); - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree), true); - const records = state.cooperation!.deliveries!.filter(record => record.kind === 'research'); - expect(records).toHaveLength(2); - for (const record of records) expect(JSON.parse(record.finding!)).toMatchObject({ taskId: record.taskId, taskDigest: record.taskDigest }); - expect(leadResearchInputs(records, new Map(state.cooperation!.tasks.map(node => [node.task.id, node])))).toHaveLength(2); - expect(node('first_route').status).toBe('pending'); - }); - - it('rejects a structured finding for another task while preserving its recoverable draft', async () => { - const action = await task(); - write(peer, { taskId: 'second_route', summary: 'Misattributed boundary finding.', conclusion: 'inconclusive' }); - const commit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, commit, true); - expect(state.cooperation!.deliveries?.filter(record => record.kind === 'research') ?? []).toEqual([]); - expect(state.cooperation!.deliveryReceipts).toContainEqual(expect.objectContaining({ status: 'needs-correction', - taskId: 'first_route', issues: [expect.objectContaining({ path: 'taskId' })] })); - expect(state.cooperation!.researchDrafts!.first_route.commit).toBe(commit); - expect(node('first_route')).toMatchObject({ status: 'pending', assignment: action.assignment }); - }); - - it('delivers an exact gap and partial check finding without prematurely settling the scoped investigation', async () => { - const checker: ResearchWorker = { ...peer, id: 'checker', worktree: path.join(directory, 'checker') }; - git(lead.worktree, ['worktree', 'add', '--quiet', '--detach', checker.worktree, problem.baseCommit]); - inputWorkers.push(checker); state.workers!.push({ ...checker, phase: 'running', turns: 0 }); - cooperative = create(); await cooperative.restore(); - node('goal_1').task = { ...node('goal_1').task, sharing: 'problem', status: 'paused' }; - const action = await task(); - const gap = { consumer: { taskId: 'goal_1', taskDigest: taskVersion(node('goal_1').task) }, - previousGap: 'The construction needs a uniform estimate.', reduced: 'The boundary case is established.', - remaining: 'Prove the estimate for the exact original quantifiers.', evidenceScope: 'The present local argument only.', - reconsiderWhen: ['A uniform estimate with its stated assumptions.'], - nextCheck: { action: 'construction-check', targetTaskId: 'first_route', objective: 'Check the missing uniform implication.', - expectedEvidence: 'An exact local inference or the remaining unsupported hypothesis.' } }; - write(peer, { summary: 'The precise uniform gap is ready for independent investigation.', conclusion: 'inconclusive', mathematicalGap: gap }); - await cooperative.deliver(peer, action, commitSolverSources(problem, peer.worktree), true); - expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); - expect(state.cooperation!.deliveries!.filter(record => record.kind === 'research')).toHaveLength(1); - const record = state.cooperation!.nextChecks![0]; - expect(record.status).toBe('pending'); expect(node('first_route').status).toBe('pending'); - expect(cooperative.contextState(undefined, lead).mathematicalGaps).toContainEqual(expect.objectContaining({ - remaining: gap.remaining, scopeStatus: 'current-contracts', evidence: 'model-reported-advisory' })); - const checkTurn = async () => { - const next = await cooperative.next(checker, budget); - if (next?.kind !== 'task' || next.task.id !== record.taskId) throw new Error('fixture_expected_scoped_check'); - expect(cooperative.started(checker, next)).toBe(true); return next; - }; - const partial = await checkTurn(); - write(checker, { summary: 'The uniform estimate is still under investigation.', conclusion: 'inconclusive', - remainingObligations: ['Test the exact uniform implication before reporting its outcome.'] }); - await cooperative.deliver(checker, partial, commitSolverSources(problem, checker.worktree), true); - expect(record.status).toBe('pending'); expect(node(record.taskId).status).toBe('pending'); - expect(state.cooperation!.deliveries!.filter(delivery => delivery.taskId === record.taskId && delivery.kind === 'research')).toHaveLength(1); - const resumed = await checkTurn(); - write(checker, { summary: 'The scoped check result remains inconclusive.', conclusion: 'inconclusive', - checkOutcome: { checkId: record.id, summary: 'The current assumptions leave the uniform implication unresolved.', - conclusion: 'inconclusive', evidenceRefs: [] } }); - const outcomeCommit = commitSolverSources(problem, checker.worktree); - await cooperative.deliver(checker, resumed, outcomeCommit, true); - expect(record.status).toBe('pending'); expect(node(record.taskId).status).toBe('pending'); - expect(node(record.taskId).researchCompletion).toBeUndefined(); - expect(state.cooperation!.researchDrafts![record.taskId].commit).toBe(outcomeCommit); - expect(state.cooperation!.deliveries!.filter(delivery => delivery.taskId === record.taskId && delivery.kind === 'research')).toHaveLength(1); - const completed = await checkTurn(); - await cooperative.deliver(checker, completed, commitSolverSources(problem, checker.worktree)); - expect(record.status).toBe('awaiting-decision'); expect(record.outcome?.conclusion).toBe('inconclusive'); - expect(node(record.taskId).status).toBe('completed'); expect(node('first_route').status).toBe('pending'); - expect(state.cooperation!.tasks.some(node => node.proof || node.integratedCheck)).toBe(false); - }); - - it('does not publish or reset an assignment superseded during checkpoint admission checks', async () => { - const action = await task(); saveFinding(); - const entered = deferred(), checked = deferred<[]>(); - vi.spyOn(knowledgeApplications, 'checkKnowledgeApplications').mockImplementation(() => { entered.resolve(); return checked.promise; }); - const pending = cooperative.deliver(peer, action, commitSolverSources(problem, peer.worktree), true); - await entered.promise; - const replacement = { ...action.assignment, assignmentId: 'replacement-research' }; - node('first_route').assignment = replacement; - checked.resolve([]); await pending; - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(node('first_route')).toMatchObject({ status: 'running', assignment: replacement }); - }); - - it('restores an imported draft on a different branch with its original frozen seed ancestry', async () => { - fs.writeFileSync(notes(), 'The old assignment inherited these exact input notes.'); - const seed = commitSolverSources(problem, peer.worktree); - const { action, commit } = await saveDraft(); - expect(action.assignment.seedCommit).toBe(seed); - git(peer.worktree, ['reset', '--hard', problem.baseCommit]); - fs.writeFileSync(notes(), 'The continuation worker begins on a different branch.'); - const newHead = commitSolverSources(problem, peer.worktree); - expect(() => git(peer.worktree, ['merge-base', '--is-ancestor', seed, newHead])).toThrow(); - state.cooperation!.researchDrafts!.first_route.suspended = true; - await restart(); - const resumed = await task(); - expect(resumed.assignment).toMatchObject({ assignmentId: action.assignment.assignmentId, seedCommit: seed }); - expect(git(peer.worktree, ['rev-parse', 'HEAD'])).toBe(commit); - expect(git(peer.worktree, ['merge-base', '--is-ancestor', seed, 'HEAD'])).toBe(''); - expect(fs.readFileSync(notes(), 'utf8')).toContain('FIRST_ROUTE_FINDING'); - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree), true); - expect(state.cooperation!.deliveries!.filter(record => record.kind === 'research')).toHaveLength(1); - expect(state.cooperation!.researchDrafts!.first_route).toMatchObject({ seedCommit: seed, commit }); - expect(node('first_route').status).toBe('pending'); expect(state.check).toBeUndefined(); - }); - - it.each(['research', 'sketch'] as const)('restores a %s draft after another task and process restart', async kind => { - node('first_route').task = { ...node('first_route').task, kind }; - const { action, commit } = await saveDraft(); - expect(node('first_route').status).toBe('pending'); - expect(state.cooperation!.researchDrafts!.first_route).toMatchObject({ commit, workerId: peer.id, - seedCommit: action.assignment.seedCommit, taskDigest: taskVersion(action.task), - artifacts: { scope: 'advisory-unverified', artifacts: [{ kind: 'notes-lean' }] } }); - expect(git(lead.worktree, ['rev-parse', `refs/math/${state.runId}/evidence/${commit}`])).toBe(commit); - expect(pendingProposals()).toEqual([]); - expect(directSolverModules.M3.ready(state.cooperation!.tasks, state.cooperation!.groups).some(node => node.task.kind === 'goal')).toBe(false); - await switchTask(); await restart(); - const resumed = await task(); expect(resumed.task.id).toBe('first_route'); - expect(resumed.task.kind).toBe(kind); - expect(fs.readFileSync(notes(), 'utf8')).toContain('FIRST_ROUTE_FINDING'); - expect(fs.readFileSync(notes(), 'utf8')).not.toContain('SECOND_ROUTE_FINDING'); - expect(node('first_route').status).toBe('running'); - expect(pendingProposals()).toEqual([]); - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree)); - expect(node('first_route').status).toBe('completed'); - expect(state.cooperation!.deliveries!.filter(delivery => delivery.kind === 'research' && delivery.taskId === 'first_route')) - .toMatchObject([{ summary: 'FIRST_ROUTE_FINDING', artifacts: { reportedChecks: [{ status: 'passed' }] }, lemmaRequests: [{ id: 'bridge' }] }]); - expect(pendingProposals()).toHaveLength(1); - expect(state.cooperation!.tasks.filter(node => node.task.kind === 'goal').every(node => node.status === 'pending')).toBe(true); - }); - - it.each(['goal', 'lemma'] as const)('restores an unfinished %s connection draft after another task and process restart', async kind => { - const { id, action, commit, draftSource, draftNotes } = await connectionDraft(kind); - await switchConnectionTask(id); await restart(); - const resumed = await task(); - expect(resumed.task.id).toBe(id); - expect(resumed.assignment.assignmentId).toBe(action.assignment.assignmentId); - expect(resumed.assignment.connectionCheck).toEqual(action.assignment.connectionCheck); - expect(taskConnectionCheckCurrent(resumed.task, resumed.assignment, state.cooperation!.tasks, - { environmentDigest: state.environmentDigest, problemReceiptDigest: problem.receiptDigest })).toBe(true); - expect(fs.readFileSync(source(), 'utf8')).toBe(draftSource); - expect(fs.readFileSync(notes(), 'utf8')).toBe(draftNotes); - expect(state.cooperation!.researchDrafts![id].suspended).toBeUndefined(); - expect(state.cooperation!.researchDrafts![id]).toMatchObject({ - assignmentId: resumed.assignment.assignmentId, seedCommit: resumed.assignment.seedCommit }); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ kind: 'progress', status: 'advisory', - taskId: id, commit, artifacts: expect.objectContaining({ scope: 'advisory-unverified' }) })); - expect(node(id)).toMatchObject({ status: 'running', attempts: 2 }); - expect(node(id).proof).toBeUndefined(); - expect(node(id).integratedCheck).toBeUndefined(); - expect(pendingProposals()).toEqual([]); - }); - - it.each(['goal', 'lemma'] as const)('renews a %s connection after canonical changes while retaining its old draft as advisory evidence', async kind => { - const { id, action, commit, draftNotes } = await connectionDraft(kind); - await switchConnectionTask(id); await advanceCanonical(); await restart(); - const resumed = await task(); - expect(resumed.task.id).toBe(id); - expect(resumed.assignment.assignmentId).not.toBe(action.assignment.assignmentId); - expect(resumed.assignment.seedCommit).not.toBe(action.assignment.seedCommit); - expect(resumed.assignment.canonicalCommit).toBe(state.cooperation!.canonicalCommit); - expect(resumed.assignment.connectionCheck!.seedCommit).toBe(resumed.assignment.seedCommit); - expect(resumed.assignment.connectionCheck!.basisDigest).not.toBe(action.assignment.connectionCheck!.basisDigest); - expect(state.cooperation!.researchDrafts![id]).toMatchObject({ assignmentId: resumed.assignment.assignmentId, - seedCommit: resumed.assignment.seedCommit, canonicalCommit: resumed.assignment.canonicalCommit }); - expect(taskConnectionCheckCurrent(resumed.task, resumed.assignment, state.cooperation!.tasks, - { environmentDigest: state.environmentDigest, problemReceiptDigest: problem.receiptDigest })).toBe(true); - expect(cooperative.current(action)).toBe(false); - expect(fs.readFileSync(source(), 'utf8')).toContain('by rfl'); - expect(fs.readFileSync(source(), 'utf8')).not.toContain('connection_support'); - expect(fs.readFileSync(notes(), 'utf8')).toBe(draftNotes); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ kind: 'progress', status: 'advisory', - taskId: id, commit, artifacts: expect.objectContaining({ scope: 'advisory-unverified' }), remainingObligations: [id] })); - expect(node(id).proof).toBeUndefined(); - expect(node(id).integratedCheck).toBeUndefined(); - expect(pendingProposals()).toEqual([]); - const canonicalSource = fs.readFileSync(source(), 'utf8'); - - // A crash before the next model checkpoint must still retain the restored notes. - cooperative.interrupted(peer, resumed); - await switchConnectionTask(id); await restart(); - const recovered = await task(); - expect(recovered.task.id).toBe(id); - expect(recovered.assignment.assignmentId).toBe(resumed.assignment.assignmentId); - expect(recovered.assignment.connectionCheck).toEqual(resumed.assignment.connectionCheck); - expect(state.cooperation!.researchDrafts![id]).toMatchObject({ assignmentId: recovered.assignment.assignmentId, - seedCommit: recovered.assignment.seedCommit }); - expect(fs.readFileSync(source(), 'utf8')).toBe(canonicalSource); - expect(fs.readFileSync(notes(), 'utf8')).toBe(draftNotes); - }); - - it.each(['missing', 'empty'] as const)('preserves %s notes and checkpoint counts through another task and restart', async presence => { - const first = await task(); - fs.rmSync(notes(), { force: true }); - if (presence === 'empty') fs.writeFileSync(notes(), ''); - await cooperative.deliver(peer, first, commitSolverSources(problem, peer.worktree), true); - const previous = structuredClone(state.cooperation!.researchCheckpoints!.first_route); - expect(previous).toMatchObject({ count: 1, paused: false }); - - await switchTask(); await restart(); - const resumed = await task(); - expect(resumed.task.id).toBe('first_route'); - expect(fs.existsSync(notes())).toBe(presence === 'empty'); - if (presence === 'empty') expect(fs.readFileSync(notes(), 'utf8')).toBe(''); - expect(state.cooperation!.researchDrafts!.first_route.outputDigest).toBe(previous.outputDigest); - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree), true); - expect(state.cooperation!.researchCheckpoints!.first_route) - .toMatchObject({ count: 2, unchangedEvidenceCount: 2, paused: false, outputDigest: previous.outputDigest }); - - const third = await task(); - await cooperative.deliver(peer, third, commitSolverSources(problem, peer.worktree), true); - expect(node('first_route').status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.first_route).toMatchObject({ count: 3, paused: true }); - expect(node('goal_1').integratedCheck).toBeUndefined(); - }); - - it.each(['missing', 'saved'] as const)('keeps a paused task with %s notes parked while its worker awaits another task preflight', async presence => { - for (let attempt = 0; attempt < 3; attempt++) { - const action = await task(); - if (presence === 'saved') fs.writeFileSync(notes(), 'An unchanged saved investigation.'); - else fs.rmSync(notes(), { force: true }); - await cooperative.deliver(peer, action, commitSolverSources(problem, peer.worktree), true); - } - const paused = structuredClone(state.cooperation!.researchCheckpoints!.first_route); - expect(node('first_route').status).toBe('blocked'); - node('second_route').task = { ...node('second_route').task, kind: 'lemma', status: 'active', - theoremName: 'Tutorial.second_route', type: 'True', proofPath: 'Submission.lean' }; - const emit = vi.fn(); (cooperative as any).input.emit = emit; - let release!: () => void, entered!: () => void; - const waiting = new Promise(resolve => { release = resolve; }); - const started = new Promise(resolve => { entered = resolve; }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => { - entered(); await waiting; - return { current: () => true, result: { status: 'deferred', inputDigest: 'fixture-input', - taskDigest: taskVersion(input.task), reason: 'fixture-deferred', - evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } }; - }); - const preparation = cooperative.next(peer, budget); - await started; - try { - // The next model session is not installed until after preflight; its old task id is still present. - expect(state.workers![1].sessionTaskId).toBe('first_route'); - expect(node('second_route')).toMatchObject({ status: 'pending', attempts: 0 }); - expect(node('second_route').assignment).toBeUndefined(); - expect(state.cooperation!.researchDrafts!.first_route.suspended).toBe(true); - expect(fs.readFileSync(notes(), 'utf8')).toBe(''); - expect(node('first_route').status).toBe('blocked'); - expect(state.cooperation!.researchCheckpoints!.first_route).toEqual(paused); - expect(emit.mock.calls.some(([event]) => event === 'research_checkpoint_reopened')).toBe(false); - } finally { - release(); await preparation; - } - expect(node('second_route').status).toBe('running'); - expect(node('first_route').status).toBe('blocked'); - expect(node('first_route').attempts).toBe(3); - - // Suspension excludes the other task's output, but a real input change still reopens this investigation. - state.environmentDigest = 'new-environment'; - (cooperative as any).changed(); - expect(node('first_route').status).toBe('pending'); - expect(state.cooperation!.researchCheckpoints!.first_route).toBeUndefined(); - expect(emit).toHaveBeenCalledWith('research_checkpoint_reopened', { taskId: 'first_route', reason: 'new-input' }); - }); - - it('keeps request failures as saved drafts without increasing mathematical stagnation', async () => { - for (let index = 0; index < 4; index++) { - const action = await task(); saveFinding(); - await cooperative.deliver(peer, action, commitSolverSources(problem, peer.worktree), true, 'request-failure'); - expect(node('first_route').status).toBe('pending'); - expect(state.cooperation!.researchDrafts!.first_route.artifacts.artifacts).toHaveLength(1); - expect(state.cooperation!.researchCheckpoints?.first_route).toBeUndefined(); - } - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(pendingProposals()).toEqual([]); - expect(node('goal_1').attempts).toBe(0); - }); - - it('scopes saved drafts to visible task versions across groups', async () => { - const { action: first } = await saveDraft(); - await edit({ first_route: 'paused', second_route: 'active' }); - const second = await task(); - write(peer, { summary: 'SECOND_ROUTE_FINDING', conclusion: 'inconclusive' }); - await cooperative.deliver(peer, second, commitSolverSources(problem, peer.worktree), true); - const scoped = cooperative.contextState(second, peer); - expect(node('first_route').status).toBe('pending'); - expect(node('first_route').task.sharing).toBe('problem'); - expect(scoped.tasks.some(node => node.task.id === 'first_route')).toBe(false); - expect(Object.keys(scoped.researchDrafts ?? {})).toEqual(['second_route']); - expect(cooperative.contextState(first, peer).researchDrafts?.first_route).toBeDefined(); - state.cooperation!.researchDrafts!.second_route.taskDigest = 'stale-task-version'; - expect(cooperative.contextState(second, peer).researchDrafts).toEqual({}); - }); - - it('preserves a newer uncommitted checkpoint in the same task workspace', async () => { - await saveDraft(); - fs.writeFileSync(notes(), 'NEWER_UNCOMMITTED_FINDING'); - await restart(); - expect((await task()).task.id).toBe('first_route'); - expect(fs.readFileSync(notes(), 'utf8')).toBe('NEWER_UNCOMMITTED_FINDING'); - }); - - it.each(['legacy', 'task-version', 'assignment', 'dispatch-id', 'output-digest'] as const)('rejects %s snapshots after another responsibility', async mismatch => { - const { action } = await saveDraft(); - await switchTask(); - const draft = state.cooperation!.researchDrafts!.first_route; - if (mismatch === 'legacy') delete state.cooperation!.researchDrafts; - else if (mismatch === 'task-version') draft.taskDigest = 'obsolete-version'; - else if (mismatch === 'assignment') draft.seedCommit = git(peer.worktree, ['rev-parse', 'HEAD']); - else if (mismatch === 'dispatch-id') draft.assignmentId = 'obsolete-assignment'; - else draft.outputDigest = 'different-output'; - await restart(); - const resumed = await task(); - expect(resumed.assignment).not.toEqual(action.assignment); - expect(fs.readFileSync(notes(), 'utf8')).toBe(''); - expect(node('first_route').feedback).toContain('math_research_draft_unavailable'); - await cooperative.deliver(peer, resumed, commitSolverSources(problem, peer.worktree)); - expect(node('first_route').status).not.toBe('completed'); - expect(pendingProposals()).toEqual([]); - expect(state.cooperation!.deliveries!.some(delivery => delivery.kind === 'research' && delivery.taskId === 'first_route')).toBe(false); - }); - - it('keeps current canonical proofs while preserving a conflicting source draft as advisory evidence', async () => { - const action = await task(); saveFinding(); - fs.writeFileSync(source(), fs.readFileSync(source(), 'utf8').replace('by sorry', 'by exact unfinished_draft')); - const draftCommit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, draftCommit, true); - await switchTask(); - await advanceCanonical(); - const canonical = state.cooperation!.canonicalCommit!; - const resumed = await task(); - expect(fs.readFileSync(source(), 'utf8')).toContain('by rfl'); - expect(fs.readFileSync(source(), 'utf8')).not.toContain('unfinished_draft'); - expect(fs.readFileSync(notes(), 'utf8')).toContain('FIRST_ROUTE_FINDING'); - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ kind: 'progress', status: 'advisory', - taskId: 'first_route', commit: draftCommit, artifacts: expect.objectContaining({ scope: 'advisory-unverified' }) })); - expect(resumed.assignment.seedCommit).not.toBe(action.assignment.seedCommit); - expect(resumed.assignment.assignmentId).not.toBe(action.assignment.assignmentId); - expect(node('first_route').status).toBe('running'); - expect(pendingProposals()).toEqual([]); - }); - - it('does not restore a task paused while its snapshot is being read', async () => { - const { commit } = await saveDraft(); - await switchTask(); - duringRestore(commit, async () => { await edit({ first_route: 'paused' }); state.turns = 1; }); - await expect(cooperative.next(peer, { maxTurns: 1, remainingMs: Infinity })).resolves.toBeUndefined(); - expect(node('first_route').task.status).toBe('paused'); - expect(fs.readFileSync(notes(), 'utf8')).not.toContain('FIRST_ROUTE_FINDING'); - expect(state.cooperation!.researchDrafts!.first_route.suspended).toBe(true); - expect(pendingProposals()).toEqual([]); - }); - - it('rejects a feasibility draft when its reviewer becomes an input owner during the snapshot read', async () => { - node('first_route').task = { ...node('first_route').task, reviewScope: 'feasibility', dependsOn: ['goal_1'] }; - node('goal_1').task = { ...node('goal_1').task, sharing: 'problem', status: 'paused', dependsOn: [] }; - const action = await task(); - expect(action.task.id).toBe('first_route'); - saveFinding(); - fs.writeFileSync(source(), fs.readFileSync(source(), 'utf8').replace('by sorry', 'by exact first_route_source_draft')); - const commit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, commit, true); - await switchTask(); - fs.writeFileSync(notes(), 'CURRENT_UNCOMMITTED_NOTES'); - fs.writeFileSync(source(), fs.readFileSync(source(), 'utf8').replace('by sorry', 'by exact current_uncommitted_source')); - const currentSource = fs.readFileSync(source(), 'utf8'), head = git(peer.worktree, ['rev-parse', 'HEAD']); - const canonical = state.cooperation!.canonicalCommit; - const restore = vi.spyOn(cooperative as any, 'restoreResearchDraft'); - duringRestore(commit, async () => { - node('goal_1').task = { ...node('goal_1').task, ownerId: peer.id }; - state.turns = 1; - }); - - await expect(cooperative.next(peer, { maxTurns: 1, remainingMs: Infinity })).resolves.toBeUndefined(); - - expect(restore).toHaveBeenCalledTimes(1); - await expect(restore.mock.results[0].value).resolves.toBe(false); - expect(fs.readFileSync(notes(), 'utf8')).toBe('CURRENT_UNCOMMITTED_NOTES'); - expect(fs.readFileSync(source(), 'utf8')).toBe(currentSource); - expect(git(peer.worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(node('first_route').status).toBe('pending'); - expect(node('first_route').assignment).toBeUndefined(); - expect(cooperative.current(action)).toBe(false); - expect(state.cooperation!.researchDrafts!.first_route).toMatchObject({ commit, suspended: true }); - expect(state.cooperation!.canonicalCommit).toBe(canonical); - expect(node('goal_1').status).toBe('pending'); - expect(node('goal_1').proof).toBeUndefined(); - expect(node('goal_1').integratedCheck).toBeUndefined(); - expect(pendingProposals()).toEqual([]); - }); - - it('keeps repeated feasibility checkpoints as same-reviewer drafts without publishing or parking them', async () => { - node('first_route').task = { ...node('first_route').task, reviewScope: 'feasibility' }; - const action = await task(); - const text = 'Search scope: only the finite case; no infinite extension was found.\n' + - 'Reproduce .scratch/tmp/Probe1.lean with lake env lean .scratch/tmp/Probe1.lean\n' + - '```lean\nexample : True := by trivial\n```\n' + - '```math-result\n{"conclusion":"supporting","summary":"Provisional observation only"}\n```\n'; - fs.writeFileSync(notes(), text); - for (let i = 0; i < 4; ++i) { - const current = i ? await task() : action; - await cooperative.deliver(peer, current, commitSolverSources(problem, peer.worktree), true, 'scheduling-checkpoint'); - } - expect(node('first_route').status).toBe('pending'); - expect(node('first_route').finding).toBeUndefined(); expect(node('first_route').researchCompletion).toBeUndefined(); - expect(state.cooperation!.researchCheckpoints?.first_route).toBeUndefined(); - expect(state.cooperation!.deliveries?.some(record => record.kind === 'research') ?? false).toBe(false); - const draft = state.cooperation!.researchDrafts!.first_route; - await switchTask(); await restart(); - const resumed = await task(); - expect(resumed.assignment.assignmentId).toBe(action.assignment.assignmentId); - expect(fs.readFileSync(notes())).toEqual(Buffer.from(text)); - expect(state.cooperation!.researchDrafts!.first_route.feasibilityInputDigest).toBe(draft.feasibilityInputDigest); - expect(node('first_route').proof).toBeUndefined(); expect(state.check).toBeUndefined(); - }); - - it.each(['canonical', 'dependency', 'finding'] as const)('starts a fresh review after %s input changes and keeps the old draft archived', async change => { - node('first_route').task = { ...node('first_route').task, reviewScope: 'feasibility', dependsOn: ['goal_1'] }; - node('goal_1').task = { ...node('goal_1').task, sharing: 'problem', status: 'paused', dependsOn: [] }; - const action = await task(); fs.writeFileSync(notes(), 'OLD_REVIEW_INTERMEDIATE_NOTES\n'); - const commit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, commit, true, 'request-failure'); - if (change === 'canonical') await advanceCanonical(); - else if (change === 'dependency') node('goal_1').task = { ...node('goal_1').task, revision: 1 }; - else node('goal_1').finding = 'New inspected dependency evidence.'; - const resumed = await task(); - expect(resumed.assignment.assignmentId).not.toBe(action.assignment.assignmentId); - expect(resumed.assignment.feasibilityInputDigest).not.toBe(action.assignment.feasibilityInputDigest); - expect(fs.readFileSync(notes(), 'utf8')).toBe(''); - expect(state.cooperation!.researchDrafts!.first_route).toMatchObject({ commit, suspended: true }); - expect(committedSource(peer.worktree, commit, 'RESEARCH.md')).toBe('OLD_REVIEW_INTERMEDIATE_NOTES\n'); - expect(node('first_route').finding).toBeUndefined(); expect(node('first_route').researchCompletion).toBeUndefined(); - }); - - it.each(['plain lemma', 'following command', 'inspected name'] as const)('handles a canonical addition with a %s when resuming a review', async change => { - node('first_route').task = { ...node('first_route').task, reviewScope: 'feasibility', dependsOn: ['goal_1'] }; - node('goal_1').task = { ...node('goal_1').task, sharing: 'problem', status: 'paused', dependsOn: [], - ...(change === 'inspected name' ? { objective: 'Inspect fixtureAdded as a potential witness.' } : {}) }; - const notesText = 'Retained halfway through the finite check.\n'; - const first = await task(); - fs.writeFileSync(notes(), notesText); - const draftCommit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, first, draftCommit, true, 'request-failure'); - const original = fs.readFileSync(source(lead), 'utf8'); - const addition = 'lemma fixtureAdded : True := by trivial\n' + - (change === 'following command' ? ' attribute [simp] fixtureAdded\n' : '') + '\n'; - const current = original.replace('theorem add_zero', addition + 'theorem add_zero'); - fs.writeFileSync(source(lead), current); - state.cooperation!.canonicalCommit = commitSolverSources(problem, lead.worktree); - - const resumed = await task(); - expect(resumed.task.id).toBe('first_route'); - expect(resumed.assignment.canonicalCommit).toBe(state.cooperation!.canonicalCommit); - expect(resumed.assignment.feasibilityInputDigest).not.toBe(first.assignment.feasibilityInputDigest); - expect(fs.readFileSync(source(), 'utf8')).toBe(current); - expect(fs.readFileSync(notes(), 'utf8')).toBe(change === 'plain lemma' ? notesText : ''); - expect(committedSource(peer.worktree, draftCommit, 'RESEARCH.md')).toBe(notesText); - if (change === 'plain lemma') { - const commit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, resumed, commit, true, 'request-failure'); - expect((await task()).assignment.assignmentId).toBe(resumed.assignment.assignmentId); - expect(fs.readFileSync(notes(), 'utf8')).toBe(notesText); - } - }); - - it('starts a new reviewer with fresh notes while retaining the prior reviewer\'s pinned draft', async () => { - node('first_route').task = { ...node('first_route').task, reviewScope: 'feasibility' }; - const action = await task(); fs.writeFileSync(notes(), 'PRIOR_REVIEWER_NOTES\n'); - const commit = commitSolverSources(problem, peer.worktree); - await cooperative.deliver(peer, action, commit, true, 'request-failure'); - const worktree = path.join(directory, 'new-reviewer'); - git(lead.worktree, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const reviewer: ResearchWorker = { id: 'new-reviewer', role: 'researcher', worktree, ownedFiles: problem.ownedFiles }; - inputWorkers.push(reviewer); state.workers!.push({ ...reviewer, phase: 'running', turns: 0 }); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), 'PRIOR_REVIEWER_NOTES\n'); - node('first_route').assignment = undefined; - state.cooperation!.researchDrafts!.first_route.suspended = true; - const next = create(), fresh = await next.next(reviewer, budget); - if (fresh?.kind !== 'task') throw new Error('fixture_expected_fresh_reviewer'); - expect(fresh.task.id).toBe('first_route'); - expect(fresh.assignment.feasibilityInputDigest).not.toBe(action.assignment.feasibilityInputDigest); - expect(fs.readFileSync(path.join(worktree, 'RESEARCH.md'), 'utf8')).toBe(''); - expect(state.cooperation!.researchDrafts!.first_route).toMatchObject({ commit, workerId: peer.id, suspended: true }); - expect(committedSource(lead.worktree, commit, 'RESEARCH.md')).toBe('PRIOR_REVIEWER_NOTES\n'); - expect(node('first_route').finding).toBeUndefined(); expect(node('first_route').researchCompletion).toBeUndefined(); - }); - - it('uses canonical source changes that arrive while a snapshot is being read', async () => { - const { action, commit } = await saveDraft(); - await switchTask(); - duringRestore(commit, advanceCanonical); - const resumed = await task(); - expect(fs.readFileSync(source(), 'utf8')).toContain('by rfl'); - expect(fs.readFileSync(notes(), 'utf8')).toContain('FIRST_ROUTE_FINDING'); - expect(resumed.assignment.assignmentId).not.toBe(action.assignment.assignmentId); - expect(node('first_route').status).toBe('running'); - }); - - it('uses the current canonical proof when a snapshot read fails during canonical advancement', async () => { - const { action, commit } = await saveDraft(); - await switchTask(); - state.cooperation!.researchDrafts!.first_route.outputDigest = 'different-output'; - duringRestore(commit, advanceCanonical); - const resumed = await task(); - expect(state.cooperation!.canonicalCommit).not.toBe(action.assignment.canonicalCommit); - expect(resumed.assignment.canonicalCommit).toBe(state.cooperation!.canonicalCommit); - expect(resumed.assignment.assignmentId).not.toBe(action.assignment.assignmentId); - expect(fs.readFileSync(source(), 'utf8')).toContain('by rfl'); - expect(fs.readFileSync(notes(), 'utf8')).toBe(''); - expect(node('first_route').status).toBe('running'); - expect(pendingProposals()).toEqual([]); - }); - - it('restores notes after a fixed candidate review uses the same worker', async () => { - await saveDraft(); - const commit = state.cooperation!.canonicalCommit!; - cooperative.requireReview({ commit, sourceDigest: 'fixture-source', passed: true, - verification: { status: 'kernel_verified', results: [], targetCommit: commit } } as any); - const review = await cooperative.next(peer, budget); - expect(review?.kind).toBe('review'); - Object.assign(state.workers![1], { sessionRole: 'reviewer', sessionTaskId: undefined, sessionTaskVersion: undefined }); - if (review?.kind !== 'review') throw new Error('fixture_expected_review'); - cooperative.interrupted(peer, review); - state.cooperation!.review = undefined; - expect((await task()).task.id).toBe('first_route'); - expect(fs.readFileSync(notes(), 'utf8')).toContain('FIRST_ROUTE_FINDING'); - expect(pendingProposals()).toEqual([]); - }); -}); diff --git a/tests/solverResearchPublication.test.ts b/tests/solverResearchPublication.test.ts deleted file mode 100644 index 11ba62f5..00000000 --- a/tests/solverResearchPublication.test.ts +++ /dev/null @@ -1,581 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import { leadResearchInputs } from '../src/solver/contextCompiler'; -import { RETRY_DISPATCH } from '../src/solver/cooperationShared'; -import { leadWakePending } from '../src/solver/leadWakes'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import * as knowledgeApplications from '../src/solver/knowledgeApplications'; -import { buildResearchContext } from '../src/solver/modules/context'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git } from '../src/solver/problem'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { captureResearchBasis, researchSourceDigest } from '../src/solver/researchRecords'; -import { assignmentDeliveryFile, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; -let controller: AbortController, action: Extract; -const finding = (summary = 'EXACT_LOCAL_COUNTEREXAMPLE') => ({ summary, conclusion: 'refuted', needsDecision: true, - evidenceRefs: ['nine-listed-constraints-only'], remainingObligations: ['original_goal_1'] }); -const publish = (value: unknown) => (cooperative as any).receive(workers[1], action, value, true); -const leadInputs = () => leadResearchInputs(state.cooperation!.deliveries ?? [], - new Map(state.cooperation!.tasks.map(node => [node.task.id, node])), state.cooperation!.researchDecisions); -const summaries = () => leadInputs().map(item => item.summary); -const create = () => cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal }); -const freezeResearchBasis = () => action.assignment.researchBasis = captureResearchBasis(action.task, { - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest, - sourceDigest: researchSourceDigest(Object.fromEntries(state.problem.ownedFiles.map(file => [file, - committedSource(workers[1].worktree, action.assignment.seedCommit, `${state.problem.projectRelative}/${file}`)]))), - tasks: state.cooperation!.tasks, deliveries: state.cooperation!.deliveries, -}); -const ordinaryResearch = () => { - const node = state.cooperation!.tasks[0]; - const task = { ...node.task, kind: 'research' as const, theoremName: undefined, type: undefined, proofPath: undefined, - objective: 'Retain the exact classification argument and remaining gap.' }; - action = { kind: 'task', task, assignment: { ...action.assignment, taskDigest: taskVersion(task) } }; - node.task = task; node.assignment = action.assignment; node.status = 'running'; - return node; -}; -const gateKnowledgeChecks = (count = 1) => { - const checking = deferred<[]>(), entered = deferred(); - let calls = 0; - vi.spyOn(knowledgeApplications, 'checkKnowledgeApplications').mockImplementation(() => { - if (++calls === count) entered.resolve(); - return checking.promise; - }); - return { entered: entered.promise, release: () => checking.resolve([]) }; -}; - -beforeEach(() => { - const example = localExample('research-publication-', 'lead'), { workspace, problem } = example; - directory = example.directory; - workers = [leadWorker(problem, workspace, 'lead'), ...['proof', 'other'].map(id => peerWorker(example, id))]; - const parsed = parseCooperationPlan(problem, { tasks: [{ id: 'helper', kind: 'lemma', objective: 'Prove the exact helper.', - theoremName: 'Tutorial.helper', type: 'True', proofPath: 'Submission.lean', sharing: 'group' }, - { id: 'other', kind: 'research', objective: 'Independent route', groupId: 'other' }, - ...problem.targets.map((target, index) => ({ id: `original_goal_${index + 1}`, kind: 'goal', objective: 'Original goal', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' }))], - groups: [{ id: 'main', objective: 'Main route' }, { id: 'other', objective: 'Other route' }] }); - const task = parsed.tasks[0]; - action = { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'proof', - seedCommit: problem.baseCommit, assignmentId: 'active-proof', dependencies: [] } }; - state = solverState(problem, workspace, { runId: 'publication-fixture', phase: 'running', cooperation: { canonicalCommit: problem.baseCommit, - groups: parsed.groups.map(group => ({ group, turns: 0 })), tasks: parsed.tasks.map(task => ({ task, attempts: 1, - status: task.id === 'helper' ? 'running' : 'pending', ...(task.id === 'helper' ? { assignment: action.assignment } : {}) })) } }); - controller = new AbortController(); cooperative = create(); -}); -afterEach(async () => { - vi.restoreAllMocks(); - controller.abort(); await cooperative.stop(); fs.rmSync(directory, { recursive: true, force: true }); -}); - -it('publishes to mandatory Lead input while proof remains active, without touching live files or granting acceptance', async () => { - const basis = freezeResearchBasis(); - const interrupt = vi.fn(async () => {}); - cooperative.activate(workers[1], action, interrupt, async () => {}); - const file = path.join(workers[1].worktree, 'RESEARCH.md'); - fs.writeFileSync(file, 'UNFINISHED_LIVE_PROOF_NOTES'); - git(workers[1].worktree, ['add', 'RESEARCH.md']); - const index = git(workers[1].worktree, ['write-tree']); - const head = git(workers[1].worktree, ['rev-parse', 'HEAD']); - await publish({ kind: 'research', finding: finding() }); - const node = state.cooperation!.tasks[0], [delivery] = state.cooperation!.deliveries!; - expect(cooperative.current(action)).toBe(true); - expect(node.status).toBe('running'); expect(node.proof).toBeUndefined(); expect(node.finding).toBeUndefined(); - expect(state.cooperation!.blockers ?? []).toEqual([]); expect(interrupt).not.toHaveBeenCalled(); - expect(git(workers[1].worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(git(workers[1].worktree, ['write-tree'])).toBe(index); - expect(fs.readFileSync(file, 'utf8')).toBe('UNFINISHED_LIVE_PROOF_NOTES'); - expect(committedSource(workers[0].worktree, delivery.commit!, 'RESEARCH.md')).toBe(delivery.finding); - expect(delivery.researchRecord).toMatchObject({ id: delivery.id, complete: false, basis, - assignmentKey: assignmentDeliveryFile(action.assignment), seedCommit: action.assignment.seedCommit, commit: delivery.commit }); - expect(node.researchCompletion).toBeUndefined(); - expect(Object.isFrozen(delivery.researchRecord)).toBe(true); - const context = buildResearchContext(state.problem, state, { taskText: 'Exact problem controls', root: directory, - worktree: workers[0].worktree, environment: {}, retrievalRoot: directory, assignment: { kind: 'lead', seedCommit: head }, - frozenContexts: Object.fromEntries(state.problem.ownedFiles.filter(file => file.endsWith('.lean')).map(file => [file, - committedSource(workers[0].worktree, state.problem.baseCommit, `${state.problem.projectRelative}/${file}`)])), - maxOptionalContextBytes: 0 }); - expect(context.message).toContain('EXACT_LOCAL_COUNTEREXAMPLE'); - expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'lead-research-inputs', required: true })); -}); - -it('retains multiple findings and proposals independently across restart and duplicate submissions', async () => { - const first = { kind: 'research', finding: { ...finding(), lemmaRequests: [{ id: 'bridge', kind: 'lemma', objective: 'Repair the local gap', - theoremName: 'Tutorial.bridge', type: 'True', proofPath: 'Submission.lean' }] } }; - await publish(first); await publish(first); - const adopted = state.cooperation!.deliveries![0].lemmaRequests![0]; - state.cooperation!.tasks.push({ task: adopted, status: 'pending', attempts: 0 }); - await publish({ ...first, finding: { ...first.finding, summary: 'UPDATED_FINDING_AFTER_ADOPTION' } }); - await publish({ kind: 'research', finding: finding('SECOND_DISTINCT_FINDING') }); - expect(state.cooperation!.deliveries).toHaveLength(3); - const ordered = ['EXACT_LOCAL_COUNTEREXAMPLE', 'UPDATED_FINDING_AFTER_ADOPTION', 'SECOND_DISTINCT_FINDING']; - expect(summaries()).toEqual(ordered); - // The adopted proposal is no longer shown as an unadopted planning input. - expect(leadInputs().flatMap(item => item.lemmaRequests ?? []).filter(task => - !state.cooperation!.tasks.some(node => node.task.id === task.id))).toEqual([]); - cooperative.deactivate(workers[1]); await cooperative.stop(); - state = JSON.parse(JSON.stringify(state)); cooperative = create(); - await publish(first); - expect(state.cooperation!.deliveries).toHaveLength(3); - expect(summaries()).toEqual(ordered); -}); - -it('requires an explicit answer for each presented finding and preserves it across restart', async () => { - await publish({ kind: 'research', finding: finding('ANSWER_THIS_EXACT_FINDING') }); - const leadAction = await (cooperative as any).nextLead(workers[0], { maxTurns: Infinity, remainingMs: Infinity }, true); - expect(leadAction).toMatchObject({ kind: 'lead' }); - const shown = cooperative.contextState(leadAction, workers[0]); - const delivery = state.cooperation!.deliveries![0]; - expect(shown.leadResearchInputIds).toEqual([delivery.id]); - const tasks = state.cooperation!.tasks.map(node => node.task); - const plan = parseCooperationPlan(state.problem, { tasks, - groups: state.cooperation!.groups!.map(record => record.group) }); - await expect((cooperative as any).acceptPlan(plan, undefined, undefined, leadAction)) - .rejects.toThrow('math_plan_research_decisions_missing'); - await (cooperative as any).acceptPlan({ ...plan, researchDecisions: [{ deliveryId: delivery.id, - outcome: 'decline', reason: 'The counterexample assumes a premise absent from this exact target.' }] }, - undefined, undefined, leadAction); - expect(state.cooperation!.researchDecisions).toEqual([expect.objectContaining({ - deliveryId: delivery.id, taskDigest: delivery.taskDigest, findingDigest: delivery.findingDigest, - outcome: 'decline', planVersion: state.cooperation!.planVersion })]); - expect(cooperative.contextState(undefined, workers[2]).researchDecisions).toBeUndefined(); - expect(leadInputs()).toEqual([]); - await restart(); - expect(leadInputs()).toEqual([]); - const laterFinding = JSON.stringify(finding('A_LATER_DISTINCT_FINDING')); - state.cooperation!.deliveries!.push({ ...delivery, id: 'later-distinct-publication', - finding: laterFinding, findingDigest: mathDigest(laterFinding), summary: 'A_LATER_DISTINCT_FINDING' }); - expect(leadInputs().map(item => item.summary)).toEqual(['A_LATER_DISTINCT_FINDING']); -}); - -it('does not apply an unanswered saved plan during actionless restore', async () => { - await publish({ kind: 'research', finding: finding('RESTORED_DECISION_REQUEST') }); - const plan = parseCooperationPlan(state.problem, { tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(record => record.group) }); - await expect((cooperative as any).acceptPlan(plan)).rejects.toThrow('math_plan_research_decisions_missing'); - expect(leadInputs().map(item => item.summary)).toEqual(['RESTORED_DECISION_REQUEST']); - await (cooperative as any).acceptPlan({ ...plan, researchDecisions: [{ - deliveryId: state.cooperation!.deliveries![0].id, outcome: 'decline', - reason: 'The frozen target does not use this proposed route.' }] }); - expect(leadInputs()).toEqual([]); - expect(state.cooperation!.researchDecisions).toHaveLength(1); -}); - -it('carries the ninth unanswered finding into the next Lead turn', async () => { - for (let index = 0; index < 9; index++) - await publish({ kind: 'research', finding: finding('FINDING_' + index) }); - const first = await (cooperative as any).nextLead(workers[0], { maxTurns: Infinity, remainingMs: Infinity }, true); - const shown = cooperative.contextState(first, workers[0]).leadResearchInputIds!; - expect(shown).toHaveLength(8); - const plan = parseCooperationPlan(state.problem, { tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(record => record.group) }); - await (cooperative as any).acceptPlan({ ...plan, researchDecisions: shown.map(deliveryId => ({ deliveryId, - outcome: 'decline', reason: 'This route does not use the reported candidate.' })) }, undefined, undefined, first); - (cooperative as any).rememberLeadDecision(first); - expect(leadInputs().map(item => item.summary)).toEqual(['FINDING_0']); - expect(state.cooperation!.lastLeadInputDigest).toBeUndefined(); - const next = await (cooperative as any).nextLead(workers[0], { maxTurns: Infinity, remainingMs: Infinity }, true); - expect(next).toMatchObject({ kind: 'lead' }); - expect(cooperative.contextState(next, workers[0]).leadResearchInputIds).toEqual([state.cooperation!.deliveries![0].id]); -}); - -it('does not resolve a source answer before the changed Lean file is merged', async () => { - await publish({ kind: 'research', finding: finding('SOURCE_DECISION_PENDING_MERGE') }); - const leadAction = await (cooperative as any).nextLead(workers[0], { maxTurns: Infinity, remainingMs: Infinity }, true); - const file = path.join(workers[0].worktree, state.problem.projectRelative, 'Submission.lean'); - const plan = parseCooperationPlan(state.problem, { tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(record => record.group) }); - const answer = { ...plan, researchDecisions: [{ - deliveryId: state.cooperation!.deliveries![0].id, outcome: 'source', sourcePaths: ['Submission.lean'], - reason: 'The owned source contains the revised proof step.' }] }; - await expect((cooperative as any).acceptPlan(answer, undefined, undefined, leadAction)) - .rejects.toThrow('math_plan_research_source_unchanged'); - fs.appendFileSync(file, '\n-- Pending Lead source change.\n'); - await (cooperative as any).acceptPlan(answer, undefined, undefined, leadAction); - expect(state.cooperation!.researchDecisions ?? []).toEqual([]); - await restart(); - expect(leadInputs().map(item => item.summary)).toEqual(['SOURCE_DECISION_PENDING_MERGE']); -}); - -it('keeps private findings within their route and excludes stale or late events from decisions', async () => { - await publish({ kind: 'research', finding: finding() }); - const other = state.cooperation!.tasks.find(node => node.task.id === 'other')!; - const scoped = cooperative.contextState({ kind: 'task', task: other.task, assignment: { taskId: other.task.id, - taskDigest: taskVersion(other.task), workerId: workers[2].id, seedCommit: state.problem.baseCommit } }, workers[2]); - expect(JSON.stringify(scoped)).not.toContain('EXACT_LOCAL_COUNTEREXAMPLE'); - state.cooperation!.tasks[0].task = { ...action.task, revision: 1 }; - await publish({ kind: 'research', finding: finding('LATE_FINDING') }); - expect(state.cooperation!.deliveries!.at(-1)?.status).toBe('superseded'); - expect(leadInputs()).toEqual([]); -}); - -const restart = async () => { - controller.abort(); await cooperative.stop(); - state = JSON.parse(JSON.stringify(state)); controller = new AbortController(); cooperative = create(); -}; -const wakePending = () => leadWakePending(state.cooperation!.leadWakes!); - -it('wakes Lead after restore for an unanswered refutation until a plan answers its exact input', async () => { - expect(wakePending()).toBe(false); - await publish({ kind: 'research', finding: finding() }); - await restart(); - expect(wakePending()).toBe(true); - state.cooperation!.lastLeadInputDigest = (cooperative as any).planningInputDigest(); - await restart(); - // A saved completed-input marker is insufficient: the exact publication still has no answer. - expect(wakePending()).toBe(true); - const lead = await (cooperative as any).nextLead(workers[0], { maxTurns: Infinity, remainingMs: Infinity }, true); - expect(lead).toMatchObject({ kind: 'lead' }); - const shown = cooperative.contextState(lead, workers[0]).leadResearchInputIds!; - expect(shown).toHaveLength(1); - const plan = parseCooperationPlan(state.problem, { tasks: state.cooperation!.tasks.map(node => node.task), - groups: state.cooperation!.groups!.map(record => record.group) }); - await (cooperative as any).acceptPlan({ ...plan, researchDecisions: shown.map(deliveryId => ({ deliveryId, - outcome: 'decline', reason: 'The scoped refutation does not affect the distinct retained consumer.' })) }, undefined, undefined, lead); - (cooperative as any).rememberLeadDecision(lead); - // The explicit answer now waits for new work without a turn or a busy retry. - let settled = false; - const dispatch = (cooperative as any).nextLead(workers[0], { maxTurns: Infinity, remainingMs: Infinity }, true) - .then((result: unknown) => { settled = true; return result; }); - await new Promise(resolve => setImmediate(resolve)); - expect(wakePending()).toBe(false); - expect(settled).toBe(false); - (cooperative as any).wake(); - await expect(dispatch).resolves.toBe(RETRY_DISPATCH); -}); - -it('keeps a progress decision request across restart while other work is still running', async () => { - // Progress is not a research input the restore path could rediscover; only its saved wake-up asks the Lead. - expect(wakePending()).toBe(false); - await publish({ kind: 'progress', summary: 'The construction needs a route decision.', needsDecision: true }); - expect(wakePending()).toBe(true); - expect(state.cooperation!.leadWakes!.recent?.at(-1)?.reason).toBe('progress-decision-requested'); - await restart(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'helper')?.status).toBe('running'); - const lead = await cooperative.next(workers[0], { maxTurns: Infinity, remainingMs: Infinity }); - expect(lead).toMatchObject({ kind: 'lead' }); - expect(wakePending()).toBe(false); - // A restart before the dispatch settles asks again; the in-flight turn did not survive the process. - await restart(); - expect(wakePending()).toBe(true); -}); - -it('rejects an invalid research event and continues consuming the following line', async () => { - const log = path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)); - fs.writeFileSync(log, JSON.stringify({ kind: 'research', finding: { summary: 'Invalid', conclusion: 'accepted' } }) + '\n' + - JSON.stringify({ kind: 'research', finding: finding() }) + '\n'); - const cursors = {}; - await (cooperative as any).readWorkerDeliveries(workers[1], action, cursors); - expect(state.cooperation!.deliveries).toHaveLength(1); - expect(leadInputs()).toHaveLength(1); - expect(state.cooperation!.deliveryReceipts).toEqual([expect.objectContaining({ - status: 'needs-correction', taskId: action.task.id, assignmentKey: assignmentDeliveryFile(action.assignment), - issues: [{ path: 'conclusion', message: 'Use supporting, refuted, or inconclusive.' }], - })]); - expect(cooperative.contextState(action, workers[1]).deliveryReceipts).toHaveLength(1); - expect(cooperative.contextState(undefined, workers[2]).deliveryReceipts).toEqual([]); -}); - -it('rejects misplaced finding fields and records the corrected nested report without proof acceptance', async () => { - const log = path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)); - const blockers = [{ mechanism: 'Missing estimate', scope: 'Local argument' }]; - const misplaced = { kind: 'research', finding: finding(), blockers, lemmaRequests: [], mathematicalGap: {} }; - fs.writeFileSync(log, JSON.stringify(misplaced) + '\n'); - await (cooperative as any).readWorkerDeliveries(workers[1], action, {}); - expect(state.cooperation!.deliveries ?? []).toHaveLength(0); - const receipt = state.cooperation!.deliveryReceipts![0]; - expect(receipt).toMatchObject({ status: 'needs-correction', - issues: ['mathematicalGap', 'lemmaRequests', 'blockers'].map(path => ({ path, message: expect.stringContaining('finding.' + path) })) }); - await publish({ kind: 'research', finding: { ...finding(), blockers, replacesReceipt: receipt.id } }); - expect(receipt.status).toBe('recorded'); - expect(state.cooperation!.deliveries).toHaveLength(1); - expect(state.cooperation!.tasks[0]).toMatchObject({ status: 'running' }); - expect(state.cooperation!.tasks[0].proof).toBeUndefined(); -}); - -it('retains the nested blocker field path in a correctable research-event receipt', async () => { - const log = path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)); - fs.writeFileSync(log, JSON.stringify({ kind: 'research', finding: { ...finding(), blockers: [{ - mechanism: 'Need a bound', scope: 'Local method', reopenOn: [{ kind: 'dependency-checked', taskId: 'unrelated' }], - }] } }) + '\n'); - await (cooperative as any).readWorkerDeliveries(workers[1], action, {}); - expect(state.cooperation!.deliveries ?? []).toHaveLength(0); - expect(state.cooperation!.deliveryReceipts).toMatchObject([{ status: 'needs-correction', - issues: [{ path: 'finding.blockers[0].reopenOn[0].taskId', message: expect.stringContaining('declared dependency cone') }] }]); -}); - -it('resolves the explicitly replaced receipt only after a corrected finding is recorded', async () => { - const log = path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)); - fs.writeFileSync(log, JSON.stringify({ kind: 'research', finding: { summary: 'Invalid', conclusion: 'accepted' } }) + '\n'); - await (cooperative as any).readWorkerDeliveries(workers[1], action, {}); - const receipt = state.cooperation!.deliveryReceipts![0]; - await publish({ kind: 'research', finding: { ...finding(), replacesReceipt: receipt.id } }); - expect(receipt.status).toBe('recorded'); - expect(state.cooperation!.tasks[0].feedback).toBeUndefined(); - const contextFile = JSON.parse(fs.readFileSync(path.join(workers[1].worktree, 'COOPERATION.json'), 'utf8')); - expect(contextFile.deliveryReceipts).toMatchObject([{ status: 'recorded' }]); - expect(state.cooperation!.deliveries).toHaveLength(1); - expect(state.cooperation!.tasks[0].status).toBe('running'); - expect(state.cooperation!.tasks[0].proof).toBeUndefined(); -}); - -it('resolves a gap correction that fails again before its complete replacement is recorded', async () => { - const goal = state.cooperation!.tasks.find(node => node.task.kind === 'goal')!.task; - const gap = { consumer: { taskId: goal.id, taskDigest: taskVersion(goal) }, previousGap: 'The original missing inference', - reduced: 'The checked special case', remaining: 'The uniform classification', evidenceScope: 'Checked special-case sources', - reconsiderWhen: ['A uniform classification lemma is available'] }; - const log = path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)), cursors = {}; - const append = (value: unknown) => fs.appendFileSync(log, JSON.stringify({ kind: 'research', finding: value }) + '\n'); - const poll = () => (cooperative as any).readWorkerDeliveries(workers[1], action, cursors); - append({ ...finding(), mathematicalGap: { ...gap, previousDeliveryId: 'ordinary-research-is-not-a-gap' } }); - await poll(); - const first = state.cooperation!.deliveryReceipts![0]; - expect(first.issues[0].path).toBe('mathematicalGap.previousDeliveryId'); - const { previousGap: _omitted, ...incompleteGap } = gap; - append({ ...finding(), replacesReceipt: first.id, mathematicalGap: incompleteGap }); - await poll(); - const second = state.cooperation!.deliveryReceipts![1]; - expect(second).toMatchObject({ status: 'needs-correction', replacesReceipt: first.id, - issues: [{ path: 'mathematicalGap.previousGap' }] }); - expect(first.status).toBe('needs-correction'); - expect(state.cooperation!.deliveries ?? []).toEqual([]); - // The verified link must survive durable archive serialization before correction. - state.cooperation!.deliveryReceipts = JSON.parse(JSON.stringify(state.cooperation!.deliveryReceipts)); - append({ ...finding(), replacesReceipt: second.id, mathematicalGap: gap }); - await poll(); - expect(state.cooperation!.deliveryReceipts!.map(receipt => receipt.status)).toEqual(['recorded', 'recorded']); - expect(state.cooperation!.tasks[0].feedback).toBeUndefined(); - expect(state.cooperation!.deliveries).toHaveLength(1); - expect(state.cooperation!.deliveries![0].mathematicalGap).toEqual(gap); - expect(state.cooperation!.tasks[0].status).toBe('running'); - expect(state.cooperation!.tasks[0].proof).toBeUndefined(); -}); - -it.each(['environment', 'problem'] as const)('does not bind an old finding to a new %s after asynchronous application checking', async change => { - const { entered, release } = gateKnowledgeChecks(); - const pending = publish({ kind: 'research', finding: finding() }); - await entered; - if (change === 'environment') state.environmentDigest = 'replacement-environment'; - else state.problem = { ...state.problem, receiptDigest: 'replacement-problem' }; - release(); await pending; - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.tasks[0].status).toBe('running'); -}); - -it('tracks changed complete arguments even when short summaries and advisory conclusions match', async () => { - const event = { kind: 'research', finding: { summary: 'Same short summary', conclusion: 'supporting', argument: 'First exact argument' } }; - await publish(event); - const input = (cooperative as any).planningInputDigest(); - const checkpoint = (cooperative as any).checkpointInputDigest(action.task, workers[0].id); - const ownCheckpoint = (cooperative as any).checkpointInputDigest(action.task, workers[1].id); - await publish({ ...event, finding: { ...event.finding, argument: 'Different complete mathematical argument' } }); - expect((cooperative as any).planningInputDigest()).not.toBe(input); - expect((cooperative as any).checkpointInputDigest(action.task, workers[0].id)).not.toBe(checkpoint); - expect((cooperative as any).checkpointInputDigest(action.task, workers[1].id)).toBe(ownCheckpoint); -}); - -it('preserves notes-only Lean support under its actual commit independently of the published finding', async () => { - const code = 'namespace Probe\nlemma retained : True := by trivial\nend Probe\n'; - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), '```lean\n' + code + '```\n'); - const support = commitSolverSources(state.problem, workers[1].worktree); - await publish({ kind: 'research', commit: support, finding: { ...finding(), - leanChecks: [{ status: 'passed', path: 'RESEARCH.md', declarations: ['Probe.retained'] }] } }); - const [record] = state.cooperation!.deliveries!; - expect(record.commit).not.toBe(support); - expect(record.artifacts).toMatchObject({ commit: support, scope: 'advisory-unverified', - artifacts: [{ kind: 'notes-lean', declarations: [{ name: 'Probe.retained', draft: false }] }], - reportedChecks: [{ status: 'passed', path: 'RESEARCH.md' }] }); - expect(committedSource(workers[0].worktree, support, 'RESEARCH.md')).toContain(code); - expect(committedSource(workers[0].worktree, record.commit!, 'RESEARCH.md')).toBe(record.finding); -}); - -it('freezes a complete source event larger than 114 KB without reading or changing its active writer', async () => { - const relative = 'Submission.lean', file = path.join(workers[1].worktree, state.problem.projectRelative, relative); - const original = fs.readFileSync(file, 'utf8'); - const saved = original + '\ntheorem retained_support : True := by\n' + - (' -- Complete supporting proof retained in this immutable event.\n'.repeat(2000)) + ' trivial\n'; - fs.writeFileSync(file, saved); - const head = git(workers[1].worktree, ['rev-parse', 'HEAD']); - const index = git(workers[1].worktree, ['write-tree']); - const notes = path.join(workers[1].worktree, 'RESEARCH.md'); - fs.writeFileSync(notes, 'The active proof notes remain writable.'); - const event = { kind: 'research', sources: { [relative]: saved }, finding: { - ...finding(), leanChecks: [{ status: 'passed', path: relative, declarations: ['retained_support'] }], - } }; - const line = JSON.stringify(event) + '\n'; - expect(Buffer.byteLength(line)).toBeGreaterThan(114_000); - fs.writeFileSync(path.join(workers[1].worktree, assignmentDeliveryFile(action.assignment)), line); - const { entered, release } = gateKnowledgeChecks(); - const pending = (cooperative as any).readWorkerDeliveries(workers[1], action, {}); - await entered; - const newer = saved + '\nlemma later_support : True := by trivial\n'; - fs.writeFileSync(file, newer); - fs.writeFileSync(notes, 'Later live notes.'); - release(); await pending; - const [record] = state.cooperation!.deliveries!; - expect(committedSource(workers[0].worktree, record.commit!, `${state.problem.projectRelative}/${relative}`)).toBe(saved); - expect(record.artifacts).toMatchObject({ scope: 'advisory-unverified', commit: record.commit, - artifacts: [{ proofPath: relative, declarations: [{ name: 'retained_support', draft: false }] }], - reportedChecks: [{ status: 'passed', path: relative, declarations: ['retained_support'] }] }); - expect(record.artifactWarning).toBeUndefined(); - expect(git(workers[1].worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(git(workers[1].worktree, ['write-tree'])).toBe(index); - expect(fs.readFileSync(file, 'utf8')).toBe(newer); - expect(fs.readFileSync(notes, 'utf8')).toBe('Later live notes.'); - expect(state.cooperation!.tasks[0].status).toBe('running'); - expect(state.cooperation!.tasks[0].proof).toBeUndefined(); - expect(state.cooperation!.tasks[0].researchCompletion).toBeUndefined(); - expect(state.check).toBeUndefined(); -}); - -it.each([null, [], {}, { 'Submission.lean': 42 }, { '../Submission.lean': 'outside' }, - { 'Submission.lean': '', 'Other.lean': '' }, { 'Submission.lean': '数'.repeat(333_334) }])( - 'rejects invalid or oversized source snapshots without changing the live writer (%#)', async sources => { - const head = git(workers[1].worktree, ['rev-parse', 'HEAD']); - await expect(publish({ kind: 'research', sources, finding: finding() })).rejects.toMatchObject({ - message: 'math_delivery_invalid', issues: [{ path: 'sources' }], - }); - expect(git(workers[1].worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(state.cooperation!.deliveries ?? []).toEqual([]); - }); - -it('requires every owned Lean file and refuses to combine source bytes with a commit', async () => { - const source = committedSource(workers[1].worktree, action.assignment.seedCommit, `${state.problem.projectRelative}/Submission.lean`); - const sources = { 'Submission.lean': source }; - await expect(publish({ kind: 'research', sources, commit: action.assignment.seedCommit, finding: finding() })) - .rejects.toMatchObject({ message: 'math_delivery_invalid', issues: [{ path: 'sources' }] }); - state.problem = { ...state.problem, ownedFiles: [...state.problem.ownedFiles, 'Submission/Helpers.lean'] }; - await expect(publish({ kind: 'research', sources, finding: finding() })) - .rejects.toMatchObject({ message: 'math_delivery_invalid', issues: [{ path: 'sources' }] }); - expect(state.cooperation!.deliveries ?? []).toEqual([]); -}); - -it('checks the frozen original declarations before retaining an explicit source snapshot', async () => { - const file = `${state.problem.projectRelative}/Submission.lean`; - const original = committedSource(workers[1].worktree, action.assignment.seedCommit, file); - await expect(publish({ kind: 'research', sources: { 'Submission.lean': original.replace('n + 0 = n', 'n + 0 = 0') }, - finding: finding() })).rejects.toThrow('math_original_declaration_changed'); - expect(committedSource(workers[1].worktree, git(workers[1].worktree, ['rev-parse', 'HEAD']), file)).toBe(original); - expect(state.cooperation!.deliveries ?? []).toEqual([]); -}); - -it('keeps a malformed final research report on its original assignment and accepts its corrected finding', async () => { - const node = ordinaryResearch(), task = node.task; - freezeResearchBasis(); - state.workers = workers.map(worker => ({ ...worker, phase: 'running', turns: 0, - ...(worker.id === workers[1].id ? { threadId: 'original-research-thread', sessionTaskId: task.id, - sessionTaskVersion: taskVersion(task), sessionAssignmentId: action.assignment.assignmentId } : {}) })); - const originalAssignment = action.assignment; - const saved: SolverRunState[] = []; - (cooperative as any).input.save = () => saved.push(JSON.parse(JSON.stringify(state))); - const notes = path.join(workers[1].worktree, 'RESEARCH.md'); - const ticks = String.fromCharCode(96).repeat(3); - const malformed = ticks + 'math-result\n{"summary":\n' + ticks; - fs.writeFileSync(notes, malformed); - const invalidCommit = commitSolverSources(state.problem, workers[1].worktree); - await expect(cooperative.deliver(workers[1], action, invalidCommit)).resolves.toEqual({ checkWhole: false }); - expect(node.status).toBe('pending'); expect(node.assignment).toBe(originalAssignment); - expect(state.workers.find(worker => worker.id === workers[1].id)?.threadId).toBe('original-research-thread'); - expect(state.cooperation!.deliveryReceipts).toEqual([expect.objectContaining({ status: 'needs-correction', - taskId: task.id, taskDigest: taskVersion(task), assignmentKey: assignmentDeliveryFile(originalAssignment), - code: 'math_research_delivery_invalid', issues: [{ path: '$', message: 'The research control response must contain valid JSON.' }], - })]); - expect(saved.some(snapshot => snapshot.cooperation?.deliveryReceipts?.length === 1)).toBe(true); - expect(state.cooperation!.deliveries?.filter(delivery => delivery.kind === 'research') ?? []).toEqual([]); - expect(state.cooperation!.blockers ?? []).toEqual([]); - const resumed = await cooperative.next(workers[1], { maxTurns: Infinity, remainingMs: Infinity, aborted: false }); - expect(resumed?.kind).toBe('task'); - if (!resumed || resumed.kind !== 'task') throw new Error('Expected the same research responsibility'); - expect(resumed.assignment).toBe(originalAssignment); - expect(state.workers.find(worker => worker.id === workers[1].id)?.threadId).toBe('original-research-thread'); - expect(fs.readFileSync(notes, 'utf8')).toBe(malformed); - const corrected = { summary: 'Exact boundary result retained; uniform classification remains unresolved.', - conclusion: 'inconclusive', argument: 'Complete immutable argument with quantified remaining hypotheses.' }; - const finalNotes = '# Retained derivation\n\n' + ticks + 'json\n{"nodes":["boundary","uniform"]}\n' + ticks + - '\n\n' + ticks + 'math-result\n' + JSON.stringify(corrected) + '\n' + ticks + '\n'; - fs.writeFileSync(notes, finalNotes); - const validCommit = commitSolverSources(state.problem, workers[1].worktree); - await expect(cooperative.deliver(workers[1], resumed, validCommit)).resolves.toEqual({ checkWhole: false }); - expect(node.status).toBe('completed'); expect(node.assignment).toBe(originalAssignment); - expect(state.cooperation!.deliveryReceipts![0].status).toBe('recorded'); - const [delivery] = state.cooperation!.deliveries!.filter(item => item.kind === 'research'); - expect(JSON.parse(delivery.finding!)).toMatchObject({ ...corrected, taskId: task.id, taskDigest: taskVersion(task) }); - expect(delivery.commit).toBe(validCommit); - expect(node.researchCompletion).toBe(delivery.researchRecord); - expect(node.researchCompletion).toMatchObject({ id: delivery.id, complete: true, - basis: originalAssignment.researchBasis, commit: validCommit }); - expect(committedSource(workers[0].worktree, delivery.commit!, 'RESEARCH.md')).toBe(finalNotes); - expect(node.proof).toBeUndefined(); expect(state.check).toBeUndefined(); -}); - -it('records complete notes with their frozen dispatch inputs and persists completion together with its pinned delivery', async () => { - const node = ordinaryResearch(), basis = freezeResearchBasis(); - const { entered, release } = gateKnowledgeChecks(); - const notes = path.join(workers[1].worktree, 'RESEARCH.md'); - fs.writeFileSync(notes, JSON.stringify({ summary: 'A complete exact derivation.', conclusion: 'supporting' })); - const commit = commitSolverSources(state.problem, workers[1].worktree); - const snapshots: SolverRunState[] = []; - (cooperative as any).input.save = () => snapshots.push(JSON.parse(JSON.stringify(state))); - const pending = cooperative.deliver(workers[1], action, commit); - await entered; - action.assignment.researchBasis = captureResearchBasis(action.task, { ...basis, sourceDigest: 'newer-unrelated-context', - tasks: state.cooperation!.tasks }); - release(); await pending; - const [delivery] = state.cooperation!.deliveries!.filter(item => item.kind === 'research'); - expect(node.status).toBe('completed'); - expect(node.researchCompletion).toBe(delivery.researchRecord); - expect(delivery.researchRecord).toMatchObject({ id: delivery.id, taskId: action.task.id, complete: true, - seedCommit: action.assignment.seedCommit, commit, basis }); - expect(delivery.researchRecord!.basis.sourceDigest).not.toBe(action.assignment.researchBasis.sourceDigest); - expect(Object.isFrozen(delivery.researchRecord)).toBe(true); - expect(Object.isFrozen(delivery.researchRecord!.basis)).toBe(true); - expect(git(workers[0].worktree, ['rev-parse', `refs/math/${state.runId}/evidence/${commit}`])).toBe(commit); - expect(snapshots.some(snapshot => snapshot.cooperation!.tasks[0].status === 'completed')).toBe(true); - for (const snapshot of snapshots) if (snapshot.cooperation!.tasks[0].status === 'completed') { - const completion = snapshot.cooperation!.tasks[0].researchCompletion!; - expect(snapshot.cooperation!.deliveries).toContainEqual(expect.objectContaining({ id: completion.id, researchRecord: completion })); - } -}); - -it('does not complete a research assignment superseded while knowledge applications are checked', async () => { - const node = ordinaryResearch(); freezeResearchBasis(); - const { entered, release } = gateKnowledgeChecks(); - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), JSON.stringify({ summary: 'Old exact inputs.', conclusion: 'supporting' })); - const pending = cooperative.deliver(workers[1], action, commitSolverSources(state.problem, workers[1].worktree)); - await entered; - node.assignment = { ...action.assignment, assignmentId: 'replacement-responsibility' }; - release(); await pending; - expect(node.status).toBe('running'); expect(node.finding).toBeUndefined(); expect(node.researchCompletion).toBeUndefined(); - expect(state.cooperation!.deliveries ?? []).toEqual([]); -}); - -it('does not invent a completion basis for legacy assignments when a newer context arrives during checking', async () => { - const node = ordinaryResearch(); - expect(action.assignment.researchBasis).toBeUndefined(); - const { entered, release } = gateKnowledgeChecks(); - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), JSON.stringify({ summary: 'Legacy saved work.', conclusion: 'inconclusive' })); - const pending = cooperative.deliver(workers[1], action, commitSolverSources(state.problem, workers[1].worktree)); - await entered; freezeResearchBasis(); release(); await pending; - expect(node.status).toBe('completed'); - expect(node.researchCompletion).toBeUndefined(); - expect(state.cooperation!.deliveries!.find(item => item.kind === 'research')!.researchRecord).toBeUndefined(); -}); - -it('freezes explicit finding content before asynchronous checks', async () => { - freezeResearchBasis(); - const { entered, release } = gateKnowledgeChecks(); - const output = { summary: 'Frozen exact argument.', conclusion: 'supporting', argument: { inference: 'Original inference' } }; - const pending = publish({ kind: 'research', finding: output }); - await entered; - output.summary = 'Changed after submission'; output.argument.inference = 'Later unrelated inference'; - release(); await pending; - const [delivery] = state.cooperation!.deliveries!; - expect(JSON.parse(delivery.finding!)).toMatchObject({ summary: 'Frozen exact argument.', argument: { inference: 'Original inference' } }); - expect(committedSource(workers[0].worktree, delivery.commit!, 'RESEARCH.md')).toBe(delivery.finding); - expect(delivery.researchRecord).toMatchObject({ complete: false, id: delivery.id }); -}); diff --git a/tests/solverResearchTransfer.test.ts b/tests/solverResearchTransfer.test.ts deleted file mode 100644 index d7f99553..00000000 --- a/tests/solverResearchTransfer.test.ts +++ /dev/null @@ -1,235 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { acceptContextCheckpoint } from '../src/solver/contextCheckpoint'; -import { directSolverModules } from '../src/solver/modules'; -import { commitSolverSources, committedSource, git } from '../src/solver/problem'; -import { researchCheckpointInputDigest, researchCheckpointLocalInputDigest, researchCheckpointOutputDigest } from '../src/solver/researchCheckpoints'; -import { checkSolverRunState } from '../src/solver/stateInvariants'; -import { assignmentDeliveryFile, parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -type TaskAction = Extract; -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -const fixtures: { directory: string; cooperative: CooperativeResearch }[] = []; -afterEach(async () => { - for (const f of fixtures.splice(0)) { await f.cooperative.stop(); fs.rmSync(f.directory, { recursive: true, force: true }); } -}); - -async function fixture(options: { inheritedNotes?: string; acknowledge?: boolean } = {}) { - const example = localExample('solver-research-transfer-', 'lead'); - const lead = leadWorker(example.problem, example.workspace); - const owner = peerWorker(example, 'saved-owner'), idle = peerWorker(example, 'idle-peer'); - const workers = [lead, owner, idle]; - const plan = parseCooperationPlan(example.problem, { tasks: [ - { id: 'survey', kind: 'research', objective: 'Survey the precise boundary identity.' }, - { id: 'bridge', kind: 'research', objective: 'Develop an independent bridge.', ownerId: owner.id }, - ...example.problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: 'Original target.', theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ], groups: [{ id: 'main', objective: 'Original problem.', maxConcurrent: 3 }] }); - const state = solverState(example.problem, example.workspace, { runId: 'research-transfer-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const events: { event: string; details?: Record }[] = []; - const forbidden = () => { throw new Error('fixture_model_or_verifier_forbidden'); }; - const cooperative = cooperativeResearch({ state, workers, retrievalRoot: example.directory, - emit: (event, details) => events.push({ event, details }), - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: forbidden }, - M2: { ...directSolverModules.M2, check: forbidden, checkTask: forbidden } } }); - fixtures.push({ directory: example.directory, cooperative }); - const survey = state.cooperation!.tasks.find(node => node.task.id === 'survey')!; - const bridge = state.cooperation!.tasks.find(node => node.task.id === 'bridge')!; - // Obtain the saved assignment and snapshot through the ordinary host lifecycle. - bridge.task = { ...bridge.task, status: 'paused' }; - if (options.inheritedNotes !== undefined) fs.writeFileSync(path.join(owner.worktree, 'RESEARCH.md'), options.inheritedNotes); - const action = await cooperative.next(owner, budget) as TaskAction; - expect(action.task.id).toBe('survey'); expect(cooperative.started(owner, action)).toBe(true); - fs.writeFileSync(path.join(owner.worktree, 'RESEARCH.md'), options.inheritedNotes ?? - 'Checked the available identity; the exact uniform bound remains open.\n'); - if (options.acknowledge) { - const research = state.workers![1]; - research.threadId = 'saved-task-thread'; - research.contextCheckpoint = { threadId: research.threadId, requestId: 'confirm-saved-notes', requestedAt: Date.now() }; - acceptContextCheckpoint(research, owner.worktree, { kind: 'checkpoint', requestId: 'confirm-saved-notes', - notesDigest: mathDigest(fs.readFileSync(path.join(owner.worktree, 'RESEARCH.md'))) }); - } - const proofPath = path.join(owner.worktree, example.problem.projectRelative, 'Submission.lean'); - fs.appendFileSync(proofPath, '\n-- Retained independent draft context.\n'); - const commit = commitSolverSources(example.problem, owner.worktree); - cooperative.retainContextDraft(owner, action, commit); - cooperative.interrupted(owner, action); - const draft = state.cooperation!.researchDrafts!.survey; - bridge.task = { ...bridge.task, status: 'active' }; - // Resume another responsibility on the old writer; survey stays pending and pinned. - survey.task = { ...survey.task, status: 'paused' }; - const busy = await cooperative.next(owner, budget) as TaskAction; - expect(busy.task.id).toBe('bridge'); expect(cooperative.started(owner, busy)).toBe(true); - survey.task = { ...survey.task, status: 'active' }; - const inspect = () => (cooperative as any).nextPeer(idle, budget, true); - return { example, state, cooperative, lead, owner, idle, survey, bridge, action, busy, draft, events, commit, inspect }; -} - -describe('saved research transfers to available peers', () => { - it('preserves saved notes and source, replaces assignment identity, and rejects late old delivery', async () => { - const f = await fixture(); - const ownerHead = git(f.owner.worktree, ['rev-parse', 'HEAD']); - const ownerNotes = fs.readFileSync(path.join(f.owner.worktree, 'RESEARCH.md'), 'utf8'); - const transferred = await f.cooperative.next(f.idle, budget) as TaskAction; - expect(transferred.task.id).toBe('survey'); - expect(transferred.assignment.workerId).toBe(f.idle.id); - expect(transferred.assignment.assignmentId).not.toBe(f.action.assignment.assignmentId); - expect(assignmentDeliveryFile(transferred.assignment)).not.toBe(assignmentDeliveryFile(f.action.assignment)); - expect(f.cooperative.current(f.action)).toBe(false); - expect(f.cooperative.current(transferred)).toBe(true); - expect(f.cooperative.started(f.idle, transferred)).toBe(true); - expect(fs.readFileSync(path.join(f.idle.worktree, 'RESEARCH.md'), 'utf8')).toContain('uniform bound remains open'); - expect(fs.readFileSync(path.join(f.idle.worktree, f.state.problem.projectRelative, 'Submission.lean'), 'utf8')) - .toContain('Retained independent draft context'); - expect(git(f.owner.worktree, ['rev-parse', 'HEAD'])).toBe(ownerHead); - expect(fs.readFileSync(path.join(f.owner.worktree, 'RESEARCH.md'), 'utf8')).toBe(ownerNotes); - expect(f.state.cooperation!.researchDrafts!.survey).toMatchObject({ workerId: f.idle.id, - assignmentId: transferred.assignment.assignmentId, commit: f.commit, handoffNotesDigest: f.draft.handoffNotesDigest }); - expect(f.state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ producer: f.owner.id, - taskId: 'survey', commit: f.commit, kind: 'progress', status: 'advisory' })); - await f.cooperative.deliver(f.owner, f.action, f.commit); - expect(f.survey.assignment).toBe(transferred.assignment); - expect(f.survey.status).toBe('running'); - expect(checkSolverRunState(f.state).filter(issue => issue.severity === 'error')).toEqual([]); - }); - - it('keeps the newest canonical sources and archives conflicting old draft sources when canonical advanced', async () => { - const f = await fixture(); - fs.appendFileSync(path.join(f.lead.worktree, f.state.problem.projectRelative, 'Submission.lean'), '\n-- New canonical context.\n'); - f.state.cooperation!.canonicalCommit = commitSolverSources(f.state.problem, f.lead.worktree); - const transferred = await f.cooperative.next(f.idle, budget) as TaskAction; - expect(transferred.assignment.workerId).toBe(f.idle.id); - expect(transferred.assignment.seedCommit).not.toBe(f.action.assignment.seedCommit); - const source = fs.readFileSync(path.join(f.idle.worktree, f.state.problem.projectRelative, 'Submission.lean'), 'utf8'); - expect(source).toContain('New canonical context'); - expect(source).not.toContain('Retained independent draft context'); - expect(committedSource(f.lead.worktree, f.commit, `${f.state.problem.projectRelative}/Submission.lean`)) - .toContain('Retained independent draft context'); - expect(fs.readFileSync(path.join(f.idle.worktree, 'RESEARCH.md'), 'utf8')).toContain('uniform bound remains open'); - expect(f.state.cooperation!.researchDrafts!.survey.handoffNotesDigest).toBe(f.draft.handoffNotesDigest); - expect(f.state.cooperation!.researchDrafts!.survey.handoffNotesDigest).toMatch(/^[a-f0-9]{64}$/u); - }); - - it.each(['restore', 'transfer'] as const)('preserves confirmed seed-equal notes and keeps inherited notes unclaimed during %s', async operation => { - const notes = 'The existing reduction needs its exact boundary hypothesis checked for this task.\n'; - for (const acknowledge of [false, true]) for (const canonicalAdvanced of [false, true]) { - const f = await fixture({ inheritedNotes: notes, acknowledge }); - expect(committedSource(f.owner.worktree, f.action.assignment.seedCommit, 'RESEARCH.md')).toBe(notes); - expect(f.draft.handoffNotesDigest).toBe(acknowledge ? mathDigest(notes) : undefined); - if (canonicalAdvanced) { - fs.appendFileSync(path.join(f.lead.worktree, f.state.problem.projectRelative, 'Submission.lean'), '\n-- Canonical advancement.\n'); - f.state.cooperation!.canonicalCommit = commitSolverSources(f.state.problem, f.lead.worktree); - } - const worker = operation === 'restore' ? f.owner : f.idle; - if (operation === 'restore') { - f.cooperative.interrupted(f.owner, f.busy); - f.bridge.task = { ...f.bridge.task, status: 'paused' }; - } - const resumed = await f.cooperative.next(worker, budget) as TaskAction; - expect(resumed.task.id).toBe('survey'); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - // Restoring a snapshot is not a new notes write by the successor model. - expect(committedSource(worker.worktree, resumed.assignment.seedCommit, 'RESEARCH.md')).toBe(notes); - expect(f.state.cooperation!.researchDrafts!.survey.handoffNotesDigest).toBe(acknowledge ? mathDigest(notes) : undefined); - expect(f.survey.proof).toBeUndefined(); - expect(f.survey.researchCompletion).toBeUndefined(); - expect(f.events).toContainEqual({ event: operation === 'restore' ? 'research_draft_restored' : 'research_draft_transferred', - details: expect.objectContaining({ canonicalChanged: canonicalAdvanced }) }); - } - }); - - it('preserves the task unchanged counters and checkpoint backoff when only the writer changes', async () => { - const f = await fixture(); - const inputs = { task: f.survey.task, workerId: f.owner.id, tasks: f.state.cooperation!.tasks, - deliveries: f.state.cooperation!.deliveries ?? [], environmentDigest: f.state.environmentDigest, - problemReceiptDigest: f.state.problem.receiptDigest }; - const checkpoint = { taskDigest: f.action.assignment.taskDigest, - localInputDigest: researchCheckpointLocalInputDigest(inputs), - inputDigest: researchCheckpointInputDigest({ ...inputs, problem: f.state.problem, - worktree: f.lead.worktree, canonicalCommit: f.state.cooperation!.canonicalCommit! }), - outputDigest: researchCheckpointOutputDigest(f.state.problem, f.owner.worktree, f.commit), - count: 2, unchangedEvidenceCount: 2, paused: false, - advisoryCheckpoint: { scope: 'saved-task-scope', noProgressStreak: 2 } }; - f.state.cooperation!.researchCheckpoints = { survey: checkpoint }; - await f.cooperative.next(f.idle, budget); - expect(f.state.cooperation!.researchCheckpoints!.survey).toBe(checkpoint); - expect(checkpoint).toMatchObject({ count: 2, unchangedEvidenceCount: 2, - advisoryCheckpoint: { scope: 'saved-task-scope', noProgressStreak: 2 } }); - expect(checkpoint.localInputDigest).toBe(researchCheckpointLocalInputDigest({ ...inputs, - workerId: f.idle.id, deliveries: f.state.cooperation!.deliveries ?? [] })); - }); - - it('rechecks ownership after asynchronous snapshot inspection before touching the destination worktree', async () => { - const f = await fixture(); - const destinationHead = git(f.idle.worktree, ['rev-parse', 'HEAD']); - const host = f.cooperative as any, inspect = host.inspectResearchDraft.bind(host); - host.inspectResearchDraft = async (...args: unknown[]) => { - const result = await inspect(...args); - f.survey.task = { ...f.survey.task, ownerId: f.owner.id }; - return result; - }; - const assignment = f.survey.assignment; - const waiting = f.inspect(); - await vi.waitFor(() => expect(f.events.some(item => item.event === 'dispatch_wait')).toBe(true)); - expect(f.survey.assignment).toBe(assignment); - expect(git(f.idle.worktree, ['rev-parse', 'HEAD'])).toBe(destinationHead); - expect(f.events.some(item => item.event === 'research_draft_transferred')).toBe(false); - await f.cooperative.stop(); await waiting; - }); - - it('keeps new evidence arriving during snapshot inspection distinct from a writer-only transfer', async () => { - const f = await fixture(); - const inputs = { task: f.survey.task, workerId: f.owner.id, tasks: f.state.cooperation!.tasks, - deliveries: f.state.cooperation!.deliveries ?? [], environmentDigest: f.state.environmentDigest, - problemReceiptDigest: f.state.problem.receiptDigest }; - const checkpoint = { taskDigest: f.action.assignment.taskDigest, - localInputDigest: researchCheckpointLocalInputDigest(inputs), - inputDigest: researchCheckpointInputDigest({ ...inputs, problem: f.state.problem, - worktree: f.lead.worktree, canonicalCommit: f.state.cooperation!.canonicalCommit! }), - outputDigest: researchCheckpointOutputDigest(f.state.problem, f.owner.worktree, f.commit), count: 2 }; - f.state.cooperation!.researchCheckpoints = { survey: checkpoint }; - const oldDigest = checkpoint.localInputDigest; - const host = f.cooperative as any, inspect = host.inspectResearchDraft.bind(host); - host.inspectResearchDraft = async (...args: unknown[]) => { - const result = await inspect(...args); - host.record(f.lead, f.survey.task, 'progress', 'advisory', 'New independent evidence for the exact remaining bound.'); - return result; - }; - const transferred = await f.cooperative.next(f.idle, budget) as TaskAction; - expect(transferred.task.id).toBe('survey'); - expect(checkpoint.localInputDigest).toBe(oldDigest); - expect(checkpoint.localInputDigest).not.toBe(researchCheckpointLocalInputDigest({ ...inputs, - workerId: f.idle.id, deliveries: f.state.cooperation!.deliveries ?? [] })); - }); - - it.each(['owner-pin', 'review', 'scoped-check', 'active-old-writer', 'old-owner-free', 'bad-digest', 'policy'] as const) - ('does not move a saved task with %s', async reason => { - const f = await fixture(); - if (reason === 'owner-pin') f.survey.task = { ...f.survey.task, ownerId: f.owner.id }; - if (reason === 'review') f.survey.task = { ...f.survey.task, reviewScope: 'feasibility' }; - if (reason === 'scoped-check') f.survey.nextCheckId = 'host-check'; - if (reason === 'active-old-writer') (f.cooperative as any).active.set(f.owner.id, - { action: f.action, interrupt: async () => {}, notify: async () => {} }); - if (reason === 'old-owner-free') f.cooperative.interrupted(f.owner, f.busy); - if (reason === 'bad-digest') f.draft.outputDigest = 'invalid'; - if (reason === 'policy') (f.cooperative as any).input.modules = { ...directSolverModules, - M5: { ...directSolverModules.M5, assign: () => undefined } }; - const assignment = f.survey.assignment; - const waiting = f.inspect(); - // Transfer and no-work paths settle asynchronously through the normal wake queue. - await vi.waitFor(() => expect(f.events.some(item => reason === 'bad-digest' - ? item.event === 'research_draft_transfer_failed' : item.event === 'dispatch_wait')).toBe(true)); - expect(f.survey.assignment).toBe(assignment); - expect(f.state.cooperation!.researchDrafts!.survey).toBe(f.draft); - expect(f.events.some(item => item.event === 'research_draft_transferred')).toBe(false); - await f.cooperative.stop(); await waiting; - }); -}); diff --git a/tests/solverRestore.test.ts b/tests/solverRestore.test.ts deleted file mode 100644 index cc0f60e3..00000000 --- a/tests/solverRestore.test.ts +++ /dev/null @@ -1,277 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_STATEMENT } from '../src/math/localExample'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch, parseCooperationPlan, readCooperationPlan } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, committedSource, git, type SolverProblem } from '../src/solver/problem'; -import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; -import { leadResearchInputs } from '../src/solver/contextCompiler'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -describe('cooperative Lead checkpoint restoration', () => { - let directory: string, workspace: string, problem: SolverProblem, state: SolverRunState; - let lead: ResearchWorker, peer: ResearchWorker; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let events: { event: string; details?: Record }[]; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - - const goalTasks = (dependsOn: string[] = []): CooperativeTask[] => problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn, revision: 0, - })); - const savePlan = (tasks: CooperativeTask[]) => { - const plan = parseCooperationPlan(problem, { tasks }); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(plan) + '\n```'); - state.cooperation!.tasks = plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })); - state.cooperation!.groups = plan.groups.map(group => ({ group, turns: 0 })); - return plan; - }; - const create = (requestLead = false) => { - if (requestLead) state.cooperation!.error = 'A Lead assessment is requested.'; - const controller = new AbortController(); - const cooperative = cooperativeResearch({ state, workers: [lead, peer], retrievalRoot: directory, - signal: controller.signal, emit: (event, details) => events.push({ event, details }) }); - instances.push({ cooperative, controller }); - return cooperative; - }; - const restart = async (cooperative: CooperativeResearch) => { - const instance = instances.find(item => item.cooperative === cooperative)!; - instance.controller.abort(); - await cooperative.stop(); - const stateFile = path.join(directory, 'state.json'); - writeSolverRunState(stateFile, state); - state = readSolverRunState(stateFile); - return create(); - }; - const source = (worker = lead) => fs.readFileSync(path.join(worker.worktree, problem.projectRelative, 'Submission.lean'), 'utf8'); - const canonicalSource = () => committedSource(workspace, state.cooperation!.canonicalCommit!, - `${problem.projectRelative}/Submission.lean`); - const writeProof = (worker: ResearchWorker, name: 'add_zero' | 'zero_add', body: string, prefix = '') => { - const target = name === 'add_zero' ? 'n + 0 = n := by sorry' : '0 + n = n := by sorry'; - expect(source(worker)).toContain(target); - fs.writeFileSync(path.join(worker.worktree, problem.projectRelative, 'Submission.lean'), - prefix + source(worker).replace(target, target.replace('by sorry', body))); - }; - const leadAssignment = async (cooperative: CooperativeResearch) => { - const assignment = await cooperative.next(lead, budget); - expect(assignment?.kind).toBe('lead'); - return assignment; - }; - const deliverPeerProof = async (cooperative: CooperativeResearch, name: 'add_zero' | 'zero_add', body: string) => { - const assignment = await cooperative.next(peer, budget); - expect(assignment?.kind).toBe('task'); - if (assignment?.kind !== 'task') throw new Error('missing_peer_assignment'); - expect(assignment.task.theoremName).toBe(`Tutorial.${name}`); - expect(cooperative.started(peer, assignment)).toBe(true); - writeProof(peer, name, body); - await cooperative.deliver(peer, assignment, commitSolverSources(problem, peer.worktree)); - expect(state.cooperation!.tasks.find(node => node.task.id === assignment.task.id)?.status).toBe('integrated'); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verifiedBatch(request, { sessionId: 'restore-fixture' })); - host.createSession.mockReset().mockImplementation(() => { throw new Error('real_models_are_not_used_in_restore_tests'); }); - const example = localExample('solver-restore-test-'); - ({ directory, workspace, problem } = example); - lead = leadWorker(problem, workspace); - peer = peerWorker(example, 'researcher', { name: 'peer' }); - state = solverState(problem, workspace, { runId: 'restore-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, tasks: [] } }); - instances = []; events = []; - savePlan(goalTasks()); - }); - afterEach(async () => { - for (const instance of instances) { - instance.controller.abort(); - await instance.cooperative.stop(); - } - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['$$n + 0 = n$$', '$&', "$'", '$`']) - ('preserves exact mathematical text %s without invalidating completed findings or their consumers', async text => { - const objective = `Investigate ${text}; preserve this mathematical contract exactly.`; - const plan = savePlan([{ id: 'research', kind: 'research', objective, dependsOn: [], revision: 0 }, ...goalTasks(['research'])]); - const research = state.cooperation!.tasks[0]; - research.status = 'completed'; research.attempts = 1; - research.finding = 'A concrete library connection was already established.'; - state.cooperation!.planEdited = true; - const versions = state.cooperation!.tasks.map(node => taskVersion(node.task)); - const cooperative = create(); - - await cooperative.restore(); - - expect(readCooperationPlan(problem, workspace)).toEqual(plan); - expect(state.cooperation!.tasks.map(node => taskVersion(node.task))).toEqual(versions); - expect(state.cooperation!.tasks[0]).toMatchObject({ status: 'completed', finding: research.finding, attempts: 1 }); - expect(events.filter(item => item.event === 'plan_updated').flatMap(item => item.details?.invalidated ?? [])).toEqual([]); - }); - - it('recovers a valid initial saved plan and proceeds without another initial Lead planning turn', async () => { - const plan = readCooperationPlan(problem, workspace); - commitSolverSources(problem, workspace); - state.cooperation!.tasks = []; state.cooperation!.groups = undefined; - const cooperative = create(); - - await cooperative.restore(); - - expect(state.cooperation!.tasks.map(node => node.task)).toEqual(plan.tasks); - const nextLead = cooperative.next(lead, budget); - await deliverPeerProof(cooperative, 'add_zero', 'by rfl'); - await deliverPeerProof(cooperative, 'zero_add', 'by exact Nat.zero_add n'); - expect((await nextLead)?.kind).toBe('assemble'); - expect(state.cooperation!.initialPlanFallback).toBeUndefined(); - }); - - const researchPlan = () => { - const plan = savePlan([{ id: 'question', kind: 'research', objective: 'Investigate the missing bridge.', - dependsOn: [], revision: 0 }, ...goalTasks()]); - const question = state.cooperation!.tasks[0]; - question.status = 'completed'; - state.cooperation!.deliveries = [{ id: 'new-finding', producer: peer.id, taskId: question.task.id, - taskDigest: taskVersion(question.task), kind: 'research', status: 'advisory', statement: '', premises: [], - dependencies: [], remainingObligations: [], summary: 'A bridge is ready for a Lead decision.', evidenceRefs: [], - createdAt: 1, lemmaRequests: [{ id: 'bridge', kind: 'lemma', objective: 'Prove the exact bridge.', - type: 'True', proofPath: 'Submission.lean', theoremName: 'Tutorial.bridge', dependsOn: [], revision: 0 }] }]; - return plan; - }; - - it('keeps inherited accepted notes without rejecting them for research that has not been presented yet', async () => { - researchPlan(); - const before = structuredClone(state.cooperation!.tasks); - const cooperative = create(); - - await cooperative.restore(); - - expect(events.filter(item => item.event === 'plan_rejected')).toEqual([]); - expect(events.filter(item => item.event === 'plan_updated')).toEqual([]); - expect(state.cooperation!.tasks).toMatchObject(before); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - const action = await leadAssignment(cooperative); - expect(cooperative.contextState(action, lead).leadResearchInputIds).toEqual(['new-finding']); - expect(cooperative.leadCheckpointInstruction(action as Extract)) - .toContain('researchDecisions: ["new-finding"]'); - }); - - it('still validates a changed saved draft against pending research inputs on restore', async () => { - const plan = researchPlan(), proposal = state.cooperation!.deliveries![0].lemmaRequests![0]; - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + - JSON.stringify({ ...plan, tasks: [...plan.tasks, proposal] }) + '\n```'); - const cooperative = create(); - - await cooperative.restore(); - - expect(events.filter(item => item.event === 'plan_rejected')).toHaveLength(1); - expect(state.cooperation!.error).toContain('math_plan_research_decisions_missing'); - expect(state.cooperation!.tasks.some(node => node.task.id === proposal.id)).toBe(false); - expect(state.cooperation!.researchDecisions).toBeUndefined(); - }); - - it('recovers an explicit research decision even when the saved graph is unchanged', async () => { - const plan = researchPlan(); - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify({ ...plan, - researchDecisions: [{ deliveryId: 'new-finding', outcome: 'decline', reason: 'The bridge does not resolve the current gap.' }], - }) + '\n```'); - const cooperative = create(); - - await cooperative.restore(); - - expect(events.filter(item => item.event === 'plan_rejected')).toEqual([]); - expect(state.cooperation!.researchDecisions).toContainEqual(expect.objectContaining({ deliveryId: 'new-finding', outcome: 'decline' })); - expect(leadResearchInputs(state.cooperation!.deliveries!, - new Map(state.cooperation!.tasks.map(node => [node.task.id, node])), state.cooperation!.researchDecisions)).toEqual([]); - }); - - it('preserves a committed Lead proof and its new library import after process restoration', async () => { - const cooperative = create(true); - await leadAssignment(cooperative); - writeProof(lead, 'add_zero', 'by rfl', 'import Mathlib.Data.Nat.Basic\n\n'); - commitSolverSources(problem, workspace); - expect(git(workspace, ['diff', 'HEAD', '--name-only', '--', `${problem.projectRelative}/Submission.lean`])).toBe(''); - const resumed = await restart(cooperative); - - await resumed.restore(); - - expect(canonicalSource()).toBe(source()); - expect(canonicalSource()).toContain('import Mathlib.Data.Nat.Basic'); - expect(canonicalSource()).toContain('n + 0 = n := by rfl'); - expect(canonicalSource()).toContain('0 + n = n := by sorry'); - }); - - it('merges an uncommitted Lead proof with a newer independently integrated peer proof', async () => { - savePlan([...goalTasks()].reverse()); - const cooperative = create(true); - await leadAssignment(cooperative); - await deliverPeerProof(cooperative, 'zero_add', 'by exact Nat.zero_add n'); - expect(canonicalSource()).toContain('0 + n = n := by exact Nat.zero_add n'); - expect(source()).toBe(LOCAL_EXAMPLE_STATEMENT); - writeProof(lead, 'add_zero', 'by rfl'); - const resumed = await restart(cooperative); - - await resumed.restore(); - - expect(source()).toContain('n + 0 = n := by rfl'); - expect(source()).toContain('0 + n = n := by exact Nat.zero_add n'); - expect(canonicalSource()).toBe(source()); - expect(state.cooperation!.tasks.find(node => node.task.theoremName === 'Tutorial.zero_add')?.status).toBe('integrated'); - expect(events.filter(item => item.event === 'lead_draft_preserved')).toEqual([]); - }); - - it.each(['unknown-seed', 'conflicting-declaration'] as const) - ('preserves a %s draft as advisory evidence without reverting accepted sources or duplicating recovery records', async scenario => { - const unknownSeed = scenario === 'unknown-seed'; - if (unknownSeed) savePlan([...goalTasks()].reverse()); - const cooperative = create(true); - await leadAssignment(cooperative); - await deliverPeerProof(cooperative, unknownSeed ? 'zero_add' : 'add_zero', - unknownSeed ? 'by exact Nat.zero_add n' : 'by rfl'); - const acceptedSource = canonicalSource(); - const acceptedTask = unknownSeed ? 'Tutorial.zero_add' : 'Tutorial.add_zero'; - const draftBody = unknownSeed ? 'by rfl' : 'by exact Nat.add_zero n'; - writeProof(lead, 'add_zero', draftBody); - if (unknownSeed) delete state.cooperation!.leadSeedCommit; - const resumed = await restart(cooperative); - - await resumed.restore(); - - expect(canonicalSource()).toBe(acceptedSource); - expect(source()).toBe(acceptedSource); - expect(state.cooperation!.tasks.find(node => node.task.theoremName === acceptedTask)?.status).toBe('integrated'); - const preserved = state.cooperation!.deliveries!.filter(record => record.producer === lead.id && record.kind === 'progress'); - expect(preserved).toHaveLength(1); - const delivery = preserved[0]!; - expect(delivery).toMatchObject({ status: 'advisory', summary: expect.stringContaining('Saved Lead draft pending integration:') }); - expect(delivery.evidence).toBeUndefined(); - expect(delivery.commit).toBeTypeOf('string'); - const draftCommit = delivery.commit!; - expect(committedSource(workspace, draftCommit, `${problem.projectRelative}/Submission.lean`)) - .toContain(`n + 0 = n := ${draftBody}`); - expect(git(workspace, ['rev-parse', `refs/math/${state.runId}/evidence/${draftCommit}`])).toBe(draftCommit); - expect(events.filter(item => item.event === 'lead_draft_preserved')).toHaveLength(1); - expect(state.check).toBeUndefined(); - - const secondRestore = await restart(resumed); - await secondRestore.restore(); - - expect(canonicalSource()).toBe(acceptedSource); - expect(state.cooperation!.deliveries!.filter(record => record.producer === lead.id && record.kind === 'progress')) - .toEqual(preserved); - expect(events.filter(item => item.event === 'lead_draft_preserved')).toHaveLength(1); - expect(state.cooperation!.tasks.find(node => node.task.theoremName === acceptedTask)?.status).toBe('integrated'); - expect(state.check).toBeUndefined(); - }); -}); diff --git a/tests/solverRetainedSourceGoals.test.ts b/tests/solverRetainedSourceGoals.test.ts deleted file mode 100644 index d2f07b15..00000000 --- a/tests/solverRetainedSourceGoals.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { TaskProof } from '../src/solver/cooperativeProof'; -import { committedSource, commitSolverSources, readSolverProblem } from '../src/solver/problem'; -import { proofReferencesUnchanged } from '../src/solver/proofReferences'; -import { setTaskStatus } from '../src/solver/taskLifecycle'; -import { freshlyAccepted, markTaskAcceptance, taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { temporaryDirectory } from './helpers/files'; -import { newestLeanBinary } from './helpers/lean'; -import { leadWorker, solverState } from './helpers/solver'; -import { failedBatch, receiptBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), model: vi.fn() })); -vi.mock('../src/math/verifier', async original => ({ ...await original(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'native-retained-source-fixture', -})); -vi.mock('../src/math/mathProofEnvironment', async original => ({ - ...await original(), resolveMathProofEnvironment: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.model })); - -const lean = newestLeanBinary(); -const instances: { directory: string; controller: AbortController; cooperative: CooperativeResearch }[] = []; -afterEach(async () => { - for (const { directory, controller, cooperative } of instances.splice(0)) { - controller.abort(); await cooperative.stop(); fs.rmSync(directory, { recursive: true, force: true }); - } - expect(host.model).not.toHaveBeenCalled(); - vi.restoreAllMocks(); -}); - -const original = [ - 'namespace Retained', - 'structure Box where', - ' value : Nat', - 'theorem first (box : Box) : box.value = box.value := by sorry', - 'def frozen (box : Box) : box.value = box.value := first box', - 'theorem second (box : Box) : box.value = box.value := by sorry', - 'def chain (box : Box) : box.value = box.value := second box', - 'theorem final : True := by sorry', - 'end Retained', '', -].join('\n'); -const firstSolved = original.replace('first (box : Box) : box.value = box.value := by sorry', - 'first (box : Box) : box.value = box.value := by cases box; rfl'); - -type NotationBridge = boolean | 'overloaded'; -async function fixture(chain = false, notation: NotationBridge = false, receiver?: 'box' | '(id box)') { - const directory = temporaryDirectory('solver-retained-source-goals-'); - const bridge = (source: string) => receiver ? source.replace( - 'def frozen (box : Box) : box.value = box.value := first box', [ - 'namespace Box', 'def field (box : Box) : box.value = box.value := first box', 'end Box', - 'namespace Other', 'def field (box : Box) : box.value = box.value := first box', 'end Other', - `def receiverBridge (box : Box) : box.value = box.value := ${receiver}.field`, - 'def frozen (box : Box) : box.value = box.value := receiverBridge box', - ].join('\n')) : notation ? source.replace( - 'def frozen (box : Box) : box.value = box.value := first box', - ['local notation "frozen" => first', - ...(notation === 'overloaded' ? ['local notation (priority := high) "frozen" => (fun box : Box => Eq.refl (Box.value box))'] : []), - 'local notation "notationBridge" => frozen'].join('\n')) : source; - const receipt = bootstrapLeanTask(path.join(directory, 'workspace'), { source: bridge(original), task: 'Prove the original targets.' }); - const workspace = receipt.workspaceRoot, problem = readSolverProblem(workspace, receipt.activeProblemPath); - const records: TaskRecord[] = ['first', 'second', 'final'].map(name => ({ task: { - id: name, kind: 'goal', objective: `Prove ${name}.`, proofPath: 'Submission.lean', theoremName: `Retained.${name}`, - dependsOn: [], revision: 0, - }, status: 'pending', attempts: 0 })); - const helper: CooperativeTask = { id: 'helper', kind: 'lemma', objective: 'Use the original proved context.', - proofPath: 'Submission.lean', theoremName: 'Retained.helper', type: '∀ box : Retained.Box, box.value = box.value', - dependsOn: [], revision: 0 }; - records.push({ task: helper, status: 'pending', attempts: 0 }); - const state = solverState(problem, workspace, { runId: 'retained-source-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, tasks: records } }); - const controller = new AbortController(), worker = leadWorker(problem, workspace); - const envFile = path.join(directory, 'fixture.env'); fs.writeFileSync(envFile, ''); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - const cooperative = cooperativeResearch({ state, workers: [worker], retrievalRoot: directory, signal: controller.signal, - access: new Map([[worker.id, { environment, retrievalRoot: directory }]]) }); - instances.push({ directory, controller, cooperative }); - const nativeChecks: { theorem: string; source: string; output: string; commit: string }[] = []; - host.model.mockReset().mockImplementation(() => { throw new Error('fixture_models_forbidden'); }); - host.verify.mockReset().mockImplementation(async (request: MathematicsVerifierBatchRequest, - options?: { expectedDeclarationType?: string }) => { - const source = committedSource(workspace, request.targetCommit!, `${problem.projectRelative}/Submission.lean`); - const commands = request.items.flatMap(item => [ - `#print ${item.theoremName}`, `#print axioms ${item.theoremName}`, - ...(options?.expectedDeclarationType ? [`example : ${options.expectedDeclarationType} := ${item.theoremName}`] : []), - ]); - const nativeFile = path.join(directory, 'NativeCheck.lean'); - fs.writeFileSync(nativeFile, source + '\n' + commands.join('\n') + '\n'); - const result = spawnSync(lean!, [nativeFile], { cwd: request.projectRoot, encoding: 'utf8', timeout: 20_000 }); - expect(result.error).toBeUndefined(); - const output = `${result.stdout}${result.stderr}`; - for (const item of request.items) nativeChecks.push({ theorem: item.theoremName!, source, output, commit: request.targetCommit! }); - const batch = receiptBatch(request, { sessionId: 'native-retained-source-fixture', - receiptId: (_, name) => `native-${request.targetCommit}-${name}` }); - // A cases proof actually references the structure-generated eliminator. Its - // source region is unavailable, so production fingerprinting binds the module. - for (const item of batch.results) item.declarationReferences = { - statement: [], proof: output.includes('Box.casesOn') ? [{ name: 'Retained.Box.casesOn', file: 'Submission.lean' }] : [], - }; - if (/\b(?:sorry|admit)\b/u.test(source)) return { ...batch, status: 'failed', results: batch.results.map(item => ({ - ...item, status: 'failed', error: 'Proof source contains sorry or admit.', - sorryCount: [...source.matchAll(/\bsorry\b/gu)].length, admitCount: [...source.matchAll(/\badmit\b/gu)].length, - stdoutPreview: output, - })) }; - return result.status === 0 && !output.includes('sorryAx') ? batch : failedBatch(batch, { stdoutPreview: () => output }); - }); - const write = (source: string) => { - fs.writeFileSync(path.join(receipt.projectRoot, 'Submission.lean'), source); - const commit = commitSolverSources(problem, workspace); state.cooperation!.canonicalCommit = commit; return commit; - }; - const check = async (task: CooperativeTask, commit: string, seedCommit = commit, retained: string[] = [], - conditions: CooperativeTask[] = []): Promise => { - try { - return await (cooperative as any).check(task, { taskId: task.id, taskDigest: taskVersion(task), workerId: worker.id, seedCommit, - dependencies: conditions.map(condition => ({ taskId: condition.id, taskDigest: taskVersion(condition) })) }, - workspace, commit, conditions, undefined, false, false, records, undefined, retained); - } catch (error) { - throw new Error(`${error instanceof Error ? error.message : error}\n${nativeChecks.at(-1)?.output ?? ''}\n${nativeChecks.at(-1)?.source ?? ''}`); - } - }; - const accept = async (id: string, commit: string, seed: string, retained: string[] = []) => { - const record = records.find(node => node.task.id === id)!; - const proof = await check(record.task, commit, seed, retained); - expect(proof.passed, JSON.stringify(proof.verification)).toBe(true); - record.proof = record.integratedCheck = proof; setTaskStatus(record, 'integrated', 'integrated'); - expect(freshlyAccepted(record, taskVersion(record.task))).toBe(true); return record; - }; - const firstCommit = write(bridge(firstSolved)), first = await accept('first', firstCommit, problem.baseCommit); - let source = bridge(firstSolved), seed = firstCommit; - if (chain) { - source = source.replace('second (box : Box) : box.value = box.value := by sorry', - 'second (box : Box) : box.value = box.value := by exact frozen box'); - seed = write(source); await accept('second', seed, firstCommit, ['Retained.first']); - } - const candidateSource = source.replace('theorem final', - `theorem helper (box : Box) : box.value = box.value := by exact ${chain ? 'chain' : notation ? 'notationBridge' : 'frozen'} box\n` + - 'theorem unrelated : True := by trivial\ntheorem final'); - const candidate = write(candidateSource); - const retained = () => (cooperative as any).retainedTaskGoals(helper, records, workspace, candidate) as string[]; - return { directory, workspace, problem, state, worker, cooperative, first, records, helper, seed, candidate, candidateSource, - nativeChecks, write, check, retained }; -} - -describe.skipIf(!lean)('fresh original source retention before independent kernel checks', () => { - it.each((['box', '(id box)'] as const).flatMap(receiver => - (['fresh', 'unaccepted', 'serialized', 'conditional', 'stale-version'] as const).map(kind => ({ receiver, kind })))) - ('requires fresh acceptance for ambiguous $receiver field context ($kind)', async ({ receiver, kind }) => { - const f = await fixture(false, false, receiver), old = f.first.integratedCheck!; - if (kind === 'unaccepted') setTaskStatus(f.first, 'pending', 'reconstructed'); - if (kind === 'serialized') { - f.first.integratedCheck = structuredClone(old); - (f.cooperative as any).checkedDeliveries.add(f.first.integratedCheck); - } - if (kind === 'conditional') { - old.conditions = [{ taskId: 'unfinished', taskDigest: 'unfinished-version' }]; markTaskAcceptance(old); - } - if (kind === 'stale-version') f.first.task = { ...f.first.task, revision: f.first.task.revision + 1 }; - expect(f.helper.dependsOn).toEqual([]); - expect(f.retained()).toEqual(kind === 'fresh' ? ['Retained.first'] : []); - const before = f.nativeChecks.length; - const proof = await f.check(f.helper, f.candidate, f.seed); - expect(proof.passed, JSON.stringify(proof.verification)).toBe(kind === 'fresh'); - expect(f.nativeChecks.length).toBeGreaterThan(before); - expect(f.nativeChecks.at(-1)!.source.includes('theorem first')).toBe(kind === 'fresh'); - expect(f.records.find(node => node.task.id === 'helper')!.integratedCheck).toBeUndefined(); - if (kind === 'fresh') { - const checked = f.nativeChecks.at(-1)!; - for (const declaration of ['def field', 'def receiverBridge', 'def frozen']) expect(checked.source).toContain(declaration); - expect(checked.output).not.toContain('sorryAx'); - expect(proof.verification.targetCommit).toBe(checked.commit); - expect(proof.verification.targetCommit).not.toBe(old.verification.targetCommit); - expect(proof.verification.results[0].receiptId).not.toBe(old.verification.results[0].receiptId); - } - }); - - it('rechecks source after generated references bind an older whole module', async () => { - const f = await fixture(), old = f.first.integratedCheck!; - expect(f.nativeChecks[0].output).toContain('Box.casesOn'); - expect(old.references!.inputs).toContainEqual(expect.objectContaining({ file: 'Submission.lean', digest: expect.any(String) })); - expect(old.references!.inputs.some(input => !input.name)).toBe(true); - expect(proofReferencesUnchanged(f.problem, f.workspace, f.candidate, old.references!, 'environment')).toBe(false); - expect(f.retained()).toEqual(['Retained.first']); - const before = f.nativeChecks.length, proof = await f.check(f.helper, f.candidate, f.seed); - expect(proof.passed).toBe(true); expect(f.nativeChecks).toHaveLength(before + 1); - const checked = f.nativeChecks.at(-1)!; - expect(checked.theorem).toBe('Retained.helper'); - expect(checked.source).toContain('theorem first'); expect(checked.source).toContain('def frozen'); - expect(checked.output).not.toContain('sorryAx'); - expect(proof.verification.targetCommit).toBe(checked.commit); - expect(proof.verification.targetCommit).not.toBe(old.verification.targetCommit); - expect(proof.verification.results[0].receiptId).not.toBe(old.verification.results[0].receiptId); - expect(old).toBe(f.first.integratedCheck); - }); - - it('retains the transitive original inputs reached through definition chains', async () => { - const f = await fixture(true); - expect(f.helper.dependsOn).toEqual([]); - expect(f.retained().sort()).toEqual(['Retained.first', 'Retained.second']); - const proof = await f.check(f.helper, f.candidate, f.seed); - expect(proof.passed).toBe(true); - const checked = f.nativeChecks.at(-1)!; - for (const declaration of ['theorem first', 'theorem second', 'def frozen', 'def chain']) - expect(checked.source).toContain(declaration); - expect(checked.output).not.toContain('sorryAx'); - }); - - it.each([ - { mode: 'live', notation: false }, { mode: 'restored', notation: false }, - { mode: 'live', notation: true }, { mode: 'restored', notation: true }, - { mode: 'live', notation: 'overloaded' }, { mode: 'restored', notation: 'overloaded' }, - ] as const) - ('integrates a $mode new helper using accepted originals absent from explicit dependencies (notation: $notation)', async ({ mode, notation }) => { - const f = await fixture(true, notation), node = f.records.find(record => record.task.id === f.helper.id)!; - // Worker delivery introduces the helper; canonical still contains only the - // accepted original goals and the definitions that depend on their proofs. - f.state.cooperation!.canonicalCommit = f.seed; - expect(committedSource(f.workspace, f.seed, `${f.problem.projectRelative}/Submission.lean`)) - .not.toContain('theorem helper'); - expect(f.helper.dependsOn).toEqual([]); - expect(f.retained().sort()).toEqual(['Retained.first', 'Retained.second']); - const beforeNativeChecks = f.nativeChecks.length; - node.assignment = { taskId: f.helper.id, taskDigest: taskVersion(f.helper), workerId: f.worker.id, - seedCommit: f.seed, assignmentId: `retained-source-${mode}`, dependencies: [] }; - const delivered = await f.check(f.helper, f.candidate, f.seed); - expect(delivered.passed).toBe(true); - expect(f.nativeChecks.length).toBeGreaterThan(beforeNativeChecks); - expect(delivered.conditions ?? []).toEqual([]); - const submitted = mode === 'restored' ? JSON.parse(JSON.stringify(delivered)) as TaskProof : delivered; - expect((f.cooperative as any).checkedDeliveries.has(submitted)).toBe(mode === 'live'); - node.proof = submitted; - node.attempts = 1; - setTaskStatus(node, 'delivered', 'reconstructed'); - - await (f.cooperative as any).integrateNow(node); - - expect(node.status, node.feedback).toBe('integrated'); - expect(node.integratedCheck?.passed).toBe(true); - expect(node.integratedCheck?.commit).toBe(f.state.cooperation!.canonicalCommit); - expect(node.integratedCheck?.conditions ?? []).toEqual([]); - expect(freshlyAccepted(node, taskVersion(node.task))).toBe(true); - const checked = f.nativeChecks.at(-1)!; - for (const declaration of ['theorem helper', 'theorem first', 'theorem second', 'def chain', - ...(notation ? ['local notation "frozen"', 'local notation "notationBridge"'] : ['def frozen'])]) - expect(checked.source).toContain(declaration); - expect(checked.output).not.toContain('sorryAx'); - expect(node.integratedCheck?.verification.targetCommit).toBe(checked.commit); - expect(committedSource(f.workspace, f.state.cooperation!.canonicalCommit!, `${f.problem.projectRelative}/Submission.lean`)) - .toContain('theorem helper'); - for (const dependency of f.records.filter(record => ['first', 'second'].includes(record.task.id))) { - expect(dependency.status).toBe('integrated'); - expect(freshlyAccepted(dependency, taskVersion(dependency.task))).toBe(true); - } - }); - - it('retains fresh context used only by the type of a frozen conditional input', async () => { - const f = await fixture(); - const assumption: CooperativeTask = { id: 'assumed', kind: 'lemma', objective: 'Prove the conditional input.', - theoremName: 'Retained.assumed', proofPath: 'Submission.lean', - type: '∀ box : Retained.Box, Retained.frozen box = Retained.frozen box', dependsOn: [], revision: 0 }; - const task = { ...f.helper, type: 'True', dependsOn: [assumption.id], conditional: true }; - f.records.find(node => node.task.id === task.id)!.task = task; - f.records.push({ task: assumption, status: 'pending', attempts: 0 }); - const commit = f.write(f.candidateSource.replace( - 'theorem helper (box : Box) : box.value = box.value := by exact frozen box', - 'theorem helper : True := by have := assumed; trivial')); - const proof = await f.check(task, commit, commit, [], [assumption]); - expect(proof.passed).toBe(true); - expect(proof.conditions).toEqual([{ taskId: assumption.id, taskDigest: taskVersion(assumption) }]); - expect(proof.projection).toBeDefined(); - const checked = f.nativeChecks.at(-1)!; - expect(checked.source).toContain('theorem first'); expect(checked.source).toContain('def frozen'); - expect(checked.source).toContain('theorem helper : theorem_os_conditional_type%'); - expect(checked.source).toContain('∀ box : Retained.Box, Retained.frozen box = Retained.frozen box'); - expect(checked.output).not.toContain('sorryAx'); - expect(proof.verification.targetCommit).toBe(checked.commit); - expect(freshlyAccepted({ task, attempts: 0, status: 'integrated', integratedCheck: proof }, taskVersion(task))).toBe(false); - }); - - it.each(['fresh', 'unaccepted', 'serialized', 'conditional', 'stale-version'] as const) - ('checks a short conditional type with %s original context', async kind => { - const f = await fixture(), originalProof = f.first.integratedCheck!; - const condition: CooperativeTask = { id: 'assumed', kind: 'lemma', objective: 'Prove the frozen conditional input.', - theoremName: 'Retained.assumed', proofPath: 'Submission.lean', - type: '∀ box : Retained.Box, first box = first box', dependsOn: [], revision: 0 }; - const task = { ...f.records.find(node => node.task.id === 'final')!.task, - dependsOn: [condition.id], conditional: true }; - f.records.find(node => node.task.id === task.id)!.task = task; - f.records.push({ task: condition, status: 'pending', attempts: 0 }); - const commit = f.write(f.candidateSource.replace('theorem final : True := by sorry', - 'theorem final : True := by trivial')); - if (kind === 'unaccepted') setTaskStatus(f.first, 'pending', 'reconstructed'); - if (kind === 'serialized') { - f.first.integratedCheck = structuredClone(originalProof); - (f.cooperative as any).checkedDeliveries.add(f.first.integratedCheck); - } - if (kind === 'conditional') { - originalProof.conditions = [{ taskId: 'unfinished', taskDigest: 'unfinished-version' }]; - markTaskAcceptance(originalProof); - } - if (kind === 'stale-version') f.first.task = { ...f.first.task, revision: f.first.task.revision + 1 }; - const retained = (f.cooperative as any).retainedTaskGoals(task, f.records, f.workspace, commit, [condition]); - expect(retained).toEqual(kind === 'fresh' ? ['Retained.first'] : []); - const before = f.nativeChecks.length, proof = await f.check(task, commit, commit, [], [condition]); - expect(f.nativeChecks.length).toBeGreaterThan(before); - expect(proof.passed, JSON.stringify(proof.verification)).toBe(kind === 'fresh'); - expect(proof.conditions).toEqual([{ taskId: condition.id, taskDigest: taskVersion(condition) }]); - expect(f.nativeChecks.at(-1)!.source).toContain('theorem final : theorem_os_conditional_type%'); - expect(f.nativeChecks.at(-1)!.source).toContain('∀ box : Retained.Box, first box = first box'); - expect(f.nativeChecks.at(-1)!.source.includes('theorem first')).toBe(kind === 'fresh'); - if (kind === 'fresh') expect(f.nativeChecks.at(-1)!.output).not.toContain('sorryAx'); - expect(f.records.find(node => node.task.id === task.id)!.integratedCheck).toBeUndefined(); - }); - - it.each(([false, true, 'overloaded'] as const).flatMap(notation => (['unaccepted', 'serialized', 'conditional', 'stale-version'] as const) - .map(kind => ({ notation, kind })))) - ('does not authorize source retention from $kind inputs (notation: $notation)', async ({ kind, notation }) => { - const f = await fixture(false, notation), proof = f.first.integratedCheck!; - if (kind === 'unaccepted') setTaskStatus(f.first, 'pending', 'reconstructed'); - if (kind === 'serialized') { - f.first.integratedCheck = structuredClone(proof); - // Even a receipt seen by this run must retain its unforgeable acceptance. - (f.cooperative as any).checkedDeliveries.add(f.first.integratedCheck); - } - if (kind === 'conditional') { - proof.conditions = [{ taskId: 'unfinished', taskDigest: 'unfinished-version' }]; markTaskAcceptance(proof); - } - if (kind === 'stale-version') f.first.task = { ...f.first.task, revision: f.first.task.revision + 1 }; - expect(f.retained()).toEqual([]); - const result = await f.check(f.helper, f.candidate, f.seed).catch(error => error as Error); - expect(result instanceof Error || !result.passed).toBe(true); - expect(f.records.find(node => node.task.id === 'helper')!.integratedCheck).toBeUndefined(); - }); - - it.each(([false, 'overloaded'] as const).flatMap(notation => (['incorrect', 'sorry'] as const).map(kind => ({ notation, kind })))) - ('rejects $kind current source despite a previously accepted input (notation: $notation)', async ({ kind, notation }) => { - const f = await fixture(false, notation); - const badSource = f.candidateSource.replace('by cases box; rfl', kind === 'sorry' ? 'by sorry' : 'by exact False.elim'); - const commit = f.write(badSource), before = f.nativeChecks.length; - expect((f.cooperative as any).retainedTaskGoals(f.helper, f.records, f.workspace, commit)).toEqual(['Retained.first']); - // The faulty source is inherited from this assignment seed. Revalidation must - // reject it even when no diff policy is responsible for checking the old input. - const proof = await f.check(f.helper, commit); - expect(proof.passed).toBe(false); expect(f.nativeChecks.length).toBeGreaterThan(before); - expect(f.nativeChecks.at(-1)!.source).toContain(kind === 'sorry' ? 'by sorry' : 'by exact False.elim'); - expect(proof.verification.results[0].status).toBe('failed'); - expect(freshlyAccepted({ task: f.helper, attempts: 0, status: 'integrated', integratedCheck: proof }, taskVersion(f.helper))).toBe(false); - }); -}); diff --git a/tests/solverRoutePreflightScheduling.test.ts b/tests/solverRoutePreflightScheduling.test.ts deleted file mode 100644 index 78a7cf5f..00000000 --- a/tests/solverRoutePreflightScheduling.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import fs from 'node:fs'; -import { setTimeout as delay } from 'node:timers/promises'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { TaskTypePreflightCache, type TaskTypePreflight } from '../src/solver/taskTypePreflight'; -import { parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch, workerDeliveryModules } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -type Check = Awaited>; -type Action = Extract; -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -describe('route capacity during concurrent host preflight', () => { - let directory: string, state: SolverRunState, controller: AbortController, scheduler: CooperativeResearch; - let first: ResearchWorker, second: ResearchWorker; - const active = new Map void }[]>(); - const waits: Promise[] = []; - const events: { name: string; detail?: Record }[] = []; - const next = (worker: ResearchWorker) => { - const result = scheduler.next(worker, budget); - waits.push(result); - void result.catch(() => {}); - return result; - }; - const held = (id: string, index = 0) => active.get(id)![index]!; - const names = () => [...active].flatMap(([id, calls]) => calls.map(() => id)); - const busy = () => state.cooperation!.groups!.find(group => group.group.id === 'main')?.busy; - const node = (id: string) => state.cooperation!.tasks.find(task => task.task.id === id)!; - const assigned = () => events.filter(event => event.name === 'task_assigned').map(event => event.detail?.taskId); - const waitUntil = async (predicate: () => boolean) => { - for (let retry = 0; !predicate() && retry < 20; retry++) await new Promise(resolve => setImmediate(resolve)); - expect(predicate()).toBe(true); - }; - beforeEach(() => { - active.clear(); events.length = 0; - const example = localExample('route-preflight-contention-', 'lead'); - directory = example.directory; - const lead = leadWorker(example.problem, example.workspace); - first = peerWorker(example, 'first'); second = peerWorker(example, 'second'); - const workers = [lead, first, second]; - const plan = parseCooperationPlan(example.problem, { tasks: [ - { id: 'first_helper', kind: 'lemma', objective: 'First independent helper', theoremName: 'Tutorial.first_helper', - proofPath: 'Submission.lean', type: 'True', ownerId: first.id }, - { id: 'second_helper', kind: 'lemma', objective: 'Second independent helper', theoremName: 'Tutorial.second_helper', - proofPath: 'Submission.lean', type: 'True', ownerId: second.id }, - ...example.problem.targets.map((target, index) => ({ id: 'goal_' + index, kind: 'goal', - objective: 'Frozen target', theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ], groups: [{ id: 'main', objective: 'Run one proof at a time.', maxConcurrent: 1 }, - { id: 'other', objective: 'Independent route with its own capacity.', maxConcurrent: 1 }] }); - state = solverState(example.problem, example.workspace, { runId: 'preflight-replay', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: example.problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - controller = new AbortController(); - scheduler = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - modules: workerDeliveryModules, emit: (name, detail) => events.push({ name, detail }) }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(({ task, signal }) => { - const gate = deferred(); - const calls = active.get(task.id) ?? []; - calls.push({ signal: signal!, finish: () => gate.resolve({ current: () => true, - result: { status: 'elaborated', inputDigest: task.id, taskDigest: taskVersion(task), reason: 'fixture', - evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } as TaskTypePreflight }) }); - active.set(task.id, calls); - return gate.promise; - }); - }); - afterEach(async () => { - controller.abort(); - for (const calls of active.values()) for (const call of calls) call.finish(); - await Promise.allSettled(waits.splice(0)); - await scheduler.stop(); - vi.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('holds the final route slot from preflight through model dispatch', async () => { - const firstPending = next(first); - const secondPending = next(second); - await waitUntil(() => state.workers![2].scheduling?.wait !== undefined); - expect(names()).toEqual(['first_helper']); - expect(assigned()).toEqual([]); - expect(busy()).toBe(1); - expect(held('first_helper').signal.aborted).toBe(false); - held('first_helper').finish(); - const firstAction = await firstPending as Action; - expect(firstAction.task.id).toBe('first_helper'); - expect(busy()).toBe(1); - expect(names()).toEqual(['first_helper']); - expect(node('second_helper')).toMatchObject({ status: 'pending', attempts: 0 }); - - scheduler.release(first, firstAction); - await waitUntil(() => active.has('second_helper')); - held('second_helper').finish(); - expect(await secondPending).toMatchObject({ kind: 'task', task: { id: 'second_helper' } }); - expect(names()).toEqual(['first_helper', 'second_helper']); - expect(assigned()).toEqual(['first_helper', 'second_helper']); - }); - - it('retains the concurrent preflight on a separate route', async () => { - node('second_helper').task = { ...node('second_helper').task, groupId: 'other' }; - const firstPending = next(first); - const secondPending = next(second); - await waitUntil(() => names().length === 2); - held('first_helper').finish(); - expect(await firstPending).toMatchObject({ kind: 'task', task: { id: 'first_helper' } }); - expect(held('second_helper').signal.aborted).toBe(false); - held('second_helper').finish(); - expect(await secondPending).toMatchObject({ kind: 'task', task: { id: 'second_helper' } }); - expect(names()).toEqual(['first_helper', 'second_helper']); - }); - - it('keeps a stopped owner’s assignment when the peer preflight is cancelled', async () => { - node('second_helper').task = { ...node('second_helper').task, status: 'paused' }; - const original = next(first); - held('first_helper').finish(); - const firstAction = await original as Action; - expect(scheduler.started(first, firstAction)).toBe(true); - scheduler.stopped(first); - const takeover = next(second); - await waitUntil(() => active.get('first_helper')?.length === 2); - expect(node('first_helper').assignment).toBe(firstAction.assignment); - - scheduler.stopped(second); - expect(held('first_helper', 1).signal.aborted).toBe(true); - held('first_helper', 1).finish(); - expect(await takeover).toBeUndefined(); - expect(node('first_helper').assignment).toBe(firstAction.assignment); - expect(events.some(event => event.name === 'task_assignment_released')).toBe(false); - expect(busy()).toBe(0); - }); - - it('wakes an idle peer for fixed review when the preferred worker enters cooldown', async () => { - node('first_helper').task = { ...node('first_helper').task, status: 'paused' }; - node('second_helper').task = { ...node('second_helper').task, status: 'paused' }; - const commit = state.cooperation!.canonicalCommit!; - scheduler.requireReview({ commit, sourceDigest: 'fixture-source', passed: true, - verification: { schema: 'deepscientist.mathematics.verification-batch/v1', sessionId: 'fixture', - status: 'kernel_verified', results: [], targetCommit: commit, events: [], startedAt: 0, checkedAt: 0, durationMs: 0 } }); - const offered = next(second); - expect(await Promise.race([offered, delay(30, 'waiting')])).toBe('waiting'); - state.workers![1]!.recovery = { phase: 'cooling-down', reason: 'math_model_request_failed', cycles: 4, - nextRetryAt: Date.now() + 300_000, startedAt: Date.now(), waitedMs: 0 }; - scheduler.workerAvailabilityChanged(); - expect(await Promise.race([offered, delay(1000, 'waiting')])).toMatchObject({ kind: 'review', seedCommit: commit }); - expect(state.cooperation!.review).toMatchObject({ status: 'running', workerId: second.id }); - }); - - it('gives fixed review to the idle peer while the preferred worker is in preflight', async () => { - node('second_helper').task = { ...node('second_helper').task, status: 'paused' }; - const firstPending = next(first); - await waitUntil(() => names().length === 1); - const commit = state.cooperation!.canonicalCommit!; - scheduler.requireReview({ commit, sourceDigest: 'fixture-source', passed: true, - verification: { schema: 'deepscientist.mathematics.verification-batch/v1', sessionId: 'fixture', - status: 'kernel_verified', results: [], targetCommit: commit, events: [], startedAt: 0, checkedAt: 0, durationMs: 0 } }); - expect(state.workers![1].scheduling).toMatchObject({ status: 'preparing', taskId: 'first_helper' }); - expect(state.workers![2].scheduling?.status).toBe('idle'); - expect(await Promise.race([next(second), delay(1000, 'waiting')])).toMatchObject({ kind: 'review', seedCommit: commit }); - expect(state.cooperation!.review).toMatchObject({ status: 'running', workerId: second.id }); - expect(held('first_helper').signal.aborted).toBe(false); - held('first_helper').finish(); - expect(await firstPending).toMatchObject({ kind: 'task', task: { id: 'first_helper' } }); - }); -}); diff --git a/tests/solverRouteRetirement.test.ts b/tests/solverRouteRetirement.test.ts index cafe4314..12113a14 100644 --- a/tests/solverRouteRetirement.test.ts +++ b/tests/solverRouteRetirement.test.ts @@ -1,204 +1,153 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { parseLeadPlan } from '../src/solver/cooperationShared'; -import { routeAllowsTask } from '../src/solver/modules/search'; -import { runResearchWorkers } from '../src/solver/research'; -import { parseCooperationPlan } from '../src/solver/tasks'; +import { bootstrapLeanTask } from '../src/math/leanTask'; +import { mathDigest } from '../src/math/mathRuntimeIo'; +import { readMathAgentSkill } from '../src/runtime/agentSkills'; +import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; +import type { NativeAgentControlConnection } from '../src/runtime/nativeAgentControl'; +import { AgentResearchTeam } from '../src/solver/agentTeam'; +import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; +import { directSolverModules } from '../src/solver/modules'; +import { readSolverProblem } from '../src/solver/problem'; +import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; import { deferred } from './helpers/async'; -import { workerAccess, workerDeliveryModules } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import './helpers/solverTeamRouteRetirement'; +import { temporaryDirectory } from './helpers/files'; +import { solverState } from './helpers/solver'; -vi.mock('../src/math/mathBuildManifest', async importOriginal => ({ - ...await importOriginal(), readMathBuildManifest: vi.fn(), -})); - -const directories: string[] = []; -afterEach(() => { for (const directory of directories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }); }); -const budget = { maxTurns: 100, remainingMs: 30_000 }; - -class FixtureResearch extends CooperativeResearch { - async publish(value: unknown) { - return this.acceptPlan(parseLeadPlan(this.input.state.problem, value, this.planPatchBase())); - } -} +const goal = 'Show True.'; +const rootThreadId = '00000000-0000-4000-8000-000000000001'; +const cleanup: Array<() => Promise> = []; +afterEach(async () => { + for (const close of cleanup.splice(0)) await close(); +}); -function fixture(startWithPlan = true) { - const example = localExample('retire-cooperative-route-'); - directories.push(example.directory); - const { problem, workspace } = example; - const lead = leadWorker(problem, workspace), peer = peerWorker(example, 'peer'); - const workers = [lead, peer], file = path.join(example.directory, 'state.json'); - const originalGoals = problem.targets.map((target, index) => ({ - id: 'goal_' + index, kind: 'goal', objective: 'Prove ' + target.theoremName, ...target, - status: 'paused', - })); - const tasks = [ - { id: 'dead_active', kind: 'research', groupId: 'dead', objective: 'Check the failing approach.', ownerId: peer.id }, - { id: 'dead_queued', kind: 'research', groupId: 'dead', objective: 'Extend the failing approach.', ownerId: peer.id, - dependsOn: ['dead_active'] }, - { id: 'live_ready', kind: 'research', objective: 'Explore the independent approach.', ownerId: peer.id, status: 'paused' }, - ...originalGoals, - ]; - const groups = [{ id: 'main', objective: 'Frozen goal and viable route' }, - { id: 'dead', objective: 'A candidate route to falsify', maxConcurrent: 1 }]; - const parsed = parseCooperationPlan(problem, { tasks, groups }); - const state = solverState(problem, workspace, { runId: 'route-retirement-fixture', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - ...(startWithPlan ? { cooperation: { canonicalCommit: problem.baseCommit, - tasks: parsed.tasks.map(task => ({ task, status: 'pending' as const, attempts: 0 })), - groups: parsed.groups.map(group => ({ group, turns: 0 })) } } : {}) }); - const controller = new AbortController(); - const emit = vi.fn(); - const research = (snapshot = state) => new FixtureResearch({ - state: snapshot, workers, access: workerAccess(workers, example.directory), modules: workerDeliveryModules, - signal: controller.signal, save: () => writeSolverRunState(file, snapshot), emit, - exclusiveCheck: async check => check(), - }); - return { ...example, state, file, lead, peer, originalGoals, groups, research, emit }; +function nativeConnection(threadId: string, agentPath: string, cwd: string): NativeAgentControlConnection { + return { + info: { sessionId: rootThreadId, agent: { threadId, metadata: { threadId, agentPath }, status: 'running' }, + configSnapshot: { cwd } }, + request: vi.fn(async () => ({})), + input: vi.fn(async () => ({ accepted: true, threadId, submissionId: 'followup' })), + update: vi.fn(async request => ({ acceptedSequence: request.sequence })), + }; } -describe('cooperative route retirement', () => { - it('atomically saves retirement, interrupts the active branch, and dispatches a viable successor', async () => { - const f = fixture(), research = f.research(); - try { - const action = await research.next(f.peer, budget); - if (action?.kind !== 'task') throw new Error('Expected a route assignment.'); - expect(action.task.id).toBe('dead_active'); - expect(research.started(f.peer, action)).toBe(true); - const interrupt = vi.fn(async () => { - const saved = readSolverRunState(f.file).cooperation!; - expect(saved.retiredRoutes).toMatchObject([{ routeId: 'dead', reason: 'Counterexample at zero', evidenceRefs: ['probe-zero'] }]); - expect(saved.tasks.find(node => node.task.id === 'dead_active')?.status).toBe('blocked'); - expect(saved.groups?.find(route => route.group.id === 'dead')?.busy).toBe(0); - }); - research.activate(f.peer, action, interrupt, async () => {}); - const baseVersion = f.state.cooperation!.planVersion; - await expect(research.publish({ baseVersion, retireRoutes: [{ routeId: 'dead', reason: '' }] })) - .rejects.toThrow('math_plan_invalid_retire_routes'); - expect(interrupt).not.toHaveBeenCalled(); - expect(research.current(action)).toBe(true); - await research.publish({ baseVersion, upsert: [{ id: 'live_ready', status: 'active' }], - retireRoutes: [{ routeId: 'dead', reason: 'Counterexample at zero', evidenceRefs: ['probe-zero'] }] }); - expect(f.emit).toHaveBeenCalledWith('cooperative_route_retired', expect.objectContaining({ routeId: 'dead' })); - expect(interrupt).toHaveBeenCalledTimes(1); - // Observe errors inside the awaited interruption callback as well. - await interrupt.mock.results[0].value; - expect(research.current(action)).toBe(false); - expect(f.state.cooperation!.tasks.filter(node => node.task.groupId === 'dead').map(node => - ({ status: node.status, policy: node.task.status, attempts: node.attempts, owner: node.assignment?.workerId }))) - .toEqual([{ status: 'blocked', policy: 'stopped', attempts: 1, owner: undefined }, - { status: 'blocked', policy: 'stopped', attempts: 0, owner: undefined }]); - research.interrupted(f.peer, action); - research.deactivate(f.peer); - expect(await research.next(f.peer, budget)).toMatchObject({ kind: 'task', task: { id: 'live_ready' } }); - expect(JSON.parse(fs.readFileSync(path.join(f.peer.worktree, 'COOPERATION.json'), 'utf8')).retiredRoutes) - .toMatchObject([{ routeId: 'dead', source: 'lead' }]); - - const restored = readSolverRunState(f.file); - const resumed = f.research(restored); - try { - await resumed.publish({ baseVersion: restored.cooperation!.planVersion, - groups: f.groups, upsert: [{ id: 'dead_queued', status: 'active' }, - { id: 'replacement', kind: 'research', groupId: 'dead', objective: 'Retry the retired route.' }] }); - const dead = restored.cooperation!.tasks.filter(node => node.task.groupId === 'dead'); - expect(dead).toHaveLength(3); - expect(dead.every(node => node.task.status === 'stopped' && node.status === 'blocked')).toBe(true); - expect(dead.map(node => node.attempts)).toEqual([1, 0, 0]); - } finally { await resumed.stop(); } - } finally { await research.stop(); } +function fixture() { + const directory = temporaryDirectory('team-route-retirement-'); + const task = bootstrapLeanTask(path.join(directory, 'lead'), { source: 'theorem target : True := by sorry\n', task: goal }); + const problem = readSolverProblem(task.workspaceRoot, task.activeProblemPath); + const root = process.cwd(); + const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); + const state = solverState(problem, task.workspaceRoot, { runId: 'team-route-retirement', phase: 'running', + environmentDigest: mathDigest('offline route retirement fixture'), + researchMode: 'skill', researchSkillWorkflow: 'full', researchSkill: identity, workerCount: 1, + researchDelegation: { mode: 'team', maxAgents: 2 }, + agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [] } }); + const skill = prepareResearchSkill(root, state.worktree, identity, problem); + const controller = new AbortController(), stateFile = path.join(directory, 'state.json'); + const current = new Map; stopped: ReturnType; + interrupt: () => Promise; finish: () => void; context?: string }>(); + const teams: AgentResearchTeam[] = []; + const open = async (options: MathAgentOptions): Promise => { + const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; + const config = options.nativeAgentControl!; + const threadId = options.threadId ?? String(config.bootstrap!.threadId); + const connection = nativeConnection(threadId, '/root/' + id, options.workspace); + await config.request({ version: 1, threadId, sessionId: rootThreadId, operation: 'attach', operationId: 'attach-' + id, + payload: { threadId, sessionId: rootThreadId } }, connection, { signal: controller.signal }); + await config.bound?.(connection); + const started = deferred(), stopped = deferred(), outcome = deferred(); + const record = { started, stopped, interrupt: vi.fn(async () => { outcome.resolve('interrupted'); }), + finish: () => { stopped.resolve(); outcome.resolve('completed'); }, context: undefined as string | undefined }; + current.set(id, record); + return { threadId, usageSource: 'upstream-requests', nativeAgentControl: connection, + run: async (message, _id, _workspace, onStarted) => { + record.context = message; onStarted('turn-' + id); started.resolve(); return outcome.promise; + }, + interrupt: record.interrupt, stopForFreeze: async () => { await stopped.promise; return { status: 'stopped' }; }, + close: async () => { await config.disconnected?.(connection); } }; + }; + const create = (saved: SolverRunState) => { + const team = new AgentResearchTeam({ state: saved, root, taskText: goal, + leadAccess: { researchSkill: skill, environment: {}, retrievalRoot: saved.worktree }, + executable: 'offline', profile: 'offline', signal: controller.signal, + modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, + maxAgents: 2, maxTurns: Infinity, maxTotalTokens: 0, maxTurnMs: Infinity, remainingMs: () => Infinity, + save: () => writeSolverRunState(stateFile, saved), emit: () => {}, exclusiveCheck: operation => operation() }); + teams.push(team); return team; + }; + const team = create(state); + let sequence = 0; + const call = (args: Record, actor = 'lead', instance = team) => instance.tools(actor).call('theoremos_team', args, { + threadId: 'fixture', turnId: 'fixture', callId: 'tool-' + ++sequence, signal: controller.signal, }); - - it('prunes an alternate proof route and keeps its shared foundation available to the surviving route', async () => { - const f = fixture(false), research = f.research(); - try { - const goal = f.originalGoals[0], proofPath = goal.proofPath; - const lemma = (id: string, dependsOn: string[] = []) => ({ - id, kind: 'lemma', objective: 'Prove the finite claim ' + id, theoremName: id, proofPath, type: 'True', dependsOn, - }); - const routes = ['dead', 'live'].map(route => ({ id: route, targetTaskId: goal.id, - closingTaskId: route + '_closing', prerequisiteTaskIds: ['shared_foundation'] })); - const tasks = [...f.originalGoals, lemma('shared_foundation'), lemma('dead_only'), - lemma('dead_closing', ['dead_only', 'shared_foundation']), lemma('live_closing', ['shared_foundation'])]; - await research.publish({ tasks, proofRoutes: routes }); - const state = f.state.cooperation!; - await research.publish({ baseVersion: state.planVersion, retireRoutes: [{ routeId: 'dead', reason: 'Witness disproves its closing step.' }] }); - expect(state.proofRoutes?.map(route => route.id)).toEqual(['live']); - expect(state.retiredRouteTasks).toMatchObject({ dead_only: 'dead', dead_closing: 'dead' }); - const byId = new Map(state.tasks.map(node => [node.task.id, node])); - const allowed = (id: string) => routeAllowsTask(byId.get(id)!.task, state.tasks, state.groups); - expect(allowed('shared_foundation')).toBe(true); - expect(allowed('dead_only')).toBe(false); - expect(allowed('dead_closing')).toBe(false); - expect(allowed('live_closing')).toBe(true); - } finally { await research.stop(); } + const session = async (id: string) => { + await expect.poll(() => current.get(id)).toBeDefined(); + const worker = current.get(id)!; + await worker.started.promise; return worker; + }; + cleanup.push(async () => { + for (const session of current.values()) session.finish(); + controller.abort(); + await Promise.all(teams.map(team => team.close())); + fs.rmSync(directory, { recursive: true, force: true }); }); + return { team, state, stateFile, create, call, session, signal: controller.signal }; +} - it('installs the primary portfolio foundation ahead of its original consumers and imports gate tombstones', async () => { - const f = fixture(false); - const [goal] = f.originalGoals; - f.state.portfolioExploration = { phase: 'completed', durationMs: 500, scouts: [], gate: { - primaryRouteId: 'main', retiredRoutes: [{ routeId: 'dead', reason: 'The boundary case fails.', retiredAt: 1, source: 'portfolio' }], - foundationLemmas: [{ id: 'portfolio_base', theoremName: 'portfolio_base', proofPath: goal.proofPath, - objective: 'Prove the reusable base inequality.', type: '(n : Nat) → n = n' }], - } }; - const research = f.research(); - try { - await research.publish({ groups: f.groups, tasks: [...f.originalGoals.map(task => ({ ...task, status: 'active' })), - { id: 'wrong_direction', kind: 'research', objective: 'Repeat the falsified route.', groupId: 'dead' }] }); - const state = f.state.cooperation!, byId = new Map(state.tasks.map(node => [node.task.id, node])); - expect(state.retiredRoutes).toMatchObject([{ routeId: 'dead', source: 'portfolio' }]); - expect(byId.get('wrong_direction')).toMatchObject({ status: 'blocked', task: { status: 'stopped' } }); - expect(byId.get(goal.id)?.task.dependsOn).toContain('portfolio_base'); - expect(byId.get('portfolio_base')).toMatchObject({ status: 'pending', attempts: 0, - task: { kind: 'lemma', theoremName: 'portfolio_base', sharing: 'problem' } }); - expect(byId.get(goal.id)?.integratedCheck).toBeUndefined(); - } finally { await research.stop(); } - }); -}); +const retirement = { operation: 'retire_route', routeId: 'counterexample', + reason: 'The symmetric reduction fails at the boundary.', evidenceRefs: ['RESEARCH.md#boundary-witness'] }; -it('asks Lead to publish and delegate once per turn when its planning command limit is exceeded', async () => { - const f = fixture(false), workers = [f.lead, f.peer]; - const controller = new AbortController(), started = deferred(), done = deferred(); - const notify = vi.fn(async () => {}); - const open = vi.fn(async (_options: MathAgentOptions): Promise => ({ - threadId: 'lead-guardrail-thread', notify, interrupt: async () => { done.resolve('interrupted'); }, - close: async () => { done.resolve('interrupted'); }, - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted('lead-guardrail-turn'); started.resolve(); - return done.promise; - }, - })); - const completion = runResearchWorkers({ - state: f.state, workers, access: workerAccess(workers, f.directory), root: f.directory, - buildFile: path.join(f.directory, 'build.json'), taskText: 'Prove the original targets.', - modules: { ...workerDeliveryModules, M1: { ...workerDeliveryModules.M1, open } }, - executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, - deadline: Infinity, maxTurnMs: Infinity, maxTurns: 2, maxTotalTokens: 0, leadMaxPlanningCommands: 2, - save: () => {}, emit: f.emit, - }); - try { - await Promise.race([started.promise, completion.then(() => { throw new Error('Lead never started.'); })]); - const activity = open.mock.calls[0][0].onActivity!; - const command = () => { - activity({ event: 'item_started', itemType: 'commandExecution' }); - activity({ event: 'command_output', itemType: 'commandExecution' }); - activity({ event: 'item_completed', itemType: 'commandExecution' }); - }; - command(); command(); - expect(notify).not.toHaveBeenCalled(); - command(); command(); - expect(notify).toHaveBeenCalledExactlyOnceWith(expect.stringMatching(/publish the plan now.*Delegate further computations/u), - { waitForRequest: true }); - expect(f.emit.mock.calls.filter(([event]) => event === 'lead_planning_command_guardrail_triggered')).toEqual([ - ['lead_planning_command_guardrail_triggered', expect.objectContaining({ workerId: 'solver', commandCount: 3, limit: 2 })], +describe('atomic AgentResearchTeam route retirement', () => { + it('tags native spawn work, exposes the Lead operation, and blocks retired native requests', async () => { + const f = fixture(); + const options = f.team.nativeAgentControlOptions('lead')!; + const connection = nativeConnection(rootThreadId, '/root', f.state.worktree); + let sequence = 0; + const native = (operation: string, payload: Record) => options.request({ + version: 1, operation, operationId: 'native-' + ++sequence, threadId: rootThreadId, sessionId: rootThreadId, payload, + }, connection, { signal: f.signal }); + await native('attach', { threadId: rootThreadId, sessionId: rootThreadId }); + await options.bound?.(connection); + const spawn = (id: string, route: string) => native('spawn', { caller: rootThreadId, + source: { subagent: { thread_spawn: { agent_path: '/root/' + id, parent_thread_id: rootThreadId, depth: 1 } } }, + bootstrap: { config: { cwd: f.state.worktree, model: f.state.model, reasoningEffort: f.state.effort } }, + input: { kind: 'message', mode: 'triggerTurn', + message: { kind: 'plaintext', text: 'Route: ' + route + '\nExplore a local reduction.' } }, + }); + await spawn('old', 'counterexample'); + const old = await f.session('old'); + expect(f.team.archive.workers[0]!.tasks[0]).toMatchObject({ routeId: 'counterexample', message: 'Explore a local reduction.' }); + expect(await f.call(retirement, 'old')).toMatchObject({ ok: false, error: 'math_team_native_operation_required' }); + const task = f.team.archive.workers[0]!.tasks[0]!; + expect(await f.call(retirement)).toMatchObject({ ok: true, releasedAgentIds: ['old'], cancelledTaskIds: [task.id] }); + expect(old.interrupt).toHaveBeenCalled(); + expect(await f.call(retirement)).toMatchObject({ ok: true, cancelledTaskIds: [], releasedAgentIds: [] }); + expect(readSolverRunState(f.stateFile).agentTeam?.retiredRoutes).toMatchObject([ + { routeId: 'counterexample', source: 'lead', evidenceRefs: retirement.evidenceRefs }, ]); - } finally { - controller.abort(new Error('fixture_complete')); - await expect(completion).rejects.toThrow('fixture_complete'); - } + await expect(spawn('new', 'counterexample')).rejects.toThrow('math_team_route_retired:counterexample'); + await spawn('new', 'replacement'); + const replacement = await f.session('new'); + expect(replacement.context).toContain('"routeId":"replacement"'); + await expect(native('send', { caller: rootThreadId, target: { kind: 'path', reference: '/root/new' }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Route: counterexample\nRepeat the route.' } }, + })).rejects.toThrow('math_team_route_retired:counterexample'); + old.finish(); replacement.finish(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + expect(task.status).toBe('cancelled'); + await f.team.close(); + const saved = readSolverRunState(f.stateFile), restored = f.create(saved); + await restored.restore(); + const restoredOptions = restored.nativeAgentControlOptions(); + await restoredOptions.request({ version: 1, operation: 'attach', operationId: 'restored-attach', + threadId: rootThreadId, sessionId: rootThreadId, payload: { threadId: rootThreadId, sessionId: rootThreadId } }, + connection, { signal: f.signal }); + await restoredOptions.bound?.(connection); + await expect(restoredOptions.request({ version: 1, operation: 'send', operationId: 'restored-followup', + threadId: rootThreadId, sessionId: rootThreadId, payload: { caller: rootThreadId, + target: { kind: 'path', reference: '/root/new' }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Route: counterexample\nReopen it.' } }, + } }, connection, { signal: f.signal })).rejects.toThrow('math_team_route_retired:counterexample'); + }); }); diff --git a/tests/solverSavedPlan.test.ts b/tests/solverSavedPlan.test.ts deleted file mode 100644 index ee737cad..00000000 --- a/tests/solverSavedPlan.test.ts +++ /dev/null @@ -1,331 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentOptions } from '../src/runtime/codexSession'; -import type { SolverRunState } from '../src/solver/archive'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { git, type SolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import { parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -describe('saved Lead plans after request failure', () => { - let directory: string, problem: SolverProblem, workers: ResearchWorker[], state: SolverRunState; - let modules: SolverModules, retry: ReturnType, close: ReturnType; - let events: { event: string; details?: Record }[]; - let execute: (action: CooperativeAction, options: MathAgentOptions) => Promise; - let actions: CooperativeAction[]; - let sessionError: string; - let requestAccounting: boolean; - - const plan = () => ({ tasks: problem.targets.map((target, index) => ({ - id: `goal_${index + 1}`, kind: 'goal', objective: `Prove ${target.theoremName}`, - proofPath: target.proofPath, theoremName: target.theoremName, - })) }); - const writePlan = (options: MathAgentOptions, value: unknown = plan()) => fs.writeFileSync( - path.join(options.workspace, 'RESEARCH.md'), '```math-plan\n' + JSON.stringify(value) + '\n```'); - const existingPlan = () => { - const parsed = parseCooperationPlan(problem, plan()); - state.cooperation = { tasks: parsed.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: parsed.groups.map(group => ({ group, turns: 0 })), error: 'A Lead decision is requested.' }; - }; - const run = (maxTotalTokens = 0) => runResearchWorkers({ state, workers, modules, - access: workerAccess(workers, directory), - root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original targets.', - executable: 'fixture-no-model', profile: 'fixture', signal: new AbortController().signal, - deadline: Infinity, maxTurns: 3, maxTurnMs: Infinity, maxTotalTokens, - save: () => {}, emit: (event, details) => events.push({ event, details }) }); - - beforeEach(() => { - const example = localExample('solver-saved-plan-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'engineer', { role: 'engineer' })]; - state = solverState(problem, example.workspace, { runId: 'saved-plan-fixture', phase: 'prepared', - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })) }); - events = []; actions = []; sessionError = 'fetch failed'; requestAccounting = false; - retry = vi.fn().mockReturnValue(undefined); - close = vi.fn(async () => {}); - execute = async (_action, options) => { writePlan(options); return 'failed'; }; - modules = { ...directSolverModules, - M1: { ...directSolverModules.M1, open: async options => ({ threadId: 'failed-plan-thread', - ...(requestAccounting ? { usageSource: 'upstream-requests' as const } : {}), - get lastError() { return sessionError; }, close, interrupt: vi.fn(async () => {}), - run: async message => { - const action = JSON.parse(message) as CooperativeAction; - actions.push(action); - return execute(action, options); - } }) }, - M2: { ...directSolverModules.M2, - check: async () => { throw new Error('fixture_unexpected_whole_proof_check'); }, - checkTask: async () => { throw new Error('fixture_unexpected_task_proof_check'); } }, - M3: { ...directSolverModules.M3, retry, - select: (_state, _operations, _budget, assignment) => assignment?.kind === 'task' - ? { operation: 'stop', reason: 'fixture_task_dispatch_observed' } - : { operation: 'direct', reason: 'fixture_lead_request' } }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Local fixture session.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } }) }, - }; - }); - afterEach(() => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - - it.each(['failed', 'transport-closed', 'request-error'])('uses an accepted saved initial plan after %s', async failure => { - if (failure === 'transport-closed') sessionError = 'math_codex_transport_closed:fixture'; - execute = async (_action, options) => { - writePlan(options); - if (failure === 'transport-closed') throw new Error('math_codex_transport_closed:fixture'); - if (failure === 'request-error') throw new Error('fetch failed'); - return 'failed'; - }; - await expect(run()).resolves.toBeUndefined(); - expect(actions.map(action => action.kind)).toEqual(['lead']); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(events).toContainEqual(expect.objectContaining({ event: 'task_assigned' })); - expect(events).toContainEqual({ event: 'worker_recovered', details: { - workerId: 'solver', reason: failure === 'transport-closed' ? 'math_codex_transport_closed' : 'math_model_request_failed', - savedPlan: true, - } }); - expect(events).toContainEqual(expect.objectContaining({ event: 'context_restarted', details: expect.objectContaining({ reason: 'request' }) })); - expect(state.workers![0].previousThreadIds).toContain('failed-plan-thread'); - expect(close).toHaveBeenCalledOnce(); - expect(retry).not.toHaveBeenCalled(); - }); - - it.each(['empty', 'invalid', 'unchanged'])('retries a failed Lead with an %s response', async response => { - if (response === 'unchanged') existingPlan(); - execute = async (_action, options) => { - if (response === 'empty') fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), ''); - else if (response === 'invalid') writePlan(options, { tasks: [] }); - else writePlan(options); - return 'failed'; - }; - await expect(run()).rejects.toThrow('math_model_request_failed'); - expect(retry).toHaveBeenCalledOnce(); - expect(events.some(item => item.event === 'worker_recovered')).toBe(false); - expect(state.cooperation!.initialPlanFallback).toBeUndefined(); - if (response !== 'unchanged') expect(state.cooperation!.tasks).toEqual([]); - }); - - it('repeats an incomplete initial planning request and accepts its later complete response', async () => { - retry.mockImplementation((_error, attempts) => attempts === 0 - ? { attempt: 1, delayMs: 0, reason: 'math_model_request_failed' } : undefined); - execute = async (_action, options) => { - writePlan(options, actions.length === 1 ? { tasks: [] } : plan()); - return actions.length === 1 ? 'failed' : 'completed'; - }; - await expect(run()).resolves.toBeUndefined(); - expect(actions.map(action => action.kind)).toEqual(['lead', 'lead']); - expect(retry).toHaveBeenCalledOnce(); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(state.cooperation!.initialPlanFallback).toBeUndefined(); - }); - - it.each(['tokens', 'requests', 'resume', 'saved-plan'] as const) - ('hands off initial planning after its %s limit without losing complete usage', async mode => { - requestAccounting = true; sessionError = 'HTTP 403 Forbidden'; - if (mode === 'resume') { - const lead = state.workers![0]; - lead.turns = state.turns = 1; - lead.usage = { inputTokens: 250, outputTokens: 50, totalTokens: 300 }; - lead.usageAccounting = { startedTurns: 1, reportedTurns: 1, pending: false, incomplete: false }; - lead.requestUsageAccounting = { startedRequests: 1, reportedRequests: 1, pendingRequests: 0, incomplete: false }; - state = JSON.parse(JSON.stringify(state)); - } - let requests = 0; - execute = async (_action, options) => { - for (const totalTokens of mode === 'resume' ? [] : mode === 'requests' ? [20, 10] : [300]) { - const admission = options.requestGate!(); - expect(admission.allowed).toBe(true); - if (admission.allowed) { - requests++; - admission.settle({ usage: { totalTokens, inputTokens: totalTokens - 5, outputTokens: 5 }, complete: true }); - } - } - if (mode === 'saved-plan') writePlan(options); - for (let retry = 0; retry < 2; retry++) expect(options.requestGate!()).toEqual({ - allowed: false, reason: 'math_initial_planning_limit' }); - return 'failed'; - }; - await expect(run(1000)).resolves.toBeUndefined(); - expect(actions.map(action => action.kind)).toEqual(['lead']); - expect(requests).toBe(mode === 'resume' ? 0 : mode === 'requests' ? 2 : 1); - expect(state.tokenBudget).toMatchObject({ status: 'available', usageComplete: true, - reportedTotalTokens: mode === 'requests' ? 30 : 300 }); - const lead = state.workers![0]; - expect(lead.requestUsageAccounting).toEqual({ startedRequests: mode === 'requests' ? 2 : 1, - reportedRequests: mode === 'requests' ? 2 : 1, pendingRequests: 0, incomplete: false, - ...(mode === 'resume' ? {} : { receipts: (mode === 'requests' ? [20, 10] : [300]).map(totalTokens => ({ - requestId: expect.any(String), runId: state.runId, sessionId: expect.any(String), taskId: undefined, - startedAt: expect.any(Number), settledAt: expect.any(Number), status: 'reported', outcome: 'unknown', - usage: { totalTokens, inputTokens: totalTokens - 5, outputTokens: 5 }, - })) }) }); - if (mode === 'requests') { - const receipts = lead.requestUsageAccounting!.receipts!; - expect(new Set(receipts.map(receipt => receipt.requestId)).size).toBe(2); - expect(new Set(receipts.map(receipt => receipt.sessionId)).size).toBe(1); - } - expect(lead.lastFailure).toBeUndefined(); expect(lead.error).toBeUndefined(); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(mode === 'saved-plan' - ? ['goal_1', 'goal_2'] : ['initial_goal_1', 'initial_goal_2']); - expect(state.cooperation!.tasks.every(node => node.status === 'pending' && !node.proof)).toBe(true); - expect(Boolean(state.cooperation!.initialPlanFallback)).toBe(mode !== 'saved-plan'); - expect(events.filter(item => item.event === 'planning_budget_stopped')).toHaveLength(1); - expect(events.some(item => item.event === 'task_assigned')).toBe(true); - expect(events.some(item => ['worker_failed', 'turn_failed'].includes(item.event))).toBe(false); - expect(close).toHaveBeenCalled(); expect(retry).not.toHaveBeenCalled(); - }); - - it.each(['exhausted', 'missing'] as const)('prioritizes global %s usage over a planning handoff', async mode => { - requestAccounting = true; sessionError = 'HTTP 403 Forbidden'; - const reason = mode === 'exhausted' ? 'math_total_token_limit' : 'math_model_usage_unavailable'; - execute = async (_action, options) => { - const admission = options.requestGate!(); - expect(admission.allowed).toBe(true); - if (admission.allowed) admission.settle(mode === 'exhausted' - ? { usage: { totalTokens: 1000, inputTokens: 990, outputTokens: 10 }, complete: true } : { complete: false }); - expect(options.requestGate!()).toEqual({ allowed: false, reason }); - return 'failed'; - }; - await expect(run(1000)).resolves.toBeUndefined(); - expect(state.cooperation!.tasks).toEqual([]); - expect(state.cooperation!.initialPlanFallback).toBeUndefined(); - expect(state.workers![0].lastFailure?.reason).toBe(reason); - expect(events.some(item => item.event === 'planning_budget_stopped')).toBe(false); - expect(retry).not.toHaveBeenCalled(); - }); - - it('does not create a planning checkpoint while request receipts are pending', async () => { - requestAccounting = true; sessionError = 'HTTP 403 Forbidden'; - execute = async (_action, options) => { - const pending = [options.requestGate!(), options.requestGate!()]; - expect(pending.every(admission => admission.allowed)).toBe(true); - expect(options.requestGate!()).toEqual({ allowed: false, reason: 'math_model_request_stopped' }); - for (const admission of pending) if (admission.allowed) - admission.settle({ usage: { totalTokens: 20, inputTokens: 15, outputTokens: 5 }, complete: true }); - return 'failed'; - }; - await expect(run(1000)).rejects.toThrow('math_model_request_stopped'); - expect(state.cooperation!.tasks).toEqual([]); - expect(state.cooperation!.initialPlanFallback).toBeUndefined(); - expect(events.some(item => item.event === 'planning_budget_stopped')).toBe(false); - expect(state.tokenBudget).toMatchObject({ status: 'available', usageComplete: true, reportedTotalTokens: 40 }); - }); - - it('waits for the planning writer to close before publishing its saved plan', async () => { - requestAccounting = true; sessionError = 'HTTP 403 Forbidden'; - const closing = deferred(), startedClosing = deferred(); - close.mockImplementation(async () => { startedClosing.resolve(); await closing.promise; }); - execute = async (_action, options) => { - const admission = options.requestGate!(); expect(admission.allowed).toBe(true); - if (admission.allowed) admission.settle({ usage: { totalTokens: 300, inputTokens: 250, outputTokens: 50 }, complete: true }); - writePlan(options); - expect(options.requestGate!()).toEqual({ allowed: false, reason: 'math_initial_planning_limit' }); - return 'failed'; - }; - const running = run(1000); - try { - await startedClosing.promise; - expect(events.some(item => ['plan_updated', 'task_assigned'].includes(item.event))).toBe(false); - expect(state.cooperation!.tasks).toEqual([]); - } finally { closing.resolve(); } - await expect(running).resolves.toBeUndefined(); - expect(state.cooperation!.tasks.map(node => node.task.id)).toEqual(['goal_1', 'goal_2']); - expect(events.some(item => item.event === 'task_assigned')).toBe(true); - }); - - it('does not apply the initial planning limit to unlimited runs or later Lead decisions', async () => { - requestAccounting = true; - execute = async (_action, options) => { - for (let request = 0; request < 3; request++) { - const admission = options.requestGate!(); expect(admission.allowed).toBe(true); - if (admission.allowed) admission.settle({ usage: { totalTokens: 10, inputTokens: 5, outputTokens: 5 }, complete: true }); - } - writePlan(options); return 'completed'; - }; - await expect(run()).resolves.toBeUndefined(); - expect(state.workers![0].requestUsageAccounting?.startedRequests).toBe(3); - existingPlan(); - await expect(run(1000)).resolves.toBeUndefined(); - expect(state.workers![0].requestUsageAccounting?.startedRequests).toBe(6); - expect(events.some(item => item.event === 'planning_budget_stopped')).toBe(false); - }); - - it.each(['returned', 'thrown', 'changed-source'] as const)('keeps %s host integrity errors above planning checkpoints', async mode => { - requestAccounting = true; - execute = async (_action, options) => { - const admission = options.requestGate!(); expect(admission.allowed).toBe(true); - if (admission.allowed) admission.settle({ usage: { totalTokens: 300, inputTokens: 250, outputTokens: 50 }, complete: true }); - expect(options.requestGate!()).toEqual({ allowed: false, reason: 'math_initial_planning_limit' }); - if (mode === 'returned') sessionError = 'math_source_outside_ownership'; - else if (mode === 'thrown') throw new Error('math_candidate_identity_changed'); - else { - const trusted = Object.keys(problem.trustedFiles)[0]; - fs.appendFileSync(path.join(options.workspace, problem.projectRelative, trusted), '\nchanged frozen input\n'); - } - return 'failed'; - }; - await expect(run(1000)).rejects.toThrow(mode === 'changed-source' ? 'math_trusted_source_changed' - : mode === 'returned' ? 'math_source_outside_ownership' : 'math_candidate_identity_changed'); - expect(state.cooperation!.initialPlanFallback).toBeUndefined(); - expect(state.cooperation!.tasks).toEqual([]); - }); - - it.each(['research', 'sketch'])('keeps failed %s work on the ordinary retry path', async kind => { - modules.M3.select = () => ({ operation: 'direct', reason: 'fixture_advisory_request' }); - execute = async (action, options) => { - if (action.kind === 'lead') { - const initial = plan(); - writePlan(options, { tasks: [ - { id: 'advice', kind, objective: 'Investigate the original claims' }, - ...initial.tasks.map(task => ({ ...task, dependsOn: ['advice'] })), - ] }); - return 'completed'; - } - if (action.kind !== 'task') throw new Error('fixture_unexpected_advisory_assignment'); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), '```math-result\n' + JSON.stringify({ - taskId: action.task.id, summary: 'A saved hypothesis requiring independent proof.', - conclusion: 'supporting', needsDecision: true, lemmaRequests: [{ - id: 'saved_bridge', kind: 'lemma', objective: 'Prove the saved hypothesis', - theoremName: 'Tutorial.saved_bridge', type: 'True', proofPath: problem.targets[0].proofPath, dependsOn: [], - }], - }) + '\n```'); - return 'failed'; - }; - await expect(run()).rejects.toThrow('math_model_request_failed'); - expect(retry).toHaveBeenCalledOnce(); - expect(actions.map(action => action.kind)).toEqual(['lead', 'task']); - expect(state.cooperation!.tasks[0].task).toMatchObject({ id: 'advice', kind }); - expect(state.cooperation!.tasks[0].finding).toBeUndefined(); - expect(state.cooperation!.tasks.slice(1).every(node => !node.attempts && !node.proof)).toBe(true); - const checkpoint = state.cooperation!.researchDrafts?.advice; - expect(checkpoint).toMatchObject({ taskDigest: state.cooperation!.tasks[0].assignment!.taskDigest, - workerId: 'engineer' }); - expect(git(workers[1].worktree, ['show', `${checkpoint!.commit}:RESEARCH.md`])).toContain('saved_bridge'); - expect(state.cooperation!.researchCheckpoints?.advice).toBeUndefined(); - expect(state.cooperation!.deliveries?.some(delivery => delivery.kind === 'research')).not.toBe(true); - expect(events.some(item => item.event === 'worker_recovered')).toBe(false); - }); - - it('discards a saved plan without retrying its superseded Lead assignment', async () => { - existingPlan(); - state.cooperation!.planVersion = 'assigned-plan-version'; - execute = async (_action, options) => { - state.cooperation!.planVersion = 'superseding-plan-version'; - const revised = plan(); revised.tasks[0].objective = 'Superseded proposed objective'; - writePlan(options, revised); - return 'failed'; - }; - await expect(run()).resolves.toBeUndefined(); - expect(retry).not.toHaveBeenCalled(); - expect(events.some(item => item.event === 'lead_decision_superseded')).toBe(true); - expect(events.some(item => item.event === 'assignment_superseded')).toBe(true); - expect(events.some(item => item.event === 'worker_recovered')).toBe(false); - expect(state.cooperation!.tasks[0].task.objective).toBe(plan().tasks[0].objective); - }); -}); diff --git a/tests/solverSessionAdmission.test.ts b/tests/solverSessionAdmission.test.ts deleted file mode 100644 index 1f76b668..00000000 --- a/tests/solverSessionAdmission.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentSession } from '../src/runtime/codexSession'; -import type { SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import type { SolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import { parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const backoff = vi.hoisted(() => ({ run: vi.fn<() => Promise>() })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); -vi.mock('node:timers/promises', () => ({ setTimeout: async () => { await backoff.run(); } })); - -describe('cooperative session admission', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - - beforeEach(() => { - backoff.run.mockReset(); - const example = localExample('solver-session-admission-', 'lead'), workspace = example.workspace; - ({ directory, problem } = example); - workers = [leadWorker(problem, workspace), peerWorker(example, 'peer')]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, proofPath: target.proofPath, - theoremName: target.theoremName, status: 'paused' })), - { id: 'first_investigation', kind: 'research', objective: 'Investigate the first route.', ownerId: 'peer' }, - { id: 'next_investigation', kind: 'research', objective: 'Investigate the next route.', ownerId: 'peer' }, - ] }); - state = solverState(problem, workspace, { runId: 'session-admission-fixture', phase: 'prepared', - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture', workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - }); - afterEach(() => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - - it.each([...(['opened', 'failed', 'retrying'] as const).flatMap(opening => - (['pause', 'revise', 'remove'] as const).map(change => ({ opening, change }))), - { opening: 'opened' as const, change: 'exhaust-route' as const }]) - ('continues current work after $change supersedes a session that $opening during startup', async ({ opening, change }) => { - if (change === 'exhaust-route') { - state.cooperation!.groups![0].group = { ...state.cooperation!.groups![0].group, maxTurns: 1 }; - state.cooperation!.groups!.push({ group: { id: 'secondary', objective: 'Investigate an independent route.', - status: 'active', revision: 0 }, turns: 0 }); - const node = state.cooperation!.tasks.find(node => node.task.id === 'next_investigation')!; - node.task = { ...node.task, groupId: 'secondary' }; - } - let cooperation: CooperativeResearch | undefined; - const next = CooperativeResearch.prototype.next; - vi.spyOn(CooperativeResearch.prototype, 'next').mockImplementation(async function(worker, budget) { - cooperation = this; - return next.call(this, worker, budget); - }); - const events: { event: string; details?: Record }[] = []; - const runs: CooperativeAction[] = []; - const close = vi.fn(async () => {}); - const edit = async () => { - const tasks = state.cooperation!.tasks.flatMap(({ task }) => { - if (task.id !== 'first_investigation') return [task]; - if (change === 'remove') return []; - return [{ ...task, ...(change === 'pause' ? { status: 'paused' as const } : { revision: task.revision + 1 }) }]; - }); - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ - id: 'during-startup', baseVersion: state.cooperation!.planVersion, tasks, - }) + '\n'); - await cooperation!.pulse(); - expect(state.cooperation!.edits?.find(edit => edit.id === 'during-startup')?.status).toBe('applied'); - }; - const retry = vi.fn().mockReturnValue(opening === 'retrying' - ? { attempt: 1, reason: 'math_model_request_failed', delayMs: 0 } : undefined); - if (opening === 'retrying') backoff.run.mockImplementationOnce(edit); - const open = vi.fn(async (options: Parameters[0]): Promise => { - if (open.mock.calls.length === 1) { - if (opening === 'retrying') throw new Error('fetch failed'); - if (change === 'exhaust-route') state.cooperation!.groups![0].turns = 1; - else await edit(); - if (opening === 'failed') throw new Error('fetch failed'); - } - return { threadId: `fixture-thread-${open.mock.calls.length}`, close, interrupt: vi.fn(async () => {}), - run: async message => { - const action = JSON.parse(message) as CooperativeAction; - runs.push(action); - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), 'A concrete advisory finding for the current route.\n'); - return 'completed'; - } }; - }); - const modules: SolverModules = { ...directSolverModules, - M1: { ...directSolverModules.M1, open }, - M2: { ...directSolverModules.M2, - check: async () => { throw new Error('fixture_unexpected_proof_check'); }, - checkTask: async () => { throw new Error('fixture_unexpected_task_check'); } }, - M3: { ...directSolverModules.M3, retry }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Local fixture.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }) }, - }; - - await expect(runResearchWorkers({ state, workers, modules, access: workerAccess(workers, directory), - root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original targets.', - executable: 'fixture-no-model', profile: 'fixture', signal: new AbortController().signal, - deadline: Infinity, maxTurns: 1, maxTurnMs: Infinity, maxTotalTokens: 0, - save: () => {}, emit: (event, details) => events.push({ event, details }), - })).resolves.toBeUndefined(); - - expect(runs).toHaveLength(1); - expect(runs[0]).toMatchObject({ kind: 'task', task: change === 'revise' - ? { id: 'first_investigation', revision: 1 } : { id: 'next_investigation' } }); - expect(open).toHaveBeenCalledTimes(2); - expect(retry).toHaveBeenCalledTimes(opening === 'retrying' ? 1 : 0); - expect(state.turns).toBe(1); - expect(state.workers![1].turns).toBe(1); - expect(state.cooperation!.groups![0].turns).toBe(1); - if (change === 'exhaust-route') { - expect(state.cooperation!.groups![1].turns).toBe(1); - expect(events).toContainEqual({ event: 'assignment_deferred', details: { - workerId: 'peer', reason: 'turn-admission-declined', - } }); - } - expect(state.cooperation!.tasks.find(node => node.task.id === (change === 'revise' - ? 'first_investigation' : 'next_investigation'))).toMatchObject({ status: 'completed', attempts: 1 }); - expect(state.cooperation!.deliveries?.filter(delivery => delivery.kind === 'failure') ?? []).toEqual([]); - expect(events.some(event => event.event === 'worker_failed')).toBe(false); - expect(close).toHaveBeenCalledTimes(opening === 'opened' ? 2 : 1); - }); -}); diff --git a/tests/solverSingleProofHandoff.test.ts b/tests/solverSingleProofHandoff.test.ts index 42577bb9..ff2512f4 100644 --- a/tests/solverSingleProofHandoff.test.ts +++ b/tests/solverSingleProofHandoff.test.ts @@ -5,9 +5,9 @@ import { LOCAL_EXAMPLE_PROOF } from '../src/math/localExample'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; import { directSolverModules, type SolverModules } from '../src/solver/modules'; import { committedSource, git } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { runResearchLead } from '../src/solver/research'; import { deferred } from './helpers/async'; -import { workerAccess } from './helpers/cooperation'; +import { workerAccess } from './helpers/solver'; import { captureLeanCompletion } from './helpers/leanCompletion'; import { leadWorker, localExample, solverState } from './helpers/solver'; import { failedBatch, receiptBatch } from './helpers/verifier'; @@ -66,7 +66,7 @@ describe('single solver early proof submission', () => { message: 'Prove all original targets.', scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } }) }, }; - const completion = runResearchWorkers({ state, workers, access: workerAccess(workers, directory), modules, + const completion = runResearchLead({ state, access: workerAccess(workers, directory).get('solver')!, modules, root: directory, buildFile: path.join(directory, 'unused-build.json'), taskText: 'Prove all original targets.', executable: 'offline-no-model', profile: 'offline-no-credentials', signal: controller.signal, deadline: Infinity, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens: 0, diff --git a/tests/solverSoftSliceCompaction.test.ts b/tests/solverSoftSliceCompaction.test.ts index 8a888eed..f018ef8d 100644 --- a/tests/solverSoftSliceCompaction.test.ts +++ b/tests/solverSoftSliceCompaction.test.ts @@ -5,10 +5,10 @@ import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSes import { readMathAgentSkill } from '../src/runtime/codexSkills'; import { directSolverModules } from '../src/solver/modules'; import { commitSolverSources } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { runResearchLead } from '../src/solver/research'; import { MAX_COMPACTIONS_PER_SLICE, SOFT_SLICE_MS, softSliceSettings } from '../src/solver/softSlice'; import { deferred } from './helpers/async'; -import { leadWorker, localExample, solverState } from './helpers/solver'; +import { localExample, solverState } from './helpers/solver'; vi.mock(import('../src/math/mathBuildManifest'), async importOriginal => ({ ...await importOriginal(), readMathBuildManifest: vi.fn() })); @@ -25,7 +25,6 @@ describe('soft research milestones', () => { const interrupt = vi.fn(async () => { done.resolve('interrupted'); }); const stop = vi.fn(async () => ({ status: 'stopped' as const })); const events: { event: string; details?: Record }[] = []; - const worker = leadWorker(problem, workspace); const skill = trigger === 'independent' ? undefined : (() => { const skillRoot = path.join(workspace, '.agents/skills/theoremos-research'); fs.mkdirSync(path.dirname(skillRoot), { recursive: true }); @@ -33,7 +32,9 @@ describe('soft research milestones', () => { return readMathAgentSkill(path.join(skillRoot, 'SKILL.md')); })(); const state = solverState(problem, workspace, { runId: 'soft-slice-fixture', phase: 'prepared', - ...(trigger === 'team' ? { researchDelegation: { mode: 'team', maxAgents: 3 }, portfolioExploration: { + ...(trigger === 'team' ? { researchDelegation: { mode: 'team', maxAgents: 3 }, agentTeam: { schema: 'theorem-os.agent-team.v1', + transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [] }, + portfolioExploration: { phase: 'completed', durationMs: 1000, scouts: [{ profile: 'structural-symmetry', status: 'timed-out', turns: 1 }], gate: { retiredRoutes: [], foundationLemmas: [] }, } } : {}), @@ -56,8 +57,8 @@ describe('soft research milestones', () => { }, }) }, }; - const completion = runResearchWorkers({ state, workers: [worker], modules, - access: new Map([[worker.id, { environment: {}, retrievalRoot: directory, researchSkill: skill }]]), + const completion = runResearchLead({ state, modules, + access: { environment: {}, retrievalRoot: directory, researchSkill: skill }, root: directory, buildFile: path.join(directory, 'unused-build.json'), taskText: 'Prove both original addition targets.', executable: 'offline-fixture', profile: 'offline-fixture', signal: controller.signal, deadline: Infinity, maxTurnMs: Infinity, maxTurns: 1, maxTotalTokens: 0, @@ -84,7 +85,7 @@ describe('soft research milestones', () => { : /standalone helper.*fewer than 20 lines.*RESEARCH\.md/u; expect(notify.mock.calls).toEqual([[expect.stringMatching(notice), { mode: 'advisory' }]]); if (trigger === 'team') { - expect(options.instructions).toContain('spawn useful independent work'); + expect(options.instructions).toContain('spawn and coordinate useful child agents'); expect(notify.mock.calls.flat()).not.toContainEqual(expect.stringContaining('declaration-submission.json')); // This file is handled after the turn, outside the whole-proof diagnostics watcher. expect(options.completedOutput?.file).toMatch(/lean-diagnostics-latest\.json$/u); diff --git a/tests/solverSourceRecovery.test.ts b/tests/solverSourceRecovery.test.ts index a3ac3ad3..defe4520 100644 --- a/tests/solverSourceRecovery.test.ts +++ b/tests/solverSourceRecovery.test.ts @@ -6,7 +6,7 @@ import { readMathAgentSkill } from '../src/runtime/agentSkills'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; import { directSolverModules } from '../src/solver/modules'; import { committedSource, git, readSolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; +import { runResearchLead } from '../src/solver/research'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; import { solverState } from './helpers/solver'; import { temporaryDirectory } from './helpers/files'; @@ -70,10 +70,9 @@ describe('Lead correction after a deterministic saved-source rejection', () => { return 'completed'; }, })); - const pending = runResearchWorkers({ state, root: process.cwd(), buildFile: path.join(root, 'unused-build.json'), + const pending = runResearchLead({ state, root: process.cwd(), buildFile: path.join(root, 'unused-build.json'), taskText: 'Prove the fixed original target.', executable: 'offline-fixture', profile: path.join(root, 'profile'), - workers: [{ id: 'solver', role: 'lead', worktree, ownedFiles: problem.ownedFiles }], - access: new Map([['solver', { environment: {}, retrievalRoot: worktree, researchSkill: skill }]]), + access: { environment: {}, retrievalRoot: worktree, researchSkill: skill }, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, signal: new AbortController().signal, deadline: Infinity, maxTurns: 3, maxTurnMs: Infinity, maxTotalTokens: 0, save: () => {}, emit: (event, details) => { events.push({ event, details }); }, diff --git a/tests/solverStagnationRecovery.test.ts b/tests/solverStagnationRecovery.test.ts deleted file mode 100644 index 8d6aacc9..00000000 --- a/tests/solverStagnationRecovery.test.ts +++ /dev/null @@ -1,441 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import { committedSource, git } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import { assignmentDeliveryFile, parseCooperationPlan } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -describe('durable checkpoint before context rotation', () => { - let directory: string; - let controllers: AbortController[], running: Promise[]; - - beforeEach(() => { - vi.useFakeTimers(); - controllers = []; running = []; - vi.spyOn(CooperativeResearch.prototype, 'start').mockImplementation(() => {}); - }); - afterEach(async () => { - controllers.forEach(controller => controller.abort()); - await Promise.allSettled(running); - vi.useRealTimers(); vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - }); - - function fixture() { - const example = localExample('solver-stagnation-checkpoint-', 'lead'); - directory = example.directory; - const { workspace, problem } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'researcher')]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index + 1}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, ...target, status: 'paused' })), - { id: 'investigate', kind: 'research', ownerId: 'researcher', - objective: 'Identify and save the precise missing mathematical inference.' }, - ] }); - const state = solverState(problem, workspace, { runId: 'stagnation-checkpoint-fixture', phase: 'prepared', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const check = vi.fn(async () => { throw new Error('fixture_unexpected_proof_acceptance'); }); - const events: { event: string; details?: Record }[] = []; - const modules = (open: (options: MathAgentOptions) => Promise): SolverModules => ({ - ...directSolverModules, M1: { ...directSolverModules.M1, open }, - M2: { ...directSolverModules.M2, check, checkTask: check }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Offline durable checkpoint fixture.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }) }, - }); - const run = (open: (options: MathAgentOptions) => Promise, maxTurns = 2) => { - const controller = new AbortController(); controllers.push(controller); - const completion = runResearchWorkers({ state, workers, modules: modules(open), - access: workerAccess(workers, directory), root: directory, buildFile: path.join(directory, 'build.json'), - taskText: 'Prove the original targets.', executable: 'offline-fixture', profile: 'offline-fixture', - signal: controller.signal, deadline: Infinity, maxTurnMs: Infinity, maxTurns, maxTotalTokens: 0, - save: () => {}, emit: (event, details) => events.push({ event, details }), - }); - running.push(completion); void completion.catch(() => {}); return completion; - }; - const publishCheckpoint = () => { - const request = state.workers![1].contextCheckpoint!; - expect(request.requestId).toBeTypeOf('string'); - const assignment = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!.assignment!; - const log = path.join(workers[1].worktree, assignmentDeliveryFile(assignment)); - fs.appendFileSync(log, JSON.stringify({ kind: 'progress', - summary: 'The exact unresolved inference is retained in the saved mathematical checkpoint.' }) + '\n'); - fs.appendFileSync(log, JSON.stringify({ kind: 'checkpoint', requestId: request.requestId, - notesDigest: mathDigest(fs.readFileSync(path.join(workers[1].worktree, 'RESEARCH.md'))) }) + '\n'); - }; - return { state, workers, problem, check, events, run, publishCheckpoint }; - } - - function sessions(firstOutput: (workspace: string) => void = () => {}, inheritedNotes?: string) { - const secondStarted = deferred(), finish = deferred(); - const executedThreads: string[] = [], messages: string[] = []; - const notify = vi.fn(async (_message: string) => {}); - let turns = 0, threads = 0; - const close = vi.fn(async () => { if (turns >= 2) finish.resolve('interrupted'); }); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - expect(options.environment?.DEEPSCIENTIST_MATH_WORKER_ID).toBe('researcher'); - if (open.mock.calls.length === 1 && inheritedNotes !== undefined) - fs.writeFileSync(path.join(options.workspace, 'RESEARCH.md'), inheritedNotes); - const threadId = options.threadId ?? `checkpoint-thread-${++threads}`; - return { threadId, lastInputTokens: 100_000, close, notify, interrupt: async () => { finish.resolve('interrupted'); }, - run: async (message, _messageId, _workspace, onStarted) => { - messages.push(message); - executedThreads.push(threadId); onStarted(`checkpoint-turn-${++turns}`); - if (turns === 1) { - options.onActivity?.({ event: 'reasoning' }); - firstOutput(options.workspace); return 'checkpoint'; - } - if (turns !== 2) throw new Error('fixture_unexpected_extra_turn'); - secondStarted.resolve(); return finish.promise; - } }; - }); - const waitSecond = (completion: Promise) => Promise.race([secondStarted.promise, - completion.then(() => { throw new Error('fixture_finished_before_second_turn'); })]); - return { open, notify, close, executedThreads, messages, finish, waitSecond }; - } - - it.each(['none', 'metadata', 'scratch', 'notes'] as const)( - 'retains the same over-threshold thread when the checkpoint saves only %s output', async output => { - const { state, workers, problem, check, events, run } = fixture(); - const held = sessions(workspace => { - if (output === 'metadata') { - const notes = path.join(workspace, 'RESEARCH.md'); - fs.writeFileSync(notes, ''); fs.utimesSync(notes, new Date(), new Date(Date.now() + 1_000)); - } - if (output === 'scratch') { - const scratch = path.join(workspace, problem.projectRelative, '.scratch/tmp/Probe.lean'); - fs.mkdirSync(path.dirname(scratch), { recursive: true }); - fs.writeFileSync(scratch, '-- Unchecked exploration, not a durable mathematical checkpoint.\n#check Nat.add_zero\n'); - } - if (output === 'notes') fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), - 'The current argument is saved, but the report and checkpoint control event have not been published.\n'); - }); - const completion = run(held.open); await held.waitSecond(completion); - expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-1']); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(state.workers![1].previousThreadIds ?? []).toEqual([]); - expect(state.workers![1].lastInputTokens).toBe(100_000); - expect(events.filter(item => item.event === 'context_checkpoint_requested')).toEqual([{ - event: 'context_checkpoint_requested', details: { workerId: 'researcher', threadId: 'checkpoint-thread-1', - reason: 'context-threshold', lastInputTokens: 100_000 }, - }]); - expect(events).toContainEqual({ event: 'context_rotation_deferred', details: { workerId: 'researcher', - threadId: 'checkpoint-thread-1', reason: 'checkpoint-not-published', lastInputTokens: 100_000 } }); - expect(held.messages[1]).toMatch(/RESEARCH\.md/u); - expect(held.messages[1]).toMatch(/research-observe/u); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.proof).toBeUndefined(); - held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - if (output === 'scratch') { - const relative = path.join(problem.projectRelative, '.scratch/tmp/Probe.lean'); - expect(fs.readFileSync(path.join(workers[1].worktree, relative), 'utf8')).toContain('Unchecked exploration'); - expect(git(workers[1].worktree, ['ls-files', '--', relative])).toBe(''); - } - expect(state.tokenBudget).toMatchObject({ maxTotalTokens: 0, status: 'unlimited' }); - }); - - it('rotates only after the exact mathematical checkpoint is committed and available to the replacement thread', async () => { - const { state, workers, problem, check, events, run, publishCheckpoint } = fixture(); - const notes = 'The existing reduction preserves positive definiteness and integral representation.\n' + - 'The unresolved step is a least-truant classification; the conditional bridge does not prove it.\n'; - const held = sessions(workspace => { - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), notes); publishCheckpoint(); - }); - const completion = run(held.open); await held.waitSecond(completion); - expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-2']); - expect(state.workers![1].previousThreadIds).toEqual(['checkpoint-thread-1']); - expect(events.filter(item => item.event === 'context_restarted')).toHaveLength(1); - const published = events.findIndex(item => item.event === 'context_checkpoint_published'); - expect(published).toBeGreaterThan(events.findIndex(item => item.event === 'delivery_published' && item.details?.kind === 'progress')); - expect(events.findIndex(item => item.event === 'context_restarted')).toBeGreaterThan(published); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ kind: 'progress', - summary: 'The exact unresolved inference is retained in the saved mathematical checkpoint.' })); - expect(events).toContainEqual({ event: 'context_checkpoint_ready', details: { workerId: 'researcher', - threadId: 'checkpoint-thread-1', notesDigest: expect.stringMatching(/^[a-f0-9]{64}$/u) } }); - const draft = state.cooperation!.researchDrafts!.investigate; - expect(committedSource(workers[1].worktree, draft.commit, 'RESEARCH.md')).toBe(notes); - expect(fs.readFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), 'utf8')).toBe(notes); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - const node = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; - expect(node.proof).toBeUndefined(); expect(node.integratedCheck).toBeUndefined(); - expect(committedSource(workers[0].worktree, state.cooperation!.canonicalCommit ?? problem.baseCommit, - path.join(problem.projectRelative, 'Submission.lean'))).toContain('sorry'); - held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('does not treat inherited nonempty notes as a new handoff from the current thread', async () => { - const { state, workers, check, events, run } = fixture(); - const inherited = 'Previous assignment: a reduction exists, but its exact classification gap was not investigated here.\n'; - const held = sessions(() => {}, inherited); - const completion = run(held.open); await held.waitSecond(completion); - expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-1']); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(held.messages[1]).toMatch(/RESEARCH\.md/u); - expect(held.messages[1]).toMatch(/research-observe/u); - expect(state.workers![1].previousThreadIds ?? []).toEqual([]); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('accepts a current-thread update to inherited notes while retaining the actual saved draft', async () => { - const { state, workers, check, events, run, publishCheckpoint } = fixture(); - const revised = 'Current assignment: searched the pinned declaration corpus without a classification theorem.\n' + - 'The remaining input is least-truant classification, and the wrapper only consumes that input.\n'; - const held = sessions(workspace => { - fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), revised); publishCheckpoint(); - }, - 'An inherited earlier mathematical checkpoint.\n'); - const completion = run(held.open); await held.waitSecond(completion); - expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-2']); - expect(events.filter(item => item.event === 'context_restarted')).toHaveLength(1); - expect(committedSource(workers[1].worktree, state.cooperation!.researchDrafts!.investigate.commit, 'RESEARCH.md')).toBe(revised); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('preserves the same unsaved high-context thread across a saved run and resume', async () => { - const { state, check, events, run } = fixture(); - const held = sessions(); - await expect(run(held.open, 1)).resolves.toBeUndefined(); - const file = path.join(directory, 'resumable-state.json'); - writeSolverRunState(file, state); Object.assign(state, readSolverRunState(file)); - expect(state.workers![1]).toMatchObject({ threadId: 'checkpoint-thread-1', lastInputTokens: 100_000 }); - const completion = run(held.open, 2); await held.waitSecond(completion); - expect(held.open.mock.calls.at(-1)![0].threadId).toBe('checkpoint-thread-1'); - expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-1']); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('deduplicates checkpoint requests across repeated turns and a persisted run', async () => { - const { state, check, events, run } = fixture(); - const started = Array.from({ length: 3 }, () => deferred()); - const done = Array.from({ length: 3 }, () => deferred()); - let turns = 0; - const messages: string[] = []; - const open = vi.fn(async (options: MathAgentOptions): Promise => ({ - threadId: options.threadId ?? 'deduplicated-thread', lastInputTokens: 100_000, - close: async () => { done[turns - 1]?.resolve('interrupted'); }, - interrupt: async () => { done[turns - 1]?.resolve('interrupted'); }, - run: async (message, _messageId, _workspace, onStarted) => { - const turn = turns++; - if (turn >= 3) throw new Error('fixture_unexpected_fourth_turn'); - messages.push(message); onStarted(`deduplicated-turn-${turn}`); - // A writing turn arms the advisory clock at its first produced item. - options.onActivity?.({ event: 'reasoning' }); - started[turn].resolve(); return done[turn].promise; - }, - })); - const first = run(open, 2); await started[0].promise; - await vi.advanceTimersByTimeAsync(120_000); await started[1].promise; - await vi.advanceTimersByTimeAsync(240_000); await expect(first).resolves.toBeUndefined(); - const file = path.join(directory, 'pending-checkpoint.json'); - writeSolverRunState(file, state); - const persisted = readSolverRunState(file); - expect(persisted.workers![1]).toMatchObject({ contextCheckpoint: { threadId: 'deduplicated-thread', - requestedAt: expect.any(Number) } }); - Object.assign(state, persisted); - const completion = run(open, 3); - await Promise.race([started[2].promise, completion.then(() => { throw new Error('fixture_missing_third_turn'); })]); - expect(open.mock.calls.at(-1)![0].threadId).toBe('deduplicated-thread'); - expect(events.filter(item => item.event === 'context_checkpoint_requested')).toHaveLength(1); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(messages.slice(1).every(message => /RESEARCH\.md/u.test(message) && /research-observe/u.test(message))).toBe(true); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - done[2].resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('still replaces an unsaved thread after an actual provider context overflow', async () => { - const { state, check, events, run } = fixture(); - const recovered = deferred(), finish = deferred(); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - const overflow = open.mock.calls.length === 1; - return { threadId: overflow ? 'overflow-thread' : 'fresh-overflow-recovery', lastInputTokens: 100_000, - ...(overflow ? { lastError: 'contextWindowExceeded', lastFailureDiagnostic: { code: 'contextWindowExceeded' } } : {}), - close: async () => { if (!overflow) finish.resolve('interrupted'); }, interrupt: async () => {}, - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted(overflow ? 'overflow-turn' : 'recovered-turn'); - if (overflow) return 'failed'; - expect(options.threadId).toBeUndefined(); recovered.resolve(); return finish.promise; - } }; - }); - const completion = run(open); - await Promise.race([recovered.promise, completion.then(() => { throw new Error('fixture_overflow_not_recovered'); })]); - expect(open).toHaveBeenCalledTimes(2); - expect(state.workers![1].previousThreadIds).toEqual(['overflow-thread']); - expect(events.filter(item => item.event === 'worker_context_recovering')).toHaveLength(1); - expect(events.filter(item => item.event === 'context_restarted')).toHaveLength(1); - expect(state.workers![1].contextOverflow).toMatchObject({ maxOptionalContextBytes: 0 }); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('requests a portable argument once during a live high-context turn without interrupting it', async () => { - const { state, check, events, run } = fixture(); - const started = deferred(), finish = deferred(); - let inputTokens = 89_000; - let activity: MathAgentOptions['onActivity']; - const notify = vi.fn(async (_message: string) => {}), interrupt = vi.fn(async () => {}); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - activity = options.onActivity; - return { threadId: 'live-reasoning-thread', get lastInputTokens() { return inputTokens; }, notify, interrupt, - close: async () => { finish.resolve('interrupted'); }, - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted('live-reasoning-turn'); started.resolve(); return finish.promise; - } }; - }); - const completion = run(open, 1); await started.promise; - activity!({ event: 'reasoning' }); await Promise.resolve(); - expect(events.filter(item => item.event === 'context_checkpoint_requested')).toEqual([]); - inputTokens = 91_000; - activity!({ event: 'reasoning' }); await Promise.resolve(); await Promise.resolve(); - expect(events.filter(item => item.event === 'context_checkpoint_requested')).toEqual([{ - event: 'context_checkpoint_requested', details: { workerId: 'researcher', threadId: 'live-reasoning-thread', - reason: 'context-threshold', lastInputTokens: 91_000 }, - }]); - expect(notify).toHaveBeenCalledOnce(); - expect(notify.mock.calls[0][0]).toMatch(/RESEARCH\.md/u); - expect(notify.mock.calls[0][0]).toMatch(/research-observe/u); - inputTokens = 105_000; - activity!({ event: 'reasoning' }); await Promise.resolve(); - expect(notify).toHaveBeenCalledOnce(); expect(interrupt).not.toHaveBeenCalled(); - expect(open).toHaveBeenCalledOnce(); expect(state.workers![1].threadId).toBe('live-reasoning-thread'); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(check).not.toHaveBeenCalled(); expect(state.check).toBeUndefined(); - finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('retains early and updated notes until the report and current checkpoint are explicitly published', async () => { - const { state, workers, check, events, run, publishCheckpoint } = fixture(); - const started = Array.from({ length: 3 }, () => deferred()); - const done = Array.from({ length: 3 }, () => deferred()); - const executedThreads: string[] = [], messages: string[] = []; - const early = 'An early reduction, before the later classification argument.\n'; - const current = early + 'Current gap: the classification argument still needs an independent finite certificate.\n'; - const notes = path.join(workers[1].worktree, 'RESEARCH.md'); - let inputTokens = 89_000, turns = 0, threads = 0; - let activity: MathAgentOptions['onActivity']; - const notify = vi.fn(async (_message: string) => {}), interrupt = vi.fn(async () => {}); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - activity = options.onActivity; - const threadId = options.threadId ?? `checkpoint-window-${++threads}`; - return { threadId, get lastInputTokens() { return inputTokens; }, notify, interrupt, - close: async () => { done[turns - 1]?.resolve('interrupted'); }, - run: async (message, _messageId, _workspace, onStarted) => { - const turn = turns++; - if (turn >= 3) throw new Error('fixture_unexpected_fourth_turn'); - executedThreads.push(threadId); messages.push(message); onStarted(`checkpoint-window-turn-${turn}`); - started[turn].resolve(); return done[turn].promise; - } }; - }); - const completion = run(open, 3); await started[0].promise; - fs.writeFileSync(notes, early); - inputTokens = 91_000; activity!({ event: 'reasoning' }); await Promise.resolve(); - expect(notify).toHaveBeenCalledOnce(); - expect(state.workers![1].contextCheckpoint).toMatchObject({ threadId: 'checkpoint-window-1', notesDigest: mathDigest(early) }); - inputTokens = 96_000; done[0].resolve('checkpoint'); - await Promise.race([started[1].promise, completion.then(() => { throw new Error('fixture_missing_second_turn'); })]); - expect(executedThreads).toEqual(['checkpoint-window-1', 'checkpoint-window-1']); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(messages[1]).toMatch(/RESEARCH\.md/u); - expect(state.workers![1].threadId).toBe('checkpoint-window-1'); - fs.writeFileSync(notes, current); - await vi.advanceTimersByTimeAsync(5_000); - expect(interrupt).not.toHaveBeenCalled(); - expect(executedThreads).toEqual(['checkpoint-window-1', 'checkpoint-window-1']); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(state.workers![1].contextCheckpoint?.publishedNotesDigest).toBeUndefined(); - publishCheckpoint(); done[1].resolve('checkpoint'); - await Promise.race([started[2].promise, completion.then(() => { throw new Error('fixture_missing_replacement_turn'); })]); - expect(executedThreads).toEqual(['checkpoint-window-1', 'checkpoint-window-1', 'checkpoint-window-2']); - expect(events.filter(item => item.event === 'context_restarted')).toHaveLength(1); - expect(events).toContainEqual({ event: 'context_checkpoint_ready', details: { workerId: 'researcher', - threadId: 'checkpoint-window-1', notesDigest: mathDigest(current) } }); - expect(committedSource(workers[1].worktree, state.cooperation!.researchDrafts!.investigate.commit, 'RESEARCH.md')).toBe(current); - expect(interrupt).not.toHaveBeenCalled(); expect(check).not.toHaveBeenCalled(); - expect(state.cooperation!.tasks.find(node => node.task.id === 'investigate')?.proof).toBeUndefined(); - done[2].resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it('honors a persisted checkpoint request even when an older archive has no session baseline', async () => { - const { state, workers, check, events, run } = fixture(); - const inherited = 'A saved earlier reduction, without the later argument.\n'; - const held = sessions(() => {}, inherited); - await expect(run(held.open, 1)).resolves.toBeUndefined(); - const worker = state.workers![1]; - delete worker.contextCheckpointBaseline; - worker.contextCheckpoint = { threadId: worker.threadId!, requestedAt: Date.now(), notesDigest: mathDigest(inherited) }; - const file = path.join(directory, 'legacy-checkpoint-request.json'); - writeSolverRunState(file, state); Object.assign(state, readSolverRunState(file)); - expect(state.workers![1].contextCheckpointBaseline).toBeUndefined(); - const completion = run(held.open, 2); await held.waitSecond(completion); - expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-1']); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(fs.readFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), 'utf8')).toBe(inherited); - expect(held.messages[1]).toMatch(/RESEARCH\.md/u); expect(check).not.toHaveBeenCalled(); - held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - }); - - it.each([false, true])('preserves a legacy thread without checkpoint metadata until a requested handoff is saved (%s)', async hasNotes => { - const { state, workers, check, events, run, publishCheckpoint } = fixture(); - const held = sessions(); - await expect(run(held.open, 1)).resolves.toBeUndefined(); - const notes = path.join(workers[1].worktree, 'RESEARCH.md'); - if (hasNotes) fs.writeFileSync(notes, 'Legacy notes do not establish when the last argument was saved.\n'); - delete state.workers![1].contextCheckpoint; delete state.workers![1].contextCheckpointBaseline; - const file = path.join(directory, 'legacy-context-state.json'); - writeSolverRunState(file, state); Object.assign(state, readSolverRunState(file)); - const completion = run(held.open, 2); await held.waitSecond(completion); - expect(held.open.mock.calls.at(-1)![0].threadId).toBe('checkpoint-thread-1'); - expect(held.executedThreads).toEqual(['checkpoint-thread-1', 'checkpoint-thread-1']); - expect(events.filter(item => item.event === 'context_restarted')).toEqual([]); - expect(state.workers![1].contextCheckpoint).toMatchObject({ threadId: 'checkpoint-thread-1' }); - expect(check).not.toHaveBeenCalled(); - fs.writeFileSync(notes, 'A requested current handoff preserves the precise unresolved classification step.\n'); - publishCheckpoint(); - held.finish.resolve('checkpoint'); await expect(completion).resolves.toBeUndefined(); - const reopened = deferred(), finish = deferred(); - const open = vi.fn(async (options: MathAgentOptions): Promise => { - expect(options.threadId).toBeUndefined(); - return { threadId: 'legacy-replacement-thread', lastInputTokens: 1, - close: async () => { finish.resolve('interrupted'); }, interrupt: async () => {}, - run: async (_message, _messageId, _workspace, onStarted) => { - onStarted('legacy-replacement-turn'); reopened.resolve(); return finish.promise; - } }; - }); - const resumed = run(open, 3); - await Promise.race([reopened.promise, resumed.then(() => { throw new Error('fixture_missing_legacy_replacement'); })]); - expect(events.filter(item => item.event === 'context_restarted')).toHaveLength(1); - expect(state.workers![1].threadId).toBe('legacy-replacement-thread'); - expect(check).not.toHaveBeenCalled(); finish.resolve('checkpoint'); await expect(resumed).resolves.toBeUndefined(); - }); - - it.each([ - { contextCheckpoint: { threadId: '', requestedAt: 0 } }, - { contextCheckpoint: { threadId: 'thread', requestedAt: -1 } }, - { contextCheckpoint: { threadId: 'thread', requestedAt: 0, deferredAt: -1 } }, - { contextCheckpoint: { threadId: 'thread', requestedAt: 0, notesDigest: 'not-a-digest' } }, - { contextCheckpointBaseline: { threadId: '', notesDigest: 'a'.repeat(64) } }, - { contextCheckpointBaseline: { threadId: 'thread', notesDigest: 'not-a-digest' } }, - ])('rejects malformed persisted context checkpoint metadata: %j', invalid => { - const { state } = fixture(); - Object.assign(state.workers![1], invalid); - const file = path.join(directory, 'invalid-checkpoint.json'); - writeSolverRunState(file, state); - expect(() => readSolverRunState(file)).toThrow('math_resume_state_invalid:workers.1.contextCheckpoint'); - }); -}); diff --git a/tests/solverStaleFailure.test.ts b/tests/solverStaleFailure.test.ts deleted file mode 100644 index 5601a492..00000000 --- a/tests/solverStaleFailure.test.ts +++ /dev/null @@ -1,355 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { ownedSourceDigest } from '../src/solver/cooperativeProof'; -import { directSolverModules, type SolverModules } from '../src/solver/modules'; -import type { ProofCheck } from '../src/solver/modules/evidence'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { runResearchWorkers } from '../src/solver/research'; -import * as statementReview from '../src/solver/statementReview'; -import { isStatementAction, statementSnapshot, writeStatementSnapshot, type StatementAction, type StatementReview } from '../src/solver/statementReview'; -import { parseCooperationPlan, taskVersion, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch, workerAccess } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); - -describe('failed turns superseded while their session closes', () => { - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - let cooperative: CooperativeResearch | undefined; - let events: { event: string; details?: Record }[]; - - beforeEach(() => { - const example = localExample('solver-stale-failure-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'peer', { role: 'engineer' })]; - const plan = parseCooperationPlan(problem, { tasks: problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}`, - proofPath: target.proofPath, theoremName: target.theoremName, - })) }); - state = solverState(problem, example.workspace, { runId: 'stale-failure-fixture', phase: 'prepared', - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture', - workers: workers.map(worker => ({ ...worker, phase: 'prepared', turns: 0 })), - cooperation: { tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - events = []; cooperative = undefined; - }); - afterEach(() => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const baseDigest = () => ownedSourceDigest(problem, workers[0].worktree, problem.baseCommit); - const create = () => { - const controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal }); - return controller; - }; - const restore = async () => { - const controller = create(); - await cooperative!.restore(); - return controller; - }; - const addStatementReview = (kind: StatementAction['kind']): StatementReview => { - const node = state.cooperation!.tasks[0]; - node.task = { ...node.task, statementReview: true, informalStatement: 'The original arithmetic target holds.' }; - const snapshot = statementSnapshot(problem, node.task, workers[0].worktree, problem.baseCommit, state.environmentDigest, []); - const workspace = path.join(directory, 'statement-review'); - const review: StatementReview = { id: 'statement-fixture', taskId: node.task.id, taskDigest: taskVersion(node.task), - snapshotDigest: snapshot.snapshotDigest, environmentDigest: state.environmentDigest, commit: problem.baseCommit, - leanStatement: snapshot.input.leanStatement, intendedStatement: node.task.informalStatement!, premises: [], dependencies: [], - workspace, files: writeStatementSnapshot(workspace, snapshot), status: kind === 'backtranslate' ? 'pending' : 'translated', - ...(kind === 'statement-review' ? { translation: { mathematics: 'The original arithmetic target holds.', assumptions: [], - definitions: [], evidenceRefs: [] } } : {}) }; - state.cooperation!.statementReviews = [review]; - return review; - }; - - it.each((['task', 'lead', 'review', 'backtranslate', 'statement-review'] as const).flatMap(kind => - (['revise', 'remove', 'pause'] as const).map(change => ({ kind, change })))) - ('preserves the new plan when an edit applies $change during a failed $kind session close', async ({ kind, change }) => { - if (kind === 'lead') state.cooperation!.error = 'A new Lead assessment is requested.'; - if (kind === 'review') state.cooperation!.review = { commit: problem.baseCommit, sourceDigest: baseDigest(), status: 'pending' }; - if (kind === 'backtranslate' || kind === 'statement-review') { - vi.spyOn(statementReview, 'captureStatementContexts').mockImplementation(async (_problem, tasks) => - new Map(tasks.map(task => [task.id, { type: 'Mock fixed arithmetic type.', constants: [], omitted: [] }]))); - const restore = CooperativeResearch.prototype.restore; - vi.spyOn(CooperativeResearch.prototype, 'restore').mockImplementation(async function(...args) { - const result = await restore.apply(this, args); - addStatementReview(kind); - return result; - }); - } - const target = state.cooperation!.tasks[0].task; - const activate = CooperativeResearch.prototype.activate; - vi.spyOn(CooperativeResearch.prototype, 'activate').mockImplementation(function(...args) { - cooperative = this; - return activate.apply(this, args); - }); - let assigned: CooperativeAction | undefined; - let edited = false; - const retry = vi.fn().mockReturnValue(undefined); - const close = vi.fn(async () => { - if (edited || !assigned) return; - edited = true; - const failedTask = assigned.kind === 'task' ? assigned.task : target; - const tasks = state.cooperation!.tasks.map(node => node.task).flatMap(task => { - if (task.id !== failedTask.id) return [task]; - if (change === 'remove') return []; - return [{ ...task, ...(change === 'revise' ? { revision: task.revision + 1 } : { status: 'paused' as const }) }]; - }); - if (change === 'remove') { - tasks.push({ ...failedTask, id: 'replacement', revision: failedTask.revision + 1 }); - } - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ - id: 'during-close', baseVersion: state.cooperation!.planVersion, tasks, - }) + '\n'); - await cooperative!.pulse(); - expect(state.cooperation!.edits?.find(edit => edit.id === 'during-close')?.status).toBe('applied'); - if (kind === 'review' && change !== 'pause') { - cooperative!.rejected(assigned, 'Late failure from the superseded review.'); - expect(state.cooperation!.review).toBeUndefined(); - } - }); - const modules: SolverModules = { ...directSolverModules, - M1: { ...directSolverModules.M1, open: async options => ({ - threadId: 'fixture-failed-thread', lastError: 'fetch failed', close, - interrupt: vi.fn(async () => {}), run: async message => { - const action = JSON.parse(message) as CooperativeAction; - if (action.kind !== kind) throw new Error('fixture_unexpected_model_assignment'); - assigned = action; - if (!isStatementAction(action)) { - const file = path.join(options.workspace, problem.projectRelative, - action.kind === 'task' ? action.task.proofPath! : target.proofPath!); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('n + 0 = n', 'n + 0 = 0')); - } - return 'failed'; - }, - }) }, - M2: { ...directSolverModules.M2, - check: async () => { throw new Error('fixture_unexpected_proof_check'); }, - checkTask: async () => { throw new Error('fixture_unexpected_task_check'); } }, - M3: { ...directSolverModules.M3, retry, select: (_state, _options, _budget, assignment) => - kind === 'lead' && assignment?.kind === 'task' ? { operation: 'stop', reason: 'fixture_only_lead_runs' } - : { operation: 'direct', reason: 'fixture_failure' } }, - M4: { ...directSolverModules.M4, build: (_problem, _state, access) => ({ - instructions: 'Local fixture.', message: JSON.stringify(access.assignment), - scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, - }), statement: (_review, action, problemReceiptDigest) => ({ - instructions: 'Fixed local statement fixture.', message: JSON.stringify(action), - scope: 'fixed-statement', sources: { problemReceiptDigest }, - }) }, - }; - - const result = runResearchWorkers({ state, workers, modules, - access: workerAccess(workers, directory), root: directory, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the original targets.', - executable: 'fixture-no-model', profile: 'fixture', signal: new AbortController().signal, - deadline: Infinity, maxTurns: 1, maxTurnMs: Infinity, maxTotalTokens: 0, - save: () => {}, emit: (event, details) => events.push({ event, details }), - }); - const reviewRemainsCurrent = kind === 'review' && change === 'pause'; - await expect(result).resolves.toBeUndefined(); - - expect(edited).toBe(true); - expect(state.cooperation!.tasks.every(node => node.status === 'pending' && !node.feedback)).toBe(true); - const failures = state.cooperation!.deliveries?.filter(delivery => delivery.kind === 'failure') ?? []; - const sourceRejections = events.filter(event => event.event === 'source_rejected'); - if (reviewRemainsCurrent) { - // Pausing only changes scheduling. Reject the review's invalid edit and leave the run resumable. - expect(state.cooperation!.tasks.find(node => node.task.id === target.id)?.task.status).toBe('paused'); - const reason = expect.stringContaining('math_original_declaration_changed'); - expect(failures).toMatchObject([{ status: 'failed', summary: reason }]); - expect(state.cooperation!.review).toMatchObject({ status: 'changes_requested', - commit: problem.baseCommit, sourceDigest: baseDigest(), summary: reason }); - expect(sourceRejections).toMatchObject([{ details: { reason } }]); - } else { - expect(failures).toEqual([]); - expect(sourceRejections).toEqual([]); - } - expect(events.some(event => event.event === 'assignment_superseded')).toBe(!reviewRemainsCurrent); - if (kind === 'review' && !reviewRemainsCurrent) expect(state.cooperation!.deliveries).toContainEqual( - expect.objectContaining({ kind: 'review', status: 'superseded', commit: problem.baseCommit })); - expect(retry).not.toHaveBeenCalled(); - expect(close).toHaveBeenCalledOnce(); - }); - - it.each(['replacement', 'accepted'])('preserves a %s review and its records after late callbacks from the old action', async version => { - const controller = create(); - try { - await cooperative!.restore(); - const check: ProofCheck = { commit: problem.baseCommit, sourceDigest: baseDigest(), passed: true, - verification: { schema: 'deepscientist.mathematics.verification-batch/v1', status: 'kernel_verified', - targetCommit: problem.baseCommit, sessionId: 'review-fixture', events: [], results: [], - startedAt: 1, checkedAt: 2, durationMs: 1 } }; - cooperative!.requireReview(check); - const action = await cooperative!.next(workers[1], budget); - if (action?.kind !== 'review') throw new Error('fixture_missing_review_assignment'); - expect(cooperative!.started(workers[1], action)).toBe(true); - if (version === 'accepted') { - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), '```math-review\n' + JSON.stringify({ - commit: action.seedCommit, verdict: 'accepted', summary: 'Fixed candidate reviewed.', - }) + '\n```'); - await cooperative!.deliver(workers[1], action, commitSolverSources(problem, workers[1].worktree)); - } else { - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'A replacement immutable candidate.\n'); - cooperative!.requireReview({ ...check, commit: commitSolverSources(problem, workers[0].worktree) }); - } - const current = { ...state.cooperation!.review }; - expect(cooperative!.current(action)).toBe(false); - - cooperative!.rejected(action, 'Late failure from the old review action.'); - cooperative!.interrupted(workers[1], action); - cooperative!.release(workers[1], action); - await cooperative!.deliver(workers[1], action, action.seedCommit); - - expect(state.cooperation!.review).toEqual(current); - expect(state.cooperation!.review?.status).toBe(version === 'accepted' ? 'accepted' : 'pending'); - expect(state.cooperation!.deliveries?.filter(delivery => delivery.kind === 'review').map(delivery => delivery.status)) - .toEqual(version === 'accepted' ? ['accepted', 'superseded'] : ['superseded']); - expect(state.cooperation!.deliveries?.some(delivery => delivery.kind === 'failure')).not.toBe(true); - } finally { controller.abort(); await cooperative!.stop(); } - }); - - it.each(['accepted', 'changes_requested'] as const)('does not reopen a legacy %s review after late cancellation or release', async status => { - const controller = await restore(); - try { - state.cooperation!.review = { commit: problem.baseCommit, sourceDigest: baseDigest(), status, workerId: workers[1].id }; - const action: CooperativeAction = { kind: 'review', seedCommit: problem.baseCommit, - sourceDigest: state.cooperation!.review.sourceDigest }; - const before = { ...state.cooperation!.review }; - cooperative!.interrupted(workers[1], action); - cooperative!.release(workers[1], action); - expect(state.cooperation!.review).toEqual(before); - } finally { controller.abort(); await cooperative!.stop(); } - }); - - it('isolates repeated final reviews of the same commit and worker from every old callback', async () => { - const controller = await restore(); - try { - state.cooperation!.review = { commit: problem.baseCommit, sourceDigest: baseDigest(), status: 'pending' }; - const first = await cooperative!.next(workers[1], budget); - if (first?.kind !== 'review') throw new Error('fixture_missing_review_assignment'); - expect(cooperative!.started(workers[1], first)).toBe(true); - cooperative!.interrupted(workers[1], first); - const second = await cooperative!.next(workers[1], budget); - if (second?.kind !== 'review') throw new Error('fixture_missing_review_assignment'); - expect(first.assignmentId).toEqual(expect.any(String)); - expect(second.assignmentId).toEqual(expect.any(String)); - expect(second.assignmentId).not.toBe(first.assignmentId); - const before = { ...state.cooperation!.review }; - const turns = state.cooperation!.groups![0].turns; - - expect(cooperative!.current(first)).toBe(false); - expect(cooperative!.started(workers[1], first)).toBe(false); - expect(() => cooperative!.started(workers[0], second)).toThrow('math_review_assignment_invalid'); - cooperative!.rejected(first, 'Failure from the previous dispatch.'); - cooperative!.interrupted(workers[1], first); - cooperative!.release(workers[1], first); - fs.writeFileSync(path.join(workers[1].worktree, 'RESEARCH.md'), '```math-review\n' + JSON.stringify({ - commit: first.seedCommit, verdict: 'accepted', summary: 'Old dispatch result.', - }) + '\n```'); - await cooperative!.deliver(workers[1], first, first.seedCommit); - await cooperative!.deliver(workers[1], first, first.seedCommit, true); - - expect(state.cooperation!.review).toEqual(before); - expect(state.cooperation!.groups![0].turns).toBe(turns); - expect(state.cooperation!.deliveries?.filter(record => record.kind === 'review').map(record => record.status)) - .toEqual(['superseded', 'superseded']); - expect(state.cooperation!.deliveries?.some(record => record.kind === 'failure')).not.toBe(true); - expect(cooperative!.started(workers[1], second)).toBe(true); - cooperative!.rejected(second, 'Current reviewer diagnostic.'); - expect(state.cooperation!.review).toMatchObject({ status: 'changes_requested', workerId: undefined }); - expect(state.cooperation!.deliveries?.at(-1)).toMatchObject({ producer: workers[1].id, kind: 'failure' }); - } finally { controller.abort(); await cooperative!.stop(); } - }); - - it('accepts a legacy running review only until its first new dispatch', async () => { - const controller = await restore(); - try { - state.cooperation!.review = { commit: problem.baseCommit, sourceDigest: baseDigest(), status: 'running', workerId: workers[1].id }; - const legacy: CooperativeAction = { kind: 'review', seedCommit: problem.baseCommit, - sourceDigest: state.cooperation!.review.sourceDigest }; - expect(cooperative!.current(legacy)).toBe(true); - cooperative!.interrupted(workers[1], legacy); - const next = await cooperative!.next(workers[1], budget); - if (next?.kind !== 'review') throw new Error('fixture_missing_review_assignment'); - expect(next.assignmentId).toEqual(expect.any(String)); - expect(cooperative!.current(legacy)).toBe(false); - const wrongSource = { ...next, sourceDigest: 'wrong-fixed-source' }; - const before = { ...state.cooperation!.review }; - cooperative!.interrupted(workers[1], wrongSource); - await cooperative!.deliver(workers[1], wrongSource, next.seedCommit); - expect(state.cooperation!.review).toEqual(before); - } finally { controller.abort(); await cooperative!.stop(); } - }); - - it.each(['backtranslate', 'statement-review'] as const)('isolates repeated %s dispatches in the same workspace', async kind => { - const controller = await restore(); - try { - const review = addStatementReview(kind); - const first = await cooperative!.next(workers[1], budget); - if (!first || first.kind !== kind) throw new Error('fixture_missing_statement_assignment'); - expect(cooperative!.started(workers[1], first)).toBe(true); - cooperative!.interrupted(workers[1], first); - const second = await cooperative!.next(workers[1], budget); - if (!second || second.kind !== kind) throw new Error('fixture_missing_statement_assignment'); - expect(second.assignmentId).toEqual(expect.any(String)); - expect(second.assignmentId).not.toBe(first.assignmentId); - expect(second.workspace).toBe(first.workspace); - const before = { ...review }; - const turns = state.cooperation!.groups![0].turns; - - expect(cooperative!.current(first)).toBe(false); - expect(cooperative!.started(workers[1], first)).toBe(false); - expect(() => cooperative!.started(workers[0], second)).toThrow('math_statement_review_assignment_invalid'); - cooperative!.rejected(first, 'Failure from the previous statement dispatch.'); - cooperative!.interrupted(workers[1], first); - cooperative!.release(workers[1], first); - fs.writeFileSync(path.join(review.workspace, 'RESEARCH.md'), '```' + - (kind === 'backtranslate' ? 'math-backtranslation' : 'math-statement-review') + '\n' + JSON.stringify({ - reviewId: review.id, snapshotDigest: review.snapshotDigest, mathematics: 'The original arithmetic target holds.', - verdict: 'accepted', summary: 'The fixed intended statement agrees.', - }) + '\n```'); - await cooperative!.deliverStatement(workers[1], first); - expect(review).toEqual(before); - expect(state.cooperation!.groups![0].turns).toBe(turns); - expect(state.cooperation!.deliveries?.at(-1)).toMatchObject({ status: 'superseded' }); - expect(cooperative!.started(workers[1], second)).toBe(true); - await cooperative!.deliverStatement(workers[1], second); - expect(review.status).toBe(kind === 'backtranslate' ? 'translated' : 'accepted'); - expect(review.workerId).toBeUndefined(); - const completed = { ...review }; - cooperative!.rejected(second, 'Late terminal failure.'); - cooperative!.interrupted(workers[1], second); - cooperative!.release(workers[1], second); - expect(cooperative!.started(workers[1], second)).toBe(false); - expect(review).toEqual(completed); - } finally { controller.abort(); await cooperative!.stop(); } - }); - - it.each(['backtranslate', 'statement-review'] as const)('migrates a legacy running %s without accepting its later callbacks', async kind => { - const controller = await restore(); - try { - const review = addStatementReview(kind); - review.status = kind === 'backtranslate' ? 'translating' : 'reviewing'; review.workerId = workers[1].id; - const legacy: StatementAction = { kind, reviewId: review.id, taskId: review.taskId, taskDigest: review.taskDigest, - snapshotDigest: review.snapshotDigest, seedCommit: review.commit, workspace: review.workspace }; - expect(cooperative!.current(legacy)).toBe(true); - cooperative!.interrupted(workers[1], legacy); - const next = await cooperative!.next(workers[1], budget); - if (!next || next.kind !== kind) throw new Error('fixture_missing_statement_assignment'); - expect(next.assignmentId).toEqual(expect.any(String)); - expect(cooperative!.current(legacy)).toBe(false); - const before = { ...review }, turns = state.cooperation!.groups![0].turns; - expect(cooperative!.started(workers[1], legacy)).toBe(false); - cooperative!.rejected(legacy, 'Late legacy diagnostic.'); - cooperative!.interrupted(workers[1], legacy); - cooperative!.release(workers[1], legacy); - await cooperative!.deliverStatement(workers[1], legacy); - expect(review).toEqual(before); - expect(state.cooperation!.groups![0].turns).toBe(turns); - expect(state.cooperation!.deliveries?.at(-1)).toMatchObject({ status: 'superseded' }); - } finally { controller.abort(); await cooperative!.stop(); } - }); -}); diff --git a/tests/solverStoppedOwner.test.ts b/tests/solverStoppedOwner.test.ts deleted file mode 100644 index d9ff1c6e..00000000 --- a/tests/solverStoppedOwner.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import fs from 'node:fs'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import { assessTaskResponsibility, type ResearchWorker } from '../src/solver/modules/organization'; -import { researchCanAdvance } from '../src/solver/modules/search'; -import { parseCooperationPlan, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const record = (fields: Partial, extra: Partial = {}): TaskRecord => ({ - task: { id: 'reserved', kind: 'research', revision: 0, objective: 'Investigate.', dependsOn: [], ...fields } as TaskRecord['task'], - status: 'pending', attempts: 0, ...extra }); - -describe('reservations of stopped workers', () => { - const live = { id: 'peer-b', role: 'researcher' as const }; - - it('releases owner, engineer and saved-assignment pins only for a stopped worker', () => { - const stopped = new Set(['peer-a']); - const owned = record({ ownerId: 'peer-a' }); - expect(assessTaskResponsibility(owned, live, { tasks: [owned] })).toEqual({ kind: 'blocked', reason: 'owner' }); - expect(assessTaskResponsibility(owned, live, { tasks: [owned], stopped })).toEqual({ kind: 'matches' }); - expect(assessTaskResponsibility(owned, live, { tasks: [owned], stopped: new Set(['other']) })) - .toEqual({ kind: 'blocked', reason: 'owner' }); - const saved = record({}, { assignment: { workerId: 'peer-a' } as TaskRecord['assignment'] }); - expect(assessTaskResponsibility(saved, live, { tasks: [saved] })).toEqual({ kind: 'blocked', reason: 'saved-assignment' }); - expect(assessTaskResponsibility(saved, live, { tasks: [saved], stopped })).toEqual({ kind: 'matches' }); - const goal = record({ id: 'goal', kind: 'goal', groupId: 'main' }); - const groups = [{ group: { id: 'main', objective: 'Main', status: 'active' as const, revision: 0, engineerId: 'peer-a' }, turns: 0 }]; - expect(assessTaskResponsibility(goal, live, { tasks: [goal], groups })).toEqual({ kind: 'blocked', reason: 'engineer' }); - expect(assessTaskResponsibility(goal, live, { tasks: [goal], groups, stopped })).toEqual({ kind: 'matches' }); - }); - - it('keeps a stopped worker capacity exploration pinned', () => { - const exploration = record({ ownerId: 'peer-a' }, { capacityExploration: { workerId: 'peer-a' } as TaskRecord['capacityExploration'] }); - expect(assessTaskResponsibility(exploration, live, { tasks: [exploration], stopped: new Set(['peer-a']) })) - .toEqual({ kind: 'blocked', reason: 'owner' }); - }); - - it('lets an owned task advance once its stopped owner is released', () => { - const owned = record({ ownerId: 'peer-a' }); - expect(researchCanAdvance([owned], undefined, new Set(['peer-b']))).toBe(false); - expect(researchCanAdvance([owned], undefined, new Set(['peer-b']), undefined, undefined, new Set(['peer-a']))).toBe(true); - const exploration = record({ ownerId: 'peer-a' }, { capacityExploration: { workerId: 'peer-a' } as TaskRecord['capacityExploration'] }); - expect(researchCanAdvance([exploration], undefined, new Set(['peer-b']), undefined, undefined, new Set(['peer-a']))).toBe(false); - }); -}); - -describe('cooperative dispatch after an owner stops', () => { - let directory: string, state: SolverRunState, lead: ResearchWorker, owner: ResearchWorker, peer: ResearchWorker; - let cooperative: CooperativeResearch; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - - beforeEach(() => { - const example = localExample('solver-stopped-owner-', 'lead'), { workspace, problem } = example; - directory = example.directory; - lead = leadWorker(problem, workspace); - owner = peerWorker(example, 'peer-a'); - peer = peerWorker(example, 'peer-b'); - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}`, proofPath: target.proofPath, - theoremName: target.theoremName, status: 'paused' })), - { id: 'reserved', kind: 'research', objective: 'Investigate a concrete route.', ownerId: owner.id }, - ] }); - state = solverState(problem, workspace, { runId: 'stopped-owner-fixture', phase: 'running', - evaluatorDigest: 'evaluation', model: 'fixture', effort: 'fixture', cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const unexpectedModel = () => { throw new Error('fixture_models_forbidden'); }; - cooperative = cooperativeResearch({ state, workers: [lead, owner, peer], retrievalRoot: directory, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: unexpectedModel } } }); - }); - afterEach(async () => { - await cooperative.stop(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('gives a stopped owner\'s reserved task to an eligible live peer', async () => { - const reserved = () => state.cooperation!.tasks.find(node => node.task.id === 'reserved')!; - const first = await cooperative.next(owner, budget); - expect(first).toMatchObject({ kind: 'task', task: { id: 'reserved' } }); - expect(cooperative.started(owner, first!)).toBe(true); - cooperative.stopped(owner, 'math_source_outside_ownership'); - expect(reserved()).toMatchObject({ status: 'pending', assignment: { workerId: owner.id } }); - const next = await cooperative.next(peer, budget); - expect(next).toMatchObject({ kind: 'task', task: { id: 'reserved', ownerId: owner.id }, assignment: { workerId: peer.id } }); - expect(cooperative.started(peer, next!)).toBe(true); - expect(reserved().status).toBe('running'); - }); -}); diff --git a/tests/solverTacticBattery.test.ts b/tests/solverTacticBattery.test.ts deleted file mode 100644 index 6c10ee51..00000000 --- a/tests/solverTacticBattery.test.ts +++ /dev/null @@ -1,190 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_STATEMENT } from '../src/math/localExample'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { committedSource, commitSolverSources, git } from '../src/solver/problem'; -import type { SolverRunState } from '../src/solver/archive'; -import { tacticBatteryProof, vacuityProbeProof } from '../src/solver/tacticBattery'; -import { hasTaskAcceptance, taskVersion } from '../src/solver/tasks'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { failedBatch, verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), model: vi.fn(), lean: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'battery-fixture-tools', -})); -vi.mock('../src/math/mathProofEnvironment', async importOriginal => ({ - ...await importOriginal(), resolveMathProofEnvironment: () => undefined, -})); -vi.mock('../src/math/leanTypeDiagnostics', async importOriginal => ({ - ...await importOriginal(), checkLeanType: host.lean, -})); - -describe('host tactic battery before model dispatch', () => { - let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; - let controller: AbortController, allowed: boolean, emit: ReturnType; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const node = () => state.cooperation!.tasks.find(item => item.task.id === 'helper')!; - const next = () => cooperative.next(workers[1], budget); - const verified = (request: MathematicsVerifierBatchRequest) => verifiedBatch(request, { sessionId: 'battery-fixture', checks: true }); - const leanResult = (status: 'elaborated' | 'failed') => ({ status, timedOut: false, constants: status === 'elaborated' ? ['True.intro'] : undefined, - artifact: { path: '.lake/type-diagnostics/fixture/manifest.json', digest: 'b'.repeat(64) } }); - // The vacuity probe after a closed battery fails by default: the fixture helper has no hypotheses. - const probe = (input: { expression: string }) => input.expression === vacuityProbeProof(false); - const events = () => emit.mock.calls.filter(call => call[0] === 'task_tactic_battery').map(call => call[1]); - const canonical = () => committedSource(workers[0].worktree, state.cooperation!.canonicalCommit!, - `${state.problem.projectRelative}/Submission.lean`); - const noDelivery = () => { - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.failedTaskInputs ?? []).toEqual([]); - expect(node().proof).toBeUndefined(); expect(node().attempts).toBe(0); - expect(canonical()).toBe(LOCAL_EXAMPLE_STATEMENT); - }; - - beforeEach(() => { - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.model.mockReset().mockImplementation(() => { throw new Error('fixture_models_forbidden'); }); - host.lean.mockReset().mockImplementation(async input => leanResult(probe(input) ? 'failed' : 'elaborated')); - const example = localExample('solver-tactic-battery-'), { workspace, problem } = example; - directory = example.directory; - workers = [leadWorker(problem, workspace), peerWorker(example, 'proof')]; - const plan = parseCooperationPlan(problem, { tasks: [ - { id: 'helper', kind: 'lemma', objective: 'Prove exact helper', theoremName: 'Tutorial.helper', - proofPath: 'Submission.lean', type: 'True', ownerId: 'proof' }, - { id: 'followup', kind: 'research', objective: 'Observe dependency readiness', dependsOn: ['helper'], ownerId: 'proof' }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', objective: 'Original goal', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ], groups: [{ id: 'main', objective: 'Original problem', status: 'active', maxConcurrent: 1 }] }); - state = solverState(problem, workspace, { runId: 'battery-fixture', phase: 'running', - cooperation: { canonicalCommit: problem.baseCommit, groups: plan.groups.map(group => ({ group, turns: 0 })), - tasks: plan.tasks.map(task => ({ task, attempts: 0, status: 'pending' })) } }); - fs.writeFileSync(path.join(workers[0].worktree, state.problem.projectRelative, 'Submission.lean'), LOCAL_EXAMPLE_STATEMENT); - state.cooperation!.canonicalCommit = commitSolverSources(state.problem, workers[0].worktree); - const envFile = path.join(directory, 'math.env'); fs.writeFileSync(envFile, ''); - const environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - controller = new AbortController(); allowed = true; emit = vi.fn(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, emit, - access: new Map(workers.map(worker => [worker.id, { environment, retrievalRoot: directory }])), - modelDispatchAllowed: () => allowed, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: host.model, execute: host.model } } }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ current: () => !input.signal?.aborted, - result: { taskDigest: taskVersion(input.task), inputDigest: 'fixture', evidence: 'advisory-type-elaboration', - proofAcceptance: 'not-assessed', status: 'elaborated', reason: 'fixture', context: 'Tutorial.add_zero', type: 'True' } })); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); - expect(host.model).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('integrates a battery-closed helper through the ordinary kernel check without a model turn', async () => { - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(host.lean).toHaveBeenCalledTimes(2); - expect(host.lean.mock.calls[0][0]).toMatchObject({ context: 'Tutorial.add_zero', type: 'True', expression: tacticBatteryProof(false) }); - expect(host.lean.mock.calls[1][0]).toMatchObject({ context: 'Tutorial.add_zero', type: 'True', expression: vacuityProbeProof(false) }); - expect(node()).toMatchObject({ status: 'integrated', attempts: 0, proof: { passed: true }, integratedCheck: { passed: true } }); - // The complete-source merge preserves the checked projection, so integration reuses its exact receipt. - expect(host.verify).toHaveBeenCalledOnce(); - expect(host.verify.mock.calls.map(call => call[1].expectedDeclarationType)).toEqual(['True']); - expect(node().integratedCheck!.verification).toEqual(node().proof!.verification); - expect(node().integratedCheck!.commit).toBe(state.cooperation!.canonicalCommit); - expect(node().integratedCheck!.taskDigest).toBe(taskVersion(node().task)); - expect(hasTaskAcceptance(node().integratedCheck!)).toBe(true); - expect(canonical()).toContain(`theorem helper : True\n := ${tacticBatteryProof(false)}\n`); - for (const original of ['theorem add_zero (n : Nat) : n + 0 = n := by sorry', 'theorem zero_add (n : Nat) : 0 + n = n := by sorry']) - expect(canonical()).toContain(original); - expect(state.turns).toBe(0); expect(state.cooperation!.groups![0].turns).toBe(0); - expect(state.cooperation!.deliveries).toContainEqual(expect.objectContaining({ taskId: 'helper', kind: 'proof', status: 'verified' })); - expect(events()).toEqual([expect.objectContaining({ taskId: 'helper', workerId: 'proof', status: 'closed', - reason: 'battery-closed-erased-type', passed: true, verificationStatus: 'kernel_verified', commit: expect.any(String) })]); - expect(events()[0]).not.toHaveProperty('vacuous'); - expect(state.cooperation!.deliveries!.find(item => item.taskId === 'helper')!.summary).not.toContain('vacuity'); - }); - - it('still integrates a vacuous battery-closed helper but tells the Lead its hypotheses derive False', async () => { - host.lean.mockImplementation(async () => leanResult('elaborated')); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(node()).toMatchObject({ status: 'integrated', attempts: 0, proof: { passed: true } }); - expect(events()).toEqual([expect.objectContaining({ status: 'closed', passed: true, vacuous: true })]); - expect(state.cooperation!.deliveries!.find(item => item.taskId === 'helper')!.summary) - .toContain('Host vacuity probe: its hypotheses alone derive False'); - state.cooperation!.deliveries = JSON.parse(JSON.stringify(state.cooperation!.deliveries)); - await (cooperative as any).publishProofDelivery(node()); - expect(state.cooperation!.deliveries!.find(item => item.taskId === 'helper')!.summary) - .toContain('Host vacuity probe: its hypotheses alone derive False'); - }); - - it.each(['crashed', 'admitted'] as const)('does not report vacuity from a %s probe', async outcome => { - host.lean.mockImplementation(async input => { - if (!probe(input)) return leanResult('elaborated'); - if (outcome === 'crashed') throw new Error('fixture_probe_crashed'); - return { ...leanResult('elaborated'), constants: ['sorryAx'] }; - }); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(node().status).toBe('integrated'); expect(events()[0]).not.toHaveProperty('vacuous'); - }); - - it('falls through to normal model work after a failed battery and does not retry the same contract', async () => { - host.lean.mockImplementation(async () => leanResult('failed')); - const first = await next(); - expect(first).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - if (first?.kind !== 'task') throw new Error('expected_task_assignment'); - expect(git(workers[1].worktree, ['rev-parse', 'HEAD'])).toBe(first.assignment.seedCommit); - expect(events()).toEqual([expect.objectContaining({ status: 'failed', reason: 'battery-did-not-close' })]); - expect(host.verify).not.toHaveBeenCalled(); noDelivery(); - cooperative.release(workers[1], first); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - expect(host.lean).toHaveBeenCalledOnce(); expect(events()).toHaveLength(1); - }); - - it('reports a host failure-cache hit without creating proof evidence or reusing an old artifact', async () => { - vi.spyOn(directSolverModules.M2, 'closeTask').mockResolvedValue({ status: 'failed', reason: 'battery-did-not-close-reused', - evidence: 'advisory-tactic-battery', proofAcceptance: 'not-accepted', cacheHit: true, cacheKey: 'a'.repeat(64), - originDiagnosticDigest: 'b'.repeat(64) }); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - expect(events()).toEqual([expect.objectContaining({ status: 'failed', cacheHit: true, cacheKey: 'a'.repeat(64), - originDiagnosticDigest: 'b'.repeat(64) })]); - expect(events()[0]).not.toHaveProperty('artifact'); expect(host.lean).not.toHaveBeenCalled(); - expect(host.verify).not.toHaveBeenCalled(); noDelivery(); - }); - - it('returns model work without failure memory when the kernel rejects the battery candidate', async () => { - host.verify.mockImplementationOnce(async request => failedBatch(verified(request), - { stdoutPreview: () => 'Submission.lean:3:1: error: unsolved goals' })); - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - expect(events()).toEqual([expect.objectContaining({ status: 'closed', passed: false, verificationStatus: 'failed' })]); - expect(node().status).toBe('running'); noDelivery(); - }); - - it('keeps the contract eligible when the attempt is superseded while Lean runs', async () => { - const entered = deferred(), release = deferred(); - host.lean.mockImplementationOnce(async () => { entered.resolve(); await release.promise; return leanResult('failed'); }); - const pending = next(); await entered.promise; - allowed = false; cooperative.modelBudgetChanged(); release.resolve(); - expect(await pending).toBeUndefined(); expect(events()).toEqual([]); - expect(node()).toMatchObject({ status: 'pending' }); expect(node().assignment).toBeUndefined(); - allowed = true; - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'followup' } }); - expect(host.lean.mock.calls.filter(call => !probe(call[0]))).toHaveLength(2); expect(node().status).toBe('integrated'); - }); - - it.each(['conditional', 'saved-assignment', 'no-context', 'disabled'] as const)('does not run the battery for %s work', async kind => { - if (kind === 'conditional') node().task = { ...node().task, conditional: true }; - if (kind === 'saved-assignment') node().assignment = { taskId: 'helper', taskDigest: taskVersion(node().task), - workerId: workers[1].id, seedCommit: state.cooperation!.canonicalCommit!, assignmentId: 'saved' }; - if (kind === 'no-context') vi.mocked(TaskTypePreflightCache.prototype.check).mockImplementation(async input => ({ current: () => true, - result: { taskDigest: taskVersion(input.task), inputDigest: 'fixture', evidence: 'advisory-type-elaboration', - proofAcceptance: 'not-assessed', status: 'elaborated', reason: 'fixture' } })); - if (kind === 'disabled') (cooperative as any).input.modules.M2 = { ...directSolverModules.M2, closeTask: undefined }; - expect(await next()).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - expect(host.lean).not.toHaveBeenCalled(); expect(events()).toEqual([]); noDelivery(); - }); -}); diff --git a/tests/solverTaskTypePreflight.test.ts b/tests/solverTaskTypePreflight.test.ts deleted file mode 100644 index 6d9b3af9..00000000 --- a/tests/solverTaskTypePreflight.test.ts +++ /dev/null @@ -1,262 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { git } from '../src/solver/problem'; -import type { SolverRunState } from '../src/solver/archive'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { dropLeadWakes } from '../src/solver/leadWakes'; -import { TaskTypePreflightCache, type TaskTypePreflight } from '../src/solver/taskTypePreflight'; -import { taskVersion } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const actualPreflight = TaskTypePreflightCache.prototype.check; - -describe('typed helper dispatch admission', () => { - let directory: string, state: SolverRunState, workers: ResearchWorker[], cooperative: CooperativeResearch; - let controller: AbortController, emit: ReturnType, allowed: boolean; - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - const result = (status: TaskTypePreflight['status'] = 'elaborated', current = () => true) => ({ current, - result: { status, inputDigest: 'fixed-input', reason: 'exact closed query error', taskDigest: taskVersion(state.cooperation!.tasks[0].task), - evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } as TaskTypePreflight }); - const peer = (index = 1) => (cooperative as any).nextPeer(workers[index], budget, true); - const holdPreflight = () => { - type Finish = (status?: TaskTypePreflight['status'], current?: () => boolean) => void; - let signal!: AbortSignal, finish!: Finish; - vi.mocked(TaskTypePreflightCache.prototype.check).mockImplementation(input => { - signal = input.signal!; - return new Promise(resolve => { finish = (status, current) => resolve(result(status, current)); }); - }); - return { get signal() { return signal; }, finish: ((status, current) => finish(status, current)) as Finish }; - }; - beforeEach(() => { - budget.maxTurns = Infinity; - const example = localExample('solver-type-preflight-', 'lead'), { workspace, problem } = example; - directory = example.directory; - workers = [leadWorker(problem, workspace, 'lead'), ...['proof', 'other'].map(id => peerWorker(example, id))]; - const parsed = parseCooperationPlan(problem, { tasks: [{ id: 'helper', kind: 'lemma', objective: 'Prove helper', - theoremName: 'Tutorial.helper', type: 'True', proofPath: 'Submission.lean', ownerId: 'proof' }, - { id: 'independent', kind: 'research', objective: 'Independent question', ownerId: 'other' }, - ...problem.targets.map((target, index) => ({ id: `original_goal_${index + 1}`, kind: 'goal', objective: 'Original', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' }))] }); - state = solverState(problem, workspace, { runId: 'type-fixture', phase: 'running', cooperation: { canonicalCommit: problem.baseCommit, - tasks: parsed.tasks.map(task => ({ task, status: 'pending', attempts: 0 })) } }); - controller = new AbortController(); emit = vi.fn(); allowed = true; - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, emit, - modelDispatchAllowed: () => allowed }); - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async () => result()); - }); - afterEach(async () => { - controller.abort(); await cooperative.stop(); vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('preflights before assignment, preserves Infinity and grants no proof evidence', async () => { - const check = vi.mocked(TaskTypePreflightCache.prototype.check); - check.mockImplementation(async input => { - expect(state.cooperation!.tasks[0].status).toBe('pending'); expect(input.timeoutMs).toBe(Infinity); - return result(); - }); - const action = await peer(); - expect(action).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - expect(state.cooperation!.tasks[0]).toMatchObject({ status: 'running', attempts: 0, - typePreflight: { status: 'elaborated', proofAcceptance: 'not-assessed' } }); - expect(state.cooperation!.tasks[0].proof).toBeUndefined(); - }); - - it('quotes the parser stop in the Lead feedback and names whose worktree holds the diagnostics', async () => { - const task = state.cooperation!.tasks[0].task; - task.type = '∃ λ : Nat, λ = λ'; - vi.mocked(TaskTypePreflightCache.prototype.check).mockResolvedValue({ current: () => true, result: { status: 'invalid', - inputDigest: 'fixed-input', reason: "TypeDiagnostic.lean:9:1: error: :1:2: expected '(', '_' or identifier", - taskDigest: taskVersion(task), artifact: { path: '.lake/type-diagnostics/x/manifest.json', digest: 'd'.repeat(64) }, - evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' } }); - expect(typeof await peer()).toBe('symbol'); - const feedback = state.cooperation!.tasks[0].feedback!; - expect(feedback).toContain('∃ ⟦λ⟧ : Nat, λ = λ'); - expect(feedback).toContain('`λ` is a reserved Lean token, not an identifier'); - expect(feedback).toContain("Advisory type diagnostics in proof's worktree: .lake/type-diagnostics/x/manifest.json"); - }); - - it('blocks an exact invalid interface without charging a model attempt and gives Lead precise feedback', async () => { - vi.mocked(TaskTypePreflightCache.prototype.check).mockResolvedValue(result('invalid')); - expect(typeof await peer()).toBe('symbol'); - const node = state.cooperation!.tasks[0]; - expect(node).toMatchObject({ status: 'blocked', attempts: 0, feedback: expect.stringContaining('exact closed query error') }); - expect(node.assignment).toBeUndefined(); expect(state.lastFailure).toBeUndefined(); - expect((cooperative as any).refreshInvalidTaskTypes()).toBe(false); - expect(vi.mocked(TaskTypePreflightCache.prototype.check)).toHaveBeenCalledOnce(); - }); - - it('blocks a restored declaration-header contract before assigning a prover even when its source scope cannot be restored', async () => { - const node = state.cooperation!.tasks[0]; - node.task = { ...node.task, type: 'theorem Tutorial.helper (n : Nat) : n = n' }; - const file = path.join(workers[1].worktree, state.problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('namespace Tutorial', 'namespace Tutorial\nvariable (P : Prop)')); - vi.mocked(TaskTypePreflightCache.prototype.check).mockImplementation(function(input) { return actualPreflight.call(this, input); }); - expect(typeof await peer()).toBe('symbol'); - expect(node).toMatchObject({ status: 'blocked', attempts: 0, - feedback: expect.stringContaining('Supply a closed type term') }); - expect(node.assignment).toBeUndefined(); expect(state.lastFailure).toBeUndefined(); - expect(emit.mock.calls.some(([event]) => event === 'task_assigned')).toBe(false); - }); - - it.each(['deferred', 'unavailable'] as const)('allows work to continue with %s and records no mathematical failure', async status => { - vi.mocked(TaskTypePreflightCache.prototype.check).mockResolvedValue(result(status)); - expect(await peer()).toMatchObject({ kind: 'task' }); - expect(state.cooperation!.tasks[0].typePreflight?.status).toBe(status); - expect(state.lastFailure).toBeUndefined(); - }); - - it('records an unavailable advisory without starting Lean when the host has no bound worker environment', async () => { - (cooperative as any).input.access.delete(workers[1].id); - expect(await peer()).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - expect(state.cooperation!.tasks[0]).toMatchObject({ status: 'running', attempts: 0, - typePreflight: { status: 'unavailable', reason: 'worker-environment-unavailable', proofAcceptance: 'not-assessed' } }); - expect(vi.mocked(TaskTypePreflightCache.prototype.check)).not.toHaveBeenCalled(); - }); - - it('keeps independent work assignable while one type query is awaiting Lean', async () => { - const held = holdPreflight(), pending = peer(); - expect(await peer(2)).toMatchObject({ kind: 'task', task: { id: 'independent' } }); - held.finish(); expect(await pending).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - }); - - it.each(['contract', 'canonical', 'source', 'admission', 'turns', 'owner', 'environment-binding'] as const) - ('discards awaited preflight after %s changes', async change => { - let current = true; - const held = holdPreflight(), pending = peer(), node = state.cooperation!.tasks[0]; - if (change === 'contract') node.task = { ...node.task, type: 'False', revision: 1 }; - if (change === 'canonical') state.cooperation!.canonicalCommit = 'b'.repeat(40); - if (change === 'source') current = false; - if (change === 'admission') allowed = false; - if (change === 'turns') { state.turns = 1; budget.maxTurns = 1; } - if (change === 'owner') node.task = { ...node.task, ownerId: 'other' }; - if (change === 'environment-binding') (cooperative as any).input.access.set(workers[1].id, { environment: {}, retrievalRoot: directory }); - held.finish('elaborated', () => current); - expect(typeof await pending).toBe('symbol'); expect(node.status).toBe('pending'); expect(node.assignment).toBeUndefined(); - budget.maxTurns = Infinity; - }); - - it.each(['removed', 'revised', 'dependency-revised', 'canonical'] as const) - ('cancels a pending preflight after its %s input changes and waits for its cleanup', async change => { - const node = state.cooperation!.tasks[0]; - if (change === 'dependency-revised') { - node.task = { ...node.task, dependsOn: ['independent'] }; - state.cooperation!.tasks[1].status = 'completed'; - } - const held = holdPreflight(); - let settled = false; - const pending = peer().then(value => { settled = true; return value; }); - expect(held.signal.aborted).toBe(false); - if (change === 'canonical') { - git(workers[0].worktree, ['-c', 'user.name=TheoremOS', '-c', 'user.email=theoremos@localhost', - 'commit', '--allow-empty', '--no-gpg-sign', '--quiet', '-m', 'Update canonical fixture']); - state.cooperation!.canonicalCommit = git(workers[0].worktree, ['rev-parse', 'HEAD']); - (cooperative as any).changed(); - } else { - const tasks = state.cooperation!.tasks.filter(item => change !== 'removed' || item !== node).map(item => { - if (change === 'revised' && item === node) return { ...item.task, type: 'False', revision: item.task.revision + 1 }; - if (change === 'dependency-revised' && item.task.id === 'independent') - return { ...item.task, objective: 'Revised research input', revision: item.task.revision + 1 }; - return item.task; - }); - await (cooperative as any).acceptPlan(parseCooperationPlan(state.problem, { tasks })); - } - expect(held.signal.aborted).toBe(true); expect(controller.signal.aborted).toBe(false); - await new Promise(resolve => setImmediate(resolve)); - expect(settled).toBe(false); expect((cooperative as any).preparingTaskTypes.has(node)).toBe(true); - let woke = false; - const waiting = (cooperative as any).waitForDispatch().then(() => { woke = true; }); - await new Promise(resolve => setImmediate(resolve)); expect(woke).toBe(false); - held.finish('invalid'); - expect(typeof await pending).toBe('symbol'); await waiting; - expect(woke).toBe(true); expect((cooperative as any).preparingTaskTypes.size).toBe(0); - expect(node.assignment).toBeUndefined(); expect(node.typePreflight).toBeUndefined(); - expect(node.status).toBe('pending'); expect(state.lastFailure).toBeUndefined(); - expect(emit.mock.calls.some(([event]) => ['task_type_preflight', 'task_assigned'].includes(event))).toBe(false); - }); - - it('preserves an unchanged preflight across unrelated plan, notes and activity changes', async () => { - const held = holdPreflight(), pending = peer(); - const tasks = state.cooperation!.tasks.map(item => item.task.id === 'independent' - ? { ...item.task, objective: 'Another independent question', revision: item.task.revision + 1 } : item.task); - await (cooperative as any).acceptPlan(parseCooperationPlan(state.problem, { tasks })); - fs.writeFileSync(path.join(workers[0].worktree, 'RESEARCH.md'), 'Independent notes\n'); - (cooperative as any).changed(); cooperative.modelBudgetChanged(); - expect(await peer(2)).toMatchObject({ kind: 'task', task: { id: 'independent' } }); - expect(held.signal.aborted).toBe(false); - expect(vi.mocked(TaskTypePreflightCache.prototype.check)).toHaveBeenCalledOnce(); - held.finish(); expect(await pending).toMatchObject({ kind: 'task', task: { id: 'helper' } }); - }); - - it.each(['admission', 'turns', 'environment', 'environment-binding', 'owner', 'worker-stopped'] as const) - ('cancels obsolete host work on a %s notification without publishing an invalid type', async change => { - const held = holdPreflight(), pending = peer(), node = state.cooperation!.tasks[0]; - if (change === 'admission') allowed = false; - if (change === 'turns') { state.turns = 1; budget.maxTurns = 1; } - if (change === 'environment') state.environmentDigest = 'updated-environment'; - if (change === 'environment-binding') (cooperative as any).input.access.set(workers[1].id, { environment: {}, retrievalRoot: directory }); - if (change === 'owner') node.task = { ...node.task, ownerId: 'other' }; - if (change === 'worker-stopped') cooperative.stopped(workers[1]); - else cooperative.modelBudgetChanged(); - expect(held.signal.aborted).toBe(true); expect(controller.signal.aborted).toBe(false); - held.finish('invalid'); expect(typeof await pending).toBe('symbol'); - expect(node).toMatchObject({ status: 'pending', attempts: 0 }); - expect(node.assignment).toBeUndefined(); expect(node.typePreflight).toBeUndefined(); - expect(state.lastFailure).toBeUndefined(); - budget.maxTurns = Infinity; - }); - - it('passes run cancellation to Lean and retains the preparation until its cleanup completes', async () => { - const held = holdPreflight(); - let settled = false; - const pending = peer().then(value => { settled = true; return value; }); - controller.abort(); - expect(held.signal.aborted).toBe(true); - await new Promise(resolve => setImmediate(resolve)); expect(settled).toBe(false); - expect((cooperative as any).preparingTaskTypes.size).toBe(1); - held.finish('invalid'); expect(typeof await pending).toBe('symbol'); - expect((cooperative as any).preparingTaskTypes.size).toBe(0); - expect(state.cooperation!.tasks[0].assignment).toBeUndefined(); - expect(state.cooperation!.tasks[0].typePreflight).toBeUndefined(); - expect(state.lastFailure).toBeUndefined(); - }); - - it('drains a cancelled preflight before stop returns', async () => { - const held = holdPreflight(), pending = peer(); - let stopped = false; - const stopping = cooperative.stop().then(() => { stopped = true; }); - expect(held.signal.aborted).toBe(true); - await new Promise(resolve => setImmediate(resolve)); expect(stopped).toBe(false); - expect((cooperative as any).preparingTaskTypes.size).toBe(1); - held.finish('invalid'); expect(typeof await pending).toBe('symbol'); await stopping; - expect(stopped).toBe(true); expect((cooperative as any).preparingTaskTypes.size).toBe(0); - expect(state.cooperation!.tasks[0].assignment).toBeUndefined(); - expect(state.cooperation!.tasks[0].typePreflight).toBeUndefined(); - expect(state.lastFailure).toBeUndefined(); - }); - - it('does not reopen invalid A when its worker edits independent B, but does reopen on a canonical change', async () => { - vi.mocked(TaskTypePreflightCache.prototype.check).mockResolvedValue(result('invalid')); - await peer(); - fs.appendFileSync(path.join(workers[1].worktree, state.problem.projectRelative, 'Submission.lean'), '\n-- independent B work\n'); - expect((cooperative as any).refreshInvalidTaskTypes()).toBe(false); - expect(state.cooperation!.tasks[0].status).toBe('blocked'); - state.cooperation!.canonicalCommit = 'b'.repeat(40); - expect((cooperative as any).refreshInvalidTaskTypes()).toBe(true); - expect(state.cooperation!.tasks[0].status).toBe('pending'); - }); - - it('waits for host type work without reporting an idle or finished frontier', async () => { - const held = holdPreflight(); - state.cooperation!.tasks[1].task = { ...state.cooperation!.tasks[1].task, status: 'paused' }; - const pending = peer(); - dropLeadWakes(state.cooperation!.leadWakes!); - let settled = false; - const lead = (cooperative as any).nextLead(workers[0], budget, true).then(() => { settled = true; }); - await new Promise(resolve => setTimeout(resolve, 15)); - expect(settled).toBe(false); expect(emit.mock.calls.some(([event]) => event === 'routes_idle')).toBe(false); - held.finish(); await pending; await lead; - }); -}); diff --git a/tests/solverUsageReceipts.test.ts b/tests/solverUsageReceipts.test.ts index a88d240c..3c18d2cd 100644 --- a/tests/solverUsageReceipts.test.ts +++ b/tests/solverUsageReceipts.test.ts @@ -11,7 +11,6 @@ import { SUB2API_PROVIDER } from '../src/runtime/sub2api'; import type { MathAgentSession } from '../src/runtime/codexSession'; import { createCodexMathSession } from '../src/runtime/codexSession'; import type { ModelRequestReceipt, ModelRequestIdentity } from '../src/runtime/modelRequest'; -import type { CooperativeAction } from '../src/solver/tasks'; import { localExample, solverState } from './helpers/solver'; import { temporaryDirectory } from './helpers/files'; @@ -27,13 +26,17 @@ describe('persistent provider request receipts', () => { it('deduplicates normal receipts across serialization and preserves subset tokens', () => { const first = record(); const settle = beginRequestUsage(first, { requestId: 'request-1', runId: 'run', sessionId: 'session', taskId: 'task' }); - settle({ usage, complete: true, outcome: 'completed' }); settle({ usage, complete: true }); + const duplicate = beginRequestUsage(first, { requestId: 'request-1', taskId: 'another-task' }); + expect(first.requestUsageAccounting).toMatchObject({ startedRequests: 1, pendingRequests: 1 }); + settle({ usage, complete: true, outcome: 'completed' }); duplicate({ usage, complete: true }); const resumed: Record = JSON.parse(JSON.stringify(first)); initializeUsageAccounting(resumed); beginRequestUsage(resumed, { requestId: 'request-1' })({ usage, complete: true }); expect(resumed.usage).toEqual(usage); expect(resumed.requestUsageAccounting).toMatchObject({ startedRequests: 1, reportedRequests: 1, pendingRequests: 0, incomplete: false }); - expect(resumed.requestUsageAccounting!.receipts).toHaveLength(1); + expect(resumed.requestUsageAccounting!.receipts).toMatchObject([ + { requestId: 'request-1', taskId: 'task', status: 'reported' }, + ]); expect(buildTokenBudget(100, [resumed])).toMatchObject({ reportedTotalTokens: 13, usageComplete: true, status: 'available' }); }); @@ -109,13 +112,12 @@ describe('persistent provider request receipts', () => { function researchFixture(source: MathAgentSession['usageSource']) { const state = { runId: 'run', turns: 0 } as SolverRunState; initializeUsageAccounting(state); state.tokenBudget = buildTokenBudget(0, [state]); - const emit = vi.fn(), research = new ResearchUsage({ state, research: state, maxTotalTokens: 0, + const emit = vi.fn(), research = new ResearchUsage({ state, research: state, signal: new AbortController().signal, remainingMs: () => 1000, changed: vi.fn(), emit }); const callbacks = research.bindSession('session', () => 10); research.sessionOpened({ usageSource: source } as MathAgentSession); return { state, research, callbacks, emit }; } -const assignment = (id: string) => ({ kind: 'task', task: { id } }) as CooperativeAction; describe('usage attribution at task boundaries', () => { it('ignores cumulative replays before the next turn and flags new unscoped tokens', () => { @@ -132,7 +134,7 @@ describe('usage attribution at task boundaries', () => { expect.objectContaining({ reason: 'native-turn-identity-unavailable', reportedTotalTokens: 21 })); expect(state.usage).toEqual({ totalTokens: 51 }); - research.begin(assignment('next')); + research.begin('next'); callbacks.onUsage!({ totalTokens: 21 }, { turnId: 'next-turn' }); expect(emit).toHaveBeenCalledTimes(1); callbacks.onUsage!({ totalTokens: 21 }, { turnId: 'unrecognized-turn' }); @@ -140,9 +142,9 @@ describe('usage attribution at task boundaries', () => { }); it('settles a late request into its original task without charging the next turn', () => { const { state, research, callbacks } = researchFixture('upstream-requests'); - research.begin(assignment('first')); + research.begin('first'); const first = callbacks.requestGate!({ requestId: 'first-request' }); - research.finish(false); research.begin(assignment('second')); + research.finish(false); research.begin('second'); if (!first.allowed) throw new Error('request rejected'); first.settle({ complete: true, usage }); first.settle({ complete: true, usage }); const second = callbacks.requestGate!({ requestId: 'second-request' }); @@ -154,9 +156,9 @@ describe('usage attribution at task boundaries', () => { it('uses native turn identity for delayed totals and leaves ambiguous cross-task deltas unassigned', () => { const { state, research, callbacks, emit } = researchFixture('native-thread-totals'); - research.begin(assignment('first')); research.turnStarted('turn-1'); + research.begin('first'); research.turnStarted('turn-1'); callbacks.onUsage!({ totalTokens: 10 }, { turnId: 'turn-1' }); research.finish(true); - research.begin(assignment('second')); research.turnStarted('turn-2'); + research.begin('second'); research.turnStarted('turn-2'); callbacks.onUsage!({ totalTokens: 12 }, { turnId: 'turn-1' }); expect(state.taskUsage).toEqual({ first: { totalTokens: 12 } }); callbacks.onUsage!({ totalTokens: 20 }, { turnId: 'turn-2' }); diff --git a/tests/solverWorkerCheckpointFeedback.test.ts b/tests/solverWorkerCheckpointFeedback.test.ts deleted file mode 100644 index 9990acfc..00000000 --- a/tests/solverWorkerCheckpointFeedback.test.ts +++ /dev/null @@ -1,265 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import type { SolverProblem } from '../src/solver/problem'; -import { assignmentDeliveryFile, parseCooperationPlan, type CooperativeAction } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -type Task = Extract; -type Notice = ReturnType Promise>>; - -describe('task worker checkpoint correction feedback', () => { - const budget = { maxTurns: Infinity, remainingMs: Infinity }; - let directory: string, problem: SolverProblem, state: SolverRunState, workers: ResearchWorker[]; - let cooperative: CooperativeResearch, controller: AbortController; - let notices: Map, releases: (() => void)[]; - let events: { event: string; details?: Record }[]; - const savedFile = () => path.join(directory, 'state.json'); - const research = (worker: ResearchWorker) => state.workers!.find(record => record.id === worker.id)!; - const node = (action: Task) => state.cooperation!.tasks.find(record => record.task.id === action.task.id)!; - const log = (action: Task) => assignmentDeliveryFile(action.assignment); - const key = (worker: ResearchWorker, action: Task) => `${worker.id}/${log(action)}`; - const json = (worker: ResearchWorker) => JSON.parse(fs.readFileSync(path.join(worker.worktree, 'COOPERATION.json'), 'utf8')); - const notice = (worker: ResearchWorker) => notices.get(worker.id)!; - const request = (worker: ResearchWorker) => { - const record = research(worker); - record.threadId = `${worker.id}-thread`; - record.contextCheckpoint = { threadId: record.threadId, requestId: `${worker.id}-request`, requestedAt: 1 }; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), - `The exact ${worker.id} argument and missing construction remain saved before handing back writing.\n`); - return record.contextCheckpoint; - }; - const checkpoint = (worker: ResearchWorker, correct = false) => ({ kind: 'checkpoint', - requestId: research(worker).contextCheckpoint!.requestId, - notesDigest: correct ? mathDigest(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'))) : '0'.repeat(64) }); - const append = (worker: ResearchWorker, action: Task, value: unknown) => fs.appendFileSync( - path.join(worker.worktree, log(action)), JSON.stringify(value) + '\n'); - const publish = async (worker: ResearchWorker, action: Task, value = checkpoint(worker)) => { - append(worker, action, value); await cooperative.pulse(worker.id); - }; - const start = async (worker: ResearchWorker) => { - const action = await cooperative.next(worker, budget); - if (action?.kind !== 'task' || action.task.kind !== 'research') throw new Error('fixture_expected_research_assignment'); - expect(cooperative.started(worker, action)).toBe(true); - cooperative.activate(worker, action, async () => {}, notice(worker)); - return action; - }; - const context = (worker: ResearchWorker, action: Task) => directSolverModules.M4.build(problem, - { ...state, cooperation: cooperative.contextState(action, worker) }, - { root: directory, worktree: worker.worktree, retrievalRoot: directory, environment: {}, - taskText: 'Resolve the exact assigned mathematical question.', assignment: action, maxOptionalContextBytes: 0 }); - const expectCorrection = (message: string, worker: ResearchWorker, action: Task, notification = true) => { - for (const detail of [research(worker).contextCheckpoint!.requestId!, log(action), '--request-id', '--log']) - expect(message).toContain(detail); - expect(message).toContain('rerun checkpoint'); - if (notification) { - expect(message).not.toContain('replacesReceipt'); - expect(message).not.toContain('dispatchNonce'); - } - }; - - beforeEach(() => { - const example = localExample('solver-worker-checkpoint-feedback-', 'lead'); - ({ directory, problem } = example); - workers = [leadWorker(problem, example.workspace), peerWorker(example, 'researcher-a'), peerWorker(example, 'researcher-b')]; - const plan = parseCooperationPlan(problem, { tasks: [ - ...workers.slice(1).map(worker => ({ id: `${worker.id}-question`, kind: 'research', ownerId: worker.id, - objective: `Identify the exact ${worker.id} construction.`, dependsOn: [] })), - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: `Prove ${target.theoremName}.`, ...target, status: 'paused' })), - ] }); - state = solverState(problem, example.workspace, { runId: 'worker-checkpoint-feedback-fixture', phase: 'running', - workers: workers.map(worker => ({ id: worker.id, role: worker.role, worktree: worker.worktree, phase: 'checking', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - events = []; releases = []; notices = new Map(workers.map(worker => [worker.id, vi.fn(async (_message: string) => {})])); - controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, - save: () => writeSolverRunState(savedFile(), state), emit: (event, details) => events.push({ event, details }) }); - }); - afterEach(async () => { - controller.abort(); releases.forEach(release => release()); - await cooperative.stop(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('repairs a bad worker ACK through its notice without creating mathematical correction or replacing task feedback', async () => { - const worker = workers[1], action = await start(worker), checkpointRequest = request(worker); - const mathematicalFeedback = 'Use the exact saved coercion gap before another library search.'; - node(action).feedback = mathematicalFeedback; - cooperative.activate(worker, action, async () => {}, notice(worker)); - const before = structuredClone({ task: node(action).task, status: node(action).status, - assignment: node(action).assignment, planVersion: state.cooperation!.planVersion }); - let notifiedState: SolverRunState | undefined; - notice(worker).mockImplementation(async message => { - expectCorrection(message, worker, action); - notifiedState = readSolverRunState(savedFile()); - const saved = notifiedState.workers!.find(record => record.id === worker.id)!.contextCheckpoint!.rejection!; - expect(saved).toMatchObject({ file: log(action), reason: 'math_delivery_invalid' }); - expect(notifiedState.cooperation!.cursors![key(worker, action)]).toBe(saved.offset); - append(worker, action, checkpoint(worker, true)); - }); - await publish(worker, action); - expect(checkpointRequest.rejection).toMatchObject({ file: log(action), reason: 'math_delivery_invalid' }); - expect(notice(worker)).toHaveBeenCalledOnce(); - expect(notifiedState).toBeDefined(); - expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); - expect(node(action).feedback).toBe(mathematicalFeedback); - const rejection = cooperative.contextState(action, worker).contextCheckpointRejection; - expect(rejection).toMatchObject({ threadId: checkpointRequest.threadId, requestId: checkpointRequest.requestId }); - expect(json(worker).contextCheckpointRejection).toEqual(rejection); - for (const other of [workers[0], workers[2]]) { - expect(cooperative.contextState(undefined, other).contextCheckpointRejection).toBeUndefined(); - expect(json(other).contextCheckpointRejection).toBeUndefined(); - expect(notice(other)).not.toHaveBeenCalled(); - } - const compiled = context(worker, action); - expect(compiled.manifest!.included).toContainEqual(expect.objectContaining({ id: 'context-checkpoint-rejection', required: true })); - expect(compiled.manifest).toMatchObject({ maxOptionalBytes: 0, optionalBytes: 0 }); - for (const message of [compiled.message, compiled.continuationMessage!]) { - expectCorrection(message, worker, action, false); - expect(message).toContain(mathematicalFeedback); - } - await cooperative.pulse(worker.id); - expect(checkpointRequest.publishedNotesDigest).toBe(checkpoint(worker, true).notesDigest); - expect(checkpointRequest.rejection).toBeUndefined(); - expect(json(worker).contextCheckpointRejection).toBeUndefined(); - expect(node(action).feedback).toBe(mathematicalFeedback); - expect({ task: node(action).task, status: node(action).status, - assignment: node(action).assignment, planVersion: state.cooperation!.planVersion }).toEqual(before); - expect(state.check).toBeUndefined(); - expect(state.cooperation!.deliveries ?? []).toEqual([]); - expect(state.cooperation!.tasks.every(record => !record.proof && !record.integratedCheck)).toBe(true); - }); - - it('clears a repaired ACK while preserving an independent rejected research finding and its correction receipt', async () => { - const worker = workers[1], action = await start(worker), checkpointRequest = request(worker); - append(worker, action, { kind: 'research', finding: { summary: 42 } }); - await cooperative.pulse(worker.id); - expect(state.cooperation!.deliveryReceipts).toHaveLength(1); - const receipt = structuredClone(state.cooperation!.deliveryReceipts![0]), mathematicalFeedback = node(action).feedback; - expect(receipt).toMatchObject({ status: 'needs-correction', code: 'math_research_delivery_invalid' }); - expect(notice(worker)).toHaveBeenCalledOnce(); - notice(worker).mockClear(); - await publish(worker, action); - expect(checkpointRequest.rejection).toBeDefined(); - expect(state.cooperation!.deliveryReceipts).toEqual([receipt]); - expect(node(action).feedback).toBe(mathematicalFeedback); - expect(notice(worker)).toHaveBeenCalledOnce(); - expectCorrection(notice(worker).mock.calls[0][0], worker, action); - await publish(worker, action, checkpoint(worker, true)); - expect(checkpointRequest.rejection).toBeUndefined(); - expect(checkpointRequest.publishedNotesDigest).toBe(checkpoint(worker, true).notesDigest); - expect(state.cooperation!.deliveryReceipts).toEqual([receipt]); - expect(node(action).feedback).toBe(mathematicalFeedback); - expect(context(worker, action).continuationMessage).toContain(receipt.id); - }); - - it('accepts a later corrected ACK while its diagnostic notification is still pending', async () => { - const worker = workers[1], action = await start(worker), checkpointRequest = request(worker); - let release!: () => void; - const held = new Promise(resolve => { release = resolve; }); - releases.push(release); - notice(worker).mockImplementation(() => held); - let settled = false; - const first = publish(worker, action).then(() => { settled = true; }); - try { - await vi.waitFor(() => expect(settled).toBe(true), { timeout: 500 }); - expect(notice(worker)).toHaveBeenCalledOnce(); - const saved = readSolverRunState(savedFile()); - expect(saved.workers!.find(record => record.id === worker.id)!.contextCheckpoint!.rejection).toBeDefined(); - await publish(worker, action, checkpoint(worker, true)); - expect(checkpointRequest.publishedNotesDigest).toBe(checkpoint(worker, true).notesDigest); - expect(checkpointRequest.rejection).toBeUndefined(); - expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); - expect(notice(worker)).toHaveBeenCalledOnce(); - } finally { release(); await first; } - }); - - it('retries failures independently for two simultaneous peer requests without replaying their intake or leaking diagnostics', async () => { - const peers = workers.slice(1), actions: Task[] = []; - for (const worker of peers) { - const action = await start(worker); actions.push(action); request(worker); - notice(worker).mockRejectedValueOnce(new Error('transport unavailable')); - append(worker, action, checkpoint(worker)); - } - await cooperative.pulse(); - expect(events.filter(item => item.event === 'delivery_rejected')).toHaveLength(2); - for (const [index, worker] of peers.entries()) { - expect(research(worker).contextCheckpoint!.rejection).toMatchObject({ file: log(actions[index]) }); - expect(notice(worker)).toHaveBeenCalledOnce(); - } - await cooperative.pulse(); - await cooperative.pulse(); - for (const [index, worker] of peers.entries()) { - expect(notice(worker)).toHaveBeenCalledTimes(2); - expectCorrection(notice(worker).mock.calls[1][0], worker, actions[index]); - const other = peers[1 - index]; - expect(notice(worker).mock.calls[1][0]).not.toContain(research(other).contextCheckpoint!.requestId!); - expect(json(worker).contextCheckpointRejection.requestId).toBe(research(worker).contextCheckpoint!.requestId); - expect(state.cooperation!.cursors![key(worker, actions[index])]).toBe(fs.statSync(path.join(worker.worktree, log(actions[index]))).size); - } - expect(json(workers[0]).contextCheckpointRejection).toBeUndefined(); - expect(notice(workers[0])).not.toHaveBeenCalled(); - expect(events.filter(item => item.event === 'delivery_rejected')).toHaveLength(2); - expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); - }); - - it('drops old request and thread diagnostics and does not notify an inactive assignment', async () => { - const worker = workers[1], action = await start(worker), record = research(worker); - request(worker); - for (const change of ['request', 'thread', 'inactive'] as const) { - if (change === 'inactive') record.contextCheckpoint = { threadId: record.threadId!, requestId: 'active-again-request', requestedAt: 3 }; - notice(worker).mockRejectedValueOnce(new Error('transport unavailable')); - await publish(worker, action); - expect(record.contextCheckpoint!.rejection).toBeDefined(); - notice(worker).mockClear(); - if (change === 'request') record.contextCheckpoint = { threadId: record.threadId!, requestId: 'replacement-request', requestedAt: 2 }; - else if (change === 'thread') record.threadId = 'replacement-thread'; - else cooperative.deactivate(worker); - if (change !== 'inactive') cooperative.activate(worker, action, async () => {}, notice(worker)); - await cooperative.pulse(worker.id); - expect(notice(worker)).not.toHaveBeenCalled(); - if (change !== 'inactive') { - expect(cooperative.contextState(action, worker).contextCheckpointRejection).toBeUndefined(); - expect(json(worker).contextCheckpointRejection).toBeUndefined(); - const compiled = context(worker, action); - expect(compiled.manifest!.included).not.toContainEqual(expect.objectContaining({ id: 'context-checkpoint-rejection' })); - expect(compiled.continuationMessage).not.toContain('math_delivery_invalid'); - } - } - expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); - }); - - it('retargets unresolved checkpoint feedback to a new active assignment without retrying its old callback', async () => { - const worker = workers[1], oldAction = await start(worker), checkpointRequest = request(worker); - const oldNotice = notice(worker); - oldNotice.mockRejectedValueOnce(new Error('transport unavailable')); - await publish(worker, oldAction); - expect(checkpointRequest.rejection).toMatchObject({ file: log(oldAction) }); - expect(oldNotice).toHaveBeenCalledOnce(); - cooperative.deactivate(worker); cooperative.interrupted(worker, oldAction); - node(oldAction).assignment = undefined; - const currentNotice = vi.fn(async (_message: string) => {}); - notices.set(worker.id, currentNotice); - const currentAction = await start(worker); - expect(log(currentAction)).not.toBe(log(oldAction)); - await cooperative.pulse(worker.id); - expect(oldNotice).toHaveBeenCalledOnce(); - expect(currentNotice).toHaveBeenCalledOnce(); - expectCorrection(currentNotice.mock.calls[0][0], worker, currentAction); - for (const message of [context(worker, currentAction).message, context(worker, currentAction).continuationMessage!]) - expect(message).toContain('--log ' + log(currentAction)); - await publish(worker, currentAction, checkpoint(worker, true)); - expect(checkpointRequest.rejection).toBeUndefined(); - expect(checkpointRequest.publishedNotesDigest).toBe(checkpoint(worker, true).notesDigest); - expect(state.cooperation!.deliveryReceipts ?? []).toEqual([]); - }); -}); diff --git a/tests/solverWorkerExitDispatch.test.ts b/tests/solverWorkerExitDispatch.test.ts deleted file mode 100644 index b6bd3a0c..00000000 --- a/tests/solverWorkerExitDispatch.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { setTimeout as delay } from 'node:timers/promises'; -import { expect, it } from 'vitest'; -import { directSolverModules } from '../src/solver/modules'; -import { commitSolverSources } from '../src/solver/problem'; -import { parseCooperationPlan } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const budget = { maxTurns: Infinity, remainingMs: Infinity }; - -function fixture(emitHook?: (event: string, details?: Record) => void, addOtherWork = false) { - const example = localExample('worker-exit-replay-', 'lead'); - const { directory, workspace, problem } = example; - const workers = [leadWorker(problem, workspace), peerWorker(example, 'owner'), peerWorker(example, 'idle')]; - const [, owner, idle] = workers; - const plan = parseCooperationPlan(problem, { tasks: [ - ...(addOtherWork ? [{ id: 'other', kind: 'research', objective: 'Run an independent enumeration.', ownerId: idle.id }] : []), - { id: 'reserved', kind: 'research', objective: 'Investigate a local obstruction.', ownerId: owner.id }, - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', - objective: 'Original target.', theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' })), - ] }); - const state = solverState(problem, workspace, { runId: 'worker-exit-replay', phase: 'running', - workers: workers.map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: problem.baseCommit, tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - const events: Array<{ event: string; details?: Record }> = []; - const emit = (event: string, details?: Record) => { events.push({ event, details }); emitHook?.(event, details); }; - const controller = new AbortController(); - const forbidden = () => { throw new Error('fixture_model_and_verifier_forbidden'); }; - const newRuntime = (saved = state) => cooperativeResearch({ state: saved, workers, retrievalRoot: directory, - emit, signal: controller.signal, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: forbidden }, - M2: { ...directSolverModules.M2, check: forbidden, checkTask: forbidden } } }); - const runtime = newRuntime(); - return { ...example, owner, idle, state, runtime, events, controller, newRuntime, - reserved: state.cooperation!.tasks.find(node => node.task.id === 'reserved')! }; -} - -it.each(['registered', 'racing'] as const)('dispatches a stopped owner’s task with %s waiter timing', async timing => { - let f: ReturnType; - f = fixture((event, details) => { - if (timing === 'racing' && event === 'dispatch_wait' && details?.workerId === 'idle') - queueMicrotask(() => f.runtime.stopped(f.owner, 'fixture_worker_failed')); - }); - let waiting: ReturnType | undefined; - try { - const original = await f.runtime.next(f.owner, budget); - if (original?.kind !== 'task') throw new Error('owner task missing'); - expect(f.runtime.started(f.owner, original)).toBe(true); - f.runtime.start(); - waiting = f.runtime.next(f.idle, budget); - const observed = waiting.then(action => ({ task: action?.kind === 'task' && action.task.id })); - if (timing === 'registered') { - await new Promise(resolve => setImmediate(resolve)); - f.runtime.stopped(f.owner, 'fixture_worker_failed'); - } - expect(await Promise.race([observed, delay(1000, 'waiting')])).toEqual({ task: 'reserved' }); - expect(f.events.filter(item => item.event === 'task_assignment_released')).toEqual([{ - event: 'task_assignment_released', details: { taskId: 'reserved', workerId: f.owner.id, takenBy: f.idle.id, reason: 'worker-stopped' }, - }]); - } finally { - f.controller.abort(); - await Promise.allSettled([waiting]); - await f.runtime.stop(); - fs.rmSync(f.directory, { recursive: true, force: true }); - } -}); - -it('preserves a stopped worker’s draft when the live peer takes a different task', async () => { - const f = fixture(undefined, true); - let resumed: ReturnType | undefined; - try { - const action = await f.runtime.next(f.owner, budget); - if (action?.kind !== 'task') throw new Error('owner task missing'); - expect(action.task.id).toBe('reserved'); - expect(f.runtime.started(f.owner, action)).toBe(true); - const marker = 'A checked bound for the original task.'; - const proofFile = path.join(f.owner.worktree, f.problem.projectRelative, 'Submission.lean'); - fs.appendFileSync(proofFile, '\n-- ' + marker + '\n'); - fs.writeFileSync(path.join(f.owner.worktree, 'RESEARCH.md'), marker + '\n'); - const commit = commitSolverSources(f.problem, f.owner.worktree); - f.runtime.retainContextDraft(f.owner, action, commit); - f.runtime.stopped(f.owner, 'fixture_worker_failed'); - expect(f.reserved.assignment?.assignmentId).toBe(action.assignment.assignmentId); - expect(f.state.cooperation!.researchDrafts!.reserved.commit).toBe(commit); - const candidate = await f.runtime.next(f.idle, budget); - expect(candidate).toMatchObject({ kind: 'task', task: { id: 'other' } }); - expect(f.reserved).toMatchObject({ status: 'pending' }); - expect(f.reserved.assignment?.assignmentId).toBe(action.assignment.assignmentId); - expect(f.events.some(item => item.event === 'task_assignment_released')).toBe(false); - const previous = JSON.parse(JSON.stringify(f.state)) as typeof f.state; - resumed = f.newRuntime(previous); - await resumed.restore(); - const afterRestart = await resumed.next(f.owner, budget); - expect(afterRestart).toMatchObject({ kind: 'task', task: { id: 'reserved' } }); - if (afterRestart?.kind !== 'task') throw new Error('restart task missing'); - expect(afterRestart.assignment.assignmentId).toBe(action.assignment.assignmentId); - expect(fs.readFileSync(proofFile, 'utf8')).toContain(marker); - expect(previous.cooperation!.researchDrafts!.reserved.commit).toBe(commit); - } finally { - f.controller.abort(); - await resumed?.stop(); - await f.runtime.stop(); - fs.rmSync(f.directory, { recursive: true, force: true }); - } -}); diff --git a/tests/statementSnapshotBatch.test.ts b/tests/statementSnapshotBatch.test.ts deleted file mode 100644 index f6a0597e..00000000 --- a/tests/statementSnapshotBatch.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { LOCAL_EXAMPLE_STATEMENT } from '../src/math/localExample'; -import type { LeanStatementContext } from '../src/math/leanStatementContext'; -import type { SolverRunState } from '../src/solver/archive'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { createStatementSnapshotter, statementSnapshot } from '../src/solver/statementReview'; -import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, solverState } from './helpers/solver'; - -const host = vi.hoisted(() => ({ reads: vi.fn(), inspections: vi.fn(), masks: vi.fn(), capture: vi.fn(), sessions: vi.fn() })); -vi.mock('../src/solver/problem', async importOriginal => { - const original = await importOriginal(); - return { ...original, committedSource: (...args: Parameters) => { - host.reads(...args); return original.committedSource(...args); - } }; -}); -vi.mock('../src/math/leanSource', async importOriginal => { - const original = await importOriginal(); - return { ...original, inspectLeanDeclarationRegions: (...args: Parameters) => { - host.inspections(...args); return original.inspectLeanDeclarationRegions(...args); - } }; -}); -vi.mock('../src/math/leanSyntax', async importOriginal => { - const original = await importOriginal(); - return { ...original, maskLeanComments: (source: string) => { host.masks(source); return original.maskLeanComments(source); } }; -}); -vi.mock('../src/solver/statementReview', async importOriginal => ({ - ...await importOriginal(), captureStatementContexts: host.capture, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.sessions })); - -describe('statement snapshot preparation within a single call', () => { - let directory: string, workspace: string, commit: string, problem: SolverProblem, tasks: CooperativeTask[]; - let cooperative: CooperativeResearch, controller: AbortController, state: SolverRunState, sources: string[]; - const environmentDigest = 'statement-batch-environment'; - const dependencies = (task: CooperativeTask) => tasks.filter(item => task.dependsOn.includes(item.id)) - .map(item => ({ task: item, taskDigest: taskVersion(item) })); - const snapshot = (task: CooperativeTask, context?: LeanStatementContext) => - statementSnapshot(problem, task, workspace, commit, environmentDigest, dependencies(task), context); - const context = (task: CooperativeTask): LeanStatementContext => ({ - type: task.type ?? '∀ (n : Nat), n + 0 = n', constants: [], omitted: [], - }); - const clearCounts = () => { host.reads.mockClear(); host.inspections.mockClear(); host.masks.mockClear(); }; - const expectSinglePreparation = () => { - expect(host.reads).toHaveBeenCalledTimes(2); - expect(host.inspections).toHaveBeenCalledTimes(2); - expect(host.masks.mock.calls.filter(([source]) => sources.includes(source))).toHaveLength(2); - }; - - beforeEach(() => { - host.capture.mockReset().mockImplementation(async (_problem: SolverProblem, requested: CooperativeTask[]) => - new Map(requested.map(task => [task.id, context(task)]))); - host.sessions.mockReset().mockImplementation(() => { throw new Error('fixture_real_models_forbidden'); }); - ({ directory, workspace, problem } = localExample('statement-snapshot-batch-')); - const source = LOCAL_EXAMPLE_STATEMENT.replace('theorem add_zero', - 'def kept : String := "visible definition"\nlemma helper : True := by trivial /- COMMENT_SECRET PROOF_SECRET -/\ntheorem add_zero'); - fs.writeFileSync(path.join(workspace, problem.projectRelative, 'Submission.lean'), source); - commit = commitSolverSources(problem, workspace); - sources = [LOCAL_EXAMPLE_STATEMENT, source]; - tasks = [ - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal' as const, - theoremName: target.theoremName, proofPath: target.proofPath, dependsOn: [], revision: 0 })), - { id: 'helper', kind: 'lemma', theoremName: 'Tutorial.helper', proofPath: 'Submission.lean', type: 'True', - dependsOn: ['goal_0'], revision: 0 }, - ].map(task => ({ ...task, objective: 'INTENT_SECRET', informalStatement: 'INTENT_SECRET', statementReview: true })); - state = solverState(problem, workspace, { runId: 'statement-batch-fixture', phase: 'running', environmentDigest, - cooperation: { canonicalCommit: commit, tasks: tasks.map(task => ({ task, status: 'pending', attempts: 0 })) } }); - controller = new AbortController(); - cooperative = cooperativeResearch({ state, workers: [leadWorker(problem, workspace, 'lead')], retrievalRoot: directory, - signal: controller.signal, exclusiveCheck: operation => operation() }); - clearCounts(); - }); - afterEach(async () => { - controller?.abort(); await cooperative?.stop(); expect(host.sessions).not.toHaveBeenCalled(); - vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); - }); - - it('reads and inspects two sources once while preparing three cached statement keys', () => { - for (const task of tasks) (cooperative as any).statementContexts.set(snapshot(task).snapshotDigest, context(task)); - clearCounts(); - expect((cooperative as any).prepareStatementContexts()).toBeUndefined(); - expectSinglePreparation(); - expect(host.capture).not.toHaveBeenCalled(); - }); - - it('shares two source preparations across both synchronization passes without changing snapshots', () => { - const expected = tasks.map(task => snapshot(task, context(task))); - for (const task of tasks) (cooperative as any).statementContexts.set(snapshot(task).snapshotDigest, context(task)); - clearCounts(); - (cooperative as any).syncStatementReviews(); - expectSinglePreparation(); - expect(state.cooperation!.statementReviews).toHaveLength(3); - for (const [index, review] of state.cooperation!.statementReviews!.entries()) { - const actual = expected[index]!; - expect(review.snapshotDigest).toBe(actual.snapshotDigest); - expect(JSON.parse(fs.readFileSync(path.join(review.workspace, 'STATEMENT.json'), 'utf8'))) - .toEqual(JSON.parse(JSON.stringify({ ...actual.input, snapshotDigest: actual.snapshotDigest }))); - for (const [fileIndex, definition] of actual.definitions.entries()) - expect(fs.readFileSync(path.join(review.workspace, `definitions/${fileIndex}.lean`), 'utf8')).toBe(definition.source); - } - expect(host.capture).not.toHaveBeenCalled(); - }); - - it('keeps each blind goal and helper snapshot complete and independent', () => { - const expected = tasks.map(task => snapshot(task, context(task))); - const build = createStatementSnapshotter(problem, workspace, commit, environmentDigest); - clearCounts(); - const actual = tasks.map(task => build(task, dependencies(task), context(task))); - expectSinglePreparation(); - expect(actual).toEqual(expected); - for (const [index, value] of actual.entries()) { - expect(value.input.definitions.map(file => file.originalFile)).toEqual(['Challenge.lean', 'Submission.lean']); - const trusted = value.definitions[0]!.source, owned = value.definitions[1]!.source; - expect(trusted).not.toMatch(/\b(?:theorem|lemma)\b/u); - expect(owned).toContain('def kept : String := "visible definition"'); - if (tasks[index]!.kind === 'goal') { - const name = tasks[index]!.theoremName!.split('.').at(-1)!; - const other = tasks.find(task => task.kind === 'goal' && task.id !== tasks[index]!.id)!.theoremName!.split('.').at(-1)!; - expect(owned).toContain(`theorem ${name}`); - expect(owned).not.toContain(`theorem ${other}`); - expect(value.input.dependencies).toEqual([]); - } else { - expect(owned).not.toMatch(/\b(?:theorem|lemma)\b/u); - expect(value.input.dependencies[0]!.taskDigest).toBe(taskVersion(tasks[0]!)); - } - expect(JSON.stringify(value)).not.toMatch(/COMMENT_SECRET|PROOF_SECRET|INTENT_SECRET|by sorry|by trivial/u); - } - actual[0]!.definitions[0]!.source = 'mutated'; - actual[0]!.input.definitions[0]!.path = 'mutated'; - actual[2]!.input.dependencies[0]!.taskDigest = 'mutated'; - expect(actual[1]).toEqual(expected[1]); - expect(build(tasks[0]!, [], context(tasks[0]!))).toEqual(expected[0]); - expect(build(tasks[2]!, dependencies(tasks[2]!), context(tasks[2]!))).toEqual(expected[2]); - }); - - it('does not share mutable elaboration or audit versions between returned snapshots', () => { - const build = createStatementSnapshotter(problem, workspace, commit, environmentDigest), task = tasks[2]!; - const elaboration: LeanStatementContext = { type: 'True', constants: [ - { name: 'Nat', module: 'Init', type: 'Type' }], omitted: ['a bounded dependency'] }; - const before = build(task, dependencies(task), elaboration); - tasks[0] = { ...tasks[0]!, objective: 'A new explanation of the same contract.', revision: 1 }; - const after = build(task, dependencies(task), elaboration); - expect(after.snapshotDigest).toBe(before.snapshotDigest); - expect(after.input.dependencies[0]!.taskDigest).not.toBe(before.input.dependencies[0]!.taskDigest); - before.input.elaboration!.constants[0]!.type = 'mutated'; - before.input.elaboration!.omitted.push('mutated'); - expect(after.input.elaboration).toEqual(elaboration); - expect(build(task, dependencies(task), elaboration)).toEqual(after); - }); - - it('prepares new committed sources on later calls without altering a fixed earlier batch', () => { - const task = tasks[2]!, build = createStatementSnapshotter(problem, workspace, commit, environmentDigest); - const before = build(task, dependencies(task)); - fs.writeFileSync(path.join(workspace, problem.projectRelative, 'Submission.lean'), - sources[1]!.replace('visible definition', 'updated definition')); - commit = commitSolverSources(problem, workspace); - clearCounts(); - expect(build(task, dependencies(task))).toEqual(before); - expect(host.reads).not.toHaveBeenCalled(); - const after = createStatementSnapshotter(problem, workspace, commit, environmentDigest)(task, dependencies(task)); - expect(host.reads).toHaveBeenCalledTimes(2); - expect(host.inspections).toHaveBeenCalledTimes(2); - expect(after.definitions[1]!.source).toContain('updated definition'); - expect(after.snapshotDigest).not.toBe(before.snapshotDigest); - }); - - it('keeps size accounting per target when one prepared source is reused', () => { - const largeHelpers = `def large : String := "${'é'.repeat(370_000)}"\n`; - fs.writeFileSync(path.join(workspace, problem.projectRelative, 'Submission.lean'), - sources[1]!.replace('theorem add_zero', largeHelpers + 'theorem add_zero')); - commit = commitSolverSources(problem, workspace); - const build = createStatementSnapshotter(problem, workspace, commit, environmentDigest); - const values = [...tasks, ...tasks].map(task => build(task, dependencies(task))); - expect(values.every(value => value.definitions.reduce((total, file) => total + Buffer.byteLength(file.source), 0) < 4_000_000)).toBe(true); - expect(values.reduce((total, value) => total + value.definitions.reduce((size, file) => size + Buffer.byteLength(file.source), 0), 0)).toBeGreaterThan(4_000_000); - expect(values[0]!.definitions[1]!.source).toContain('é'.repeat(10)); - }); -}); diff --git a/tests/taskConsumerInterfaces.test.ts b/tests/taskConsumerInterfaces.test.ts index 593e4b8a..076a2a1c 100644 --- a/tests/taskConsumerInterfaces.test.ts +++ b/tests/taskConsumerInterfaces.test.ts @@ -1,6 +1,6 @@ import { expect, it } from 'vitest'; import { compileTaskContext, frozenSourceContext, type TaskContextInput } from '../src/solver/contextCompiler'; -import type { CooperationState } from '../src/solver/cooperation'; +import type { CooperationState } from '../src/solver/cooperationShared'; import { buildResearchContext } from '../src/solver/modules/context'; import { cooperativeWorkContract } from '../src/solver/modules/contracts'; import type { ResearchWorker } from '../src/solver/modules/organization'; @@ -9,7 +9,6 @@ import type { SolverProblem } from '../src/solver/problem'; import type { ProofRoute } from '../src/solver/proofRoutes'; import { contextTaskConsumers, taskConsumerInterfaces, taskConsumerProjection } from '../src/solver/taskConsumers'; import { taskVersion, type CooperativeAction, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; const seedCommit = 'a'.repeat(40); const formal = 'namespace Original\nvariable (n : Nat)\ntheorem target (h : n > 0) : n > 0 := by sorry\nend Original'; @@ -47,8 +46,6 @@ const researchContext = (cooperation: CooperationState, assignment: CooperativeA retrievalRoot: '/library', assignment, frozenContexts: frozenContexts() }); const lead: ResearchWorker = { id: 'solver', role: 'lead', worktree: '/proof', ownedFiles: ['Submission.lean'] }; const researcher: ResearchWorker = { ...lead, id: 'researcher', role: 'researcher' }; -const scopedFor = (cooperation: CooperationState, action: CooperativeAction) => cooperativeResearch({ state: stateFor(cooperation), - workers: [lead, researcher], retrievalRoot: '', access: new Map() }).contextState(action, researcher); const consumerRows = (message: string): Array> => { for (const line of message.split('\n')) { try { @@ -198,39 +195,6 @@ it('uses the same global-only route consumer for the work contract and mathemati expect(consumerRows(context.message)[0].id).toBe(target.task.id); }); -it('exposes public pending consumer contracts through a context-only bypass without expanding visible tasks', () => { - const active = node('helper', [], { groupId: 'main', sharing: 'problem' }); - const shared = node('public_consumer', ['helper', 'private_sibling'], { groupId: 'other', sharing: 'problem' }); - const privateSibling = node('private_sibling', [], { groupId: 'other', sharing: 'group', objective: 'PRIVATE_SIBLING_MATHEMATICS' }); - const privateConsumer = node('private_consumer', ['helper'], { groupId: 'other', sharing: 'group', objective: 'PRIVATE_CONSUMER_MATHEMATICS' }); - const cooperation: CooperationState = { canonicalCommit: seedCommit, tasks: [active, shared, privateSibling, privateConsumer] }; - const scoped = scopedFor(cooperation, actionFor(active)); - - expect(scoped.tasks.map(item => item.task.id)).toEqual([active.task.id]); - expect(scoped.consumerInterfaces).toMatchObject({ taskId: active.task.id, taskDigest: taskVersion(active.task) }); - expect(scoped.consumerInterfaces?.interfaces.map(item => item.task.id)).toEqual([shared.task.id]); - expect(cooperation).not.toHaveProperty('consumerInterfaces'); - expect(JSON.stringify(scoped)).not.toContain('PRIVATE_SIBLING_MATHEMATICS'); - expect(JSON.stringify(scoped)).not.toContain('PRIVATE_CONSUMER_MATHEMATICS'); - const context = compileTaskContext(inputFor(active, scoped)); - expect(consumerRows(context.message)[0].id).toBe(shared.task.id); - expect(context.manifest.requiredTaskIds).toEqual([active.task.id]); -}); - -it('shows public in-flight questions across groups without expanding executable task visibility', () => { - const active = node('active', [], { groupId: 'main' }); - const shared = node('shared', [], { kind: 'research', groupId: 'other', sharing: 'problem', objective: 'PUBLIC_QUESTION' }); - const secret = node('secret', [], { kind: 'research', groupId: 'other', sharing: 'group', objective: 'PRIVATE_QUESTION' }); - shared.status = secret.status = 'running'; - const action = actionFor(active), scoped = scopedFor({ canonicalCommit: seedCommit, tasks: [active, shared, secret] }, action); - expect(scoped.tasks.map(item => item.task.id)).toEqual(['active']); - expect(scoped.parallelQuestions?.map(item => item.taskId)).toEqual(['shared']); - const context = researchContext(scoped, action); - expect(context.message).toContain('PUBLIC_QUESTION'); - expect(context.message).not.toContain('PRIVATE_QUESTION'); - expect(context.manifest?.requiredTaskIds).toEqual(['active']); -}); - it('rejects a valid consumer projection reused for another same-group assignment', () => { const earlier = node('earlier_helper'), current = node('current_helper'); const earlierConsumer = node('earlier_consumer', [earlier.task.id]); diff --git a/tests/taskFamilies.test.ts b/tests/taskFamilies.test.ts index 346cef15..88793f02 100644 --- a/tests/taskFamilies.test.ts +++ b/tests/taskFamilies.test.ts @@ -186,30 +186,6 @@ describe('family lemma tasks', () => { expect(Math.max(...[...largest.matchAll(/h(\d+) :/gu)].map(match => Number(match[1])))).toBe(Math.log2(MAX_FAMILY_MEMBERS) - 1); }); - it('tells the Lead how to write a family and a member worker to prove only its own range', () => { - const contextProblem = { ...problem, projectRelative: '.', receiptDigest: 'problem', baseCommit: 'fixed-commit', - contract: { formalStatement: 'theorem main : True := by sorry', assumptions: [] } } as unknown as SolverProblem; - const accepted = parseCooperationPlan(problem, { tasks: tasks() }).tasks; - const build = (planned: readonly CooperativeTask[], assignment: Parameters[2]['assignment']) => - buildResearchContext(contextProblem, { cooperation: { planVersion: 'v1', - tasks: planned.map(task => ({ task, status: 'pending', attempts: 0 })) } } as unknown as SolverRunState, - { root: '/runtime', worktree: '/proof', environment: {}, taskText: 'Prove it', retrievalRoot: '/library', maxOptionalContextBytes: 0, - frozenContexts: { 'Submission.lean': '' }, assignment }).instructions; - const task = (id: string) => { - const item = accepted.find(entry => entry.id === id)!; - return { kind: 'task' as const, task: item, assignment: { taskId: id, taskDigest: taskVersion(item), workerId: 'worker', seedCommit: 'fixed-commit' } }; - }; - const initial = build([], { kind: 'lead', seedCommit: 'fixed-commit' }); - expect(initial).toContain('A finite case table may be one family lemma task'); - expect(initial).toContain(`(at most ${MAX_FAMILY_MEMBERS})`); - expect(initial).not.toContain('Family member tasks are derived'); - expect(build(accepted, { kind: 'lead', seedCommit: 'fixed-commit', planVersion: 'v1' })).toContain('Family member tasks are derived from their family task'); - expect(build(accepted, task('cases_c1'))).toContain('This lemma is one member of family task cases. Prove only its own index range'); - for (const id of ['cases', 'base']) { - const text = build(accepted, task(id)); - expect(text).not.toContain('one member of family task'); expect(text).not.toContain('A finite case table'); - } - }); }); const lean = newestLeanBinary(); diff --git a/tests/taskLifecycle.test.ts b/tests/taskLifecycle.test.ts deleted file mode 100644 index 34999efb..00000000 --- a/tests/taskLifecycle.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import fs from 'node:fs'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import type { SolverRunState } from '../src/solver/archive'; -import { checkSolverRunState } from '../src/solver/stateInvariants'; -import { MAX_INVALID_TASK_TRANSITIONS } from '../src/solver/taskLifecycle'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -describe('live task transitions', () => { - let directory: string, state: SolverRunState, cooperative: CooperativeResearch, emit: ReturnType; - const controller = new AbortController(); - const start = () => { - const example = localExample('solver-task-lifecycle-', 'lead'), { workspace, problem } = example; - directory = example.directory; - const workers = [leadWorker(problem, workspace, 'lead'), peerWorker(example, 'proof')]; - const parsed = parseCooperationPlan(problem, { tasks: [{ id: 'helper', kind: 'lemma', objective: 'Prove helper', - theoremName: 'Tutorial.helper', type: 'True', proofPath: 'Submission.lean', ownerId: 'proof' }, - ...problem.targets.map((target, index) => ({ id: `original_goal_${index + 1}`, kind: 'goal', objective: 'Original', - theoremName: target.theoremName, proofPath: target.proofPath, status: 'paused' }))] }); - state = solverState(problem, workspace, { runId: 'lifecycle-fixture', phase: 'running', cooperation: { - canonicalCommit: problem.baseCommit, tasks: parsed.tasks.map(task => ({ task, status: 'pending', attempts: 0 })) } }); - emit = vi.fn(); - cooperative = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, emit }); - }; - const move = (...args: unknown[]) => (cooperative as any).moveTask(...args); - afterEach(async () => { await cooperative.stop(); fs.rmSync(directory, { recursive: true, force: true }); }); - - it('applies an illegal change but records and reports it at the mutation site', () => { - start(); - const node = state.cooperation!.tasks[0]; - move(node, 'running', 'dispatched'); - expect(state.cooperation!.invalidTaskTransitions).toBeUndefined(); - move(node, 'completed', 'research-completed'); - move(node, 'running', 'dispatched'); - expect(node.status).toBe('running'); - const record = { taskId: 'helper', from: 'completed', to: 'running', cause: 'dispatched' }; - expect(state.cooperation!.invalidTaskTransitions).toEqual([expect.objectContaining(record)]); - expect(emit).toHaveBeenCalledWith('task_transition_invalid', expect.objectContaining(record)); - expect(checkSolverRunState(state).map(item => item.code)).toContain('task_transition_invalid'); - }); - - it('does not record changes to staged copies and keeps only the latest records', () => { - start(); - const node = state.cooperation!.tasks[0]; - move({ ...node, status: 'completed' }, 'running', 'dispatched'); - expect(state.cooperation!.invalidTaskTransitions).toBeUndefined(); - for (let index = 0; index <= MAX_INVALID_TASK_TRANSITIONS; index++) { - move(node, 'completed', 'research-completed'); move(node, 'running', 'dispatched'); - } - expect(state.cooperation!.invalidTaskTransitions).toHaveLength(MAX_INVALID_TASK_TRANSITIONS); - }); -}); diff --git a/tests/taskWorkspaceResume.test.ts b/tests/taskWorkspaceResume.test.ts deleted file mode 100644 index 36777b42..00000000 --- a/tests/taskWorkspaceResume.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import type { CooperativeResearch } from '../src/solver/cooperation'; -import { researchTaskRole } from '../src/solver/modules/organization'; -import { commitSolverSources, git } from '../src/solver/problem'; -import { TaskTypePreflightCache } from '../src/solver/taskTypePreflight'; -import { taskVersion, type CooperativeAction, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { localExample, peerWorker, solverState } from './helpers/solver'; - -type TaskAction = Extract; -const budget = { maxTurns: Infinity, remainingMs: Infinity }; -const directories: string[] = []; -const instances: CooperativeResearch[] = []; - -function fixture() { - const example = localExample('task-workspace-resume-'); - directories.push(example.directory); - const lead = peerWorker(example, 'lead', { role: 'lead' }); - const worker = peerWorker(example, 'prover-1'); - const tasks: TaskRecord[] = ['a', 'b'].map(id => ({ - task: { id, kind: 'lemma', objective: `Prove helper ${id}`, dependsOn: [], revision: 0, - ownerId: worker.id, proofPath: 'Submission.lean', theoremName: `Tutorial.task_${id}`, type: 'True', - status: id === 'a' ? 'active' : 'paused' }, - status: 'pending', attempts: 0, - })); - tasks.push(...example.problem.targets.map((target, index): TaskRecord => ({ - task: { id: `goal-${index}`, kind: 'goal', objective: `Prove ${target.theoremName}`, dependsOn: ['a', 'b'], - revision: 0, conditional: false, proofPath: target.proofPath, theoremName: target.theoremName }, - status: 'pending', attempts: 0, - }))); - const state = solverState(example.problem, lead.worktree, { runId: 'workspace-resume', phase: 'running', - coordination: 'cooperative', workerCount: 2, - workers: [lead, worker].map(peer => ({ id: peer.id, role: peer.role, worktree: peer.worktree, - phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: example.problem.baseCommit, tasks, - groups: [{ group: { id: 'main', objective: 'Prove the original tutorial targets', status: 'active', revision: 0 }, turns: 0 }] }, - }); - const cooperative = cooperativeResearch({ state, workers: [lead, worker], retrievalRoot: '' }); - instances.push(cooperative); - const sourceFile = path.join(worker.worktree, example.problem.projectRelative, 'Submission.lean'); - const canonicalSource = fs.readFileSync(sourceFile, 'utf8'); - return { ...example, state, cooperative, worker, tasks, - session: state.workers![1]!, sourceFile, canonicalSource, notesFile: path.join(worker.worktree, 'RESEARCH.md') }; -} - -type Fixture = ReturnType; - -function select(f: Fixture, id: 'a' | 'b') { - for (const node of f.tasks.filter(node => node.task.kind === 'lemma')) - node.task = { ...node.task, status: node.task.id === id ? 'active' : 'paused' }; -} - -async function start(f: Fixture, id: 'a' | 'b'): Promise { - const action = await f.cooperative.next(f.worker, budget); - expect(action).toMatchObject({ kind: 'task', task: { id } }); - if (action?.kind !== 'task') throw new Error('fixture_expected_typed_task'); - expect(f.cooperative.started(f.worker, action)).toBe(true); - Object.assign(f.session, { sessionRole: researchTaskRole(action.task), sessionTaskId: action.task.id, - sessionTaskVersion: taskVersion(action.task), sessionAssignmentId: action.assignment.assignmentId }); - return action; -} - -function saveDraft(f: Fixture, action: TaskAction, name: string, notes: string) { - const source = f.canonicalSource.replace('end Tutorial', `lemma ${name} : True := by sorry\n\nend Tutorial`); - fs.writeFileSync(f.sourceFile, source); - fs.writeFileSync(f.notesFile, notes); - const commit = commitSolverSources(f.problem, f.worker.worktree); - f.cooperative.retainContextDraft(f.worker, action, commit); - return { commit, source, notes }; -} - -async function deliverFailedRequest(f: Fixture, action: TaskAction) { - const commit = commitSolverSources(f.problem, f.worker.worktree); - await expect(f.cooperative.deliver(f.worker, action, commit, true, 'request-failure')) - .resolves.toMatchObject({ checkWhole: false }); - expect(f.tasks.find(node => node.task.id === action.task.id)!.status).toBe('pending'); - expect(f.state.cooperation!.failedTaskInputs ?? []).toEqual([]); -} - -beforeEach(() => { - // These scheduling tests do not need Lean elaboration or a model session. - vi.spyOn(TaskTypePreflightCache.prototype, 'check').mockImplementation(async input => ({ - result: { status: 'unavailable', taskDigest: taskVersion(input.task), inputDigest: mathDigest('fixture-no-lean'), - reason: 'fixture-no-lean', evidence: 'advisory-type-elaboration', proofAcceptance: 'not-assessed' }, - current: () => true, - })); -}); - -afterEach(async () => { - for (const instance of instances.splice(0)) await instance.stop(); - vi.restoreAllMocks(); - for (const directory of directories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }); -}); - -describe('typed task workspace resumption', () => { - it('reassigns an unsaved typed task after another draft restores HEAD behind its seed', async () => { - const f = fixture(); - select(f, 'b'); - const b = await start(f, 'b'); - const savedB = saveDraft(f, b, 'saved_b_support', 'Task B draft notes.\n'); - f.cooperative.interrupted(f.worker, b); - - select(f, 'a'); - const a = await start(f, 'a'); - expect(git(f.worker.worktree, ['rev-parse', `${a.assignment.seedCommit}^`])).toBe(savedB.commit); - expect(f.state.cooperation!.researchDrafts?.a).toBeUndefined(); - f.cooperative.interrupted(f.worker, a); - - select(f, 'b'); - const restoredB = await start(f, 'b'); - expect(git(f.worker.worktree, ['rev-parse', 'HEAD'])).toBe(savedB.commit); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(savedB.source); - f.cooperative.interrupted(f.worker, restoredB); - - select(f, 'a'); - const resumed = await start(f, 'a'); - await deliverFailedRequest(f, resumed); - expect(resumed.assignment.assignmentId).not.toBe(a.assignment.assignmentId); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(f.canonicalSource); - expect(fs.readFileSync(f.notesFile, 'utf8')).toBe(''); - }); - - it('restores a saved typed draft with that task’s source and exact notes', async () => { - const f = fixture(); - const a = await start(f, 'a'); - const savedA = saveDraft(f, a, 'saved_a_support', '\ufeffTask A draft λ\r\n'); - f.cooperative.interrupted(f.worker, a); - - select(f, 'b'); - const b = await start(f, 'b'); - saveDraft(f, b, 'saved_b_support', 'Task B draft notes.\n'); - f.cooperative.interrupted(f.worker, b); - - select(f, 'a'); - const resumed = await start(f, 'a'); - expect(resumed.assignment).toBe(a.assignment); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(savedA.source); - expect(fs.readFileSync(f.notesFile, 'utf8')).toBe(savedA.notes); - expect(git(f.worker.worktree, ['merge-base', '--is-ancestor', resumed.assignment.seedCommit, 'HEAD'])).toBe(''); - f.cooperative.interrupted(f.worker, resumed); - }); - - it('reassigns a same-task session when HEAD is reset to the assignment seed’s parent', async () => { - const f = fixture(); - select(f, 'b'); - const b = await start(f, 'b'); - fs.writeFileSync(f.notesFile, 'Previous task B notes.\n'); - const previous = commitSolverSources(f.problem, f.worker.worktree); - f.cooperative.interrupted(f.worker, b); - - select(f, 'a'); - const a = await start(f, 'a'); - expect(git(f.worker.worktree, ['rev-parse', `${a.assignment.seedCommit}^`])).toBe(previous); - f.cooperative.interrupted(f.worker, a); - git(f.worker.worktree, ['reset', '--hard', previous]); - expect(f.session.sessionTaskId).toBe(a.task.id); - expect(f.session.sessionTaskVersion).toBe(taskVersion(a.task)); - - const resumed = await start(f, 'a'); - await deliverFailedRequest(f, resumed); - expect(resumed.assignment.assignmentId).not.toBe(a.assignment.assignmentId); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(f.canonicalSource); - expect(fs.readFileSync(f.notesFile, 'utf8')).toBe(''); - }); - - it.each(['prover', 'engineer'] as const)('preserves uncommitted source and notes on a same-task %s continuation', async role => { - const f = fixture(); - const a = await start(f, 'a'); - const saved = saveDraft(f, a, 'saved_a_support', 'Earlier task A checkpoint.\n'); - const latestSource = saved.source.replace('saved_a_support', 'latest_a_support'); - const latestNotes = 'Task A made more progress after its checkpoint.\n'; - fs.writeFileSync(f.sourceFile, latestSource); - fs.writeFileSync(f.notesFile, latestNotes); - f.cooperative.interrupted(f.worker, a); - f.session.sessionRole = role; - - const resumed = await start(f, 'a'); - expect(resumed.assignment).toBe(a.assignment); - expect(git(f.worker.worktree, ['rev-parse', 'HEAD'])).toBe(saved.commit); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(latestSource); - expect(fs.readFileSync(f.notesFile, 'utf8')).toBe(latestNotes); - expect(f.state.cooperation!.researchDrafts!.a!.commit).toBe(saved.commit); - f.cooperative.interrupted(f.worker, resumed); - }); -}); diff --git a/tests/theoryModules.test.ts b/tests/theoryModules.test.ts index 482c7c48..dd03c182 100644 --- a/tests/theoryModules.test.ts +++ b/tests/theoryModules.test.ts @@ -14,7 +14,7 @@ import { buildResearchContext } from '../src/solver/modules/context'; import { taskVersion } from '../src/solver/tasks'; import { assertSolverSources, commitSolverSources, committedSource, git, readSolverProblem, solverProofImports, type SolverProblem } from '../src/solver/problem'; -import type { CooperativeTask } from '../src/solver/cooperation'; +import type { CooperativeTask } from '../src/solver/tasks'; import { temporaryDirectory } from './helpers/files'; import { newestLeanBinary } from './helpers/lean'; diff --git a/tests/usageBudget.test.ts b/tests/usageBudget.test.ts index be03633c..b44c8384 100644 --- a/tests/usageBudget.test.ts +++ b/tests/usageBudget.test.ts @@ -3,7 +3,6 @@ import { aggregateUsage, allowanceReached, attributeTaskUsage, beginRequestUsage modelDispatchAllowed, recordThreadUsage, reportedTotalTokens, type RequestUsageAccounting, type UsageAccounting } from '../src/solver/usageBudget'; import type { SolverRunState } from '../src/solver/archive'; import { ResearchUsage } from '../src/solver/researchUsage'; -import type { CooperativeAction } from '../src/solver/tasks'; const accounting = (overrides: Partial = {}): UsageAccounting => ({ startedTurns: 1, reportedTurns: 1, pending: false, incomplete: false, ...overrides }); @@ -201,16 +200,16 @@ describe('task usage attribution in research sessions', () => { it('credits a request settled after its turn to the task that admitted it, not to a later lead turn', () => { const state = { turns: 0, tokenBudget: buildTokenBudget(0, []) } as unknown as SolverRunState; initializeUsageAccounting(state); - const usage = new ResearchUsage({ state, research: state, maxTotalTokens: 0, signal: new AbortController().signal, + const usage = new ResearchUsage({ state, research: state, signal: new AbortController().signal, remainingMs: () => Infinity, changed: () => {}, emit: () => {} }); const callbacks = usage.bindSession('session', () => undefined); usage.sessionOpened({ threadId: 'thread', usageSource: 'upstream-requests', run: async () => 'completed', close: async () => {}, interrupt: async () => {} }); - usage.begin({ kind: 'task', task: { id: 'lemma_a' }, assignment: {} } as unknown as CooperativeAction); + usage.begin('lemma_a'); const late = callbacks.requestGate!(); if (!late.allowed) throw new Error('fixture_request_not_admitted'); usage.finish(true); - usage.begin({ kind: 'lead', seedCommit: 'seed' }); + usage.begin(); const lead = callbacks.requestGate!(); if (!lead.allowed) throw new Error('fixture_request_not_admitted'); late.settle({ usage: { totalTokens: 40, inputTokens: 30, outputTokens: 10 }, complete: true }); diff --git a/tests/verificationCheckpoint.test.ts b/tests/verificationCheckpoint.test.ts index 3168fc97..ce731d7d 100644 --- a/tests/verificationCheckpoint.test.ts +++ b/tests/verificationCheckpoint.test.ts @@ -6,7 +6,6 @@ import { checkpointVerification, VerificationCheckpointError, withVerificationCh type VerificationCheckpoint } from '../src/solver/verificationCheckpoint'; import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { WorkerProofLifecycle } from '../src/solver/workerProofLifecycle'; import { taskVersion, type CooperativeAction } from '../src/solver/tasks'; import path from 'node:path'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; @@ -92,22 +91,4 @@ describe('resumable verification scheduling', () => { expect(checkpoints).toEqual([]); }); - it('keeps a frozen candidate pending on timeout and retries it without opening a model writer', async () => { - const task = { id: 'goal', kind: 'goal' as const, objective: 'Prove the target', dependsOn: [], revision: 0 }; - const assignment: CooperativeAction = { kind: 'task', task, - assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'peer', seedCommit: example.problem.baseCommit } }; - const ready = { status: 'frozen', snapshotCommit: example.problem.baseCommit }; - const close = vi.fn(async () => {}), checked = vi.fn(), completed = vi.fn(); - const cooperation = { pendingProofReady: () => ready, - deliver: vi.fn(async () => { throw new VerificationCheckpointError({ key: 'fixture', timeoutMs: 1000, attempts: 1, - at: 1, targetCommit: example.problem.baseCommit, receiptIds: [] }); }), proofReadyCompleted: completed }; - const state = solverState(example.problem, example.workspace, { runId: 'frozen', phase: 'running' }); - const lifecycle = new WorkerProofLifecycle({ state, research: state, worker: { id: 'peer', role: 'engineer', worktree: example.workspace, ownedFiles: [] }, - cooperation: cooperation as never, close, checked, save: () => {}, emit: () => {} }); - await expect(lifecycle.resumeFrozen(assignment)).rejects.toBeInstanceOf(VerificationCheckpointError); - expect(ready.status).toBe('frozen'); expect(completed).not.toHaveBeenCalled(); - cooperation.deliver.mockResolvedValueOnce({ check: undefined } as never); - expect(await lifecycle.resumeFrozen(assignment)).toBe(true); - expect(cooperation.deliver.mock.calls).toHaveLength(2); expect(close).toHaveBeenCalledTimes(2); expect(checked).toHaveBeenCalledOnce(); - }); }); diff --git a/tests/verifiedProofPublication.test.ts b/tests/verifiedProofPublication.test.ts deleted file mode 100644 index cc242d4d..00000000 --- a/tests/verifiedProofPublication.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { canonicalMathJson } from '../src/math/mathRuntimeIo'; -import type { TaskProof } from '../src/solver/cooperativeProof'; -import type { DeliveryRecord } from '../src/solver/deliveries'; -import { commitSolverSources } from '../src/solver/problem'; -import { assignmentDeliveryFile, taskVersion, type CooperativeTask, type TaskRecord } from '../src/solver/tasks'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; - -const fixtures: ReturnType[] = []; -const verifiedSummary = 'Checked proof integrated with freshly validated dependencies.'; - -function fixture() { - const example = localExample('verified-proof-publication-'); - const { directory, workspace, problem } = example; - const worker = peerWorker(example, 'writer'), lead = leadWorker(problem, workspace); - const file = path.join(worker.worktree, problem.projectRelative, 'Submission.lean'); - fs.appendFileSync(file, '\nlemma published : True := by trivial\n'); - const submitted = commitSolverSources(problem, worker.worktree); - fs.appendFileSync(file, '\n-- The canonical merge includes the discharged dependency.\n'); - const canonical = commitSolverSources(problem, worker.worktree); - const task: CooperativeTask = { id: 'parent', kind: 'lemma', objective: 'Prove the parent.', - theoremName: 'published', proofPath: 'Submission.lean', type: 'True', dependsOn: ['child'], conditional: true }; - const child: CooperativeTask = { id: 'child', kind: 'lemma', objective: 'Prove the child.', - theoremName: 'child', proofPath: 'Submission.lean', type: 'True', dependsOn: [] }; - const assignment = { taskId: task.id, taskDigest: taskVersion(task), workerId: worker.id, - seedCommit: problem.baseCommit, assignmentId: 'publication-assignment' }; - const proof = (commit: string, receiptId: string, conditions: TaskProof['conditions'] = []): TaskProof => ({ - commit, taskDigest: taskVersion(task), sourceDigest: `source-${receiptId}`, seedCommit: problem.baseCommit, - passed: true, conditions, changes: [], - references: { sourceCommit: commit, environmentDigest: 'environment', contextDigest: `context-${receiptId}`, - root: { name: 'published', file: 'Submission.lean' }, inputs: [], statement: [], proof: [], tasks: [] }, - verification: { schema: 'deepscientist.mathematics.verification-batch/v1', status: 'kernel_verified', - targetCommit: commit, sessionId: receiptId, events: [], startedAt: 1, checkedAt: 2, durationMs: 1, - results: [{ receiptId, status: 'kernel_verified', targetCommit: commit, proofPath: 'Submission.lean', - theoremName: 'published', statementHash: taskVersion(task), leanStatementHash: taskVersion(task) }] }, - }); - const original = proof(submitted, 'conditional-receipt', [{ taskId: child.id, taskDigest: taskVersion(child) }]); - const integrated = proof(canonical, 'unconditional-receipt'); - const node: TaskRecord = { task, assignment, status: 'integrated', attempts: 1, proof: original, integratedCheck: integrated }; - const state = solverState(problem, workspace, { runId: 'publication-fixture', phase: 'running', - cooperation: { canonicalCommit: canonical, tasks: [node, { task: child, status: 'integrated', attempts: 1 }] } }); - const controller = new AbortController(), save = vi.fn(), events: { event: string; details?: Record }[] = []; - const cooperative = cooperativeResearch({ state, workers: [lead, worker], retrievalRoot: directory, - signal: controller.signal, save, emit: (event, details) => events.push({ event, details }) }); - const host = cooperative as any; - host.checkedDeliveries.add(original); host.checkedDeliveries.add(integrated); - const artifacts = { schema: 'theorem-os.delivery-artifacts.v1' as const, scope: 'advisory-unverified' as const, - problemReceiptDigest: problem.receiptDigest, taskId: task.id, taskDigest: taskVersion(task), - seedCommit: assignment.seedCommit, commit: submitted, artifacts: [] }; - const request = { worker, action: { kind: 'task', task, assignment }, commit: submitted, - summary: 'Fixed declaration checked; unresolved lemma assumptions remain obligations.', - options: { assignmentKey: assignmentDeliveryFile(assignment), artifacts, submissionId: 'original-submission' } }; - host.proofDeliveryRequests.set(canonicalMathJson([worker.id, assignmentDeliveryFile(assignment), submitted]), request); - const records = () => state.cooperation!.deliveries ?? []; - const f = { directory, controller, cooperative, host, node, state, worker, original, integrated, proof, request, - save, events, records, publish: () => host.publishProofDelivery(node) as Promise }; - fixtures.push(f); return f; -} - -afterEach(async () => { - for (const f of fixtures.splice(0)) { - f.controller.abort(); await f.cooperative.stop(); fs.rmSync(f.directory, { recursive: true, force: true }); - } - vi.restoreAllMocks(); -}); - -describe('verified proof publication evidence', () => { - it.each([true, false])('publishes canonical evidence with the original artifact source (live request: %s)', async live => { - const f = fixture(); - if (!live) f.host.proofDeliveryRequests.clear(); - await f.publish(); await f.publish(); - - expect(f.records()).toHaveLength(1); - const record = f.records()[0]; - expect(record).toMatchObject({ status: 'verified', commit: f.integrated.commit, - sourceDigest: f.integrated.sourceDigest, summary: verifiedSummary, actualReferences: f.integrated.references, - evidence: { passed: true, verification: { targetCommit: f.integrated.verification.targetCommit, - results: [{ receiptId: 'unconditional-receipt' }] } } }); - if (live) expect(record.artifacts).toBe(f.request.options.artifacts); - expect(f.events.filter(item => item.event === 'delivery_published')).toHaveLength(1); - expect(f.node.proof).toBe(f.original); - }); - - it('corrects an existing legacy verified record in place and preserves its original submission artifacts', async () => { - const f = fixture(); - const old: DeliveryRecord = f.host.createDeliveryRecord(f.worker, f.node.task, 'proof', 'verified', f.request.summary, - { ...f.request.options, commit: f.original.commit, sourceDigest: f.original.sourceDigest, - evidence: f.original, actualReferences: f.original.references, knowledgeUses: [] }); - f.state.cooperation!.deliveries = [old]; - await f.publish(); await f.publish(); - - expect(f.records()).toEqual([old]); - expect(old).toMatchObject({ commit: f.integrated.commit, sourceDigest: f.integrated.sourceDigest, - summary: verifiedSummary, actualReferences: f.integrated.references, - evidence: { verification: { results: [{ receiptId: 'unconditional-receipt' }] } }, - artifacts: { commit: f.original.commit }, submissionId: 'original-submission' }); - expect(f.events.filter(item => item.event === 'delivery_published')).toHaveLength(1); - }); - - it('rolls back a failed metadata correction and retries the same record without duplicate publication', async () => { - const f = fixture(); - const old: DeliveryRecord = f.host.createDeliveryRecord(f.worker, f.node.task, 'proof', 'verified', f.request.summary, - { ...f.request.options, commit: f.original.commit, sourceDigest: f.original.sourceDigest, - evidence: f.original, actualReferences: f.original.references, knowledgeUses: [] }); - f.state.cooperation!.deliveries = [old]; - const before = structuredClone(old), error = new Error('fixture_storage_failure'); - f.save.mockImplementationOnce(() => { throw error; }); - await expect(f.publish()).rejects.toBe(error); - expect(old).toEqual(before); expect(f.events).not.toContainEqual(expect.objectContaining({ event: 'delivery_published' })); - await f.publish(); await f.publish(); - expect(f.records()).toEqual([old]); - expect(old.evidence?.verification.results).toEqual([{ receiptId: 'unconditional-receipt' }]); - expect(old.artifacts?.commit).toBe(f.original.commit); - expect(f.events.filter(item => item.event === 'delivery_published')).toHaveLength(1); - }); - - it('keeps one verified publication when a fresh canonical recheck changes its commit and references', async () => { - const f = fixture(); await f.publish(); - const record = f.records()[0]; - const refreshed = f.proof(f.node.assignment!.seedCommit, 'refreshed-receipt'); - f.node.integratedCheck = refreshed; f.host.checkedDeliveries.add(refreshed); - await f.publish(); await f.publish(); - expect(f.records()).toEqual([record]); - expect(record).toMatchObject({ commit: refreshed.commit, sourceDigest: refreshed.sourceDigest, - actualReferences: refreshed.references, evidence: { verification: { results: [{ receiptId: 'refreshed-receipt' }] } }, - artifacts: { commit: f.original.commit } }); - expect(f.events.filter(item => item.event === 'delivery_published')).toHaveLength(2); - }); - - it.each(['conditional', 'failed'] as const)('keeps submitted evidence and the appropriate summary for %s publications', async status => { - const f = fixture(); - f.node.status = status === 'conditional' ? 'conditional' : 'blocked'; - if (status === 'failed') { - f.original.passed = false; f.original.verification.status = 'failed'; - f.node.feedback = 'The submitted proof failed independent checking.'; - } - await f.publish(); await f.publish(); - expect(f.records()).toHaveLength(1); - expect(f.records()[0]).toMatchObject({ status, commit: f.original.commit, sourceDigest: f.original.sourceDigest, - summary: status === 'conditional' ? f.request.summary : f.node.feedback, actualReferences: f.original.references, - evidence: { verification: { results: [{ receiptId: 'conditional-receipt' }] } } }); - }); - - it('retains the merged failure evidence when resuming publication without a live submission', async () => { - const f = fixture(); f.host.proofDeliveryRequests.clear(); - f.node.status = 'blocked'; f.node.feedback = 'The merged proof failed independent checking.'; - f.integrated.passed = false; f.integrated.verification.status = 'failed'; - f.integrated.verification.results[0].status = 'failed'; - await f.host.publishProofDelivery(f.node, undefined, f.host.proofDeliveryState(f.node)); - - expect(f.records()).toMatchObject([{ status: 'failed', commit: f.integrated.commit, - summary: f.node.feedback, evidence: { passed: false, verification: { status: 'failed', - results: [{ receiptId: 'unconditional-receipt' }] } } }]); - }); - - it('ignores a late request from an older assignment without changing the current verified record', async () => { - const f = fixture(); await f.publish(); - const record = f.records()[0], before = structuredClone(record); - f.node.assignment = { ...f.node.assignment!, assignmentId: 'new-assignment' }; - await f.host.publishProofDelivery(f.node, f.request); - expect(f.records()).toEqual([record]); expect(record).toEqual(before); - expect(f.events.filter(item => item.event === 'delivery_published')).toHaveLength(1); - }); -}); diff --git a/tests/webCollaboration.test.ts b/tests/webCollaboration.test.ts index dcbb9a12..848d8f75 100644 --- a/tests/webCollaboration.test.ts +++ b/tests/webCollaboration.test.ts @@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { createWebService } from '../apps/web/server'; import { readWebConfig } from '../apps/web/config'; import { isAcceptedRun } from '../apps/web/presentation'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; import { WebJobs } from '../apps/web/jobs'; import { readWebArchiveObservations, WebStorage } from '../apps/web/storage'; import type { WebCommand, WebCommandResult, WebObservation } from '../apps/web/collaboration'; @@ -20,6 +21,7 @@ const key = 'sk-collaboration-offline-test'; const input = (): WebRunInput => ({ providerId: 'openai', apiKey: key, model: 'fixture', effort: 'high', source: 'theorem example : True := by sorry', task: 'Offline collaboration fixture', workers: 2, maxRunSeconds: 60, maxTurns: 2, coordination: 'cooperative', environment: 'standard' }); +const approvalInput = (): WebRunInput => ({ ...input(), ...webAgentTeamPreset(), planApproval: true }); const provider = { id: 'openai', name: 'Fixture', baseUrl: 'https://api.openai.com/v1' }; const tick = () => new Promise(resolve => setImmediate(resolve)); @@ -56,11 +58,22 @@ function observation(webRunId: string, sequence = 1): WebObservation { }; } +function approvalObservation(runId: string, sequence = 1): WebObservation { + const observed = observation(runId, sequence); + const configuration = observed.inspection.configuration; + Object.assign(configuration, { + workers: 1, coordination: 'independent', researchMode: 'skill', + researchSkill: { name: 'theoremos-research', digest: mathDigest('fixture skill'), loading: 'native' }, + researchDelegation: { mode: 'team', maxAgents: approvalInput().nativeTeamCapacity }, + }); + observed.inspection.planApproval = { required: true, status: 'pending', planVersion: 'plan-1', rejections: [], leadRevising: false }; + return observed; +} + class FixtureRunner implements WebRunner { calls: { value: WorkerInput; send: (message: WorkerMessage) => void; finish: () => void }[] = []; commands: WebCommand[] = []; failCommands = false; - commandObservation?: WebObservation; commandResult?: (command: WebCommand) => WebCommandResult; async readiness() { return { ready: true, message: 'Offline test worker' }; } async run(value: WorkerInput, send: (message: WorkerMessage) => void, signal: AbortSignal) { @@ -76,15 +89,8 @@ class FixtureRunner implements WebRunner { if (this.commandResult) return this.commandResult(command); if (this.failCommands) throw new Error('Fixture receipt timed out'); if (command.type === 'capture') return { id: 'capture', status: 'captured' }; - if (command.type === 'guidance') { - const now = new Date().toISOString(); - return { id: command.guidance.id, status: 'queued', guidance: { ...command.guidance, status: 'queued', createdAt: now, updatedAt: now }, - ...(this.commandObservation ? { observation: this.commandObservation } : {}) }; - } - if (command.type === 'plan-approval') return { id: command.approval.id, status: 'queued', planVersion: command.approval.planVersion, - ...(this.commandObservation ? { observation: this.commandObservation } : {}) }; - return { id: command.proposal.id, status: command.type === 'edit-preview' ? 'validated' : 'queued', - baseVersion: command.proposal.baseVersion, affectedTaskIds: ['helper'] }; + if (command.type === 'plan-approval') return { id: command.approval.id, status: 'queued', planVersion: command.approval.planVersion }; + throw new Error('Unexpected fixture command'); } } @@ -116,49 +122,43 @@ describe('real collaboration HTTP and job boundaries without model calls', () => runner.calls[0].finish(); await tick(); }); - it('coalesces identical commands, rejects reused IDs, and queries uncertain writes without resending', async () => { + it('coalesces identical approvals, rejects reused IDs and queries uncertain writes without resending', async () => { const runner = new FixtureRunner(), jobs = new WebJobs(runner, { concurrency: 1, queueLimit: 2 }); closing.push(() => jobs.close()); - const run = jobs.create('alice', input(), provider); await tick(); - const observed = observation(run.id); runner.calls[0].send({ type: 'observation', observation: observed }); - const proposal = { ...observed.plan!, id: 'edit-one' }; - expect((await jobs.command('alice', run.id, { type: 'edit-preview', proposal })).status).toBe('validated'); - expect(jobs.storage.getCommand('alice', run.id, proposal.id)).toBeUndefined(); - const command = { type: 'edit' as const, proposal }; + const run = jobs.create('alice', approvalInput(), provider); await tick(); + const observed = approvalObservation(run.id); runner.calls[0].send({ type: 'observation', observation: observed }); + const command = { type: 'plan-approval' as const, approval: { id: 'approve-once', planVersion: 'plan-1' } }; const first = jobs.command('alice', run.id, command), duplicate = jobs.command('alice', run.id, command); - expect(await first).toEqual(await duplicate); - expect(runner.commands.filter(item => item.type === 'edit')).toHaveLength(1); - await jobs.command('alice', run.id, command); - expect(runner.commands.filter(item => item.type === 'edit')).toHaveLength(1); - await expect(jobs.command('alice', run.id, { ...command, proposal: { ...proposal, baseVersion: 'other' } })).rejects.toThrow(/命令 ID/); + const receipt = await first; + expect(await duplicate).toEqual(receipt); + expect(receipt.commandDigest).toBe(mathDigest(canonicalMathJson(command))); + expect(runner.commands).toHaveLength(1); + expect(await jobs.command('alice', run.id, command)).toEqual(receipt); + expect(runner.commands).toHaveLength(1); + await expect(jobs.command('alice', run.id, { ...command, approval: { ...command.approval, planVersion: 'other' } })).rejects.toThrow(/命令 ID/); runner.failCommands = true; - const uncertain = { type: 'edit' as const, proposal: { ...proposal, id: 'edit-timeout' } }; - expect((await jobs.command('alice', run.id, uncertain)).status).toBe('unknown'); - await jobs.command('alice', run.id, uncertain); - expect(runner.commands.filter(item => item.type === 'edit')).toHaveLength(2); - runner.failCommands = false; - await jobs.command('alice', run.id, { type: 'guidance', guidance: { id: 'guidance-one', recipient: { kind: 'lead' }, text: 'Check the quantifier.', - observationRef: { sequence: 1, stateDigest: observed.snapshot.stateDigest } } }); - expect(jobs.guidance('alice', run.id, 'guidance-one')?.status).toBe('queued'); - expect(run.observation?.plan?.baseVersion).toBe('plan-1'); + const uncertain = { ...command, approval: { ...command.approval, id: 'approval-timeout' } }; + const unknown = await jobs.command('alice', run.id, uncertain); + expect(unknown.status).toBe('unknown'); + expect(jobs.commandReceipt('alice', run.id, uncertain.approval.id)).toEqual(unknown); + expect(await jobs.command('alice', run.id, uncertain)).toEqual(unknown); + expect(runner.commands).toHaveLength(2); runner.calls[0].finish(); await tick(); }); - it.each(['queued', 'rejected'] as const)('keeps a saved %s command receipt when saving its activity event fails', async status => { + it('keeps a saved approval receipt when saving its activity event fails', async () => { const runner = new FixtureRunner(), jobs = new WebJobs(runner, { concurrency: 1, queueLimit: 2 }); closing.push(() => jobs.close()); - const run = jobs.create('alice', input(), provider); await tick(); - const proposal = { ...observation(run.id).plan!, id: `event-failure-${status}` }, command = { type: 'edit' as const, proposal }; - runner.commandResult = () => ({ id: proposal.id, status, ...(status === 'rejected' ? { reason: 'math_edit_version_conflict' } : {}) }); + const run = jobs.create('alice', approvalInput(), provider); await tick(); + const approval = { id: 'event-failure', planVersion: 'plan-1' }, command = { type: 'plan-approval' as const, approval }; const save = vi.spyOn(jobs.storage, 'saveRun').mockImplementationOnce(() => { throw new Error(`disk unavailable ${key}`); }); try { const receipt = await jobs.command('alice', run.id, command); - expect(receipt.status).toBe(status); - expect(receipt.reason).toBe(status === 'rejected' ? 'math_edit_version_conflict' : undefined); - expect(jobs.storage.getCommand('alice', run.id, proposal.id)).toMatchObject({ status, commandDigest: receipt.commandDigest }); - expect(jobs.commandReceipt('alice', run.id, proposal.id)).toEqual(receipt); + expect(receipt.status).toBe('queued'); + expect(jobs.storage.getCommand('alice', run.id, approval.id)).toMatchObject({ status: 'queued', commandDigest: receipt.commandDigest }); + expect(jobs.commandReceipt('alice', run.id, approval.id)).toEqual(receipt); const sent = runner.commands.length; expect(await jobs.command('alice', run.id, command)).toEqual(receipt); expect(runner.commands).toHaveLength(sent); - expect(JSON.stringify([run, receipt, jobs.storage.getCommand('alice', run.id, proposal.id)])).not.toContain(key); + expect(JSON.stringify([run, receipt, jobs.storage.getCommand('alice', run.id, approval.id)])).not.toContain(key); runner.calls[0]!.finish(); await tick(); } finally { save.mockRestore(); } }); @@ -166,7 +166,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => it.each(['receipt', 'failure'] as const)('redacts a late command %s after the worker has cleared its credential', async outcome => { const runner = new FixtureRunner(), jobs = new WebJobs(runner, { concurrency: 1, queueLimit: 2 }); closing.push(() => jobs.close()); - const run = jobs.create('alice', input(), provider); await tick(); + const run = jobs.create('alice', approvalInput(), provider); await tick(); const response = Promise.withResolvers(); runner.command = () => response.promise; const command = { type: 'plan-approval' as const, approval: { id: 'late-approval', planVersion: 'plan-1' } }; @@ -190,7 +190,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-deleted-command-')); roots.push(root); const storage = new WebStorage(root), runner = new FixtureRunner(); const jobs = new WebJobs(runner, { concurrency: 1, queueLimit: 2 }, { storage }); closing.push(() => jobs.close()); - const run = jobs.create('alice', input(), provider); await tick(); + const run = jobs.create('alice', approvalInput(), provider); await tick(); const response = Promise.withResolvers(); runner.command = () => response.promise; const command = { type: 'plan-approval' as const, approval: { id: 'deleted-approval', planVersion: 'plan-1' } }; @@ -199,7 +199,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => if (removed === 'run') expect(jobs.remove('alice', run.id)).toBe('deleted'); else { jobs.forget('alice'); storage.deleteOwner('alice'); } const settled = expect(pending).rejects.toThrow(/不存在|不属于/); - if (outcome === 'receipt') response.resolve({ id: command.approval.id, status: 'queued', observation: observation(run.id) }); + if (outcome === 'receipt') response.resolve({ id: command.approval.id, status: 'queued', observation: approvalObservation(run.id) }); else response.reject(new Error('Late transport failure')); await settled; expect(jobs.list('alice')).toEqual([]); @@ -250,10 +250,9 @@ describe('real collaboration HTTP and job boundaries without model calls', () => it('settles a plan approval from the observed solver record and keeps a known rejection', async () => { const runner = new FixtureRunner(), jobs = new WebJobs(runner, { concurrency: 1, queueLimit: 2 }); closing.push(() => jobs.close()); - const run = jobs.create('alice', { ...input(), planApproval: true }, provider); await tick(); + const run = jobs.create('alice', approvalInput(), provider); await tick(); expect(runner.calls[0].value.input.planApproval).toBe(true); - const pending = observation(run.id); - pending.inspection.planApproval = { required: true, status: 'pending', planVersion: 'plan-1', rejections: [], leadRevising: false }; + const pending = approvalObservation(run.id); runner.calls[0].send({ type: 'observation', observation: pending }); const command = { type: 'plan-approval' as const, approval: { id: 'approve-one', planVersion: 'plan-1' } }; expect(await jobs.command('alice', run.id, command)).toMatchObject({ id: 'approve-one', status: 'queued', planVersion: 'plan-1' }); @@ -266,7 +265,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => expect(await jobs.command('alice', run.id, stale)).toMatchObject({ status: 'rejected', reason: 'math_plan_approval_version_conflict' }); expect(run.events.filter(item => item.type === 'plan_approval_queued')).toHaveLength(1); - const approved = observation(run.id, 2); + const approved = approvalObservation(run.id, 2); approved.inspection.planApproval = { required: true, status: 'approved', planVersion: 'plan-1', approvedId: 'approve-one', approvedVersion: 'plan-1', approvedAt: 5, rejections: [], leadRevising: false }; runner.calls[0].send({ type: 'observation', observation: approved }); @@ -276,42 +275,6 @@ describe('real collaboration HTTP and job boundaries without model calls', () => runner.calls[0].finish(); await tick(); }); - it('uses one edit digest for preview, submission and queried receipts without applying or saving the preview', async () => { - const runner = new FixtureRunner(), jobs = new WebJobs(runner, { concurrency: 1, queueLimit: 2 }); closing.push(() => jobs.close()); - const run = jobs.create('alice', input(), provider); await tick(); - const initial = observation(run.id); runner.calls[0].send({ type: 'observation', observation: initial }); - const proposal = { ...initial.plan!, id: 'digest-consistent-edit' }, command = { type: 'edit' as const, proposal }; - const canonicalDigest = mathDigest(canonicalMathJson(command)), workerDigest = 'd'.repeat(64); - const workerReceipts: WebCommandResult[] = []; - let applied = 0; - runner.commandResult = requested => { - if (requested.type === 'capture' || requested.type === 'guidance') throw new Error('Unexpected fixture command'); - if (requested.type === 'edit') { - applied++; - const next = observation(run.id, initial.sequence + 1); - next.inspection.edits = [{ id: proposal.id, status: 'applied', baseVersion: proposal.baseVersion, - planVersion: 'plan-2', affectedTasks: ['helper'] }]; - runner.calls[0].send({ type: 'observation', observation: next }); - } - const receipt = { id: proposal.id, status: requested.type === 'edit-preview' ? 'validated' : 'queued', commandDigest: workerDigest }; - workerReceipts.push(receipt); return receipt; - }; - const preview = await jobs.command('alice', run.id, { type: 'edit-preview', proposal }); - expect(preview.status).toBe('validated'); expect(preview.commandDigest).toBe(canonicalDigest); - expect(preview.commandDigest).not.toBe(workerDigest); expect(applied).toBe(0); - expect(run.observation).toEqual(initial); expect(jobs.commandReceipt('alice', run.id, proposal.id)).toBeUndefined(); - expect(jobs.storage.listCommands('alice', run.id)).toEqual([]); - expect(runner.commands.map(item => item.type)).toEqual(['edit-preview']); - const submitted = await jobs.command('alice', run.id, command); - expect(submitted.status).toBe('applied'); expect(submitted.commandDigest).toBe(preview.commandDigest); - expect(jobs.commandReceipt('alice', run.id, proposal.id)).toEqual(submitted); - expect(jobs.storage.getCommand('alice', run.id, proposal.id)?.commandDigest).toBe(canonicalDigest); - expect(await jobs.command('alice', run.id, command)).toEqual(submitted); - expect(applied).toBe(1); expect(runner.commands.map(item => item.type)).toEqual(['edit-preview', 'edit']); - expect(workerReceipts.map(receipt => receipt.commandDigest)).toEqual([workerDigest, workerDigest]); - runner.calls[0].finish(); await tick(); - }); - it('resolves command GET receipts from observed host outcomes without resending uncertain writes', async () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-command-receipt-http-')); roots.push(root); const reservation = net.createServer(); await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve)); @@ -326,28 +289,23 @@ describe('real collaboration HTTP and job boundaries without model calls', () => const request = (route: string, body?: unknown) => fetch(base + route, { method: body ? 'POST' : 'GET', headers: { Cookie: cookie, 'X-CSRF-Token': csrf, ...(body ? { 'Content-Type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined }); - const run = (await (await request('/api/runs', input())).json()).run; await tick(); + const run = service.jobs.create(cookie.slice('theoremos_session='.length), input(), provider); await tick(); const prefix = '/api/runs/' + run.id, initial = observation(run.id); runner.calls[0].send({ type: 'observation', observation: initial }); const proposals = ['http-applied', 'http-rejected', 'http-unconfirmed'].map(id => ({ ...initial.plan!, id })); - runner.failCommands = true; - const uncertain: WebCommandResult[] = []; - for (const proposal of proposals) { - const response = await request(prefix + '/edits', proposal); expect(response.status).toBe(200); - const receipt = (await response.json()).receipt; - expect(receipt.status).toBe('unknown'); expect(receipt.reason).toBe('Fixture receipt timed out'); - expect(receipt.commandDigest).toMatch(/^[a-f0-9]{64}$/u); uncertain.push(receipt); - } + const uncertain = proposals.map(proposal => ({ id: proposal.id, status: 'unknown', reason: 'Fixture receipt timed out', + commandDigest: mathDigest(canonicalMathJson({ type: 'edit', proposal })) })); + for (const record of uncertain) service.storage.saveCommand(owner, run.id, record.id, record); const receipt = async (id: string): Promise => { const response = await request(prefix + '/commands/' + id); expect(response.status).toBe(200); return (await response.json()).receipt; }; expect(await receipt(proposals[0].id)).toEqual({ ...uncertain[0], observation: initial }); - runner.failCommands = false; - runner.commandObservation = initial; const guidance = { id: 'http-guidance', recipient: { kind: 'lead' as const }, text: 'Check the quantifier.', observationRef: { sequence: initial.sequence, stateDigest: initial.snapshot.stateDigest } }; - expect((await request(prefix + '/guidance', guidance)).status).toBe(200); + service.storage.saveCommand(owner, run.id, guidance.id, { id: guidance.id, status: 'queued', + guidance: { ...guidance, status: 'queued', createdAt: initial.observedAt, updatedAt: initial.observedAt } }); + expect((await request(prefix + '/guidance', guidance)).status).toBe(409); const queued = await receipt(guidance.id); expect(queued.status).toBe('queued'); expect(queued.observation).toEqual(initial); const savedCommands = service.storage.listCommands(owner, run.id), sentCommands = runner.commands.length; @@ -366,7 +324,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => edit: next.inspection.edits[1], observation: next }); expect(await receipt(proposals[2].id)).toEqual({ ...uncertain[2], observation: next }); expect(await receipt(guidance.id)).toEqual({ ...queued, status: 'delivered', guidance: next.guidance[0], observation: next }); - expect((await (await request(prefix + '/edits', proposals[0])).json()).receipt).toEqual(applied); + expect((await request(prefix + '/edits', proposals[0])).status).toBe(409); expect(runner.commands).toHaveLength(sentCommands); expect(service.storage.listCommands(owner, run.id)).toEqual(savedCommands); const bob = await fetch(base + '/api/session'), bobCookie = bob.headers.get('set-cookie')!.split(';')[0]; @@ -394,15 +352,15 @@ describe('real collaboration HTTP and job boundaries without model calls', () => headers: { Cookie: cookie, 'X-CSRF-Token': csrf, ...(body ? { 'Content-Type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined }) }; }; const { owner, request: alice } = await login(), { request: bob } = await login(); - const first = (await (await alice('/api/runs', input())).json()).run; await tick(); + const first = service.jobs.create(owner, input(), provider); await tick(); runner.calls[0].send({ type: 'observation', observation: observation(first.id) }); runner.calls[0].finish(); const from = { runId: first.id, taskId: 'helper', commit: 'a'.repeat(40), label: 'Conditional fixture helper · 第 1 次' }; - expect((await alice('/api/runs', { ...input(), continueFrom: { ...from, commit: 'f'.repeat(40) } })).status).toBe(404); - expect((await bob('/api/runs', { ...input(), continueFrom: from })).status).toBe(404); - expect((await alice('/api/runs', { ...input(), continueFrom: { ...from, source: 'theorem forged : False := sorry' } })).status).toBe(400); - expect((await alice('/api/runs', { ...input(), continueFrom: { ...from, label: 'line\nbreak' } })).status).toBe(400); - const response = await alice('/api/runs', { ...input(), continueFrom: from }); + expect((await alice('/api/runs', { ...input(), workers: 1, continueFrom: { ...from, commit: 'f'.repeat(40) } })).status).toBe(404); + expect((await bob('/api/runs', { ...input(), workers: 1, continueFrom: from })).status).toBe(404); + expect((await alice('/api/runs', { ...input(), workers: 1, continueFrom: { ...from, source: 'theorem forged : False := sorry' } })).status).toBe(400); + expect((await alice('/api/runs', { ...input(), workers: 1, continueFrom: { ...from, label: 'line\nbreak' } })).status).toBe(400); + const response = await alice('/api/runs', { ...input(), workers: 1, continueFrom: from }); expect(response.status).toBe(201); const next = (await response.json()).run; const frozen = { ...from, taskVersion: 'version-1', sourceDigest: 'b'.repeat(64), environmentDigest: 'env', file: 'Submission.lean' }; @@ -449,7 +407,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => headers: { Cookie: cookie, 'X-CSRF-Token': csrf, 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) }; }; const { owner, request: alice } = await login(), { request: bob } = await login(); - const run = (await (await alice('/api/runs', input())).json()).run; await tick(); + const run = service.jobs.create(owner, input(), { ...provider, baseUrl: `http://127.0.0.1:${(upstream.address() as net.AddressInfo).port}/v1` }); await tick(); const failed = observation(run.id); const firstAt = Date.parse(failed.observedAt), secondAt = firstAt + 1; failed.checks[0]!.record = { passed: false, status: 'failed', theoremName: 'helper', checkedAt: firstAt, @@ -515,31 +473,20 @@ describe('real collaboration HTTP and job boundaries without model calls', () => for (const text of ['Why did it fail?', 'Nat.zero_add', 'Earlier answer.', key]) expect(stored).not.toContain(text); }); - it.each(['queued', 'unknown', 'receipt-error'] as const)('keeps host outcomes that arrive before a %s worker receipt', async transport => { + it.each(['queued', 'unknown', 'receipt-error'] as const)('keeps host approval outcomes that arrive before a %s worker receipt', async transport => { const runner = new FixtureRunner(), jobs = new WebJobs(runner, { concurrency: 1, queueLimit: 2 }); closing.push(() => jobs.close()); - const run = jobs.create('alice', input(), provider); await tick(); - let current = observation(run.id); + const run = jobs.create('alice', approvalInput(), provider); await tick(); + let current = approvalObservation(run.id); runner.calls[0].send({ type: 'observation', observation: current }); - for (const outcome of ['applied', 'rejected', 'delivered'] as const) { + for (const outcome of ['rejected', 'approved'] as const) { const id = `${outcome}-${transport}`, before = current; - const command = outcome === 'delivered' - ? { type: 'guidance' as const, guidance: { id, recipient: { kind: 'lead' as const }, text: 'Check the quantifier.', - observationRef: { sequence: before.sequence, stateDigest: before.snapshot.stateDigest } } } - : { type: 'edit' as const, proposal: { ...before.plan!, id } }; + const planVersion = 'plan-1'; + const command = { type: 'plan-approval' as const, approval: { id, planVersion } }; runner.commandResult = () => { - current = observation(run.id, before.sequence + 1); - current.inspection.edits = [...before.inspection.edits]; current.guidance = [...before.guidance]; - if (command.type === 'guidance') { - current.guidance.push({ ...command.guidance, status: 'delivered', deliveredTo: ['engineer'], - createdAt: before.observedAt, updatedAt: current.observedAt }); - } else { - current.inspection.edits.push(outcome === 'applied' - ? { id, status: 'applied', baseVersion: before.plan!.baseVersion, planVersion: 'plan-2', affectedTasks: ['helper'], - recheck: { status: 'complete', tasks: [{ taskId: 'helper', taskDigest: 'version-1', status: 'conditional', - lastCheck: { commit: 'a'.repeat(40), sourceDigest: 'b'.repeat(64), environmentDigest: 'env', - passed: true, conditional: true, receiptIds: ['fixture-check'] } }] } } - : { id, status: 'rejected', baseVersion: before.plan!.baseVersion, reason: 'math_edit_version_conflict' }); - } + current = approvalObservation(run.id, before.sequence + 1); + const approval = current.inspection.planApproval!; + if (outcome === 'rejected') approval.rejections = [{ id, planVersion, reason: 'math_plan_approval_version_conflict', at: 5 }]; + else Object.assign(approval, { status: 'approved', approvedId: id, approvedVersion: planVersion, approvedAt: 5 }); runner.calls[0].send({ type: 'observation', observation: current }); if (transport === 'receipt-error') throw new Error('Fixture receipt timed out'); return { id, status: transport, reason: 'Worker has not confirmed the host outcome', observation: before }; @@ -547,10 +494,8 @@ describe('real collaboration HTTP and job boundaries without model calls', () => const first = jobs.command('alice', run.id, command), duplicate = jobs.command('alice', run.id, command); const result = await first; expect(await duplicate).toEqual(result); expect(result.status).toBe(outcome); - expect(result.reason).toBe(outcome === 'rejected' ? 'math_edit_version_conflict' : undefined); - expect(result.observation).toEqual(current); expect(result.commandDigest).toMatch(/^[a-f0-9]{64}$/u); - if (command.type === 'guidance') expect(result.guidance).toEqual(current.guidance.at(-1)); - else expect(result.edit).toEqual(current.inspection.edits.at(-1)); + expect(result.reason).toBe(outcome === 'rejected' ? 'math_plan_approval_version_conflict' : undefined); + expect(result.observation).toEqual(current); expect(result.commandDigest).toBe(mathDigest(canonicalMathJson(command))); expect(result).toEqual(jobs.commandReceipt('alice', run.id, id)); expect(jobs.storage.getCommand('alice', run.id, id)?.status).toBe(transport === 'receipt-error' ? 'unknown' : transport); const sentCommands = runner.commands.length; @@ -558,63 +503,6 @@ describe('real collaboration HTTP and job boundaries without model calls', () => expect(jobs.commandReceipt('alice', run.id, id + '-other')).toBeUndefined(); expect(run.result).toBeUndefined(); expect(isAcceptedRun(run)).toBe(false); } - const saved = jobs.storage.listCommands('alice', run.id), beforePreview = current; - runner.commandResult = undefined; - const preview = await jobs.command('alice', run.id, { type: 'edit-preview', proposal: { ...current.plan!, id: `applied-${transport}` } }); - expect(preview.status).toBe('validated'); expect(preview.edit).toBeUndefined(); - expect(jobs.storage.listCommands('alice', run.id)).toEqual(saved); expect(run.observation).toEqual(beforePreview); - runner.calls[0].finish(); await tick(); - }); - - it('returns observed outcomes and full rechecks in POST receipts even when worker acknowledgements lag or fail', async () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-command-race-http-')); roots.push(root); - const reservation = net.createServer(); await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve)); - const port = (reservation.address() as net.AddressInfo).port; - await new Promise(resolve => reservation.close(() => resolve())); - const base = `http://127.0.0.1:${port}`, runner = new FixtureRunner(); - const service = createWebService({ ...readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: base }), - staticRoot: root }, runner); closing.push(() => service.close()); - await new Promise(resolve => service.server.listen(port, '127.0.0.1', resolve)); - const session = await fetch(base + '/api/session'), cookie = session.headers.get('set-cookie')!.split(';')[0]; - const owner = cookie.slice('theoremos_session='.length), csrf = (await session.json()).csrfToken; - const request = (route: string, body?: unknown) => fetch(base + route, { method: body ? 'POST' : 'GET', - headers: { Cookie: cookie, 'X-CSRF-Token': csrf, ...(body ? { 'Content-Type': 'application/json' } : {}) }, - body: body ? JSON.stringify(body) : undefined }); - const run = (await (await request('/api/runs', input())).json()).run; await tick(); - const prefix = '/api/runs/' + run.id; - let current = observation(run.id); - runner.calls[0].send({ type: 'observation', observation: current }); - for (const outcome of ['applied', 'rejected', 'delivered', 'unknown'] as const) { - const id = `http-race-${outcome}`, before = current; - const body = outcome === 'delivered' ? { id, recipient: { kind: 'lead' }, text: 'Inspect the conditional premise.', - observationRef: { sequence: before.sequence, stateDigest: before.snapshot.stateDigest } } : { ...before.plan!, id }; - const route = prefix + (outcome === 'delivered' ? '/guidance' : '/edits'); - runner.commandResult = command => { - current = observation(run.id, before.sequence + 1); - current.inspection.edits = [...before.inspection.edits]; current.guidance = [...before.guidance]; - if (command.type === 'guidance') current.guidance.push({ ...command.guidance, status: 'delivered', - deliveredTo: ['engineer'], createdAt: before.observedAt, updatedAt: current.observedAt }); - else current.inspection.edits.push(outcome === 'rejected' - ? { id, status: 'rejected', baseVersion: 'plan-1', reason: 'math_edit_version_conflict' } - : { id: outcome === 'unknown' ? id + '-other' : id, status: 'applied', baseVersion: 'plan-1', planVersion: 'plan-2', - affectedTasks: ['helper'], recheck: { status: 'complete', tasks: [{ taskId: 'helper', taskDigest: 'version-1', status: 'conditional' }] } }); - runner.calls[0].send({ type: 'observation', observation: current }); - if (outcome === 'delivered') throw new Error('Fixture receipt timed out'); - return { id, status: outcome === 'applied' ? 'queued' : 'unknown', observation: before }; - }; - const submitted = await request(route, body); expect(submitted.status).toBe(200); - const result = (await submitted.json()).receipt; - expect(result.status).toBe(outcome); expect(result.observation).toEqual(current); - if (outcome === 'applied' || outcome === 'rejected') expect(result.edit).toEqual(current.inspection.edits.at(-1)); - if (outcome === 'delivered') expect(result.guidance).toEqual(current.guidance.at(-1)); - if (outcome === 'unknown') expect(result.edit).toBeUndefined(); - const savedCommands = service.storage.listCommands(owner, run.id), sentCommands = runner.commands.length; - const queried = await request(prefix + '/commands/' + id); expect(queried.status).toBe(200); - expect((await queried.json()).receipt).toEqual(result); - expect((await (await request(route, body)).json()).receipt).toEqual(result); - expect(service.storage.listCommands(owner, run.id)).toEqual(savedCommands); expect(runner.commands).toHaveLength(sentCommands); - expect((await request(prefix + '/commands/' + id + '-other')).status).toBe(404); - } runner.calls[0].finish(); await tick(); }); @@ -656,8 +544,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => expect(crossOwner.status).toBe(200); expect((await crossOwner.json()).runs).toEqual([]); expect((await fetch(base + '/api/runs', { headers: { 'If-None-Match': initialTag } })).status).toBe(401); - const created = await write(alice, '/api/runs', input()); expect(created.status).toBe(201); - const run = (await created.json()).run; await tick(); + const run = service.jobs.create(alice.cookie.slice('theoremos_session='.length), input(), provider); await tick(); let current = await changed(alice.cookie, initialTag); expect(current.runs.map((item: { id: string }) => item.id)).toEqual([run.id]); await unchanged(bob.cookie, bobInitialTag); @@ -669,8 +556,7 @@ describe('real collaboration HTTP and job boundaries without model calls', () => runner.calls[0].send({ type: 'observation', observation: structuredClone(newer) }); await unchanged(alice.cookie, current.etag); - const bobCreated = await write(bob, '/api/runs', input()); expect(bobCreated.status).toBe(201); - const bobRun = (await bobCreated.json()).run; await tick(); + const bobRun = service.jobs.create(bob.cookie.slice('theoremos_session='.length), input(), provider); await tick(); const bobCurrent = await changed(bob.cookie, bobInitialTag); expect(bobCurrent.runs.map((item: { id: string }) => item.id)).toEqual([bobRun.id]); await unchanged(alice.cookie, current.etag); @@ -723,16 +609,16 @@ describe('real collaboration HTTP and job boundaries without model calls', () => const request = (route: string, body?: unknown) => fetch(base + route, { method: body ? 'POST' : 'GET', headers: { Cookie: cookie, 'X-CSRF-Token': csrf, ...(body ? { 'Content-Type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined }); - const run = (await (await request('/api/runs', input())).json()).run; await tick(); + const run = service.jobs.create(cookie.slice('theoremos_session='.length), input(), provider); await tick(); runner.calls[0].send({ type: 'observation', observation: observation(run.id) }); const prefix = '/api/runs/' + run.id; expect((await (await request(prefix + '/observation')).json()).observation.solverRunId).toBe('solver-fixture'); expect((await fetch(base + prefix + '/observation')).status).toBe(401); const bob = await fetch(base + '/api/session'), bobCookie = bob.headers.get('set-cookie')!.split(';')[0]; expect((await fetch(base + prefix + '/checks/fixture-check', { headers: { Cookie: bobCookie } })).status).toBe(404); - expect((await request(prefix + '/edits/preview', { ...observation(run.id).plan!, id: 'http-edit' })).status).toBe(200); + expect((await request(prefix + '/edits/preview', { ...observation(run.id).plan!, id: 'http-edit' })).status).toBe(409); expect((await fetch(base + prefix + '/guidance', { method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json' }, body: '{}' })).status).toBe(403); - expect((await request(prefix + '/guidance', {})).status).toBe(400); + expect((await request(prefix + '/guidance', {})).status).toBe(409); runner.calls[0].finish(); await tick(); const archived = await request(prefix + '/archive', {}); expect(archived.status).toBe(200); const archive = (await archived.json()).archive; diff --git a/tests/webContinuationIdentity.test.ts b/tests/webContinuationIdentity.test.ts index 8a1ee2dd..8401491e 100644 --- a/tests/webContinuationIdentity.test.ts +++ b/tests/webContinuationIdentity.test.ts @@ -12,7 +12,7 @@ afterEach(async () => { await Promise.all(closing.splice(0).map(close => close() describe('web continuation frozen source identity', () => { it('freezes the actually selected saved source without changing request replay or the worker input', async () => { const calls: WorkerInput[] = [], port = await freePort(), origin = `http://127.0.0.1:${port}`; - const runner: WebRunner = { async readiness() { return { ready: true, message: 'Offline fixture' }; }, + const runner: WebRunner = { async readiness() { return { ready: true, nativeTeam: true, message: 'Offline fixture' }; }, async run(input, send) { calls.push(structuredClone(input)); send({ type: 'result', result: { status: 'limit_reached', proof: '', report: {} } }); } }; const config = readWebConfig({ THEOREMOS_WEB_PORT: String(port), THEOREMOS_WEB_PUBLIC_URL: origin }); const service = createWebService(config, runner, { sample: null }); closing.push(() => service.close()); @@ -57,7 +57,8 @@ describe('web continuation frozen source identity', () => { const from: WebContinuation = { runId: parent.id, taskId: target.taskId, commit: target.commit, label: 'Saved version', taskVersion: matching.checks.find((check: { passed: boolean }) => check.passed).taskVersion }; const expected = { ...from, sourceDigest: target.sourceDigest, environmentDigest: target.environmentDigest, file: target.file }; - const body = { ...input, task: 'Continued offline', continueFrom: from, requestId: 'freeze-source-once' }; + const continuedInput = { ...input, workers: 1, coordination: 'independent' as const, task: 'Continued offline', continueFrom: from }; + const body = { ...continuedInput, requestId: 'freeze-source-once' }; const response = await post(body); expect(response.status).toBe(201); const continued = (await response.json()).run as WebRun; expect(continued.continueFrom).toEqual(expected); expect(continued.continueFrom).not.toHaveProperty('source'); @@ -65,6 +66,7 @@ describe('web continuation frozen source identity', () => { expect(body.continueFrom).toEqual(from); await new Promise(resolve => setImmediate(resolve)); const worker = calls.find(call => call.id === continued.id)!; + expect(worker.input.nativeTeamCapacity).toBe(3); expect(worker.input.continueFrom).toEqual(from); expect(worker.continuation).toEqual({ ...expected, source: target.source }); const { taskVersion: _taskVersion, ...legacyFrom } = from; @@ -82,7 +84,7 @@ describe('web continuation frozen source identity', () => { const wrong = await post({ ...body, requestId: 'forged-identity', continueFrom: { ...from, taskVersion: 'not-the-selected-version' } }); expect(wrong.status).toBe(409); const restart = new WebJobs(runner, { concurrency: 1, queueLimit: 8 }, { storage: service.storage }); closing.push(() => restart.close()); - expect(restart.replay(owner, { ...input, task: body.task, continueFrom: from }, provider, body.requestId)?.id).toBe(continued.id); + expect(restart.replay(owner, continuedInput, provider, body.requestId)?.id).toBe(continued.id); expect(restart.get(owner, continued.id)?.continueFrom).toEqual(expected); }); }); diff --git a/tests/webConversations.test.ts b/tests/webConversations.test.ts index 5513fd49..36384a72 100644 --- a/tests/webConversations.test.ts +++ b/tests/webConversations.test.ts @@ -930,7 +930,7 @@ describe('conversation HTTP boundary with local fake provider only', () => { const guidance = guidanceInput(); expect((await fetch(route + '/guidance', { method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json' }, body: JSON.stringify(guidance) })).status).toBe(403); expect((await fetch(route + '/guidance', { method: 'POST', headers: { ...headers, Cookie: otherCookie, 'X-CSRF-Token': otherSession.csrfToken }, body: JSON.stringify(guidance) })).status).toBe(404); - expect((await fetch(route + '/guidance', { method: 'POST', headers, body: JSON.stringify({ ...guidance, receipt: { status: 'delivered' } }) })).status).toBe(400); + expect((await fetch(route + '/guidance', { method: 'POST', headers, body: JSON.stringify({ ...guidance, receipt: { status: 'delivered' } }) })).status).toBe(409); expect((await (await fetch(route, { headers })).json() as { conversation: WebConversation }).conversation.messages).toHaveLength(saved.messages.length); const title = { title: ' 我的证明\n 第一版 ' }; expect((await fetch(route, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(title) })).status).toBe(401); diff --git a/tests/webFormalizations.test.ts b/tests/webFormalizations.test.ts index ef90542c..7be572db 100644 --- a/tests/webFormalizations.test.ts +++ b/tests/webFormalizations.test.ts @@ -32,7 +32,8 @@ class Runner implements WebRunner { runs: WorkerInput[] = []; proofs: { input: WorkerInput; signal: AbortSignal; send(message: WorkerMessage): void; resolve(): void }[] = []; ready = true; - async readiness() { return { ready: this.ready, message: 'Disposable test runner' }; } + nativeTeam = true; + async readiness() { return { ready: this.ready, nativeTeam: this.nativeTeam, message: 'Disposable test runner' }; } run(input: WorkerInput, send: (message: WorkerMessage) => void, signal: AbortSignal) { this.runs.push(input); return new Promise(resolve => { @@ -503,7 +504,8 @@ describe('online formalization ownership and evidence handoff', () => { expect(completed).toMatchObject({ status: 'confirmed', confirmation: 'automatic', workflow: 'solve' }); expect(completed.runId).toMatch(/^[a-f0-9-]{36}$/u); expect(completed.researchError).toBeUndefined(); expect(runner.runs).toHaveLength(1); - expect(runner.runs[0].input).toMatchObject({ ...webDefaults, effort: value.researchEffort ?? value.effort, environment: 'standard', apiKey: KEY, + expect(runner.runs[0].input).toMatchObject({ ...webDefaults, coordination: 'independent', nativeTeamCapacity: 3, + effort: value.researchEffort ?? value.effort, environment: 'standard', apiKey: KEY, providerId: 'sub2api', model: 'deepseek-flash', source: evidence.candidate.source, formalizationId: value.id }); expect(runner.runs[0].input).toMatchObject({ maxRunSeconds: 0, maxTotalTokens: 0, maxTurns: 0 }); expect(runner.runs[0].formalization).toEqual(evidence); @@ -555,7 +557,7 @@ describe('online formalization ownership and evidence handoff', () => { expect((await (await request(alice, route + '/research', {})).json()).formalization.runId).toBe(started[0].runId); await settle(); expect(runner.runs).toHaveLength(1); expect(runner.inputs).toHaveLength(1); expect(runner.runs[0].input).toMatchObject({ ...research, providerId: 'openai', model: 'gpt-6.1-sol', effort: 'max', apiKey: KEY, - workers: 2, coordination: 'cooperative', planApproval: true, environment: 'standard', source: evidence.candidate.source, formalizationId: value.id }); + workers: 1, coordination: 'independent', nativeTeamCapacity: 3, planApproval: true, environment: 'standard', source: evidence.candidate.source, formalizationId: value.id }); expect(runner.runs[0].formalization).toEqual(evidence); const run = (await (await request(alice, `/api/runs/${started[0].runId}`)).json()).run as WebRun; expect(run.formalization).toMatchObject({ original: body.original, evidenceSha256: review.report!.evidenceSha256, @@ -600,7 +602,7 @@ describe('online formalization ownership and evidence handoff', () => { expect(restored.report?.evidenceSha256).toBe(digest); expect(restored.confirmedAt).toBe(confirmed.confirmedAt); await settle(); expect(runner.inputs).toHaveLength(0); expect(runner.runs).toHaveLength(1); expect(runner.runs[0].input).toMatchObject({ ...research, providerId: 'openai', model: 'gpt-6.1-sol', apiKey: retryKey, - workers: 2, coordination: 'cooperative', planApproval: true, source: evidence.candidate.source, environment: 'standard' }); + workers: 1, coordination: 'independent', nativeTeamCapacity: 3, planApproval: true, source: evidence.candidate.source, environment: 'standard' }); expect(runner.runs[0].formalization).toEqual(evidence); await restart(); expect((await (await request(alice, route + '/research', {})).json()).formalization.runId).toBe(restored.runId); @@ -887,6 +889,26 @@ describe('online formalization ownership and evidence handoff', () => { expect((await fetch(base + '/readyz')).status).toBe(200); }); + it('reports when a legacy worker can compile statements but cannot run the native proof stage', async () => { + runner.nativeTeam = false; + const alice = await client(); + expect((await fetch(base + '/healthz')).status).toBe(200); + const readiness = await fetch(base + '/readyz'); + expect(readiness.status).toBe(503); + expect(await readiness.json()).toMatchObject({ ready: false, maintenance: false, nativeTeam: false }); + const product = await (await fetch(base + '/api/product/status')).json(); + expect(product.service).toMatchObject({ reachable: true, runtimeReady: false }); + const capabilities = async () => (await (await request(alice, '/api/formalizations')).json()).generation; + expect(await capabilities()).toMatchObject({ available: true, solveAvailable: false }); + expect((await request(alice, '/api/formalizations', { ...body, solve: true })).status).toBe(503); + expect(runner.inputs).toHaveLength(0); + await create(alice); + expect(runner.inputs).toHaveLength(1); + runner.nativeTeam = true; + expect((await fetch(base + '/readyz')).status).toBe(200); + expect(await capabilities()).toMatchObject({ available: true, solveAvailable: true }); + }); + it('keeps the independent fidelity policy mandatory on legacy reviewed records', async () => { const alice = await client(), value = await create(alice), pending = runner.pending.at(-1)!; const evidence = webReviewedFormalizationEvidence({ ...pending.input, reviewMode: undefined }); diff --git a/tests/webJobs.test.ts b/tests/webJobs.test.ts index c1a29578..e21b2333 100644 --- a/tests/webJobs.test.ts +++ b/tests/webJobs.test.ts @@ -7,6 +7,7 @@ import { webLimits, type WebProvider, type WebResult, type WebRunInput, type Wor import { mathDigest } from '../src/math/mathRuntimeIo'; import { buildTheoremKnowledge, type KnowledgeCandidate } from '../src/solver/theoremKnowledge'; import { mailsCompletion } from '../apps/web/completionMail'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; const provider: WebProvider = { id: 'openai', name: 'OpenAI', baseUrl: 'https://api.openai.com/v1' }; const input = (apiKey = 'sk-test-job-secret'): WebRunInput => ({ providerId: provider.id, apiKey, @@ -161,6 +162,33 @@ describe('web job ownership, scheduling and secret lifetime without provider cal runner.calls[0].finish({ status: 'incomplete', proof: '', report: {} }); await tick(); }); + it('keeps the original native route approval and its receipt after installing a library', async () => { + const { jobs, runner } = setup(), run = jobs.create('owner', { ...input(), ...webAgentTeamPreset(), planApproval: true }, provider); + await tick(); + const send = runner.calls[0].send; + const nativeObservation = (solverRunId: string, sequence: number) => { + const snapshot = observation(run.id, solverRunId, sequence); + snapshot.inspection.configuration = { researchMode: 'skill', researchSkill: { name: 'fixture', digest: mathDigest('fixture'), loading: 'native' }, + researchDelegation: { mode: 'team', maxAgents: 3 } } as WebObservation['inspection']['configuration']; + return snapshot; + }; + const initial = nativeObservation('solver-first', 1), planVersion = 'original-plan', id = 'approved-plan'; + initial.inspection.planApproval = { required: true, status: 'approved', approvedId: id, planVersion, + approvedVersion: planVersion, approvedAt: 1_800_000_000_000, rejections: [], leadRevising: false }; + jobs.storage.saveCommand('owner', run.id, id, { id, status: 'queued', planVersion }); + send({ type: 'observation', observation: initial }); + send({ type: 'library_restart', previousSolverRunId: 'solver-first', solverRunId: 'solver-next', round: 1 }); + const next = nativeObservation('solver-next', 2); + next.inspection.planApproval = { required: false, status: 'not-required', rejections: [], leadRevising: false }; + send({ type: 'observation', observation: next }); + const persisted = jobs.storage.getRun('owner', run.id)!; + expect(persisted.initialPlanApproval).toEqual({ solverRunId: 'solver-first', receipt: initial.inspection.planApproval }); + expect(persisted.observation?.solverRunId).toBe('solver-next'); + expect(jobs.commandReceipt('owner', run.id, id)).toMatchObject({ id, status: 'approved', planVersion }); + expect(run.result).toBeUndefined(); + runner.calls[0].finish({ status: 'incomplete', proof: '', report: {} }); await tick(); + }); + it('saves the new round evidence delivered during cancellation without accepting a late result', async () => { const { jobs, runner } = setup(), run = jobs.create('owner', input(), provider); await tick(); diff --git a/tests/webKnowledgeApi.test.ts b/tests/webKnowledgeApi.test.ts index 1d2c2947..55cbfd21 100644 --- a/tests/webKnowledgeApi.test.ts +++ b/tests/webKnowledgeApi.test.ts @@ -28,11 +28,11 @@ const candidate = (name: string): KnowledgeCandidate => ({ }); const input = (): WebRunInput => ({ providerId: 'openai', apiKey: 'sk-disposable-http-fixture', model: 'never-called', effort: 'high', source: 'theorem example : True := by sorry', task: 'Offline HTTP fixture only', maxTurns: 1, - maxRunSeconds: 30, workers: 2, coordination: 'cooperative', environment: 'standard' }); + maxRunSeconds: 30, workers: 1, coordination: 'independent', environment: 'standard' }); class ApiFixtureRunner implements WebRunner { calls: WorkerInput[] = []; - async readiness() { return { ready: true, message: 'Offline fixture ready' }; } + async readiness() { return { ready: true, nativeTeam: true, message: 'Offline fixture ready' }; } async run(value: WorkerInput, send: (message: WorkerMessage) => void) { this.calls.push(value); send({ type: 'result', result: { status: 'incomplete', proof: '', report: {} } }); @@ -177,8 +177,8 @@ describe('knowledge and module configuration through the real HTTP service witho const response = await request(alice, '/api/module-plans', { name: 'HTTP scheme', plan }); expect(response.status).toBe(200); const saved = (await response.json()).plan; expect((await get(bob, '/api/module-plans')).plans).toEqual([]); - const runResponse = await request(alice, '/api/runs', { ...input(), modulePlan: saved.plan }); - expect(runResponse.status).toBe(201); const run = (await runResponse.json()).run; + const run = service.jobs.create(alice.owner, { ...input(), workers: 2, coordination: 'cooperative', modulePlan: saved.plan }, + config.providers.find(provider => provider.id === 'openai')!); const update = await request(alice, '/api/module-plans', { id: saved.id, baseUpdatedAt: saved.updatedAt, name: saved.name, plan: { scheduler: 'continuation', context: 'full', custom: [] } }); expect(update.status).toBe(200); const changed = (await update.json()).plan; diff --git a/tests/webLibraryResearch.test.ts b/tests/webLibraryResearch.test.ts index 47b7f4a7..2363203d 100644 --- a/tests/webLibraryResearch.test.ts +++ b/tests/webLibraryResearch.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { runWebLibraryResearch, type WebLibraryRound } from '../apps/web/libraryResearch'; import { prepareWebProblem } from '../apps/web/formalizationSeed'; import { webDefaults } from '../apps/web/config'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; import type { WebRunInput, WorkerInput } from '../apps/web/shared'; import { formalizationDigest, readFormalizationArtifact } from '../src/math/formalization'; import { LIBRARY_PACK_SCHEMA, type LibraryPack } from '../src/math/libraryPacks'; @@ -12,6 +13,7 @@ import { mathDigest, readMathJson, readMathText, writeMathJsonDurable } from '.. import { writeSolverRunState } from '../src/solver/archive'; import { readContinuationInput } from '../src/solver/continuationInput'; import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; +import { publishNativeApprovalPlan } from '../src/solver/planApproval'; import { git, readSolverProblem } from '../src/solver/problem'; import { approvedFormalization } from './helpers/approvedFormalizationFixture'; import { solverState } from './helpers/solver'; @@ -77,6 +79,41 @@ function finishRound(f: Fixture, round: WebLibraryRound, names?: string[], used: } describe('Web library research supervision without provider calls', () => { + it('keeps the approved route with the next two library rounds without requesting approval again', async () => { + const f = fixture({ ...webAgentTeamPreset(), planApproval: true }); + let originalVersion: string | undefined; + const gates: (boolean | undefined)[] = []; + const result = await runWebLibraryResearch({ ...f, run: async round => { + gates.push(round.planApproval); + const completed = finishRound(f, round, + round.round === 0 ? ['Research.desired'] : round.round === 1 ? ['Research.final_hint'] : undefined); + if (round.round === 0) { + const { state, stateFile } = completed; + state.planApproval = true; + originalVersion = publishNativeApprovalPlan(state, { operation: 'publish_plan', goals: [ + { theoremName: 'Original.goal', objective: 'Find the relevant library lemma, then prove the original goal.' }, + ] }, () => {}, () => {}).planVersion; + Object.assign(state.cooperation!.planApproval!, { approvedAt: 1001, approvedId: 'owner-approval', approvedVersion: originalVersion }); + writeSolverRunState(stateFile, state); + } else { + const continuation = readContinuationInput(round.continuationFile!, { taskDigest: mathDigest(readMathText(round.seed.taskFile)), + problemReceiptDigest: completed.problem.receiptDigest }); + const route = continuation.manifest.attachments.find(item => item.provenance.source === `Approved initial route, version ${originalVersion}`); + expect(route?.provenance).toMatchObject({ evidence: 'recorded-not-replayed', runId: 'solver-round-0' }); + expect(continuation.contents.get(route!.sha256)).toContain('Find the relevant library lemma, then prove the original goal.'); + } + } }); + expect(gates).toEqual([true, false, false]); + expect(result.raw.status).toBe('incomplete'); + }); + + it('refuses a native library continuation when the initial route lacks approval', async () => { + const f = fixture({ ...webAgentTeamPreset(), planApproval: true }); + const run = vi.fn(async (round: WebLibraryRound) => { finishRound(f, round, ['Research.desired']); }); + await expect(runWebLibraryResearch({ ...f, run })).rejects.toThrow('math_library_request_plan_not_approved'); + expect(run).toHaveBeenCalledTimes(1); + }); + it('keeps the exact shared pack and original imports through repeated built-in library installations', async () => { const shared = 'Submission/Library/Shared/Result.lean', sharedSource = 'namespace Shared\nlemma result : True := by trivial\nend Shared\n'; const frozenPack: LibraryPack = { ...pack, modules: [pack.modules[0]!, { file: shared, source: sharedSource, diff --git a/tests/webOperationsApi.test.ts b/tests/webOperationsApi.test.ts index 1d3360b1..c5ed0174 100644 --- a/tests/webOperationsApi.test.ts +++ b/tests/webOperationsApi.test.ts @@ -15,7 +15,8 @@ const input = (): WebRunInput => ({ providerId: 'openai', apiKey: 'sk-operations maxRunSeconds: 30, workers: 1, coordination: 'cooperative' }); class HeldRunner implements WebRunner { ready = true; - async readiness() { return { ready: this.ready, message: 'Local fixture worker' }; } + nativeTeam = true; + async readiness() { return { ready: this.ready, nativeTeam: this.nativeTeam, message: 'Local fixture worker' }; } private hold(signal: AbortSignal) { return new Promise((_resolve, reject) => { signal.throwIfAborted(); @@ -110,7 +111,7 @@ describe('administrator operations HTTP API', () => { expect((await maintenance(admin, true)).status).toBe(200); const ready = await request('/readyz'); expect(ready.status).toBe(503); - expect(await ready.json()).toEqual({ ready: false, maintenance: true, commit: config.sourceCommit }); + expect(await ready.json()).toEqual({ ready: false, maintenance: true, nativeTeam: true, commit: config.sourceCommit }); expect((await request('/healthz')).status).toBe(200); for (const route of ['/api/runs', '/api/formalizations', '/api/precheck']) expect((await request(route, admin, {})).status).toBe(503); @@ -119,6 +120,9 @@ describe('administrator operations HTTP API', () => { expect(await status(admin)).toMatchObject({ maintenance: true, queues: { research: { running: 1, queued: 0 } } }); expect((await maintenance(admin, false)).status).toBe(200); expect((await request('/readyz')).status).toBe(200); + runner.nativeTeam = false; + expect(await status(admin)).toMatchObject({ maintenance: false, ready: false }); + runner.nativeTeam = true; runner.ready = false; expect((await request('/readyz')).status).toBe(503); expect(await status(admin)).toMatchObject({ maintenance: false, ready: false }); diff --git a/tests/webResearchApi.test.ts b/tests/webResearchApi.test.ts index 63553406..4840c604 100644 --- a/tests/webResearchApi.test.ts +++ b/tests/webResearchApi.test.ts @@ -6,7 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createWebService } from '../apps/web/server'; import { readWebConfig } from '../apps/web/config'; import { DockerWebRunner, type WebRunner } from '../apps/web/runner'; -import type { WebCommand, WebCommandResult, WebGuidanceRecord, WebObservation } from '../apps/web/collaboration'; +import type { WebCommand, WebCommandResult, WebObservation } from '../apps/web/collaboration'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; import type { WebResult, WebRunInput, WorkerInput, WorkerMessage } from '../apps/web/shared'; import type { WebPrecheckRunner } from '../apps/web/precheck'; import type { ResearchAsset, ResearchAssetPreview, ResearchAssetRelease, ResearchPublication } from '../apps/web/researchAssetTypes'; @@ -54,10 +55,18 @@ class ResearchFixtureRunner implements WebRunner { private observations = new Map(); private sends = new Map void>(); private completions = new Map void>(); - async readiness() { return { ready: true, message: 'Disposable fixture' }; } + async readiness() { return { ready: true, nativeTeam: false, message: 'Disposable fixture' }; } async run(value: WorkerInput, send: (message: WorkerMessage) => void, signal: AbortSignal) { this.calls.push(structuredClone(value)); this.sends.set(value.id, send); - const observed = observation(value.id); this.observations.set(value.id, observed); + const observed = observation(value.id); + if (value.input.nativeTeamCapacity) Object.assign(observed.inspection.configuration, { + workers: 1, coordination: 'independent', researchMode: 'skill', + researchSkill: { name: 'theoremos-research', digest: mathDigest('fixture skill'), loading: 'native' }, + researchDelegation: { mode: 'team', maxAgents: value.input.nativeTeamCapacity }, + }); + if (value.input.planApproval) observed.inspection.planApproval = { required: true, status: 'pending', planVersion: 'plan-v1', + rejections: [], leadRevising: false }; + this.observations.set(value.id, observed); send({ type: 'progress', event: 'solve_started', message: 'PRIVATE_WORKER_LOG' }); send({ type: 'observation', observation: structuredClone(observed) }); await new Promise(resolve => { @@ -86,14 +95,7 @@ class ResearchFixtureRunner implements WebRunner { this.commands.push({ runId, command: structuredClone(command) }); const observed = this.observations.get(runId)!; let receipt: WebCommandResult; - if (command.type === 'guidance') { - const guidance: WebGuidanceRecord = { ...command.guidance, status: 'delivered', createdAt: at, updatedAt: at, deliveredTo: ['lead'] }; - observed.guidance.push(guidance); receipt = { id: guidance.id, status: 'delivered', guidance }; - } else if (command.type === 'edit') { - observed.inspection.planVersion = 'plan-v2'; - observed.inspection.edits.push({ id: command.proposal.id, status: 'applied', planVersion: 'plan-v2', affectedTasks: ['target'] }); - receipt = { id: command.proposal.id, status: 'queued' }; - } else if (command.type === 'plan-approval') { + if (command.type === 'plan-approval') { observed.inspection.planApproval = { required: true, status: 'approved', planVersion: command.approval.planVersion, approvedId: command.approval.id, approvedVersion: command.approval.planVersion, rejections: [], leadRevising: false }; receipt = { id: command.approval.id, status: 'approved', planVersion: command.approval.planVersion }; @@ -142,14 +144,24 @@ describe('collaborative research through the actual HTTP service', () => { const response = await request(client, route, body, method), result = await response.json(); expect(response.status, `${route}: ${JSON.stringify(result)}`).toBe(status); return result.item; } - async function newRun(client: Client, changes: object = {}) { - const response = await request(client, '/api/runs', { ...input(), ...changes }), result = await response.json(); - expect(response.status, JSON.stringify(result)).toBe(201); - for (let attempt = 0; attempt < 10 && !service.jobs.get(client.owner, result.run.id)?.observation; attempt++) + async function newRun(client: Client, changes: Partial & { requestId?: string } = {}) { + const submitted = { ...input(), ...changes }; + let run: WebRun; + if (submitted.researchSelection || submitted.workers === 1) { + const response = await request(client, '/api/runs', { ...submitted, workers: 1, coordination: 'independent' }); + const result = await response.json(); + expect(response.status, JSON.stringify(result)).toBe(201); + run = result.run; + } else { + // The project still supports historical cooperative evidence and commands. + run = service.jobs.create(client.owner, { ...submitted, source: submitted.source.trim() }, + { id: 'openai', name: 'Research fixture', baseUrl: 'https://api.openai.com/v1' }); + } + for (let attempt = 0; attempt < 10 && !service.jobs.get(client.owner, run.id)?.observation; attempt++) await new Promise(resolve => setImmediate(resolve)); - expect(service.jobs.get(client.owner, result.run.id)?.observation).toBeDefined(); return result.run; + expect(service.jobs.get(client.owner, run.id)?.observation).toBeDefined(); return run; } - async function projectWithRun(alice: Client, bob: Client, visibility = 'members') { + async function projectWithRun(alice: Client, bob: Client, visibility = 'members', changes: Partial = {}) { const source = `${original}\n`; let project = await item(alice, '/api/research/theorems', { requestId: 'create-project', title: 'True theorem', visibility }, 'POST', 201); @@ -158,7 +170,7 @@ describe('collaborative research through the actual HTTP service', () => { { requestId: 'member-bob', expectedRevision: project.revision, role: 'collaborator' }, 'PUT'); project = await item(alice, route + '/versions', { requestId: 'statement-v1', expectedRevision: project.revision, statement: 'Prove True', source, environment: 'standard' }, 'POST', 201); - const run = await newRun(alice, { source }); + const run = await newRun(alice, { source, ...changes }); project = await item(alice, route + '/runs', { requestId: 'bind-run', expectedRevision: project.revision, runId: run.id, statementVersionId: project.versions[0].id, exposure: visibility === 'public' ? 'public' : 'members', grants: { guidance: true, edit: true, approve: true, proof: true } }, 'POST', 201); @@ -208,9 +220,9 @@ describe('collaborative research through the actual HTTP service', () => { const observed = service.jobs.get(alice.owner, run.id)!.observation!; const target = { runId: run.id, statementVersionId: project.versions[0].id, taskRef: { id: 'target', version: 'task-v1' }, observationRef: { sequence: observed.sequence, stateDigest: observed.snapshot.stateDigest } }; - const feedback = await item(bob, route + '/feedback', { requestId: 'private-assignment-feedback', + const feedback = service.research.projects.submitFeedback(bob.owner, project.id, { requestId: 'private-assignment-feedback', kind: 'guidance', text: 'Private work on this exact task', visibility: 'members', target, - recipient: { kind: 'task', id: 'target' } }, 'POST', 201); + recipient: { kind: 'task', id: 'target' } }); let current = await item(alice, route); current = await item(bob, route + '/assignments', { requestId: 'submit-assignment', expectedRevision: current.revision, target, status: 'submitted', feedbackId: feedback.id }); @@ -260,8 +272,8 @@ describe('collaborative research through the actual HTTP service', () => { : kind === 'plan-approval' ? { planVersion: observed.inspection.planVersion } : kind === 'proof-submission' ? { source: proof, base: { commit, sourceDigest, environmentDigest, file: 'Main.lean' } } : { proposal: { schema: 'deepscientist.math.plan-edit.v1', baseVersion: observed.inspection.planVersion, tasks: observed.plan!.tasks } }; - const submitted = await item(bob, route + '/feedback', - { requestId: `decision-${kind}`, kind, text: 'A contribution to review', target, ...payload }, 'POST', 201); + const submitted = service.research.projects.submitFeedback(bob.owner, project.id, + { requestId: `decision-${kind}`, kind, text: 'A contribution to review', target, ...payload }); expect(submitted.kind).toBe(kind); let current = await item(bob, route); expect(current.permissions.manage).toBe(false); expect(current.runs[0].permissions.manage).toBe(false); @@ -306,11 +318,10 @@ describe('collaborative research through the actual HTTP service', () => { let current = await item(bob, route + '/runs', { requestId: 'bind-ungranted-run', expectedRevision: project.revision, runId: run.id, statementVersionId: project.versions[0].id }, 'POST', 201); const observed = service.jobs.get(bob.owner, run.id)!.observation!; - const feedback = await item(bob, route + '/feedback', { requestId: 'owner-guidance', kind: 'guidance', + const feedback = service.research.projects.submitFeedback(bob.owner, project.id, { requestId: 'owner-guidance', kind: 'guidance', text: 'A run owner contribution', recipient: { kind: 'task', id: 'target' }, target: { runId: run.id, statementVersionId: project.versions[0].id, taskRef: { id: 'target', version: 'task-v1' }, - observationRef: { sequence: observed.sequence, stateDigest: observed.snapshot.stateDigest } } }, 'POST', 201); - expect(feedback.delivery.status).toBe('delivered'); + observationRef: { sequence: observed.sequence, stateDigest: observed.snapshot.stateDigest } } }); current = await item(alice, route); expect(current.permissions.manage).toBe(true); expect(current.runs.find(binding => binding.runId === run.id)?.permissions.guidance).toBe(false); @@ -343,133 +354,51 @@ describe('collaborative research through the actual HTTP service', () => { requestId: 'outsider-discussion-decision', expectedRevision: accepted.revision })).status).toBe(403); }); - it('authorizes a collaborator guidance proxy, persists feedback, deduplicates retries and revokes access', async () => { + it('keeps historical guidance visible through the project while rejecting new guidance', async () => { const alice = await client('Alice'), bob = await client('Bob'), carol = await client('Carol'); const { project, run, route } = await projectWithRun(alice, bob); - expect((await request(carol, route)).status).toBe(404); - expect((await request(bob, `/api/runs/${run.id}`)).status).toBe(404); - const observed = (await request(bob, route + `/runs/${run.id}/observation`)); - expect(observed.status).toBe(200); const observation: WebObservation = (await observed.json()).observation; - const guidance = { id: 'guide-once', recipient: { kind: 'task', id: 'target' }, text: 'Try using helper', - taskRef: { id: 'target', version: 'task-v1' }, observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } }; - const response = await request(bob, route + `/runs/${run.id}/guidance`, guidance); - expect(response.status).toBe(200); const body = await response.json(); - expect(body.receipt.id).toBe(guidance.id); expect(body.receipt.guidance.id).toBe(guidance.id); - expect(body.receipt.observation.guidance[0].id).toBe(guidance.id); - expect(body.feedback.delivery.status).toBe('delivered'); expect(body.feedback.decision.status).toBe('pending'); - expect(body.feedback.author.id).toBe(bob.researcherId); expect(runner.commands).toHaveLength(1); - expect(runner.commands[0]!.command).toMatchObject({ type: 'guidance', guidance: { id: body.feedback.id } }); - const commandRead = await request(bob, route + `/runs/${run.id}/commands/${guidance.id}`); - expect(commandRead.status).toBe(200); expect((await commandRead.json()).receipt.id).toBe(guidance.id); - const guidanceRead = await request(bob, route + `/runs/${run.id}/guidance/${guidance.id}`); - expect(guidanceRead.status).toBe(200); expect((await guidanceRead.json()).guidance.id).toBe(guidance.id); - const observationRead = await request(bob, route + `/runs/${run.id}/observation`); - expect(observationRead.status).toBe(200); const observationBody = await observationRead.json(); - expect(observationBody.observation.guidance[0].id).toBe(guidance.id); - expect(observationBody.run.observation.guidance[0].id).toBe(guidance.id); - expect((await request(bob, route + `/runs/${run.id}/guidance`, guidance)).status).toBe(200); - expect(runner.commands).toHaveLength(1); - expect((await request(bob, route + `/runs/${run.id}/guidance`, { ...guidance, text: 'Changed content' })).status).toBe(409); - const feedback = await item(bob, route + `/feedback/${body.feedback.id}`); - const accepted = await item(alice, route + `/feedback/${feedback.id}/decision`, - { requestId: 'decision', expectedRevision: feedback.revision, status: 'accepted', reason: 'A useful suggestion' }); - expect(accepted.execution.status).toBe('not-started'); - const currentObservation = service.jobs.get(alice.owner, run.id)!.observation!; - const planFeedback = await item(bob, route + '/feedback', { requestId: 'apply-guided-plan', kind: 'plan-edit', text: 'Apply the suggested route', - target: { runId: run.id, statementVersionId: project.versions[0].id, - observationRef: { sequence: currentObservation.sequence, stateDigest: currentObservation.snapshot.stateDigest } }, - proposal: { schema: 'deepscientist.math.plan-edit.v1', baseVersion: 'plan-v1', tasks: currentObservation.plan!.tasks } }, 'POST', 201); - expect(planFeedback.execution.status).toBe('completed'); - const latestGuidance = await item(alice, route + `/feedback/${feedback.id}`); - const linked = await item(alice, route + `/feedback/${feedback.id}/decision`, - { requestId: 'link-applied-plan', expectedRevision: latestGuidance.revision, status: 'accepted', reason: 'Applied to the plan', evidenceRefs: [`edit:${planFeedback.id}`] }); - expect(linked.execution).toMatchObject({ status: 'completed', planVersion: 'plan-v2', resultRefs: [`edit:${planFeedback.id}`] }); - let current = await item(alice, route); - current = await item(alice, route + `/members/${bob.researcherId}`, { requestId: 'remove-bob', expectedRevision: current.revision, role: null }, 'PUT'); - expect((await request(bob, route + `/runs/${run.id}/observation`)).status).toBe(404); - expect((await request(bob, route + `/runs/${run.id}/guidance`, { ...guidance, id: 'after-revocation' })).status).toBe(404); - expect(current.id).toBe(project.id); expect(runner.commands).toHaveLength(2); - }); - - it('recovers a forwarded discussion after an unknown command outcome without sending another command', async () => { - const alice = await client('Alice'), bob = await client('Bob'); - const { project, run, route } = await projectWithRun(alice, bob); - const source = await item(bob, route + '/feedback', { requestId: 'recovery-discussion', - kind: 'discussion', text: 'Try the supporting lemma.', visibility: 'members' }, 'POST', 201); + const runRoute = route + `/runs/${run.id}`; const observed = service.jobs.get(alice.owner, run.id)!.observation!; - const input = { requestId: 'recovery-forward', sourceFeedbackId: source.id, kind: 'guidance', text: source.text, - target: { runId: run.id, statementVersionId: project.versions[0].id, taskRef: { id: 'target', version: 'task-v1' }, - observationRef: { sequence: observed.sequence, stateDigest: observed.snapshot.stateDigest } }, - recipient: { kind: 'task', id: 'target' } }; - vi.spyOn(runner, 'command').mockImplementationOnce(async (runId, command) => { - runner.commands.push({ runId, command: structuredClone(command) }); - throw new Error('Fixture transport closed after submitting the command; outcome is unknown.'); - }); - const lostResponse = await request(alice, route + '/feedback', input); - expect(lostResponse.status).toBe(201); await lostResponse.body?.cancel(); - - const listResponse = await request(alice, route + '/feedback'); - expect(listResponse.status).toBe(200); - const feedback = ((await listResponse.json()).items as ResearchFeedback[]).find(item => item.requestId === input.requestId)!; - expect(feedback).toMatchObject({ sourceFeedbackId: source.id, author: { id: alice.researcherId }, - visibility: 'members', delivery: { status: 'unknown', commandId: feedback.id }, decision: { status: 'pending' } }); - const saved = await request(alice, route + `/runs/${run.id}/commands/${input.requestId}`); - expect(saved.status).toBe(200); expect((await saved.json()).receipt).toMatchObject({ id: input.requestId, status: 'unknown' }); - const replay = await item(alice, route + '/feedback', input, 'POST', 201); - expect(replay.id).toBe(feedback.id); expect(replay.delivery.status).toBe('unknown'); expect(runner.commands).toHaveLength(1); - expect((await request(alice, route + '/feedback', { ...input, text: 'Changed retry content.' })).status).toBe(409); - expect(runner.commands).toHaveLength(1); - - runner.update(run.id, next => { - next.guidance.push({ id: feedback.id, text: input.text, recipient: { kind: 'task', id: 'target' }, - taskRef: input.target.taskRef, observationRef: input.target.observationRef, status: 'delivered', createdAt: at, updatedAt: at, deliveredTo: ['lead'] }); - next.inspection.tasks[0]!.version = 'task-v2'; - }); - const recovered = await item(alice, route + `/feedback/${feedback.id}`); - expect(recovered.delivery.status).toBe('delivered'); expect(recovered.decision.status).toBe('pending'); - const receipt = await request(alice, route + `/runs/${run.id}/commands/${feedback.id}`); - expect(receipt.status).toBe(200); expect((await receipt.json()).receipt.status).toBe('delivered'); - expect((await item(alice, route + '/feedback', input, 'POST', 201)).id).toBe(feedback.id); - expect(runner.commands).toHaveLength(1); - expect(await item(bob, route + `/feedback/${source.id}`)).toEqual(source); - const final = await item(alice, route); - expect(final.feedback.filter(item => item.sourceFeedbackId === source.id).map(item => item.id)).toEqual([feedback.id]); + const observationRef = { sequence: observed.sequence, stateDigest: observed.snapshot.stateDigest }; + const taskRef = { id: 'target', version: 'task-v1' }; + const target = { runId: run.id, statementVersionId: project.versions[0].id, observationRef, taskRef }; + const recipient = { kind: 'task' as const, id: 'target' }; + const feedback = service.research.projects.submitFeedback(bob.owner, project.id, { requestId: 'old-guidance', + kind: 'guidance', text: 'Try using the helper', recipient, target }); + const guidance = { id: feedback.id, text: feedback.text, recipient, taskRef, observationRef }; + service.storage.saveCommand(alice.owner, run.id, guidance.id, { id: guidance.id, status: 'delivered', + guidance: { ...guidance, status: 'delivered', createdAt: at, updatedAt: at, deliveredTo: ['lead'] } }); + const read = await request(bob, runRoute + '/guidance/' + feedback.requestId); + expect(read.status).toBe(200); + expect((await read.json()).guidance).toMatchObject({ id: feedback.requestId, status: 'delivered' }); + const receipt = await request(bob, runRoute + '/commands/' + feedback.requestId); + expect(receipt.status).toBe(200); + expect((await receipt.json()).receipt).toMatchObject({ id: feedback.requestId, status: 'delivered' }); + expect((await request(carol, runRoute + '/guidance/' + feedback.requestId)).status).toBe(404); + expect((await request(bob, runRoute + '/guidance', { ...guidance, id: 'fresh-guidance' })).status).toBe(409); + expect((await request(bob, route + '/feedback', { requestId: 'fresh-feedback', kind: 'guidance', text: guidance.text, recipient, target })).status).toBe(409); + expect(runner.commands).toHaveLength(0); }); - it('replays edit and approval proxy requests after observations advance and rejects changed payloads', async () => { + it('replays native plan approval after observations advance and rejects changed payloads', async () => { const alice = await client('Alice'), bob = await client('Bob'); - const { run, route } = await projectWithRun(alice, bob); + vi.spyOn(runner, 'readiness').mockResolvedValue({ ready: true, nativeTeam: true, message: 'Disposable fixture' }); + const { run, route } = await projectWithRun(alice, bob, 'members', { ...webAgentTeamPreset(), planApproval: true }); const runRoute = route + `/runs/${run.id}`; - const proposal = { schema: 'deepscientist.math.plan-edit.v1', id: 'raw-plan-edit', baseVersion: 'plan-v1', - tasks: service.jobs.get(alice.owner, run.id)!.observation!.plan!.tasks }; - const applied = await request(bob, runRoute + '/edits', proposal); - expect(applied.status).toBe(200); const first = await applied.json(); - expect(first.receipt.id).toBe(proposal.id); expect(first.receipt.edit.id).toBe(proposal.id); - expect(first.receipt.observation.inspection.edits[0].id).toBe(proposal.id); - expect(first.feedback.execution.status).toBe('completed'); - const repeated = await request(bob, runRoute + '/edits', proposal); - expect(repeated.status).toBe(200); expect((await repeated.json()).feedback.id).toBe(first.feedback.id); - expect(runner.commands).toHaveLength(1); - expect((await request(bob, runRoute + '/edits', { ...proposal, - tasks: proposal.tasks.map(task => ({ ...task, objective: 'Changed objective' })) })).status).toBe(409); - - const approval = { id: 'raw-plan-approval', planVersion: 'plan-v2' }; + const approval = { id: 'raw-plan-approval', planVersion: 'plan-v1' }; const approved = await request(bob, runRoute + '/plan-approval', approval); expect(approved.status).toBe(200); const approvedBody = await approved.json(); expect(approvedBody.receipt.id).toBe(approval.id); expect(approvedBody.receipt.observation.inspection.planApproval.approvedId).toBe(approval.id); const approvedAgain = await request(bob, runRoute + '/plan-approval', approval); expect(approvedAgain.status).toBe(200); expect((await approvedAgain.json()).feedback.id).toBe(approvedBody.feedback.id); - expect(runner.commands).toHaveLength(2); - expect((await request(bob, runRoute + '/plan-approval', { ...approval, planVersion: 'plan-v3' })).status).toBe(409); - const savedEdit = await request(bob, runRoute + `/commands/${proposal.id}`); - expect(savedEdit.status).toBe(200); expect((await savedEdit.json()).receipt.edit.id).toBe(proposal.id); + expect(runner.commands).toHaveLength(1); + expect((await request(bob, runRoute + '/plan-approval', { ...approval, planVersion: 'plan-v2' })).status).toBe(409); const savedApproval = await request(bob, runRoute + `/commands/${approval.id}`); expect(savedApproval.status).toBe(200); expect((await savedApproval.json()).receipt.id).toBe(approval.id); const updated = await request(bob, runRoute + '/observation'); - expect(updated.status).toBe(200); const updatedBody = await updated.json(); - expect(updatedBody.observation.inspection.edits[0].id).toBe(proposal.id); - expect(updatedBody.observation.inspection.planApproval.approvedId).toBe(approval.id); + expect(updated.status).toBe(200); + expect((await updated.json()).observation.inspection.planApproval.approvedId).toBe(approval.id); }); it('preserves old statement versions and handles stale revisions and private ownership fields through HTTP', async () => { @@ -570,14 +499,11 @@ describe('collaborative research through the actual HTTP service', () => { expect(feedback.proofCheck?.status).toBe('checked'); expect(runner.checks.at(-1)?.source).toBe(candidate); expect(runner.checks.at(-1)).toMatchObject({ sourceFile: 'Main.lean', dependencySources: observed.sources[0].dependencySources }); expect(runner.checks.at(-1)?.candidateTarget).toEqual({ name: 'target' }); - expect(runner.commands).toHaveLength(1); - expect(runner.commands[0].command).toMatchObject({ type: 'guidance', guidance: { id: feedback.id, - recipient: { kind: 'task', id: 'target' }, candidate: { source: candidate, sourceDigest: mathDigest(candidate), file: 'Main.lean', - baseCommit: commit, baseSourceDigest: sourceDigest, environmentDigest, taskRef: { id: 'target', version: 'task-v1' } } } }); - expect(feedback.delivery.status).toBe('delivered'); expect(feedback.decision.status).toBe('pending'); + expect(runner.commands).toHaveLength(0); + expect(feedback.decision.status).toBe('pending'); expect(feedback.execution.status).toBe('not-started'); const replay = await item(bob, route + '/feedback', submitted, 'POST', 201); - expect(replay.proofCheck).toEqual(feedback.proofCheck); expect(runner.checks).toHaveLength(1); expect(runner.commands).toHaveLength(1); + expect(replay.proofCheck).toEqual(feedback.proofCheck); expect(runner.checks).toHaveLength(1); expect(runner.commands).toHaveLength(0); expect(service.jobs.get(alice.owner, run.id)?.result).toBeUndefined(); expect(service.jobs.get(alice.owner, run.id)?.source).toBe(original); const asset = await createAsset(alice, 'mathematics', 'SharedMath', { source: { kind: 'run', runId: run.id, taskId: 'target', commit } }); @@ -619,7 +545,7 @@ describe('collaborative research through the actual HTTP service', () => { source: 'theorem target : True ∧ True := by exact ⟨True.intro, True.intro⟩\n' }; }); const historical = await item(bob, reviewRoute); - expect(historical).toEqual(initial); expect(runner.checks).toHaveLength(1); expect(runner.commands).toHaveLength(1); + expect(historical).toEqual(initial); expect(runner.checks).toHaveLength(1); expect(runner.commands).toHaveLength(0); expect((await request(carol, reviewRoute)).status).toBe(403); expect((await request(undefined, reviewRoute)).status).toBe(403); expect((await item(carol, route + '/feedback/' + feedback.id)).payload).toEqual(feedback.payload); @@ -683,7 +609,7 @@ describe('collaborative research through the actual HTTP service', () => { } expect(feedback.execution.status).toBe('not-started'); expect(runner.checks.at(-1)).toMatchObject({ source, candidateTarget: { name: 'helper', expectedType: helper.type } }); - expect(runner.commands).toHaveLength(1); expect(runner.commands[0]!.command.type).toBe('guidance'); + expect(runner.commands).toHaveLength(0); expect(service.jobs.get(alice.owner, run.id)?.result).toBeUndefined(); }); @@ -737,8 +663,8 @@ describe('collaborative research through the actual HTTP service', () => { observationRef: { sequence: observed.sequence, stateDigest: observed.snapshot.stateDigest } }, base: { commit, sourceDigest: baselineDigest, environmentDigest, file: 'Main.lean' } }, 'POST', 201); expect(feedback.proofCheck?.status, feedback.proofCheck?.reason).toBe('checked'); - expect(feedback.delivery.status).toBe('delivered'); expect(feedback.decision.status).toBe('pending'); - expect(feedback.execution.status).toBe('not-started'); expect(runner.commands).toHaveLength(1); + expect(feedback.decision.status).toBe('pending'); + expect(feedback.execution.status).toBe('not-started'); expect(runner.commands).toHaveLength(0); expect(service.jobs.get(alice.owner, run.id)?.source).toBe(original); expect(service.jobs.get(alice.owner, run.id)?.result).toBeUndefined(); }, 120_000); @@ -869,7 +795,8 @@ describe('collaborative research through the actual HTTP service', () => { const savedResponse = await request(carol, `/api/runs/${created.id}`); expect(savedResponse.status).toBe(200); const saved = (await savedResponse.json()).run; expect(saved.researchConfiguration).toEqual(frozen); expect(JSON.stringify(saved.researchConfiguration)).not.toContain('SECOND_SKILL_INSTRUCTION'); - const repeated = await request(carol, '/api/runs', { ...input(), requestId: 'third-person-run', researchSelection: selection }); + const repeated = await request(carol, '/api/runs', { ...input(), workers: 1, coordination: 'independent', + requestId: 'third-person-run', researchSelection: selection }); expect(repeated.status).toBe(200); expect((await repeated.json()).run.id).toBe(created.id); expect(runner.calls.filter(call => call.id === created.id)).toHaveLength(1); }); diff --git a/tests/webResearchProjects.test.ts b/tests/webResearchProjects.test.ts index 6db90463..3a350b5a 100644 --- a/tests/webResearchProjects.test.ts +++ b/tests/webResearchProjects.test.ts @@ -70,6 +70,32 @@ function fixture(disk = false) { } describe('research projects and collaboration permissions', () => { + it.each(['restart', 'next observation', 'command retry'])('recovers a native approval for the project after %s', mode => { + const { projects, storage, project, target } = fixture(); + const feedback = projects.submitFeedback(bob, project.id, { requestId: 'initial-route-approval', kind: 'plan-approval', + text: 'Approve the first route', target, planVersion: 'plan-v1' }); + const queued = projects.recordCommand(bob, project.id, feedback.id, { id: feedback.id, status: 'queued', planVersion: 'plan-v1' }); + expect(queued).toMatchObject({ delivery: { status: 'queued' }, execution: { status: 'not-started' } }); + const next = observation('run-a', { planVersion: undefined }); + next.sequence = 2; + next.solverRunId = 'solver-next'; + next.snapshot.runId = next.solverRunId; + const initialPlanApproval = { solverRunId: 'solver-fixture', receipt: { required: true, status: 'approved' as const, + planVersion: 'plan-v1', approvedId: feedback.id, approvedVersion: 'plan-v1', approvedAt: Date.parse(at), + rejections: [], leadRevising: false } }; + storage.saveRun(alice, { ...run('run-a', next), observation: mode === 'restart' ? undefined : next, + nativeTeamCapacity: 3, planApproval: true, workers: 1, coordination: 'independent', researchMode: 'skill', initialPlanApproval }); + if (mode === 'command retry') projects.recordCommand(bob, project.id, feedback.id, { id: feedback.id, status: 'approved', + planVersion: 'plan-v1', observation: next }); + else projects.syncRunObservation(bob, project.id, 'run-a'); + const updated = projects.feedback(bob, project.id, feedback.id); + expect(updated).toMatchObject({ delivery: { status: 'delivered', commandId: feedback.id }, execution: { status: 'completed', + planVersion: 'plan-v1', resultRefs: [`plan-approval:${feedback.id}`] } }); + projects.syncRunObservation(bob, project.id, 'run-a'); + expect(projects.feedback(bob, project.id, feedback.id)).toEqual(updated); + expect(storage.getRun(alice, 'run-a')?.observation?.inspection.planApproval).toBeUndefined(); + }); + it('retains exact historical step discussions after the task changes and the run ends', () => { const { projects, storage, project, target } = fixture(true); const originalObservation = observation(); originalObservation.sequence = 2; originalObservation.inspection.tasks[0].proof.commit = commit; diff --git a/tests/webResearchWorkspace.test.ts b/tests/webResearchWorkspace.test.ts index a405bee6..73c4ba86 100644 --- a/tests/webResearchWorkspace.test.ts +++ b/tests/webResearchWorkspace.test.ts @@ -147,6 +147,16 @@ describe('personal research search and accounting', () => { }); describe('evidence-based research brief', () => { + it('shows the initial route approval after a new solver round starts', () => { + const f = fixture(), value = run(); + value.initialPlanApproval = { solverRunId: 'first-round', receipt: { required: true, status: 'approved', + planVersion: 'later-route', approvedVersion: 'first-route', approvedId: 'approved-route', approvedAt: Date.parse(value.createdAt), + rejections: [], leadRevising: false } }; + delete value.observation!.inspection.planApproval; + f.save(alice, value); + expect(f.workspace.brief(alice, value.id).planApproval).toEqual({ status: 'approved', planVersion: 'first-route' }); + }); + it.each(['pending', 'rejected', 'interrupted', 'superseded'] as const)('exports %s candidate review without approved evidence', confirmation => { const f = fixture(), value = run(); value.formalization = { id: crypto.randomUUID(), original: 'Prove True', candidateDigest: 'c'.repeat(64), confirmation }; diff --git a/tests/webRunner.test.ts b/tests/webRunner.test.ts index a02fd156..b7659954 100644 --- a/tests/webRunner.test.ts +++ b/tests/webRunner.test.ts @@ -11,7 +11,7 @@ import { standaloneObservationFrame } from '../apps/web/observationSources'; import { loadWebSample } from '../apps/web/sample'; import { createWebHostDisconnectWatchdog, webWorkerHeartbeatMs } from '../apps/web/workerDisconnect'; import { writeMathJsonDurable } from '../src/math/mathRuntimeIo'; -import type { WorkerExplanationInput, WorkerExplanationMessage, WorkerInput, WorkerMessage } from '../apps/web/shared'; +import { retiredResearchCoordinationCode, type WorkerExplanationInput, type WorkerExplanationMessage, type WorkerInput, type WorkerMessage } from '../apps/web/shared'; function candidateCheckDocker(reply: { severity?: string; wrongMarker?: boolean; plain?: boolean; exitCode: number }) { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-target-query-')); @@ -51,6 +51,47 @@ main().catch(error => { if (error?.fixtureExit) process.exitCode = error.code; e } describe('Docker web runner', () => { + it('requires the current native workflow capability and launches the image it checked', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-docker-native-workflow-')); + const metadata = path.join(root, 'metadata'), created = path.join(root, 'created'); + const imageId = 'sha256:' + 'a'.repeat(64); + fs.writeFileSync(path.join(root, 'docker'), `#!${process.execPath} +const fs = require('node:fs'), path = require('node:path'), args = process.argv.slice(2); +if (args[0] === 'image') process.stdout.write(fs.readFileSync(path.join(__dirname, 'metadata'))); +else if (args[0] === 'create') { + fs.writeFileSync(path.join(__dirname, 'created'), args.at(-2)); + process.exitCode = 1; +} else if (args[0] !== 'rm') process.exitCode = 1; +`, { mode: 0o700 }); + vi.stubEnv('PATH', root); + try { + const config = readWebConfig({}), request: WorkerInput = { id: 'native-workflow', provider: config.providers[0], input: { + ...webDefaults, providerId: config.providers[0].id, apiKey: 'sk-offline-fixture', source: 'theorem goal : True := by sorry', + task: 'Offline native approval fixture', workers: 1, coordination: 'independent', nativeTeamCapacity: 3, planApproval: true, + } }; + const signal = new AbortController().signal; + fs.writeFileSync(metadata, `v1|v1|v1|v1||${imageId}\n`); + const old = new DockerWebRunner(config); + await expect(old.run({ ...request, input: { ...request.input, workers: 2, coordination: 'cooperative' } }, + () => {}, signal)).rejects.toThrow(retiredResearchCoordinationCode); + await expect(old.command(request.id, { type: 'guidance-withdraw', id: 'withdraw', guidanceId: 'old-direction' })) + .rejects.toThrow(retiredResearchCoordinationCode); + expect(await old.readiness()).toMatchObject({ ready: true, nativeTeam: false, nativeTeamPreferences: false, nativeTeamExpertCards: false }); + await expect(old.run(request, () => {}, signal)).rejects.toThrow('路线审批'); + expect(fs.existsSync(created)).toBe(false); + + fs.writeFileSync(metadata, `v1|v1|v1|v1|v1|${imageId}\n`); + const current = new DockerWebRunner(config); + expect(await current.readiness()).toMatchObject({ nativeTeam: true, nativeTeamPreferences: true, nativeTeamExpertCards: true }); + fs.writeFileSync(metadata, `v1|v1|v1|v1||sha256:${'b'.repeat(64)}\n`); + await expect(current.run(request, () => {}, signal)).rejects.toThrow('无法创建隔离运行环境'); + expect(fs.readFileSync(created, 'utf8')).toBe(imageId); + } finally { + vi.unstubAllEnvs(); + fs.rmSync(root, { recursive: true, force: true }); + } + }); + it('reads the candidate and terminal receipt after Docker attach exits while the worker is still alive', async () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-docker-detached-proof-')); const journal = path.join(root, 'journal'), callsPath = path.join(root, 'calls.jsonl'); @@ -310,7 +351,8 @@ const fs = require('node:fs'), path = require('node:path'); const args = process.argv.slice(2), root = __dirname; fs.appendFileSync(path.join(root, 'calls.jsonl'), JSON.stringify(args) + '\\n'); async function main() { - if (args[0] === 'create') fs.writeFileSync(path.join(root, 'container'), 'waiting'); + if (args[0] === 'image') process.stdout.write('v1|v1|v1||v1|sha256:' + 'a'.repeat(64) + '\\n'); + else if (args[0] === 'create') fs.writeFileSync(path.join(root, 'container'), 'waiting'); else if (args[0] === 'start') { for await (const _chunk of process.stdin) {} process.stdout.write(JSON.stringify({ type: 'progress', event: 'plan_approval_wait_started', message: 'Waiting' }) + '\\n'); @@ -334,7 +376,7 @@ main().catch(() => process.exit(1)); const config = readWebConfig({}), request: WorkerInput = { id: 'approval-wait-fixture', provider: config.providers[0], input: { ...webDefaults, providerId: config.providers[0].id, apiKey: 'sk-offline-fixture', source: 'theorem goal : True := by sorry', - task: 'Offline human review fixture', maxRunSeconds, workers: 2, planApproval }, + task: 'Offline human review fixture', maxRunSeconds, workers: 1, coordination: 'independent', nativeTeamCapacity: 3, planApproval }, }; const observation = { ...loadWebSample()!.observations[0]!, webRunId: request.id }; const libraryRestart = { previousSolverRunId: 'solver-first', solverRunId: observation.solverRunId, round: 1 }; @@ -363,7 +405,7 @@ main().catch(() => process.exit(1)); ? ['plan_approval_wait_started', 'plan_approval_wait_ended', 'result'] : ['plan_approval_wait_started', 'library_restart', 'observation']); if (decision === 'cancel') { expect(messages.slice(-2)).toEqual([{ type: 'library_restart', ...libraryRestart }, { type: 'observation', observation }]); - expect(calls.map(args => args[0])).toEqual(['create', 'start', 'exec', 'rm']); + expect(calls.map(args => args[0])).toEqual(['image', 'create', 'start', 'exec', 'rm']); } expect(vi.getTimerCount()).toBe(0); } finally { diff --git a/tests/webServer.test.ts b/tests/webServer.test.ts index 0ab46502..7ace7d04 100644 --- a/tests/webServer.test.ts +++ b/tests/webServer.test.ts @@ -12,7 +12,7 @@ import { loadWebSample } from '../apps/web/sample'; import { decodeTaskDraft } from '../apps/web/client/draft'; import { readWebArchiveObservations, type StoredWebArchiveV2 } from '../apps/web/storage'; import type { WebRunner } from '../apps/web/runner'; -import { webLimits, webSampleRunId, type WebResult, type WebRun, type WebRunInput, type WebSession, type WorkerInput, type WorkerMessage } from '../apps/web/shared'; +import { retiredResearchCoordinationCode, webLimits, webSampleRunId, type WebResult, type WebRun, type WebRunInput, type WebSession, type WorkerInput, type WorkerMessage } from '../apps/web/shared'; import type { WebObservation } from '../apps/web/collaboration'; const key = 'sk-http-test-never-publish'; @@ -25,7 +25,8 @@ type Call = { value: WorkerInput; signal: AbortSignal; send(message: WorkerMessa class HttpTestRunner implements WebRunner { calls: Call[] = []; ready = true; - async readiness() { return { ready: this.ready, message: this.ready ? 'Test worker ready' : 'Test worker unavailable' }; } + nativeTeam = false; + async readiness() { return { ready: this.ready, nativeTeam: this.nativeTeam, message: this.ready ? 'Test worker ready' : 'Test worker unavailable' }; } async run(value: WorkerInput, send: (message: WorkerMessage) => void, signal: AbortSignal) { await new Promise((resolve, reject) => { this.calls.push({ value, signal, send, fail: reject, @@ -117,7 +118,7 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( const replay = await request('/api/runs', alice, { body: { ...input(), apiKey: '' }, headers: { 'Idempotency-Key': 'http-retry' } }); expect(replay.status).toBe(200); expect((await replay.json()).run.id).toBe(runs[0].id); }); - it('creates and replays Skill research, preserving cooperation and single-run control limits', async () => { + it('creates and replays solo Skill research and keeps its control limits', async () => { const client = await session(), submitted = { ...input(), requestId: 'skill-http', researchMode: 'skill', coordination: 'independent' }; const response = await request('/api/runs', client, { body: submitted }); expect(response.status).toBe(201); @@ -130,11 +131,8 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( expect((await request('/api/runs', client, { body: { ...submitted, skillLoading: 'file' } })).status).toBe(409); const cooperative = await request('/api/runs', client, { body: { ...submitted, requestId: 'cooperative-skill', workers: 3, coordination: 'cooperative', planApproval: true, modulePlan: { scheduler: 'critical-path', context: 'essential', custom: [] } } }); - expect(cooperative.status).toBe(201); - const cooperating = (await cooperative.json()).run; - expect(cooperating).toMatchObject({ researchMode: 'skill', workers: 3, coordination: 'cooperative', planApproval: true, - moduleConfiguration: { selection: { scheduler: 'critical-path', context: 'essential' } } }); - expect((await request('/api/runs', client, { body: { ...submitted, requestId: 'invalid-plan', planApproval: true } })).status).toBe(400); + expect(cooperative.status).toBe(400); + expect((await request('/api/runs', client, { body: { ...submitted, requestId: 'unsupported-plan', planApproval: true } })).status).toBe(503); expect((await request('/api/runs', client, { body: { ...input(), requestId: 'invalid-loading', skillLoading: 'file' } })).status).toBe(400); const controls = [ ['guidance', { id: 'unsupported-guidance', recipient: { kind: 'lead' }, text: 'An unsupported control.', observationRef: { sequence: 1, stateDigest: 'a'.repeat(64) } }], @@ -144,7 +142,10 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( ] as const; for (const [operation, body] of controls) { const rejected = await request(`/api/runs/${run.id}/${operation}`, client, { body }); - expect(rejected.status).toBe(409); expect((await rejected.json()).error).toMatch(/此研究安排不支持/); + expect(rejected.status).toBe(409); + const error = await rejected.json(); + if (operation === 'plan-approval') expect(error.error).toMatch(/此研究安排不支持/); + else expect(error.code).toBe(retiredResearchCoordinationCode); } expect((await request(`/api/runs/${run.id}`, client)).status).toBe(200); const conversation = (await (await request('/api/conversations', client, { body: { runId: run.id } })).json()).conversation; @@ -153,6 +154,54 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( const retained = (await (await request(`/api/conversations/${conversation.id}`, client)).json()).conversation; expect(retained.messages).toHaveLength(conversation.messages.length); }); + + it('defaults new Codex jobs to native teams, supports opt-in approval, and replays a saved legacy receipt', async () => { + runner.nativeTeam = true; + const client = await session(), owner = client.cookie.slice('theoremos_session='.length); + const legacy = { ...input(), maxTotalTokens: 0, workers: 2, environment: 'standard' as const }; + const provider = config.providers.find(item => item.id === legacy.providerId)!; + const saved = service.jobs.create(owner, legacy, provider, undefined, 'legacy-request'); + const historical = await request('/api/runs', client, { body: { ...legacy, requestId: 'legacy-request' } }); + expect(historical.status).toBe(200); + expect((await historical.json()).run).toMatchObject({ id: saved.id, workers: 2, coordination: 'cooperative' }); + const prefix = `/api/runs/${saved.id}`; + service.storage.saveCommand(owner, saved.id, 'saved-edit', { id: 'saved-edit', status: 'applied' }); + for (const operation of ['guidance', 'edits', 'edits/preview']) { + const response = await request(`${prefix}/${operation}`, client, { body: {} }); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ code: retiredResearchCoordinationCode }); + } + const receipt = await request(`${prefix}/commands/saved-edit`, client); + expect(receipt.status).toBe(200); + expect(await receipt.json()).toEqual({ receipt: { id: 'saved-edit', status: 'applied' } }); + const refused = await request('/api/runs', client, { body: { ...legacy, requestId: 'new-legacy-request' } }); + expect(refused.status).toBe(400); + expect(await refused.json()).toMatchObject({ code: retiredResearchCoordinationCode }); + await tick(); runner.calls[0].finish(); await tick(); + + const scout = await request('/api/runs', client, { body: { ...input(), requestId: 'old-scout', + portfolioExploration: true, portfolioSeconds: 45 } }); + expect(scout.status).toBe(400); + expect(await scout.json()).toMatchObject({ code: retiredResearchCoordinationCode, error: expect.stringContaining('路线探索') }); + + for (const planApproval of [undefined, true]) { + const body = { ...input(), requestId: planApproval ? 'guided-native' : 'autonomous-native', planApproval }; + const response = await request('/api/runs', client, { body }); + expect(response.status).toBe(201); + const run = (await response.json()).run; + expect(run).toMatchObject({ researchMode: 'skill', skillLoading: 'native', workers: 1, + coordination: 'independent', nativeTeamCapacity: 3 }); + expect(run.planApproval).toBe(planApproval); + await tick(); + const call = runner.calls.at(-1)!; + expect(call.value.input).toMatchObject({ nativeTeamCapacity: 3 }); + expect(call.value.input.planApproval).toBe(planApproval); + const replay = await request('/api/runs', client, { body }); + expect(replay.status).toBe(200); + expect((await replay.json()).run.id).toBe(run.id); + call.finish(); await tick(); + } + }); it('selects only an operator-configured native harness and omits private launch configuration from HTTP records', async () => { const provider = { id: 'claude', name: 'Native Claude', baseUrl: 'https://anthropic.example.test/v1', harness: 'claude-code' as const, execution: { executable: '/opt/private-bin/claude' } }; @@ -161,11 +210,11 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( expect(client.session.providers.find(item => item.id === provider.id)).toEqual({ id: provider.id, name: provider.name, baseUrl: provider.baseUrl, harness: provider.harness }); const submitted = { ...input(), providerId: provider.id, model: 'claude-fixture', effort: 'high', - workers: 3, coordination: 'cooperative', requestId: 'native-http' }; + workers: 1, coordination: 'independent', requestId: 'native-http' }; const response = await request('/api/runs', client, { body: submitted }); expect(response.status).toBe(201); const created = (await response.json()).run; - expect(created).toMatchObject({ harness: 'claude-code', researchMode: 'skill', skillLoading: 'file', workers: 3 }); + expect(created).toMatchObject({ harness: 'claude-code', researchMode: 'skill', skillLoading: 'file', workers: 1 }); expect(created.harnessConfigurationDigest).toMatch(/^[a-f0-9]{64}$/u); expect(JSON.stringify(created)).not.toContain(provider.execution.executable); expect((await request('/api/runs', client, { body: submitted })).status).toBe(200); @@ -527,7 +576,9 @@ describe('web HTTP boundary with disposable local servers and no model calls', ( expect(await response.text()).not.toContain(key); } expect(runner.calls).toHaveLength(0); - const atLimits = await request('/api/runs', alice, { body: { ...input(), maxTurns: 20, maxRunSeconds: 900, workers: 4, maxTotalTokens: 100_000_000 } }); + runner.nativeTeam = true; + const atLimits = await request('/api/runs', alice, { body: { ...input(), maxTurns: 20, maxRunSeconds: 900, + researchMode: 'skill', coordination: 'independent', nativeTeamCapacity: 8, maxTotalTokens: 100_000_000 } }); expect(atLimits.status).toBe(201); await tick(); expect(runner.calls[0].value.input.maxTotalTokens).toBe(100_000_000); diff --git a/tests/webSkillResearch.test.ts b/tests/webSkillResearch.test.ts index abedf7d1..8aff20f0 100644 --- a/tests/webSkillResearch.test.ts +++ b/tests/webSkillResearch.test.ts @@ -7,7 +7,7 @@ import { WebStorage } from '../apps/web/storage'; import { WebResearchPersonal } from '../apps/web/researchPersonal'; import { WebResearchProjects } from '../apps/web/researchProjects'; import type { WebResearchProblems } from '../apps/web/researchProblems'; -import { webAgentTeamPreset, webPortfolioPreset, webResearchArguments, webResearchModeError } from '../apps/web/researchMode'; +import { webAgentTeamPreset, webResearchArguments, webResearchModeError } from '../apps/web/researchMode'; import { webSolverModules } from '../apps/web/worker'; import { directSolverModules } from '../src/solver/modules'; import { decodeTaskDraft, encodeTaskDraft, type TaskDraft } from '../apps/web/client/draft'; @@ -17,7 +17,7 @@ import { loadWebSample } from '../apps/web/sample'; import { isWebObservation, parseWorkerMessage, type WebRunner } from '../apps/web/runner'; import { projectWebNativeTeam } from '../apps/web/nativeTeamObservation'; import type { WebObservation } from '../apps/web/collaboration'; -import type { WebProvider, WebRunInput, WorkerInput, WorkerMessage } from '../apps/web/shared'; +import { retiredPortfolioMessage, retiredResearchCoordinationMessage, type WebProvider, type WebRunInput, type WorkerInput, type WorkerMessage } from '../apps/web/shared'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { personalExpertCardsDigest } from '../src/solver/personalExperts'; import { defaultResearchModulePlan } from '../src/solver/modules/policy'; @@ -53,23 +53,14 @@ function observation(id: string, sequence: number): WebObservation { } describe('Web Skill research arrangement and frozen identity', () => { - it('opts into portfolio scouting with enough capacity and freezes its configuration for dispatch', async () => { - const fixture = controlled(), jobs = new WebJobs(fixture.runner, { concurrency: 1, queueLimit: 4 }); queues.push(jobs); - const selected = input({ workers: 2, coordination: 'cooperative', portfolioExploration: true, portfolioSeconds: 45 }); - const run = jobs.create('owner', selected, provider, undefined, 'portfolio'); - await tick(); - expect(run).toMatchObject({ portfolioExploration: true, portfolioSeconds: 45 }); - expect(webResearchArguments(fixture.actual.input, provider).slice(-3)) - .toEqual(['--portfolio-exploration', '--portfolio-seconds', '45']); - expect(webResearchArguments({ ...selected, portfolioExploration: undefined, portfolioSeconds: undefined })) - .toEqual(['--research-mode', 'skill', '--skill-loading', 'native']); - expect(webResearchArguments({ ...selected, portfolioExploration: false, portfolioSeconds: undefined }).at(-1)).toBe('--skip-portfolio'); - expect(webResearchArguments(input({ nativeTeamCapacity: 2, portfolioExploration: true })).at(-1)).toBe('--portfolio-exploration'); - expect(webPortfolioPreset({ workers: 2 })).toBe(true); - expect(webPortfolioPreset({ workers: 2, portfolioExploration: false })).toBe(false); - for (const invalid of [{ workers: 1 }, { portfolioSeconds: 0 }, { portfolioExploration: false }]) - expect(webResearchModeError({ ...selected, ...invalid })).toBeDefined(); - expect(() => jobs.replay('owner', { ...selected, portfolioSeconds: 46 }, provider, 'portfolio')).toThrow(/不同/); + it('retires standalone scouting and accepts an explicit false as an old-client no-op', () => { + const team = input(webAgentTeamPreset()); + for (const historical of [{ portfolioExploration: true }, { portfolioSeconds: 45 }]) { + const requested = { ...team, ...historical }; + expect(webResearchModeError(requested, provider)).toBe(retiredPortfolioMessage); + expect(() => webResearchArguments(requested, provider)).toThrow(retiredPortfolioMessage); + } + expect(webResearchArguments({ ...team, portfolioExploration: false }, provider)).toEqual(webResearchArguments(team, provider)); }); it('restores a native team with the chosen capacity, rejects host scheduling, and binds observations to the same team', async () => { const selected = { ...draft(), nativeTeamCapacity: 3 }; @@ -78,7 +69,8 @@ describe('Web Skill research arrangement and frozen identity', () => { const team = input({ ...webAgentTeamPreset(), skillLoading: 'file' }); expect(webResearchArguments(team, provider)).toEqual(['--research-mode', 'skill', '--skill-loading', 'file', '--skill-delegation', 'team', '--skill-max-agents', '3']); - for (const change of [{ workers: 3 }, { coordination: 'cooperative' as const }, { planApproval: true }, { nativeTeamCapacity: 1 }, { nativeTeamCapacity: 9 }]) + expect(webResearchArguments({ ...team, planApproval: true }, provider)).toEqual(webResearchArguments(team, provider)); + for (const change of [{ workers: 3 }, { coordination: 'cooperative' as const }, { nativeTeamCapacity: 1 }, { nativeTeamCapacity: 9 }]) expect(() => webResearchArguments({ ...team, ...change }, provider)).toThrow(); expect(() => webResearchArguments(team, { harness: 'cli' })).toThrow(/Codex/); const fixture = controlled(), jobs = new WebJobs(fixture.runner, { concurrency: 1, queueLimit: 4 }); queues.push(jobs); @@ -118,7 +110,7 @@ describe('Web Skill research arrangement and frozen identity', () => { record.inspection.configuration.researchDelegation.preferredProfiles = ['D011', 'engineer']; fixture.send({ type: 'observation', observation: record }); expect(run.observation?.sequence).toBe(1); }); - it('forwards explicit skill CLI arguments while preserving the legacy default and cooperative module choices', () => { + it('forwards explicit Skill arguments and refuses to execute a retired host team', () => { expect(webResearchArguments(input())).toEqual(['--research-mode', 'skill', '--skill-loading', 'native']); expect(webResearchArguments(input({ skillLoading: 'file' }))).toEqual(['--research-mode', 'skill', '--skill-loading', 'file']); expect(webResearchArguments(input({ researchMode: undefined }))).toEqual([]); @@ -128,7 +120,8 @@ describe('Web Skill research arrangement and frozen identity', () => { { researchSelection: { skills: [{ assetId: 'custom-strategy', version: '1.0.0' }] } }]) expect(webResearchModeError(input(change as Partial))).toBeUndefined(); expect(webResearchModeError(input({ researchMode: undefined, skillLoading: 'native' }))).toMatch(/Skill/); - expect(webResearchModeError(input({ workers: 4, coordination: 'cooperative', planApproval: true }))).toBeUndefined(); + expect(() => webResearchArguments(input({ workers: 4, coordination: 'cooperative', planApproval: true }))) + .toThrow(retiredResearchCoordinationMessage); const modules = webSolverModules({ id: 'fixture', input: input(), provider }); expect(modules.M3).toBe(directSolverModules.M3); expect(modules.M5).toBe(directSolverModules.M5); expect(webSolverModules({ id: 'fixture', input: input(), provider }, undefined, @@ -183,7 +176,7 @@ describe('Web Skill research arrangement and frozen identity', () => { }); it('keeps skill mode through local drafts, archive imports and account drafts, and includes it in submission matching', () => { - const original = { ...draft(), nativeTeamCapacity: 8, nativeTeamPreferredProfiles: ['D011', 'engineer'] }; + const original = { ...draft(), planApproval: true as const, nativeTeamCapacity: 8, nativeTeamPreferredProfiles: ['D011', 'engineer'] }; expect(decodeTaskDraft(JSON.parse(encodeTaskDraft(original)))).toEqual(original); const { templateId: _template, ...archived } = original; expect(decodeTaskDraft({ schema: 'theorem-os.web-export.v1', run: { ...archived, @@ -195,7 +188,7 @@ describe('Web Skill research arrangement and frozen identity', () => { scope: { kind: 'problem', draftKey: 'skill-draft' }, value, requestId: 'save-skill', expectedRevision: 0, summary: 'Skill draft', deviceId: 'fixture', deviceName: 'Fixture', clientUpdatedAt: new Date().toISOString() }); expect(personal.draft('account:alice@example.org', saved.draft.id).version.value).toEqual(value); - const run = jobs.create('owner', input({ skillLoading: 'file', nativeTeamCapacity: 8, nativeTeamPreferredProfiles: original.nativeTeamPreferredProfiles }), provider); + const run = jobs.create('owner', input({ skillLoading: 'file', planApproval: true, nativeTeamCapacity: 8, nativeTeamPreferredProfiles: original.nativeTeamPreferredProfiles }), provider); expect(matchesProblemRun(value, run)).toBe(true); expect(matchesProblemRun(value, { ...run, researchMode: 'legacy' })).toBe(false); expect(matchesProblemRun(value, { ...run, skillLoading: 'native' })).toBe(false); diff --git a/tests/webWorkerBridge.test.ts b/tests/webWorkerBridge.test.ts index b3ef26dd..22b33493 100644 --- a/tests/webWorkerBridge.test.ts +++ b/tests/webWorkerBridge.test.ts @@ -4,17 +4,15 @@ import { Writable } from 'node:stream'; import { afterEach, describe, expect, it } from 'vitest'; import { createWebWorkerBridge, freezeWebKnowledge, handleWebWorkerCommand, writeWebActiveRun } from '../apps/web/workerBridge'; import { writeSolverRunState } from '../src/solver/archive'; -import { exportRunPlan } from '../src/solver/inspection'; import { taskVersion } from '../src/solver/tasks'; import { readKnowledgeCatalog } from '../src/solver/theoremKnowledgeStore'; import { WebKnowledgeService } from '../apps/web/knowledgeService'; import { WebStorage } from '../apps/web/storage'; import { WebTrajectories } from '../apps/web/trajectory'; -import type { WorkerInput, WorkerMessage } from '../apps/web/shared'; +import { retiredResearchCoordinationCode, type WorkerInput, type WorkerMessage } from '../apps/web/shared'; import { webWorkerFixture } from './helpers/webWorkerBridge'; import { mathDigest, withMathRuntimeLease } from '../src/math/mathRuntimeIo'; import { hashMathFormalSourceDeclaration } from '../src/math/leanSource'; -import { webGuidanceSchema } from '../apps/web/collaborationValidation'; import { parseWorkerMessage } from '../apps/web/runner'; import type { WebObservation } from '../apps/web/collaboration'; import { webProofMessageSink } from '../apps/web/proofJournal'; @@ -268,7 +266,7 @@ describe('isolated Web worker bridge', () => { .toMatchObject({ taskId: f.goal.id, record: { status: 'kernel_verified', passed: false } }); }); - it('continues observation sequences across a host-authorized library round and retires old guidance references', async () => { + it('continues observation sequences across a host-authorized library round', async () => { const f = fixture(), messages: WorkerMessage[] = []; const options = { webRunId: 'web-fixture', directory: f.directory, onMessage: (message: WorkerMessage) => messages.push(message) }; const original = createWebWorkerBridge({ ...options, output: f.output }); @@ -290,21 +288,12 @@ describe('isolated Web worker bridge', () => { expect((await next.capture()).observation.sequence).toBe(3); expect(messages.filter(message => message.type === 'library_restart')).toHaveLength(1); expect(JSON.parse(fs.readFileSync(path.join(f.directory, 'web-bridge.json'), 'utf8'))).toMatchObject({ - solverRunId: 'solver-next', libraryRound: 1, sequence: 3, - observations: [{ sequence: 3, stateDigest: captured.observation.snapshot.stateDigest }] }); + solverRunId: 'solver-next', libraryRound: 1, sequence: 3 }); writeWebActiveRun({ ...options, output }, f.activeRunFile); const commandOptions = { activeRunFile: f.activeRunFile }; expect((await handleWebWorkerCommand({ type: 'capture' }, commandOptions)).observation) .toMatchObject({ solverRunId: 'solver-next', sequence: 3 }); - const guidance = { id: 'old-round-direction', recipient: { kind: 'task', id: 'goal' }, - taskRef: { id: 'goal', version: taskVersion(f.goal) }, text: 'Inspect the intermediate implication.', - observationRef: { sequence: before.sequence, stateDigest: before.snapshot.stateDigest } }; - expect(await handleWebWorkerCommand({ type: 'guidance', guidance }, commandOptions)).toMatchObject({ - status: 'rejected', reason: 'web_guidance_observation_unknown' }); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance: { ...guidance, id: 'new-round-direction', - observationRef: { sequence: captured.observation.sequence, stateDigest: captured.observation.snapshot.stateDigest } } }, commandOptions)) - .toMatchObject({ status: 'queued' }); await expect(original.capture({ force: true })).rejects.toThrow('web_bridge_run_identity_changed'); }); @@ -394,57 +383,6 @@ describe('isolated Web worker bridge', () => { expect((await createWebWorkerBridge(options).capture()).observation.sequence).toBe(1); }); - it('previews control changes without changing state and queues the same full versioned plan once', async () => { - const f = fixture(), before = fs.readFileSync(f.stateFile); - const proposal = { ...exportRunPlan(f.state), id: 'pause-goal' }; - proposal.tasks = proposal.tasks.map(task => task.id === 'goal' ? { ...task, status: 'paused' as const } : task); - const options = { activeRunFile: f.activeRunFile }; - const preview = await handleWebWorkerCommand({ type: 'edit-preview', proposal }, options); - expect(preview).toMatchObject({ id: 'pause-goal', status: 'validated', affectedTaskIds: ['goal'], changes: [{ taskId: 'goal', fields: ['status'] }] }); - expect(fs.readFileSync(f.stateFile)).toEqual(before); - expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'))).toBe(false); - expect(await handleWebWorkerCommand({ type: 'edit', proposal }, options)).toMatchObject({ id: 'pause-goal', status: 'queued', commandDigest: preview.commandDigest }); - expect(await handleWebWorkerCommand({ type: 'edit', proposal }, options)).toMatchObject({ id: 'pause-goal', status: 'already_queued' }); - expect(fs.readFileSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'), 'utf8').trim().split('\n')).toHaveLength(1); - await expect(handleWebWorkerCommand({ type: 'edit', proposal: { ...proposal, id: 'stale', baseVersion: 'stale' } }, options)).rejects.toThrow('version_conflict'); - }); - - it.each(['edit-preview', 'edit'] as const)('rejects an unowned proofPath in %s with its proposal id and repair details without appending', async type => { - const f = fixture(), before = fs.readFileSync(f.stateFile); - const proposal = { ...exportRunPlan(f.state), id: 'invalid-proof-path' }; - proposal.tasks = proposal.tasks.map(task => task.id === 'goal' ? { ...task, proofPath: 'generated/problem/Submission.lean' } : task); - const result = await handleWebWorkerCommand({ type, proposal }, { activeRunFile: f.activeRunFile }); - expect(result).toMatchObject({ id: proposal.id, status: 'rejected', baseVersion: 'plan-v1' }); - expect(result.reason).toMatch(/^math_plan_invalid_proof_target:/u); - expect(result.reason).toContain('"taskId":"goal"'); - expect(result.reason).toContain('"proofPath":"generated/problem/Submission.lean"'); - expect(result.reason).toContain('Use an owned proofPath'); - expect(fs.readFileSync(f.stateFile)).toEqual(before); - expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'))).toBe(false); - }); - - it('rejects an unavailable preferred owner during both preview and submission', async () => { - const f = fixture(), before = fs.readFileSync(f.stateFile), options = { activeRunFile: f.activeRunFile }; - const proposal = { ...exportRunPlan(f.state), id: 'missing-preferred-owner' }; - proposal.tasks = proposal.tasks.map(task => task.id === 'goal' ? { ...task, preferredOwnerId: 'missing-worker' } : task); - const rejected = { id: proposal.id, status: 'rejected', baseVersion: proposal.baseVersion, reason: 'math_plan_task_owner_unavailable' }; - expect(await handleWebWorkerCommand({ type: 'edit-preview', proposal }, options)).toEqual(rejected); - expect(await handleWebWorkerCommand({ type: 'edit', proposal }, options)).toEqual(rejected); - expect(fs.readFileSync(f.stateFile)).toEqual(before); - expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'))).toBe(false); - }); - - it('keeps an incomplete edit queue distinct from a rejected proposal', async () => { - const f = fixture(), before = fs.readFileSync(f.stateFile); - const proposal = { ...exportRunPlan(f.state), id: 'valid-proposal' }; - const log = path.join(path.dirname(f.stateFile), 'edits.jsonl'), partial = '{"id":'; - fs.writeFileSync(log, partial); - await expect(handleWebWorkerCommand({ type: 'edit', proposal }, { activeRunFile: f.activeRunFile })) - .rejects.toThrow('math_edit_incomplete_log'); - expect(fs.readFileSync(log, 'utf8')).toBe(partial); - expect(fs.readFileSync(f.stateFile)).toEqual(before); - }); - it('allows capture before cancellation and freezes reusable catalog input with its exact digest', async () => { const f = fixture(); const captured = await handleWebWorkerCommand({ type: 'capture' }, { activeRunFile: f.activeRunFile }); @@ -467,83 +405,32 @@ describe('isolated Web worker bridge', () => { expect(readKnowledgeCatalog(file).base.sources).toEqual(captured.catalog!.sources); }); - it('accepts guidance only for a captured observation and reports its queued receipt', async () => { - const f = fixture(), options = { activeRunFile: f.activeRunFile }; - const captured = await handleWebWorkerCommand({ type: 'capture' }, options), observation = captured.observation!; - const guidance = { id: 'direction-one', recipient: { kind: 'task', id: 'goal' }, - taskRef: { id: 'goal', version: taskVersion(f.goal) }, text: 'Inspect the missing intermediate implication.', - observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } }; - expect(await handleWebWorkerCommand({ type: 'guidance', guidance }, options)).toMatchObject({ id: guidance.id, status: 'queued', - guidance: { text: guidance.text, recipient: guidance.recipient } }); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance: { ...guidance, id: 'unknown', - observationRef: { ...guidance.observationRef, sequence: 999 } } }, options)).toEqual({ - id: 'unknown', status: 'rejected', reason: 'web_guidance_observation_unknown' }); - expect((await handleWebWorkerCommand({ type: 'capture' }, options)).observation!.guidance).toHaveLength(1); - const metaFile = path.join(f.directory, 'web-bridge.json'), meta = JSON.parse(fs.readFileSync(metaFile, 'utf8')); - meta.observations = []; fs.writeFileSync(metaFile, JSON.stringify(meta)); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance }, options)).toMatchObject({ - id: guidance.id, status: 'queued', guidance: { text: guidance.text } }); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance: { ...guidance, text: 'A different message under the same ID' } }, options)).toEqual({ - id: guidance.id, status: 'rejected', reason: 'math_guidance_id_conflict' }); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance: { ...guidance, id: 'uncaptured-new-guidance' } }, options)).toEqual({ - id: 'uncaptured-new-guidance', status: 'rejected', reason: 'web_guidance_observation_unknown' }); - expect((await handleWebWorkerCommand({ type: 'capture' }, options)).observation!.guidance).toHaveLength(1); - }); - - it('withdraws a queued note with a fresh observation and rejects unknown notes without writing', async () => { - const f = fixture(), options = { activeRunFile: f.activeRunFile }; - const observation = (await handleWebWorkerCommand({ type: 'capture' }, options)).observation!; - const guidance = { id: 'queued-direction', recipient: { kind: 'task', id: 'goal' }, - taskRef: { id: 'goal', version: taskVersion(f.goal) }, text: 'Check the base case first.', - observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } }; - expect(await handleWebWorkerCommand({ type: 'guidance', guidance }, options)).toMatchObject({ status: 'queued' }); - const withdrawn = await handleWebWorkerCommand({ type: 'guidance-withdraw', id: 'withdraw-1', guidanceId: guidance.id }, options); - expect(withdrawn).toMatchObject({ id: 'withdraw-1', status: 'withdrawn', guidance: { id: guidance.id, status: 'failed', reason: 'math_guidance_withdrawn' } }); - expect(withdrawn.observation!.guidance).toEqual([expect.objectContaining({ id: guidance.id, status: 'failed', reason: 'math_guidance_withdrawn' })]); - const before = fs.readFileSync(path.join(path.dirname(f.stateFile), 'human-guidance.json')); - expect(await handleWebWorkerCommand({ type: 'guidance-withdraw', id: 'withdraw-2', guidanceId: 'never-sent' }, options)) - .toMatchObject({ id: 'withdraw-2', status: 'rejected', reason: 'math_guidance_unknown', observation: { guidance: [expect.objectContaining({ id: guidance.id })] } }); - expect(fs.readFileSync(path.join(path.dirname(f.stateFile), 'human-guidance.json'))).toEqual(before); - await expect(handleWebWorkerCommand({ type: 'guidance-withdraw', id: 'withdraw-3', guidanceId: '../escape' }, options)).rejects.toThrow(); - }); - - it('keeps a known guidance rejection distinct from an uncertain queue write', async () => { - const f = fixture(), options = { activeRunFile: f.activeRunFile }; - const observation = (await handleWebWorkerCommand({ type: 'capture' }, options)).observation!; - const guidance = { id: 'superseded-direction', recipient: { kind: 'task', id: 'goal' }, - taskRef: { id: 'goal', version: taskVersion(f.goal) }, text: 'Inspect this version before changing its dependencies.', - observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } }; - const before = fs.readFileSync(f.stateFile); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance: { ...guidance, - taskRef: { ...guidance.taskRef, version: 'old-task-version' } } }, options)).toEqual({ - id: guidance.id, status: 'rejected', reason: 'math_guidance_task_superseded' }); - expect(fs.readFileSync(f.stateFile)).toEqual(before); - expect((await handleWebWorkerCommand({ type: 'capture' }, options)).observation!.guidance).toEqual([]); - fs.writeFileSync(path.join(path.dirname(f.stateFile), 'human-guidance.json'), '{invalid'); - await expect(handleWebWorkerCommand({ type: 'guidance', guidance }, options)).rejects.toThrow(); - }); - - it('passes a validated candidate attachment through the worker command and captures it without editing source', async () => { + it('captures historical guidance and rejects retired commands before modifying the run', async () => { const f = fixture(), options = { activeRunFile: f.activeRunFile }; const observation = (await handleWebWorkerCommand({ type: 'capture' }, options)).observation!; - const baseline = observation.sources.find(item => item.taskId === 'goal')!, source = baseline.source.replace('by sorry', 'by trivial'); - const taskRef = { id: baseline.taskId, version: baseline.taskVersion }; - const guidance = webGuidanceSchema.parse({ id: 'candidate-direction', recipient: { kind: 'task', id: taskRef.id }, taskRef, - text: 'Please assess this independently checked candidate through the ordinary task protocol.', - observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest }, - candidate: { source, sourceDigest: mathDigest(source), file: baseline.file, baseCommit: baseline.commit, - baseSourceDigest: baseline.sourceDigest, environmentDigest: baseline.environmentDigest, taskRef } }); - const before = fs.readFileSync(path.join(f.project, baseline.file)); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance }, options)).toMatchObject({ - id: guidance.id, status: 'queued', guidance: { candidate: guidance.candidate }, - }); + const observationRef = { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest }; + const guidance = { id: 'historical-direction', recipient: { kind: 'task', id: 'goal' }, + taskRef: { id: 'goal', version: taskVersion(f.goal) }, text: 'Check the base case first.', observationRef }; + const at = new Date().toISOString(); + const record = { ...guidance, status: 'delivered', createdAt: at, updatedAt: at }; + const guidanceLog = path.join(path.dirname(f.stateFile), 'human-guidance.json'); + fs.writeFileSync(guidanceLog, JSON.stringify({ schema: 'theorem-os.human-guidance.v1', runId: f.state.runId, records: [record] })); + const metaFile = path.join(f.directory, 'web-bridge.json'), meta = JSON.parse(fs.readFileSync(metaFile, 'utf8')); + fs.writeFileSync(metaFile, JSON.stringify({ ...meta, observations: [observationRef] })); + const state = fs.readFileSync(f.stateFile), log = fs.readFileSync(guidanceLog); + const proposal = { ...observation.plan, id: 'pause-goal' }; + for (const command of [{ type: 'edit-preview', proposal }, { type: 'edit', proposal }, + { type: 'guidance', guidance: { ...guidance, id: 'new-direction' } }, + { type: 'guidance-withdraw', id: 'withdraw', guidanceId: guidance.id }]) { + await expect(handleWebWorkerCommand(command, options)).rejects.toThrow(retiredResearchCoordinationCode); + } + expect(fs.readFileSync(f.stateFile)).toEqual(state); + expect(fs.readFileSync(guidanceLog)).toEqual(log); + expect(fs.existsSync(path.join(path.dirname(f.stateFile), 'edits.jsonl'))).toBe(false); const captured = (await handleWebWorkerCommand({ type: 'capture' }, options)).observation!; - expect(captured.guidance[0].candidate).toEqual(guidance.candidate); - expect(await handleWebWorkerCommand({ type: 'guidance', guidance: { ...guidance, id: 'changed-environment', - candidate: { ...guidance.candidate, environmentDigest: '0'.repeat(64) } } }, options)).toMatchObject({ - status: 'rejected', reason: 'math_guidance_candidate_environment_changed', - }); - expect(fs.readFileSync(path.join(f.project, baseline.file))).toEqual(before); + expect(captured.sequence).toBe(observation.sequence + 1); + expect(captured.guidance).toEqual([record]); + expect(captured.plan).toEqual(observation.plan); }); it('queues a plan approval only for the exact pending version and reports each saved-checkpoint rejection', async () => { diff --git a/tests/workerDeliveryIdentity.test.ts b/tests/workerDeliveryIdentity.test.ts deleted file mode 100644 index 58d75d5f..00000000 --- a/tests/workerDeliveryIdentity.test.ts +++ /dev/null @@ -1,384 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { parseCooperationPlan, type CooperativeResearch } from '../src/solver/cooperation'; -import { directSolverModules } from '../src/solver/modules'; -import { taskDependenciesReady } from '../src/solver/modules/search'; -import type { ResearchWorker } from '../src/solver/modules/organization'; -import { commitSolverSources, type SolverProblem } from '../src/solver/problem'; -import { assignmentDeliveryFile, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; -import { cooperativeResearch } from './helpers/cooperation'; -import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; -import { verifiedBatch } from './helpers/verifier'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn() })); -vi.mock('../src/math/verifier', async importOriginal => ({ - ...await importOriginal(), - checkManyFormalVerifications: host.verify, - formalVerificationToolIdentity: () => 'delivery-identity-fixture-tools', - resolveMathematicsLakePackagesCache: () => undefined, -})); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.createSession })); - -const verified = (request: MathematicsVerifierBatchRequest) => verifiedBatch(request, { sessionId: 'delivery-identity-fixture' }); - -type TaskAction = Extract; -type Log = 'scoped' | 'legacy'; -const budget = { maxTurns: Infinity, remainingMs: Infinity }; - -describe('assignment-bound worker delivery identities', () => { - let directory: string, problem: SolverProblem, state: SolverRunState; - let lead: ResearchWorker, peer: ResearchWorker, other: ResearchWorker, cooperative: CooperativeResearch; - let instances: { cooperative: CooperativeResearch; controller: AbortController }[]; - let events: { event: string; details?: Record }[]; - let edits: number; - let environment: NodeJS.ProcessEnv; - - const create = () => { - const controller = new AbortController(); - let queue = Promise.resolve(); - const instance = cooperativeResearch({ state, workers: [lead, peer, other], retrievalRoot: directory, - access: new Map([lead, peer, other].map(worker => [worker.id, { environment, retrievalRoot: directory }])), - signal: controller.signal, emit: (event, details) => events.push({ event, details }), - // These `True` helpers exercise worker deliveries; the host battery would close them before dispatch. - modules: { ...directSolverModules, M2: { ...directSolverModules.M2, closeTask: undefined } }, - exclusiveCheck: async check => { - const previous = queue; - let release!: () => void; - queue = new Promise(resolve => { release = resolve; }); - await previous; - try { return await check(); } finally { release(); } - } }); - instances.push({ cooperative: instance, controller }); - return instance; - }; - const start = async (id: string) => { - const action = await cooperative.next(peer, budget); - if (action?.kind !== 'task') throw new Error('missing_delivery_assignment'); - expect(action.task.id).toBe(id); - expect(cooperative.started(peer, action)).toBe(true); - cooperative.activate(peer, action, async () => {}, async () => {}); - return action; - }; - const logName = (action: TaskAction, log: Log) => log === 'scoped' ? assignmentDeliveryFile(action.assignment) : 'DELIVERIES.jsonl'; - const cursorKey = (action: TaskAction, log: Log) => log === 'scoped' ? `${peer.id}/${logName(action, log)}` : peer.id; - const append = (action: TaskAction, log: Log, value: Record) => fs.appendFileSync( - path.join(peer.worktree, logName(action, log)), JSON.stringify(log === 'scoped' ? value : { - taskId: action.task.id, taskDigest: action.assignment.taskDigest, ...value, - }) + '\n'); - const saveProof = (action: TaskAction) => { - const file = path.join(peer.worktree, problem.projectRelative, 'Submission.lean'); - const source = fs.readFileSync(file, 'utf8'); - const declaration = `lemma ${action.task.id} : True := by trivial\n`; - if (!source.includes(declaration)) fs.writeFileSync(file, source.replace('end Tutorial', declaration + 'end Tutorial')); - return commitSolverSources(problem, peer.worktree); - }; - const applyEdit = async (change: (task: CooperativeTask) => CooperativeTask) => { - const id = `edit-${++edits}`; - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id, - baseVersion: state.cooperation!.planVersion, tasks: state.cooperation!.tasks.map(node => change(node.task)) }) + '\n'); - await cooperative.pulse(lead.id); - expect(state.cooperation!.edits?.find(record => record.id === id)?.status).toBe('applied'); - }; - const reassign = async () => { - await applyEdit(task => task.id === 'a' ? { ...task, ownerId: other.id } : task); - await applyEdit(task => task.id === 'a' ? { ...task, ownerId: peer.id } : task); - }; - const restart = async () => { - const instance = instances.find(item => item.cooperative === cooperative)!; - instance.controller.abort(); - await cooperative.stop(); - const file = path.join(directory, 'state.json'); - writeSolverRunState(file, state); - state = readSolverRunState(file); - cooperative = create(); - await cooperative.restore(); - }; - - beforeEach(() => { - const example = localExample('worker-delivery-identity-', 'lead'); - ({ directory, problem } = example); - const envFile = path.join(directory, 'math.env'); - fs.writeFileSync(envFile, ''); - environment = { PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile }; - [peer, other] = ['peer', 'other'].map(id => peerWorker(example, id)); - lead = leadWorker(problem, example.workspace); - const plan = parseCooperationPlan(problem, { tasks: [ - ...problem.targets.map((target, index) => ({ id: `goal_${index}`, kind: 'goal', objective: `Prove ${target.theoremName}.`, - proofPath: target.proofPath, theoremName: target.theoremName, status: 'paused' })), - ...['a', 'b'].map(id => ({ id, kind: 'lemma', objective: `Prove helper ${id}.`, proofPath: 'Submission.lean', - theoremName: `Tutorial.${id}`, type: 'True', ownerId: peer.id })), - ] }); - state = solverState(problem, example.workspace, { runId: 'delivery-identity-fixture', phase: 'running', failures: [], - cooperation: { canonicalCommit: problem.baseCommit, - tasks: plan.tasks.map(task => ({ task, status: 'pending', attempts: 0 })), - groups: plan.groups.map(group => ({ group, turns: 0 })) } }); - host.verify.mockReset().mockImplementation(async request => verified(request)); - host.createSession.mockReset().mockImplementation(() => { throw new Error('real_models_are_not_used_in_delivery_tests'); }); - instances = []; events = []; edits = 0; - cooperative = create(); - }); - afterEach(async () => { - for (const instance of instances) { instance.controller.abort(); await instance.cooperative.stop(); } - expect(host.createSession).not.toHaveBeenCalled(); - vi.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each(['scoped', 'legacy'] as const)('accepts reused explicit ids for different assignments in %s logs and checks each proof once', async log => { - for (const [index, id] of ['a', 'b'].entries()) { - const action = await start(id), commit = saveProof(action); - const value = { id: 'ready', kind: 'proof', commit, summary: `${id} proved.` }; - append(action, log, value); append(action, log, value); - await cooperative.pulse(peer.id); - const node = state.cooperation!.tasks.find(node => node.task.id === id)!; - expect(node.status).toBe('integrated'); - expect(node.proof).toMatchObject({ taskDigest: action.assignment.taskDigest, seedCommit: action.assignment.seedCommit }); - expect(node.integratedCheck?.verification).toEqual(node.proof!.verification); - expect(node.integratedCheck?.verification.targetCommit).toBe(host.verify.mock.calls[index][0].targetCommit); - expect(state.cooperation!.cursors?.[cursorKey(action, log)]).toBe(fs.statSync(path.join(peer.worktree, logName(action, log))).size); - expect(state.cooperation!.deliveries?.filter(record => record.taskId === id && record.submissionId === 'ready')) - .toMatchObject([{ status: 'verified', taskDigest: action.assignment.taskDigest, assignmentKey: assignmentDeliveryFile(action.assignment) }]); - await cooperative.pulse(peer.id); - expect(host.verify).toHaveBeenCalledTimes(index + 1); - cooperative.deactivate(peer); - } - expect(host.verify.mock.calls.map(([request]) => request.items.map((item: { theoremName: string }) => item.theoremName))) - .toEqual([['Tutorial.a'], ['Tutorial.b']]); - expect(events.some(item => item.event === 'delivery_rejected')).toBe(false); - }); - - it.each(['scoped', 'legacy'] as const)('isolates reused ids after a mathematical task revision in %s logs', async log => { - const first = await start('a'); - append(first, log, { id: 'ready', kind: 'proof', commit: saveProof(first) }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - const firstVerification = state.cooperation!.tasks.find(node => node.task.id === 'a')!.integratedCheck!.verification; - expect(host.verify).toHaveBeenCalledOnce(); - // Keep this identity test on the worker publication path; conditional tasks skip canonical adoption. - await applyEdit(task => task.id === 'a' ? { ...task, revision: 1, premises: ['Revised mathematical premise'], conditional: true } : task); - const revised = await start('a'); - expect(revised.assignment.taskDigest).not.toBe(first.assignment.taskDigest); - append(revised, log, { id: 'ready', kind: 'proof', commit: saveProof(revised) }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - const node = state.cooperation!.tasks.find(node => node.task.id === 'a')!; - expect(node).toMatchObject({ task: { revision: 1 }, status: 'integrated', proof: { taskDigest: revised.assignment.taskDigest } }); - expect(node.integratedCheck?.verification).toEqual(node.proof!.verification); - expect(state.cooperation!.deliveries?.filter(record => record.submissionId === 'ready')).toMatchObject([ - { status: 'superseded', taskDigest: first.assignment.taskDigest, assignmentKey: assignmentDeliveryFile(first.assignment) }, - { status: 'verified', taskDigest: revised.assignment.taskDigest, assignmentKey: assignmentDeliveryFile(revised.assignment) }, - ]); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(host.verify.mock.calls.map(([request]) => request.items[0].statementHash)) - .toEqual([first.assignment.taskDigest, revised.assignment.taskDigest]); - expect(host.verify.mock.calls[0][0].items[0].expectedSourceDeclarationHash) - .toBe(host.verify.mock.calls[1][0].items[0].expectedSourceDeclarationHash); - expect(firstVerification.results[0].statementHash).toBe(first.assignment.taskDigest); - expect(node.integratedCheck?.verification.results[0].statementHash).toBe(revised.assignment.taskDigest); - }); - - it.each(['passed', 'failed', 'unavailable'] as const)('allows independent work and isolates consumers while descriptive source revalidation is %s', async outcome => { - const first = await start('a'); - append(first, 'scoped', { id: 'ready', kind: 'proof', commit: saveProof(first) }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - expect(state.cooperation!.tasks.find(node => node.task.id === 'a')?.status).toBe('integrated'); - const unrelated = await cooperative.next(peer, budget); - if (unrelated?.kind !== 'task') throw new Error('missing_unrelated_assignment'); - expect(unrelated.task.id).toBe('b'); - expect(cooperative.current(unrelated)).toBe(true); - const { promise: checking, resolve: entered } = deferred(), { promise: blocked, resolve: release } = deferred(); - host.verify.mockImplementationOnce(async request => { - expect(request.items.map((item: { theoremName: string }) => item.theoremName)).toEqual(['Tutorial.a']); - entered(); await blocked; - const result = verified(request); - const status = outcome === 'unavailable' ? 'unavailable' : 'failed'; - return outcome === 'passed' ? result : { ...result, status, results: result.results.map(item => ({ - ...item, status, stdoutPreview: 'Submission.lean:1:1: error: revalidation rejected the proof', - })) }; - }); - const consumer: CooperativeTask = { id: 'consumer', kind: 'lemma', objective: 'Use the revalidated helper a.', - proofPath: 'Submission.lean', theoremName: 'Tutorial.consumer', type: 'True', dependsOn: ['a'], - ownerId: other.id, revision: 0 }; - fs.appendFileSync(path.join(directory, 'edits.jsonl'), JSON.stringify({ id: 'describe-and-consume', - baseVersion: state.cooperation!.planVersion, - tasks: [...state.cooperation!.tasks.map(node => node.task.id === 'a' - ? { ...node.task, objective: 'Clarify the existing helper a.', revision: 1 } : node.task), consumer], - }) + '\n'); - const pendingEdit = cooperative.pulse(lead.id); - const controller = instances.find(instance => instance.cooperative === cooperative)!.controller; - let synchronization: Promise | undefined; - let pendingAssignment: Promise | undefined; - let assigned = false; - try { - await checking; - await pendingEdit; - synchronization = (cooperative as any).schedulePlanSynchronization() as Promise; - void synchronization.catch(() => {}); - expect(state.cooperation!.tasks.find(node => node.task.id === 'a')?.pendingValidation).toBeDefined(); - expect(taskDependenciesReady(consumer, state.cooperation!.tasks)).toBe(false); - expect(cooperative.current(unrelated)).toBe(true); - expect(cooperative.started(peer, unrelated)).toBe(true); - expect(state.cooperation!.tasks.find(node => node.task.id === 'b')?.attempts).toBe(1); - pendingAssignment = cooperative.next(other, budget).then(action => { assigned = true; return action; }); - void pendingAssignment.catch(() => {}); - await Promise.resolve(); await Promise.resolve(); - expect(assigned).toBe(false); - expect(events.some(item => item.event === 'task_assigned' && item.details?.taskId === 'consumer')).toBe(false); - release(); - if (outcome === 'unavailable') await expect(synchronization).rejects.toThrow('math_verifier_unavailable'); - else { - await synchronization; - expect(state.cooperation!.tasks.find(node => node.task.id === 'a')?.status) - .toBe(outcome === 'passed' ? 'integrated' : 'blocked'); - expect(state.cooperation!.tasks.find(node => node.task.id === 'a')?.pendingValidation).toBeUndefined(); - } - expect(state.cooperation!.tasks.find(node => node.task.id === 'b')).toMatchObject({ status: 'running', attempts: 1 }); - if (outcome === 'passed') { - expect(taskDependenciesReady(consumer, state.cooperation!.tasks)).toBe(true); - const action = await pendingAssignment; - expect(action?.kind).toBe('task'); - if (action?.kind !== 'task') throw new Error('missing_revalidated_consumer'); - expect(action.task.id).toBe('consumer'); - expect(cooperative.started(other, action)).toBe(true); - } else { - await Promise.resolve(); await Promise.resolve(); - expect(taskDependenciesReady(consumer, state.cooperation!.tasks)).toBe(false); - expect(assigned).toBe(false); - if (outcome === 'unavailable') expect(cooperative.started(peer, unrelated)).toBe(false); - expect(events.some(item => item.event === 'task_assigned' && item.details?.taskId === 'consumer')).toBe(false); - expect(state.cooperation!.tasks.find(node => node.task.id === 'consumer')).toMatchObject({ status: 'pending', attempts: 0 }); - if (outcome === 'unavailable') await expect(pendingAssignment).rejects.toThrow('math_verifier_unavailable'); - else { - controller.abort(); - await expect(pendingAssignment).rejects.toThrow(); - } - } - } finally { - release(); await pendingEdit.catch(() => {}); await synchronization?.catch(() => {}); - controller.abort(); await pendingAssignment?.catch(() => {}); - } - }); - - it.each([ - { log: 'scoped', legacyRecord: false }, { log: 'legacy', legacyRecord: false }, - { log: 'scoped', legacyRecord: true }, { log: 'legacy', legacyRecord: true }, - ] as const)('accepts the same task version from a new seed after restore ($log, old record: $legacyRecord)', async ({ log, legacyRecord }) => { - const first = await start('a'); - append(first, log, { id: 'ready', kind: 'progress', summary: 'First assignment evidence.' }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - if (legacyRecord) delete state.cooperation!.deliveries![0].assignmentKey; - await reassign(); - fs.writeFileSync(path.join(peer.worktree, 'RESEARCH.md'), 'A new assignment checkpoint.'); - commitSolverSources(problem, peer.worktree); - await restart(); - const next = await start('a'); - expect(next.assignment.taskDigest).toBe(first.assignment.taskDigest); - expect(next.assignment.seedCommit).not.toBe(first.assignment.seedCommit); - const value = { id: 'ready', kind: 'progress', summary: 'Current assignment evidence.' }; - append(next, log, value); append(next, log, value); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - expect(state.cooperation!.deliveries?.filter(record => record.submissionId === 'ready')).toMatchObject([ - { summary: 'First assignment evidence.' }, - { summary: 'Current assignment evidence.', assignmentKey: assignmentDeliveryFile(next.assignment) }, - ]); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it.each(['scoped', 'legacy'] as const)('accepts reused ids after the same-version assignment is replaced without a new seed in %s logs', async log => { - const first = await start('a'); - append(first, log, { id: 'ready', kind: 'progress', summary: 'First assignment evidence.' }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - await reassign(); - const next = await start('a'); - expect(next.assignment).not.toBe(first.assignment); - expect(next.assignment.taskDigest).toBe(first.assignment.taskDigest); - expect(next.assignment.seedCommit).toBe(first.assignment.seedCommit); - expect(next.assignment.assignmentId).not.toBe(first.assignment.assignmentId); - expect(assignmentDeliveryFile(next.assignment)).not.toBe(assignmentDeliveryFile(first.assignment)); - append(next, log, { id: 'ready', kind: 'progress', summary: 'Replacement assignment evidence.' }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - expect(state.cooperation!.deliveries?.filter(record => record.submissionId === 'ready').map(record => record.summary)) - .toEqual(['First assignment evidence.', 'Replacement assignment evidence.']); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('does not attribute a late old scoped log to a replacement assignment with the same task and seed', async () => { - const first = await start('a'); - append(first, 'scoped', { id: 'ready', kind: 'progress', summary: 'First assignment evidence.' }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - await reassign(); - const next = await start('a'); - expect(next.assignment.seedCommit).toBe(first.assignment.seedCommit); - append(first, 'scoped', { id: 'late', kind: 'proof', commit: saveProof(next), summary: 'Late old assignment proof.' }); - append(next, 'scoped', { id: 'ready', kind: 'progress', summary: 'Replacement assignment evidence.' }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - expect(state.cooperation!.deliveries?.map(record => record.summary)) - .toEqual(['First assignment evidence.', 'Replacement assignment evidence.']); - expect(state.cooperation!.tasks.find(node => node.task.id === 'a')?.proof).toBeUndefined(); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it.each(['scoped', 'legacy'] as const)('keeps a stale asynchronous proof out of the revised task in %s logs', async log => { - const { promise: checking, resolve: entered } = deferred(), { promise: blocked, resolve: release } = deferred(); - host.verify.mockImplementationOnce(async request => { entered(); await blocked; return verified(request); }); - const old = await start('a'); - append(old, log, { id: 'ready', kind: 'proof', commit: saveProof(old) }); - const pending = cooperative.pulse(peer.id); - try { - await checking; - await cooperative.pulse(lead.id); - await applyEdit(task => task.id === 'a' ? { ...task, revision: 1 } : task); - expect(cooperative.current(old)).toBe(false); - } finally { release(); await pending; } - cooperative.deactivate(peer); - expect(state.cooperation!.tasks.find(node => node.task.id === 'a')).toMatchObject({ task: { revision: 1 }, status: 'pending' }); - expect(state.cooperation!.tasks.find(node => node.task.id === 'a')?.proof).toBeUndefined(); - expect(host.verify).toHaveBeenCalledOnce(); - const next = await start('a'); - expect(next.assignment.taskDigest).not.toBe(old.assignment.taskDigest); - append(next, log, { id: 'ready', kind: 'proof', commit: saveProof(next) }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - expect(state.cooperation!.deliveries?.filter(record => record.submissionId === 'ready')).toMatchObject([ - { status: 'superseded', taskDigest: old.assignment.taskDigest, assignmentKey: assignmentDeliveryFile(old.assignment) }, - { status: 'verified', taskDigest: next.assignment.taskDigest, assignmentKey: assignmentDeliveryFile(next.assignment) }, - ]); - const node = state.cooperation!.tasks.find(node => node.task.id === 'a')!; - expect(node).toMatchObject({ status: 'integrated', proof: { taskDigest: next.assignment.taskDigest } }); - expect(node.integratedCheck?.verification).toEqual(node.proof!.verification); - expect(host.verify).toHaveBeenCalledTimes(2); - expect(host.verify.mock.calls.map(([request]) => request.items[0].statementHash)) - .toEqual([old.assignment.taskDigest, next.assignment.taskDigest]); - expect(node.integratedCheck?.verification.targetCommit).toBe(host.verify.mock.calls[1][0].targetCommit); - }); - - it.each(['scoped', 'legacy'] as const)('deduplicates a persisted assignment after replaying a %s cursor', async log => { - const first = await start('a'); - const value = { id: 'ready', kind: 'progress', summary: 'Saved assignment evidence.' }; - append(first, log, value); append(first, log, value); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - state.cooperation!.cursors![cursorKey(first, log)] = 0; - await restart(); - const resumed = await start('a'); - expect(resumed.assignment.assignmentId).toBe(first.assignment.assignmentId); - expect(assignmentDeliveryFile(resumed.assignment)).toBe(assignmentDeliveryFile(first.assignment)); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - expect(state.cooperation!.deliveries).toHaveLength(1); - expect(host.verify).not.toHaveBeenCalled(); - }); - - it('preserves assignment-bound automatic id deduplication for old scoped records', async () => { - const first = await start('a'); - delete first.assignment.assignmentId; - append(first, 'scoped', { summary: 'Automatic assignment evidence.' }); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - delete state.cooperation!.deliveries![0].assignmentKey; - state.cooperation!.cursors![cursorKey(first, 'scoped')] = 0; - await restart(); - await start('a'); - await cooperative.pulse(peer.id); cooperative.deactivate(peer); - expect(state.cooperation!.deliveries).toHaveLength(1); - expect(host.verify).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/workerDeliveryRecovery.test.ts b/tests/workerDeliveryRecovery.test.ts deleted file mode 100644 index 07598a14..00000000 --- a/tests/workerDeliveryRecovery.test.ts +++ /dev/null @@ -1,270 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { CooperativeResearch } from '../src/solver/cooperation'; -import { MAX_DELIVERY_LINE_BYTES, type DeliveryRecord } from '../src/solver/deliveries'; -import { git } from '../src/solver/problem'; -import { assignmentDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; -import { deferred } from './helpers/async'; - -describe('worker delivery log recovery', () => { - let directory: string, commit: string, cooperative: any, controller: AbortController; - let action: Extract; - let cursors: Record, records: DeliveryRecord[], events: { event: string; reason?: string }[]; - let snapshots: Record[]; - const worker = () => ({ id: 'peer', role: 'researcher' as const, worktree: directory, ownedFiles: [] }); - const log = () => assignmentDeliveryFile(action.assignment); - const key = () => `peer/${log()}`; - const append = (value: unknown, legacy = false) => fs.appendFileSync(path.join(directory, legacy ? 'DELIVERIES.jsonl' : log()), - JSON.stringify(legacy && value && typeof value === 'object' ? { - taskId: action.task.id, taskDigest: action.assignment.taskDigest, ...value, - } : value) + '\n'); - const poll = () => cooperative.readWorkerDeliveries(worker(), action, cursors) as Promise; - const create = () => { - const instance = Object.create(CooperativeResearch.prototype); - const node = { task: action.task, status: 'running', attempts: 1, assignment: action.assignment }; - Object.assign(instance, { - archive: { tasks: [node], deliveries: records }, - input: { signal: controller.signal, state: { problem: { baseCommit: commit } }, - save: () => snapshots.push({ ...cursors }), - emit: (event: string, details: { reason?: string }) => events.push({ event, ...details }) }, - current: () => true, dependencies: () => [], reportBlockers: vi.fn(), - record: (_worker: unknown, _task: unknown, kind: DeliveryRecord['kind'], status: DeliveryRecord['status'], - summary: string, options: Partial) => records.push({ producer: 'peer', taskId: action.task.id, - taskDigest: action.assignment.taskDigest, kind, status, summary, ...options } as DeliveryRecord), - }); - instance.publishTaskProof = vi.fn(async (_worker: unknown, _action: unknown, _commit: string, summary: string, - options: Partial) => instance.record(worker(), action.task, 'proof', 'verified', summary, options)); - return instance; - }; - - beforeEach(() => { - directory = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'worker-delivery-recovery-'))); - git(directory, ['init', '--quiet']); - git(directory, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', 'commit', '--quiet', '--allow-empty', '-m', 'Fixture']); - commit = git(directory, ['rev-parse', 'HEAD']); - const task: CooperativeTask = { id: 'a', kind: 'lemma', objective: 'Prove a.', dependsOn: [], revision: 0, - theoremName: 'a', proofPath: 'Submission.lean', type: 'True' }; - action = { kind: 'task', task, assignment: { taskId: task.id, taskDigest: taskVersion(task), workerId: 'peer', - seedCommit: commit, assignmentId: 'dispatch' } }; - controller = new AbortController(); cursors = {}; records = []; events = []; snapshots = []; - cooperative = create(); - }); - afterEach(() => { vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); - - it.each(['storage', 'verifier'] as const)('retries a %s failure without consuming its proof or replaying the accepted prefix', async failure => { - append({ summary: 'Useful prefix.' }); - const prefixEnd = fs.statSync(path.join(directory, log())).size; - append({ id: 'proof', kind: 'proof', commit, summary: 'Checked proof.' }); - append({ summary: 'Useful suffix.' }); - const error = failure === 'storage' ? Object.assign(new Error('Transient storage failure'), { code: 'EIO' }) : - new Error('math_verifier_unavailable'); - cooperative.publishTaskProof.mockRejectedValueOnce(error); - await expect(poll()).rejects.toBe(error); - expect(cursors[key()]).toBe(prefixEnd); - expect(snapshots.at(-1)?.[key()]).toBe(prefixEnd); - expect(records.map(record => record.summary)).toEqual(['Useful prefix.']); - expect(events).toEqual([]); - await poll(); - expect(records.map(record => record.summary)).toEqual(['Useful prefix.', 'Checked proof.', 'Useful suffix.']); - expect(cooperative.publishTaskProof).toHaveBeenCalledTimes(2); - expect(cursors[key()]).toBe(fs.statSync(path.join(directory, log())).size); - }); - - it('preserves an aborted proof for a resumed reader', async () => { - append({ summary: 'Useful prefix.' }); - const prefixEnd = fs.statSync(path.join(directory, log())).size; - append({ kind: 'proof', commit, summary: 'Resume this proof.' }); - cooperative.publishTaskProof.mockImplementationOnce(async () => { - controller.abort(); controller.signal.throwIfAborted(); - }); - await expect(poll()).rejects.toMatchObject({ name: 'AbortError' }); - expect(cursors[key()]).toBe(prefixEnd); - expect(snapshots.at(-1)?.[key()]).toBe(prefixEnd); - expect(events).toEqual([]); - controller = new AbortController(); cooperative = create(); - await poll(); - expect(records.map(record => record.summary)).toEqual(['Useful prefix.', 'Resume this proof.']); - }); - - it('does not consume any line when the run was already stopped', async () => { - append({ kind: 'proof', commit }); controller.abort(); - await expect(poll()).rejects.toMatchObject({ name: 'AbortError' }); - expect(cursors[key()] ?? 0).toBe(0); - expect(cooperative.publishTaskProof).not.toHaveBeenCalled(); - expect(events).toEqual([]); - }); - - it('rejects malformed JSON, schema and nonexistent commits once, then accepts later lines', async () => { - fs.appendFileSync(path.join(directory, log()), '{broken\n'); - append({ summary: 123 }); - append({ kind: 'proof', commit: 'not a commit' }); - append({ kind: 'proof', commit: '0'.repeat(40) }); - append({ summary: 'Still useful.' }); - await poll(); await poll(); - expect(events.map(event => event.reason)).toEqual(['math_delivery_invalid_json', 'math_delivery_invalid', - 'math_delivery_requires_fixed_proof', 'math_delivery_invalid_commit']); - expect(records.map(record => record.summary)).toEqual(['Still useful.']); - expect(cooperative.publishTaskProof).not.toHaveBeenCalled(); - }); - - it('saves actionable rejection receipts with the cursor and retries notification after restore', async () => { - fs.appendFileSync(path.join(directory, log()), '{broken\n'); - const notify = vi.fn().mockRejectedValueOnce(new Error('transport unavailable')); - cooperative.active = new Map([['peer', { action, notify }]]); - await poll(); - const receipt = cooperative.archive.deliveryReceipts[0]; - expect(receipt).toMatchObject({ workerId: 'peer', assignmentKey: log(), taskId: action.task.id, - taskDigest: action.assignment.taskDigest, status: 'needs-correction', code: 'math_delivery_invalid_json', - issues: [{ path: '$', message: 'math_delivery_invalid_json' }] }); - expect(snapshots.at(-1)?.[key()]).toBe(fs.statSync(path.join(directory, log())).size); - const saved = JSON.parse(JSON.stringify(cooperative.archive.deliveryReceipts)); - cursors = JSON.parse(JSON.stringify(cursors)); cooperative = create(); - cooperative.archive.deliveryReceipts = saved; - const resumedNotify = vi.fn().mockResolvedValue(undefined); - cooperative.active = new Map([['peer', { action, notify: resumedNotify }]]); - await poll(); await poll(); - expect(resumedNotify).toHaveBeenCalledOnce(); - expect(resumedNotify.mock.calls[0][0]).toContain(receipt.id); - expect(cooperative.archive.deliveryReceipts).toEqual(saved); - expect(events.filter(event => event.event === 'delivery_rejected')).toHaveLength(1); - }); - - it('keeps consuming worker deliveries while a correction notice waits for its request boundary', async () => { - fs.appendFileSync(path.join(directory, log()), '{broken\n'); - let release!: () => void; - const waiting = new Promise(resolve => { release = resolve; }); - const notify = vi.fn(() => waiting); - cooperative.active = new Map([['peer', { action, notify }]]); - try { - const firstPoll = poll(); - expect(await Promise.race([firstPoll.then(() => 'polled'), new Promise(resolve => setTimeout(() => resolve('blocked'), 100))])) - .toBe('polled'); - append({ summary: 'Progress produced while the reminder is pending.' }); - await poll(); - expect(records.map(record => record.summary)).toEqual(['Progress produced while the reminder is pending.']); - expect(notify).toHaveBeenCalledOnce(); - release(); await Promise.resolve(); await Promise.resolve(); - await poll(); expect(notify).toHaveBeenCalledOnce(); - } finally { release(); } - }); - - it('retries a pending correction notice after delivery fails without replaying accepted logs', async () => { - fs.appendFileSync(path.join(directory, log()), '{broken\n'); - let rejectNotice!: (error: Error) => void; - const waiting = new Promise((_resolve, reject) => { rejectNotice = reject; }); - const notify = vi.fn().mockImplementationOnce(() => waiting).mockResolvedValue(undefined); - cooperative.active = new Map([['peer', { action, notify }]]); - await poll(); await poll(); expect(notify).toHaveBeenCalledOnce(); - rejectNotice(new Error('turn settled before delivery')); - await Promise.allSettled([...cooperative.notifications]); - append({ summary: 'Keep this progress while retrying the reminder.' }); - await poll(); await Promise.allSettled([...cooperative.notifications]); await poll(); - expect(notify).toHaveBeenCalledTimes(2); - expect(cooperative.archive.deliveryReceipts).toHaveLength(1); - expect(records.map(record => record.summary)).toEqual(['Keep this progress while retrying the reminder.']); - }); - - it('lets a replacement session receive a correction while the previous notice is still pending', async () => { - fs.appendFileSync(path.join(directory, log()), '{broken\n'); - const previous = deferred(), current = deferred(); - const oldNotify = vi.fn(() => previous.promise), newNotify = vi.fn(() => current.promise); - cooperative.active = new Map([['peer', { action, notify: oldNotify }]]); - try { - await poll(); - expect(oldNotify).toHaveBeenCalledOnce(); - cooperative.active.set('peer', { action, notify: newNotify }); - await poll(); await poll(); - expect(newNotify).toHaveBeenCalledOnce(); - const receipt = cooperative.archive.deliveryReceipts[0]; - expect(newNotify.mock.calls[0]).toEqual([expect.stringContaining(receipt.id)]); - - const oldNotice = [...cooperative.notifications][0]; - previous.reject(new Error('previous session closed')); - await oldNotice; - await poll(); - expect(newNotify).toHaveBeenCalledOnce(); - expect(cooperative.archive.deliveryReceipts).toHaveLength(1); - expect(events.filter(event => event.event === 'delivery_rejected')).toHaveLength(1); - } finally { - previous.resolve(); current.resolve(); - await Promise.allSettled([...cooperative.notifications]); - } - }); - - it('rejects a commit outside the frozen problem history once without blocking following progress', async () => { - const tree = git(directory, ['rev-parse', `${commit}^{tree}`]); - const unrelated = git(directory, ['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost', - 'commit-tree', tree, '-m', 'Unrelated root']); - append({ kind: 'proof', commit: unrelated }); append({ summary: 'Valid progress after the rejected root.' }); - await poll(); await poll(); - expect(events.map(event => event.reason)).toEqual(['math_delivery_invalid_commit']); - expect(cooperative.publishTaskProof).not.toHaveBeenCalled(); - expect(records.map(record => record.summary)).toEqual(['Valid progress after the rejected root.']); - }); - - it.each(['math_task_existing_declaration_changed', 'math_original_context_changed', 'math_trusted_source_changed'])( - 'consumes a deterministic source rejection once: %s', async reason => { - append({ kind: 'proof', commit }); append({ summary: 'The following progress.' }); - cooperative.publishTaskProof.mockRejectedValueOnce(new Error(reason + '\nRestore the frozen source.')); - await poll(); await poll(); - expect(cooperative.publishTaskProof).toHaveBeenCalledOnce(); - expect(events).toEqual([{ event: 'delivery_rejected', workerId: 'peer', reason: reason + '\nRestore the frozen source.' }]); - expect(records.map(record => record.summary)).toEqual(['The following progress.']); - }); - - it.each([null, false, 42, 'plain string', []])('rejects a scoped non-object response %j', async value => { - append(value); append({ summary: 'Valid object.' }); - await poll(); await poll(); - expect(events.map(event => event.reason)).toEqual(['math_delivery_invalid']); - expect(records.map(record => record.summary)).toEqual(['Valid object.']); - }); - - it('discards a complete oversized line in bounded chunks and keeps both log streams usable', async () => { - fs.appendFileSync(path.join(directory, log()), JSON.stringify({ summary: 'x'.repeat(MAX_DELIVERY_LINE_BYTES * 2 + 100) }) + '\n'); - append({ summary: 'Scoped progress after the oversized line.' }); - append({ id: 'legacy', kind: 'progress', summary: 'Legacy progress.' }, true); - const read = vi.spyOn(fs, 'readSync'); - await poll(); - expect(records.map(record => record.summary)).toEqual(['Legacy progress.']); - expect(cursors[`${key()}/discardingOversized`]).toBe(1); - expect(snapshots.at(-1)?.[`${key()}/discardingOversized`]).toBe(1); - cursors = JSON.parse(JSON.stringify(cursors)); cooperative = create(); - await poll(); await poll(); await poll(); - expect(events.map(event => event.reason)).toEqual(['math_delivery_line_too_large']); - expect(records.map(record => record.summary)).toEqual(['Legacy progress.', 'Scoped progress after the oversized line.']); - expect(cursors[`${key()}/discardingOversized`]).toBe(0); - expect(read.mock.calls.every(call => call[3] <= MAX_DELIVERY_LINE_BYTES + 1)).toBe(true); - }); - - it('remembers an oversized partial write across resume and never parses its trailing fragment', async () => { - fs.appendFileSync(path.join(directory, log()), 'x'.repeat(MAX_DELIVERY_LINE_BYTES + 1)); - await poll(); await poll(); - expect(events.map(event => event.reason)).toEqual(['math_delivery_line_too_large']); - cursors = JSON.parse(JSON.stringify(cursors)); cooperative = create(); - fs.appendFileSync(path.join(directory, log()), '{"summary":"Tail fragment must stay rejected."}\n'); - append({ summary: 'A complete new line.' }); - await poll(); - expect(records.map(record => record.summary)).toEqual(['A complete new line.']); - expect(events.map(event => event.reason)).toEqual(['math_delivery_line_too_large']); - }); - - it('reports a rewritten log once, never replays its contents and keeps reading appended lines across resume', async () => { - append({ summary: 'First progress.' }); append({ summary: 'Second progress.' }); - await poll(); - const file = path.join(directory, log()); - fs.writeFileSync(file, JSON.stringify({ summary: 'Rewritten copy.' }) + '\n{"summary":"Unfin'); - await expect(poll()).resolves.toBeUndefined(); - expect(events).toEqual([{ event: 'delivery_rejected', workerId: 'peer', reason: 'math_delivery_log_rewritten' }]); - expect(cursors[key()]).toBe(fs.statSync(file).size); - expect(snapshots.at(-1)?.[`${key()}/discardingOversized`]).toBe(1); - cursors = JSON.parse(JSON.stringify(cursors)); cooperative = create(); - fs.appendFileSync(file, 'ished rewrite."}\n'); append({ summary: 'Appended progress.' }); - await poll(); await poll(); - expect(records.map(record => record.summary)).toEqual(['First progress.', 'Second progress.', 'Appended progress.']); - expect(events).toHaveLength(1); - expect(cursors[`${key()}/discardingOversized`]).toBe(0); - }); - -}); diff --git a/tests/workerProofCheckpoint.test.ts b/tests/workerProofCheckpoint.test.ts deleted file mode 100644 index 1c265785..00000000 --- a/tests/workerProofCheckpoint.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, expect, it, vi } from 'vitest'; -import { localExample, leadWorker, peerWorker, solverState } from './helpers/solver'; -import { receiptBatch } from './helpers/verifier'; -import { commitSolverSources } from '../src/solver/problem'; -import { ownedSourceDigest } from '../src/solver/cooperativeProof'; -import { proofReadyRecord } from '../src/solver/proofReady'; -import { taskVersion, parseCooperationPlan, type TaskAssignment } from '../src/solver/tasks'; -import { directSolverModules } from '../src/solver/modules'; -import { runResearchWorkers } from '../src/solver/research'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { withVerificationCheckpoints, VerificationCheckpointError } from '../src/solver/verificationCheckpoint'; -import { deferred } from './helpers/async'; - -const host = vi.hoisted(() => ({ verify: vi.fn(), open: vi.fn() })); -vi.mock('../src/math/verifier', async original => ({ ...await original(), - checkManyFormalVerifications: host.verify, formalVerificationToolIdentity: () => 'checkpoint-fixture', - resolveMathematicsLakePackagesCache: () => undefined })); -vi.mock('../src/runtime/codexSession', () => ({ createCodexMathSession: host.open })); - -let directory: string; -afterEach(() => { if (directory) fs.rmSync(directory, { recursive: true, force: true }); vi.restoreAllMocks(); }); - -function frozenProofFixture() { - host.open.mockReset(); host.verify.mockReset(); - const example = localExample('worker-proof-checkpoint-', 'lead'); directory = example.directory; - const lead = leadWorker(example.problem, example.workspace), peer = peerWorker(example, 'engineer', { role: 'engineer' }); - const sourceFile = path.join(peer.worktree, example.problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(sourceFile, fs.readFileSync(sourceFile, 'utf8').replace('by sorry', 'by rfl')); - const commit = commitSolverSources(example.problem, peer.worktree); - const plan = parseCooperationPlan(example.problem, { tasks: example.problem.targets.map((target, index) => ({ - id: `goal_${index}`, kind: 'goal', objective: 'Prove the original goal.', proofPath: target.proofPath, - theoremName: target.theoremName, ownerId: peer.id, - })) }); - const task = plan.tasks[0]!; - const assignment: TaskAssignment = { taskId: task.id, taskDigest: taskVersion(task), workerId: peer.id, - seedCommit: example.problem.baseCommit, assignmentId: 'frozen-assignment' }; - const ready = { ...proofReadyRecord({ assignment, workerId: peer.id, submissionId: 'saved-ready', - environmentDigest: 'environment', problemReceiptDigest: example.problem.receiptDigest, now: 1 }), - status: 'frozen' as const, snapshotCommit: commit, sourceDigest: ownedSourceDigest(example.problem, peer.worktree, commit), frozenAt: 2 }; - let state = solverState(example.problem, example.workspace, { runId: 'same-frozen-run', phase: 'running', workerCount: 2, - workers: [lead, peer].map(worker => ({ ...worker, phase: 'running', turns: 0 })), - cooperation: { canonicalCommit: example.problem.baseCommit, planVersion: 'fixture-plan', planEdited: true, - groups: plan.groups.map(group => ({ group, turns: 0 })), leadWakes: { requested: 0, consumed: 0, settled: 0 }, - tasks: plan.tasks.map(item => ({ task: item, status: 'pending', attempts: 1, - ...(item === task ? { assignment } : {}) })), proofReadyRecords: [ready] } }); - const file = path.join(directory, 'state.json'), environmentFile = path.join(directory, 'math.env'); fs.writeFileSync(environmentFile, ''); - const access = new Map([lead, peer].map(worker => [worker.id, { environment: { - PATH: '/usr/bin:/bin', DEEPSCIENTIST_MATH_ENV_FILE: environmentFile }, retrievalRoot: directory }])); - host.open.mockImplementation(() => { throw new Error('unexpected_model_writer'); }); - const execute = (signal: AbortSignal, emit: (event: string) => void = () => {}) => withVerificationCheckpoints({ - environmentDigest: state.environmentDigest, problemReceiptDigest: state.problem.receiptDigest, - checkpoints: state.verificationCheckpoints ??= [], save: () => writeSolverRunState(file, state), emit, - }, () => runResearchWorkers({ state, workers: [lead, peer], access, modules: { ...directSolverModules, - M2: { ...directSolverModules.M2, closeTask: undefined } }, root: directory, buildFile: 'unused', taskText: 'Prove the goals.', - executable: 'unused', profile: 'unused', signal, deadline: Infinity, maxTurns: Infinity, - maxTurnMs: Infinity, maxTotalTokens: 0, proofTimeoutMs: 1000, save: () => writeSolverRunState(file, state), emit })); - return { commit, execute, get state() { return state; }, reload() { state = readSolverRunState(file); } }; -} - -const timedOut = (request: Parameters[0]) => { - const batch = receiptBatch(request, { sessionId: 'timeout', receiptId: i => `timeout-${i}` }); - return { ...batch, status: 'blocked' as const, results: batch.results.map(item => ({ ...item, - status: 'blocked' as const, error: 'Lean verification timed out.' })) }; -}; - -it('checkpoints and restores a frozen cooperative proof before any new model writer starts', async () => { - const f = frozenProofFixture(); - host.verify.mockImplementation(async request => timedOut(request)); - const failure = await f.execute(new AbortController().signal).catch(error => error); - expect(failure).toBeInstanceOf(VerificationCheckpointError); - f.reload(); - expect(f.state.cooperation!.proofReadyRecords![0]).toMatchObject({ status: 'frozen', snapshotCommit: f.commit }); - expect(f.state.cooperation!.tasks[0]!.status).toBe('pending'); expect(host.open).not.toHaveBeenCalled(); - host.verify.mockImplementation(async request => receiptBatch(request, { sessionId: 'resumed', receiptId: i => `resumed-${i}` })); - const resumed = new AbortController(); - await expect(f.execute(resumed.signal, event => { if (event === 'proof_ready_checked') resumed.abort(); })).rejects.toMatchObject({ name: 'AbortError' }); - expect(f.state.runId).toBe('same-frozen-run'); - expect(f.state.cooperation!.proofReadyRecords![0]).toMatchObject({ status: 'checked', snapshotCommit: f.commit }); - expect(host.open).not.toHaveBeenCalled(); - expect(host.verify.mock.calls[0]![0].timeoutMs).toBe(1000); - expect(host.verify.mock.calls[1]![0].timeoutMs).toBe(2000); -}); - -it.each([false, true])('retains the frozen candidate across a cancelled verification and repeated restarts (prior timeout: %s)', async priorTimeout => { - const f = frozenProofFixture(); - if (priorTimeout) { - host.verify.mockImplementation(async request => timedOut(request)); - await expect(f.execute(new AbortController().signal)).rejects.toBeInstanceOf(VerificationCheckpointError); - f.reload(); - } - const checkpoints = structuredClone(f.state.verificationCheckpoints ?? []); - const started = deferred(); - host.verify.mockImplementation(async (_request, options) => { - started.resolve(); - options.signal.throwIfAborted(); - await new Promise((_resolve, reject) => options.signal.addEventListener('abort', - () => reject(new DOMException('Cancelled verification', 'AbortError')), { once: true })); - }); - const cancelled = new AbortController(), pending = f.execute(cancelled.signal); - const rejected = expect(pending).rejects.toMatchObject({ name: 'AbortError' }); - await started.promise; cancelled.abort(); await rejected; - f.reload(); - expect(f.state.verificationCheckpoints ?? []).toEqual(checkpoints); - expect(f.state.cooperation!.proofReadyRecords![0]).toMatchObject({ status: 'frozen', snapshotCommit: f.commit }); - expect(f.state.cooperation!.tasks[0]!.status).toBe('pending'); - expect(f.state.turns).toBe(0); expect(f.state.check?.passed).not.toBe(true); - - host.verify.mockClear().mockImplementation(async request => timedOut(request)); - for (const expected of priorTimeout ? [2000, 4000] : [1000, 2000]) { - await expect(f.execute(new AbortController().signal)).rejects.toBeInstanceOf(VerificationCheckpointError); - f.reload(); - expect(f.state.verificationCheckpoints).toMatchObject([{ timeoutMs: expected }]); - expect(f.state.cooperation!.proofReadyRecords![0]).toMatchObject({ status: 'frozen', snapshotCommit: f.commit }); - expect(f.state.check?.passed).not.toBe(true); - } - const limits = host.verify.mock.calls.map(([request]) => request.timeoutMs); - expect(limits).toEqual(priorTimeout ? [2000, 4000] : [1000, 2000]); - host.verify.mockImplementation(async request => receiptBatch(request, { sessionId: 'fresh-after-cancellation', receiptId: i => `fresh-${i}` })); - const resumed = new AbortController(); - await expect(f.execute(resumed.signal, event => { if (event === 'proof_ready_checked') resumed.abort(); })) - .rejects.toMatchObject({ name: 'AbortError' }); - expect(f.state.cooperation!.proofReadyRecords![0]).toMatchObject({ status: 'checked', snapshotCommit: f.commit, - receiptIds: ['fresh-0'] }); - expect(f.state.runId).toBe('same-frozen-run'); expect(f.state.turns).toBe(0); - expect(host.open).not.toHaveBeenCalled(); -}); diff --git a/tests/workerRecovery.test.ts b/tests/workerRecovery.test.ts index 645a67f6..8be37d47 100644 --- a/tests/workerRecovery.test.ts +++ b/tests/workerRecovery.test.ts @@ -218,49 +218,6 @@ describe('bounded role session recovery', () => { expect(host.official).toHaveBeenCalledOnce(); }); - it('keeps a cooperative proof worker available after an empty upstream failure', async () => { - const assignments = new Map(); - let proofTurns = 0; - let failedWorkspace: string | undefined, failedThread: string | undefined; - host.open.mockImplementation(async (options: MathAgentOptions) => { - let diagnostic: MathAgentFailureDiagnostic | undefined; - const current: MathAgentSession = session(options, async () => { - const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') research(options, { tasks: [claim] }); - else if (action.kind === 'task') { - if (++proofTurns === 1) { - failedWorkspace = options.workspace; - failedThread = current.threadId; - diagnostic = { code: 'other', reason: 'upstream_request_failed' }; - return 'failed'; - } - expect(options.workspace).toBe(failedWorkspace); - expect(options.threadId).toBe(failedThread); - expect(fs.readFileSync(proof(options), 'utf8')).toBe(original); - fs.writeFileSync(proof(options), completed); - } else throw new Error(`unexpected recovery action: ${action.kind}`); - return 'completed'; - }, 'upstream request failed: completed turn had no assistant output or tool operation'); - return { ...current, get lastFailureDiagnostic() { return diagnostic; } }; - }); - expect(await cooperate(assignments)).toBe(0); - expect(proofTurns).toBe(2); - expect(result().status).toBe('evaluated_passed'); - expect(events().filter(event => event.event === 'worker_recovering')).toEqual([ - expect.objectContaining({ reason: 'math_model_request_failed', attempt: 1, delayMs: 10_000 }), - ]); - expect(events().filter(event => event.event === 'turn_retry')).toHaveLength(1); - expect(events().filter(event => event.event === 'context_restarted' && event.reason === 'request' && - event.previousThreadId === failedThread)).toHaveLength(0); - expect(events().filter(event => event.event === 'worker_failed')).toHaveLength(0); - expect(state().workers.some((worker: { lastFailure?: { reason: string; diagnostic?: MathAgentFailureDiagnostic } }) => - worker.lastFailure?.reason === 'math_model_request_failed' && - worker.lastFailure.diagnostic?.reason === 'upstream_request_failed')).toBe(true); - expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(state().cooperation.review).toBeUndefined(); - expect(host.official).toHaveBeenCalledOnce(); - }); - it('resumes an accepted check saved after restoring the running phase without another model turn', async () => { host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { fs.writeFileSync(proof(options), completed); return 'completed'; @@ -316,27 +273,6 @@ describe('bounded role session recovery', () => { expect(host.official).not.toHaveBeenCalled(); }); - it('keeps peers running after a Lead context overflow with a saved valid plan', async () => { - const assignments = new Map(); - let leadOverflow = false; - host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { - const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') { - research(options, { tasks: [claim] }); - if (!leadOverflow) { leadOverflow = true; throw new Error('contextWindowExceeded'); } - } else if (action.kind === 'task') fs.writeFileSync(proof(options), completed); - else if (action.kind === 'review') research(options, { commit: action.seedCommit, verdict: 'accepted' }); - else throw new Error(`unexpected action: ${action.kind}`); - return 'completed'; - })); - expect(await cooperate(assignments)).toBe(0); - expect(leadOverflow).toBe(true); - expect(events().filter(event => event.event === 'worker_failed')).toHaveLength(0); - expect(events().filter(event => event.event === 'worker_context_recovering')).toHaveLength(1); - expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(host.official).toHaveBeenCalledOnce(); - }); - it.each(['tool', 'network'] as const)('recovers a thrown %s failure in the same role with saved notes, proof and exact usage', async kind => { const detail = kind === 'tool' ? 'Error parsing function call: invalid JSON arguments' : 'stream disconnected before completion: error sending request'; host.open.mockImplementationOnce(async (options: MathAgentOptions) => session(options, async () => { @@ -521,35 +457,6 @@ describe('bounded role session recovery', () => { expect(host.official).not.toHaveBeenCalled(); }); - it.each(['solver', 'engineer'] as const)('keeps cooperative worker %s available after a sustained startup outage', async workerId => { - recoveryClock(); - const assignments = new Map(); - let failedOpenings = 0; - host.open.mockImplementation(async (options: MathAgentOptions) => { - if (options.environment.DEEPSCIENTIST_MATH_WORKER_ID === workerId && ++failedOpenings <= 5) - throw new Error('math_codex_transport_closed'); - return session(options, async () => { - const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') research(options, { tasks: [{ ...claim, ownerId: 'engineer' }] }); - else if (action.kind === 'task') fs.writeFileSync(proof(options), completed); - else throw new Error(`unexpected recovery action: ${action.kind}`); - return 'completed'; - }); - }); - expect(await cooperate(assignments)).toBe(0); - expect(state().workers.find((worker: { id: string }) => worker.id === workerId)).toMatchObject({ - recovery: { phase: 'recovered', reason: 'math_codex_transport_closed', cycles: 1, waitedMs: 60_000 }, - }); - expect(state().workers.every((worker: { error?: string }) => !worker.error)).toBe(true); - expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(state().cooperation.review).toBeUndefined(); - expect(events().filter(event => event.event === 'worker_failed')).toHaveLength(0); - expect(events().filter(event => event.event === 'worker_cooling_down')).toEqual([ - expect.objectContaining({ workerId, cycle: 1, delayMs: 60_000 }), - ]); - expect(host.official).toHaveBeenCalledOnce(); - }); - it('bounds repeated tool schema failures without setting any solving deadline or discarding the draft', async () => { host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { fs.writeFileSync(proof(options), partial); options.onUsage({ totalTokens: 3 }); return 'failed'; @@ -596,76 +503,6 @@ describe('bounded role session recovery', () => { expect(host.official).not.toHaveBeenCalled(); }); - it.each(['Invalid authentication', 'unclassified provider failure'])('retains a checked task proof but stops its worker after a hard failure: %s', async error => { - const assignments = new Map(); - let proofTurns = 0; - host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { - const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') research(options, { tasks: [claim, finalAudit] }); - else if (action.kind === 'task') { - proofTurns++; fs.writeFileSync(proof(options), completed); options.onUsage({ totalTokens: 11 }); - return 'failed'; - } else throw new Error('hard-failed worker must not be dispatched for review'); - options.onUsage({ totalTokens: 8 }); return 'completed'; - }, error)); - expect(await cooperate(assignments)).toBe(1); - expect(proofTurns).toBe(1); - expect(events().filter(event => event.event === 'task_integrated' && event.taskId === 'claim')).toHaveLength(1); - expect(events().filter(event => event.event === 'worker_recovered')).toHaveLength(0); - expect(state().workers.some((worker: { error?: string }) => worker.error === researchFailureReason(error))).toBe(true); - expect(host.delay).not.toHaveBeenCalled(); expect(host.official).not.toHaveBeenCalled(); - }); - - it('continues distinct typed proof checkpoints beyond the first repair without a solving limit', async () => { - const assignments = new Map(); - let proofTurns = 0; - host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { - const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') research(options, { tasks: [claim] }); - else if (action.kind === 'task') { - proofTurns++; - const helpers = Array.from({ length: Math.min(proofTurns, 3) }, (_, index) => - `lemma checkpoint_${index + 1} : True := by trivial\n`).join(''); - const draft = original.replace('theorem claim', helpers + 'theorem claim'); - fs.writeFileSync(proof(options), proofTurns <= 3 ? draft : draft.replace('by sorry', 'by exact checkpoint_3')); - options.onUsage({ totalTokens: 11 }); - return proofTurns <= 3 ? 'checkpoint' : 'completed'; - } else throw new Error(`unexpected checkpoint action: ${action.kind}`); - options.onUsage({ totalTokens: 8 }); return 'completed'; - })); - expect(await cooperate(assignments)).toBe(0); - expect(proofTurns).toBe(4); - expect(events().filter(event => event.event === 'turn_checkpoint')).toHaveLength(3); - expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(state().cooperation.review).toBeUndefined(); - expect(host.delay).not.toHaveBeenCalled(); expect(host.official).toHaveBeenCalledOnce(); - }); - - it('checks and integrates a saved proof once after a tool failure, then keeps the peer available for an explicit review', async () => { - const assignments = new Map(); - let proofTurns = 0; - host.open.mockImplementation(async (options: MathAgentOptions) => session(options, async () => { - const action = assignments.get(options.workspace)!; - if (action.kind === 'lead') research(options, { tasks: [claim, finalAudit] }); - else if (action.kind === 'task') { - proofTurns++; fs.writeFileSync(proof(options), completed); - options.onUsage({ totalTokens: 11 }); - throw new Error('math_model_turn_failed', { cause: new Error('Error parsing function call: invalid JSON arguments') }); - } else if (action.kind === 'review') research(options, { commit: action.seedCommit, verdict: 'accepted' }); - else throw new Error(`unexpected offline action: ${action.kind}`); - options.onUsage({ totalTokens: 8 }); return 'completed'; - })); - expect(await cooperate(assignments)).toBe(0); - expect(proofTurns).toBe(1); - expect(events().filter(event => event.event === 'task_integrated' && event.taskId === 'claim')).toHaveLength(1); - expect(events().filter(event => event.event === 'worker_recovered')).toEqual([ - expect.objectContaining({ reason: 'math_model_tool_failed', savedTaskProof: true }), - ]); - expect(state().cooperation.review.status).toBe('accepted'); - expect(state().cooperation.tasks[0].status).toBe('integrated'); - expect(state().workers.every((worker: { error?: string }) => !worker.error)).toBe(true); - expect(host.official).toHaveBeenCalledOnce(); - }); }); describe('recoverable failure classification', () => { From 14dfd50795c82d9a8e98b9d0ef076ef62045c1bb Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Sat, 28 Nov 2026 01:26:52 +0800 Subject: [PATCH 2/7] Return the refreshed team budget to the Lead --- src/solver/agentTeam.ts | 1 + src/solver/research.ts | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index 2e77893c..e05e43c1 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -199,6 +199,7 @@ export class AgentResearchTeam { const records = [state, ...this.archive.workers]; state.tokenBudget = buildTokenBudget(this.input.maxTotalTokens, records, state.tokenBudget?.enforcement); state.teamUsage = aggregateUsage(records); + return state.tokenBudget; } private event(from: string | null, to: string, kind: AgentTeamState['events'][number]['kind'], message: string, diff --git a/src/solver/research.ts b/src/solver/research.ts index 6aab405f..b0793245 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -150,9 +150,8 @@ export async function runResearchLead(input: { : { turnTimeoutMs: Number.isFinite(input.maxTurnMs) ? input.maxTurnMs : undefined }; const updateUsage = () => { const previous = state.tokenBudget!.status; - if (team) team.refreshUsage(); - else state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [research], enforcement); - if (state.tokenBudget.status !== previous && !dispatchAllowed()) input.emit('model_budget_stopped', { ...state.tokenBudget }); + const next = team ? team.refreshUsage() : (state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [research], enforcement)); + if (next.status !== previous && !modelDispatchAllowed(next)) input.emit('model_budget_stopped', { ...next }); }; const errors: unknown[] = []; const cleanupErrors: unknown[] = []; From 2eeaa3fd1d8cbeab109583c344d172738de8e139 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Sat, 28 Nov 2026 01:30:20 +0800 Subject: [PATCH 3/7] Keep historical run events translated after scheduler retirement --- apps/web/i18n/errors.ts | 4 +--- apps/web/i18n/release.ts | 1 - scripts/web-i18n.ts | 6 +++++- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/web/i18n/errors.ts b/apps/web/i18n/errors.ts index da63f16d..a0b3cf7f 100644 --- a/apps/web/i18n/errors.ts +++ b/apps/web/i18n/errors.ts @@ -42,7 +42,7 @@ export const errors: Record = { '无法选择角色偏好:{0}。请从当前角色目录中选择。': 'Unknown profile: {0}. Choose a profile from the current catalog.', '原生团队由一名 Lead 自主派工,不能与宿主协作或自定义模块方案一起使用。': 'The Lead coordinates the native team. Host collaboration and custom module plans are unavailable with native teams.', '原生团队不使用自定义模块方案。': 'Native teams do not use custom module plans.', - '此研究安排不支持该协作操作。': 'This research mode does not support that collaboration action.', + '此研究安排不支持计划审批。': 'This research mode does not support plan approval.', '当前运行镜像未安装支持原生团队与路线审批的 worker,请更新运行镜像。': 'Update the worker image to support native teams and route approval.', '这次运行的 Codex 模型服务已不在配置中。': 'This run’s Codex model provider is no longer configured.', '旧协作任务请使用对应的历史版本继续。新建多人研究使用 Codex 原生团队。': 'Continue old collaboration runs from the matching historical release. New multi-agent runs use Codex native teams.', @@ -221,8 +221,6 @@ export const errors: Record = { "指导未能提交。": "The guidance could not be submitted.", "请重新读取当前计划后再批准。": "Reload the current plan before approving it.", "计划批准未能提交。": "The plan approval could not be submitted.", - "计划草稿格式无效,请保留完整计划与基线版本。": "Invalid plan draft; keep the complete plan and its base version.", - "计划未能提交。": "The plan could not be submitted.", "归档不存在。": "Archive not found.", "只有通过独立验收的运行可以分享。": "Only runs that passed independent acceptance can be shared.", "排队中或运行中的任务不能删除,请先取消或等待结束。": "A queued or running task cannot be deleted; cancel it or wait for it to finish.", diff --git a/apps/web/i18n/release.ts b/apps/web/i18n/release.ts index 2329480b..390c2ef1 100644 --- a/apps/web/i18n/release.ts +++ b/apps/web/i18n/release.ts @@ -118,7 +118,6 @@ export const release: Record = { '撤回结果尚未确认,可以稍后再试一次。': 'The withdrawal is not confirmed yet. You can try again shortly.', '这条指导或它关联的证明任务不存在。': 'This guidance or its proof task no longer exists.', '撤回未能提交。': 'The withdrawal could not be submitted.', - '请检查要撤回的指导。': 'Check the guidance to withdraw.', '一条尚未送达的数学指导已撤回,Agent 不会收到它。': 'Guidance that had not been delivered was withdrawn; no agent will receive it.', '记录满后可在这里清理。有研究使用的题目,需要先删除关联研究。': 'Clear records here when storage is full. Delete a problem’s linked research before deleting the problem.', '查看关联研究': 'View linked research', diff --git a/scripts/web-i18n.ts b/scripts/web-i18n.ts index afa93b2a..a523d605 100644 --- a/scripts/web-i18n.ts +++ b/scripts/web-i18n.ts @@ -136,6 +136,9 @@ export function pageKeys() { */ export function serverKeys() { const keys = new Map(); + // The retired scheduler wrote these event messages into run archives, including the bundled sample. + for (const message of ['数学指导已提交;投递和采纳结果另行记录。', '计划修改已提交;应用与证明重查结果另行记录。', + '一条尚未送达的数学指导已撤回,Agent 不会收到它。']) keys.set(message, 'historical run events'); for (const example of researchExamples) for (const value of [example.name, example.task]) keys.set(value, 'apps/web/problemExamples.ts'); const files = ['apps/web/progress.ts', 'apps/web/jobs.ts', 'apps/web/runner.ts', 'apps/web/config.ts', 'apps/web/share.ts', 'apps/web/moduleRegistry.ts', 'src/solver/modules/policy.ts', 'scripts/build-web-sample.ts']; for (const relative of files) { @@ -194,7 +197,8 @@ export function errorKeys() { else if (['apps/web/researchAssets.ts', 'apps/web/researchApi.ts', 'apps/web/researchMathematics.ts', 'apps/web/researchAssetPrefill.ts', 'apps/web/researchLibraryTrials.ts', 'apps/web/researchPersonal.ts', 'apps/web/researchJourney.ts', 'apps/web/sharedProofs.ts'].includes(relative) && ts.isCallExpression(node) && node.expression.getText(source) === 'fail' && node.arguments[1]) collect(node.arguments[1]); else if (relative === 'apps/web/researchLibraryTrials.ts' && ts.isPropertyAssignment(node) && ['incompatibility', 'error'].includes(node.name.getText(source))) collect(node.initializer); else if (relative === 'apps/web/researchLibraryTrials.ts' && ts.isVariableDeclaration(node) && node.name.getText(source) === 'reason' && node.initializer) collect(node.initializer); - else if (relative === 'apps/web/researchAssets.ts' && ts.isPropertyAssignment(node) && node.name.getText(source) === 'reason') collect(node.initializer); + else if (['apps/web/researchAssets.ts', 'apps/web/conversations.ts'].includes(relative) && + ts.isPropertyAssignment(node) && node.name.getText(source) === 'reason') collect(node.initializer); else if (relative === 'apps/web/researchApi.ts' && ts.isBinaryExpression(node) && node.left.getText(source) === 'reason') collect(node.right); else if (relative === 'apps/web/researchApi.ts' && ts.isVariableDeclaration(node) && node.name.getText(source) === 'reason' && node.initializer) collect(node.initializer); else if (relative === 'apps/web/researchCandidateScope.ts' && ts.isReturnStatement(node) && node.expression) collect(node.expression); From 474436db17ff8a10d8ca585e7be8a918c2b3d8b5 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Sat, 28 Nov 2026 01:48:15 +0800 Subject: [PATCH 4/7] Keep retired research controls read-only in the Web workbench --- apps/web/client/collaborationFlow.css | 2 - apps/web/client/collaborationFlow.tsx | 4 +- apps/web/client/researchInlineActions.tsx | 54 +---- apps/web/client/researchIssueExecution.tsx | 203 ++---------------- .../web/client/researchIssueExecutionDraft.ts | 89 ++------ apps/web/client/researchReview.tsx | 5 +- scripts/test-web-candidate-continuity.ts | 26 ++- scripts/test-web-collaboration-actions.ts | 75 ++++--- ...est-web-collaboration-entry-permissions.ts | 5 +- scripts/test-web-inline-annotations.ts | 29 +-- scripts/test-web-issue-action-continuity.ts | 152 ++++++------- scripts/test-web-problem-drafts.ts | 4 +- scripts/test-web-problem-lifecycle.ts | 7 +- ...st-web-research-decisions-followthrough.ts | 9 +- .../test-web-research-decisions-lifecycle.ts | 57 +---- scripts/test-web-research-draft-lifecycle.ts | 76 ++++--- scripts/test-web-research-library-trials.ts | 7 +- tests/researchIssueExecutionDraft.test.ts | 92 ++------ 18 files changed, 281 insertions(+), 615 deletions(-) diff --git a/apps/web/client/collaborationFlow.css b/apps/web/client/collaborationFlow.css index 8cd7849f..4a36be55 100644 --- a/apps/web/client/collaborationFlow.css +++ b/apps/web/client/collaborationFlow.css @@ -33,8 +33,6 @@ .collaboration-draft code, .collaboration-issue-execution code { overflow-wrap: anywhere; white-space: normal; } .collaboration-issue-execution { margin-block: 1rem; } .collaboration-issue-execution > details, .collaboration-review { padding-block: .75rem; border-top: 1px solid var(--line); } -.collaboration-issue-execution .research-check { display: flex; align-items: center; gap: .6rem; } -.collaboration-issue-execution .research-check input { width: auto; } .collaboration-review > p { display: flex; align-items: center; gap: .7rem; flex-wrap: wrap; } .collaboration-review select { width: 100%; min-width: 0; } .collaboration-review .research-form { max-width: 100%; } diff --git a/apps/web/client/collaborationFlow.tsx b/apps/web/client/collaborationFlow.tsx index ed8991d3..744a25f2 100644 --- a/apps/web/client/collaborationFlow.tsx +++ b/apps/web/client/collaborationFlow.tsx @@ -9,7 +9,7 @@ import type { WebApi } from './collaborationUi'; import { Rich, RichProse } from './richText'; import { BookmarkControl } from './researchCollections'; import { ResearchDraftPicker, useResearchDrafts } from './researchDrafts'; -import { IssueExecution } from './researchIssueExecution'; +import { IssueExecutionHistory } from './researchIssueExecution'; import { completeIssueReply, type IssueReplyDraft } from './researchIssueReplyDraft'; import { SharedStageReference } from './researchStageReference'; import { ProjectInvitationLinks } from './researchInvite'; @@ -223,7 +223,7 @@ function IssueThread({ issue, project, selfId, refresh, onRevealFeedback }: { is {project.permissions.member && issue.status === 'open' && })} {issue.resolution &&
    {issue.resolution.author.displayName} · {issue.resolution.action === 'reopen' ? tx('重新讨论的原因', 'Reason for reopening') : tx('决议', 'Resolution')} {issue.resolution.proposalId && {tx('采用的方案', 'Selected proposal')}}{issue.resolution.feedbackIds.map(id => { event.preventDefault(); onRevealFeedback(id); }}>{tx('查看决议关联的指导或调整', 'View linked guidance or changes')})}
    } - {issue.status === 'resolved' && issue.resolution && project.permissions.edit && } + {Boolean(issue.resolutionHistory?.length) &&
    {tx('历次决议与重新讨论', 'Previous resolutions and reopenings')}{issue.resolutionHistory!.map((record, index) =>
    {record.author.displayName} · {stamp(record.createdAt)}
    {record.proposalId && {tx('采用的方案', 'Selected proposal')}}
    )}
    } {selfId && project.permissions.member && (issue.status === 'open' || project.permissions.edit) &&
    { if (event.currentTarget.open && !text.trim()) setRevision(issue.revision); }}>{issue.status === 'open' ? tx('补充意见或记录决议', 'Reply or record a resolution') : tx('重新讨论', 'Reopen discussion')} item.scope.issueId === issue.id} onRestore={item => { const value = item.value; setText(value.text); setKind(value.kind); setReplyTo(value.replyTo); setProposal(value.proposalId); setFeedback(value.feedbackId); setRevision(value.revision); action.reset(); }} /> diff --git a/apps/web/client/researchInlineActions.tsx b/apps/web/client/researchInlineActions.tsx index 03bb4d32..ab628085 100644 --- a/apps/web/client/researchInlineActions.tsx +++ b/apps/web/client/researchInlineActions.tsx @@ -1,20 +1,16 @@ import { useEffect, useRef, useState } from 'preact/hooks'; import type { WebObservation } from '../collaboration'; import type { WebRun } from '../shared'; -import type { ResearchFeedback, ResearchFeedbackTarget, ResearchProjectDetail, ResearchRunBinding } from '../researchProjectTypes'; +import type { ResearchFeedbackTarget, ResearchProjectDetail, ResearchRunBinding } from '../researchProjectTypes'; import type { ResearchProblem } from '../researchProblemTypes'; import type { ResearchBriefTask } from '../researchWorkspaceTypes'; import { RichProse } from './richText'; -import { base, enc, ErrorBox, Field, MutationState, theoremHref, tx, useMutation, useResource, type Item, type ResearchContext } from './researchShared'; +import { base, enc, ErrorBox, MutationState, theoremHref, tx, useMutation, useResource, type ResearchContext } from './researchShared'; import { FeedbackWorkspace, type FeedbackFocus } from './researchFeedback'; import { ProofSubmission } from './researchTheorems'; import { ProjectPlanApproval } from './researchPlanApproval'; import { InlinePersonalApproval } from './researchPersonalApproval'; import { ResearchAnnotations } from './researchAnnotations'; -import { ResearchDraftPicker } from './researchDrafts'; -import { useResearchInputDraft } from './researchInputDraft'; -import type { ResearchDraftValues } from '../researchPersonalTypes'; -import { usePersonalGuidance } from './usePersonalGuidance'; import './researchInlineActions.css'; /** Route-local controls keep the displayed mathematical contract beside every human action. */ @@ -39,7 +35,7 @@ export function ResearchInlineActions({ problem, task, context, refresh, onTask, }, [focusAnnotationId]); if (project && !project.permissions.member) return null; return
    - + { if (event.target === event.currentTarget) { const box = event.currentTarget.getBoundingClientRect(); if (event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom) event.currentTarget.close(); } }}>

    {task ? tx('就在这一步参与研究', 'Work on this step here') : tx('审阅当前路线并参与决定', 'Review the route and take action')}

    {task &&
    {[ @@ -48,13 +44,11 @@ export function ResearchInlineActions({ problem, task, context, refresh, onTask, {resource.error && } {!observation && !resource.error &&

    {tx('正在读取当前任务与操作权限…', 'Loading the current task and available actions…')}

    } {observation && run && <> - {task && !current &&

    {tx('当前显示的是历史任务版本。可以批注原文;运行指导、认领和候选请使用当前任务版本。', 'This is a historical task version. You can annotate its original text. Use the current task version for guidance, claims and candidates.')}

    } + {task && !current &&

    {tx('当前显示的是历史任务版本。可以批注原文;认领和候选请使用当前任务版本。', 'This is a historical task version. You can annotate its original text. Use the current task version for claims and candidates.')}

    } {project && binding ? <> - : !project && } - {(!project || ((!task || current) && binding?.permissions.guidance && run.status === 'running')) && { setFocus(previous => ({ id, request: (previous?.request ?? 0) + 1 })); setShowFeedback(true); }} />} + : !project && run.nativeTeamCapacity && run.planApproval && } {project && binding && task && current && binding.permissions.proof && run.status === 'running' && <> {openedCandidate &&
    ; } - -function InlineGuidance({ selfId, project, binding, observation, task, root, refresh, onSaved, canSend, running }: { canSend: boolean; running: boolean; selfId: string; project?: ResearchProjectDetail; binding?: ResearchRunBinding; observation: WebObservation; task?: ResearchBriefTask; root: string; refresh(): void; onSaved(id: string): void }) { - const runId = binding?.runId ?? observation.webRunId; - const scope = { runId, ...(binding ? { statementVersionId: binding.statementVersionId } : {}), ...(task ? { taskId: task.id, taskVersion: task.version } : {}) }; - const input = useResearchInputDraft(selfId, project?.id, 'guidance', scope, { text: '', - planVersion: observation.inspection.planVersion, observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } }); - const text = input.value.text, [confirmed, setConfirmed] = useState(''), action = useMutation(); - const personal = usePersonalGuidance(selfId, runId, root, observation, running, !project, refresh, (submitted, receipt) => { - if ((submitted.body.taskRef?.id ?? '') === (task?.id ?? '') && (submitted.body.taskRef?.version ?? '') === (task?.version ?? '')) - void input.complete(submitted.draft, { kind: 'guidance', id: receipt.id }, submitted.value); - else if (submitted.draft) void input.drafts.complete(submitted.draft, { kind: 'guidance', id: receipt.id }); - }); - const signature = JSON.stringify([task?.id, task?.version, observation.inspection.planVersion]), checked = confirmed === signature; - const target: ResearchFeedbackTarget | undefined = binding ? { runId: binding.runId, statementVersionId: binding.statementVersionId, observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest }, ...(task ? { taskRef: { id: task.id, version: task.version } } : {}) } : undefined; - const recipient = task ? { kind: 'task', id: task.id } : { kind: 'lead' }, busy = action.busy || personal.busy; - return
    {task ? tx('对这一步提供指导', 'Give guidance for this step') : tx('向 Lead 提供路线意见', 'Give route guidance to the Lead')} - item.scope.runId === runId && (item.scope.taskId ?? '') === (task?.id ?? '') && (item.scope.taskVersion ?? '') === (task?.version ?? '')} onRestore={item => { input.restore(item); setConfirmed(''); action.reset(); }} /> -
    { event.preventDefault(); if (!checked || !canSend || personal.attempt || personal.blocked) return; const submitted = input.drafts.current(), value = input.value; - if (project && target) void action.run>('POST', `${base}/theorems/${enc(project.id)}/feedback`, { kind: 'guidance', target, recipient, text }, result => { void input.complete(submitted, { kind: 'feedback', id: result.item.id }, value); refresh(); onSaved(result.item.id); }); - else personal.send({ draft: submitted, value, planVersion: observation.inspection.planVersion ?? '', body: { id: crypto.randomUUID(), text, recipient: task ? { kind: 'task', id: task.id } : { kind: 'lead' }, observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest }, ...(task ? { taskRef: { id: task.id, version: task.version } } : {}) } }); - }}>

    {tx('指导对象', 'Recipient')}: {task ? `${task.id} · ${task.version.slice(0, 12)}` : 'Lead'}

    - input.update({ text, planVersion: observation.inspection.planVersion, observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest } })} multiline required maxLength={4000} /> - - - {!project && } -
    ; -} - -function PersonalCommandStatus({ command }: { command: ReturnType }) { - return <>{command.blocked && } - {command.attempt &&

    {tx('这条指导的投递结果尚待确认。刷新后会继续查询原记录。', 'Delivery of this guidance is unconfirmed. Refreshing checks the original record.')}

    -

    {tx('原指导对象', 'Original recipient')}: {command.attempt.body.taskRef ? `${command.attempt.body.taskRef.id} · ${command.attempt.body.taskRef.version}` : 'Lead'}

    - - {command.canRetry ? - :

    {tx('原路线或任务版本已变化,只能查询原回执。', 'The original route or task version has changed. Only receipt checks are available.')}

    } -
    } - {command.receipt &&

    {tx('运行回执', 'Run receipt')}: {command.receipt.status}{command.receipt.reason && <> · {command.receipt.reason}}

    }; -} diff --git a/apps/web/client/researchIssueExecution.tsx b/apps/web/client/researchIssueExecution.tsx index 2a85016e..3df19063 100644 --- a/apps/web/client/researchIssueExecution.tsx +++ b/apps/web/client/researchIssueExecution.tsx @@ -1,196 +1,25 @@ -import { useEffect, useRef, useState } from 'preact/hooks'; -import type { WebCommandResult, WebObservation, WebPlan } from '../collaboration'; +import { useState } from 'preact/hooks'; import type { ResearchIssue } from '../researchCollaborationTypes'; -import type { ResearchFeedback, ResearchProjectDetail } from '../researchProjectTypes'; -import type { WebRun } from '../shared'; +import type { ResearchProjectDetail } from '../researchProjectTypes'; import { RichProse } from './richText'; -import { ResearchWorkImpactView } from './researchWorkImpact'; -import { issueExecutionAttemptFromFeedback, issueExecutionCanRetry, issueExecutionContextMatches, readIssueExecutionAttempt, readIssueExecutionDraft, removeIssueExecutionAttempt, removeIssueExecutionDraft, saveIssueExecutionAttempt, saveIssueExecutionDraft, type IssueExecutionAttempt, type IssueExecutionContext, type IssueExecutionDraft, type IssueExecutionInput } from './researchIssueExecutionDraft'; -import { api, base, enc, ErrorBox, errorText, Field, nameOf, ResearchHttpError, tx, useResource, type Item, type Items } from './researchShared'; +import { readIssueExecutionNotes } from './researchIssueExecutionDraft'; +import { nameOf, tx } from './researchShared'; -type Prepared = IssueExecutionAttempt & { planVersion?: string; receipt?: WebCommandResult }; -const knownDelivery = (record: ResearchFeedback) => ['queued', 'delivered', 'deferred', 'failed'].includes(record.delivery.status); - -/** An issue decision becomes an ordinary, version-bound feedback command only after an explicit confirmation. */ -export function IssueExecution({ issue, project, selfId, refresh, onRevealFeedback }: { - issue: ResearchIssue; project: ResearchProjectDetail; selfId: string; refresh(): void; onRevealFeedback(id: string): void; +export function IssueExecutionHistory({ issue, project, selfId, onRevealFeedback }: { + issue: ResearchIssue; project: ResearchProjectDetail; selfId: string; onRevealFeedback(id: string): void; }) { - const scope = { owner: selfId, projectId: project.id, issueId: issue.id }; - const initial: IssueExecutionDraft = { mode: 'guidance', - runId: issue.target?.runId ?? project.runs.find(run => run.status === 'running' && run.permissions.guidance && (!issue.statementVersionId || run.statementVersionId === issue.statementVersionId))?.runId ?? '', - taskId: issue.target?.taskRef?.id ?? '', text: issue.resolution?.text ?? '', objective: '', dependencies: '', editedTask: '' }; - const [draft, setDraft] = useState(initial), current = useRef(draft); current.current = draft; - const { mode, runId, taskId, text, objective, dependencies, editedTask } = draft; - const [prepared, setPrepared] = useState(), [confirmed, setConfirmed] = useState(false), [busy, setBusy] = useState(false), [error, setError] = useState(''); - const [pending, setPendingState] = useState(), [saved, setSaved] = useState(); - const [loaded, setLoaded] = useState(false), [restored, setRestored] = useState(false), [reviewed, setReviewed] = useState(false), [retryable, setRetryable] = useState(false); - const [storageError, setStorageError] = useState(''), [draftError, setDraftError] = useState(''), [notice, setNotice] = useState(''), [reviewedTask, setReviewedTask] = useState(''); - const pendingRef = useRef(), lock = useRef(false), draftGeneration = useRef(0), alive = useRef(true), edited = useRef(false), handled = useRef(new Set()); - const draftUnsaved = useRef(false); - const permission = mode === 'guidance' ? 'guidance' : 'edit'; - const runs = project.runs.filter(run => run.permissions[permission] && run.status === 'running' && (!issue.statementVersionId || run.statementVersionId === issue.statementVersionId) && (!issue.target || run.runId === issue.target.runId)); - const binding = runs.find(run => run.runId === runId); - const resource = useResource<{ run?: WebRun; observation: WebObservation | null }>(binding ? `${base}/theorems/${enc(project.id)}/runs/${enc(runId)}/observation` : undefined, 5000); - const observation = resource.data?.observation?.webRunId === runId ? resource.data.observation : undefined; - const tasks = observation?.inspection.tasks ?? [], task = tasks.find(task => task.id === taskId); - const planTask = observation?.plan?.tasks.find(task => task.id === taskId); - const context: IssueExecutionContext | undefined = binding && observation && (!taskId || task) ? { issueRevision: issue.revision, resolutionAt: issue.resolution!.createdAt, - target: { runId, statementVersionId: binding.statementVersionId, observationRef: { sequence: observation.sequence, stateDigest: observation.snapshot.stateDigest }, ...(task ? { taskRef: { id: task.id, version: task.version } } : {}) }, - ...(observation.inspection.planVersion ? { planVersion: observation.inspection.planVersion } : {}) } : undefined; - const changedTaskVersion = Boolean(issue.target?.taskRef && task && task.version !== issue.target.taskRef.version); - const targetStale = Boolean(issue.target?.taskRef && (!task || changedTaskVersion && reviewedTask !== JSON.stringify([task.id, task.version]))); - const needsReview = targetStale || restored && !reviewed || Boolean(draft.context && context && !issueExecutionContextMatches(draft.context, context)); - const active = Boolean(loaded && !storageError && binding && resource.data?.run?.status === 'running' && context && !resource.error && !needsReview); - const origin = { issueId: issue.id, issueRevision: issue.revision, resolutionAt: issue.resolution!.createdAt, ...(issue.resolution?.proposalId ? { proposalId: issue.resolution.proposalId } : {}), - ...(changedTaskVersion && !needsReview && task ? { reviewedTaskRef: { id: task.id, version: task.version } } : {}) }; + const [notes] = useState(() => { + if (!selfId) return []; + try { return readIssueExecutionNotes(localStorage, { owner: selfId, projectId: project.id, issueId: issue.id }); } + catch { return []; } + }); const linked = project.feedback.filter(item => item.issueSource?.issueId === issue.id); - const invalidate = () => { draftGeneration.current++; setPrepared(undefined); setConfirmed(false); setError(''); }; - const update = (next: Partial, resetContext = false) => { - const value = { ...current.current, ...next, context: resetContext ? undefined : next.context ?? current.current.context ?? context }; - current.current = value; edited.current = true; setDraft(value); invalidate(); - try { saveIssueExecutionDraft(localStorage, scope, value); draftUnsaved.current = false; setDraftError(''); } - catch { draftUnsaved.current = true; setDraftError(tx('执行草稿未能保存在本机,请保留页面或复制内容。', 'The action draft could not be saved locally. Keep this page open or copy its contents.')); } - }; - const setPending = (value?: IssueExecutionAttempt) => { pendingRef.current = value; if (alive.current) setPendingState(value); }; - const clearAttempt = (attempt: IssueExecutionAttempt) => { - removeIssueExecutionAttempt(localStorage, scope, attempt.input.requestId); - handled.current.add(attempt.input.requestId); - if (pendingRef.current?.input.requestId === attempt.input.requestId) { setPending(undefined); if (alive.current) setRetryable(false); } - }; - const resolve = (attempt: IssueExecutionAttempt, record: ResearchFeedback) => { - if (knownDelivery(record)) { - clearAttempt(attempt); - if (attempt.draft && record.delivery.status !== 'failed') removeIssueExecutionDraft(localStorage, scope, attempt.draft); - } - if (!alive.current) return; - setSaved(record); setError(''); setRetryable(record.delivery.status === 'not-sent'); - if (knownDelivery(record)) { setPrepared(undefined); setConfirmed(false); setNotice(''); if (JSON.stringify(current.current) === JSON.stringify(attempt.draft)) setRestored(false); } - else setNotice(tx('原投递结果尚未确认。可查询原记录;结果未明时不会再次投递,也不会创建新请求。', 'The original delivery is unconfirmed. Check its record; an unknown result will not resend it or create a new request.')); - refresh(); - }; - async function findOriginal(input: IssueExecutionInput) { - const result = await api>(`${base}/theorems/${enc(project.id)}/feedback`); - return result.items.find(item => item.requestId === input.requestId && item.author.id === selfId && item.issueSource?.issueId === issue.id); - } - async function post(attempt: IssueExecutionAttempt) { - try { const result = await api>(`${base}/theorems/${enc(project.id)}/feedback`, { method: 'POST', body: JSON.stringify(attempt.input) }); resolve(attempt, result.item); } - catch (cause) { - if (alive.current) setError(errorText(cause)); - try { const record = await findOriginal(attempt.input); if (record) resolve(attempt, record); - else if (cause instanceof ResearchHttpError && cause.status < 500) clearAttempt(attempt); } - catch { /* Preserve the original request until its record can be checked. */ } - } - } - async function recover(retry: boolean) { - const attempt = pendingRef.current; - if (lock.current || !attempt) return; - lock.current = true; setBusy(true); setError(''); - try { - const record = await findOriginal(attempt.input); - if (record) resolve(attempt, record); - else if (alive.current) { setRetryable(true); setNotice(tx('尚未找到原提交。重试会使用相同内容、目标和请求身份。', 'The original submission was not found. Retrying keeps its text, target and request identity.')); } - if (retry && (!record || record.delivery.status === 'not-sent')) { - if (!issueExecutionCanRetry(attempt, issue, observation, resource.data?.run?.status === 'running' && Boolean(binding))) { - setError(tx('原决议、任务或计划版本已变化。请继续查询原记录,草稿会保留。', 'The original resolution, task or plan changed. Keep checking its record; your draft is preserved.')); return; - } - await post(attempt); - } - } catch (cause) { if (alive.current) setError(errorText(cause)); } - finally { lock.current = false; if (alive.current) setBusy(false); } - } - const initialize = () => { - try { - const local = readIssueExecutionDraft(localStorage, scope); - const original = readIssueExecutionAttempt(localStorage, scope) ?? linked.filter(item => item.author.id === selfId && !handled.current.has(item.requestId)).map(issueExecutionAttemptFromFeedback).find(Boolean); - if (!edited.current && (local || original?.draft)) { const value = local ?? original!.draft!; current.current = value; setDraft(value); setRestored(true); setReviewed(false); } - if (original) { saveIssueExecutionAttempt(localStorage, scope, original); setPending(original); } - setLoaded(true); setStorageError(''); if (original) void recover(false); - } catch { setStorageError(tx('无法读取待确认执行记录。请恢复浏览器存储后重试,以免重复投递。', 'Pending action records could not be read. Restore browser storage and check again before sending.')); } - }; - useEffect(() => { - alive.current = true; initialize(); - const warn = (event: BeforeUnloadEvent) => { if (draftUnsaved.current) { event.preventDefault(); event.returnValue = ''; } }; - window.addEventListener('beforeunload', warn); - return () => { alive.current = false; window.removeEventListener('beforeunload', warn); }; - }, []); - useEffect(() => { - if (!loaded || storageError) return; - const attempt = pendingRef.current, record = attempt && linked.find(item => item.requestId === attempt.input.requestId && item.author.id === selfId); - if (attempt && record && knownDelivery(record)) { - try { resolve(attempt, record); } catch (cause) { setStorageError(errorText(cause)); } - } else if (!attempt) { - const original = linked.filter(item => item.author.id === selfId && !handled.current.has(item.requestId)).map(issueExecutionAttemptFromFeedback).find(Boolean); - if (original) { try { saveIssueExecutionAttempt(localStorage, scope, original); setPending(original); void recover(false); } catch (cause) { setStorageError(errorText(cause)); } } - } - }, [project.feedback, loaded]); - async function prepare() { - if (lock.current || pendingRef.current || !active || !observation || !binding || !context || !text.trim() || text.length > 4000 || mode === 'plan-edit' && !planTask) return; - lock.current = true; setBusy(true); setError(''); setConfirmed(false); const generation = draftGeneration.current, snapshot = current.current; - try { - const target = context.target; - if (mode === 'guidance') setPrepared({ input: { requestId: crypto.randomUUID(), kind: 'guidance', text, visibility: 'members', issueSource: origin, target, recipient: task ? { kind: 'task', id: task.id } : { kind: 'lead' } }, draft: snapshot }); - else { - const currentPlan = observation.plan; - if (!currentPlan || !planTask) return; - const changed = editedTask === taskId; - const proposal: WebPlan = { ...currentPlan, schema: 'deepscientist.math.plan-edit.v1', baseVersion: observation.inspection.planVersion ?? currentPlan.baseVersion, - tasks: currentPlan.tasks.map(task => task.id === taskId ? { ...task, objective: changed ? objective : task.objective, - dependsOn: changed ? [...new Set(dependencies.split(/[,\n]/u).map(item => item.trim()).filter(Boolean))] : task.dependsOn, revision: task.revision + 1 } : task) }; - const id = crypto.randomUUID(); - const preview = await api<{ receipt: WebCommandResult }>(`${base}/theorems/${enc(project.id)}/runs/${enc(runId)}/edits/preview`, { method: 'POST', body: JSON.stringify({ ...proposal, id }) }); - if (!alive.current || generation !== draftGeneration.current) return; - if (!['validated', 'previewed', 'ready'].includes(preview.receipt.status)) { setError(preview.receipt.reason ?? tx('计划预览未通过,请检查任务和依赖。', 'The plan preview did not pass. Check the task and dependencies.')); return; } - setPrepared({ input: { requestId: crypto.randomUUID(), kind: 'plan-edit', text, visibility: 'members', issueSource: origin, target, proposal }, draft: snapshot, planVersion: proposal.baseVersion, receipt: preview.receipt }); - } - } catch (cause) { if (alive.current) setError(errorText(cause)); } - finally { lock.current = false; if (alive.current) setBusy(false); } - } - const preparedStale = Boolean(prepared && (prepared.input.issueSource?.issueRevision !== issue.revision || prepared.planVersion && prepared.planVersion !== observation?.inspection.planVersion - || prepared.input.target.taskRef && !tasks.some(task => task.id === prepared.input.target.taskRef!.id && task.version === prepared.input.target.taskRef!.version))); - async function send() { - if (lock.current || pendingRef.current || !prepared || !confirmed || preparedStale || !active) return; - const attempt: IssueExecutionAttempt = { input: prepared.input, draft: prepared.draft }; - try { - const existing = readIssueExecutionAttempt(localStorage, scope); - if (existing) { setPending(existing); void recover(false); return; } - saveIssueExecutionAttempt(localStorage, scope, attempt); - } catch { setStorageError(tx('原请求记录未能保存在本机,执行尚未投递。恢复浏览器存储后重试。', 'The original request could not be saved locally, so the action was not sent. Restore browser storage and try again.')); return; } - lock.current = true; setBusy(true); setPending(attempt); setRetryable(false); - try { await post(attempt); } finally { lock.current = false; if (alive.current) setBusy(false); } - } + if (linked.length === 0 && notes.length === 0) return null; return
    {linked.map(item =>

    { event.preventDefault(); onRevealFeedback(item.id); }}>{tx('查看此议题的执行反馈', 'View execution feedback from this issue')} · {nameOf(item.delivery.status)} · {nameOf(item.execution.status)}

    )} -
    {tx('将决议转为执行', 'Turn the resolution into action')}
    { event.preventDefault(); void prepare(); }}> - - - - {restored &&

    {tx('已恢复本机执行草稿,请重新核对目标和任务版本。', 'Your local action draft is restored. Review its target and task version again.')}

    } - {needsReview &&

    {tx('请核对这份草稿是否适用于当前决议、任务和计划版本。', 'Review whether this draft applies to the current resolution, task and plan version.')}

    - {draft.context &&

    {tx('草稿任务版本', 'Draft task version')}: {draft.context.target.taskRef?.version ?? 'Lead'}

    } - {task && <>{task.version}} -
    } - {issue.target?.taskRef && {issue.target.taskRef.id} · {issue.target.taskRef.version}} - update({ text })} multiline required maxLength={4000} /> - {mode === 'plan-edit' && planTask && <> update({ objective, editedTask: taskId, ...(editedTask !== taskId ? { dependencies: planTask.dependsOn.join(', ') } : {}) })} multiline required /> - update({ dependencies, editedTask: taskId, ...(editedTask !== taskId ? { objective: planTask.objective } : {}) })} />} - - - {prepared &&
    {tx('待确认的执行内容', 'Action awaiting confirmation')}

    {prepared.input.target.runId} · {prepared.input.target.taskRef ? `${prepared.input.target.taskRef.id} · ${prepared.input.target.taskRef.version}` : 'Lead'}

    - {'proposal' in prepared.input &&
    {tx('完整计划与依赖', 'Complete plan and dependencies')}
    {JSON.stringify(prepared.input.proposal, null, 2)}
    } - {prepared.receipt &&

    {tx('受影响任务:', 'Affected tasks: ')}{prepared.receipt.affectedTaskIds?.join(' · ') || tx('见计划预览', 'See plan preview')}

    } - {prepared.receipt && binding && } - {preparedStale &&

    {tx('决议、任务或计划已有更新,请重新预览。', 'The resolution, task or plan changed. Preview it again.')}

    } - -
    } - {notice &&

    {notice}

    } - {pending &&

    {tx('原提交的投递结果尚待核对,暂不能创建新执行。', 'The original delivery is awaiting confirmation. A new action cannot be created yet.')}

    -
    {tx('查看待核对的原执行', 'View the original action')}

    {pending.input.target.runId} · {pending.input.target.taskRef?.id ?? 'Lead'} · {pending.input.target.taskRef?.version} · {pending.input.requestId}

    - - {retryable && } - {retryable && !issueExecutionCanRetry(pending, issue, observation, resource.data?.run?.status === 'running' && Boolean(binding)) &&

    {tx('原决议、任务或计划版本已变化,请继续查询原记录。', 'The original resolution, task or plan changed. Keep checking its record.')}

    } -
    } - {saved &&

    {tx('执行反馈已保存:', 'Execution feedback saved: ')}{nameOf(saved.delivery.status)}

    } - {storageError && }{!binding &&

    {tx('没有与此决议对应且有权限操作的运行。', 'No authorized running session matches this resolution.')}

    } -
    + {notes.length > 0 &&
    + {tx('查看旧版执行草稿', 'Read the previous action draft')} + {notes.map(note => )} +
    }
    ; } diff --git a/apps/web/client/researchIssueExecutionDraft.ts b/apps/web/client/researchIssueExecutionDraft.ts index a68e57b5..e74b92eb 100644 --- a/apps/web/client/researchIssueExecutionDraft.ts +++ b/apps/web/client/researchIssueExecutionDraft.ts @@ -1,76 +1,17 @@ -import type { WebObservation } from '../collaboration'; -import type { ResearchIssue } from '../researchCollaborationTypes'; -import type { ResearchFeedback, ResearchFeedbackInput, ResearchFeedbackTarget } from '../researchProjectTypes'; +type IssueExecutionScope = { owner: string; projectId: string; issueId: string }; +type LegacyDraft = { text?: unknown; objective?: unknown; dependencies?: unknown }; -export type IssueExecutionInput = Extract - | (Extract & { kind: 'plan-edit' }); -export type IssueExecutionScope = { owner: string; projectId: string; issueId: string }; -export type IssueExecutionContext = { issueRevision: number; resolutionAt: string; target: ResearchFeedbackTarget; planVersion?: string }; -export type IssueExecutionDraft = { - mode: 'guidance' | 'plan-edit'; runId: string; taskId: string; text: string; - objective: string; dependencies: string; editedTask: string; context?: IssueExecutionContext; -}; -export type IssueExecutionAttempt = { input: IssueExecutionInput; draft?: IssueExecutionDraft }; -type DraftStorage = Pick; -export const issueExecutionKey = (scope: IssueExecutionScope, kind: 'draft' | 'pending') => - `theoremos:issue-execution-${kind}:v1:${encodeURIComponent(JSON.stringify([scope.owner, scope.projectId, scope.issueId]))}`; -const targetValid = (target: ResearchFeedbackTarget | undefined) => Boolean(target && typeof target.runId === 'string' && target.runId - && typeof target.statementVersionId === 'string' && target.statementVersionId && Number.isInteger(target.observationRef?.sequence) - && typeof target.observationRef.stateDigest === 'string' && (!target.taskRef || typeof target.taskRef.id === 'string' && typeof target.taskRef.version === 'string')); -const draftValid = (draft: IssueExecutionDraft | undefined): draft is IssueExecutionDraft => Boolean(draft - && ['guidance', 'plan-edit'].includes(draft.mode) - && ['runId', 'taskId', 'text', 'objective', 'dependencies', 'editedTask'].every(key => typeof draft[key as keyof IssueExecutionDraft] === 'string') - && (!draft.context || Number.isInteger(draft.context.issueRevision) && typeof draft.context.resolutionAt === 'string' && targetValid(draft.context.target) - && draft.context.target.runId === draft.runId && (draft.context.target.taskRef?.id ?? '') === draft.taskId)); - -export function readIssueExecutionDraft(storage: DraftStorage, scope: IssueExecutionScope): IssueExecutionDraft | undefined { - const raw = storage.getItem(issueExecutionKey(scope, 'draft')); if (raw === null) return; - const draft = JSON.parse(raw) as IssueExecutionDraft; - if (!draftValid(draft)) throw new Error('Invalid saved issue execution draft'); - return draft; -} -export function saveIssueExecutionDraft(storage: DraftStorage, scope: IssueExecutionScope, draft: IssueExecutionDraft) { - storage.setItem(issueExecutionKey(scope, 'draft'), JSON.stringify(draft)); -} -export function removeIssueExecutionDraft(storage: DraftStorage, scope: IssueExecutionScope, submitted: IssueExecutionDraft) { - if (storage.getItem(issueExecutionKey(scope, 'draft')) === JSON.stringify(submitted)) storage.removeItem(issueExecutionKey(scope, 'draft')); -} -export function readIssueExecutionAttempt(storage: DraftStorage, scope: IssueExecutionScope): IssueExecutionAttempt | undefined { - const raw = storage.getItem(issueExecutionKey(scope, 'pending')); if (raw === null) return; - const attempt = JSON.parse(raw) as IssueExecutionAttempt | null, input = attempt?.input; - if (!input || !['guidance', 'plan-edit'].includes(input.kind) || typeof input.requestId !== 'string' || !input.requestId - || typeof input.text !== 'string' || !targetValid(input.target) || input.issueSource?.issueId !== scope.issueId - || !Number.isInteger(input.issueSource.issueRevision) || typeof input.issueSource.resolutionAt !== 'string' - || input.kind === 'guidance' && (!['lead', 'task'].includes(input.recipient?.kind) - || input.recipient.kind === 'task' && input.recipient.id !== input.target.taskRef?.id) - || input.kind === 'plan-edit' && (!input.proposal || !Array.isArray(input.proposal.tasks) || typeof input.proposal.baseVersion !== 'string') - || attempt?.draft && !draftValid(attempt.draft)) throw new Error('Invalid saved issue execution identity'); - return attempt!; -} -export function saveIssueExecutionAttempt(storage: DraftStorage, scope: IssueExecutionScope, attempt: IssueExecutionAttempt) { - storage.setItem(issueExecutionKey(scope, 'pending'), JSON.stringify(attempt)); -} -export function removeIssueExecutionAttempt(storage: DraftStorage, scope: IssueExecutionScope, requestId: string) { - if (readIssueExecutionAttempt(storage, scope)?.input.requestId === requestId) storage.removeItem(issueExecutionKey(scope, 'pending')); -} -export function issueExecutionContextMatches(left: IssueExecutionContext, right: IssueExecutionContext) { - return left.issueRevision === right.issueRevision && left.resolutionAt === right.resolutionAt && left.planVersion === right.planVersion - && left.target.runId === right.target.runId && left.target.statementVersionId === right.target.statementVersionId - && left.target.taskRef?.id === right.target.taskRef?.id && left.target.taskRef?.version === right.target.taskRef?.version; -} -export function issueExecutionCanRetry(attempt: IssueExecutionAttempt, issue: ResearchIssue, observation?: WebObservation, running = false) { - const { input } = attempt, source = input.issueSource; - return Boolean(running && observation?.webRunId === input.target.runId && issue.status === 'resolved' - && source?.issueId === issue.id && source.issueRevision === issue.revision && source.resolutionAt === issue.resolution?.createdAt - && (!input.target.taskRef || observation.inspection.tasks.some(task => task.id === input.target.taskRef!.id && task.version === input.target.taskRef!.version)) - && (input.kind !== 'plan-edit' || input.proposal.baseVersion === observation.inspection.planVersion)); -} -/** Existing unknown records remain recoverable even when created before local attempt persistence. */ -export function issueExecutionAttemptFromFeedback(record: ResearchFeedback): IssueExecutionAttempt | undefined { - if (!record.issueSource || !record.target || !['unknown', 'not-sent'].includes(record.delivery.status)) return; - const { issueId, issueRevision, resolutionAt, proposalId, reviewedTaskRef } = record.issueSource; - const common = { requestId: record.requestId, text: record.text, visibility: 'members' as const, target: record.target, - issueSource: { issueId, issueRevision, resolutionAt, ...(proposalId ? { proposalId } : {}), ...(reviewedTaskRef ? { reviewedTaskRef } : {}) } }; - if (record.kind === 'guidance' && record.payload && 'recipient' in record.payload) return { input: { ...common, kind: 'guidance', recipient: record.payload.recipient } }; - if (record.kind === 'plan-edit' && record.payload && 'proposal' in record.payload) return { input: { ...common, kind: 'plan-edit', proposal: record.payload.proposal } }; +export function readIssueExecutionNotes(storage: Pick, scope: IssueExecutionScope) { + const suffix = encodeURIComponent(JSON.stringify([scope.owner, scope.projectId, scope.issueId])); + const read = (kind: 'draft' | 'pending') => { + const raw = storage.getItem(`theoremos:issue-execution-${kind}:v1:${suffix}`); + if (!raw) return; + try { return JSON.parse(raw); } catch { return undefined; } + }; + const draft: LegacyDraft | undefined = read('draft'); + const pending = read('pending') as { input?: LegacyDraft & { issueSource?: { issueId?: unknown } }; draft?: LegacyDraft } | undefined; + const submitted = pending?.input?.issueSource?.issueId === scope.issueId ? pending.input : undefined; + return [...new Set([draft?.text, draft?.objective, draft?.dependencies, submitted?.text, + ...(submitted ? [pending?.draft?.text, pending?.draft?.objective, pending?.draft?.dependencies] : [])] + .filter((value): value is string => typeof value === 'string' && Boolean(value.trim())))]; } diff --git a/apps/web/client/researchReview.tsx b/apps/web/client/researchReview.tsx index ac92cab6..09e845e5 100644 --- a/apps/web/client/researchReview.tsx +++ b/apps/web/client/researchReview.tsx @@ -38,15 +38,14 @@ export function ResearchReview({ feedback, project, selfId, canReview, refresh, return
    {feedback.candidateDelivery &&

    {needsNewCandidate && feedback.decision.status === 'needs-info' ? tx('评审要求新版候选,请按当前任务版本修订源码并重新检查。', 'The reviewer requested a new candidate. Revise the source for the current task and check it again.') + : feedback.candidateDelivery.status === 'awaiting-review' && feedback.decision.status === 'accepted' ? tx('人工评审已采纳。', 'Accepted in human review.') : feedback.candidateDelivery.status === 'awaiting-review' ? tx('候选检查已通过,等待人工批准。', 'The candidate passed its check and is waiting for human approval.') : feedback.candidateDelivery.status === 'approved' && newAttempt ? tx('已评审通过,请在带入固定库的新尝试中使用。', 'Review approved. Use this candidate in a new attempt with the fixed library.') : feedback.candidateDelivery.status === 'approved' ? tx('候选已批准,投递回执待确认。', 'The candidate is approved; delivery is awaiting confirmation.') : feedback.candidateDelivery.status === 'dispatched' ? tx('候选已投递,可继续跟踪采纳和执行。', 'The candidate was sent. Follow its adoption and execution below.') : feedback.candidateDelivery.status === 'withdrawn' ? tx('此候选已撤回或由新修订接续。', 'This candidate was withdrawn or continued in a newer revision.') : feedback.proofCheck?.status === 'failed' ? tx('候选未通过检查,可修改后提交新修订。', 'The candidate check failed. Revise it and submit a new version.') : tx('候选检查中。', 'Checking the candidate.')}

    - {newAttempt &&

    {tx('这份候选将在新尝试中使用,评审批准后可准备完整源码与固定库。', 'This candidate will be used in a new attempt. After review, prepare its complete source and fixed library.')}

    } - {feedback.candidateDelivery.status === 'awaiting-review' && canJudge && !feedback.supersededBy && !['needs-info', 'declined'].includes(feedback.decision.status) && } - {['checking', 'awaiting-review', 'approved'].includes(feedback.candidateDelivery.status) && (feedback.author.id === selfId || project.permissions.manage) && } + {newAttempt &&

    {tx('这份候选将在新尝试中使用,记录采纳决定后可准备完整源码与固定库。', 'This candidate will be used in a new attempt. Record an acceptance decision to prepare its complete source and fixed library.')}

    } {canPrepareAttempt && {tx('带入完整源码与固定库,准备新尝试', 'Prepare a new attempt with the complete source and fixed library')}}
    } {Boolean(relatedAttempts.length) &&
    diff --git a/scripts/test-web-candidate-continuity.ts b/scripts/test-web-candidate-continuity.ts index 6a4a4185..32ac509c 100644 --- a/scripts/test-web-candidate-continuity.ts +++ b/scripts/test-web-candidate-continuity.ts @@ -13,7 +13,7 @@ import { mathDigest } from '../src/math/mathRuntimeIo'; import type { WebRunner } from '../apps/web/runner'; import type { WebObservation } from '../apps/web/collaboration'; import type { ResearchFeedback, ResearchProjectDetail } from '../apps/web/researchProjectTypes'; -import { freePort, startBrowser, preferFullCollaboration, settled } from './web-scenario'; +import { freePort, startBrowser, preferFullCollaboration } from './web-scenario'; const root = path.resolve(import.meta.dirname, '..'), output = path.join(root, 'out/product-continuity/candidate-continuity'); await fs.mkdir(output, { recursive: true }); @@ -107,9 +107,9 @@ try { assert.equal(candidate.proofCheck?.status, 'checked'); assert.equal(candidate.candidateDelivery?.status, 'awaiting-review'); assert.equal(commands.length, commandsBefore, 'Checking must not dispatch a candidate that needs human review'); await reviewer.goto(`${href}#feedback-${candidate.id}`); - let row = reviewer.locator(`#feedback-${candidate.id}`); await row.locator('[data-candidate-approve]').waitFor(); + let row = reviewer.locator(`#feedback-${candidate.id}`); await row.locator('[data-candidate-delivery-status="awaiting-review"]').waitFor(); await author.goto(`${href}#feedback-${candidate.id}`); - assert.equal(await author.locator(`#feedback-${candidate.id} [data-candidate-approve]`).count(), 0, 'The author cannot approve their own candidate'); + await author.locator(`#feedback-${candidate.id} [data-decision-peer-required]`).waitFor(); await reviewer.screenshot({ path: path.join(output, `awaiting-review-${language}-${width}.png`), fullPage: true }); phase = `review-and-revise-${language}-${width}`; await row.locator('[data-review-comment]').fill('Please spell out the constructor used to close True.'); @@ -137,12 +137,18 @@ try { await row.locator('[data-candidate-revision] > summary').click(); await row.locator('[data-candidate-revision-diff]').waitFor(); assert.match(await row.locator('[data-candidate-revision]').innerText(), /True\.intro/); await reviewer.screenshot({ path: path.join(output, `revision-${language}-${width}.png`), fullPage: true }); - phase = `approve-once-${language}-${width}`; - const approvedResponse = mutation(reviewer, `${projectPath}/feedback/${candidate.id}/candidate-delivery`); - await row.locator('[data-candidate-approve]').click(); assert.equal((await approvedResponse).status(), 200); - await settled(reviewer); assert.equal(commands.length, commandsBefore + 1); + phase = `human-adoption-does-not-dispatch-${language}-${width}`; + assert.equal(await row.locator('[data-candidate-approve], [data-candidate-withdraw]').count(), 0); + const decision = row.locator('[data-feedback-decision]'); + await decision.locator('summary').click(); + await decision.locator('[data-decision-status]').selectOption('accepted'); + await decision.getByLabel(language === 'zh' ? '理由' : 'Reason', { exact: true }).fill('The explicit constructor proves the reviewed statement.'); + const adoptionResponse = mutation(reviewer, `${projectPath}/feedback/${candidate.id}/decision`); + await decision.locator('[data-save-decision]').click(); assert.equal((await adoptionResponse).status(), 200); candidate = (await http<{ item: ResearchFeedback }>(reviewer, 'GET', `${projectPath}/feedback/${candidate.id}`)).item; - assert.equal(candidate.candidateDelivery?.status, 'dispatched'); + assert.equal(candidate.decision.status, 'accepted'); + assert.equal(candidate.delivery.status, 'not-sent'); + assert.equal(commands.length, commandsBefore); phase = `continue-work-after-plan-change-${language}-${width}`; project = (await http<{ item: ResearchProjectDetail }>(author, 'GET', projectPath)).item; await http(author, 'POST', `${projectPath}/assignments`, { requestId: crypto.randomUUID(), expectedRevision: project.revision, target, status: 'claimed' }); @@ -167,9 +173,9 @@ try { project = (await http<{ item: ResearchProjectDetail }>(author, 'GET', projectPath)).item; assert.ok(project.assignments.some(item => item.author.id === authorSession.researcherId && item.target.taskRef?.version === 'goal-v1' && item.status === 'released')); assert.ok(project.assignments.some(item => item.author.id === authorSession.researcherId && item.target.taskRef?.version === 'goal-v2' && item.status === 'claimed')); - assert.equal(commands.length, commandsBefore + 1, 'Moving a claim does not submit another proof or rerun research'); + assert.equal(commands.length, commandsBefore, 'Moving a claim does not submit another proof or rerun research'); await author.screenshot({ path: path.join(output, `continued-work-${language}-${width}.png`), fullPage: true }); - checks.push({ language, width, checkedBeforeReview: true, authorCannotApprove: true, revisionRetainsEvidenceAndResponses: true, supersededCandidateNotDispatched: true, approvedDispatchesOnce: true, claimContinuesWithHistory: true }); + checks.push({ language, width, checkedBeforeReview: true, authorCannotApprove: true, revisionRetainsEvidenceAndResponses: true, supersededCandidateNotDispatched: true, humanDecisionWithoutDispatch: true, claimContinuesWithHistory: true }); assert.ok(await reviewer.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No page overflow'); await Promise.all(actors.map(actor => actor.close())); } diff --git a/scripts/test-web-collaboration-actions.ts b/scripts/test-web-collaboration-actions.ts index 3ff2abfe..c2ced60a 100644 --- a/scripts/test-web-collaboration-actions.ts +++ b/scripts/test-web-collaboration-actions.ts @@ -10,7 +10,7 @@ import { readWebConfig } from '../apps/web/config'; import { createWebService } from '../apps/web/server'; import type { WebRunner } from '../apps/web/runner'; import type { WebObservation } from '../apps/web/collaboration'; -import type { ResearchProjectDetail } from '../apps/web/researchProjectTypes'; +import type { ResearchFeedback, ResearchProjectDetail } from '../apps/web/researchProjectTypes'; import type { ResearchCollaborationInbox, ResearchIssue } from '../apps/web/researchCollaborationTypes'; import { freePort, startBrowser, preferFullCollaboration, settled } from './web-scenario'; import { mathDigest } from '../src/math/mathRuntimeIo'; @@ -21,7 +21,7 @@ const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-collaboratio const source = 'theorem plan_access_fixture : True := by sorry\n', commit = '1'.repeat(40), environment = 'e'.repeat(64); const now = () => new Date().toISOString(), hash = mathDigest; const controls = new Map(); -const commands: { type: string; id: string }[] = []; +const commands: string[] = []; const checks: object[] = [], errors: string[] = [], external: string[] = [], mail: unknown[] = []; let phase = 'setup', controlledChecks = 0; function observation(id: string): WebObservation { @@ -55,12 +55,8 @@ const runner: WebRunner = { }, async command(_runId, command) { if (command.type === 'capture') return { id: 'capture', status: 'captured' }; - if (command.type === 'guidance-withdraw') return { id: command.id, status: 'rejected', reason: 'fixture_guidance_withdraw_not_simulated' }; - const id = command.type === 'guidance' ? command.guidance.id : command.type === 'plan-approval' ? command.approval.id : command.proposal.id; - commands.push({ type: command.type, id }); - if (command.type === 'edit-preview') return { id, status: 'validated', baseVersion: 'plan-v1', affectedTaskIds: ['goal'], changes: [{ taskId: 'goal', fields: ['objective'] }] }; - if (command.type === 'edit') return { id, status: 'applied', baseVersion: 'plan-v1', planVersion: 'plan-v2', affectedTaskIds: ['goal'] }; - return { id, status: 'delivered' }; + commands.push(command.type); + throw new Error('A historical run must not receive scheduler commands'); }, }; const port = await freePort(), origin = 'http://127.0.0.1:' + port; @@ -130,37 +126,40 @@ try { currentIssue = (await http<{ item: ResearchIssue }>(owner, 'POST', `${projectPath}/issues/${issue.id}/resolution`, { requestId: crypto.randomUUID(), expectedRevision: currentIssue.revision, action: 'resolve', proposalId: proposal.id, text: '采用辅助引理后消去前提的路线' })).item; checks.push({ name: phase, exactRevisionRecovered: true, staleSubmissionBlocked: true, explicitReview: true }); - phase = 'issue-guidance-confirmation-and-uncertain-response'; await open(owner, href); - const execution = owner.locator(`#issue-${issue.id} [data-issue-execution]`); - await execution.getByText('将决议转为执行', { exact: true }).click(); - await execution.getByLabel('执行说明').fill('请采用已决议的引理路线,补全连接原题的最后一步'); - await execution.locator('[data-prepare-issue-execution]').click(); await execution.locator('[data-issue-execution-preview]').waitFor(); - assert.equal(await execution.locator('[data-send-issue-execution]').isDisabled(), true); assert.equal(commands.length, 0); - await execution.locator('[data-confirm-issue-execution]').check(); - let dropped = false; - await owner.route('**' + projectPath + '/feedback', async route => { - if (route.request().method() === 'POST' && !dropped) { dropped = true; await route.fetch(); await route.abort('failed'); } else await route.continue(); + phase = 'historical-issue-execution-is-read-only'; + const resolution = currentIssue.resolution!; + const issueSource = { issueId: issue.id, issueRevision: currentIssue.revision, + resolutionAt: resolution.createdAt, proposalId: proposal.id }; + const historicalFeedback: ResearchFeedback = { + id: 'historical-guidance', requestId: crypto.randomUUID(), projectId: project.id, + author: resolution.author, kind: 'guidance', text: '历史指导:用辅助引理完成最后一步', visibility: 'members', + issueSource: { ...issueSource, title: issue.title, resolution: { text: resolution.text, author: resolution.author }, + proposal: { id: proposal.id, text: proposal.text, author: proposal.author }, originalTarget: target }, + target, payload: { recipient: { kind: 'task', id: 'goal' } }, delivery: { status: 'delivered', commandId: 'historical-guidance' }, + decision: { status: 'pending', evidenceRefs: [] }, execution: { status: 'not-started', taskRefs: [], resultRefs: [] }, + revision: 1, createdAt: resolution.createdAt, updatedAt: resolution.createdAt, + }; + const projectRecord = ['research', 'projects', `${project.id}.json`]; + const stored = service.storage.getRecord<{ feedback: ResearchFeedback[] }>(projectRecord)!; + stored.feedback.push(historicalFeedback); + service.storage.saveRecord(projectRecord, stored); + await open(owner, href); + const issueAnchor = '#issue-' + issue.id; + const resolvedIssue = owner.locator(issueAnchor); + await resolvedIssue.getByText(resolution.text, { exact: true }).waitFor(); + assert.equal(await resolvedIssue.locator('[data-prepare-issue-execution]').count(), 0); + const record = owner.locator('#feedback-' + historicalFeedback.id); + await record.locator('[data-feedback-issue-source] summary').click(); + await record.getByText(proposal.text, { exact: true }).waitFor(); + assert.equal(await record.getByRole('link', { name: '查看议题', exact: true }).getAttribute('href'), issueAnchor); + const session = await http<{ csrfToken: string }>(owner, 'GET', '/api/session'); + const legacyMutation = await owner.request.post(origin + projectPath + '/feedback', { + headers: { 'X-CSRF-Token': session.csrfToken }, + data: { requestId: crypto.randomUUID(), kind: 'guidance', text: '继续历史运行', issueSource, target, recipient: { kind: 'task', id: 'goal' } }, }); - await execution.locator('[data-send-issue-execution]').click(); await execution.getByRole('button', { name: '查看后续采纳与执行', exact: true }).waitFor(); - await owner.unroute('**' + projectPath + '/feedback'); - project = (await http<{ item: ResearchProjectDetail }>(owner, 'GET', projectPath)).item; - const guidance = project.feedback.find(item => item.kind === 'guidance')!; assert.ok(guidance); - assert.equal(guidance.issueSource?.proposal?.id, proposal.id); assert.deepEqual(guidance.issueSource?.originalTarget, target); - assert.equal(commands.filter(command => command.type === 'guidance').length, 1); assert.equal(await execution.locator('[data-issue-execution-pending]').count(), 0); - checks.push({ name: phase, explicitConfirmation: true, frozenOrigin: true, droppedResponseRecovered: true, guidanceDispatches: 1 }); - - phase = 'issue-plan-preview-before-apply'; - await execution.locator('[data-issue-execution-kind]').selectOption('plan-edit'); - await execution.getByLabel('任务目标', { exact: true }).fill('使用辅助事实构造最终证明,逐步核对依赖'); - await save(owner, 'POST', `${projectPath}/runs/${createdRun.id}/edits/preview`, () => execution.locator('[data-prepare-issue-execution]').click()); - assert.equal(commands.filter(command => command.type === 'edit-preview').length, 1); assert.equal(commands.filter(command => command.type === 'edit').length, 0); - await execution.locator('[data-confirm-issue-execution]').check(); - await save(owner, 'POST', projectPath + '/feedback', () => execution.locator('[data-send-issue-execution]').click(), 201); - project = (await http<{ item: ResearchProjectDetail }>(owner, 'GET', projectPath)).item; - const edit = project.feedback.find(item => item.kind === 'plan-edit')!; assert.ok(edit?.payload && 'proposal' in edit.payload); - assert.equal(edit.payload.proposal.tasks.length, 2); assert.equal(edit.payload.proposal.tasks.find(task => task.id === 'lemma')?.objective, '证明辅助事实'); - assert.equal(commands.filter(command => command.type === 'edit').length, 1); - checks.push({ name: phase, previewHasNoEdit: true, fullPlanPreserved: true, explicitApply: true }); + assert.equal(legacyMutation.status(), 409); + assert.deepEqual(commands, []); + checks.push({ name: phase, frozenOriginVisible: true, legacyWriteRejected: true }); phase = 'review-ownership-and-personal-inbox'; const feedback = (await http<{ item: ResearchProjectDetail['feedback'][number] }>(owner, 'POST', projectPath + '/feedback', { requestId: crypto.randomUUID(), kind: 'discussion', text: '请评审这一步 $P \\Rightarrow Q$', statementVersionId: version })).item; diff --git a/scripts/test-web-collaboration-entry-permissions.ts b/scripts/test-web-collaboration-entry-permissions.ts index ce21e7d4..49f2f34b 100644 --- a/scripts/test-web-collaboration-entry-permissions.ts +++ b/scripts/test-web-collaboration-entry-permissions.ts @@ -6,6 +6,7 @@ import os from 'node:os'; import path from 'node:path'; import type { Page } from 'playwright'; import { readWebConfig } from '../apps/web/config'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; import { createWebService } from '../apps/web/server'; import type { WebRunner } from '../apps/web/runner'; import type { ResearchProjectDetail } from '../apps/web/researchProjectTypes'; @@ -17,7 +18,7 @@ const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'theoremos-collaboratio const errors: string[] = [], external: string[] = [], mail: unknown[] = [], finishers: (() => void)[] = [], checks: object[] = []; const source = 'theorem collaboration_entry_fixture : True := by sorry\n'; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Disposable entry-permission check' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Disposable entry-permission check' }; }, async run(_input, _send, signal) { await new Promise(resolve => { finishers.push(resolve); signal.addEventListener('abort', () => resolve(), { once: true }); }); }, async check() { throw new Error('This check must not invoke Lean'); }, async command() { throw new Error('This check must not dispatch solver commands'); }, @@ -46,7 +47,7 @@ try { let project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', '/api/research/theorems', { requestId: crypto.randomUUID(), title: '公开入口授权', visibility: 'public' })).item; const projectPath = '/api/research/theorems/' + project.id; project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/versions', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statement: 'Prove True', source, environment: 'standard' })).item; - const run = (await http<{ run: { id: string } }>(owner, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-entry-check', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Check entry permissions', maxTurns: 1, maxRunSeconds: 600, workers: 1, coordination: 'cooperative' })).run; + const run = (await http<{ run: { id: string } }>(owner, 'POST', '/api/runs', { requestId: crypto.randomUUID(), providerId: 'openai', apiKey: 'sk-disposable-entry-check', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Check entry permissions', maxTurns: 1, maxRunSeconds: 600, ...webAgentTeamPreset() })).run; project = (await http<{ item: ResearchProjectDetail }>(owner, 'POST', projectPath + '/runs', { requestId: crypto.randomUUID(), expectedRevision: project.revision, statementVersionId: project.currentStatementVersionId, runId: run.id, exposure: 'public' })).item; project = (await http<{ item: ResearchProjectDetail }>(owner, 'PUT', projectPath + '/members/' + researcher.researcherId, { requestId: crypto.randomUUID(), expectedRevision: project.revision, role: 'reader' })).item; const href = `${origin}/theorems.html?id=${project.id}&run=${run.id}&version=${project.currentStatementVersionId}`; diff --git a/scripts/test-web-inline-annotations.ts b/scripts/test-web-inline-annotations.ts index 70a45ad0..e76f967d 100644 --- a/scripts/test-web-inline-annotations.ts +++ b/scripts/test-web-inline-annotations.ts @@ -1,6 +1,6 @@ #!/usr/bin/env bun // Disposable HTTP/Chromium state with a controlled runner; no real models, Lean or mail. -import { seedCooperativeRun } from './web-cooperative-fixture'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; @@ -23,13 +23,17 @@ const controls = new Map( const commands: { id: string; type: string }[] = [], errors: string[] = [], external: string[] = [], checks: object[] = []; let compileCalls = 0, prohibited = 0, phase = 'setup', active: Page | undefined, failure: unknown; const runner: WebRunner = { - async readiness() { return { ready: true, message: 'Controlled inline annotation workflow' }; }, + async readiness() { return { ready: true, nativeTeam: true, message: 'Controlled inline annotation workflow' }; }, async check(input) { compileCalls++; return { exitCode: 0, timedOut: false, output: '', checkedTarget: input.candidateTarget?.name }; }, async run(input, send, signal) { const observation = structuredClone(loadWebSample()!.observations.at(-1)!); observation.webRunId = input.id; observation.sequence = 1; observation.snapshot.stateDigest = mathDigest(`inline-v1:${input.id}`); observation.inspection.problem = { id: 'inline-fixture', statement: 'Prove $\\mathrm{True}$', formalStatement: 'True', assumptions: [], targets: [{ theoremName: 'target', proofPath: 'Main.lean' }] }; - observation.inspection.configuration.environmentDigest = environmentDigest; + Object.assign(observation.inspection.configuration, { + environmentDigest, workers: 1, coordination: 'independent', researchMode: 'skill', + researchSkill: { name: 'theoremos-research', digest: mathDigest('fixture skill'), loading: 'native' }, + researchDelegation: { mode: 'team', maxAgents: input.input.nativeTeamCapacity }, + }); observation.inspection.tasks = [{ id: 'goal', kind: 'goal', objective: 'Prove True', theorem: 'target', type: 'True', informalStatement: 'The proposition $\\mathrm{True}$ is inhabited.', informalProof: 'Use the constructor $\\mathrm{True.intro}$ to close the goal.', group: 'main', status: 'working', control: 'active', version: 'goal-v1', premises: ['No extra assumptions.'], plannedDependencies: [], attempts: 0, proof: { status: 'open' }, parkedBy: [], parkedRoutes: {} }]; @@ -48,8 +52,8 @@ const runner: WebRunner = { }, async command(runId, command) { if (command.type === 'capture') return { id: 'capture', status: 'captured' }; - if (command.type === 'guidance-withdraw') return { id: command.id, status: 'rejected', reason: 'fixture_guidance_withdraw_not_simulated' }; - const id = command.type === 'guidance' ? command.guidance.id : command.type === 'plan-approval' ? command.approval.id : command.proposal.id; + if (command.type !== 'plan-approval') throw new Error('Unexpected command: ' + command.type); + const id = command.approval.id; commands.push({ id, type: command.type }); const control = controls.get(runId)!; if (command.type === 'plan-approval') { @@ -86,7 +90,7 @@ try { await Promise.all([owner, peer].map(page => page.goto(origin + '/theorems.html'))); const peerSession = await http<{ researcherId: string }>(peer, 'GET', '/api/research/session'); for (const [page, name] of [[owner, 'Owner'], [peer, 'Peer']] as const) await http(page, 'PUT', '/api/research/profile', { requestId: crypto.randomUUID(), expectedRevision: 0, displayName: name, visibility: 'public' }); - const run = await seedCooperativeRun(service, owner.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-inline-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); + const { run } = await http<{ run: { id: string } }>(owner, 'POST', '/api/runs', { providerId: 'openai', apiKey: 'sk-disposable-inline-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, ...webAgentTeamPreset(), planApproval: true }); await owner.waitForFunction(async id => (await (await fetch(`/api/runs/${id}`)).json()).run.observation, run.id); const routeUrl = `${origin}/problem.html?${new URLSearchParams({ run: run.id, tab: 'route', task: 'goal', taskVersion: 'goal-v1' })}`; await owner.goto(routeUrl); const inline = owner.locator('[data-research-inline-actions]'); await inline.locator('[data-inline-open]').click(); await inline.locator('[data-inline-approve-plan]').waitFor(); @@ -95,14 +99,11 @@ try { assert.equal(await inline.locator('[data-inline-open]').evaluate(node => document.activeElement === node), true); await inline.locator('[data-inline-open]').click(); assert.match(await inline.locator('[data-inline-math-context]').innerText(), /True\.intro/); - phase = `personal-plan-and-guidance-${language}-${width}`; + phase = `personal-plan-approval-${language}-${width}`; assert.equal(await inline.locator('[data-inline-approve-plan]').isDisabled(), true); await inline.locator('[data-inline-confirm-plan]').check(); const approval = mutation(owner, `/api/runs/${run.id}/plan-approval`); await inline.locator('[data-inline-approve-plan]').click(); assert.equal((await approval).status(), 200); - await inline.getByText(language === 'zh' ? '对这一步提供指导' : 'Give guidance for this step', { exact: true }).click(); - await inline.getByLabel(language === 'zh' ? '希望怎样改进这一步或路线' : 'How should this step or route improve?', { exact: true }).fill('Use True.intro explicitly in this task.'); - await inline.locator('[data-inline-confirm-guidance]').check(); - const guidance = mutation(owner, `/api/runs/${run.id}/guidance`); await inline.locator('[data-inline-send-guidance]').click(); assert.equal((await guidance).status(), 200); + assert.equal(await inline.locator('[data-inline-guidance]').count(), 0); phase = `personal-math-and-source-annotations-${language}-${width}`; const notesPath = `/api/research/runs/${run.id}/annotations`, notes = inline.locator('[data-research-annotations]'); @@ -144,7 +145,7 @@ try { await owner.goto(projectUrl); active = owner; const ownerInline = owner.locator('[data-research-inline-actions]'); await ownerInline.locator('[data-inline-open]').click(); await ownerInline.getByText(language === 'zh' ? '在此审阅对应提交与决定' : 'Review related submissions and decisions here', { exact: true }).click(); assert.equal(await ownerInline.locator('[data-feedback-scope]').inputValue(), 'task', 'The drawer initially scopes reviews to the selected task'); - const candidateRow = ownerInline.locator(`#feedback-${candidate.id}`); await candidateRow.locator('[data-candidate-approve]').waitFor(); + const candidateRow = ownerInline.locator(`#feedback-${candidate.id}`); await candidateRow.locator('[data-candidate-delivery-status="awaiting-review"]').waitFor(); await candidateRow.getByText(language === 'zh' ? '对公式或源码作精确评审' : 'Review a formula or exact source passage', { exact: true }).click(); const candidateNotes = candidateRow.locator('[data-research-annotations]'); await candidateNotes.getByText(language === 'zh' ? '添加精确批注' : 'Add a passage comment', { exact: true }).click(); await candidateNotes.locator('[data-annotation-kind="source"]').click(); await candidateNotes.locator('[data-annotation-line="2"]').click(); @@ -168,11 +169,11 @@ try { assert.ok(await drawer.evaluate(node => node.scrollHeight > node.clientHeight && node.scrollWidth <= node.clientWidth + 1), 'Drawer scrolls internally without horizontal overflow'); await drawer.locator('[data-inline-close]').click(); assert.equal(await owner.locator('[data-inline-open]').evaluate(node => document.activeElement === node), true); assert.ok(await owner.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No page overflow'); - checks.push({ language, width, initialScopeTask: true, drawerFocusRestored: true, drawerScrollsWithoutOverflow: true, personalPlanApproved: true, personalGuidanceSent: true, sourceAndMathAnchorsValidated: true, replyResolved: true, + checks.push({ language, width, initialScopeTask: true, drawerFocusRestored: true, drawerScrollsWithoutOverflow: true, personalPlanApproved: true, sourceAndMathAnchorsValidated: true, replyResolved: true, sharedClaimAndCandidateInline: true, exactReviewJoinsRevisionFlow: true, outdatedAnchorRetained: true }); await Promise.all(actors.map(actor => actor.close())); } - assert.deepEqual(errors, []); assert.deepEqual(external, []); assert.equal(prohibited, 0); assert.equal(compileCalls, 2); + assert.deepEqual(errors, []); assert.deepEqual(external, []); assert.equal(prohibited, 0); assert.equal(compileCalls, 2); assert.equal(commands.length, 2); } catch (error) { failure = error; if (active && !active.isClosed()) await active.screenshot({ path: path.join(output, 'failure.png'), fullPage: true }).catch(() => {}); } finally { diff --git a/scripts/test-web-issue-action-continuity.ts b/scripts/test-web-issue-action-continuity.ts index 41292350..3a3743a0 100644 --- a/scripts/test-web-issue-action-continuity.ts +++ b/scripts/test-web-issue-action-continuity.ts @@ -10,8 +10,9 @@ import { readWebConfig } from '../apps/web/config'; import { loadWebSample } from '../apps/web/sample'; import { mathDigest } from '../src/math/mathRuntimeIo'; import type { WebRunner } from '../apps/web/runner'; -import type { WebObservation } from '../apps/web/collaboration'; +import type { ResearchIssue } from '../apps/web/researchCollaborationTypes'; import type { ResearchFeedback, ResearchProjectDetail } from '../apps/web/researchProjectTypes'; +import { seedCooperativeRun } from './web-cooperative-fixture'; import { freePort, startBrowser, preferFullCollaboration, settled } from './web-scenario'; const root = path.resolve(import.meta.dirname, '..'); @@ -20,18 +21,21 @@ const staticRoot = process.env.THEOREMOS_FRONTEND_TEST_STATIC_ROOT ?? path.join( await fs.mkdir(output, { recursive: true }); const dataRoot = await fs.mkdtemp(path.join(output, 'disposable-data-')); const source = 'theorem target : True := by sorry\n', commit = '1'.repeat(40), environmentDigest = mathDigest('controlled-candidate-environment'); -const controls = new Map(); -const commands: { id: string; type: string }[] = [], errors: string[] = [], external: string[] = [], checks: object[] = []; -let delivery: 'unknown' | 'delivered' = 'delivered'; +const stateDigest = mathDigest('candidate-v1'); +const commands: string[] = [], executionWrites: string[] = [], errors: string[] = [], external: string[] = [], checks: object[] = []; let compileCalls = 0, prohibited = 0, phase = 'setup', active: Page | undefined, failure: unknown; const runner: WebRunner = { async readiness() { return { ready: true, message: 'Controlled candidate workflow' }; }, async check(input) { compileCalls++; return { exitCode: 0, timedOut: false, output: '', checkedTarget: input.candidateTarget?.name }; }, async run(input, send, signal) { const observation = structuredClone(loadWebSample()!.observations.at(-1)!); - observation.webRunId = input.id; observation.sequence = 1; observation.snapshot.stateDigest = mathDigest('candidate-v1'); + observation.webRunId = input.id; observation.sequence = 1; observation.snapshot.stateDigest = stateDigest; observation.inspection.problem = { id: 'candidate-fixture', statement: 'Prove True', formalStatement: 'True', assumptions: [], targets: [{ theoremName: 'target', proofPath: 'Main.lean' }] }; - observation.inspection.configuration.environmentDigest = environmentDigest; + const configuration = observation.inspection.configuration; + const { model, effort, workers, coordination } = input.input; + Object.assign(configuration, { model, effort, workers, coordination, environmentDigest }); + delete configuration.researchMode; + delete configuration.researchDelegation; observation.inspection.tasks = [{ id: 'goal', kind: 'goal', objective: 'Prove True', theorem: 'target', type: 'True', group: 'main', status: 'working', control: 'active', version: 'goal-v1', premises: [], plannedDependencies: [], attempts: 0, proof: { status: 'open' }, parkedBy: [], parkedRoutes: {} }]; @@ -43,15 +47,14 @@ const runner: WebRunner = { observation.checks = []; observation.guidance = []; observation.history = []; observation.deliveries = []; observation.coverage = { sources: 'recorded', checks: 'recorded' }; await new Promise(resolve => { - controls.set(input.id, { observation, emit() { send({ type: 'observation', observation: structuredClone(this.observation) }); } }); - controls.get(input.id)!.emit(); signal.addEventListener('abort', () => resolve(), { once: true }); + signal.addEventListener('abort', () => resolve(), { once: true }); + send({ type: 'observation', observation }); }); }, async command(_id, command) { if (command.type === 'capture') return { id: 'capture', status: 'captured' }; - if (command.type === 'guidance-withdraw') return { id: command.id, status: 'rejected', reason: 'fixture_guidance_withdraw_not_simulated' }; - const id = command.type === 'guidance' ? command.guidance.id : command.type === 'plan-approval' ? command.approval.id : command.proposal.id; - commands.push({ id, type: command.type }); if(command.type==='edit-preview')return {id,status:'validated',baseVersion:'plan-v1',affectedTaskIds:['goal']}; return { id, status: delivery, reason: delivery === 'unknown' ? 'Controlled delivery acknowledgement unavailable' : 'Controlled delivered receipt' }; + commands.push(command.type); + throw new Error('Historical issue execution must not dispatch a command'); }, }; const port = await freePort(), origin = `http://127.0.0.1:${port}`; @@ -90,27 +93,22 @@ try { for(const p of [page,peer]){p.setDefaultTimeout(15000);p.on('pageerror',e=>errors.push(e.message));p.on('dialog',async dialog=>{dialogs.push({language,type:dialog.type(),message:dialog.message()});await dialog.accept();});await p.goto(origin+'/workspace.html');await p.locator('.workspace-tabs').waitFor();} const owner=`account:${accounts[offset].id}`,reviewer=`account:${accounts[offset+1].id}`,peerId=service.research.projects.identity(reviewer); for(const [p,name]of [[page,'Project Owner'],[peer,'Independent Reviewer']]as const)await http(p,'PUT','/api/research/profile',{requestId:crypto.randomUUID(),expectedRevision:0,displayName:name,visibility:'public'}); - const {run}=await http<{run:{id:string}}>(page,'POST','/api/runs',{requestId:crypto.randomUUID(),providerId:'openai',apiKey:'sk-disposable-collaboration-fixture',model:'fixture',effort:'low',environment:'standard',source,task:'Prove True',maxTurns:2,maxRunSeconds:600,workers:2,coordination:'cooperative'}); + const run=await seedCooperativeRun(service,page.context(),origin,{providerId:'openai',apiKey:'sk-disposable-collaboration-fixture',model:'fixture',effort:'low',environment:'standard',source,task:'Prove True',maxTurns:2,maxRunSeconds:600,workers:2,coordination:'cooperative'}); await page.waitForFunction(async id=>(await(await fetch(`/api/runs/${id}`)).json()).run.observation,run.id); let project=(await http<{item:ResearchProjectDetail}>(page,'POST','/api/research/theorems',{requestId:crypto.randomUUID(),title:'Human decision and action continuity',visibility:'members',candidateDeliveryPolicy:'reviewed'})).item; const projectPath=`/api/research/theorems/${project.id}`; project=(await http<{item:ResearchProjectDetail}>(page,'PUT',`${projectPath}/members/${peerId}`,{requestId:crypto.randomUUID(),expectedRevision:project.revision,role:'collaborator'})).item; project=(await http<{item:ResearchProjectDetail}>(page,'POST',`${projectPath}/versions`,{requestId:crypto.randomUUID(),expectedRevision:project.revision,source,statement:'Prove True',environment:'standard'})).item; project=(await http<{item:ResearchProjectDetail}>(page,'POST',`${projectPath}/runs`,{requestId:crypto.randomUUID(),expectedRevision:project.revision,runId:run.id,statementVersionId:project.currentStatementVersionId,grants:{guidance:true,edit:true,approve:true,proof:true}})).item; - const target={runId:run.id,statementVersionId:project.currentStatementVersionId!,observationRef:{sequence:1,stateDigest:controls.get(run.id)!.observation.snapshot.stateDigest},taskRef:{id:'goal',version:'goal-v1'}}; + const target={runId:run.id,statementVersionId:project.currentStatementVersionId!,observationRef:{sequence:1,stateDigest},taskRef:{id:'goal',version:'goal-v1'}}; const issueUrl=(id:string)=>`${origin}/theorems.html?${new URLSearchParams({id:project.id,run:run.id,version:target.statementVersionId,task:'goal',taskVersion:'goal-v1'})}#issue-${id}`; const createIssue=async(title:string,resolution?:string)=>{ project=service.research.projects.detail(owner,project.id); - let issue=(await http<{item:any}>(page,'POST',`${projectPath}/issues`,{requestId:crypto.randomUUID(),expectedRevision:project.revision,title,text:'Review the argument and agree on an explicit action.',target})).item; - if(resolution)issue=(await http<{item:any}>(page,'POST',`${projectPath}/issues/${issue.id}/resolution`,{requestId:crypto.randomUUID(),expectedRevision:issue.revision,action:'resolve',text:resolution})).item; + let issue=(await http<{item:ResearchIssue}>(page,'POST',`${projectPath}/issues`,{requestId:crypto.randomUUID(),expectedRevision:project.revision,title,text:'Review the argument and agree on an explicit action.',target})).item; + if(resolution)issue=(await http<{item:ResearchIssue}>(page,'POST',`${projectPath}/issues/${issue.id}/resolution`,{requestId:crypto.randomUUID(),expectedRevision:issue.revision,action:'resolve',text:resolution})).item; return issue; }; const openIssue=async(p:Page,id:string)=>{active=p;await p.goto(issueUrl(id));const card=p.locator(`[data-collaboration-issue="${id}"]`);await card.waitFor();return card;}; - const openExecution=async(p:Page,id:string)=>{const card=await openIssue(p,id),execution=card.locator('[data-issue-execution]');await openDetails(execution.locator(':scope>details'));await execution.locator('[data-prepare-issue-execution]').waitFor();await p.waitForFunction(()=>!document.querySelector('main[aria-busy="true"]'));return execution;}; - const submitExecution=async(p:Page,execution:Locator)=>{ - await execution.locator('[data-prepare-issue-execution]').click();await execution.locator('[data-issue-execution-preview]').waitFor();await execution.locator('[data-confirm-issue-execution]').check(); - const response=p.waitForResponse(r=>r.request().method()==='POST'&&new URL(r.url()).pathname===`${projectPath}/feedback`);await execution.locator('[data-send-issue-execution]').click();const saved=await response;assert.equal(saved.status(),201);return(await saved.json()).item as ResearchFeedback; - }; phase=`normal-contribution-draft-${language}`; const open=await createIssue('Control: issue contribution survives navigation'); @@ -126,63 +124,70 @@ try { await card.screenshot({path:path.join(output,`control-contribution-draft-${language}-${width}.png`)}); checks.push({id:'normal-contribution-draft',language,width,localPickerAvailable:true,restoredText:await contribution.inputValue()}); - phase=`execution-edit-refresh-${language}`; - const resolved=await createIssue('Decision: prepare the next exact step','Use the explicit constructor after checking all dependencies.'); - let execution=await openExecution(page,resolved.id); - const edited='UNSAVED_ACTION: Check the current goal, explicitly construct True.intro, and record why no assumptions are needed.'; - const instructions=execution.getByLabel(language==='zh'?'执行说明':'Execution instructions',{exact:true});await instructions.fill(edited); - await execution.locator('[data-issue-execution-kind]').selectOption('plan-edit');await execution.getByLabel(language==='zh'?'任务目标':'Task objective',{exact:true}).fill('HUMAN_PLAN_EDIT: Explain the construction and then close the exact goal.');await execution.getByLabel(language==='zh'?'前置任务,用逗号分隔':'Prerequisite task IDs, separated by commas',{exact:true}).fill('lemma-a, lemma-b'); - await execution.locator('[data-prepare-issue-execution]').waitFor({state:'visible'}); - await execution.screenshot({path:path.join(output,`execution-edit-before-refresh-${language}-${width}.png`)}); - const localBefore=await page.evaluate(()=>Object.keys(localStorage).filter(key=>key.startsWith('theoremos:issue-execution-draft:v1:')).map(key=>localStorage.getItem(key)).filter(Boolean)); - const dialogBefore=dialogs.length;await page.reload();execution=await openExecution(page,resolved.id); - const afterInstructions=await execution.getByLabel(language==='zh'?'执行说明':'Execution instructions',{exact:true}).inputValue(),afterMode=await execution.locator('[data-issue-execution-kind]').inputValue(); - const restoredObjective=await execution.getByLabel(language==='zh'?'任务目标':'Task objective',{exact:true}).inputValue(); - assert.equal(afterInstructions,edited);assert.equal(afterMode,'plan-edit');assert.equal(restoredObjective,'HUMAN_PLAN_EDIT: Explain the construction and then close the exact goal.');assert.equal(await execution.getByLabel(language==='zh'?'前置任务,用逗号分隔':'Prerequisite task IDs, separated by commas',{exact:true}).inputValue(),'lemma-a, lemma-b');assert.equal(dialogs.length,dialogBefore);assert.equal(localBefore.some(v=>v!.includes('UNSAVED_ACTION')&&v!.includes('HUMAN_PLAN_EDIT')),true); - await execution.locator('[data-issue-execution-restored]').waitFor();assert.equal(await execution.locator('[data-prepare-issue-execution]').isDisabled(),true);assert.equal(await execution.locator('[data-issue-execution-preview]').count(),0); - await execution.screenshot({path:path.join(output,`execution-edit-restored-${language}-${width}.png`)}); - await execution.locator('[data-confirm-issue-task-version]:enabled').click();await execution.locator('[data-prepare-issue-execution]:enabled').waitFor(); - checks.push({id:'A4-complete-action-draft-restores-and-requires-review',language,width,mode:afterMode,text:afterInstructions,objective:restoredObjective,restoredWithoutOldConfirmation:true}); - - phase=`normal-execution-and-return-${language}`; - delivery='delivered';await execution.locator('[data-issue-execution-kind]').selectOption('guidance');const normal=await submitExecution(page,execution);assert.equal(normal.delivery.status,'delivered');await execution.getByRole('button',{name:language==='zh'?'查看后续采纳与执行':'View decisions and execution',exact:true}).click(); - const feedback=page.locator(`#feedback-${normal.id}`);await feedback.waitFor();assert.ok((await feedback.innerText()).includes(edited)); - await feedback.screenshot({path:path.join(output,`control-execution-feedback-${language}-${width}.png`)}); - checks.push({id:'normal-resolution-execution-feedback',language,width,feedbackId:normal.id,delivery:normal.delivery.status,exactTaskVersion:new URL(page.url()).searchParams.get('taskVersion')}); + phase=`historical-execution-${language}`; + const resolved = await createIssue('Decision: use the explicit constructor', 'Apply True.intro after checking the dependencies.'); + const resolution = resolved.resolution!; + const issueSource = { issueId: resolved.id, issueRevision: resolved.revision, resolutionAt: resolution.createdAt }; + const feedbackId = 'historical-action-' + language; + const savedText = 'Historical execution: the constructor closes the exact goal.'; + const historicalFeedback: ResearchFeedback = { + id: feedbackId, requestId: crypto.randomUUID(), projectId: project.id, + author: resolution.author, kind: 'guidance', text: savedText, visibility: 'members', + issueSource: { ...issueSource, title: resolved.title, resolution: { text: resolution.text, author: resolution.author }, originalTarget: target }, + target, payload: { recipient: { kind: 'task', id: target.taskRef.id } }, + delivery: { status: 'delivered', commandId: feedbackId }, + decision: { status: 'not-recorded', evidenceRefs: [] }, + execution: { status: 'not-started', taskRefs: [], resultRefs: [] }, + revision: 1, createdAt: resolution.createdAt, updatedAt: resolution.createdAt, + }; + const projectRecord = ['research', 'projects', `${project.id}.json`]; + const stored = seed.getRecord<{ feedback: ResearchFeedback[] }>(projectRecord)!; + stored.feedback.push(historicalFeedback); + seed.saveRecord(projectRecord, stored); - phase=`unknown-execution-refresh-${language}`; - const uncertain=await createIssue('Decision: an acknowledgement may arrive late','Follow the resolved construction exactly once.');delivery='unknown';execution=await openExecution(peer,uncertain.id);await execution.locator('[data-prepare-issue-execution]:enabled').waitFor(); - const first=await submitExecution(peer,execution);assert.equal(first.delivery.status,'unknown');await execution.locator('[data-issue-execution-pending]').waitFor(); - const beforeCommands=commands.filter(command=>command.type==='guidance').length; - const checkResponse=peer.waitForResponse(r=>r.request().method()==='GET'&&new URL(r.url()).pathname===`${projectPath}/feedback`);await execution.locator('[data-query-issue-execution]').click();assert.equal((await checkResponse).status(),200);await settled(peer); - assert.equal(commands.filter(command=>command.type==='guidance').length,beforeCommands); - assert.equal(await execution.locator('[data-retry-issue-execution]').count(),0); - await execution.screenshot({path:path.join(output,`unknown-execution-before-refresh-${language}-${width}.png`)}); - await peer.reload();execution=await openExecution(peer,uncertain.id);await execution.locator('[data-issue-execution-pending]').waitFor();assert.equal(await execution.locator('[data-issue-execution-pending]').getAttribute('data-issue-execution-request'),first.requestId);assert.equal(await execution.locator('[data-prepare-issue-execution]').isDisabled(),true); - await execution.locator('[data-issue-execution-notice]').waitFor();assert.equal(await execution.locator('[data-retry-issue-execution]').count(),0); - await execution.screenshot({path:path.join(output,`unknown-execution-restored-${language}-${width}.png`)}); - await peer.goto(origin+'/workspace.html?tab=inbox');execution=await openExecution(peer,uncertain.id);await execution.locator('[data-issue-execution-pending]').waitFor();assert.equal(await execution.locator('[data-issue-execution-pending]').getAttribute('data-issue-execution-request'),first.requestId); - assert.equal(commands.filter(command=>command.id===first.id).length,1);assert.equal(service.research.projects.detail(owner,project.id).feedback.filter(f=>f.issueSource?.issueId===uncertain.id).length,1); - service.research.projects.recordCommand(owner,project.id,first.id,{id:first.id,status:'delivered'});await peer.reload();execution=await openExecution(peer,uncertain.id);await peer.waitForFunction(()=>!document.querySelector('[data-issue-execution-pending]')); - checks.push({id:'A3-unknown-original-survives-refresh-and-reopen',language,width,originalRequestId:first.requestId,controlledDeliveries:1,newActionBlockedWhileUnknown:true,confirmedReceiptClearsPending:true}); + page.on('request', request => { + const pathname = new URL(request.url()).pathname; + if (request.method() === 'POST' && [`${projectPath}/feedback`, `/api/runs/${run.id}/edits/preview`].includes(pathname)) { + executionWrites.push(pathname); + } + }); + const draft = { kind: 'plan-edit', text: 'Unsent execution draft.', objective: 'Explain the proof step.', dependencies: 'lemma-a, lemma-b' }; + const pendingText = 'Execution request with a missing acknowledgement.'; + await page.evaluate(({ suffix, draft, input }) => { + localStorage.setItem(`theoremos:issue-execution-draft:v1:${suffix}`, JSON.stringify(draft)); + localStorage.setItem(`theoremos:issue-execution-pending:v1:${suffix}`, JSON.stringify({ input })); + }, { + suffix: encodeURIComponent(JSON.stringify([service.research.projects.identity(owner), project.id, resolved.id])), + draft, input: { kind: 'guidance', requestId: crypto.randomUUID(), text: pendingText, issueSource, target }, + }); + const execution = (await openIssue(page, resolved.id)).locator('[data-issue-execution]'); + const restored = execution.locator('[data-issue-execution-restored]'); + await openDetails(restored); + for (const note of [draft.text, draft.objective, draft.dependencies, pendingText]) { + await restored.getByText(note, { exact: true }).waitFor(); + } + assert.equal(await execution.locator('form, button, input, select, textarea').count(), 0); + await execution.screenshot({ path: path.join(output, `historical-execution-${language}-${width}.png`) }); - phase=`missing-original-retry-and-changed-target-${language}`; - const interrupted=await createIssue('Decision: a request was not received','Send the original action once.');execution=await openExecution(peer,interrupted.id);await execution.locator('[data-prepare-issue-execution]:enabled').waitFor(); - let interruptedBody:any,interruptionDone!:()=>void;const interruption=new Promise(resolve=>interruptionDone=resolve);const feedbackPath=origin+`${projectPath}/feedback`; - await peer.route(feedbackPath,async route=>{if(route.request().method()==='POST'){interruptedBody=route.request().postDataJSON();await route.abort('failed');interruptionDone();}else await route.continue();}); - await execution.locator('[data-prepare-issue-execution]').click();await execution.locator('[data-confirm-issue-execution]').check();await execution.locator('[data-send-issue-execution]').click();await interruption;await execution.locator('[data-issue-execution-pending]').waitFor();await peer.unroute(feedbackPath); - assert.ok(interruptedBody.requestId);await peer.reload();execution=await openExecution(peer,interrupted.id);await execution.locator('[data-retry-issue-execution]:enabled').waitFor();assert.equal(await execution.locator('[data-issue-execution-pending]').getAttribute('data-issue-execution-request'),interruptedBody.requestId); - const control=controls.get(run.id)!,originalObservation=structuredClone(control.observation);control.observation.history=[structuredClone(control.observation.inspection.tasks[0])];control.observation.inspection.tasks[0].version='goal-v2';control.observation.sources[0].taskVersion='goal-v2';control.observation.sequence=2;control.observation.snapshot.stateDigest=mathDigest('version-changed');control.emit(); - await peer.reload();execution=await openExecution(peer,interrupted.id);await execution.locator('[data-retry-issue-execution]').waitFor();assert.equal(await execution.locator('[data-retry-issue-execution]').isDisabled(),true);assert.equal(await execution.locator('[data-issue-execution-pending]').getAttribute('data-issue-execution-request'),interruptedBody.requestId); - await execution.screenshot({path:path.join(output,`original-retry-blocked-changed-task-${language}-${width}.png`)}); - control.observation={...originalObservation,sequence:3,snapshot:{...originalObservation.snapshot,stateDigest:mathDigest('task-version-restored')}};control.emit();await peer.reload();execution=await openExecution(peer,interrupted.id);await execution.locator('[data-retry-issue-execution]:enabled').waitFor(); - const retriedResponse=peer.waitForResponse(r=>r.request().method()==='POST'&&new URL(r.url()).pathname===`${projectPath}/feedback`);await execution.locator('[data-retry-issue-execution]').click();const retryResponse=await retriedResponse;assert.equal(retryResponse.status(),201);const retryRecord=(await retryResponse.json()).item;assert.equal(retryRecord.requestId,interruptedBody.requestId);assert.equal(retryRecord.text,interruptedBody.text);assert.deepEqual(retryRecord.target,interruptedBody.target);assert.equal(commands.filter(command=>command.id===retryRecord.id).length,1); - checks.push({id:'A3-missing-request-retry-keeps-original-id-and-frozen-target',language,width,originalId:interruptedBody.requestId,retriedId:retryRecord.requestId,targetChangesBlockRetry:true,controlledDeliveries:1}); + await execution.getByRole('link', { + name: language === 'zh' ? '查看此议题的执行反馈' : 'View execution feedback from this issue', exact: true, + }).click(); + await page.waitForURL(url => url.hash === `#feedback-${feedbackId}`); + const feedback = page.locator(`#feedback-${feedbackId}`); + await feedback.getByText(savedText, { exact: true }).waitFor(); + const feedbackSource = feedback.locator('[data-feedback-issue-source]'); + assert.ok((await feedbackSource.locator('summary').innerText()).includes(resolved.title)); + await openDetails(feedbackSource); + await feedbackSource.getByText(resolution.text, { exact: true }).waitFor(); + assert.equal(await feedbackSource.locator('a').getAttribute('href'), `#issue-${resolved.id}`); + assert.ok((await feedbackSource.locator('code').innerText()).includes(target.taskRef.version)); + await feedback.screenshot({ path: path.join(output, `historical-execution-feedback-${language}-${width}.png`) }); + checks.push({ id: 'historical-execution-is-read-only', language, width, feedbackId, restoredDraft: true, savedResolutionVisible: true }); phase=`issue-contribution-late-success-${language}`; const late=await createIssue('Control: later contribution keeps its explicit reply target'); - let thread=(await http<{item:any}>(peer,'POST',`${projectPath}/issues/${late.id}/replies`,{requestId:crypto.randomUUID(),expectedRevision:late.revision,kind:'proposal',text:'Proposal A: use a constructor.'})).item; - thread=(await http<{item:any}>(peer,'POST',`${projectPath}/issues/${late.id}/replies`,{requestId:crypto.randomUUID(),expectedRevision:thread.revision,kind:'proposal',text:'Proposal B: use the elimination rule.'})).item; + let thread=(await http<{item:ResearchIssue}>(peer,'POST',`${projectPath}/issues/${late.id}/replies`,{requestId:crypto.randomUUID(),expectedRevision:late.revision,kind:'proposal',text:'Proposal A: use a constructor.'})).item; + thread=(await http<{item:ResearchIssue}>(peer,'POST',`${projectPath}/issues/${late.id}/replies`,{requestId:crypto.randomUUID(),expectedRevision:thread.revision,kind:'proposal',text:'Proposal B: use the elimination rule.'})).item; card=await openIssue(page,late.id);await openDetails(card.locator(':scope>details').last());const input=card.locator('textarea[id^="issue-input-"]'); await card.locator('.collaboration-replies>li').first().getByRole('button',{name:language==='zh'?'回复此条':'Reply',exact:true}).click();await input.fill('First reply sent to proposal A.'); const replyPath=`${projectPath}/issues/${late.id}/replies`;let release!:()=>void;const gate=new Promise(resolve=>release=resolve);releases.push(release); @@ -204,10 +209,11 @@ try { if(language==='zh'){await service.close();service=makeService();await new Promise((resolve,reject)=>{service.server.once('error',reject);service.server.listen(port,'127.0.0.1',resolve);});} } assert.deepEqual(errors,[]);assert.deepEqual(external,[]);assert.equal(prohibited,0); + assert.deepEqual(executionWrites, []);assert.deepEqual(commands, []); }catch(cause){failure=cause;if(active&&!active.isClosed())await active.screenshot({path:path.join(output,'probe-failure.png'),fullPage:true}).catch(()=>{});} finally{ releases.forEach(release=>release()); - await fs.writeFile(path.join(output,'report.json'),JSON.stringify({status:failure?'failed':'passed',at:new Date().toISOString(),...provenance,phase,findings,checks,dialogs,commands,controlledCheckCalls:compileCalls,realModels:0,realLean:0,externalMail:prohibited,errors,external,...(failure?{error:failure instanceof Error?failure.stack:String(failure)}:{})},null,2)); + await fs.writeFile(path.join(output,'report.json'),JSON.stringify({status:failure?'failed':'passed',at:new Date().toISOString(),...provenance,phase,findings,checks,dialogs,commands,executionWrites,controlledCheckCalls:compileCalls,realModels:0,realLean:0,externalMail:prohibited,errors,external,...(failure?{error:failure instanceof Error?failure.stack:String(failure)}:{})},null,2)); await browser.close();await service.close();await fs.rm(dataRoot,{recursive:true,force:true});await fs.writeFile(path.join(output,'cleanup.json'),JSON.stringify({browserClosed:true,serviceClosed:true,disposableDataRemoved:true})); } if(failure)throw failure;console.log(`Passed ${checks.length} collaboration action continuity workflows`); diff --git a/scripts/test-web-problem-drafts.ts b/scripts/test-web-problem-drafts.ts index a7a8fd2b..8925f7bf 100644 --- a/scripts/test-web-problem-drafts.ts +++ b/scripts/test-web-problem-drafts.ts @@ -169,14 +169,14 @@ try { await page.locator('#composer-settings').click(); await page.locator('#model').fill('lean-draft-model'); await page.locator('[data-settings-section="settings-execution"]').click(); await page.locator('#max-turns').fill('7'); await page.locator('#max-seconds').fill('600'); - await page.locator('#research-mode').selectOption('native-team'); + assert.match(await page.locator('#current-research-mode').innerText(), /Codex 原生团队/u); await page.locator('#native-team-capacity').selectOption('5'); await closeSettings(page); const lean = await save(page, 'Lean 待完成版本'); assert.equal(lean.version.value.mode, 'lean'); await chooseVersion(other, lean); await other.locator('body[data-entry=lean]').waitFor({ state: 'attached' }); assert.equal(await other.locator('#source').inputValue(), leanSource); assert.equal(await other.locator('#task').inputValue(), '保留这一份未完成证明与预算。'); assert.equal(await other.locator('#model').inputValue(), 'lean-draft-model'); assert.equal(await other.locator('#max-turns').inputValue(), '7'); assert.equal(await other.locator('#max-seconds').inputValue(), '600'); - assert.equal(await other.locator('#research-mode').inputValue(), 'native-team'); + assert.match(await other.locator('#current-research-mode').textContent() ?? '', /Native Codex team/u); assert.equal(await other.locator('#native-team-capacity').inputValue(), '5'); assert.equal(await other.locator('#api-key').inputValue(), ''); await other.goto(`${origin}/?accountDraft=${lean.draft.id}&draftVersion=${lean.version.id}`); diff --git a/scripts/test-web-problem-lifecycle.ts b/scripts/test-web-problem-lifecycle.ts index 4c9716de..a9cd22e8 100644 --- a/scripts/test-web-problem-lifecycle.ts +++ b/scripts/test-web-problem-lifecycle.ts @@ -76,9 +76,12 @@ try{ await page.unroute(unknownPattern);await page.locator('#formalize-start:enabled').click();await page.waitForURL(url=>url.searchParams.has('chat')); await waitSubmitted(page,first.draft.id,undefined,first.version.id); const all=await list(page),submitted=all.find(x=>x.id===first.draft.id)!.versions.find(x=>x.id===first.version.id)!;assert.ok(submitted.submission?.href);assert.equal(all.find(x=>x.id===second.draft.id)!.versions[0].status??'open','open'); - const another=await context(language,width);await another.addCookies(await current.cookies(origin));const other=await another.newPage();active=other;await other.goto(`${origin}/workspace.html?tab=drafts`);await other.locator('[data-personal-show-archived-drafts]').check();const archived=other.locator(`[data-personal-draft="${first.draft.id}"]`);await archived.waitFor();await archived.locator(':scope > summary').click();await archived.locator('[data-draft-status=submitted] a').waitFor();assert.equal(await archived.locator('[data-draft-status=submitted] a').getAttribute('href'),submitted.submission!.href); + const another=await context(language,width);await another.addCookies(await current.cookies(origin));const other=await another.newPage();active=other;await other.goto(`${origin}/workspace.html?tab=drafts`);await other.locator('[data-personal-show-archived-drafts]').check();const archived=other.locator(`[data-personal-draft="${first.draft.id}"]`);await archived.waitFor();await archived.locator(':scope > summary').click(); + const submittedVersion = archived.locator('article').filter({ has: archived.locator(`a[href*="draftVersion=${first.version.id}"]`) }); + const submittedLink = submittedVersion.locator('[data-draft-status=submitted] a'); + await submittedLink.waitFor(); assert.equal(await submittedLink.getAttribute('href'), submitted.submission!.href); await other.screenshot({path:path.join(output,`${language}-${width}-submitted-on-another-device.png`),fullPage:true});assert.ok(await other.evaluate(()=>Math.max(document.body.scrollWidth,document.documentElement.scrollWidth)<=innerWidth+1)); - await archived.locator('[data-draft-status=submitted] a').click();await other.waitForURL(url=>url.searchParams.has('chat')||url.searchParams.has('formalization')||url.searchParams.has('run')||url.pathname.endsWith('/formalize.html')&&url.searchParams.has('id')); + await submittedLink.click();await other.waitForURL(url=>url.searchParams.has('chat')||url.searchParams.has('formalization')||url.searchParams.has('run')||url.pathname.endsWith('/formalize.html')&&url.searchParams.has('id')); phase=`restore-submitted-${language}`;active=page; await page.goto(`${origin}/?accountDraft=${first.draft.id}&draftVersion=${first.version.id}`);await page.locator('#formalize-original').waitFor();await restore(page,first); await page.waitForFunction(text=>(document.querySelector('#formalize-original') as HTMLTextAreaElement)?.value===text,webFormalizationStatement); diff --git a/scripts/test-web-research-decisions-followthrough.ts b/scripts/test-web-research-decisions-followthrough.ts index b9d588d7..466c24cb 100644 --- a/scripts/test-web-research-decisions-followthrough.ts +++ b/scripts/test-web-research-decisions-followthrough.ts @@ -7,6 +7,7 @@ import path from 'node:path'; import type { Page } from 'playwright'; import { createWebService } from '../apps/web/server'; import { readWebConfig } from '../apps/web/config'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; import type { WebRunner } from '../apps/web/runner'; import type { WebObservation } from '../apps/web/collaboration'; import type { ResearchFeedback } from '../apps/web/researchProjectTypes'; @@ -31,6 +32,11 @@ const runner: WebRunner = { observation.plan!.baseVersion = 'decision-plan-1'; observation.guidance = []; observation.inspection.edits = []; observation.inspection.planApproval = input.input.model === 'fixture-approval' ? { required: true, status: 'pending', planVersion: 'decision-plan-1', rejections: [], leadRevising: false } : undefined; + if (input.input.nativeTeamCapacity) Object.assign(observation.inspection.configuration, { + workers: 1, coordination: 'independent', researchMode: 'skill', + researchSkill: { name: 'theoremos-research', digest: mathDigest('fixture skill'), loading: 'native' }, + researchDelegation: { mode: 'team', maxAgents: input.input.nativeTeamCapacity }, + }); for (const check of observation.checks) check.record = { passed: true }; originals.set(input.id, structuredClone(observation)); send({ type: 'observation', observation: structuredClone(observation) }); if (input.input.model === 'fixture-history') { @@ -79,7 +85,8 @@ try { service.research.projects.saveProfile(owner, { requestId: 'owner-profile', expectedRevision: 0, displayName: 'Project Owner', visibility: 'public' }); service.research.projects.saveProfile(peerOwner, { requestId: 'private-peer-profile', expectedRevision: 0, displayName: 'Private Teammate', visibility: 'private', bio: 'PRIVATE_PROFILE_BIO' }); const create = (model: string) => service.jobs.create(owner, { providerId: provider.id, apiKey: 'sk-disposable-not-sent', model, effort: 'high', source, - task: 'Trace the saved mathematical route', environment: 'standard', maxTurns: 2, maxRunSeconds: 600, workers: 1, coordination: 'cooperative' }, provider); + task: 'Trace the saved mathematical route', environment: 'standard', maxTurns: 2, maxRunSeconds: 600, ...(model === 'fixture-approval' ? { ...webAgentTeamPreset(), planApproval: true } + : { workers: 1, coordination: 'cooperative' }) }, provider); const history = create('fixture-history'); await page.waitForFunction(async id => (await (await fetch(`/api/runs/${id}`)).json()).run.status === 'completed', history.id); let project = service.research.projects.create(owner, { requestId: 'project', title: 'Decision continuity', visibility: 'members' }); project = service.research.projects.setMember(owner, project.id, peerId, { requestId: 'private-peer', expectedRevision: project.revision, role: 'collaborator' }); diff --git a/scripts/test-web-research-decisions-lifecycle.ts b/scripts/test-web-research-decisions-lifecycle.ts index c528ec8f..c13a3625 100644 --- a/scripts/test-web-research-decisions-lifecycle.ts +++ b/scripts/test-web-research-decisions-lifecycle.ts @@ -91,53 +91,16 @@ try { const run = await seedCooperativeRun(service, page.context(), origin, { providerId: 'openai', apiKey: 'sk-disposable-audit-fixture', model: 'fixture', effort: 'low', environment: 'standard', source, task: 'Prove True', maxTurns: 2, maxRunSeconds: 600, workers: 2, coordination: 'cooperative' }); await waitForRun({page},run.id,item=>Boolean(item.observation)); - phase = `personal-guidance-unknown-${language}-${width}`; - const route = `${origin}/problem.html?run=${run.id}&tab=route`; - const sent: any[] = []; - page.on('request', request => { if (request.method() === 'POST' && new URL(request.url()).pathname === `/api/runs/${run.id}/guidance`) sent.push(request.postDataJSON()); }); - await page.goto(route); await page.locator('[data-inline-open]').click(); - const note = language === 'zh' ? '请先核对归纳基,再按 n 到 n+1 的顺序处理归纳步。' : 'Check the induction base before deriving the step from n to n+1.'; - await page.locator('[data-inline-guidance] > summary').click(); - const guide = page.locator('[data-inline-guidance]'); - await guide.getByLabel(language === 'zh' ? '希望怎样改进这一步或路线' : 'How should this step or route improve?', { exact: true }).fill(note); - await guide.locator('[data-inline-confirm-guidance]').check(); await guide.locator('[data-inline-send-guidance]').click(); - await guide.locator('[data-inline-command-status="unknown"]').waitFor(); - const original = structuredClone(sent[0]); - await page.reload(); await page.locator('[data-inline-open]').click(); await guide.locator('[data-inline-pending-guidance]').waitFor(); - assert.equal(await guide.getByLabel(language === 'zh' ? '希望怎样改进这一步或路线' : 'How should this step or route improve?', { exact: true }).inputValue(), note); - assert.equal(sent.length, 1); assert.equal(await guide.locator('[data-inline-send-guidance]').isDisabled(), true); - await guide.locator('[data-inline-retry-command]').click(); await settled(page); assert.equal(sent.length, 1); - // Receipt absent on the server: only an explicit retry may POST the original command. - let missing = true, resolved = false, hold = false, release: (() => void) | undefined; - await page.route(`**/api/runs/${run.id}/commands/${original.id}`, async route => { - if (hold) await new Promise(resolve => { release = resolve; }); - if (resolved) await route.fulfill({ json: { receipt: { id: original.id, status: 'delivered' } } }); - else if (missing) await route.fulfill({ status: 404, json: { error: 'Fixture receipt absent' } }); - else await route.continue(); - }); - await page.reload(); await page.locator('[data-inline-open]').click(); await guide.locator('[data-inline-pending-guidance]').waitFor(); - await settled(page); assert.equal(sent.length, 1); - await guide.locator('[data-inline-retry-command]').click(); await page.waitForFunction(() => !document.querySelector('[data-inline-retry-command]')?.disabled); - assert.equal(sent.length, 2); assert.deepEqual(sent[1], original); - const revised = note + ' NEW UNSUBMITTED DETAIL'; - await guide.getByLabel(language === 'zh' ? '希望怎样改进这一步或路线' : 'How should this step or route improve?', { exact: true }).fill(revised); - controls.get(run.id)!.observation.inspection.planVersion = 'plan-v2'; controls.get(run.id)!.observation.sequence++; controls.get(run.id)!.emit(); - await waitForRun({page},run.id,item=>item.observation?.inspection.planVersion==='plan-v2'); - await page.reload(); await page.locator('[data-inline-open]').click(); await guide.locator('[data-inline-pending-guidance]').waitFor(); await settled(page); - assert.equal(await guide.locator('[data-inline-retry-command]').count(), 0); assert.equal(sent.length, 2); - assert.equal(await guide.getByLabel(language === 'zh' ? '希望怎样改进这一步或路线' : 'How should this step or route improve?', { exact: true }).inputValue(), revised); - await page.locator('[data-inline-drawer]').screenshot({path:path.join(output, `guidance-changed-target-${language}-${width}.png`)}); - missing = false; resolved = true; hold = true; - await guide.locator('[data-inline-query-command]').click(); - for(let i=0;i<50&&!release;i++)await page.waitForTimeout(20); - const newer = revised + ' WHILE WAITING'; - await guide.getByLabel(language === 'zh' ? '希望怎样改进这一步或路线' : 'How should this step or route improve?', { exact: true }).fill(newer); - assert.ok(release); release!(); hold = false; - await guide.locator('[data-inline-command-status="delivered"]').waitFor(); - assert.equal(await guide.getByLabel(language === 'zh' ? '希望怎样改进这一步或路线' : 'How should this step or route improve?', { exact: true }).inputValue(), newer); - await page.reload(); await page.locator('[data-inline-open]').click(); await guide.waitFor(); await settled(page); - assert.equal(await guide.locator('[data-inline-pending-guidance]').count(), 0); assert.equal(sent.length, 2); - checks.push({id:'guidance-original-id-refresh-retry-version-change-late-result',language,width,requestIds:sent.map(x=>x.id),preservedDraft:newer}); + phase = `historical-guidance-cannot-dispatch-${language}-${width}`; + await page.goto(`${origin}/problem.html?run=${run.id}&tab=route`); + await page.locator('[data-inline-open]').click(); + await page.locator('[data-inline-drawer][open]').waitFor(); + assert.equal(await page.locator('[data-inline-guidance]').count(), 0); + await assert.rejects(http(page, 'POST', `/api/runs/${run.id}/guidance`, { + id: 'retired-guidance', text: 'Check the induction base.', recipient: { kind: 'lead' }, + }), /409/); + assert.deepEqual(commands, []); + checks.push({id:'historical-guidance-cannot-dispatch',language,width}); phase = `solo-candidate-review-${language}-${width}`; let project = (await http<{item:ResearchProjectDetail}>(page,'POST','/api/research/theorems',{requestId:crypto.randomUUID(),title:'Solo reviewed candidate',visibility:'members',candidateDeliveryPolicy:'reviewed'})).item; diff --git a/scripts/test-web-research-draft-lifecycle.ts b/scripts/test-web-research-draft-lifecycle.ts index 5d72fe81..b58e49b0 100644 --- a/scripts/test-web-research-draft-lifecycle.ts +++ b/scripts/test-web-research-draft-lifecycle.ts @@ -32,11 +32,7 @@ const runner: WebRunner = { async readiness() { return { ready: true, message: ' send({ type: 'observation', observation }); await new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true })); }, async check() { prohibited++; throw new Error('No Lean calls in input draft verification'); }, async formalize() { prohibited++; throw new Error('No model calls in input draft verification'); }, - async command(_id, command) { - if (command.type !== 'guidance' || command.guidance.candidate) { prohibited++; throw new Error('Only controlled guidance records are allowed'); } - const at = new Date().toISOString(), guidance = { ...command.guidance, status: 'queued' as const, createdAt: at, updatedAt: at }; - return { id: guidance.id, status: 'queued', guidance }; - }, + async command() { prohibited++; throw new Error('No solver commands in input draft verification'); }, }; const service = createWebService(config, runner, { sample: null, mailer: async () => { prohibited++; throw new Error('No mail in this fixture'); } }); const owner = `account:${accounts[0].id}`, reviewerOwner = `account:${accounts[1].id}`, provider = config.providers[0]; @@ -77,33 +73,41 @@ try { const alicePage = await actor(0, width, language), reviewerPage = await actor(1, width, language); active = alicePage; const problemHref = (task = firstTask, extra: Record = {}) => `${origin}/problem.html?${new URLSearchParams({ project: project.id, run: run.id, tab: 'route', task: task.id, taskVersion: task.version, ...extra })}`; const openDrawer = async (page: Page) => { const drawer = page.locator('[data-inline-drawer]'); await page.locator('[data-inline-open]').waitFor(); if (!(await drawer.evaluate(element => (element as HTMLDialogElement).open))) await page.locator('[data-inline-open]').click(); return drawer; }; - const guidanceText = 'Retain the cancellation reasoning before trying induction.'; - phase = `${width}-${language}-guidance-preservation-and-completion`; - await alicePage.goto(problemHref()); let drawer = await openDrawer(alicePage), guidance = drawer.locator('[data-inline-guidance]'); await openDetails(guidance); - await guidance.locator('textarea').fill(guidanceText); await drawer.locator('[data-inline-close]').click(); await openDrawer(alicePage); - assert.equal(await guidance.locator('textarea').inputValue(), guidanceText); - await alicePage.goto(problemHref(secondTask)); await openDrawer(alicePage); const otherGuidance = alicePage.locator('[data-inline-guidance]'); await openDetails(otherGuidance); - assert.equal(await otherGuidance.locator('textarea').inputValue(), ''); - await alicePage.goto(problemHref()); await openDrawer(alicePage); guidance = alicePage.locator('[data-inline-guidance]'); - assert.equal(await guidance.locator('textarea').inputValue(), guidanceText); await saveAccount(guidance); + phase = `${width}-${language}-annotation-and-thread-reply`; + const annotationText = 'Explain how the displayed premise gives this result.'; + const newerText = 'Add the derivation after checking the intermediate expression.'; + await alicePage.goto(problemHref()); const drawer = await openDrawer(alicePage); + const annotations = alicePage.locator('[data-research-annotations]'); + const annotationForm = () => annotations.locator('form').filter({ has: alicePage.locator('[data-save-annotation]') }); + const annotationInput = () => annotationForm().getByRole('textbox').last(); + await openDetails(annotations.locator(':scope>details').last()); + await annotations.locator('[data-annotation-whole-field]').click(); + await annotationInput().fill(annotationText); + await drawer.locator('[data-inline-close]').click(); await openDrawer(alicePage); + assert.equal(await annotationInput().inputValue(), annotationText); + await alicePage.goto(problemHref(secondTask)); await openDrawer(alicePage); + await openDetails(annotations.locator(':scope>details').last()); + assert.equal(await annotationInput().inputValue(), ''); + await alicePage.goto(problemHref()); await openDrawer(alicePage); + assert.equal(await annotationInput().inputValue(), annotationText); + await annotations.locator('[data-annotation-selection]').waitFor(); + await saveAccount(annotations); + + const annotationRoute = `**/api/research/theorems/${project.id}/runs/${run.id}/annotations*`; let release: (() => void) | undefined; - await alicePage.route(`**/api/research/theorems/${project.id}/feedback`, async route => { - if (route.request().method() !== 'POST' || route.request().postDataJSON().kind !== 'guidance') return route.continue(); - const response = await route.fetch(); await new Promise(resolve => { release = resolve; }); await route.fulfill({ response }); + await alicePage.route(annotationRoute, async route => { + if (route.request().method() !== 'POST') return route.continue(); + const response = await route.fetch(); + await new Promise(resolve => { release = resolve; }); + await route.fulfill({ response }); }); - await guidance.locator('[data-inline-confirm-guidance]').check(); await guidance.locator('[data-inline-send-guidance]').click(); - await guidance.locator('textarea').fill('New reasoning entered while the first submission finishes.'); - for (let attempt = 0; attempt < 100 && !release; attempt++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(release); release(); - await archived(alicePage, 'guidance', project.id); assert.equal(await guidance.locator('textarea').inputValue(), 'New reasoning entered while the first submission finishes.'); - await alicePage.unroute(`**/api/research/theorems/${project.id}/feedback`); - checks.push({ phase, drawerRetainsText: true, tasksIsolated: true, newerTextRetained: true, cloudArchived: true }); - - phase = `${width}-${language}-annotation-and-thread-reply`; - let annotations = alicePage.locator('[data-research-annotations]'); await openDetails(annotations.locator(':scope>details').last()); - await annotations.locator('[data-annotation-whole-field]').click(); await annotations.locator('form').last().getByRole('textbox').last().fill('Explain how the displayed premise gives this result.'); - await alicePage.reload(); await openDrawer(alicePage); annotations = alicePage.locator('[data-research-annotations]'); - assert.equal(await annotations.locator('form').last().getByRole('textbox').last().inputValue(), 'Explain how the displayed premise gives this result.'); - await annotations.locator('[data-annotation-selection]').waitFor(); await saveAccount(annotations); await annotations.locator('[data-save-annotation]').click(); await archived(alicePage, 'annotation', project.id); + await annotations.locator('[data-save-annotation]').click(); + await annotationInput().fill(newerText); + for (let attempt = 0; attempt < 100 && !release; attempt++) await new Promise(resolve => setTimeout(resolve, 20)); + assert.ok(release); release(); + await archived(alicePage, 'annotation', project.id); + assert.equal(await annotationInput().inputValue(), newerText); + await alicePage.unroute(annotationRoute); const thread = annotations.locator('[data-annotation-thread]').first(); await thread.waitFor(); const annotationId = (await thread.getAttribute('data-annotation-thread'))!; await thread.getByRole('textbox').fill('Use the original equality to rewrite the target.'); await alicePage.reload(); await openDrawer(alicePage); const restoredThread = alicePage.locator(`[data-annotation-thread="${annotationId}"]`); assert.equal(await restoredThread.getByRole('textbox').inputValue(), 'Use the original equality to rewrite the target.'); @@ -134,13 +138,15 @@ try { phase = `${width}-${language}-archive-management-and-restore`; await alicePage.goto(`${origin}/workspace.html?tab=drafts`); const panel = alicePage.locator('[data-personal-drafts-panel]'); await panel.locator('[data-personal-show-archived-drafts]').check(); - const savedGuidance = await alicePage.evaluate(async projectId => (await (await fetch(`/api/research/personal/drafts?${new URLSearchParams({ kind: 'guidance', projectId, status: 'archived' })}`)).json()).items[0], project.id); - const row = panel.locator(`[data-personal-draft="${savedGuidance.id}"]`); await openDetails(row); + const savedAnnotation = await alicePage.evaluate(async projectId => (await (await fetch(`/api/research/personal/drafts?${new URLSearchParams({ kind: 'annotation', projectId, status: 'archived' })}`)).json()).items[0], project.id); + const row = panel.locator(`[data-personal-draft="${savedAnnotation.id}"]`); await openDetails(row); const restoreHref = (await row.getByRole('link').filter({ hasText: /回到编辑器恢复|Open the editor to restore/u }).first().getAttribute('href'))!; assert.ok(restoreHref.startsWith('problem.html?')); await alicePage.goto(`${origin}/${restoreHref}`); - const requested = alicePage.locator(`[data-account-draft-version="${savedGuidance.versions[0].id}"]`); await requested.locator('[data-restore-account-draft]').click(); - await alicePage.waitForFunction(text => [...document.querySelectorAll('[data-inline-guidance] textarea')].some(input => input.value === text), guidanceText); - assert.ok(await alicePage.evaluate(() => Object.keys(localStorage).some(key => key.startsWith('theoremos:human-draft') && (localStorage.getItem(key) ?? '').includes('New reasoning entered while')))); + const requested = alicePage.locator(`[data-account-draft-version="${savedAnnotation.versions[0].id}"]`); await requested.locator('[data-restore-account-draft]').click(); + await alicePage.waitForFunction(text => Array.from(document.querySelectorAll('[data-research-annotations] textarea')) + .some(input => input.value === text), annotationText); + assert.equal(await annotationInput().inputValue(), annotationText); + assert.ok(await alicePage.evaluate(text => Object.keys(localStorage).some(key => key.startsWith('theoremos:human-draft') && (localStorage.getItem(key) ?? '').includes(text)), newerText)); assert.ok(await alicePage.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)); await alicePage.screenshot({ path: path.join(output, `drafts-${language}-${width}.png`), fullPage: true }); checks.push({ phase, archivedRestorable: true, localAlternativePreserved: true, fitsViewport: true }); diff --git a/scripts/test-web-research-library-trials.ts b/scripts/test-web-research-library-trials.ts index 6cc3998c..9db650bf 100644 --- a/scripts/test-web-research-library-trials.ts +++ b/scripts/test-web-research-library-trials.ts @@ -258,7 +258,12 @@ try { await frozenEvidence.getByText('namespace Shared', { exact: false }).waitFor(); assert.equal(await peer.evaluate(async id => (await fetch(`/api/research/library-trials/${id}`)).status, new URL(libraryReturn).searchParams.get('trial')), 404, 'A project member reviews the shared snapshot without access to the author’s private trial'); - await peerFeedback.locator('[data-candidate-approve]').click(); await peerFeedback.locator('[data-candidate-delivery-status="approved"]').waitFor(); + const decision = peerFeedback.locator('[data-feedback-decision]'); + await decision.locator('summary').click(); + await decision.locator('[data-decision-status]').selectOption('accepted'); + await decision.getByLabel(language === 'zh' ? '理由' : 'Reason', { exact: true }).fill('The reviewed trial supports a new attempt with this fixed library.'); + await decision.locator('[data-save-decision]').click(); + await peerFeedback.locator('[data-candidate-delivery-status="approved"]').waitFor(); assert.equal(commandCalls, beforeCommands, 'Human approval for a new attempt never dispatches to the completed run'); await page.reload(); await ownerFeedback.locator('[data-prepare-library-attempt]').waitFor(); const workersAtPreparation = workerCalls; diff --git a/tests/researchIssueExecutionDraft.test.ts b/tests/researchIssueExecutionDraft.test.ts index 5b631fbb..5d5c4eba 100644 --- a/tests/researchIssueExecutionDraft.test.ts +++ b/tests/researchIssueExecutionDraft.test.ts @@ -1,81 +1,27 @@ import { describe, expect, it } from 'vitest'; -import type { WebObservation } from '../apps/web/collaboration'; -import type { ResearchIssue } from '../apps/web/researchCollaborationTypes'; -import type { ResearchFeedback } from '../apps/web/researchProjectTypes'; -import { issueExecutionAttemptFromFeedback, issueExecutionCanRetry, issueExecutionContextMatches, issueExecutionKey, - readIssueExecutionAttempt, readIssueExecutionDraft, removeIssueExecutionAttempt, removeIssueExecutionDraft, - saveIssueExecutionAttempt, saveIssueExecutionDraft, type IssueExecutionAttempt, type IssueExecutionDraft } from '../apps/web/client/researchIssueExecutionDraft'; +import { readIssueExecutionNotes } from '../apps/web/client/researchIssueExecutionDraft'; import { completeIssueReply, type IssueReplyDraft } from '../apps/web/client/researchIssueReplyDraft'; -const scope = { owner: 'alice', projectId: 'project', issueId: 'issue' }; -const target = { runId: 'run', statementVersionId: 'statement', observationRef: { sequence: 2, stateDigest: 'saved-state' }, taskRef: { id: 'goal', version: 'v1' } }; -const draft = (): IssueExecutionDraft => ({ mode: 'plan-edit', runId: 'run', taskId: 'goal', text: 'Explain and construct the witness.', - objective: 'Show why this witness solves the target.', dependencies: 'lemma-a, lemma-b', editedTask: 'goal', - context: { issueRevision: 4, resolutionAt: 'resolved-at', target, planVersion: 'plan-v1' } }); -const attempt = (): IssueExecutionAttempt => ({ input: { requestId: 'original-request', kind: 'guidance', text: 'Use this witness exactly once.', - recipient: { kind: 'task', id: 'goal' }, target, visibility: 'members', issueSource: { issueId: 'issue', issueRevision: 4, resolutionAt: 'resolved-at' } }, draft: draft() }); -const issue = { id: 'issue', revision: 4, status: 'resolved', resolution: { createdAt: 'resolved-at' } } as ResearchIssue; -const observation = { webRunId: 'run', inspection: { planVersion: 'plan-v1', tasks: [{ id: 'goal', version: 'v1' }] } } as WebObservation; -function fixture() { - const values = new Map(); - return { values, storage: { getItem: (key: string) => values.get(key) ?? null, - setItem: (key: string, value: string) => { values.set(key, value); }, removeItem: (key: string) => { values.delete(key); } } }; -} +describe('historical issue drafts', () => { + const scope = { owner: 'alice', projectId: 'project', issueId: 'issue' }; + const key = (kind: string) => 'theoremos:issue-execution-' + kind + ':v1:' + encodeURIComponent(JSON.stringify(['alice', 'project', 'issue'])); -describe('issue action editing and original request recovery', () => { - it('restores the complete editing draft and fixed context while isolating owner, project and issue', () => { - const { storage } = fixture(), value = draft(); saveIssueExecutionDraft(storage, scope, value); - expect(readIssueExecutionDraft(storage, scope)).toEqual(value); - for (const other of [{ ...scope, owner: 'bob' }, { ...scope, projectId: 'another' }, { ...scope, issueId: 'another' }]) - expect(readIssueExecutionDraft(storage, other)).toBeUndefined(); - expect(issueExecutionContextMatches(value.context!, { ...value.context!, target: { ...target, observationRef: { sequence: 3, stateDigest: 'new-observation' } } })).toBe(true); - for (const changed of [{ ...value.context!, issueRevision: 5 }, { ...value.context!, planVersion: 'plan-v2' }, - { ...value.context!, target: { ...target, taskRef: { id: 'goal', version: 'v2' } } }, { ...value.context!, target: { ...target, statementVersionId: 'different' } }]) - expect(issueExecutionContextMatches(value.context!, changed)).toBe(false); - expect(readIssueExecutionDraft(storage, scope)?.context?.target.taskRef?.version).toBe('v1'); + it('reads the local draft and original submission within their account and issue', () => { + const records = new Map([ + [key('draft'), JSON.stringify({ text: 'Updated instructions', objective: 'Show the witness', dependencies: 'lemma-a' })], + [key('pending'), JSON.stringify({ input: { text: 'Original instructions', issueSource: { issueId: 'issue' } }, draft: { objective: 'Show the witness' } })], + ]); + const storage = { getItem: (name: string) => records.get(name) ?? null }; + expect(readIssueExecutionNotes(storage, scope)).toEqual(['Updated instructions', 'Show the witness', 'lemma-a', 'Original instructions']); + expect(readIssueExecutionNotes(storage, { ...scope, owner: 'bob' })).toEqual([]); + expect(readIssueExecutionNotes(storage, { ...scope, issueId: 'another' })).toEqual([]); }); - it('retains original command identity separately from later human editing', () => { - const { storage } = fixture(), original = attempt(); saveIssueExecutionAttempt(storage, scope, original); - const newer = { ...draft(), text: 'New argument typed while delivery is pending.' }; saveIssueExecutionDraft(storage, scope, newer); - expect(readIssueExecutionAttempt(storage, scope)).toEqual(original); - expect(readIssueExecutionAttempt(storage, { ...scope, owner: 'bob' })).toBeUndefined(); - removeIssueExecutionDraft(storage, scope, original.draft!); - expect(readIssueExecutionDraft(storage, scope)).toEqual(newer); - removeIssueExecutionAttempt(storage, scope, original.input.requestId); - expect(readIssueExecutionAttempt(storage, scope)).toBeUndefined(); - expect(readIssueExecutionDraft(storage, scope)).toEqual(newer); - }); - it('does not let a delayed receipt delete a newer pending request or draft', () => { - const { storage } = fixture(), original = attempt(), next = { ...attempt(), input: { ...attempt().input, requestId: 'next-request' } }; - saveIssueExecutionAttempt(storage, scope, next); removeIssueExecutionAttempt(storage, scope, original.input.requestId); - expect(readIssueExecutionAttempt(storage, scope)?.input.requestId).toBe('next-request'); - saveIssueExecutionDraft(storage, scope, draft()); removeIssueExecutionDraft(storage, scope, draft()); - expect(readIssueExecutionDraft(storage, scope)).toBeUndefined(); - }); - it('allows retry only against the same active resolution, run, task and plan', () => { - expect(issueExecutionCanRetry(attempt(), issue, observation, true)).toBe(true); - expect(issueExecutionCanRetry(attempt(), issue, observation, false)).toBe(false); - expect(issueExecutionCanRetry(attempt(), { ...issue, revision: 5 }, observation, true)).toBe(false); - expect(issueExecutionCanRetry(attempt(), { ...issue, status: 'open' }, observation, true)).toBe(false); - expect(issueExecutionCanRetry(attempt(), issue, { ...observation, webRunId: 'another' }, true)).toBe(false); - expect(issueExecutionCanRetry(attempt(), issue, { ...observation, inspection: { ...observation.inspection, tasks: [{ id: 'goal', version: 'v2' }] } } as WebObservation, true)).toBe(false); - const plan: IssueExecutionAttempt = { input: { ...attempt().input, kind: 'plan-edit', proposal: { schema: 'deepscientist.math.plan-edit.v1', baseVersion: 'plan-v1', tasks: [] } } }; - expect(issueExecutionCanRetry(plan, issue, observation, true)).toBe(true); - expect(issueExecutionCanRetry(plan, issue, { ...observation, inspection: { ...observation.inspection, planVersion: 'plan-v2' } }, true)).toBe(false); - }); - it('recovers a legacy unknown server record using the exact original input and no projection-only fields', () => { - const original = attempt().input; - const record = { ...original, id: 'feedback', requestId: original.requestId, delivery: { status: 'unknown' }, payload: { recipient: { kind: 'task', id: 'goal' } }, - issueSource: { ...original.issueSource, title: 'Issue title', resolution: { text: 'Resolution' } } } as ResearchFeedback; - expect(issueExecutionAttemptFromFeedback(record)).toEqual({ input: original }); - expect(issueExecutionAttemptFromFeedback({ ...record, delivery: { status: 'delivered' } })).toBeUndefined(); - }); - it('surfaces unavailable or damaged storage instead of treating an unconfirmed action as absent', () => { - const { storage, values } = fixture(); values.set(issueExecutionKey(scope, 'pending'), '{broken'); expect(() => readIssueExecutionAttempt(storage, scope)).toThrow(); - values.set(issueExecutionKey(scope, 'pending'), JSON.stringify({ ...attempt(), input: { ...attempt().input, issueSource: { ...attempt().input.issueSource, issueId: 'another' } } })); - expect(() => readIssueExecutionAttempt(storage, scope)).toThrow('Invalid saved issue execution identity'); - values.set(issueExecutionKey(scope, 'draft'), JSON.stringify({ ...draft(), runId: 'different-run' })); expect(() => readIssueExecutionDraft(storage, scope)).toThrow(); - expect(() => saveIssueExecutionAttempt({ ...storage, setItem() { throw new Error('unavailable'); } }, scope, attempt())).toThrow('unavailable'); + + it('still reads a valid draft if the original attempt refers to a different issue', () => { + const draft = JSON.stringify({ text: 'Keep this draft' }); + const pending = JSON.stringify({ input: { text: 'Other issue', issueSource: { issueId: 'other' } } }); + const storage = { getItem: (name: string) => name === key('draft') ? draft : pending }; + expect(readIssueExecutionNotes(storage, scope)).toEqual(['Keep this draft']); }); }); From cc63eb9746494b5cd20dac4bfdc7a30f8f2228e0 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Sat, 28 Nov 2026 01:52:01 +0800 Subject: [PATCH 5/7] Verify native plan approval in research continuity fixtures --- scripts/test-web-problem-lifecycle.ts | 2 +- scripts/test-web-research-run-continuity.ts | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/scripts/test-web-problem-lifecycle.ts b/scripts/test-web-problem-lifecycle.ts index a9cd22e8..24925858 100644 --- a/scripts/test-web-problem-lifecycle.ts +++ b/scripts/test-web-problem-lifecycle.ts @@ -77,7 +77,7 @@ try{ await waitSubmitted(page,first.draft.id,undefined,first.version.id); const all=await list(page),submitted=all.find(x=>x.id===first.draft.id)!.versions.find(x=>x.id===first.version.id)!;assert.ok(submitted.submission?.href);assert.equal(all.find(x=>x.id===second.draft.id)!.versions[0].status??'open','open'); const another=await context(language,width);await another.addCookies(await current.cookies(origin));const other=await another.newPage();active=other;await other.goto(`${origin}/workspace.html?tab=drafts`);await other.locator('[data-personal-show-archived-drafts]').check();const archived=other.locator(`[data-personal-draft="${first.draft.id}"]`);await archived.waitFor();await archived.locator(':scope > summary').click(); - const submittedVersion = archived.locator('article').filter({ has: archived.locator(`a[href*="draftVersion=${first.version.id}"]`) }); + const submittedVersion = archived.locator('article').filter({ has: other.locator(`a[href*="draftVersion=${first.version.id}"]`) }); const submittedLink = submittedVersion.locator('[data-draft-status=submitted] a'); await submittedLink.waitFor(); assert.equal(await submittedLink.getAttribute('href'), submitted.submission!.href); await other.screenshot({path:path.join(output,`${language}-${width}-submitted-on-another-device.png`),fullPage:true});assert.ok(await other.evaluate(()=>Math.max(document.body.scrollWidth,document.documentElement.scrollWidth)<=innerWidth+1)); diff --git a/scripts/test-web-research-run-continuity.ts b/scripts/test-web-research-run-continuity.ts index 9061e446..284dcb8a 100644 --- a/scripts/test-web-research-run-continuity.ts +++ b/scripts/test-web-research-run-continuity.ts @@ -7,6 +7,7 @@ import path from 'node:path'; import type { Page } from 'playwright'; import { createWebService } from '../apps/web/server'; import { readWebConfig } from '../apps/web/config'; +import { webAgentTeamPreset } from '../apps/web/researchMode'; import type { WebRunner } from '../apps/web/runner'; import type { WebRun } from '../apps/web/shared'; import { mathDigest } from '../src/math/mathRuntimeIo'; @@ -46,8 +47,15 @@ const runner: WebRunner = { if (input.input.model === 'fixture-auth-error') { send({ type: 'error', message: 'Fixture key rejected', failure: { kind: 'authentication' } }); return; } const fixture = records(input.id); fixtures.set(input.id, fixture); if (input.input.model === 'fixture-approval') { - fixture.first.observation!.inspection.planApproval = { required: true, status: 'pending', planVersion: 'plan-1', rejections: [], leadRevising: false }; - send({ type: 'observation', observation: fixture.first.observation! }); + const observation = fixture.first.observation!; + Object.assign(observation.inspection.configuration, { + workers: 1, coordination: 'independent', researchMode: 'skill', + researchSkill: { name: 'theoremos-research', digest: mathDigest('fixture skill'), loading: 'native' }, + researchDelegation: { mode: 'team', maxAgents: input.input.nativeTeamCapacity }, + }); + observation.plan!.baseVersion = 'plan-1'; + observation.inspection.planApproval = { required: true, status: 'pending', planVersion: 'plan-1', rejections: [], leadRevising: false }; + send({ type: 'observation', observation }); await new Promise(resolve => { if (signal.aborted) resolve(); else signal.addEventListener('abort', () => resolve(), { once: true }); }); return; } send({ type: 'observation', observation: fixture.first.observation! }); @@ -75,7 +83,8 @@ try { const owner = (await context.cookies(origin)).find(cookie => cookie.name === 'theoremos_session')!.value; const session = await page.evaluate(async () => (await fetch('/api/session')).json()), provider = session.providers[0], recorded = readingRun(); const create = (model: string) => service.jobs.create(owner, { providerId: provider.id, apiKey: 'sk-disposable-not-sent', model, effort: 'high', - source: recorded.source, task: recorded.task, environment: recorded.environment, maxTurns: 2, maxRunSeconds: 600, workers: 1, coordination: 'cooperative' }, provider); + source: recorded.source, task: recorded.task, environment: recorded.environment, maxTurns: 2, maxRunSeconds: 600, + ...(model === 'fixture-approval' ? { ...webAgentTeamPreset(), planApproval: true } : { workers: 1, coordination: 'cooperative' }) }, provider); phase = `failure-and-recovery-${language}`; const failed = create('fixture-auth-error'); await page.waitForFunction(async id => (await (await fetch(`/api/runs/${id}`)).json()).run.status === 'error', failed.id); From 8ac7b0c22005320e8d9cbbd5b48d4933bf8f8409 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:06:17 +0800 Subject: [PATCH 6/7] Wait for available proof inputs after unchanged checkpoints --- src/solver/cooperation.ts | 24 +++++++-- src/solver/goalProgress.ts | 13 +++-- src/solver/planningEvidence.ts | 2 + tests/solverAtomicPlanApply.test.ts | 16 ++++++ tests/solverCooperativeCheckpoints.test.ts | 60 ++++++++++++++++++++++ 5 files changed, 106 insertions(+), 9 deletions(-) diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index 61022438..6a5c7517 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -28,7 +28,7 @@ import { leadResearchInputs } from './contextCompiler'; import { deliverHumanGuidance, readHumanGuidance } from './humanGuidance'; import { mathematicalGaps, mathematicalGapVisible } from './mathematicalGaps'; import { currentNextCheck, visibleNextChecks } from './nextChecks'; -import { goalProgressForTask } from './goalProgress'; +import { GOAL_PROGRESS_REASON_MAX_LENGTH, goalProgressForTask } from './goalProgress'; import { automaticTaskConnection, createTaskConnectionCheck, taskConnectionNeedsRefresh } from './taskConnections'; import { TACTIC_BATTERY_TIMEOUT_MS } from './tacticBattery'; import { LIBRARY_APPLICATION_TIMEOUT_MS } from './libraryApplication'; @@ -608,7 +608,8 @@ export class CooperativeResearch extends CooperationInputs { if (obligations.research) required.push('Answer each still-unanswered presented delivery in researchDecisions: ' + JSON.stringify(obligations.researchInputs.map(record => record.id)) + '.'); if (obligations.progressReview) required.push('Include progressReview with id ' + JSON.stringify(obligations.progressReview.id) + - ', a reason and nextChecks covering every reviewed goal: ' + JSON.stringify(obligations.progressReview.goalIds) + '.'); + ', a reason of at most ' + GOAL_PROGRESS_REASON_MAX_LENGTH + ' characters and nextChecks covering every reviewed goal: ' + + JSON.stringify(obligations.progressReview.goalIds) + '.'); if (obligations.nextCheck) required.push('Include nextCheckDecisions for each still-unanswered presented outcome: ' + JSON.stringify(obligations.nextCheckOutcomes.map(record => ({ checkId: record.id, outcomeDeliveryId: record.outcome?.deliveryId }))) + '.'); @@ -685,7 +686,7 @@ export class CooperativeResearch extends CooperationInputs { node.status === 'conditional' && taskDependenciesReady(node.task, this.archive.tasks))) || Boolean(this.archive.statementReviews?.some(review => route.has(review.taskId) && ['translating', 'reviewing'].includes(review.status))); } - private taskDispatchBlock(node: TaskRecord): 'preparing-type' | 'synchronizing' | 'capacity-expired' | 'awaiting-lead' | undefined { + private taskDispatchBlock(node: TaskRecord, ranked?: readonly TaskRecord[]): 'preparing-type' | 'synchronizing' | 'capacity-expired' | 'awaiting-lead' | 'dependency' | undefined { if (this.preparingTaskTypes.has(node)) return 'preparing-type'; if (this.transferringResearch.has(node) || this.synchronizationBlocked(node.task)) return 'synchronizing'; if (node.capacityExploration && !currentCapacityExploration(node, this.archive.tasks, this.explorationIdentity)) @@ -704,6 +705,19 @@ export class CooperativeResearch extends CooperationInputs { } // Older checkpoints recorded only the Lead turn's wake sequence. if (checkpoint.leadWake !== undefined && this.archive.leadWakes!.settled < checkpoint.leadWake) return 'awaiting-lead'; + if (!ranked) return; + // An unchanged speculative application can wait while a worker proves its missing input. + const peers = this.allocationPeers; + const progressingInput = this.dependencies(node.task).some(input => { + if (advisory(input.task)) return false; + if (input.status === 'delivered') return true; + if (input.status === 'running') return input.assignment !== undefined && this.liveWorkers.has(input.assignment.workerId); + // Only an unconditional, dispatchable input can make progress without this application. + return input.status === 'pending' && ranked.includes(input) && taskDependenciesReady(input.task, this.archive.tasks) && + !this.taskDispatchBlock(input) && this.nextCheckDispatchable(input) && peers.some(peer => assessTaskResponsibility(input, peer, this.responsibility).kind === 'matches' && + this.assignPeerTask([input], peer, this.archive.tasks, this.archive.groups, peers) === input); + }); + if (progressingInput) return 'dependency'; } private transferringResearch = new Set(); private transferableResearch(node: TaskRecord, worker: ResearchWorker): boolean { @@ -756,7 +770,7 @@ export class CooperativeResearch extends CooperationInputs { return; } const candidates: DispatchWaitObservation['candidates'] = ranked.slice(0, 16).map(node => { - const hostBlock = this.taskDispatchBlock(node); + const hostBlock = this.taskDispatchBlock(node, ranked); const assessment = assessTaskResponsibility(node, worker, this.responsibility); return { taskId: node.task.id, taskDigest: digest(node.task), reason: hostBlock ?? (assessment.kind === 'blocked' ? assessment.reason : 'policy-no-selection') }; @@ -768,7 +782,7 @@ export class CooperativeResearch extends CooperationInputs { const finalReview = this.finalReviewCommit(); const ranked = this.input.modules.M3.ready(tasks, groups).filter(node => !isFinalCandidateReview(node.task)); const ready = ranked.filter(node => (!finalReview || !ordinaryAdvisoryTask(node.task)) && - this.nextCheckDispatchable(node) && !this.taskDispatchBlock(node)); + this.nextCheckDispatchable(node) && !this.taskDispatchBlock(node, ranked)); return { ranked, ready }; } private finalReviewCommit(): string | undefined { diff --git a/src/solver/goalProgress.ts b/src/solver/goalProgress.ts index f5482d4f..64e55cb6 100644 --- a/src/solver/goalProgress.ts +++ b/src/solver/goalProgress.ts @@ -8,9 +8,11 @@ import { nextCheckSchema, type NextCheck } from './mathematicalGapContract'; import { nextCheckExecutionMatchesTask } from './mathematicalGaps'; import type { NextCheckRecord } from './nextCheckContract'; import { z } from 'zod'; +import { invalidPlanField } from './planDiagnostics'; /** A review interval of started worker execution, never a deadline for a proof. */ export const GOAL_PROGRESS_REVIEW_MS = 30 * 60_000; +export const GOAL_PROGRESS_REASON_MAX_LENGTH = 2000; export type GoalProgressNextCheck = NextCheck & { targetTaskId: string; taskDigest?: string }; export type GoalProgressDecision = { id: string; reason: string; nextChecks: GoalProgressNextCheck[] }; export type GoalProgressState = { @@ -34,7 +36,7 @@ export const goalProgressStateSchema = z.object({ coreFrontier: z.array(z.object({ taskId: z.string(), taskDigest: z.string(), contractDigest: z.string() })).optional() })), pending: z.object({ id: z.string(), at: savedCount, goalKeys: z.array(z.string()), goalIds: z.array(z.string()), retryAt: savedCount.optional() }).optional(), - decisions: z.array(z.object({ id: z.string(), at: savedCount, reason: z.string().min(1).max(2000), goalKeys: z.array(z.string()), + decisions: z.array(z.object({ id: z.string(), at: savedCount, reason: z.string().min(1).max(GOAL_PROGRESS_REASON_MAX_LENGTH), goalKeys: z.array(z.string()), nextChecks: z.array(nextCheckSchema.required({ targetTaskId: true }).extend({ taskDigest: z.string().optional() })) .min(1).max(32).optional() })).max(16).optional(), }).transform((value): GoalProgressState => value as GoalProgressState); @@ -244,16 +246,19 @@ export function parseGoalProgressDecision(value: unknown, restoring = false): Go const decision = (value as { progressReview: unknown }).progressReview; if (!decision || typeof decision !== 'object' || Array.isArray(decision) || typeof (decision as GoalProgressDecision).id !== 'string' || !(decision as GoalProgressDecision).id.trim() || - typeof (decision as GoalProgressDecision).reason !== 'string' || !(decision as GoalProgressDecision).reason.trim() || - (decision as GoalProgressDecision).reason.length > 2000) + typeof (decision as GoalProgressDecision).reason !== 'string' || !(decision as GoalProgressDecision).reason.trim()) throw new Error('math_plan_progress_review_invalid: provide the presented id, reason and nextChecks.'); + const reason = (decision as GoalProgressDecision).reason; + if (reason.length > GOAL_PROGRESS_REASON_MAX_LENGTH) + throw invalidPlanField('math_plan_progress_review_invalid', 'progressReview.reason', + 'Shorten the reason to at most ' + GOAL_PROGRESS_REASON_MAX_LENGTH + ' characters (received ' + reason.length + ').'); // Historical notes may contain a reason-only response. Loading it supplies no new decision. if (restoring && !Object.hasOwn(decision, 'nextChecks')) return; const nextChecks = nextCheckSchema.required({ targetTaskId: true }).array().min(1).max(32) .safeParse((decision as GoalProgressDecision).nextChecks); if (!nextChecks.success) throw new Error('math_plan_progress_review_invalid: nextChecks require action, objective, expectedEvidence and targetTaskId.'); - return { id: (decision as GoalProgressDecision).id, reason: (decision as GoalProgressDecision).reason.trim(), + return { id: (decision as GoalProgressDecision).id, reason: reason.trim(), nextChecks: nextChecks.data.map(check => ({ ...check, targetTaskId: check.targetTaskId })) }; } diff --git a/src/solver/planningEvidence.ts b/src/solver/planningEvidence.ts index def23bdd..e1fadde4 100644 --- a/src/solver/planningEvidence.ts +++ b/src/solver/planningEvidence.ts @@ -6,6 +6,7 @@ import type { ProofRoute } from './proofRoutes'; import { reviewGoalPaths } from './goalPathReview'; import type { GoalPathReview } from './goalPathReview'; import { originalGoalTaskFocus } from './modules/search'; +import { GOAL_PROGRESS_REASON_MAX_LENGTH } from './goalProgress'; const summaryLimit = 8, referenceLimit = 4; const reference = (task: CooperativeTask) => ({ taskId: task.id, taskDigest: taskVersion(task) }); @@ -167,6 +168,7 @@ export function leadPlanningEvidenceText(evidence: ReturnType { } }); + it('identifies an oversized progress review reason in command validation', () => { + const { workspace, plan, file } = fixture(); + const progressReview = { id: 'review', reason: 'x'.repeat(2001), nextChecks: [{ + action: 'construction-check', targetTaskId: plan.tasks[0].id, objective: 'Perform the base case check.', + expectedEvidence: 'A checked base case or the exact failed goal.', + }] }; + const input = { workspace, text: JSON.stringify({ ...plan, progressReview }) }; + const rejected = validateCooperationPlanFile(input); + expect(rejected).toEqual({ ok: false, error: 'math_plan_progress_review_invalid', + issues: [{ path: 'progressReview.reason', message: 'Shorten the reason to at most 2000 characters (received 2001).' }] }); + expect(applyCooperationPlanFile(input)).toEqual(rejected); + expect(fs.readFileSync(file, 'utf8')).toBe(notes + '\n' + malformed); + progressReview.reason = 'x'.repeat(2000); + expect(validateCooperationPlanFile({ workspace, text: JSON.stringify({ ...plan, progressReview }) })).toMatchObject({ ok: true }); + }); + it('accepts full JSON through the CLI from stdin and replaces only old plan fences', () => { const { workspace, plan, file, problem } = fixture(); const extraPlan = '```math\n' + JSON.stringify(plan) + '\n```\n'; diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts index 1062c6c2..830efa8a 100644 --- a/tests/solverCooperativeCheckpoints.test.ts +++ b/tests/solverCooperativeCheckpoints.test.ts @@ -1760,6 +1760,66 @@ describe('cooperative advisory scheduling checkpoints', () => { return run; } + it.each(['available', 'cooling-down', 'blocked'] as const)( + 'respects upstream availability after an unchanged connection checkpoint (%s)', async availability => { + const { state, workers, problem, check, controller } = connectionChain(); + const producer = peerWorker({ directory, problem, workspace: workers[0].worktree }, 'producer', { role: 'prover' }); + workers.push(producer); + state.workers!.push({ ...producer, phase: 'prepared', turns: 0 }); + const bridge = state.cooperation!.tasks.find(node => node.task.id === 'connection_bridge')!; + bridge.task = { ...bridge.task, ownerId: producer.id, dependsOn: [] }; + state.cooperation!.tasks = state.cooperation!.tasks.filter(node => node.task.id !== 'connection_leaf'); + const [lead, worker] = workers; + const budget = { maxTurns: Infinity, remainingMs: Infinity }; + const cooperation = cooperativeResearch({ state, workers, retrievalRoot: directory, signal: controller.signal, + modules: { ...directSolverModules, M2: { ...directSolverModules.M2, check, checkTask: check, closeTask: undefined } } }); + try { + const action = await cooperation.next(worker, budget); + if (action?.kind !== 'task') throw new Error('fixture_expected_task'); + expect(action.task.id).toBe('connection_consumer'); + expect(cooperation.started(worker, action)).toBe(true); + await cooperation.retainContextDraft(worker, action, commitSolverSources(problem, worker.worktree), 'connection'); + cooperation.interrupted(worker, action); + const consumer = state.cooperation!.tasks.find(node => node.task.id === action.task.id)!; + expect(consumer.connectionCheckpoint).toBeDefined(); + expect(consumer.connectionCheckpoint?.leadDeliveryId).toBeUndefined(); + if (availability === 'blocked') bridge.status = 'blocked'; + if (availability === 'cooling-down') state.workers!.find(item => item.id === producer.id)!.recovery = { + phase: 'cooling-down', reason: 'fixture', cycles: 1, startedAt: Date.now(), nextRetryAt: Date.now() + 1000, waitedMs: 0, + }; + const dispatched = vi.fn(); + const resumed = cooperation.next(worker, budget).then(dispatched); void resumed.catch(() => {}); + if (availability !== 'available') { + await resumed; + expect(dispatched).toHaveBeenCalledWith(expect.objectContaining({ kind: 'task', assignment: action.assignment })); + expect(check).not.toHaveBeenCalled(); + return; + } + await vi.advanceTimersByTimeAsync(0); + expect(dispatched).not.toHaveBeenCalled(); + + const input = await cooperation.next(producer, budget); + if (input?.kind !== 'task') throw new Error('fixture_expected_input_task'); + expect(input.task.id).toBe(bridge.task.id); + expect(cooperation.started(producer, input)).toBe(true); + await vi.advanceTimersByTimeAsync(0); + expect(dispatched).not.toHaveBeenCalled(); + expect(consumer.attempts).toBe(1); + + const source = path.join(lead.worktree, problem.projectRelative, problem.targets[0].proofPath); + fs.appendFileSync(source, '\n-- Updated canonical input.\n'); + state.cooperation!.canonicalCommit = commitSolverSources(problem, lead.worktree); + cooperation.modelBudgetChanged(); + await resumed; + expect(dispatched).toHaveBeenCalledWith(expect.objectContaining({ kind: 'task', assignment: action.assignment })); + expect(consumer.connectionCheckpoint).toBeUndefined(); + expect(check).not.toHaveBeenCalled(); + } finally { + controller.abort(new Error('fixture_complete')); + await cooperation.stop(); + } + }); + it.each(['refuted', 'prose', 'jsonl', 'jsonl-context', 'restart', 'legacy-restart'] as const)( 'waits for Lead to decide the proof checkpoint (%s)', async report => { const { state: initialState, workers, problem, check, controller } = connectionChain(); From df90d4285d6c8aa2e521b2f74c313ef5e9f6456c Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:06:17 +0800 Subject: [PATCH 7/7] Keep native proof handoffs from blocking collaboration --- .../test-web-research-decisions-lifecycle.ts | 13 ++- src/runtime/codexSession.ts | 41 ++++++++-- src/solver/agentTeam.ts | 26 +++++- src/solver/agentTeamContext.ts | 2 + src/solver/agentTeamState.ts | 1 + tests/agentTeamNativeLifecycle.test.ts | 81 ++++++++++++++++--- tests/codexSessionAgentControl.test.ts | 73 ++++++++++------- tests/solverSoftSliceCompaction.test.ts | 9 +-- 8 files changed, 183 insertions(+), 63 deletions(-) diff --git a/scripts/test-web-research-decisions-lifecycle.ts b/scripts/test-web-research-decisions-lifecycle.ts index c13a3625..e39a290c 100644 --- a/scripts/test-web-research-decisions-lifecycle.ts +++ b/scripts/test-web-research-decisions-lifecycle.ts @@ -160,7 +160,14 @@ try { project=service.research.projects.setMember(owner,project.id,peerId,{requestId:crypto.randomUUID(),expectedRevision:project.revision,role:'collaborator'}); const next=controls.get(run.id)!.observation; next.history=[structuredClone(next.inspection.tasks[0])]; next.inspection.tasks[0].version='goal-v2'; next.sources[0].taskVersion='goal-v2'; next.sequence++; controls.get(run.id)!.emit(); await waitForRun({page},run.id,item=>item.observation?.inspection.tasks[0].version==='goal-v2'); - await page.reload(); await workspace.waitFor(); await workspace.getByRole('combobox').first().selectOption(JSON.stringify(['goal','goal-v2'])); + const reloadAndSelectCurrentTask = async () => { + await page.reload(); + // Let the deep link restore the old version before choosing the new one. + await page.locator('[data-inspected-task-version]').filter({ hasText: /^goal-v1$/u }).waitFor(); + await workspace.getByRole('combobox').first().selectOption(JSON.stringify(['goal','goal-v2'])); + await page.locator('[data-inspected-task-version]').filter({ hasText: /^goal-v2$/u }).waitFor(); + }; + await reloadAndSelectCurrentTask(); await workspace.locator('[data-handoff-review]').waitFor(); assert.equal(await workspace.getByLabel(noteLabel,{exact:true}).inputValue(),handoffNote); assert.equal(await workspace.locator('[data-handoff-submit]').isDisabled(),true); await workspace.locator('[data-handoff-confirm-context]').click(); assert.equal(await workspace.locator('[data-handoff-submit]').isEnabled(),true); @@ -175,12 +182,12 @@ try { const laterNote=handoffNote+' ANOTHER HANDOFF DRAFT';await workspace.getByLabel(noteLabel,{exact:true}).fill(laterNote); completeHandoff!();await settled(page); assert.equal(await workspace.getByLabel(noteLabel,{exact:true}).inputValue(),laterNote); - await page.reload();await workspace.waitFor();await workspace.getByRole('combobox').first().selectOption(JSON.stringify(['goal','goal-v2'])); + await reloadAndSelectCurrentTask(); await workspace.locator('[data-handoff-restored]').waitFor();assert.equal(await workspace.getByLabel(noteLabel,{exact:true}).inputValue(),laterNote); await page.unroute(`**${projectPath}/handoffs`); const handoff=service.research.projects.collaboration(owner,project.id).handoffs.find(item=>item.status==='pending'&&item.target.taskRef?.version==='goal-v2')!; assert.ok(handoff); service.research.projects.respondHandoff(peerOwner,project.id,handoff.id,{requestId:crypto.randomUUID(),expectedRevision:handoff.revision,action:'decline'}); - await page.reload();await workspace.waitFor();await workspace.getByRole('combobox').first().selectOption(JSON.stringify(['goal','goal-v2'])); + await reloadAndSelectCurrentTask(); await workspace.locator('[data-handoff-submit]').click();await page.waitForFunction(()=>document.querySelector('[data-handoff-composer] textarea')?.value===''); assert.equal(await page.evaluate(text=>Object.values(localStorage).some(value=>value.includes(text)),laterNote),false); checks.push({id:'handoff-reload-role-version-review-exact-cleanup',language,width,restoredNote,restoredRecipient,laterDraftPreserved:true}); diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 4278a0c2..6344ca7d 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -40,6 +40,37 @@ const completedAssistantText = (value: unknown): string | undefined => { if (item.type === 'agentMessage' && typeof item.text === 'string' && item.text.trim() && (item.phase === undefined || item.phase === null || item.phase === 'final_answer')) return item.text; }; + +function acceptedTeamHandoff(item: Json, readOnlyWorkspace: boolean | undefined): boolean { + if (item.type !== 'dynamicToolCall' || item.tool !== 'theoremos_team' || item.namespace != null || + item.success !== true || !Array.isArray(item.contentItems)) return false; + const args = item.arguments; + if (!args || typeof args !== 'object' || !('operation' in args)) return false; + const output = item.contentItems[0]; + if (output?.type !== 'inputText' || typeof output.text !== 'string') return false; + let result: Json; + try { result = object(JSON.parse(output.text)); } + catch { return false; } + if (result.ok !== true) return false; + switch (args.operation) { + case 'publish_plan': + return Boolean(readOnlyWorkspace) && result.status === 'pending'; + case 'finish': + case 'submit': + case 'submit_helpers': + case 'yield': + return result.status === 'pending-writer-stop'; + case 'adopt': { + const adoption = result.adoption; + if (!adoption || typeof adoption !== 'object') return false; + const { targetId, status } = adoption as Json; + return targetId === 'lead' && (status === 'queued' || status === 'integrating'); + } + default: + return false; + } +} + const RELAY_CAPABILITY_ENV = 'THEOREM_OS_MODEL_RELAY_CAPABILITY'; // Responses may remain silent between completed reasoning and their next tool/output event. // Restore Codex's default idle tolerance per session, preserving frozen provider profiles. @@ -721,12 +752,10 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise } if (method === 'item/started' || method === 'item/completed') { const item = object(params.item); - // Direct providers have no request relay. The completed host-tool item - // confirms the read-only planner received the result before we stop it. - const args = item.arguments; - if (options.readOnlyWorkspace && !usesRequestReceipts && method === 'item/completed' && - params.turnId === activeTurn && item.type === 'dynamicToolCall' && item.tool === 'theoremos_team' && - item.success === true && args && typeof args === 'object' && 'operation' in args && args.operation === 'publish_plan') + // Direct providers have no request relay. The completed tool item confirms + // that Codex received the accepted handoff before we check whether to stop. + if (!usesRequestReceipts && method === 'item/completed' && activeTurn && + params.threadId === threadId && params.turnId === activeTurn && acceptedTeamHandoff(item, options.readOnlyWorkspace)) checkTurnCheckpoint?.(false); if (compacting?.turnId && method === 'item/completed' && params.turnId === compacting.turnId && item.type === 'contextCompaction') compacting.installed = true; diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index e05e43c1..f253ed0b 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -68,6 +68,11 @@ export function assertAgentTeamProcessesStopped(state: SolverRunState) { } } +function followupObjective(task: AgentTeamTask, message: string): string { + const inherited = agentTeamProfileSelection(task.message); + return !inherited.length || agentTeamProfileSelection(message).length ? message : 'Profiles: ' + inherited.join(', ') + '\n' + message; +} + function correctableSourceFailure(error: unknown) { return error instanceof SolverSourceError || error instanceof Error && error.message === 'math_source_outside_ownership'; } @@ -425,6 +430,8 @@ export class AgentResearchTeam { this.assertRouteAvailable(task.routeId); if (task.declarations || task.helperSubmission) throw new NativeAgentControlInputError( 'math_team_submission_pending: this member has already submitted. Send new work after its writer stops and the nomination is checked.'); + if (task.pauseRequested) throw new NativeAgentControlInputError( + 'math_team_native_member_busy: this member is handing off its draft. Give it a new assignment after the handoff settles.'); const changedProfiles = profiles && canonicalMathJson(profiles.evidence.selected) !== canonicalMathJson(task.profileEvidence?.selected); // Preserve the attributed native message and codec. The receiver's frozen // profile and its local reading paths accompany the very same turn input. @@ -438,7 +445,10 @@ export class AgentResearchTeam { const accepted = this.nativeControl.accepted(worker, active.session, worker.native!.turnId!); return { ...accepted, submissionId: result.submissionId }; } - if (active) await active.task; + // Keep the native operation queue available while the previous writer or Lean check settles. + if (active) throw new NativeAgentControlInputError( + 'math_team_native_member_busy: ' + worker.id + ' is ' + (worker.activity ?? worker.status) + + '. Continue other work or send an advisory message. Follow up after this member finishes.'); await this.closeNativeIdle(worker); this.assertNativeDispatchOpen(signal); if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); @@ -452,7 +462,15 @@ export class AgentResearchTeam { throw new NativeAgentControlInputError('math_team_native_assignment_queued: Continue the queued route before assigning different work to this member.'); if (saved) { this.assertRouteAvailable(saved.routeId); - this.updateNativeFollowup(saved, message, profiles?.evidence); + const followup = followupObjective(saved, message); + if (saved.status === 'paused' && saved.pauseRequested?.kind === 'handoff' && saved.sourceCommit && + followup.trim() === saved.message.trim() && + saved.lastStartedSourceCommit === saved.sourceCommit && + git(worker.worktree, ['rev-parse', 'HEAD']) === saved.sourceCommit) + throw new NativeAgentControlInputError( + 'math_team_native_followup_unchanged: This member paused without a new draft. Adopt a needed result into their workspace, ' + + 'or give them a concrete next step with the new evidence or a different approach.'); + this.updateNativeFollowup(saved, followup, profiles?.evidence); saved.pauseRequested = undefined; saved.status = 'queued'; saved.error = undefined; } else worker.tasks.push(this.newTask(message, profiles?.evidence, routeId)); worker.native!.initialInput = initialInput; @@ -464,8 +482,7 @@ export class AgentResearchTeam { /** Native input is the instruction source; retain it for isolated-workspace resume. */ private updateNativeFollowup(task: AgentTeamTask, message: string, evidence?: AgentTeamTask['profileEvidence']) { - const selected = agentTeamProfileSelection(message), inherited = agentTeamProfileSelection(task.message); - const nextMessage = selected.length || !inherited.length ? message : 'Profiles: ' + inherited.join(', ') + '\n' + message; + const nextMessage = followupObjective(task, message); const nextEvidence = evidence ?? resolveAgentTeamProfiles(this.input.leadAccess.researchSkill!, nextMessage, this.expertCards).evidence; (task.objectiveHistory ??= []).push({ revision: task.objectiveRevision ?? 1, message: task.message, workKind: task.workKind, at: Date.now(), reason: 'Native followup.', profileEvidence: task.profileEvidence }); @@ -814,6 +831,7 @@ export class AgentResearchTeam { // A corrected or deferred delivery still includes the draft written in earlier assignments. worker.pendingSourceBase ??= sourceCommit; task.seedCommit = worker.pendingSourceBase; + task.lastStartedSourceCommit = sourceCommit; task.status = 'running'; task.startedAt ??= Date.now(); task.lastStartedAt = Date.now(); task.finishedAt = undefined; task.summary = undefined; task.error = undefined; task.declarations = undefined; task.nomination = undefined; worker.status = 'running'; worker.activity = 'running'; worker.phase = 'running'; worker.error = undefined; diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index 225a96d7..f768701d 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -23,6 +23,8 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number): s 'If several goals share a mathematical foundation, assign and check its small Lean interfaces before dispatching the consuming goals. ' + 'For a native spawn or followup, put an optional Route: ROUTE_ID line first, then an optional Profiles: line of comma-separated IDs or slugs, then the assignment. Use theoremos_team retire_route with the obstruction and evidence refs to stop a refuted route. ' + 'Idle members still occupy their places. Use native followup_task to reuse a member for another gap or specialty; interrupt_agent stops its turn and preserves its place and work. ' + + 'If a member is handing off sources or waiting for a host check, continue other work until it finishes. ' + + 'When resuming a paused draft, adopt the missing result or give a concrete next step based on new evidence. ' + 'Only Lead dispatches, interrupts and adopts; members can exchange findings directly. ' + 'Adopt a checked delivery when its interface fits. Use inspect for exact declarations and evidence when needed. For adoption into your own workspace, save sources and notes, request adoption and return. ' + 'Save all original proofs and return for independent host checking. Use finish to request early handoff.\n' + shared; diff --git a/src/solver/agentTeamState.ts b/src/solver/agentTeamState.ts index e3ad1637..62e60bc9 100644 --- a/src/solver/agentTeamState.ts +++ b/src/solver/agentTeamState.ts @@ -42,6 +42,7 @@ const task = z.object({ id: z.string(), message: z.string(), seedCommit: z.strin budget: agentTeamAllowanceSchema.optional(), turns: z.number().int().nonnegative().optional(), pauseRequested: z.object({ at: z.number(), kind: z.enum(['handoff', 'budget']), reason: z.string() }).strict().optional(), pausedAt: z.number().optional(), lastStartedAt: z.number().optional(), + lastStartedSourceCommit: z.string().regex(/^[a-f0-9]{40,64}$/u).optional(), startedAt: z.number().optional(), finishedAt: z.number().optional(), declarations: z.array(declaration).optional(), summary: z.string().optional(), deliveryId: z.string().optional(), helperSubmission: z.array(declaration).min(1).max(32).optional(), diff --git a/tests/agentTeamNativeLifecycle.test.ts b/tests/agentTeamNativeLifecycle.test.ts index 39ee1418..595ccfac 100644 --- a/tests/agentTeamNativeLifecycle.test.ts +++ b/tests/agentTeamNativeLifecycle.test.ts @@ -30,7 +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 }: { earlyCompletion?: boolean; beforeOpen?: () => Promise } = {}) { +function fixture({ earlyCompletion = false, beforeOpen, beforeVerification }: { + earlyCompletion?: boolean; beforeOpen?: () => Promise; beforeVerification?: () => Promise; +} = {}) { const directory = temporaryDirectory('native-team-lifecycle-'), root = path.resolve('.'); const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { task: 'Prove the frozen statement.', source: 'namespace NativeTeam\ntheorem original : True := by sorry\nend NativeTeam\n', @@ -109,7 +111,8 @@ function fixture({ earlyCompletion = false, beforeOpen }: { earlyCompletion?: bo 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: () => {}, exclusiveCheck: operation => operation(), + save: () => writeSolverRunState(path.join(directory, 'state.json'), state), emit: () => {}, + exclusiveCheck: async operation => { await beforeVerification?.(); return operation(); }, }); const rootOptions = team.nativeAgentControlOptions()!; const rootConnection: NativeAgentControlConnection = { info: { sessionId: ROOT, @@ -214,7 +217,7 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => expect((await capture()).inspection.nativeTeam!.adoptions[0]).toEqual(latest.inspection.nativeTeam!.adoptions[0]); await f.native('send', { caller: ROOT, target: { kind: 'id', threadId: originalThread }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue with the checked helper.' } }, startOptions: {} }); + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: consumerTask.message } }, startOptions: {} }); expect(consumer!.native!.threadId).toBe(originalThread); expect(consumer!.tasks.map(task => task.id)).toEqual([consumerTask.id]); const resumed = fs.readFileSync(f.source(consumer!.worktree), 'utf8'); @@ -325,24 +328,56 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => await expect(f.team.restore()).rejects.toThrow('math_writer_stop_unconfirmed:broken'); }); - it('rejects a followup when the run stops while the previous writer is being closed', async () => { + it('rejects a followup promptly while the previous writer is still stopping', async () => { const f = fixture(); await f.spawn('analyst'); const worker = f.state.agentTeam!.workers[0]!, session = f.sessions[0]!; await session.complete(false); await expect.poll(() => worker.activity).toBe('stopping'); - const followup = f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue the work.' } } }) - .then(() => 'accepted', error => (error as Error).message); - await new Promise(resolve => setImmediate(resolve)); - f.controller.abort(new Error('run-stopped')); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const nextTick = new Promise(resolve => setImmediate(() => resolve('still pending'))); - expect(await Promise.race([followup, nextTick])).toBe('math_team_dispatch_stopped'); + await expect(f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue the work.' } } })) + .rejects.toThrow('math_team_native_member_busy'); expect(worker.tasks).toHaveLength(1); expect(f.sessions).toHaveLength(1); + session.stopGate.resolve(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); }); + it('keeps the member mailbox available while a Lean delivery check runs', async () => { + const checking = deferred(), finishCheck = deferred(); + const f = fixture({ beforeVerification: () => { checking.resolve(); return finishCheck.promise; } }); + try { + await f.spawn('analyst'); + const worker = f.state.agentTeam!.workers[0]!, prior = f.sessions[0]!; + fs.writeFileSync(f.source(worker.worktree), fs.readFileSync(f.source(worker.worktree), 'utf8').replace('end NativeTeam', + 'theorem reusable (n : Nat) : n = n := by rfl\nend NativeTeam')); + expect(await f.tool({ operation: 'submit', summary: 'A useful helper.', + declarations: [{ file: 'Submission.lean', name: 'NativeTeam.reusable', type: '∀ n : Nat, n = n' }] }, worker.id)) + .toMatchObject({ status: 'pending-writer-stop' }); + await prior.complete(); + await checking.promise; + expect(worker.activity).toBe('checking'); + const target = { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId } }; + const send = (mode: 'queueOnly' | 'triggerTurn', text: string) => f.native('send', { + ...target, input: { kind: 'message', mode, message: { kind: 'plaintext', text } }, + }); + const followup = send('triggerTurn', 'Investigate a new gap.'); + const message = send('queueOnly', 'Save this advisory update for later.'); + await expect(followup).rejects.toThrow('math_team_native_member_busy'); + const response = await message; + expect(f.team.archive.nativeControl!.mailbox).toContainEqual(expect.objectContaining({ + id: response.result.submissionId, status: 'queued', + })); + expect(f.team.archive.deliveries).toHaveLength(0); + expect(worker.tasks).toHaveLength(1); + finishCheck.resolve(); + await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); + expect(f.team.archive.deliveries).toHaveLength(1); + await send('triggerTurn', 'Investigate a new gap.'); + expect(worker.tasks).toHaveLength(2); + } finally { finishCheck.resolve(); } + }, 40_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); @@ -445,6 +480,28 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toContain('saved dependency'); }); + it('keeps an unchanged handoff paused and accepts new instructions on the same draft', async () => { + const f = fixture(); + const objective = 'Prove the same helper.'; + await f.spawn('analyst', 'Profiles: prover\n' + objective); + const worker = f.state.agentTeam!.workers[0], task = worker.tasks[0], first = f.sessions[0]; + expect(await f.tool({ operation: 'yield', reason: 'Waiting for a checked premise.' }, worker.id)) + .toMatchObject({ status: 'pending-writer-stop' }); + await first.complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + expect(task.status).toBe('paused'); + const saved = readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0]!.tasks[0]!; + expect(saved.sourceCommit).toBe(saved.lastStartedSourceCommit); + const followup = (text: string) => f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } } }); + await expect(followup(objective)).rejects.toThrow('math_team_native_followup_unchanged'); + expect(f.sessions).toHaveLength(1); + expect(task).toMatchObject({ status: 'paused', objectiveRevision: 1 }); + await followup('First derive the premise by induction.'); + expect(worker.tasks).toEqual([task]); + expect(task).toMatchObject({ status: 'running', objectiveRevision: 2 }); + }); + it('can reuse a yielded worker for a different route and return to its original task', async () => { const f = fixture(); await f.spawn('analyst', 'Route: initial\nProfiles: prover, D006\nInvestigate the first approach.'); const worker = f.state.agentTeam!.workers[0], original = worker.tasks[0]; diff --git a/tests/codexSessionAgentControl.test.ts b/tests/codexSessionAgentControl.test.ts index 1af6450c..5db3b80d 100644 --- a/tests/codexSessionAgentControl.test.ts +++ b/tests/codexSessionAgentControl.test.ts @@ -13,22 +13,26 @@ const fixture = String.raw` const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'); const directory = process.env.CODEX_HOME; const send = value => process.stdout.write(JSON.stringify(value) + '\n'); -let start, settings, threadId, counter = 0, planningTurn; +let start, settings, threadId, counter = 0, handoffTurn; +const handoffOperation = process.env.TEAM_HANDOFF_FIXTURE; +const handoffCall = id => send({id,method:'item/tool/call',params:{threadId,turnId:handoffTurn.id, + tool:'theoremos_team',callId:id,arguments:{operation:handoffOperation}}}); +const handoffComplete = (id, result, turnId = handoffTurn.id) => + send({method:'item/completed',params:{threadId,turnId,item:{id,type:'dynamicToolCall', + tool:'theoremos_team',arguments:{operation:handoffOperation},success:result.success,contentItems:result.contentItems}}}); const host = (operation, id, extra = {}) => send({id,method:'theoremos/agentControl/request',params:{version:1, sessionId:'root-id',threadId,operationId:'operation-'+id,operation,payload:{threadId,sessionId:'root-id',...extra}}}); readline.createInterface({input:process.stdin}).on('line', line => { const call = JSON.parse(line); fs.appendFileSync(path.join(directory,'calls.jsonl'), JSON.stringify(call)+'\n'); const reply = result => send({id:call.id,result}); - if (call.id === 'invalid-plan-tool') { - send({method:'item/completed',params:{threadId,turnId:planningTurn.id,item:{id:'invalid',type:'dynamicToolCall', - tool:'theoremos_team',arguments:null,success:call.result.success}}}); - return send({id:'plan-tool',method:'item/tool/call',params:{threadId,turnId:planningTurn.id, - tool:'theoremos_team',callId:'publish',arguments:{operation:'publish_plan'}}}); + if (call.id === 'invalid-team-tool') { + handoffComplete(call.id, call.result); + return handoffCall('team-tool'); } - if (call.id === 'plan-tool') { - send({method:'item/completed',params:{threadId,turnId:planningTurn.id,item:{id:'publish',type:'dynamicToolCall', - tool:'theoremos_team',arguments:{operation:'publish_plan'},success:call.result.success}}}); + if (call.id === 'team-tool') { + handoffComplete('stale-tool', call.result, 'previous-turn'); + handoffComplete(call.id, call.result); return; } if (call.id === 'attach') { @@ -68,11 +72,10 @@ readline.createInterface({input:process.stdin}).on('line', line => { const turn = {id:'native-turn-'+ ++counter,status:'inProgress'}; const native = process.env.THEOREMOS_HOST_AGENT_CONTROL === '1'; if (native) host('admitTurn','admit-'+counter,{turnId:turn.id}); - if (process.env.PLAN_TOOL_FIXTURE) { - planningTurn = turn; + if (handoffOperation) { + handoffTurn = turn; reply({threadId,submissionId:turn.id,turn,accepted:true}); - return send({id:'invalid-plan-tool',method:'item/tool/call',params:{threadId,turnId:turn.id, - tool:'theoremos_team',callId:'invalid',arguments:null}}); + return handoffCall('invalid-team-tool'); } if (process.env.HOLD_HOST_CALLBACK) host('recordUsage','usage'); send({method:'item/completed',params:{threadId,turnId:turn.id,item:{id:'answer',type:'agentMessage',text:'Research saved.'}}}); @@ -83,10 +86,10 @@ readline.createInterface({input:process.stdin}).on('line', line => { }); return reply({threadId,submissionId:turn.id,turn,accepted:true}); } - if (call.method === 'turn/interrupt' && planningTurn) { + if (call.method === 'turn/interrupt' && handoffTurn) { reply({}); - send({method:'turn/completed',params:{threadId,turn:{...planningTurn,status:'interrupted'}}}); - return host('releaseTurn','release-plan',{turnId:planningTurn.id}); + send({method:'turn/completed',params:{threadId,turn:{...handoffTurn,status:'interrupted'}}}); + return host('releaseTurn','release-handoff',{turnId:handoffTurn.id}); } if (call.method === 'theoremos/agentControl/update') return reply({acceptedSequence:call.params.sequence}); }); @@ -112,27 +115,35 @@ describe('native AgentControl stdio integration without model calls', () => { fs.rmSync(directory, { recursive: true, force: true }); }); - it('allows a direct provider to correct invalid plan arguments before the successful checkpoint', async () => { + it.each([ + ['publish_plan', { status: 'pending' }], + ['submit', { status: 'pending-writer-stop' }], + ['submit_helpers', { status: 'pending-writer-stop' }], + ['yield', { status: 'pending-writer-stop' }], + ['finish', { status: 'pending-writer-stop' }], + ['adopt', { adoption: { targetId: 'lead', status: 'queued' } }], + ])('stops a direct provider after the current %s is accepted and acknowledged', async (operation, accepted) => { const workspace = path.join(directory, 'workspace'), profile = path.join(directory, 'profile'); fs.mkdirSync(workspace); fs.mkdirSync(profile); - let published = false; + let latestCompletedItem: unknown; + const checkpointedAfter: unknown[] = []; const requestGate: NonNullable = () => ({ allowed: true, settle: () => {} }); - requestGate.checkpoint = () => published; - session = await createCodexMathSession({ ...options, workspace, profile, isolateProcess: true, readOnlyWorkspace: true, - nativeAgentControl: host, requestGate, turnTimeoutMs: 5000, tools: { - definitions: [{ name: 'theoremos_team', description: 'Publish initial route', inputSchema: { type: 'object' } }], - call: async (_tool, args) => { - if (args === null) return { ok: false, error: 'Expected a plan object' }; - published = true; return { ok: true }; - }, - }, environment: { ...options.environment, PLAN_TOOL_FIXTURE: '1' } }); + requestGate.checkpoint = () => { checkpointedAfter.push(latestCompletedItem); return true; }; + session = await createCodexMathSession({ ...options, workspace, profile, isolateProcess: true, + readOnlyWorkspace: operation === 'publish_plan', nativeAgentControl: host, requestGate, turnTimeoutMs: 1000, + onItem: (event, item) => { if (event === 'completed') latestCompletedItem = item.id; }, + tools: { + definitions: [{ name: 'theoremos_team', description: 'Schedule a handoff', inputSchema: { type: 'object' } }], + call: async (_tool, _args, { callId }) => callId === 'invalid-team-tool' + ? { ok: false, error: 'Reject the invalid handoff.' } : { ok: true, ...accepted }, + }, environment: { ...options.environment, TEAM_HANDOFF_FIXTURE: operation } }); expect(session.usageSource).toBe('native-thread-totals'); - expect(await session.run('Publish a plan.', 'task', workspace, () => {})).toBe('checkpoint'); - expect(published).toBe(true); + expect(await session.run('Schedule a handoff.', 'task', workspace, () => {})).toBe('checkpoint'); + expect(checkpointedAfter).toEqual(['stale-tool']); expect(await session.stopForFreeze!()).toMatchObject({ status: 'stopped' }); const rpc = fs.readFileSync(path.join(profile, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); - expect(rpc.find(call => call.id === 'invalid-plan-tool')?.result.success).toBe(true); - expect(rpc.findIndex(call => call.id === 'plan-tool')).toBeLessThan(rpc.findIndex(call => call.method === 'turn/interrupt')); + expect(rpc.find(call => call.id === 'invalid-team-tool')?.result.success).toBe(true); + expect(rpc.findIndex(call => call.id === 'team-tool')).toBeLessThan(rpc.findIndex(call => call.method === 'turn/interrupt')); }); it('dispatches factory attach before thread startup returns and enables actual native tools explicitly', async () => { diff --git a/tests/solverSoftSliceCompaction.test.ts b/tests/solverSoftSliceCompaction.test.ts index f018ef8d..bdfa4d7a 100644 --- a/tests/solverSoftSliceCompaction.test.ts +++ b/tests/solverSoftSliceCompaction.test.ts @@ -33,11 +33,7 @@ describe('soft research milestones', () => { })(); const state = solverState(problem, workspace, { runId: 'soft-slice-fixture', phase: 'prepared', ...(trigger === 'team' ? { researchDelegation: { mode: 'team', maxAgents: 3 }, agentTeam: { schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [] }, - portfolioExploration: { - phase: 'completed', durationMs: 1000, scouts: [{ profile: 'structural-symmetry', status: 'timed-out', turns: 1 }], - gate: { retiredRoutes: [], foundationLemmas: [] }, - } } : {}), + transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [] } } : {}), ...(skill ? { researchMode: 'skill', researchSkill: { name: skill.name, digest: skill.digest, loading: skill.loading } } : {}) }); const modules: typeof directSolverModules = { ...directSolverModules, M2: { ...directSolverModules.M2, check: async () => { @@ -49,8 +45,7 @@ describe('soft research milestones', () => { M1: { ...directSolverModules.M1, open: async (options: MathAgentOptions): Promise => ({ threadId: 'offline-soft-slice', usageSource: 'upstream-requests', advisoryNotifications: 'native-history', notify, interrupt, close: vi.fn(async () => {}), stopForFreeze: stop, - run: async (message, _id, _workspace, begin) => { - if (trigger === 'team') expect(message).toContain('Phase 1 ended without a usable report'); + run: async (_message, _id, _workspace, begin) => { begin('held-turn'); started.resolve(options); return done.promise;