From 60a11478c9b651dde03107f2faaac8cb9a32520e Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:47:42 +0800 Subject: [PATCH] Redesign multi-agent proof harness for stability, helper reuse, and protocol convergence Implements the P0-P3 harness redesign derived from the Erdos #677 and 3D exponential entropy trajectory audits: - P0 (Stability & hygiene): default file output delivery for formalization workers and permit top-level import Mathlib; deduplicate Web observation sources by SHA-256 blob reference and throttle/cap running reasoning previews; add a host-disconnect watchdog for containerized workers; add a 180s minimum advisory protection window and preemption-mismatch cooldown. - P1 (Helper reuse & bounded slices): land standalone Lean-kernel-verified helpers incrementally in both AgentResearchTeam (submit_helpers) and CooperativeResearch (helpers deliveries) while preserving frozen declarations and the 3-axiom whitelist; enforce soft time/compaction milestone slices; compact context into pointer indexes and retain warm threads across same-route tasks. - P2 (Portfolio exploration & route control): add opt-in Phase 1 heterogeneous route scouting (structural-symmetry, explicit-constructive, falsification-obstruction) with a route-selection gate and durable negative knowledge; add atomic route retirement (retire_route / retireRoutes) and a 15-command Lead planning guardrail. - P3 (Protocol convergence): flatten theoremos_team wire schemas above Codex CLI's 16-branch oneOf drop threshold while keeping host-side strict Zod validation; add 0-turn native-agent-control startup fallback to host-tools and bounded route_summary; add atomic plan-validate/plan-apply commands and isolate malformed Lead drafts from shared deliveries while keeping M5 identity frozen. --- apps/web/Dockerfile | 1 + apps/web/agentActions.ts | 20 +- apps/web/collaboration.ts | 1 + apps/web/formalizationTypes.ts | 2 +- apps/web/formalizationWorker.ts | 2 + apps/web/i18n/errors.ts | 2 + apps/web/nativeTeamObservation.ts | 3 +- apps/web/observationSources.ts | 54 +++ apps/web/proofJournal.ts | 9 +- apps/web/researchMode.ts | 24 +- apps/web/runner.ts | 85 ++-- apps/web/server.ts | 4 +- apps/web/shared.ts | 9 +- apps/web/storage.ts | 62 ++- apps/web/worker.ts | 59 ++- apps/web/workerBridge.ts | 21 +- apps/web/workerDisconnect.ts | 41 ++ bin/math.ts | 6 +- docs/codex-skill-runtime.md | 8 +- scripts/build-agent-tools.ts | 1 + scripts/mathematics/planApply.ts | 3 + scripts/mathematics/planCommand.ts | 47 +++ scripts/mathematics/planValidate.ts | 3 + skills/theoremos-research/SKILL.md | 1 + .../references/cooperation.md | 16 +- .../references/parallel-work.md | 2 + .../references/portfolio.md | 11 + .../references/team-roles.md | 4 + src/math/verifier.ts | 66 ++-- src/runtime/codexSession.ts | 15 +- src/solver/agentTeam.ts | 368 ++++++++++++++++-- src/solver/agentTeamContext.ts | 14 +- src/solver/agentTeamProof.ts | 18 +- src/solver/agentTeamState.ts | 14 +- src/solver/agentTeamTool.ts | 32 +- src/solver/agentTeamViews.ts | 86 +++- src/solver/archive.ts | 16 +- src/solver/contextCompiler.ts | 112 +++++- src/solver/cooperation.ts | 62 ++- src/solver/cooperationCore.ts | 91 ++++- src/solver/cooperationInputs.ts | 40 +- src/solver/cooperationIntegration.ts | 46 +++ src/solver/cooperationPlanning.ts | 118 +++++- src/solver/cooperationRoutes.ts | 64 +++ src/solver/cooperationShared.ts | 44 ++- src/solver/cooperationStatements.ts | 10 +- src/solver/cooperativeProof.ts | 14 +- src/solver/declarationArtifacts.ts | 22 +- src/solver/formalization.ts | 2 +- src/solver/incrementalHelpers.ts | 234 +++++++++++ src/solver/inspection.ts | 6 +- src/solver/modules/context.ts | 78 ++-- src/solver/planDiagnostics.ts | 25 ++ src/solver/planPatch.ts | 52 ++- src/solver/planTool.ts | 116 ++++++ src/solver/portfolioExploration.ts | 277 +++++++++++++ src/solver/problem.ts | 18 +- src/solver/research.ts | 222 ++++++++--- src/solver/researchGuidance.ts | 41 +- src/solver/researchUsage.ts | 5 +- src/solver/routeControl.ts | 14 + src/solver/run.ts | 43 +- src/solver/skillResearchContext.ts | 11 +- src/solver/softSlice.ts | 71 ++++ src/solver/sourceContext.ts | 6 +- src/solver/taskLifecycle.ts | 2 + src/solver/taskTypeContract.ts | 3 +- src/solver/tasks.ts | 24 +- tests/agentResearchTeam.test.ts | 12 +- tests/agentTeamNativeControl.test.ts | 4 +- tests/agentTeamNativeTools.test.ts | 49 ++- tests/agentTeamRouteSummary.test.ts | 112 ++++++ tests/agentTeamSolver.test.ts | 24 +- tests/agentTeamSourceRecovery.test.ts | 107 ++++- tests/agentTeamTool.test.ts | 2 +- tests/agentTeamTransportFallback.test.ts | 105 +++++ tests/agentTools.test.ts | 2 +- tests/commonResearchGuidance.test.ts | 4 +- tests/contextCompiler.test.ts | 2 +- tests/definitionTasks.test.ts | 6 +- tests/fixtures/agentTeamFollowupPeer.cjs | 4 +- tests/fixtures/agentTeamHandoffPeer.cjs | 4 +- tests/fixtures/agentTeamPeer.cjs | 4 +- tests/fixtures/web-cooperative-codex.mjs | 2 +- tests/frontierPriorityContext.test.ts | 3 +- tests/helpers/solverAtomicPlanRejection.ts | 91 +++++ tests/helpers/solverTeamRouteRetirement.ts | 176 +++++++++ tests/installedLibraryContext.test.ts | 4 +- tests/leadPlanRejectionFeedback.test.ts | 3 +- tests/solver.test.ts | 51 ++- tests/solverAdvisoryPriority.test.ts | 21 +- tests/solverAtomicPlanApply.test.ts | 123 ++++++ tests/solverContext.test.ts | 69 +++- tests/solverCooperativeCheckpoints.test.ts | 93 ++++- tests/solverIncrementalHelperLanding.test.ts | 152 ++++++++ tests/solverPortfolioGate.test.ts | 165 ++++++++ tests/solverRouteRetirement.test.ts | 204 ++++++++++ tests/solverSoftSliceCompaction.test.ts | 111 ++++++ tests/webAgentActions.test.ts | 17 +- tests/webFormalizationActivity.test.ts | 2 +- tests/webFormalizationWorker.test.ts | 8 +- tests/webRunner.test.ts | 101 ++++- tests/webSkillResearch.test.ts | 36 +- tests/webWorkerBridge.test.ts | 68 ++++ 104 files changed, 4455 insertions(+), 489 deletions(-) create mode 100644 apps/web/observationSources.ts create mode 100644 apps/web/workerDisconnect.ts create mode 100644 scripts/mathematics/planApply.ts create mode 100644 scripts/mathematics/planCommand.ts create mode 100644 scripts/mathematics/planValidate.ts create mode 100644 skills/theoremos-research/references/portfolio.md create mode 100644 src/solver/cooperationRoutes.ts create mode 100644 src/solver/incrementalHelpers.ts create mode 100644 src/solver/planDiagnostics.ts create mode 100644 src/solver/planTool.ts create mode 100644 src/solver/portfolioExploration.ts create mode 100644 src/solver/softSlice.ts create mode 100644 tests/agentTeamRouteSummary.test.ts create mode 100644 tests/agentTeamTransportFallback.test.ts create mode 100644 tests/helpers/solverAtomicPlanRejection.ts create mode 100644 tests/helpers/solverTeamRouteRetirement.ts create mode 100644 tests/solverAtomicPlanApply.test.ts create mode 100644 tests/solverIncrementalHelperLanding.test.ts create mode 100644 tests/solverPortfolioGate.test.ts create mode 100644 tests/solverRouteRetirement.test.ts create mode 100644 tests/solverSoftSliceCompaction.test.ts diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 0fd2edca..b4e565e4 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -96,6 +96,7 @@ RUN timeout 30s python3 scripts/codex-backend/check-capabilities.py "$THEOREMOS_ LABEL org.theoremos.native-agent-control=v1 LABEL org.theoremos.team-profile-preferences=v1 LABEL org.theoremos.team-expert-cards=v1 +LABEL org.theoremos.worker-control=v1 ENTRYPOINT ["/opt/theorem-os/apps/web/worker-entrypoint.sh"] FROM source AS web diff --git a/apps/web/agentActions.ts b/apps/web/agentActions.ts index 602b8096..d29f3645 100644 --- a/apps/web/agentActions.ts +++ b/apps/web/agentActions.ts @@ -408,6 +408,14 @@ export function isWebAgentActionBody(value: unknown): value is WebAgentActionBod /** Coalesce only sanitized public text snapshots; lifecycle reports and tool actions remain immediate. */ export function createAgentActionStream(send: (action: WebAgentActionBody) => void) { + const reasoningIntervalMs = 4_000, reasoningPreviewBytes = 2_048; + const runningPreview = (action: WebAgentActionBody) => { + if (action.kind !== 'reasoning' || !action.text || Buffer.byteLength(action.text) <= reasoningPreviewBytes) return action; + const bytes = Buffer.from(action.text); + let start = bytes.length - reasoningPreviewBytes + Buffer.byteLength('…'); + while ((bytes[start]! & 0xc0) === 0x80) start++; + return { ...action, text: '…' + bytes.toString('utf8', start), textClipped: true }; + }; type Entry = { sentAt?: number; signature?: string; latest?: WebAgentActionBody; pending?: WebAgentActionBody; timer?: ReturnType; completed?: boolean }; const entries = new Map(); @@ -442,13 +450,15 @@ export function createAgentActionStream(send: (action: WebAgentActionBody) => vo if (!action.textSource) { if (!incremental) deliver(action); return; } if (!entry) { entry = {}; entries.set(itemId, entry); } entry.latest = action; - if (!incremental) { emit(entry, action); return; } - if (entry.signature === signature(action)) { + const preview = runningPreview(action); + if (!incremental) { emit(entry, preview); return; } + if (entry.signature === signature(preview)) { clearTimeout(entry.timer); entry.timer = undefined; entry.pending = undefined; return; } - entry.pending = action; - const remaining = entry.sentAt === undefined ? 0 : Math.max(0, 1_000 - (Date.now() - entry.sentAt)); - if (!remaining) { clearTimeout(entry.timer); entry.timer = undefined; emit(entry, action); } + entry.pending = preview; + const interval = action.kind === 'reasoning' ? reasoningIntervalMs : 1_000; + const remaining = entry.sentAt === undefined ? 0 : Math.max(0, interval - (Date.now() - entry.sentAt)); + if (!remaining) { clearTimeout(entry.timer); entry.timer = undefined; emit(entry, preview); } else if (!entry.timer) { entry.timer = setTimeout(() => { entry!.timer = undefined; diff --git a/apps/web/collaboration.ts b/apps/web/collaboration.ts index 6e9a51ca..bcf00816 100644 --- a/apps/web/collaboration.ts +++ b/apps/web/collaboration.ts @@ -102,6 +102,7 @@ export type WebNativeTeamTask = { id: string; memberId: string; objective: strin reassignment?: { ref: string; revision: number } }; export type WebNativeTeam = { schema: 'theorem-os.web-native-team.v1'; runId: string; + transport?: 'native-agent-control' | 'host-tools'; maxAgents: number; memberCount: number; taskCount: number; taskOmissions: number; tasks: WebNativeTeamTask[]; findings: WebTeamFinding[]; deliveries: WebTeamDelivery[]; adoptions: WebTeamAdoption[]; }; diff --git a/apps/web/formalizationTypes.ts b/apps/web/formalizationTypes.ts index 590924da..31b58529 100644 --- a/apps/web/formalizationTypes.ts +++ b/apps/web/formalizationTypes.ts @@ -49,7 +49,7 @@ export type WebFormalizationRequest = { original: string; environment: WebEnviro requestId?: string; providerId?: string; model?: string; researchEffort?: 'low' | 'high' | 'max'; maxRunSeconds?: number; maxTotalTokens?: number; research?: Partial }; export type WorkerFormalizationInput = Omit & { id: string; model: string; provider: WebWorkerProvider; maxRunSeconds: number; maxTotalTokens: number; maxRounds: number; maxPlanningRounds: number; reviewers: number; - contextProtocol?: LeanStatementContextProtocol; reviewMode?: 'direct' }; + contextProtocol?: LeanStatementContextProtocol; reviewMode?: 'direct'; outputDelivery?: 'native-schema' | 'file' }; export type WorkerFormalizationAuditMessage = { type: 'audit-progress'; tokens: number } | { type: 'audit-result'; result: FormalizationAuditResult } | { type: 'audit-error'; reason: string }; diff --git a/apps/web/formalizationWorker.ts b/apps/web/formalizationWorker.ts index a25ee0ea..a360ff0e 100644 --- a/apps/web/formalizationWorker.ts +++ b/apps/web/formalizationWorker.ts @@ -40,6 +40,7 @@ const formalizationWorkerInputObject = z.object({ reviewers: z.literal(webFormalizationLimits.reviewers), contextProtocol: z.literal(LEAN_STATEMENT_CONTEXT_PROTOCOL).optional(), reviewMode: z.literal('direct').optional(), + outputDelivery: z.enum(['native-schema', 'file']).optional(), }).strict(); const providerConfiguration = (input: { provider: { id: string; baseUrl: string }; model: string }, context: z.RefinementCtx) => { let url: URL; @@ -81,6 +82,7 @@ export function webFormalizationPreparation(input: WorkerFormalizationInput, pro ...author, ...(input.reviewMode === 'direct' ? { reviewMode: 'direct' as const } : { workflow, fidelityPolicy: 'task-preserving-v2' as const }), buildManifestRef, contextProtocol: input.contextProtocol ?? LEAN_STATEMENT_CONTEXT_PROTOCOL, + outputDelivery: input.outputDelivery ?? 'file', maxRounds: input.maxRounds, maxRunSeconds: input.maxRunSeconds, maxTurnSeconds: 0, maxCompileSeconds: 0, maxTotalTokens: input.maxTotalTokens }; } diff --git a/apps/web/i18n/errors.ts b/apps/web/i18n/errors.ts index ce8ad914..b2247871 100644 --- a/apps/web/i18n/errors.ts +++ b/apps/web/i18n/errors.ts @@ -14,6 +14,8 @@ 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.', diff --git a/apps/web/nativeTeamObservation.ts b/apps/web/nativeTeamObservation.ts index 0ca7fc34..95e91b23 100644 --- a/apps/web/nativeTeamObservation.ts +++ b/apps/web/nativeTeamObservation.ts @@ -19,7 +19,7 @@ export function projectWebNativeTeam(state: SolverRunState, runDirectory: string committed: (archive: string, commit: string) => { files: Record; digest: string }, ): WebNativeTeam | undefined { const team = state.agentTeam; - if (team?.transport !== 'native-agent-control') return; + if (!team || (team.transport !== 'native-agent-control' && state.researchDelegation?.mode !== 'team')) return; const root = path.join(path.dirname(state.worktree), 'agent-team'); const contained = root !== runDirectory && isMathPathWithin(runDirectory, root); const proofs = path.join(root, 'proofs'), archive = path.join(proofs, 'sources.git'); @@ -185,6 +185,7 @@ export function projectWebNativeTeam(state: SolverRunState, runDirectory: string for (const reference of (team.researchArtifacts ?? []).slice(-16)) finding('research:' + reference.id); for (const entry of mail.filter(entry => entry.originTaskId).slice(-24)) finding('message:' + entry.id); return { schema: 'theorem-os.web-native-team.v1', runId: state.runId, maxAgents: inspection.maxAgents, + transport: team.transport ?? 'host-tools', memberCount: overview.totals.workers, taskCount: overview.totals.tasks, taskOmissions: overview.totals.tasks - tasks.length, tasks, findings: [...findings.values()], deliveries: published, adoptions }; } diff --git a/apps/web/observationSources.ts b/apps/web/observationSources.ts new file mode 100644 index 00000000..07f5ba3c --- /dev/null +++ b/apps/web/observationSources.ts @@ -0,0 +1,54 @@ +import { mathDigest } from '../../src/math/mathRuntimeIo'; +import type { WebObservation, WebTaskSource } from './collaboration'; + +type SourceReference = { sha256: string }; +type ObservationWithSource = Omit & { + sources: (Omit & { + source: Text; dependencySources?: { file: string; source: Text }[]; + })[]; +}; + +export type CompactWebObservation = ObservationWithSource; +export type WorkerObservationFrame = { + type: 'observation'; + observation: CompactWebObservation; + sourceBlobs: Record; +}; + +function mapSources(observation: ObservationWithSource, map: (source: From) => To): ObservationWithSource { + return { + ...observation, + sources: observation.sources.map(({ source, dependencySources, ...metadata }) => ({ + ...metadata, source: map(source), + ...(dependencySources === undefined ? {} : { + dependencySources: dependencySources.map(dependency => ({ ...dependency, source: map(dependency.source) })), + }), + })), + }; +} + +export function compactObservation(observation: WebObservation, save: (digest: string, text: string) => void): CompactWebObservation { + const digests = new Map(); + return mapSources(observation, (source: string) => { + let sha256 = digests.get(source); + if (!sha256) { + sha256 = mathDigest(source); + digests.set(source, sha256); + save(sha256, source); + } + return { sha256 }; + }); +} + +/** Legacy records inline their sources. References must all resolve before handing the observation to a consumer. */ +export function hydrateObservation(observation: WebObservation | CompactWebObservation, + read: (digest: string) => string | undefined): WebObservation { + return mapSources(observation, (source: string | SourceReference) => { + if (typeof source === 'string') return source; + if (typeof source?.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(source.sha256)) + throw new Error('web_observation_source_reference_invalid'); + const text = read(source.sha256); + if (text === undefined) throw new Error('web_observation_source_blob_missing'); + return text; + }); +} diff --git a/apps/web/proofJournal.ts b/apps/web/proofJournal.ts index ca3a7cff..7caeac33 100644 --- a/apps/web/proofJournal.ts +++ b/apps/web/proofJournal.ts @@ -1,6 +1,7 @@ import path from 'node:path'; import { writeMathTextDurable } from '../../src/math/mathRuntimeIo'; import type { WorkerMessage } from './shared'; +import type { WorkerObservationFrame } from './observationSources'; export const webProofJournalDirectory = '/var/theoremos-proof'; export const webProofJournalFiles = ['transitions.json', 'observation.json', 'artifact.json', 'terminal.json'] as const; @@ -15,8 +16,10 @@ export function webProofMessageSink(output: NodeJS.WritableStream, apiKey: strin }; const transitions: Extract[] = []; let disconnected = false; - output.on('error', () => { disconnected = true; }); - return (message: WorkerMessage) => { + const disconnect = () => { disconnected = true; }; + output.on('error', disconnect); + output.on('close', disconnect); + return (message: WorkerMessage, frame?: WorkerObservationFrame) => { if (journal) { let file: typeof webProofJournalFiles[number] | undefined; switch (message.type) { @@ -35,6 +38,6 @@ export function webProofMessageSink(output: NodeJS.WritableStream, apiKey: strin } catch { /* A failed backup write must not suppress the live result. */ } } } - if (!disconnected) output.write(redact(message) + '\n'); + if (!disconnected) output.write(redact(frame ?? message) + '\n'); }; } diff --git a/apps/web/researchMode.ts b/apps/web/researchMode.ts index e4f18250..b989a1b8 100644 --- a/apps/web/researchMode.ts +++ b/apps/web/researchMode.ts @@ -4,10 +4,27 @@ import type { WebProvider, 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); +export const webPortfolioSecondsSchema = z.number().int().min(1).max(86_400); + +/** Team preset for Web callers. Capacity counts the Lead and its isolated members. */ +export function webAgentTeamPreset(capacity = 3): Pick { + return { researchMode: 'skill', workers: 1, coordination: 'independent', nativeTeamCapacity: nativeTeamCapacitySchema.parse(capacity) }; +} + +/** Presets can opt in at two or more workers. An explicit choice always wins. */ +export function webPortfolioPreset(input: Pick): boolean { + return input.portfolioExploration ?? (input.nativeTeamCapacity ?? input.workers) >= 2; +} /** The optional research engine is frozen with each new run, never changed by an observation. */ export function webResearchModeError(input: Pick, provider?: Pick): string | undefined { + 'coordination' | 'planApproval' | 'modulePlan' | 'researchSelection' | 'nativeTeamCapacity' | 'nativeTeamPreferredProfiles' | + 'portfolioExploration' | 'portfolioSeconds'>, 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 (input.nativeTeamPreferredProfiles?.length && input.nativeTeamCapacity === undefined) return '角色偏好仅适用于 Codex 原生团队。'; if (input.nativeTeamCapacity !== undefined) { if (!nativeTeamCapacitySchema.safeParse(input.nativeTeamCapacity).success) @@ -25,10 +42,13 @@ export function webResearchModeError(input: Pick): string[] { const error = webResearchModeError(input, provider); if (error) throw new Error(error); - return input.researchMode === 'skill' + const research = 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/runner.ts b/apps/web/runner.ts index 1c34ec95..9a70f87f 100644 --- a/apps/web/runner.ts +++ b/apps/web/runner.ts @@ -26,8 +26,10 @@ import { mathConstructionImports } from '../../src/math/mathConstructionSources' import { formalizationAuditResultSchema } from '../../src/math/formalizationAudit'; import { webFormalizationPhases, webFormalizationReason, type WorkerFormalizationInput, type WorkerFormalizationMessage, type WorkerFormalizationAuditMessage } from './formalizationTypes'; -import { readMathText } from '../../src/math/mathRuntimeIo'; +import { mathDigest, readMathText } from '../../src/math/mathRuntimeIo'; import { webProofJournalDirectory, webProofJournalFiles } from './proofJournal'; +import { webWorkerDisconnectGraceMs, webWorkerHeartbeatMs, webWorkerShutdownMs } from './workerDisconnect'; +import { hydrateObservation, type CompactWebObservation } from './observationSources'; export type WebRunner = { readiness(): Promise<{ ready: boolean; message: string; nativeTeam?: boolean; nativeTeamPreferences?: boolean; nativeTeamExpertCards?: boolean }>; @@ -64,6 +66,7 @@ export function isWebObservation(value: unknown): value is WebObservation { !object(value.coverage) || value.declarations !== undefined && !webDeclarationArtifactsSchema.safeParse(value.declarations).success) return false; const team = value.inspection.nativeTeam; if (team !== undefined && (!object(team) || team.schema !== 'theorem-os.web-native-team.v1' || team.runId !== value.solverRunId || + team.transport !== undefined && team.transport !== 'native-agent-control' && team.transport !== 'host-tools' || !Array.isArray(team.tasks) || !Array.isArray(team.findings) || !Array.isArray(team.deliveries) || !Array.isArray(team.adoptions))) return false; const configuration = value.inspection.configuration; if (object(configuration)) { @@ -74,7 +77,9 @@ export function isWebObservation(value: unknown): value is WebObservation { loading: z.enum(['native', 'file']) }).strict().safeParse(configuration.researchSkill).success) return false; } return value.sources.every(source => object(source) && source.scope === 'owned-file' && - ['taskId', 'taskVersion', 'commit', 'sourceDigest', 'environmentDigest', 'file', 'source'].every(field => typeof source[field] === 'string')) && + ['taskId', 'taskVersion', 'commit', 'sourceDigest', 'environmentDigest', 'file', 'source'].every(field => typeof source[field] === 'string') && + (source.dependencySources === undefined || Array.isArray(source.dependencySources) && + source.dependencySources.every(entry => object(entry) && typeof entry.file === 'string' && typeof entry.source === 'string'))) && value.checks.every(check => object(check) && object(check.record) && ['id', 'taskId', 'taskVersion', 'commit', 'sourceDigest', 'environmentDigest'].every(field => typeof check[field] === 'string')); } @@ -94,11 +99,35 @@ const workerMessageSchema = z.discriminatedUnion('type', [ proof: z.string().max(128 * 1024), report: z.record(z.unknown()) }).strict() }).strict(), ]); -export function parseWorkerMessage(line: string): WorkerMessage | undefined { +export function parseWorkerMessage(line: string, stream?: { runId: string; sources: Map }): WorkerMessage | undefined { try { const value: unknown = JSON.parse(line); - if (object(value) && value.type === 'observation' && Object.keys(value).length === 2 && isWebObservation(value.observation)) - return { type: 'observation', observation: value.observation }; + if (object(value) && value.type === 'observation') { + if (Object.keys(value).length === 2 && isWebObservation(value.observation)) + return { type: 'observation', observation: value.observation }; + if (Object.keys(value).length !== 3 || !object(value.observation) || !object(value.sourceBlobs) || + stream && value.observation.webRunId !== stream.runId) return; + const current = new Map(); + let bytes = 0; + const observation = hydrateObservation(value.observation as CompactWebObservation, digest => { + let source = current.get(digest); + if (source === undefined) { + const supplied = value.sourceBlobs as Record; + if (Object.hasOwn(supplied, digest)) { + const text = supplied[digest]; + if (typeof text !== 'string' || mathDigest(text) !== digest) throw new Error('web_observation_invalid_source_blob'); + source = text; + } else source = stream?.sources.get(digest); + if (source !== undefined) current.set(digest, source); + } + if (source !== undefined) bytes += Buffer.byteLength(source); + if (bytes > 15 * 1024 * 1024) throw new Error('web_observation_too_large'); + return source; + }); + if (!isWebObservation(observation)) return; + if (stream) stream.sources = current; + return { type: 'observation', observation }; + } if (object(value) && value.type === 'catalog' && Object.keys(value).length === 2) return { type: 'catalog', catalog: validateTheoremKnowledge(value.catalog) }; if (object(value) && value.type === 'action') @@ -167,7 +196,7 @@ export function parseFormalizationMessage(line: string): WorkerFormalizationMess } export class DockerWebRunner implements WebRunner { - private cached?: { at: number; result: Awaited> }; + private cached?: { at: number; result: Awaited>; workerControl: boolean }; private active = new Set(); constructor(private readonly config: Pick) {} @@ -304,14 +333,14 @@ 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"}}', + 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"}}', this.config.workerImage], { timeout: 5_000, maxBuffer: 4096 }).catch(() => undefined); const ready = Boolean(metadata); - const [team, preferences, expertCards] = metadata?.stdout.trim().split('|') ?? []; + 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', message: ready ? '运行环境就绪' : '运行镜像尚未就绪,请先构建 theorem-os-worker 镜像。' }; - this.cached = { at: Date.now(), result }; + this.cached = { at: Date.now(), result, workerControl: workerControl === 'v1' }; return result; } @@ -321,6 +350,10 @@ export class DockerWebRunner implements WebRunner { const environment = input.input.environment ?? 'standard'; const mathlib = environment === 'mathlib'; const memory = mathlib ? '8g' : '4g'; + const workerControl = this.cached?.workerControl === true; + let cleanup: Promise | undefined; + const remove = () => cleanup ??= execute('docker', ['rm', '--force', '--volumes', name], { timeout: 15_000 }) + .then(() => {}, () => { cleanup = undefined; }); const args = ['create', '--interactive', '--pull=never', '--name', name, '--add-host=host.docker.internal:host-gateway', '--log-driver=none', '--read-only', '--cap-drop=ALL', '--security-opt=no-new-privileges', @@ -332,6 +365,7 @@ export class DockerWebRunner implements WebRunner { '--ulimit', 'nofile=1024:1024', '--mount', `type=volume,destination=${webProofJournalDirectory}`, '--env', `THEOREMOS_WORKER_JOURNAL=${webProofJournalDirectory}`, + ...(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]; @@ -339,11 +373,11 @@ export class DockerWebRunner implements WebRunner { try { await execute('docker', args, { timeout: 30_000, maxBuffer: 8_192 }); } catch { - await execute('docker', ['rm', '--force', '--volumes', name], { timeout: 15_000 }).catch(() => {}); + await remove(); throw new Error('无法创建隔离运行环境,请检查 Docker 与 worker 镜像。'); } if (signal.aborted) { - await execute('docker', ['rm', '--force', '--volumes', name], { timeout: 15_000 }).catch(() => {}); + await remove(); signal.throwIfAborted(); } try { await new Promise((resolve, reject) => { @@ -352,9 +386,12 @@ export class DockerWebRunner implements WebRunner { let buffer = '', finished = false, receivedResult = false; let workerError: Error | undefined; let observedSequence = 0, libraryRound = 0, artifactAt = ''; + const observationStream = { runId: input.id, sources: new Map() }; let recovery: AbortController | undefined; let stopping: Promise | undefined; + let heartbeat: ReturnType | undefined; const stop = () => stopping ??= (async () => { + clearInterval(heartbeat); recovery?.abort(); // Capture the actual saved checkpoint and source evidence before deleting the container. try { @@ -362,12 +399,8 @@ export class DockerWebRunner implements WebRunner { if (captured.observation) onMessage({ type: 'observation', observation: captured.observation }); if (captured.catalog) onMessage({ type: 'catalog', catalog: captured.catalog }); } catch { /* A run cancelled during bootstrap may not have a checkpoint yet. */ } - await new Promise(done => { - const cleanup = spawn('docker', ['rm', '--force', '--volumes', name], { stdio: 'ignore' }); - const timer = setTimeout(() => { cleanup.kill('SIGKILL'); child.kill('SIGKILL'); done(); }, 15_000); - const complete = () => { clearTimeout(timer); child.kill('SIGTERM'); done(); }; - cleanup.once('error', complete); cleanup.once('close', complete); - }); + await remove(); + child.kill('SIGKILL'); })(); const abort = () => { void stop(); }; const watchdog = new ExecutionDeadline(input.input.maxRunSeconds === 0 ? Number.POSITIVE_INFINITY @@ -375,7 +408,7 @@ export class DockerWebRunner implements WebRunner { signal.addEventListener('abort', abort, { once: true }); const finish = async (error?: Error) => { if (finished) return; - finished = true; watchdog.stop(); signal.removeEventListener('abort', abort); + finished = true; clearInterval(heartbeat); watchdog.stop(); signal.removeEventListener('abort', abort); if (error || signal.aborted) await stop(); await stopping; if (error) reject(error); else resolve(); @@ -409,13 +442,14 @@ export class DockerWebRunner implements WebRunner { const newline = buffer.indexOf('\n'); if (newline < 0) break; const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1); - const message = parseWorkerMessage(line); + const message = parseWorkerMessage(line, observationStream); if (message) forward(message); } }); child.stdin.on('error', () => {}); child.once('error', () => { void finish(new Error('无法启动隔离运行环境。')); }); child.once('close', () => { + clearInterval(heartbeat); if (finished) return; if (signal.aborted || receivedResult) { void finish(); return; } if (workerError) { void finish(workerError); return; } @@ -426,7 +460,8 @@ export class DockerWebRunner implements WebRunner { void (async () => { try { // Losing Docker's attach process says nothing about the solver's lifetime. - await execute('docker', ['wait', name], { signal: recoverySignal, maxBuffer: 8_192 }); + await execute('docker', ['wait', name], { signal: recoverySignal, maxBuffer: 8_192, + timeout: webWorkerDisconnectGraceMs + webWorkerShutdownMs + 10_000 }); for (const message of await readProofJournal(name, input.id, recoverySignal)) { if (signal.aborted || stopping) break; forward(message); @@ -436,11 +471,17 @@ export class DockerWebRunner implements WebRunner { })(); }); // Credentials travel over the private input pipe, never Docker args, env or logs. - child.stdin.end(JSON.stringify(input) + '\n'); + const request = JSON.stringify({ ...input, observationSourceRefs: true }) + '\n'; + if (workerControl) { + child.stdin.write(request); + heartbeat = setInterval(() => { + if (child.stdin.writable && !child.stdin.writableNeedDrain) child.stdin.write('\n'); + }, webWorkerHeartbeatMs); + } else child.stdin.end(request); if (signal.aborted) abort(); }); } finally { this.active.delete(input.id); - await execute('docker', ['rm', '--force', '--volumes', name], { timeout: 15_000 }).catch(() => {}); + await remove(); } } diff --git a/apps/web/server.ts b/apps/web/server.ts index dde6e765..008c7f64 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -1,5 +1,5 @@ import { publicWebProvider, webProviderHarness, webHarnessResearchError } from './harness'; -import { nativeTeamCapacitySchema, nativeTeamPreferencesSchema, webDefaultSkillLoading } from './researchMode'; +import { nativeTeamCapacitySchema, nativeTeamPreferencesSchema, webDefaultSkillLoading, webPortfolioSecondsSchema } from './researchMode'; import { webTeamProfiles } from './nativeTeamProfiles'; import http, { type IncomingMessage, type ServerResponse } from 'node:http'; import fs from 'node:fs'; @@ -70,6 +70,8 @@ const inputSchema = z.object({ explanationLanguage: z.enum(['zh', 'en']).optional(), researchMode: z.enum(['legacy', 'skill']).optional(), skillLoading: z.enum(['native', 'file']).optional(), + portfolioExploration: z.boolean().optional(), + portfolioSeconds: webPortfolioSecondsSchema.optional(), nativeTeamCapacity: nativeTeamCapacitySchema.optional(), nativeTeamPreferredProfiles: nativeTeamPreferencesSchema.optional(), planApproval: z.boolean().optional(), diff --git a/apps/web/shared.ts b/apps/web/shared.ts index e4389ee4..fb185472 100644 --- a/apps/web/shared.ts +++ b/apps/web/shared.ts @@ -77,7 +77,10 @@ export type WebRunInput = { /** Omitted on older runs: retain the existing research engine. */ researchMode?: WebResearchMode; skillLoading?: WebSkillLoading; - /** Native Codex capacity includes Lead. The host still runs one worker. */ + /** 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. */ nativeTeamCapacity?: number; /** Advisory Skill profile IDs requested before starting; actual assignments belong to Lead. */ nativeTeamPreferredProfiles?: string[]; @@ -164,6 +167,8 @@ export type WebRun = { explanationLanguage?: WebExplanationLanguage; researchMode?: WebResearchMode; skillLoading?: WebSkillLoading; + portfolioExploration?: boolean; + portfolioSeconds?: number; researchSkill?: { name: string; digest: string; loading: WebSkillLoading }; nativeTeamCapacity?: number; nativeTeamPreferredProfiles?: string[]; @@ -255,6 +260,8 @@ export type WebProofOutlineDeclaration = { export type WebProofOutline = { references: 'recorded' | 'unrecorded'; declarations: WebProofOutlineDeclaration[]; omitted: number }; /** Catalog payloads are opaque on the Web transport; worker/service consumers validate the full knowledge schema. */ export type WorkerInput = { id: string; input: WebRunInput; provider: WebWorkerProvider; knowledgeCatalog?: unknown; + /** The attached runner can resolve source references in observation frames. */ + observationSourceRefs?: true; researchConfiguration?: import('./researchAssetTypes').FrozenResearchConfiguration; /** Validated server-side artifact; never supplied directly by the browser. */ formalization?: unknown; diff --git a/apps/web/storage.ts b/apps/web/storage.ts index c35e9006..b39c47fe 100644 --- a/apps/web/storage.ts +++ b/apps/web/storage.ts @@ -5,9 +5,12 @@ import { canonicalMathJson, mathDigest, syncMathDirectory, writeMathFrozen } fro import type { WebArchive, WebCheckReceipt, WebCommandResult, WebObservation, WebTaskSource } from './collaboration'; import type { WebAccountIdentity, WebAgentAction, WebEvent, WebExplanation, WebRun, WorkerExplanationCheckpoint } from './shared'; import type { WebShareSnapshot } from './share'; +import { compactObservation, hydrateObservation, type CompactWebObservation } from './observationSources'; export type WebCreation = { schema: 'theorem-os.web-creation.v1'; requestId: string; digest: string }; type StoredRun = { owner: string; run: WebRun; creation?: WebCreation }; +type RunRecord = StoredRun & { observationSequence?: number }; +type ObservationRecord = WebObservation | CompactWebObservation; type StoredExplanationCheckpoint = { binding: string; checkpoint: WorkerExplanationCheckpoint }; export type StoredWebSession = { id: string; csrf: string; touchedAt: number; account?: WebAccountIdentity & { id: string }; passwordResetUntil?: number }; @@ -166,14 +169,26 @@ export class WebStorage { if (run.observation) this.saveObservation(owner, run.observation); for (const event of run.events) this.saveRecord([...directory, 'events', `${event.sequence}.json`], event, true); creation ??= this.getRecord([...directory, 'run.json'])?.creation; - this.saveRecord([...directory, 'run.json'], { owner, run, ...(creation ? { creation } : {}) }); + const { observation, ...summary } = run; + this.saveRecord([...directory, 'run.json'], { owner, run: summary, + ...(observation ? { observationSequence: observation.sequence } : {}), ...(creation ? { creation } : {}) }); + } + private readRun(directory: string[]): StoredRun | undefined { + const stored = this.getRecord([...directory, 'run.json']); + if (!stored) return; + const { observationSequence, ...result } = stored; + if (observationSequence !== undefined) { + const observation = this.readObservation(directory, observationSequence); + if (observation) result.run.observation = observation; + } + return result; } getRun(owner: string, id: string): WebRun | undefined { - return this.getRecord<{ owner: string; run: WebRun }>([...this.runPath(owner, id), 'run.json'])?.run; + return this.readRun(this.runPath(owner, id))?.run; } loadRuns(): StoredRun[] { return this.listRecords(['owners']).flatMap(directory => this.listRecords(['owners', directory, 'runs']) - .map(id => this.getRecord(['owners', directory, 'runs', id, 'run.json'])) + .map(id => this.readRun(['owners', directory, 'runs', id])) .filter((item): item is StoredRun => Boolean(item))) .sort((a, b) => a.run.createdAt.localeCompare(b.run.createdAt)); } @@ -216,15 +231,43 @@ export class WebStorage { saveObservation(owner: string, observation: WebObservation): void { if (!Number.isSafeInteger(observation.sequence) || observation.sequence < 1) throw new Error('web_storage_invalid_observation_sequence'); const directory = this.runPath(owner, observation.webRunId); - this.saveRecord([...directory, 'observations', `${observation.sequence}.json`], observation, true); + const recordPath = [...directory, 'observations', `${observation.sequence}.json`]; + const existing = this.getRecord(recordPath); + if (existing?.sources.some(source => typeof source.source === 'string')) { + // A run restored from an older server can still save its last inline observation. + this.saveRecord(recordPath, observation, true); + return; + } + const record = compactObservation(observation, (digest, source) => { + const segments = [...directory, 'source-blobs', `${digest}.json`], key = this.key(segments); + if (!(this.root ? fs.existsSync(path.join(this.root, key)) : this.memory.has(key))) this.saveRecord(segments, source, true); + }); + this.saveRecord(recordPath, record, true); + } + private hydrateObservations(directory: string[], records: ObservationRecord[]): WebObservation[] { + const sources = new Map(); + return records.map(record => hydrateObservation(record, digest => { + const cached = sources.get(digest); + if (cached !== undefined) return cached; + const text = this.getRecord([...directory, 'source-blobs', `${digest}.json`]); + if (text !== undefined) sources.set(digest, text); + return text; + })); + } + private readObservation(directory: string[], sequence: number): WebObservation | undefined { + const observation = this.getRecord([...directory, 'observations', `${sequence}.json`]); + return observation && this.hydrateObservations(directory, [observation])[0]; } listObservations(owner: string, runId: string): WebObservation[] { - const directory = [...this.runPath(owner, runId), 'observations']; - return bySequence(this.listRecords(directory).map(file => this.getRecord([...directory, file])!)); + const directory = this.runPath(owner, runId), observations = [...directory, 'observations']; + return this.hydrateObservations(directory, bySequence(this.listRecords(observations) + .map(file => this.getRecord([...observations, file])!))); } getObservation(owner: string, runId: string, sequence?: number): WebObservation | undefined { - if (sequence !== undefined) return this.getRecord([...this.runPath(owner, runId), 'observations', `${sequence}.json`]); - return this.listObservations(owner, runId).at(-1); + const directory = this.runPath(owner, runId); + if (sequence === undefined) sequence = this.listRecords([...directory, 'observations']) + .reduce((latest, file) => /^\d+\.json$/u.test(file) ? Math.max(latest, Number.parseInt(file, 10)) : latest, 0); + return sequence ? this.readObservation(directory, sequence) : undefined; } getTaskSource(owner: string, runId: string, taskId: string, version?: string, commit?: string): WebTaskSource | undefined { return this.listObservations(owner, runId).reverse().flatMap(item => item.sources) @@ -309,7 +352,8 @@ export class WebStorage { return this.recordsAfter([...this.runPath(owner, runId), 'actions'], after, limit); } listObservationsAfter(owner: string, runId: string, after: number, limit: number): WebObservation[] { - return this.recordsAfter([...this.runPath(owner, runId), 'observations'], after, limit); + const directory = this.runPath(owner, runId); + return this.hydrateObservations(directory, this.recordsAfter([...directory, 'observations'], after, limit)); } /** Numbered records after `after` in sequence order; reading stops at a record that cannot be parsed, to be read again later. */ listRecordsAfter(directory: string[], after: number, limit: number): T[] { return this.recordsAfter(directory, after, limit); } diff --git a/apps/web/worker.ts b/apps/web/worker.ts index 4443f163..fe1458ce 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -28,6 +28,7 @@ import { webAgentLibraryAccess } from './frozenLibrary'; import { runWebLibraryResearch } from './libraryResearch'; import { webResearchArguments } from './researchMode'; import { webProofMessageSink } from './proofJournal'; +import { createWebHostDisconnectWatchdog, webWorkerShutdownMs } from './workerDisconnect'; import { bindWebWorkerProfile, pinWebWorkerSession, prepareWebNativeProfile, webHarnessEnvironment, webHarnessExecutable, webHarnessModel, webProviderHarness } from './harness'; @@ -252,19 +253,39 @@ export function webSolverModules(request: WorkerInput, } } }; } -async function main() { +async function main(watchdog: ReturnType, controlledStdin: boolean) { let bytes = 0; const chunks: Buffer[] = []; - for await (const chunk of process.stdin) { - bytes += chunk.length; + // Legacy callers send a single JSON document to EOF. The runner can keep stdin + // open on compatible images, framing the request with a newline and then sending heartbeats. + const stdin = process.stdin[Symbol.asyncIterator](); + if (controlledStdin) watchdog.heartbeat(); + for (;;) { + const { value, done } = await stdin.next(); + if (done) break; + const chunk = Buffer.from(value); + const newline = controlledStdin ? chunk.indexOf(10) : -1; + const input = newline === -1 ? chunk : chunk.subarray(0, newline); + bytes += input.length; if (bytes > 16 * 1024 * 1024) throw new Error('运行输入过大。'); - chunks.push(chunk); + chunks.push(input); + if (newline !== -1) { + watchdog.heartbeat(); + void (async () => { + try { + while (!(await stdin.next()).done) watchdog.heartbeat(); + } catch { /* A broken stdin pipe also ends the control stream. */ } + finally { watchdog.disconnect(); } + })(); + break; + } } const request = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))) as WorkerInput; const key = request.input.apiKey; const journalDirectory = process.env.THEOREMOS_WORKER_JOURNAL && fs.realpathSync(process.env.THEOREMOS_WORKER_JOURNAL); - const send = webProofMessageSink(process.stdout, key, journalDirectory + 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 workspaceRoot = process.env.THEOREMOS_WORKER_ROOT || '/work'; const directory = fs.mkdtempSync(path.join(workspaceRoot, 'run-')); let output = path.join(directory, 'result.json'); @@ -333,6 +354,7 @@ async function main() { { tools, hiddenRoots: [root, buildState, ...(journalDirectory ? [journalDirectory] : [])] }); const completed = await runWebLibraryResearch({ directory, request, seed: receipt, output, continuationFile, libraryCatalog: webAgentLibraryAccess(environment.id), run: async round => { + watchdog.signal.throwIfAborted(); output = round.output; solverRunId = undefined; writeWebActiveRun({ webRunId: request.id, directory, output }, path.join(workspaceRoot, 'active-run.json')); @@ -363,7 +385,7 @@ async function main() { ...(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'] : []), - '--evaluator-timeout-seconds', round.limits.maxRunSeconds === 0 ? '0' : '120'], root, modules); + '--evaluator-timeout-seconds', round.limits.maxRunSeconds === 0 ? '0' : '120'], root, modules, watchdog.signal); sampleArtifact(); await capturePending; await capture(true); @@ -374,7 +396,9 @@ async function main() { const report = Object.fromEntries(['schema', 'runId', 'problemId', 'status', 'solution_commit', 'solver_ready_receipt_valid', 'completion_signal_valid', 'evaluator', 'turns', 'solveWallMs', 'solveExecutionMs', 'solveWaitingMs', 'usage', 'winningWorker', 'workers', 'teamContributions', 'reason', 'tokenBudget', 'libraryResearch', 'libraryUsage'].filter(field => Object.hasOwn(raw, field)).map(field => [field, raw[field]])); - const failure = classifyWebResult(raw); + const disconnected = watchdog.signal.aborted && raw.status !== 'evaluated_passed'; + if (disconnected) report.reason = 'math_host_disconnected'; + const failure = disconnected ? { kind: 'network', reason: 'math_host_disconnected' } : classifyWebResult(raw); if (failure) report.failure = failure; const stopReason = webIncompleteReason(raw, request.input); if (stopReason) report.stopReason = stopReason; @@ -396,9 +420,12 @@ async function main() { winningWorker: raw.winningWorker, state, artifact: latestArtifact }); send({ type: 'result', result: { status: String(raw.status || 'runtime_error'), proof, report } }); } catch (error) { + clearInterval(artifactTimer); + clearInterval(observationTimer); await capturePending; await capture(true); - send({ type: 'error', message: '运行未能完成。请检查 Lean 原题、模型服务配置与隔离环境。', failure: classifyWebError(error) }); + send({ type: 'error', message: '运行未能完成。请检查 Lean 原题、模型服务配置与隔离环境。', + failure: watchdog.signal.aborted ? { kind: 'network', reason: 'math_host_disconnected' } : classifyWebError(error) }); process.exitCode = 1; } finally { clearInterval(artifactTimer); @@ -409,8 +436,22 @@ async function main() { } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { - main().catch(() => { + const controlledStdin = process.env.THEOREMOS_WORKER_CONTROL === '1'; + const graceMs = Number(process.env.THEOREMOS_WORKER_DISCONNECT_GRACE_MS); + let forceExit: ReturnType | undefined; + const watchdog = createWebHostDisconnectWatchdog(process.stdout, { + ...(Number.isSafeInteger(graceMs) && graceMs > 0 && graceMs <= 2_147_483_647 ? { graceMs } : {}), + // The normal abort unwinds the solver and records the latest evidence first. + onAbort: () => { forceExit = setTimeout(() => process.exit(1), webWorkerShutdownMs); }, + }); + main(watchdog, controlledStdin).catch(() => { process.stdout.write(JSON.stringify({ type: 'error', message: '运行输入无效或环境无法初始化。' }) + '\n'); process.exitCode = 1; + }).finally(() => { + watchdog.stop(); + clearTimeout(forceExit); + if (controlledStdin) process.stdin.destroy(); + // Journal writes finished above. A stale attach pipe must not keep the worker alive. + if (watchdog.signal.aborted) process.exit(process.exitCode); }); } diff --git a/apps/web/workerBridge.ts b/apps/web/workerBridge.ts index 280b285b..03f1daa1 100644 --- a/apps/web/workerBridge.ts +++ b/apps/web/workerBridge.ts @@ -18,6 +18,7 @@ import type { WebCheckReceipt, WebCommand, WebCommandResult, WebObservation, Web import type { WorkerMessage } from './shared'; import { projectWebDeclarationArtifacts } from './declarationArtifacts'; import { projectWebNativeTeam } from './nativeTeamObservation'; +import { compactObservation, type WorkerObservationFrame } from './observationSources'; export const webActiveRunFile = '/work/active-run.json'; const activeRunSchema = z.object({ schema: z.literal('theorem-os.web-active-run.v1'), @@ -187,12 +188,14 @@ export function createWebWorkerBridge(options: { webRunId: string; output: string; directory: string; apiKey?: string; /** The host authorizes one transition; directory stays fixed while output points at the new round. */ libraryRestart?: LibraryRestart; - onMessage?(message: WorkerMessage): void; + onMessage?(message: WorkerMessage, frame?: WorkerObservationFrame): void; }) { const directory = fs.realpathSync(options.directory), metaFile = path.join(directory, 'web-bridge.json'); if (!childOf(directory, path.resolve(options.output))) throw new Error('web_bridge_output_outside_run'); if (options.libraryRestart && (!Number.isSafeInteger(options.libraryRestart.round) || options.libraryRestart.round < 1 || !options.libraryRestart.previousSolverRunId)) throw new Error('web_bridge_run_identity_changed'); + // Each new bridge starts with a self-contained frame. Retain only the previous frame's digests. + let emittedSources = new Set(); async function capture(input: { includeCatalog?: boolean; force?: boolean } = {}) { const messages: WorkerMessage[] = []; const result = await withMathRuntimeLease({ lockPath: path.join(directory, 'web-bridge.lock'), flockExecutable: '/usr/bin/flock' }, async lease => { @@ -264,12 +267,24 @@ export function createWebWorkerBridge(options: { if (input.includeCatalog && !catalog && fs.existsSync(catalogFile)) { catalog = validateTheoremKnowledge(JSON.parse(readMathText(catalogFile, maxMessageBytes))); } - lease.assertHeld(); writeMathJsonDurable(metaFile, meta); + lease.assertHeld(); + if (!previous || canonicalMathJson(previous) !== canonicalMathJson(meta)) writeMathJsonDurable(metaFile, meta); if (changed || input.force) messages.push({ type: 'observation', observation }); if (catalog) messages.push({ type: 'catalog', catalog }); return { observation, ...(catalog ? { catalog } : {}) }; }); - for (const message of messages) options.onMessage?.(message); + for (const message of messages) { + if (!options.onMessage) break; + if (message.type !== 'observation') { options.onMessage(message); continue; } + const current = new Set(); + const sourceBlobs: Record = {}; + const observation = compactObservation(message.observation, (digest, source) => { + current.add(digest); + if (!emittedSources.has(digest)) sourceBlobs[digest] = source; + }); + options.onMessage(message, { type: 'observation', observation, sourceBlobs }); + emittedSources = current; + } return result; } return { capture }; diff --git a/apps/web/workerDisconnect.ts b/apps/web/workerDisconnect.ts new file mode 100644 index 00000000..be6cb9c0 --- /dev/null +++ b/apps/web/workerDisconnect.ts @@ -0,0 +1,41 @@ +import type { EventEmitter } from 'node:events'; + +export const webWorkerDisconnectGraceMs = 30_000; +export const webWorkerHeartbeatMs = 5_000; +export const webWorkerShutdownMs = 20_000; + +export function createWebHostDisconnectWatchdog(output: Pick, + options: { graceMs?: number; onAbort?(): void } = {}) { + const controller = new AbortController(); + let timer: ReturnType | undefined; + let disconnected = false, stopped = false; + const graceMs = options.graceMs ?? webWorkerDisconnectGraceMs; + const arm = () => { + timer = setTimeout(() => { + timer = undefined; + controller.abort('host_disconnected'); + options.onAbort?.(); + }, graceMs); + }; + const disconnect = () => { + disconnected = true; + if (!stopped && !timer && !controller.signal.aborted) arm(); + }; + output.on('error', disconnect); + output.on('close', disconnect); + return { + signal: controller.signal, + disconnect, + heartbeat() { + if (stopped || disconnected || controller.signal.aborted) return; + clearTimeout(timer); + arm(); + }, + stop() { + stopped = true; + clearTimeout(timer); + output.off('error', disconnect); + output.off('close', disconnect); + }, + }; +} diff --git a/bin/math.ts b/bin/math.ts index 38107578..fbe00af3 100644 --- a/bin/math.ts +++ b/bin/math.ts @@ -24,6 +24,8 @@ const commands: Readonly> = { 'check-lean': 'scripts/mathematics/checkLean.ts', 'proof-search': 'scripts/mathematics/proofSearch.ts', 'research-observe': 'scripts/mathematics/researchObserve.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', @@ -52,7 +54,7 @@ if (!command || ['help', '--help', '-h'].includes(command)) { doctor Check local tools, login and sandbox permissions example Replay or solve a small Lean tutorial without Mathlib component Create and check a replaceable search component - run Run or resume an isolated mathematics proof + run Run or resume an isolated mathematics proof (optional --portfolio-exploration) batch Run prepared problems concurrently in separate processes bootstrap-imo Prepare an IMO2026 proof workspace bootstrap-lean-eval Prepare a public Lean-Eval workspace @@ -65,6 +67,8 @@ if (!command || ['help', '--help', '-h'].includes(command)) { 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 + plan-validate Check a cooperative Lead plan and report field-level issues + plan-apply Save a validated cooperative Lead plan for host intake 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 diff --git a/docs/codex-skill-runtime.md b/docs/codex-skill-runtime.md index 03025297..51ec0b74 100644 --- a/docs/codex-skill-runtime.md +++ b/docs/codex-skill-runtime.md @@ -85,9 +85,9 @@ 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. Its `theoremos_team` host interface exposes only `finish`, `history`, `inspect`, `inspect-research` and `adopt` to Lead; members see only `yield`, `history`, `inspect`, `inspect-research` and `submit`. These are seven distinct mathematical operations. 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/evidence identities after their writer process stops. +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`, `submit` and `submit_helpers`. 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. -Historical host-tool runs retain their role-specific schemas: Lead sees `spawn`, `assign`, `amend`, `finish`, `coordinate`, `resume`, `cancel`, `publish`, `message`, `poll`, `wait`, `history`, `inspect`, `inspect-research`, `adopt` and `stop`; children see `progress`, `message`, `poll`, `wait`, `history`, `inspect`, `inspect-research`, `yield` and `submit`. `budget` and its parameters are available only with an explicitly configured finite token or turn allowance. Descriptions and parameters follow those capabilities, and the host independently rejects unauthorized calls. The pinned [parallel-work reference](../skills/theoremos-research/references/parallel-work.md) documents both transports. Historical spawn/assign queue work and return a task ID. Poll/wait deliver individual arrivals and a durable cursor while other children 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. +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. Historical `coordinate` and `publish` remain optional note and summary operations. Saved coordination decisions, observations and presentations remain readable historical records; they do not gate tools, create collaboration stages or schedule turn handoffs. @@ -210,7 +210,7 @@ In this separate read-only investigation mode, stock Codex V1 and V2 spawn inher ## Web workflow -Web proof requests distinguish a Codex native team from host-managed cooperative workers. Selecting the native option saves `nativeTeamCapacity` (2–8, including Lead; Web default 3) and starts one host Lead with `--research-mode skill --skill-delegation team --skill-max-agents N`. It requires a Codex provider and a worker image labeled `org.theoremos.native-agent-control=v1` after its backend passes the image's capability check. Older images continue to support their existing modes; a native-team request does not fall back to host coordination. Browser requests select neither host binaries nor CLI profiles. Building source does not upgrade a deployed image or a saved run. +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. If native transport startup fails before the Lead starts research, the same team can restart with `theoremos_team` host tools and records the transport change for resume. Existing cooperative requests retain their plan and approval workflow. Browser requests select neither host binaries nor CLI profiles. 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. @@ -219,7 +219,7 @@ The skill view displays the actual researcher and independent declaration source | Work | Verified result | Remaining boundary | | --- | --- | --- | | Agent-organized team | Local protocol processes exercise two isolated proof writers, independent arrivals, two Lead thread resumes and checked adoption of both helpers. The actual CLI path prepares Lead/child dependencies and environments, independently accepts all original targets through S3 and saves the final result. Manager/proof tests cover follow-up tasks, messages, child-to-child reuse, shared budgets and interrupted integration recovery before another writer starts. | Protocol peers control responses; no paid-model team campaign, deployment or comparative success-rate result is claimed. | -| Native team tool transport | An installed Codex app-server with an isolated profile advertises all 15 Lead operations and their operation-specific argument contracts to a local Responses endpoint, executes a returned team function call through the real manager, and sends the host result in its next request. | The endpoint supplies fixed replies. This verifies native transport, not a real model choosing to delegate. | +| Native team tool transport | An installed Codex app-server with an isolated profile advertises the Lead operations and their argument contracts to a local Responses endpoint, executes a returned team function call through the manager, and sends the host result in its next request. | The local endpoint supplies fixed replies. | | 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. | diff --git a/scripts/build-agent-tools.ts b/scripts/build-agent-tools.ts index c9b6ff56..2e6c697e 100644 --- a/scripts/build-agent-tools.ts +++ b/scripts/build-agent-tools.ts @@ -16,6 +16,7 @@ const agentToolCommands = { declarations: 'readDeclarations.ts', hub: 'huggingMath.ts', 'research-observe': 'researchObserve.ts', 'proof-search': 'proofSearch.ts', + 'plan-validate': 'planValidate.ts', 'plan-apply': 'planApply.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/mathematics/planApply.ts b/scripts/mathematics/planApply.ts new file mode 100644 index 00000000..055c9b26 --- /dev/null +++ b/scripts/mathematics/planApply.ts @@ -0,0 +1,3 @@ +import { runPlanCommand } from './planCommand'; + +runPlanCommand('plan-apply', process.argv.slice(2)); diff --git a/scripts/mathematics/planCommand.ts b/scripts/mathematics/planCommand.ts new file mode 100644 index 00000000..49d0d584 --- /dev/null +++ b/scripts/mathematics/planCommand.ts @@ -0,0 +1,47 @@ +import fs from 'node:fs'; +import { parseArgs } from 'node:util'; +import { MAX_RESEARCH_NOTES_BYTES } from '../../src/solver/deliveries'; +import { applyCooperationPlanFile, validateCooperationPlanFile } from '../../src/solver/planTool'; + +function readStandardInput(): string { + const bytes = Buffer.alloc(MAX_RESEARCH_NOTES_BYTES + 1); + let length = 0; + while (length < bytes.length) { + const count = fs.readSync(0, bytes, length, bytes.length - length, null); + if (!count) break; + length += count; + } + if (length > MAX_RESEARCH_NOTES_BYTES) throw new Error('Keep the plan JSON at or below 1 MB.'); + 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]`; + let field = 'arguments'; + try { + const { values } = parseArgs({ args, options: { + file: { type: 'string' }, workspace: { type: 'string' }, worktree: { type: 'string' }, + 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 for host intake.' : 'Report validation issues.') })); + return; + } + if (values.worktree && values.workspace) throw new Error('Choose --workspace or --worktree.'); + const workspace = values.workspace ?? values.worktree ?? process.cwd(); + let input: { workspace: string; text: string } | { workspace: string; file: string }; + if (!values.file || values.file === '-') { + field = 'stdin'; + input = { workspace, text: readStandardInput() }; + } else input = { workspace, file: values.file }; + const result = command === 'plan-apply' ? applyCooperationPlanFile(input) : validateCooperationPlanFile(input); + console.log(JSON.stringify(result)); + if (!result.ok) process.exitCode = 1; + } catch (error) { + console.log(JSON.stringify({ ok: false, error: 'math_plan_cli_input_invalid', + issues: [{ path: field, message: error instanceof Error ? error.message : usage }] })); + process.exitCode = 1; + } +} diff --git a/scripts/mathematics/planValidate.ts b/scripts/mathematics/planValidate.ts new file mode 100644 index 00000000..b9fe057b --- /dev/null +++ b/scripts/mathematics/planValidate.ts @@ -0,0 +1,3 @@ +import { runPlanCommand } from './planCommand'; + +runPlanCommand('plan-validate', process.argv.slice(2)); diff --git a/skills/theoremos-research/SKILL.md b/skills/theoremos-research/SKILL.md index b746b6ce..c727dde5 100644 --- a/skills/theoremos-research/SKILL.md +++ b/skills/theoremos-research/SKILL.md @@ -28,6 +28,7 @@ Use these references when the work calls for them: - [Literature](references/literature.md): when a proof idea or missing result may be found in external sources. - [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. diff --git a/skills/theoremos-research/references/cooperation.md b/skills/theoremos-research/references/cooperation.md index dab1f19e..7cc64fc5 100644 --- a/skills/theoremos-research/references/cooperation.md +++ b/skills/theoremos-research/references/cooperation.md @@ -8,7 +8,7 @@ The current assignment and `.scratch/theoremos-help.md` provide exact paths, int Append complete newline-terminated JSON events to the current delivery log. A missing log is normal; create it by appending. Preserve earlier events. In an assignment-scoped task log, omitted `id`, `taskId`, `taskDigest` and `kind` are supplied by the host (`kind` defaults to `progress`); supplied task identity must match the assignment. Explicit event and task IDs use `[A-Za-z0-9_-]{1,64}`. -Edit only assigned source paths. Preserve other seed proofs and frozen declaration interfaces, kinds, imports, options, scopes and source order. A goal cannot depend on a later original goal in the same file; put a shared helper before its consumers instead of moving original declarations. Do not edit host state, `COOPERATION.json`, generated help, Skills, configuration or receipts. Do not run `git add` or `git commit`; the host freezes saved sources. Notes, checkpoint receipts, local diagnostics and peer messages remain evidence rather than proof acceptance. +Edit only assigned source paths. Preserve other seed proofs and frozen declaration interfaces, kinds, options, scopes and source order. Keep all existing imports. When proving in a Mathlib project, you may add `import Mathlib` or any pinned `Mathlib.*` import in assigned files without creating import cycles. A goal cannot depend on a later original goal in the same file; put a shared helper before its consumers instead of moving original declarations. Do not edit host state, `COOPERATION.json`, generated help, Skills, configuration or receipts. Do not run `git add` or `git commit`; the host freezes saved sources. Notes, checkpoint receipts, local diagnostics and peer messages remain evidence rather than proof acceptance. ## Lead plan @@ -20,7 +20,7 @@ Leave Lean sources unchanged and return a plan without running Lean diagnostics; Replace dispatch values from the assignment; omit `dispatchNonce` if none is supplied. Replace the empty `tasks` array with the complete graph. The first plan covers every original target exactly once. Keep checked task contracts and active unrelated assignments stable. Publish once per dispatch, save concise route notes and return promptly without polling approval or copying the published graph into other responses. -When returning without live publication, save the graph in one `math-plan` JSON fence in worktree-root `RESEARCH.md`. Include any [required decision fields](#required-lead-decisions) in the same plan object. +When returning without live publication, save the graph or revision as a JSON file with any [required decision fields](#required-lead-decisions). From the Lead worktree, run `theorem-os plan-validate --file .scratch/plan.json` to see field-level issues, then `theorem-os plan-apply --file .scratch/plan.json` to replace the plan block in `RESEARCH.md` atomically. Both commands also read JSON from stdin. `planVersion` in the result fingerprints the validated draft. Use `COOPERATION.json.planVersion` as the accepted `baseVersion` for a revision. Return after saving so the host can check the draft against live state. For `idleWorkers` with `m3-no-ready`, `dependency-blocked` or `m5-no-selection`, inspect M3 readiness, role/owner and saved-assignment pins. Publish an executable revision, name the concrete running dependency when waiting, or explicitly pause the route. Returning an unchanged accepted graph does not resolve that continuous idle episode. @@ -52,6 +52,10 @@ Revise the accepted graph with top-level fields instead of repeating it: An existing task upsert merges only supplied fields; `null` deletes a field. Changing `kind` replaces the whole task, and a new ID requires its complete definition. Unlisted tasks, groups and proof routes remain. Supplying `groups` or `proofRoutes` replaces that entire list. Do not mix `tasks` with `upsert`/`remove`. Decision-only revisions may use `upsert:[]`. +Start with the shared foundation. When several goals use the same measure change, algebraic identity, or comparison estimate, assign that input as one or more small typed lemmas. Connect the consumers by dependency and land the shared results before dispatching the large goal proofs. Delegate calculations and route probes to workers and use the planning turn to decide and publish the graph. + +For a refuted route or group, add `"retireRoutes":[{"routeId":"...","reason":"...","evidenceRefs":["..."]}]` to the current plan revision. Record the failed claim and its evidence. The host stops unfinished work on the branch and retains the reason in `COOPERATION.json`. Read retired routes before assigning work. If new evidence changes the inference, describe it explicitly and propose a new route with a distinct ID. + Use the current accepted base and dispatch; stale revisions are rejected. Revise a contract only for a mathematical change: changing prose or `revision` is not new input and can invalidate saved work. Read the host-synced graph by task ID instead of rewriting it wholesale. ### Optional task forms @@ -63,6 +67,14 @@ Use the current accepted base and dispatch; stale revisions are rejected. Revise ## Proof delivery +A proof or research worker can publish standalone helpers before finishing its assignment. Save the helpers in an owned Lean file, before the first declaration that uses them. Append a line to the current assignment log: + +```json +{"kind":"helpers","declarations":[{"file":"Submission.lean","name":"MyNamespace.helper"}],"summary":"The comparison estimate used by the main argument."} +``` + +The host snapshots the saved files and independently checks the helpers and their same-file helper dependencies. Keep the original target and its unfinished body intact. The host publishes checked signatures with their canonical commit. Other workers can inspect that commit or reuse the helpers in their next seeded worktree. Publishing a helper does not complete the assignment. + Save the assigned exact declaration in its allowed proof file, then append: ```json diff --git a/skills/theoremos-research/references/parallel-work.md b/skills/theoremos-research/references/parallel-work.md index 535bde2b..fee073f1 100644 --- a/skills/theoremos-research/references/parallel-work.md +++ b/skills/theoremos-research/references/parallel-work.md @@ -133,6 +133,8 @@ 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_helpers` with `summary` and the standalone declarations you want to share. Supply the same declaration fields as `submit`. 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. + 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. 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. 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. diff --git a/skills/theoremos-research/references/portfolio.md b/skills/theoremos-research/references/portfolio.md new file mode 100644 index 00000000..e43cb13a --- /dev/null +++ b/skills/theoremos-research/references/portfolio.md @@ -0,0 +1,11 @@ +# Portfolio exploration + +Use this stage when the host assigns bounded scouting before formal proof work. Read the frozen statement and record a route that makes its hardest inference smaller. Save a short blueprint, key transformations, and exact candidate interfaces for small shared lemmas. Keep Lean sources unchanged. Use scratch files for reproducible calculations and small Lean API probes. + +- `structural-symmetry` looks for invariant quantities, coordinate changes, symmetries, convexity, and monotone reductions. +- `explicit-constructive` looks for formulas, rational bounds, witnesses, and direct constructions. +- `falsification-obstruction` tests fragile intermediate claims, aiming for explicit counterexamples, degeneracy, or combinatorial blowup. Use a focused Python, PARI/GP, SymPy, or finite constraint probe when it can decide a step. + +Report `proposed` for a viable blueprint, `refuted` when you can name the exact failed claim and provide a concrete witness or obstruction, and `inconclusive` when an experiment or search has not settled it. Include the assumptions, reproduction command, result, and saved probe references. State which route ID the evidence concerns. Numerical approximations may motivate a test. Give exact bounds or a reproducible witness before retiring a route. + +The gate selects a primary route and may keep one backup. Start proof work with the primary route's shared foundation lemmas and mark the consumer of each. Keep the persisted reasons and evidence for retired routes available to the team. Reconsider a dead end only when new evidence addresses its recorded obstruction. All scout reports and gate decisions are advisory. The host verifies every proof against the frozen Lean problem. diff --git a/skills/theoremos-research/references/team-roles.md b/skills/theoremos-research/references/team-roles.md index 9349cca4..aba67778 100644 --- a/skills/theoremos-research/references/team-roles.md +++ b/skills/theoremos-research/references/team-roles.md @@ -48,6 +48,10 @@ A member reads the selected sections and the current assignment before working. Own a connected proof effort that closes the frozen original targets. Divide work by the mathematical result or formal interface needed, not by agent names, tactics or coordinate systems. Keep one owner per active proof obligation, including your own work. Use specialist results as inputs to the shared proof; your own research and Lean work advances their consumer, the connecting argument or another unassigned gap. +If several goals share a measure change, algebraic construction, or comparison estimate, commission independent, small typed lemmas for that foundation first. Land and reuse them before you dispatch the large consumer proofs. Delegate exploratory computation and use the planning turn to review evidence, choose a route, and publish assignments. Give host tool tasks a `routeId`. For native assignments, use `Route: ROUTE_ID` on the first line, then the usual profile and objective. When concrete evidence refutes a route, use `retire_route` with its ID, scoped reason, and evidence references so its unfinished work stops immediately. + +Lead and members can call `route_summary` for a compact snapshot before changing direction or reusing a result. Pass `routeId` to focus the assignments and checked deliveries, or set `includeRetired: false` to hide retired branches. The snapshot includes shared landed helper signatures. Use `history` for full task text and `inspect` for exact declarations and proof evidence. + Look for useful complementary work after reading the statement and necessary definitions, before deriving the complete solution; see [start and reassess](parallel-work.md#start-and-reassess). A missing argument, library application, boundary claim or route-discriminating question is enough to assign; an exact helper type can be negotiated with the member. Avoid solving a gap merely to make it assignable. If a direct proof is already clear and no useful independent question remains, check it without filling agent slots. Reassess ownership when a failed probe, library-interface uncertainty or substantial new gap creates useful work. No opening acknowledgment or fixed sequence of collaboration decisions is required. Start the member's message with its specialty, for example `Profiles: prover` for a checked helper, `researcher` for a missing argument or `library-scout` for a library interface. Add a domain profile when its specific knowledge helps. The host selects `lead` for you alone. A useful split might give the member one existence lemma while you show how its witness implies the original conclusion. Send the hypotheses and expected output, identify the inference you retain, and let the member choose its proof. Ask for the first usable finding, probe result or blocker as soon as it is available. Independent declarations that answer the assignment should be saved, submitted and returned for host checking before optional extensions. An investigation can instead return an advisory finding, exact interface or blocker. diff --git a/src/math/verifier.ts b/src/math/verifier.ts index cb70648d..2d325bac 100644 --- a/src/math/verifier.ts +++ b/src/math/verifier.ts @@ -3,7 +3,7 @@ import { createLeanDiagnosticCapture, leanDiagnosticPreview, renderLeanDiagnosti import type { LeanDiagnosticMessage } from './leanTypes'; type ProcessResult = MathProcessResult & { sandboxBackend?: SandboxBackend; sourceDiagnostics?: { stdout?: LeanDiagnosticMessage; stderr?: LeanDiagnosticMessage } }; -import { declarationHashes, inspectLeanSource } from './leanSource'; +import { declarationHashes, inspectLeanDeclarationRegions, inspectLeanSource, inspectScopedLeanDeclarations } from './leanSource'; export { hashMathFormalSourceDeclaration, inspectLeanDeclarationRegions, inspectLeanDeclarations, inspectLeanSource } from './leanSource'; export type { MathematicsLeanSourceDeclaration } from './leanSource'; @@ -73,6 +73,8 @@ export type MathematicsVerifierExecutionOptions = { prepareLocalDependencies?: boolean; /** Restrict source staging to construction files while preserving verifier source checks. */ constructionSourcesOnly?: boolean; + /** Host helper checks bind named declarations while allowing unrelated holes in the same committed file. */ + checkDeclarationsInDraft?: boolean; /** Exact closed type checked outside the source section, inline or after a module import. */ expectedDeclarationType?: string; expectedDeclarationTypes?: Readonly>; @@ -211,6 +213,7 @@ type PreparedFile = { directProofReferences?: Map; proofHash: string; inspection: Pick; + declarationInspections?: Map; items: PreparedItem[]; }; @@ -1877,7 +1880,8 @@ const prepareLeanDeclarationQuery = async ( dependencyCandidates?: readonly string[]; referenceModules?: readonly { module: string; file: string }[]; directProof?: boolean; - }> + }>, + privateMarkers = false ): Promise => { const theoremNameSet = new Set(); for (const item of items) { @@ -1891,7 +1895,7 @@ const prepareLeanDeclarationQuery = async ( ); const queryAbsolutePath = path.join(verificationProjectRoot, ...queryRelativePath.split('/')); const theoremQueries = theoremNames.map((name) => { - const markerId = mathDigest(name).slice(0, 16); + const markerId = privateMarkers ? crypto.randomBytes(8).toString('hex') : mathDigest(name).slice(0, 16); return { name, localName: name.split('.').at(-1), @@ -2272,7 +2276,7 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat name && !file.declarationHashes.has(name) && !file.declarationHashes.has(localDeclarationName(name))); const declarationMismatchItems = file.items.filter(item => item.theoremName && item.expectedSourceDeclarationHash && declarationNamed(file.sourceDeclarationHashes, item.theoremName) !== item.expectedSourceDeclarationHash); - const verifiableItems = file.items.filter(item => + let verifiableItems = file.items.filter(item => !missingDeclarationItems.includes(item) && !declarationMismatchItems.includes(item)); for (const item of missingDeclarationItems) reject(`The requested theorem declaration was not found in ${file.relativeProofPath}: ${item.theoremName}`, [item]); @@ -2280,20 +2284,34 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat reject(`The theorem declaration in ${file.relativeProofPath} does not match the immutable formal statement: ${item.theoremName}`, [item]); if (verifiableItems.length === 0) return; - const draftAccepted = - file.inspection.sorryCount === 0 && - file.inspection.admitCount === 0 && - file.inspection.axioms.length === 0; - emit('check.draft_checked', { - proofPath: file.relativeProofPath, - status: draftAccepted ? 'accepted' : 'rejected', - ...file.inspection, - }); - if (!draftAccepted) { - const error = - file.inspection.sorryCount > 0 || file.inspection.admitCount > 0 - ? 'Proof source contains sorry or admit.' - : `Proof source declares explicit axioms: ${file.inspection.axioms.join(', ')}.`; + const checkDraft = (inspection: PreparedFile['inspection']) => { + const accepted = !inspection.sorryCount && !inspection.admitCount && !inspection.axioms.length; + emit('check.draft_checked', { proofPath: file.relativeProofPath, status: accepted ? 'accepted' : 'rejected', ...inspection }); + return accepted; + }; + if (options.checkDeclarationsInDraft && !file.inspection.axioms.length) { + const positions = new Map(inspectScopedLeanDeclarations(file.source).map(item => [item.qualifiedName, item.startOffset])); + const regions = new Map(inspectLeanDeclarationRegions(file.source).map(region => [region.startOffset, region])); + const inspections = file.declarationInspections = new Map(); + verifiableItems = verifiableItems.filter(item => { + const start = item.theoremName ? positions.get(item.theoremName) : undefined; + const region = start === undefined ? undefined : regions.get(start); + if (!item.theoremName || !item.expectedSourceDeclarationHash || !region) { + reject('A helper check in a draft requires one exact source-bound declaration name.', [item]); + return false; + } + const inspection = inspectLeanSource(file.source.slice(region.startOffset, region.endOffset)); + inspections.set(item.theoremName, inspection); + if (!checkDraft(inspection)) { + reject('Helper source contains sorry or admit.', [item]); + return false; + } + return true; + }); + if (verifiableItems.length === 0) return; + } else if (!checkDraft(file.inspection)) { + const error = file.inspection.sorryCount || file.inspection.admitCount ? 'Proof source contains sorry or admit.' + : `Proof source declares explicit axioms: ${file.inspection.axioms.join(', ')}.`; reject(error, verifiableItems); return; } @@ -2304,7 +2322,8 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat const localModules = (options.prepareLocalDependencies || options.collectDeclarationReferences) && lakeFile ? mathLocalModuleGraph(verificationProjectRoot, file.relativeProofPath) : undefined; const helperModule = - localModules && (options.expectedDeclarationType || options.expectedDeclarationTypes || options.forbiddenImportModules || options.dependencyCandidates || options.collectDeclarationReferences) + localModules && (options.checkDeclarationsInDraft || options.expectedDeclarationType || options.expectedDeclarationTypes || + options.forbiddenImportModules || options.dependencyCandidates || options.collectDeclarationReferences) ? localModules!.at(-1)!.module : undefined; if (helperModule && !/^[A-Za-z_][A-Za-z0-9_']*(?:\.[A-Za-z_][A-Za-z0-9_']*)*$/u.test(helperModule)) @@ -2326,7 +2345,8 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat ? localModules ?? [{ module: '', file: file.relativeProofPath }] : undefined, directProof: options.collectDirectProofReferences, } - : undefined + : undefined, + options.checkDeclarationsInDraft ); const verificationPath = declarationQuery?.relativePath || file.relativeProofPath; let processResult: ProcessResult; @@ -2539,6 +2559,7 @@ async function checkManyFormalVerificationsUnbounded( const checkedAt = Date.now(); for (const item of selectedItems) { const theoremName = item.theoremName; + const inspection = (theoremName && file.declarationInspections?.get(theoremName)) || file.inspection; const base: ResultBase = { targetCommit, statementHash: item.statementHash, @@ -2564,8 +2585,8 @@ async function checkManyFormalVerificationsUnbounded( statementBinding: 'caller-bound-to-committed-declaration', toolchain, goalsRemaining: status === 'kernel_verified' ? 0 : 1, - sorryCount: file.inspection.sorryCount, - admitCount: file.inspection.admitCount, + sorryCount: inspection.sorryCount, + admitCount: inspection.admitCount, axioms: (theoremName && declarationNamed(file.axiomDependencies, theoremName)) || file.inspection.axioms, checkedAt, checkId: item.checkId, @@ -3005,6 +3026,7 @@ async function buildFormalVerificationCacheKey( targetCommit: resolvedTarget, verifierCommandPath: options.verifierCommandPath || null, prepareLocalDependencies: options.prepareLocalDependencies ?? false, + ...(options.checkDeclarationsInDraft ? { checkDeclarationsInDraft: true } : {}), expectedDeclarationType: options.expectedDeclarationType ?? null, expectedDeclarationTypes: options.expectedDeclarationTypes ?? null, forbiddenImportModules: options.forbiddenImportModules ?? [], diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 92b4c31e..3c78f45c 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -200,7 +200,12 @@ class CodexRpc { this.pending.delete(message.id); clearTimeout(call.timer); const code = typeof error?.code === 'number' && Number.isSafeInteger(error.code) ? error.code : 'invalid_code'; - if (error) call.reject(new Error(`math_codex_rpc_failed:${code}:${call.method}`, + const startup = call.method === 'thread/start' || call.method === 'initialize' || + call.method.startsWith('theoremos/agentControl/'); + const authFailure = startup && (code === 401 || code === 403 || typeof error?.message === 'string' && + /\b(?:authentication|unauthorized|forbidden|api[ _-]?key|credential(?:s)?|login required)\b/iu.test(error.message)); + if (authFailure) call.reject(new Error('math_codex_authentication_failed')); + else if (error) call.reject(new Error(`math_codex_rpc_failed:${code}:${call.method}`, call.method.startsWith('theoremos/agentControl/') ? { cause: error } : undefined)); else call.resolve(result!); } @@ -1202,5 +1207,11 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise return rpc.confirmStopped(); }, }; - } catch (error) { await closeSession(); options.signal?.throwIfAborted(); throw error; } + } catch (error) { + await closeSession(); + options.signal?.throwIfAborted(); + if (nativeControl && processLaunch && await rpc.confirmStopped().then(receipt => receipt.status !== 'stopped')) + throw new Error('math_codex_startup_shutdown_unconfirmed'); + throw error; + } } diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index de2ef3a5..7c988c32 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -10,7 +10,7 @@ import { bindLeanPackages } from '../math/leanDiagnostics'; import type { SolverRunState } from './archive'; import type { WorkerAccess } from './research'; import type { SolverModules } from './modules'; -import { git, commitSolverSources, solverSourceConstraints, SolverSourceError } from './problem'; +import { git, commitSolverSources, solverSourceConstraints, SolverSourceError, withSolverWorktree } from './problem'; import { solverSourceFeedback } from './feedback'; import { prepareResearchSkill } from './researchSkill'; import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext'; @@ -30,7 +30,7 @@ import { ownedSourceDigest } from './cooperativeProof'; import { agentTeamWorkerSection } from './agentTeamContext'; import { saveAgentTeamResearchArtifact, inspectAgentTeamResearchArtifact } from './agentTeamResearch'; import { agentTeamChildAdmission, projectAgentTeamBudget } from './agentTeamBudget'; -import { agentTeamOverview, agentTeamTaskHistory } from './agentTeamViews'; +import { agentTeamOverview, agentTeamRouteSummary, agentTeamTaskHistory } from './agentTeamViews'; import { agentTeamProfileSelection, resolveNewMemberProfiles, resolveAgentTeamProfiles } from './agentTeamProfiles'; import { writeWorkerProject } from './workerProject'; import { agentTeamRequestSchema as request, agentTeamToolDefinition as teamTool, @@ -40,9 +40,23 @@ import type { ModelRequestGate } from '../runtime/modelRequest'; import { LeanEnvironmentHealthCheckError } from '../runtime/leanHealthCheck'; import { prepareAgentTeamWorkspace } from './agentTeamWorkspace'; import { AgentTeamNativeControl, nativeSpawnHistory, nativeTeamAssignmentMessage, type NativeTeamAcceptedChild, type NativeTeamSpawn } from './agentTeamNative'; +import { IncrementalHelperRejection, landVerifiedHelpers } from './incrementalHelpers'; +import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; +import { portfolioRouteIdSchema, type RetiredRoute, type routeRetirementSchema } from './routeControl'; -type LiveWorker = { session?: MathAgentSession; task: Promise; abort: AbortController; cancelledTaskId?: string; - admittedTurnId?: string; runSettled?: boolean }; +type LiveWorker = { session?: MathAgentSession; task: Promise; abort: AbortController; routeAbort: AbortController; + cancelledTaskId?: string; admittedTurnId?: string; runSettled?: boolean }; +const CHECKPOINT_CLOSE_GRACE_MS = 10_000; + +/** Native AgentControl carries an attributed message rather than a separate route field. */ +function nativeTaskRoute(message: string) { + const firstLine = message.trimStart().split('\n', 1)[0]!; + if (!/^Route\s*:/iu.test(firstLine)) return { message, routeId: undefined }; + const route = portfolioRouteIdSchema.safeParse(firstLine.slice(firstLine.indexOf(':') + 1).trim()); + const objective = message.trimStart().slice(firstLine.length).trimStart(); + if (!route.success || !objective) throw new NativeAgentControlInputError('math_team_native_route_invalid: Use Route: ROUTE_ID on the first line, followed by the task.'); + return { message: objective, routeId: route.data }; +} /** Check persisted process identities before preparing or reading recovered proof workspaces. */ export function assertAgentTeamProcessesStopped(state: SolverRunState) { @@ -65,12 +79,16 @@ function correctableProofFailure(error: unknown) { return error instanceof Error && /^math_agent_team_proof_(?:undeclared_source_change|declaration_missing|declaration_outside_ownership|import_removed)$/u.test(error.message); } +function teamTaskResearchSummary(task: AgentTeamTask) { + return task.summary ?? task.pauseRequested?.reason ?? task.cancelRequested?.reason ?? task.error ?? 'Research saved.'; +} + /** Mechanical execution of Agent decisions. Mathematical decomposition and adoption stay with Lead. */ export class AgentResearchTeam { readonly archive: AgentTeamState; readonly directory: string; private live = new Map(); - private readonly nativeControl?: AgentTeamNativeControl; + private nativeControl?: AgentTeamNativeControl; private readonly nativeIdle = new Map(); private readonly failedNominations: TeamFailureCache = new Map(); private readonly nativeStarts = new Map; @@ -88,6 +106,7 @@ export class AgentResearchTeam { executable: string; profile: string; signal: AbortSignal; maxAgents: number; maxTurns: number; maxTurnMs: number; maxTotalTokens: number; proofTimeoutMs?: number; remainingMs: () => number; prepareWorker?: (id: string, worktree: string) => Promise; + softSlice?: SoftSliceSettings; save: () => void; emit: (event: string, details?: Record) => void; exclusiveCheck: (operation: () => Promise) => Promise; }) { @@ -96,6 +115,10 @@ export class AgentResearchTeam { 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; @@ -108,7 +131,7 @@ export class AgentResearchTeam { admit: (worker, turnId) => { const live = this.live.get(worker.id); if (!live || live.runSettled || live.admittedTurnId && live.admittedTurnId !== turnId || - !worker.tasks.some(task => task.status === 'running') || worker.writerStopUnconfirmed) + !worker.tasks.some(task => task.status === 'running' && !task.cancelRequested) || worker.writerStopUnconfirmed) throw new Error('math_team_native_turn_not_dispatched:' + turnId); live.admittedTurnId = turnId; worker.native!.turnId = turnId; worker.native!.status = 'running'; @@ -122,6 +145,23 @@ export class AgentResearchTeam { 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 }; + } private get budgetControlsEnabled() { return this.input.maxTotalTokens > 0 || Number.isFinite(this.input.maxTurns); } setLeadSession(session?: MathAgentSession) { this.leadSession = session; @@ -153,7 +193,8 @@ export class AgentResearchTeam { return true; } const adoptions = this.archive.adoptions.filter(item => item.targetId === 'lead' && - ['queued', 'integrating'].includes(item.status)); + ['queued', 'integrating'].includes(item.status) && + this.archive.deliveries.find(delivery => delivery.id === item.deliveryId)?.kind !== 'helpers'); if (!adoptions.length) return false; if (!this.leadAdoptionCheckpoint) { this.leadAdoptionCheckpoint = true; @@ -166,8 +207,9 @@ export class AgentResearchTeam { private changed() { const { state } = this.input; - state.tokenBudget = buildTokenBudget(this.input.maxTotalTokens, [state, ...this.usageRecords], state.tokenBudget?.enforcement); - state.teamUsage = aggregateUsage([state, ...this.usageRecords]); + const records = [state, ...this.usageRecords, ...(state.portfolioExploration?.scouts ?? [])]; + state.tokenBudget = buildTokenBudget(this.input.maxTotalTokens, records, state.tokenBudget?.enforcement); + state.teamUsage = aggregateUsage(records); this.input.save(); for (const wake of this.waiters) wake(); } @@ -223,6 +265,7 @@ export class AgentResearchTeam { if (operation.agentId) this.worker(operation.agentId); return agentTeamTaskHistory(this.archive, operation); } + if (operation.operation === 'route_summary') return agentTeamRouteSummary(this.archive, operation); const key = canonicalMathJson([actor, context.threadId, context.turnId, context.callId]); const digest = mathDigest(canonicalMathJson(operation)); // Serializing mutations also prevents concurrent spawn/adoption calls from racing capacity or source checks. @@ -255,6 +298,69 @@ export class AgentResearchTeam { return worker; } + private occupiedAgentSlots() { + return this.archive.workers.filter(worker => { + const active = this.live.get(worker.id); + return worker.status !== 'stopped' || Boolean(active && !active.routeAbort.signal.aborted); + }).length; + } + + private assertRouteAvailable(routeId?: string) { + if (routeId && this.archive.retiredRoutes?.some(route => route.routeId === routeId)) + throw new Error('math_team_route_retired:' + routeId + ': Review the saved evidence and use a new route ID only for a materially revised route.'); + } + + private retireRoute(input: z.infer) { + const existing = this.archive.retiredRoutes?.find(route => route.routeId === input.routeId); + if (existing) return { ok: true, retiredRoute: existing, cancelledTaskIds: [], releasedAgentIds: [] }; + const retiredRoute: RetiredRoute = { ...input, retiredAt: Date.now(), source: 'lead' }; + (this.archive.retiredRoutes ??= []).push(retiredRoute); + const cancelledTaskIds: string[] = [], releasedAgentIds: string[] = []; + const interrupted: LiveWorker[] = [], idle: AgentTeamWorker[] = []; + for (const worker of this.archive.workers) { + const pending = worker.pendingDelivery?.taskId; + const affected = worker.tasks.filter(task => task.routeId === input.routeId && + (['queued', 'running', 'paused'].includes(task.status) || pending === task.id || task.helperSubmission)); + if (!affected.length) continue; + const executing = affected.find(task => task.status === 'running' || pending === task.id || task.helperSubmission); + for (const task of affected) { + cancelledTaskIds.push(task.id); + task.cancelRequested = { at: retiredRoute.retiredAt, reason: retiredRoute.reason }; + task.helperSubmission = undefined; + if (pending === task.id) worker.pendingDelivery = undefined; + if (task.status !== 'running') { + task.status = 'cancelled'; task.finishedAt = retiredRoute.retiredAt; + } + } + const live = this.live.get(worker.id); + if (!worker.tasks.some(task => !task.cancelRequested && ['queued', 'running', 'paused'].includes(task.status))) { + worker.status = 'stopped'; + worker.activity = live ? 'stopping' : 'idle'; + releasedAgentIds.push(worker.id); + idle.push(worker); + } + if (live && (executing || worker.status === 'stopped')) { + worker.activity = 'stopping'; + interrupted.push(live); + } + } + // Save the entire route decision before signalling workers. Reuse of an + // affected member still goes through its stopped-writer barrier. + this.changed(); + for (const entry of interrupted) { + const reason = new Error('math_team_route_retired:' + input.routeId); + entry.routeAbort.abort(reason); + entry.abort.abort(reason); + void entry.session?.interrupt().catch(() => {}); + } + for (const worker of idle) + void this.closeNativeIdle(worker).catch(() => { /* stopProofWriter durably records failures. */ }); + const text = 'Route ' + input.routeId + ' retired. ' + input.reason; + for (const to of ['lead', ...this.archive.workers.filter(worker => worker.status !== 'stopped').map(worker => worker.id)]) + this.event(null, to, 'route-retired', text); + return { ok: true, retiredRoute, cancelledTaskIds, releasedAgentIds }; + } + private nativeStart(worker: AgentTeamWorker) { const existing = this.nativeStarts.get(worker.id); if (existing) return existing; @@ -288,12 +394,14 @@ export class AgentResearchTeam { } private async spawnNative(request: NativeTeamSpawn, signal: AbortSignal): Promise { - if (this.archive.workers.filter(item => item.status !== 'stopped' || this.live.has(item.id)).length >= this.input.maxAgents - 1) + const { message, routeId } = nativeTaskRoute(request.message); + this.assertRouteAvailable(routeId); + if (this.occupiedAgentSlots() >= this.input.maxAgents - 1) throw new NativeAgentControlInputError('math_team_capacity_exceeded'); 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(request.message); + 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', @@ -314,7 +422,8 @@ export class AgentResearchTeam { } private async followupNative(worker: AgentTeamWorker, initialInput: Record, signal: AbortSignal): Promise { - const message = nativeTeamAssignmentMessage(initialInput.input as Record); + const { message, routeId } = nativeTaskRoute(nativeTeamAssignmentMessage(initialInput.input as Record)); + this.assertRouteAvailable(routeId); if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); if (worker.status === 'stopped') throw new Error('math_team_agent_stopped'); const profiles = message.trimStart().startsWith('Profiles:') ? this.memberProfiles(message, worker) : undefined; @@ -323,8 +432,11 @@ export class AgentResearchTeam { const connection = active.session.nativeAgentControl; if (!connection) throw new Error('math_team_native_backend_required'); const task = worker.tasks.find(task => task.status === 'running'); - if (!task) throw new Error('math_team_task_not_running'); - if (task.declarations) throw new NativeAgentControlInputError( + if (!task || task.cancelRequested) throw new Error('math_team_task_not_running'); + if (routeId !== undefined && routeId !== task.routeId) + throw new NativeAgentControlInputError('math_team_route_switch_requires_stopped_task'); + 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.'); const changedProfiles = profiles && canonicalMathJson(profiles.evidence.selected) !== canonicalMathJson(task.profileEvidence?.selected); // Preserve the attributed native message and codec. The receiver's frozen @@ -334,21 +446,26 @@ export class AgentResearchTeam { ...(changedProfiles ? { contextItems: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: profiles.section.text }] }] } : {}) }); 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.saveNativeFollowup(task, message, profiles?.evidence ?? task.profileEvidence); const accepted = this.nativeControl!.accepted(worker, active.session, worker.native!.turnId!); return { ...accepted, submissionId: result.submissionId }; } if (active) await active.task; await this.closeNativeIdle(worker); + if ((worker.status as string) === 'stopped') throw new Error('math_team_agent_stopped'); + this.assertRouteAvailable(routeId); worker.native!.initialInput = initialInput; this.nativeStart(worker); - const saved = worker.tasks.toReversed().find(task => ['paused', 'interrupted', 'queued'].includes(task.status) && !task.cancelRequested && !task.deliveryId); + const saved = worker.tasks.toReversed().find(task => ['paused', 'interrupted', 'queued'].includes(task.status) && + !task.cancelRequested && !task.deliveryId && (routeId === undefined || routeId === task.routeId)); if (saved) { + this.assertRouteAvailable(saved.routeId); this.saveNativeFollowup(saved, message, profiles?.evidence); saved.pauseRequested = undefined; saved.status = 'queued'; saved.error = undefined; this.launch(worker); } else { - this.enqueue(worker, this.newTask(message, profiles?.evidence)); + this.enqueue(worker, this.newTask(message, profiles?.evidence, { routeId })); } return this.waitNativeStart(worker, signal); } @@ -381,6 +498,7 @@ export class AgentResearchTeam { } private async loadNative(worker: AgentTeamWorker) { + if (worker.status === 'stopped') throw new Error('math_team_agent_stopped'); if (this.live.get(worker.id)?.session || this.nativeIdle.has(worker.id)) return; if (this.live.has(worker.id) || worker.writerStopUnconfirmed || worker.pendingDelivery || ['checking', 'integrating', 'stopping'].includes(worker.activity ?? '')) throw new Error('math_team_native_member_busy'); @@ -408,6 +526,7 @@ export class AgentResearchTeam { this.nativeIdle.set(worker.id, session); if (worker.native && session.nativeConfiguration) worker.native.runtimeConfiguration = session.nativeConfiguration; worker.writerProcess = session.processIdentity; this.changed(); + if ((worker.status as string) === 'stopped') await this.closeNativeIdle(worker); } private snapshot(actor: string, after: number) { @@ -473,9 +592,10 @@ export class AgentResearchTeam { 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.archive.workers.filter(item => item.status !== 'stopped' || this.live.has(item.id)).length >= this.input.maxAgents - 1) + 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); @@ -487,6 +607,7 @@ export class AgentResearchTeam { 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)); @@ -566,6 +687,7 @@ export class AgentResearchTeam { 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'); @@ -597,7 +719,7 @@ export class AgentResearchTeam { 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) : undefined; + ? 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 }; @@ -675,11 +797,12 @@ export class AgentResearchTeam { artifacts: delivery.artifacts.map(artifact => ({ id: artifact.id, declaration: artifact.declaration, proof: artifact.proof })), originalProblemAcceptance: 'not-assessed' }; } - case 'submit': { + case 'submit': + case 'submit_helpers': { if (actor === 'lead') throw new Error('math_team_child_submission_required'); 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) throw new Error('math_team_submission_pending'); + 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) @@ -690,6 +813,14 @@ export class AgentResearchTeam { ownedFiles: this.input.state.problem.ownedFiles, hint: 'Declaration file paths are relative to the Lean project. Use an exact owned file path; ' + 'put helpers in an editable owned Lean file or keep exploratory files under .scratch. No nomination was saved; correct the declarations and submit again.' }; + if (operation.operation === 'submit_helpers') { + 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(); + 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(); return { ok: true, status: 'pending-writer-stop', taskId: task.id, @@ -715,6 +846,10 @@ export class AgentResearchTeam { 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.' } : {}) }; } + case 'retire_route': { + 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(); @@ -739,9 +874,10 @@ export class AgentResearchTeam { } private newTask(message: string, profileEvidence = this.memberProfiles(message).evidence, - { budget, workKind }: Pick = {}): AgentTeamTask { + { budget, workKind, routeId }: Pick = {}): AgentTeamTask { + this.assertRouteAvailable(routeId); return { id: crypto.randomUUID(), message, status: 'queued', createdAt: Date.now(), turns: 0, budget, - objectiveRevision: 1, workKind, + objectiveRevision: 1, workKind, routeId, profileEvidence, sequence: Math.max(0, ...this.archive.workers.flatMap(worker => worker.tasks.map(task => task.sequence ?? 0))) + 1 }; } @@ -762,7 +898,7 @@ export class AgentResearchTeam { 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 }; + profileEvidence: task.profileEvidence, objectiveRevision: task.objectiveRevision, workKind: task.workKind, routeId: task.routeId }; } private async prepare(worker: AgentTeamWorker) { @@ -808,6 +944,7 @@ export class AgentResearchTeam { }; } task.status = 'failed'; task.error = reason; task.finishedAt ??= Date.now(); + task.helperSubmission = undefined; worker.pendingDelivery = undefined; 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'; @@ -818,10 +955,11 @@ export class AgentResearchTeam { private launch(worker: AgentTeamWorker) { if (this.live.has(worker.id) || this.stopping || this.input.signal.aborted || worker.status === 'stopped' || worker.writerStopUnconfirmed) return; const abort = new AbortController(); - const entry: LiveWorker = { abort, task: undefined as unknown as Promise }; + 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); + 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') { @@ -833,6 +971,7 @@ export class AgentResearchTeam { this.pauseForBudget(worker, task, admission.reason); break; } if (this.input.remainingMs() <= 0) break; + await this.flushAdoptions(worker.id); await this.runTask(worker, task, entry); } }).catch(error => { @@ -847,7 +986,7 @@ export class AgentResearchTeam { this.live.delete(worker.id); this.changed(); // 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.cancelledTaskId && worker.tasks.find(task => task.id === entry.cancelledTaskId)?.researchArtifactId && + if ((entry.routeAbort.signal.aborted || entry.cancelledTaskId && worker.tasks.find(task => task.id === entry.cancelledTaskId)?.researchArtifactId) && 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); }); @@ -859,6 +998,8 @@ export class AgentResearchTeam { await this.closeNativeIdle(worker); const { state } = this.input, access = this.access.get(worker.id)!; const signal = AbortSignal.any([this.input.signal, entry.abort.signal]); + if (signal.aborted || task.status !== 'queued' || task.cancelRequested) return; + this.assertRouteAvailable(task.routeId); access.assertHarnessCurrent?.(); access.assertKnowledgeCurrent?.(); if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); const sourceFeedback = this.sourceFeedback(worker); @@ -879,6 +1020,35 @@ export class AgentResearchTeam { emit: (event, details) => this.input.emit(event, { ...details, workerId: worker.id }) }); const sessionId = crypto.randomUUID(); const callbacks = usage.bindSession(sessionId, () => entry.session?.lastInputTokens); + const sliceSettings = softSliceSettings(this.input.softSlice ?? {}); + let milestoneCheckpoint = false, turnId: string | undefined; + let checkpointCloseTimer: ReturnType | undefined, closingSession: Promise | undefined; + const closeSession = (session: MathAgentSession) => closingSession ??= Promise.resolve().then(() => session.close()); + const milestone = createSoftSlice(sliceSettings, { + current: () => Boolean(entry.session) && !signal.aborted && !entry.runSettled && !task.pauseRequested && !task.cancelRequested && !task.declarations, + notice: (reason, completedCompactions) => { + this.input.emit(reason === 'time' ? 'soft_slice_milestone_requested' : 'compaction_circuit_breaker_triggered', + { workerId: worker.id, taskId: task.id, turnId, completedCompactions, graceMs: sliceSettings.graceMs }); + const active = entry.session; + void active?.notify?.( + 'Use theoremos_team submit_helpers for standalone helpers. 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.', + active.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }).catch(() => {}); + }, + interrupt: () => { + const active = entry.session; + if (!active) return; + milestoneCheckpoint = true; + this.input.emit('soft_slice_checkpoint_requested', { workerId: worker.id, taskId: task.id, turnId, boundary: 'wait-limit' }); + const closeStalledTurn = () => { + if (entry.runSettled || entry.session !== active || closingSession) return; + this.input.emit('soft_slice_session_closed', { workerId: worker.id, taskId: task.id, turnId, reason: 'interrupt-not-settled' }); + void closeSession(active).catch(() => {}); + }; + checkpointCloseTimer = setTimeout(closeStalledTurn, CHECKPOINT_CLOSE_GRACE_MS); + checkpointCloseTimer.unref(); + void Promise.resolve().then(() => active.interrupt()).catch(closeStalledTurn); + }, + }); const requestGate: NonNullable = identity => { const admission = agentTeamChildAdmission(this.budgetInput(task), 'request'); if (admission.allowed === false) { @@ -893,6 +1063,11 @@ export class AgentResearchTeam { requestGate.checkpoint = () => { if (callbacks.requestGate?.checkpoint?.()) return true; if ((worker.requestUsageAccounting?.pendingRequests ?? 0) > 0) return false; + if (milestone.useBoundary()) { + milestoneCheckpoint = true; + this.input.emit('soft_slice_checkpoint_requested', { workerId: worker.id, taskId: task.id, turnId, boundary: 'request' }); + return true; + } // Nomination and handoff are member decisions. Finish the current response // and its tools, then release the writer before any further paid request. return task.declarations !== undefined || task.pauseRequested?.kind === 'handoff'; @@ -936,6 +1111,7 @@ export class AgentResearchTeam { ...turnTiming, onActivity: activity => { 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(); }, ...callbacks, requestGate }); @@ -946,7 +1122,8 @@ export class AgentResearchTeam { 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(); - const status = await entry.session.run(context.message, task.id, worker.worktree, turnId => { + 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'); @@ -955,8 +1132,10 @@ export class AgentResearchTeam { if (pending) { pending.accepted = true; pending.resolve(accepted); } } }); - if (status === 'checkpoint' && !task.declarations) { - task.pauseRequested ??= { at: Date.now(), kind: 'budget', reason: 'math_team_turn_checkpoint' }; + 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(); } completed = ['completed', 'submitted'].includes(status) || status === 'checkpoint' && task.declarations !== undefined; @@ -969,14 +1148,16 @@ export class AgentResearchTeam { if (error instanceof LeanEnvironmentHealthCheckError) this.input.emit('lean_environment_unavailable', { workerId: worker.id, health: error.health }); } finally { + milestone.stop(); + clearTimeout(checkpointCloseTimer); entry.runSettled = true; try { if (entry.session) { const current = entry.session; worker.activity = 'stopping'; this.changed(); - if (signal.aborted) await current.interrupt().catch(() => {}); + if (signal.aborted && !closingSession) await current.interrupt().catch(() => {}); await stopProofWriter({ session: current, record: worker, workerId: worker.id, - close: async () => { await current.close(); entry.session = undefined; usage.sessionClosed(sessionId); }, + 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); worker.writerProcess = undefined; @@ -986,6 +1167,9 @@ export class AgentResearchTeam { if (started) usage.finish(completed); else if (reserved) { state.turns--; worker.turns--; } if (writerStopped) { + if ((milestoneCheckpoint || milestone.requested && completed) && !task.declarations) + task.pauseRequested ??= { at: Date.now(), kind: 'handoff', reason: milestoneCheckpoint + ? 'math_soft_slice_checkpoint' : 'math_soft_slice_milestone' }; task.status = task.cancelRequested ? 'cancelled' : task.pauseRequested ? 'paused' : outcome; if (task.status === 'paused') task.pausedAt = Date.now(); else task.finishedAt = Date.now(); worker.phase = 'prepared'; @@ -1005,12 +1189,13 @@ export class AgentResearchTeam { } } access.assertHarnessCurrent?.(); + await this.flushHelperSubmissions(worker); if (worker.pendingDelivery) { await this.finishDelivery(worker); } else { this.event(worker.id, 'lead', task.status === 'completed' ? 'completed' : task.status === 'failed' ? 'failed' : task.status === 'cancelled' ? 'cancelled' : task.status === 'paused' ? 'paused' : 'interrupted', - (task.status === 'failed' ? task.error : undefined) ?? task.summary ?? task.pauseRequested?.reason ?? task.cancelRequested?.reason ?? task.error ?? 'Research saved.', + (task.status === 'failed' ? task.error : undefined) ?? teamTaskResearchSummary(task), { taskId: task.id, researchArtifactId: task.researchArtifactId }); } } @@ -1025,7 +1210,7 @@ export class AgentResearchTeam { } const reference = saveAgentTeamResearchArtifact({ directory: path.join(this.directory, 'research'), state: this.input.state, worktree: worker.worktree, agentId: worker.id, taskId: task.id, commit: task.sourceCommit, - summary: task.summary ?? task.pauseRequested?.reason ?? task.cancelRequested?.reason ?? task.error ?? 'Research saved.', status: task.status }); + 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(); @@ -1049,21 +1234,107 @@ export class AgentResearchTeam { return [...declarations.values()]; } + private async flushHelperSubmissions(worker: AgentTeamWorker) { + 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; + } + 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; + const assertWriterStopped = () => { + 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?.(); + }; + const { state } = this.input; + try { + assertWriterStopped(); + const sourceCommit = task.sourceCommit ?? commitSolverSources(state.problem, worker.worktree); + await this.input.exclusiveCheck(async () => { + const expectedCommit = this.archive.canonicalCommit ?? git(state.worktree, ['rev-parse', 'HEAD']); + const result = await landVerifiedHelpers({ state, worktree: state.worktree, expectedCommit, + sourceWorktree: worker.worktree, sourceCommit, seedCommit: task.seedCommit ?? worker.seedCommit, + declarations: nominations.map(({ file, name, type, kind }) => ({ file, name, type, kind })), + env: this.input.leadAccess.environment, signal, timeoutMs: this.input.proofTimeoutMs, + assertCurrent: assertWriterStopped }); + if (!result.helpers.length) { + task.helperSubmission = undefined; + this.event(null, worker.id, 'helpers', 'The nominated helpers already exist in the canonical sources.', { taskId: task.id }); + return; + } + // Register the partial patch as ordinary stopped-writer evidence, so peers + // use the same checked adoption and pending-draft baseline as other deliveries. + const evidenceDirectory = path.join(this.directory, 'proofs'); + const delivery = await withSolverWorktree(state.worktree, result.commit, async checkout => { + const project = path.join(checkout, state.problem.projectRelative); + const packages = path.join(state.worktree, state.problem.projectRelative, '.lake', 'packages'); + if (fs.existsSync(packages)) bindLeanPackages(project, packages); + return checkAgentTeamProofDelivery({ state, agentId: worker.id, worktree: checkout, + seedCommit: expectedCommit, declarations: result.declarations, + inferredHelperTypes: result.declarations.map(({ file, name }) => file + '\0' + name), + provenance: { taskId: task.id, objectiveRevision: task.objectiveRevision ?? 1, + objectiveDigest: mathDigest(task.message), workKind: task.workKind, + ...(worker.native ? { spawnHistory: worker.native.spawnHistory ?? 'unknown' } : {}), + exposures: structuredClone(worker.exposures ?? []) }, + env: this.input.leadAccess.environment, signal, timeoutMs: this.input.proofTimeoutMs, + evidenceDirectory, assertWriterStopped }); + }); + signal.throwIfAborted(); + this.archive.canonicalCommit = delivery.commit; + const landedAt = Date.now(); + (this.archive.landedHelpers ??= []).push(...result.helpers.map(helper => ({ ...helper, landedAt }))); + this.archive.deliveries.push({ id: delivery.id, agentId: worker.id, taskId: task.id, kind: 'helpers', + path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json'), + declarationCount: delivery.declarations.length, summary: task.summary?.slice(0, 200) }); + task.helperSubmission = undefined; + this.changed(); + 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. ' + + 'The producer assignment remains open.'; + for (const actor of new Set(['lead', worker.id, ...this.live.keys()])) { + this.event(null, actor, 'helpers', notice, { taskId: task.id, deliveryId: delivery.id }); + } + this.input.emit('incremental_helpers_landed', { workerId: worker.id, taskId: task.id, + commit: delivery.commit, declarations: result.helpers.map(helper => helper.qualifiedName) }); + }); + } catch (error) { + if (task.cancelRequested && signal.aborted) return; + if (!(error instanceof IncrementalHelperRejection) && !correctableProofFailure(error)) throw error; + task.helperSubmission = undefined; + task.error = (error as Error).message; + this.event(null, worker.id, 'failed', task.error, { taskId: task.id }); + this.event(worker.id, 'lead', 'failed', task.error, { taskId: task.id }); + } + } + private async finishDelivery(worker: AgentTeamWorker) { await this.closeNativeIdle(worker); - const pending = worker.pendingDelivery!; + 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 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(); try { + const explicit = new Set(task.declarations?.map(({ file, name }) => file + '\0' + name)); + const inferredHelperTypes = (worker.pendingPeerDeliveries ?? []).flatMap(id => { + const reference = this.archive.deliveries.find(delivery => delivery.id === id); + return reference?.kind === 'helpers' ? readAgentTeamProofDelivery(reference.path, this.input.state).inferredHelperTypes ?? [] : []; + }).filter(key => !explicit.has(key)); 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(); const delivery = await this.input.exclusiveCheck(() => checkAgentTeamProofDelivery({ state: this.input.state, failureCache: this.nativeAgentControlEnabled ? this.failedNominations : undefined, - agentId: worker.id, worktree: worker.worktree, seedCommit: pending.seedCommit, declarations: pending.declarations, - env: this.access.get(worker.id)!.environment, signal: this.input.signal, timeoutMs: this.input.proofTimeoutMs, + 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, // 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, @@ -1072,9 +1343,11 @@ export class AgentResearchTeam { assertWriterStopped: () => { if (worker.writerStopUnconfirmed || this.live.get(worker.id)?.session) throw new Error('math_writer_stop_unconfirmed:' + worker.id); }, evidenceDirectory: path.join(this.directory, 'proofs') })); + signal.throwIfAborted(); task.deliveryId = delivery.id; if (!this.archive.deliveries.some(item => item.id === delivery.id)) this.archive.deliveries.push({ - id: delivery.id, agentId: worker.id, taskId: task.id, path: path.join(this.directory, 'proofs/deliveries', delivery.id + '.json') }); + id: delivery.id, agentId: worker.id, taskId: task.id, path: path.join(this.directory, 'proofs/deliveries', delivery.id + '.json'), + declarationCount: delivery.declarations.length, summary: task.summary?.slice(0, 200) }); worker.pendingDelivery = undefined; worker.pendingSourceBase = undefined; worker.pendingPeerDeliveries = undefined; const ready = delivery.declarations.slice(0, 8).map(item => item.name).join(', '); const more = delivery.declarations.length - 8; @@ -1083,6 +1356,12 @@ export class AgentResearchTeam { this.event(worker.id, 'lead', 'delivery', checked + (task.summary ? '\n' + task.summary : ''), { taskId: task.id, deliveryId: delivery.id, researchArtifactId: task.researchArtifactId }); } catch (error) { + if (task.cancelRequested && signal.aborted) { + worker.phase = 'prepared'; + worker.activity = 'idle'; + this.changed(); + return; + } // Keep infrastructure failures pending; deterministic proof feedback is correctable by another explicit assignment. if (correctableProofFailure(error)) { this.rejectSubmission(worker, task, error); @@ -1101,9 +1380,16 @@ export class AgentResearchTeam { const { state } = this.input; const target = targetId === 'lead' ? undefined : this.worker(targetId); if (target) await this.closeNativeIdle(target); - if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && state.writerStopUnconfirmed) + if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed)) throw new Error('math_team_target_writing'); const worktree = target?.worktree ?? state.worktree; + const helpers = this.archive.deliveries.filter(delivery => delivery.kind === 'helpers' && + !this.archive.adoptions.some(adoption => adoption.deliveryId === delivery.id && adoption.targetId === targetId)); + 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 adoption of this.archive.adoptions.filter(item => item.targetId === targetId && ['queued', 'integrating'].includes(item.status))) { const reference = this.archive.deliveries.find(item => item.id === adoption.deliveryId)!; const delivery = readAgentTeamProofDelivery(reference.path, state); @@ -1116,7 +1402,7 @@ export class AgentResearchTeam { expectedCommit: adoption.expectedCommit!, env: (target ? this.access.get(targetId) : this.input.leadAccess)!.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' && state.writerStopUnconfirmed) + if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed)) throw new Error('math_team_target_writing'); } })); adoption.status = 'completed'; adoption.commit = result.commit; adoption.receiptId = result.id; adoption.error = undefined; @@ -1124,8 +1410,9 @@ export class AgentResearchTeam { if (targetId === 'lead') { state.check = undefined; // Save the next acceptance step with adoption completion, so restart needs no extra model turn. - state.pendingResearchFreeze = { commit: result.commit, sourceDigest: result.sourceDigest, - problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest }; + if (reference.kind !== 'helpers' || state.pendingResearchFreeze) + state.pendingResearchFreeze = { commit: result.commit, sourceDigest: result.sourceDigest, + problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest }; } else { // An adopted peer is part of the next transfer until the member's own draft // has been delivered. Retain the old ancestor instead of losing that draft. @@ -1194,6 +1481,7 @@ export class AgentResearchTeam { this.changed(); } } + await this.flushHelperSubmissions(worker); if (worker.pendingDelivery) await this.finishDelivery(worker); } await this.flushAdoptions(); diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index 51149857..b16202d4 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -24,7 +24,7 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, '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. ' + 'Coordinate and publish are optional compatibility operations for saved decision notes and shared research summaries; they do not gate research, tools or turn scheduling. ' + - 'Use cancel to withdraw or replace a particular assignment while retaining that member. ' + + '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. ' + @@ -44,13 +44,13 @@ export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number, '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 and call submit, then return to release writing for host checking; a local check or normal return alone does not publish a team delivery. ' + - 'Deliver an independent helper as soon as it answers the assignment, even while other original goals remain open. Ask Lead before expanding into another member\'s gap; finish the handoff before starting unrelated work. ' + + 'Use submit_helpers to share checked standalone helpers while the assigned target is unfinished. Save your draft, then return for the host to check and land the helpers. ' + '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 or stop members. Write only in your own workspace. ' + shared + '\n'; + '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 { @@ -65,7 +65,8 @@ 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 several branches need the same lemma, agree on its Lean statement and assign one member to prove it for those consumers. ' + + 'If several goals share a mathematical foundation, assign and check its small Lean interfaces before dispatching the consuming goals. ' + + 'Tag route-specific native spawn and followup objectives with Route: ROUTE_ID as the first line. 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. ' + 'Only Lead dispatches, interrupts and adopts; members can exchange findings directly. ' + 'Inspect evidence before adopting into yourself or a stopped writer. Save sources and notes, request adoption and return so the host can stop writing, integrate and continue your saved thread. ' + @@ -73,7 +74,7 @@ function nativeAgentTeamInstructions(role: AgentTeamRole, maxAgents: number): st return `You are a mathematical researcher and Lean proof writer; your workspace member ID is ${JSON.stringify(role.id)} and your coordinator is /root (lead). ` + 'Carry out the current Lead assignment; the frozen original problem supplies background and source constraints. ' + 'Use native send_message for the first usable finding, probe result or blocker without waiting for the complete proof. Include the exact claim, assumptions and available evidence. ' + - 'Tell Lead if another branch could use your lemma and confirm the Lean statement with its consumer. Submit its independent proof as soon as you have it. ' + + 'Tell Lead if another branch could use your lemma and confirm its Lean statement with its consumer. Use submit_helpers for standalone helpers while your current target is unfinished. ' + 'Save exact declarations and RESEARCH.md, then call submit and return. The pending-writer-stop acknowledgment is not a checked delivery. ' + 'When the same task needs a dependency or Lead decision, save the draft, call yield with a reason and return. Lead can adopt dependencies into your stopped workspace and resume this same task with native followup_task. ' + 'Only Lead dispatches and adopts. Ask Lead before expanding into another gap. Do not spawn subteams or interrupt peers.\n' + shared; @@ -85,7 +86,7 @@ export function agentTeamWorkerDeliveryHelp(): string { 'Use the member\'s own editable paths listed by the host; the same filename in Lead\'s workspace is a separate copy. New independent helper declarations may be added inside these files while frozen original statements remain fixed; put scratch results in an editable owned file before nomination. ' + 'List every changed declaration since the assignment deliveryBaseCommit, including earlier unpublished or rejected drafts. ' + 'For a new shared def or abbrev in an existing owned file, add kind:"definition". Its checked body is reusable; prove any claimed property separately. Each declaration may include description and explicit premises. Submit accepts 1–32 declarations, including original targets you have proved. ' + - 'Submit useful independent declarations when they answer the assignment; other original goals may remain unfinished. Message Lead about the result before extending the scope. ' + + 'For standalone helpers before the assignment is finished, use submit_helpers with the same declaration fields. Nominate just the helpers and return. The host checks and lands eligible helpers, and Lead can resume the current task. ' + 'The pending-writer-stop result acknowledges the request only: stop editing and return. The host confirms writer shutdown and checks actual source before publishing a delivery ID. ' + 'Read your task feedback on the next assignment. Messages, notes and local checks remain advisory. ' + 'Save reproducible findings in RESEARCH.md before returning; after writer shutdown the host records its fixed-commit advisory artifact. ' + @@ -111,6 +112,7 @@ export function agentTeamWorkerSection(state: Readonly, role: Ag : 'Current team assignment (replaces earlier assignments; messages are advisory updates):\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 } : {}), deliveryExposures: worker.exposures ?? [], sourceCommit: assignment.sourceCommit, deliveryBaseCommit: current.seedCommit, cancelRequested: current.cancelRequested, pauseRequested: current.pauseRequested, diff --git a/src/solver/agentTeamProof.ts b/src/solver/agentTeamProof.ts index 684c4dc9..6f730c10 100644 --- a/src/solver/agentTeamProof.ts +++ b/src/solver/agentTeamProof.ts @@ -23,6 +23,7 @@ export type AgentTeamProofDelivery = Readonly; export type AgentTeamProofAdoption = Readonly !delivery.declarations.some(declaration => + key === declaration.file + '\0' + declaration.name && !state.problem.declarations[declaration.file]?.some(original => + original.name === declaration.name || original.name === declaration.name.split('.').at(-1))))) + return fail('delivery_evidence_changed'); if (artifacts.length !== delivery.declarations.length || artifacts.some((artifact, index) => !sameIdentity(artifact, state) || artifact.proof.commit !== delivery.commit || artifact.proof.sourceDigest !== delivery.sourceDigest || @@ -249,7 +255,7 @@ async function checkTeamDeclarationArtifacts(input: Parameters { const declarations = teamDeclarations.parse(input.declarations); const agentId = deliverySchema.shape.agentId.parse(input.agentId); @@ -268,13 +274,15 @@ export async function checkAgentTeamProofDelivery(input: CheckInput & { }; const environment = input.failureCache && environmentKey(); const key = environment && mathDigest(canonicalMathJson({ ...identityOf(input.state), environment, declarations, + inferredHelperTypes: input.inferredHelperTypes, // The project trees include trusted local imports, but exclude the worker's top-level research notes. project: git(input.worktree, ['rev-parse', commit + ':' + problem.projectRelative]), seed: git(input.worktree, ['rev-parse', input.seedCommit + ':' + problem.projectRelative]), timeoutMs: Number.isFinite(input.timeoutMs) ? input.timeoutMs : null })); 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, assertWriterStopped: stable }).catch(error => { + const artifacts = await checkTeamDeclarationArtifacts({ ...input, commit, declarations, + inferredExpectedTypes: new Set(input.inferredHelperTypes), assertWriterStopped: stable }).catch(error => { if (key && input.failureCache && error instanceof DeclarationArtifactCheckError && hasDeterministicLeanFailure(error.verification)) { stable(); if (canonicalMathJson(environmentKey() ?? null) === canonicalMathJson(environment)) { @@ -288,6 +296,7 @@ export async function checkAgentTeamProofDelivery(input: CheckInput & { const record: AgentTeamProofDelivery = { schema: 'theorem-os.agent-team-proof-delivery.v1', id: '', ...identityOf(input.state), agentId, sourceWorktree: input.worktree, seedCommit: input.seedCommit, commit, sourceDigest: ownedSourceDigest(problem, input.worktree, commit), declarations, artifacts, ...patch, + ...(input.inferredHelperTypes?.length ? { inferredHelperTypes: input.inferredHelperTypes } : {}), ...(input.provenance === undefined ? {} : { provenance: provenanceSchema.parse(input.provenance) }) }; const delivery = { ...record, id: recordId(record) }; validateDelivery(delivery, input.state); @@ -333,7 +342,8 @@ async function resumeAdoption(input: IntegrationInput, delivery: AgentTeamProofD if (fs.existsSync(packages)) bindLeanPackages(path.join(checkout, problem.projectRelative), packages); const checkoutStable = frozenSource(input, checkout, adoption.commit); await checkTeamDeclarationArtifacts({ ...input, worktree: checkout, commit: adoption.commit, - declarations: delivery.declarations, assertWriterStopped: () => { stable(); checkoutStable(); } }); + declarations: delivery.declarations, inferredExpectedTypes: new Set(delivery.inferredHelperTypes), + assertWriterStopped: () => { stable(); checkoutStable(); } }); stable(); checkoutStable(); } }); @@ -368,7 +378,7 @@ export async function integrateAgentTeamProofDelivery(input: IntegrationInput): const commit = commitSolverSources(problem, checkout), checkoutStable = frozenSource(input, checkout, commit); const assertStopped = () => { stable(); checkoutStable(); }; const artifacts = await checkTeamDeclarationArtifacts({ ...input, worktree: checkout, commit, - declarations: delivery.declarations, assertWriterStopped: assertStopped }); + declarations: delivery.declarations, inferredExpectedTypes: new Set(delivery.inferredHelperTypes), assertWriterStopped: assertStopped }); assertStopped(); const record: AgentTeamProofAdoption = { schema: 'theorem-os.agent-team-proof-adoption.v1', id: '', ...identityOf(input.state), deliveryId: delivery.id, beforeCommit: input.expectedCommit, commit, diff --git a/src/solver/agentTeamState.ts b/src/solver/agentTeamState.ts index de6dbc84..e3ad1637 100644 --- a/src/solver/agentTeamState.ts +++ b/src/solver/agentTeamState.ts @@ -2,6 +2,7 @@ import { z } from 'zod'; import type { SolverWorkerState } from './archive'; import type { HarnessProcessIdentity } from '../runtime/harnessProcess'; import { agentTeamProfileEvidenceSchema } from './agentTeamProfiles'; +import { portfolioRouteIdSchema, retiredRouteSchema } from './routeControl'; const identifier = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/u); export const writerProcessSchema = z.object({ schema: z.literal('theorem-os.harness-process-identity.v1'), @@ -26,6 +27,7 @@ export const teamSpawnHistory = z.enum(['fresh', 'parent-history', 'unknown']); const exposure = z.object({ deliveryId: z.string(), agentId: identifier, taskId: z.string(), commit: z.string(), kind: teamExposureKind, at: z.string() }).strict(); const task = z.object({ id: z.string(), message: z.string(), seedCommit: z.string().optional(), + routeId: portfolioRouteIdSchema.optional(), objectiveRevision: z.number().int().positive().optional(), workKind: agentTeamWorkKindSchema.optional(), profileEvidence: agentTeamProfileEvidenceSchema.optional(), objectiveHistory: z.array(z.object({ revision: z.number().int().positive(), message: z.string(), @@ -42,6 +44,7 @@ const task = z.object({ id: z.string(), message: z.string(), seedCommit: z.strin pausedAt: z.number().optional(), lastStartedAt: z.number().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(), nomination: z.object({ objectiveRevision: z.number().int().positive(), objectiveDigest: z.string().regex(/^[a-f0-9]{64}$/u), workKind: agentTeamWorkKindSchema.optional() }).strict().optional(), failedCheck: z.object({ declaration, seedCommit: z.string(), commit: z.string(), sourceDigest: z.string(), @@ -55,6 +58,11 @@ const task = z.object({ id: z.string(), message: z.string(), seedCommit: z.strin cancelRequested: z.object({ at: z.number(), reason: z.string().optional(), replacementTaskId: z.string().optional() }).strict().optional(), error: z.string().optional() }).strict(); export const agentTeamStateSchema = z.object({ schema: z.literal('theorem-os.agent-team.v1'), + canonicalCommit: z.string().regex(/^[a-f0-9]{40,64}$/u).optional(), + retiredRoutes: z.array(retiredRouteSchema).optional(), + landedHelpers: z.array(z.object({ qualifiedName: z.string(), file: z.string(), type: z.string(), + commit: z.string().regex(/^[a-f0-9]{40,64}$/u), kind: z.literal('definition').optional(), + landedAt: z.number().int().nonnegative().optional() }).strict()).optional(), /** Absent retains the historical dynamic-tool team on resume. */ transport: z.enum(['host-tools', 'native-agent-control']).optional(), nativeControl: z.object({ sessionId: z.string(), rootThreadId: z.string(), @@ -112,12 +120,14 @@ export const agentTeamStateSchema = z.object({ schema: z.literal('theorem-os.age writerStopUnconfirmed: z.object({ at: z.number(), reason: z.string() }).strict().optional(), }).passthrough()), events: z.array(z.object({ sequence: z.number().int().positive(), from: z.string(), to: z.string(), - kind: z.enum(['message', 'completed', 'delivery', 'failed', 'interrupted', 'adopted', 'research-updated', 'cancelled', 'paused', 'resumed', 'budget-updated', 'amended', 'progress']), + kind: z.enum(['message', 'completed', 'delivery', 'failed', 'interrupted', 'adopted', 'research-updated', 'cancelled', 'paused', 'resumed', 'budget-updated', 'amended', 'progress', 'helpers', 'route-retired']), at: z.number(), text: z.string(), taskId: z.string().optional(), deliveryId: z.string().optional(), sourceTaskId: z.string().optional(), relatedTaskId: z.string().optional(), dispatchResearchRevision: z.number().int().positive().optional(), researchArtifactId: z.string().optional(), researchRevision: z.number().int().positive().optional(), objectiveRevision: z.number().int().positive().optional(), progressId: z.string().optional() }).strict()), - deliveries: z.array(z.object({ id: z.string(), agentId: identifier, taskId: z.string(), path: z.string() }).strict()), + deliveries: z.array(z.object({ id: z.string(), agentId: identifier, taskId: z.string(), path: z.string(), + kind: z.literal('helpers').optional(), declarationCount: z.number().int().nonnegative().optional(), + summary: z.string().max(200).optional() }).strict()), adoptions: z.array(z.object({ id: z.string(), deliveryId: z.string(), targetId: z.string(), status: z.enum(['queued', 'integrating', 'completed', 'failed']), expectedCommit: z.string().optional(), commit: z.string().optional(), receiptId: z.string().regex(/^[a-f0-9]{64}$/u).optional(), error: z.string().optional() }).strict()), diff --git a/src/solver/agentTeamTool.ts b/src/solver/agentTeamTool.ts index d1afaa3e..a43cc595 100644 --- a/src/solver/agentTeamTool.ts +++ b/src/solver/agentTeamTool.ts @@ -2,16 +2,19 @@ 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'; type Json = Record; export type AgentTeamTransport = 'host-tools' | 'native-agent-control'; -const nativeOperations = new Set(['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'yield', 'submit']); +// 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', 'submit_helpers', '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); export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ - z.object({ operation: z.literal('spawn'), agentId: id, message: text, workKind: agentTeamWorkKindSchema.optional(), budget: agentTeamAllowanceSchema.optional() }).strict(), - z.object({ operation: z.literal('assign'), agentId: id, message: text, workKind: agentTeamWorkKindSchema.optional(), budget: agentTeamAllowanceSchema.optional() }).strict(), + 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(), z.object({ operation: z.literal('finish'), summary: text }).strict(), @@ -38,11 +41,15 @@ export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ z.object({ operation: z.literal('inspect-research'), artifactId: z.string().regex(/^[a-f0-9]{64}$/u), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(16000).optional() }).strict(), z.object({ operation: z.literal('submit'), summary: text, objectiveRevision: z.number().int().positive().optional(), declarations: declarationSubmissionSchema.shape.declarations }).strict(), + z.object({ operation: z.literal('submit_helpers'), summary: text, objectiveRevision: z.number().int().positive().optional(), declarations: declarationSubmissionSchema.shape.declarations }).strict(), 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']); +export const agentTeamMemberOperations = new Set(['message', 'poll', 'wait', 'inspect', 'inspect-research', 'history', 'yield', 'submit', 'submit_helpers', 'progress', 'route_summary']); export function agentTeamMessageRouteFeedback(actor: string, recipient: string) { if (recipient !== actor) return; @@ -54,7 +61,7 @@ export function agentTeamMessageRouteFeedback(actor: string, recipient: string) 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') + ? !['submit', 'submit_helpers', 'yield', 'progress'].includes(option.shape.operation.value) && (budgetControlsEnabled || option.shape.operation.value !== 'budget') : agentTeamMemberOperations.has(option.shape.operation.value))); } @@ -81,6 +88,7 @@ function fieldSchema(value: z.ZodTypeAny): Json { if (value.maxValue !== null) schema.maximum = value.maxValue; return schema; } + if (value instanceof z.ZodBoolean) return { type: 'boolean' }; if (value instanceof z.ZodLiteral) return { type: 'string', enum: [value.value] }; if (value instanceof z.ZodEnum) return { type: 'string', enum: value.options }; if (value instanceof z.ZodArray) return { type: 'array', items: fieldSchema(value.element), @@ -133,6 +141,9 @@ export function agentTeamArgumentFeedback(actor: string, budgetControlsEnabled: 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; const properties: Json = {}; for (const { schema } of contracts) Object.assign(properties, schema.properties); properties.operation = { type: 'string', enum: contracts.map(item => item.operation) }; @@ -152,12 +163,13 @@ export function agentTeamToolDefinition(actor: string, budgetControlsEnabled: bo '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. ') + - (lead ? (native ? '' : 'For spawn/assign, select assignment profiles from the pinned Skill for the gap. ') : + (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, tag the assignment with Route: ROUTE_ID on its first line. ' : + 'For spawn/assign, use routeId to tag the route and select assignment profiles from the pinned Skill for the gap. ') : + 'Use submit_helpers at a milestone to nominate standalone helpers, even while the assigned proof is open. Save and return for independent checking, then resume the same assignment. The host makes accepted signatures available to peers and applies the helpers 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. ') + - // Native Codex preserves these descriptions. Its provider conversion drops - // the entire finite-budget schema when the nested allowances are in oneOf; - // keep that wire schema flat and enforce the exact branches on the host. + '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, - ...(lead && budgetControlsEnabled && !native ? {} : { oneOf: contracts.map(item => item.schema) }) } }; + ...(flat ? {} : { oneOf: contracts.map(item => item.schema) }) } }; } diff --git a/src/solver/agentTeamViews.ts b/src/solver/agentTeamViews.ts index 64af0e9d..06e200aa 100644 --- a/src/solver/agentTeamViews.ts +++ b/src/solver/agentTeamViews.ts @@ -29,6 +29,7 @@ function taskProjection(task: AgentTeamTask, historyOffset: number, full = false const result = { id: task.id, sequence: task.sequence, historyOffset, status: task.status, objectiveRevision: task.objectiveRevision ?? 1, workKind: task.workKind, + ...(task.routeId ? { routeId: task.routeId } : {}), profileEvidence: full ? task.profileEvidence : task.profileEvidence && { skillDigest: task.profileEvidence.skillDigest, selected: task.profileEvidence.selected, loaded: task.profileEvidence.loaded, unresolved: task.profileEvidence.unresolved, @@ -131,6 +132,7 @@ export function agentTeamOverview(state: Readonly, 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; @@ -163,10 +165,16 @@ export function agentTeamOverview(state: Readonly, }), ...(research && { researchState: { revision: research.revision, publishedAt: research.publishedAt, summary: researchPreview!.text, advisory: true, ...(researchPreview!.truncated ? { summaryTruncated: true } : {}) } }), + ...(retiredRoutes.length > 0 && { retiredRouteCount: retiredRoutes.length, + retiredRoutes: retiredRoutes.slice(-REFERENCES).map(route => ({ ...route, + reason: preview(route.reason, TASK_TEXT).text, evidenceRefs: route.evidenceRefs?.slice(0, 4) })) }), completionRequested: team?.completionRequested && { at: team.completionRequested.at, summary: preview(team.completionRequested.summary, EVENT_TEXT).text }, + ...(team?.landedHelpers?.length ? { canonicalCommit: team.canonicalCommit, + landedHelpers: team.landedHelpers.slice(-REFERENCES).map(helper => ({ ...helper, type: preview(helper.type, 240).text })), + 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 }) => ({ id, agentId, taskId })), + 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, @@ -188,6 +196,82 @@ export function agentTeamOverview(state: Readonly, }; } +function oneLine(value: string, limit: number) { + const clipped = preview(value.trim().replace(/[\s\p{Cc}]+/gu, ' '), limit); + return clipped.truncated ? clipped.text + '…' : clipped.text; +} + +/** Bound each section by its serialized UTF-8 bytes, including JSON escapes. */ +function routeSummaryRows(rows: readonly T[], bytes: number) { + let used = 2; // Array brackets. + const selected: T[] = []; + for (const row of rows) { + const size = Buffer.byteLength(JSON.stringify(row)) + Number(selected.length > 0); + if (used + size > bytes) break; + selected.push(row); + used += size; + } + return selected; +} + +const routeTaskRank = { running: 0, queued: 1, paused: 2, completed: 3 } as const; + +/** A read-only index for route decisions. Full task and proof evidence stays behind history and inspect. */ +export function agentTeamRouteSummary(team: Readonly, + { routeId, includeRetired = true }: { routeId?: string; includeRetired?: boolean } = {}) { + const retired = new Map((team.retiredRoutes ?? []).map(route => [route.routeId, route])); + const matched = team.workers.flatMap(worker => worker.tasks.filter(task => + (routeId === undefined || routeId === task.routeId) && (includeRetired || !task.routeId || !retired.has(task.routeId))) + .map(task => ({ workerId: worker.id, task }))); + const byTask = new Map(matched.map(({ task }) => [task.id, task])); + const activeRoutes = new Map(); + const taskRows = matched.flatMap(({ task, workerId }) => { + const status = task.status; + if (status !== 'running' && status !== 'queued' && status !== 'paused' && status !== 'completed') return []; + const key = task.routeId ?? null; + if (!key || !retired.has(key)) { + let group = activeRoutes.get(key); + if (!group) { + group = { routeId: key, running: 0, queued: 0, paused: 0, completed: 0 }; + activeRoutes.set(key, group); + } + 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); + 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); + 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); + const helpers = team.landedHelpers ?? []; + const landedHelpers = routeSummaryRows(helpers.slice(-8).reverse().map(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 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, + routes, tasks, retiredRoutes, landedHelpers, recentDeliveries, + research: research ? { revision: research.revision, summary: oneLine(research.summary, 160) } : null, + omitted: { routes: activeRoutes.size - routes.length, tasks: taskRows.length - tasks.length, + retiredRoutes: retirementRows.length - retiredRoutes.length, landedHelpers: helpers.length - landedHelpers.length, + recentDeliveries: deliveries.length - recentDeliveries.length }, + }; +} + /** 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; diff --git a/src/solver/archive.ts b/src/solver/archive.ts index 7c91d764..e875da95 100644 --- a/src/solver/archive.ts +++ b/src/solver/archive.ts @@ -23,8 +23,10 @@ import { proofImportRecordSchema } from './proofImportRecord'; import { proofSearchCheckpointReferenceSchema, proofSearchRecordSchema } from './proofSearchRecords'; import { researchBasisSchema, researchRecordSchema } from './researchRecords'; import { nextCheckRecordSchema } from './nextCheckContract'; +import { retiredRouteSchema } from './routeControl'; import { goalProgressStateSchema } from './goalProgress'; import { MIN_TEAM_AGENTS, MAX_TEAM_AGENTS } from './teamCapacity'; +import { portfolioExplorationSchema, portfolioScoutSchema, type PortfolioExploration } from './portfolioExploration'; /** A recorded dispatch observation, never a permission to dispatch or accept a proof. */ export type DispatchWaitObservation = { @@ -49,8 +51,10 @@ export type SolverWorkerState = Pick; writerProcess?: import('../runtime/harnessProcess').HarnessProcessIdentity; nativeAgents?: import('../runtime/nativeDelegation').NativeResearchAgent[]; @@ -367,6 +372,11 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver. z.object({ mode: z.literal('read-only'), maxAgents: z.number().int().min(2).max(4) }).strict(), ]).optional(), agentTeam: agentTeamStateSchema.optional(), teamUsage: record.optional(), writerProcess: writerProcessSchema.optional(), + portfolioExploration: portfolioExplorationSchema.extend({ + scouts: z.array(portfolioScoutSchema.extend({ + 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(), @@ -384,7 +394,9 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver. planApproval: z.boolean().optional(), workers: z.array(research.extend({ id: z.string(), role, sessionRole: role.optional(), sessionLeadMode: z.enum(['planning', 'coordination']).optional(), - sessionAssignmentId: z.string().optional(), + sessionGroupId: z.string().optional(), sessionRouteId: z.string().optional(), sessionTaskId: z.string().optional(), + sessionTaskVersion: z.string().optional(), sessionTaskContextDigest: z.string().optional(), + sessionAssignmentId: z.string().optional(), sessionStatementReview: z.boolean().optional(), scheduling: z.object({ status: z.enum(['working', 'preparing', 'stopping', 'idle', 'stopped']), since: safeCount, action: z.string().optional(), taskId: z.string().optional(), wait: dispatchWaitObservation.optional() }).optional() })).optional(), cooperation: z.object({ tasks: z.array(taskRecord), groups: z.array(z.object({ group: z.object({ id: z.string(), @@ -395,8 +407,10 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver. searchCheckpoint: proofSearchCheckpointReferenceSchema.optional() }).passthrough()).optional(), nextChecks: z.array(nextCheckRecordSchema).optional(), deliveryReceipts: z.array(deliveryReceiptSchema).optional(), blockers: z.array(routeBlocker).optional(), + retiredRoutes: z.array(retiredRouteSchema).optional(), retiredRouteTasks: z.record(z.string()).optional(), proofReadyRecords: z.array(proofReadyRecordSchema).optional(), proofImports: z.array(proofImportRecordSchema).optional(), + landedHelpers: z.array(z.object({ qualifiedName: z.string(), file: z.string(), commit: z.string(), type: z.string() })).optional(), proofSearchRecords: z.record(proofSearchRecordSchema).optional(), initialPlanPublication: planPublication.optional(), planPublication: planPublication.optional(), lastLeadPauseInputDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(), diff --git a/src/solver/contextCompiler.ts b/src/solver/contextCompiler.ts index a64a3421..b42cdf68 100644 --- a/src/solver/contextCompiler.ts +++ b/src/solver/contextCompiler.ts @@ -11,9 +11,11 @@ import { contextTaskConsumers } from './taskConsumers'; import { mathematicalGapContextText } from './mathematicalGaps'; import { nextCheckContextText } from './nextChecks'; import { goalProgressTaskContext } from './goalProgress'; -import { leadPlanPublicationFeedback } from './cooperationShared'; +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; @@ -46,6 +48,8 @@ export type TaskContextInput = Readonly<{ maxOptionalContextBytes?: number; mandatory?: readonly ContextSection[]; optional?: readonly ContextSection[]; + /** The same thread already has this frozen problem; still send the new task's exact interfaces. */ + taskSwitch?: boolean; }>; export class TaskContextError extends Error { constructor(readonly code: 'math_context_missing_required' | 'math_context_stale_required' | @@ -62,6 +66,40 @@ const stale = (id: string): never => { throw new TaskContextError('math_context_ const present = (value: unknown): value is string => typeof value === 'string' && !!value.trim(); const localName = (name: string) => name.split('.').at(-1); const sourcePath = (problem: SolverProblem, file: string) => path.posix.join(problem.projectRelative.replaceAll('\\', '/'), file); +const ARCHIVE_INDEX_THRESHOLD = 48; +const compactArchive = (cooperation?: CooperationState) => Boolean(cooperation && ( + cooperation.tasks.length + (cooperation.history?.length ?? 0) > ARCHIVE_INDEX_THRESHOLD || + (cooperation.deliveries?.length ?? 0) > ARCHIVE_INDEX_THRESHOLD)); +const oneLine = (text: string) => { + const summary = text.trim().replace(/\s+/gu, ' '); + return summary.length > 120 ? summary.slice(0, 119) + '…' : summary; +}; + +export function deliveryIndexRow(record: DeliveryRecord, proofPath?: string) { + return { id: record.id, kind: record.kind, status: record.status, taskId: record.taskId, + summary: oneLine(record.summary), commit: record.commit, findingDigest: record.findingDigest, + file: record.commit ? (record.kind === 'proof' ? proofPath : undefined) ?? 'RESEARCH.md' : 'COOPERATION.json' }; +} + +export function landedHelperSection(cooperation?: CooperationState) { + const helpers = cooperation?.landedHelpers; + if (!helpers?.length) return; + return section('landed-helpers', 'sources', + 'Latest verified standalone helper signatures. Look up older entries in COOPERATION.json landedHelpers. ' + + '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. @@ -102,7 +140,7 @@ export function frozenSourceContext(problem: SolverProblem, file: string, source function originalProblemSection(input: TaskContextInput): ContextSection { const { problem } = input, statement = problem.contract.formalStatement, bytes = Buffer.byteLength(statement); const title = `${input.taskText}\n\nOriginal problem:`, digest = mathDigest(statement); - const file = bytes > COMPACT_CONTEXT_SOURCE_BYTES && present(problem.baseCommit) + const file = bytes > (compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES) && present(problem.baseCommit) ? Object.keys(problem.trustedFiles ?? {}).sort().find(file => problem.trustedFiles[file] === digest) : undefined; if (!file) return section('original-problem', 'problem', title, statement); return section('original-problem', 'problem', title, { commit: problem.baseCommit, path: sourcePath(problem, file), bytes, sha256: digest, @@ -294,9 +332,15 @@ function taskRecordReference(node: TaskRecord) { theoremName: node.task.theoremName, proofPath: node.task.proofPath }; } -function checkedHelperReference(input: TaskContextInput, node: TaskRecord) { +function compactTaskReference(node: TaskRecord) { + return { id: node.task.id, kind: node.task.kind, status: node.status, summary: oneLine(node.task.objective), + file: node.task.proofPath }; +} + +function checkedHelperReference(input: TaskContextInput, node: TaskRecord, compact?: boolean) { const proof = evidence(node, input.environmentDigest)!; - return { ...taskRecordReference(node), sharing: node.task.sharing ?? 'problem', + return { ...(compact ? compactTaskReference(node) : taskRecordReference(node)), theoremName: node.task.theoremName, + sharing: node.task.sharing ?? 'problem', source: { commit: proof.commit, path: sourcePath(input.problem, node.task.proofPath!), sourceDigest: proof.sourceDigest }, evidence: 'recorded-not-replayed' }; } @@ -313,6 +357,10 @@ function sourceReferences(input: TaskContextInput) { retrieval: 'Read full proofs and namespace/section/instance context with git show COMMIT:PATH in this isolated worktree. Source references identify immutable content; they grant no proof acceptance.', files: files.map(file => { const context = input.frozenContexts![file], declarations = problem.declarations[file] ?? []; + if ((input.taskSwitch || compactArchive(input.cooperation)) && Buffer.byteLength(context) > 4 * 1024) { + return { commit: problem.baseCommit, path: sourcePath(problem, file), contextDigest: problem.sourceStructure?.[file], + imports: problem.sourceImports?.[file], declarationCount: declarations.length, contextByReference: true }; + } return { commit: problem.baseCommit, path: sourcePath(problem, file), contextDigest: problem.sourceStructure?.[file], imports: problem.sourceImports?.[file], // Large sources already retain every exact header in context. Repeating the @@ -337,13 +385,15 @@ function frozenDeclarationOrder(input: TaskContextInput) { .filter(([file]) => !Object.hasOwn(input.problem.frozenFiles ?? {}, file)) .map(([file, declarations]) => { const names = declarations.map(declaration => declaration.name), context = input.frozenContexts?.[file]; - return [file, context && Buffer.byteLength(context) > COMPACT_CONTEXT_SOURCE_BYTES ? { + const byReference = context && Buffer.byteLength(context) > + (input.taskSwitch || compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES); + return [file, byReference ? { encoding: 'frozen-declaration-order-v1', commit: input.problem.baseCommit, path: sourcePath(input.problem, file), declarationCount: names.length, orderDigest: mathDigest(canonicalMathJson(names)), retrieval: 'Read the complete frozen file with git show COMMIT:PATH for its exact declaration order. ' + 'The ordered array of declaration names as written (including dotted names and repeated local names) must match ' + 'declarationCount and SHA-256(canonicalMathJson(names)) = orderDigest. ' + - 'Missing or mismatched source is unavailable. The frozen-sources context keeps the declaration headers inline; ' + + 'Missing or mismatched source is unavailable. ' + 'this reference replaces only the duplicate name list and grants no proof acceptance.', } : names]; })); @@ -424,7 +474,7 @@ export function leadResearchInputSection(input: Pick) { if (input.action?.kind !== 'lead' || !input.cooperation?.error) return; return section('plan-rejection', 'feedback', - 'Host rejected the proposed plan. Repair this error while preserving every exact original target:', { + 'Host rejected the proposed plan. Repair this error while preserving every exact original target. ' + LEAD_PLAN_REPAIR_INSTRUCTION, { error: input.cooperation.error, rejection: input.cooperation.planRejection, originalTargets: input.problem.targets.map(({ proofPath, theoremName }) => ({ proofPath, theoremName })), }); @@ -464,6 +514,13 @@ function optionalDeliveries(input: TaskContextInput, required: ReadonlySet { // Interfaces and receipts live in mandatory sections. A delivery summary is advisory prose. const current = record.taskId ? byId.get(record.taskId) : undefined; + if ((compactArchive(input.cooperation) || input.taskSwitch) && !(record.taskId && required.has(record.taskId))) { + omitted.push({ id: `delivery:${record.id}:details`, kind: 'delivery', reason: 'advisory-details-by-reference' }); + const file = current?.task.proofPath && sourcePath(input.problem, current.task.proofPath); + return [{ ...section(`delivery:${record.id}`, 'delivery', + 'Delivery index (advisory; retrieve the saved source or the record in COOPERATION.json before using it):', + deliveryIndexRow(record, file)), priority: priority(record) * 10 + 2 }]; + } // Keep a shared mathematical finding independently selectable from its delivery metadata. const sharedFinding = deliveryMatchesFinding(record, current); const ownFinding = sharedFinding ? undefined : deliveryFinding(record); @@ -501,7 +558,8 @@ function optionalDeliveries(input: TaskContextInput, required: ReadonlySet ({ ...consumer.task, taskDigest: consumer.taskDigest, @@ -569,7 +633,7 @@ export function compileTaskContext(input: TaskContextInput): { message: string; if (deferred.length) { mandatory.push(section('task-record-reference-encoding', 'sources', 'Digest-bound task record retrieval (required before using an indexed task):', { - retrieval: 'Read worktree-root COOPERATION.json tasks[] and match record.task.id to row.id. Require taskVersion(record.task) = row.taskDigest ' + + retrieval: 'Read worktree-root COOPERATION.json tasks[] and match record.task.id to row.id. If shown, require taskVersion(record.task) = row.taskDigest ' + 'and SHA-256(canonicalMathJson(record)) = row.recordDigest; canonicalMathJson sorts object keys recursively and omits undefined object fields. ' + 'Missing or mismatched records are unavailable. Retrieve exact Lean types, premises, conditions, feedback and evidence before reasoning from ' + 'an indexed task or replacing the full plan. Every visible task remains discoverable, including running and blocked work. ' + @@ -579,11 +643,11 @@ export function compileTaskContext(input: TaskContextInput): { message: string; const helpers = deferred.filter(closedLeadHelper), others = deferred.filter(node => !closedLeadHelper(node)); if (helpers.length) mandatory.push(section('checked-helper-catalog', 'sources', 'Checked helpers outside the current open-task closure (retrieve before using; recorded, not replayed):', { - helpers: helpers.map(node => checkedHelperReference(input, node)), + helpers: helpers.map(node => checkedHelperReference(input, node, compact)), })); if (others.length) mandatory.push(section('task-record-index', 'sources', 'Other visible task records outside the current goal and requested-input closure (retrieve exact interfaces before use):', { - tasks: others.map(taskRecordReference), + tasks: others.map(node => compact ? compactTaskReference(node) : taskRecordReference(node)), })); } if (action?.kind === 'lead') { @@ -646,8 +710,8 @@ export function compileTaskContext(input: TaskContextInput): { message: string; 'row.evidence.verification.targetCommit. Only null has this meaning; absent fields remain absent, and every distinct explicit value is retained.', })); } - mandatory.push(section('declaration-order', 'sources', 'Frozen declaration order by file:', frozenDeclarationOrder(input)), - section('original-targets', 'problem', 'Original targets:', problem.targets)); + if (!input.taskSwitch) mandatory.push(section('declaration-order', 'sources', 'Frozen declaration order by file:', frozenDeclarationOrder(input)), + section('original-targets', 'problem', 'Original targets:', problem.targets)); mandatory.push(...(input.mandatory ?? [])); const { sections: deliveries, findingSources } = optionalDeliveries(input, required, byId, omitted); const active = action?.kind === 'task' ? action.task : undefined; @@ -695,14 +759,20 @@ export function compileTaskContext(input: TaskContextInput): { message: string; optional.push(...deliveries); for (const node of [...(input.cooperation?.tasks ?? [])].sort((a, b) => rank(a.task.id, taskGroup(a.task)) - rank(b.task.id, taskGroup(b.task)))) { + // Deferred Lead records already have a compact index entry and a live retrieval path. + if (compact && deferredIds.has(node.task.id)) continue; const priority = rank(node.task.id, taskGroup(node.task)) * 10; - if (node.feedback && node.task.id !== active?.id) optional.push({ ...section(`feedback:${node.task.id}`, 'feedback', `Host feedback for ${node.task.id}:`, node.feedback), priority: priority + 3 }); + if (node.feedback && node.task.id !== active?.id) optional.push({ ...section(`feedback:${node.task.id}`, 'feedback', `Host feedback for ${node.task.id}:`, + compact ? oneLine(node.feedback) + ' (full feedback in COOPERATION.json tasks)' : node.feedback), priority: priority + 3 }); if (present(node.finding)) optional.push({ ...section(`finding:${node.task.id}`, 'finding', `Advisory finding for ${node.task.id}:`, { - taskId: node.task.id, taskDigest: taskVersion(node.task), finding: node.finding, + taskId: node.task.id, taskDigest: taskVersion(node.task), + ...(compact && !required.has(node.task.id) ? { summary: oneLine(node.finding), reference: 'COOPERATION.json tasks' } : { finding: node.finding }), savedSource: findingSources.get(node.task.id), }), priority: priority + 1 }); if (!required.has(node.task.id) && !consumerIds.has(node.task.id) && !deferredIds.has(node.task.id)) optional.push({ ...section(`interface:${node.task.id}`, 'interfaces', 'Other visible task (advisory planning context):', - { ...node.task, taskDigest: taskVersion(node.task), status: node.task.status ?? 'active', executionStatus: node.status }), priority: priority + 8 }); + compact ? { id: node.task.id, kind: node.task.kind, summary: oneLine(node.task.objective), + file: node.task.proofPath, status: node.status, reference: 'COOPERATION.json tasks' } + : { ...node.task, taskDigest: taskVersion(node.task), status: node.task.status ?? 'active', executionStatus: node.status }), priority: priority + 8 }); } for (const route of input.cooperation?.proofRoutes ?? []) { if (route.id === selectedRoute?.id) continue; @@ -717,9 +787,11 @@ export function compileTaskContext(input: TaskContextInput): { message: string; } const proof = entry.integratedCheck ?? entry.proof; optional.push({ ...section(id, 'history', 'Earlier route finding (historical and advisory; not a current premise):', { - taskId: entry.task.id, taskDigest: taskVersion(entry.task), objective: entry.task.objective, - producer: entry.producer, finding: entry.finding, commit: proof?.commit, sourceDigest: proof?.sourceDigest, - evidenceRefs: proof?.verification.results.map(result => result.receiptId), + taskId: entry.task.id, taskDigest: taskVersion(entry.task), + ...(compact ? { kind: entry.task.kind, status: 'historical', summary: oneLine(entry.finding ?? entry.task.objective) } : { + objective: entry.task.objective, producer: entry.producer, finding: entry.finding, sourceDigest: proof?.sourceDigest, + evidenceRefs: proof?.verification.results.map(result => result.receiptId) }), + commit: proof?.commit, source: proof && entry.task.proofPath ? { commit: proof.commit, path: sourcePath(problem, entry.task.proofPath) } : undefined, evidence: 'historical-not-current' }), priority: rank(entry.task.id, taskGroup(entry.task)) * 10 + 5 }); } diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index f4f516a1..60fcd4f0 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -38,7 +38,8 @@ import { assignmentDeliveryFile, isDefinitionTask, isFeasibilityReview, taskGrou 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, leadPlanPublicationTarget, rejectionCode, CooperationState, TaskVersions, DispatchBudget, RETRY_DISPATCH, DispatchResult, bounded } from './cooperationShared'; +import { digest, directDeliveryRejections, isTaskSourceRepairFeedback, leadPlanPublicationTarget, 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'; @@ -47,6 +48,8 @@ export type { CooperativeTask, RouteGroup, RouteRecord, TaskAssignment, TaskReco export { readCooperationPlan } from './cooperationShared'; export type { ReviewRecord, HumanEditRecord, InitialPlanPublication, CooperationState } from './cooperationShared'; +const PREEMPTION_MISMATCH_COOLDOWN_MS = 10 * 60_000; + /** Lead plans; workers claim distinct ready obligations; only checked source enters the canonical proof. */ export class CooperativeResearch extends CooperationInputs { private humanGuidanceCheckpoint(stopped = false): Promise { @@ -153,9 +156,17 @@ export class CooperativeResearch extends CooperationInputs { } 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) || + 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 && @@ -345,7 +356,7 @@ export class CooperativeResearch extends CooperationInputs { 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.researchDecisions === undefined && + 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), @@ -413,7 +424,18 @@ export class CooperativeResearch extends CooperationInputs { 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) return result; + 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 { @@ -581,7 +603,8 @@ export class CooperativeResearch extends CooperationInputs { 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.'); + 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.publishedPlans.has(action) ? undefined : leadPlanPublicationTarget(action); const { file, ...envelope } = target ?? {}; const revision = Boolean(this.archive.tasks.length && action.planVersion); @@ -1283,6 +1306,7 @@ export class CooperativeResearch extends CooperationInputs { 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), @@ -1324,18 +1348,24 @@ export class CooperativeResearch extends CooperationInputs { const notesFile = path.join(worker.worktree, 'RESEARCH.md'); const savedNotes = (publishedPlan || schedulingDraft) && fs.existsSync(notesFile) ? readMathText(notesFile, MAX_RESEARCH_NOTES_BYTES) : ''; - let unchangedCheckpoint = false; + let unchangedCheckpoint = false, changedNotes = false; if (schedulingDraft) { try { const seedNotes = git(worker.worktree, ['ls-tree', '--name-only', action.seedCommit, '--', 'RESEARCH.md']) ? committedSource(worker.worktree, action.seedCommit, 'RESEARCH.md') : ''; unchangedCheckpoint = this.proposedPlanDigest(seedNotes) === this.proposedPlanDigest(savedNotes); + changedNotes = seedNotes.trim() !== savedNotes.trim(); } catch { /* Without a readable dispatch baseline, validate the saved response normally. */ } } const notes = savedNotes.trimStart(); - const hasFinalPlan = this.publishedPlans.get(action)?.responseDigest !== this.proposedPlanDigest() && - (notes.startsWith('{') || /```(?:math|json|math-plan)\s*\n/u.test(notes)); - if (unchangedCheckpoint && !requiredDecision) { + const hasPlanResponse = notes.startsWith('{') || /```(?:math|json|math-[a-z-]+)\b/u.test(notes); + const hasFinalPlan = hasPlanResponse && this.publishedPlans.get(action)?.responseDigest !== this.proposedPlanDigest(); + if (schedulingDraft && changedNotes && notes.trim() && !hasPlanResponse) { + // 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: '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'); @@ -1344,14 +1374,16 @@ export class CooperativeResearch extends CooperationInputs { } 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); - if (!unchangedCheckpoint || requiredDecision) accepted = true; + } else { + await this.acceptPlan(undefined, undefined, undefined, action); + accepted = true; + } } catch (error) { this.rejectPlan(error, recovering ? recoveryKind : undefined); if (recovering) { - // A checkpoint or failed request may leave only a partial graph. Keep it resumable. + // 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, false); + this.preserveLeadDraft(commit, action.seedCommit, reason, { requestDecision: false, shareSource: sourceChanged }); } if (!this.archive.tasks.length && !(recovering && recoveryKind === 'request-failure')) { try { await this.startInitialTasks(); } @@ -1388,7 +1420,7 @@ export class CooperativeResearch extends CooperationInputs { for (;;) { const snapshot = await this.input.exclusiveCheck(async () => { if (this.archive.planVersion !== staged.planVersion) { - this.preserveLeadDraft(commit, action.seedCommit, 'math_lead_decision_superseded', false); this.changed(); return; + 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 }; @@ -1398,7 +1430,7 @@ export class CooperativeResearch extends CooperationInputs { 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', false); this.changed(); return 'superseded'; + 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'; @@ -1427,7 +1459,7 @@ export class CooperativeResearch extends CooperationInputs { 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', - this.archive.planVersion === staged.planVersion); + { requestDecision: this.archive.planVersion === staged.planVersion }); this.changed(); }); return { checkWhole: false, ...saved }; diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts index 1a553ae9..453d7edb 100644 --- a/src/solver/cooperationCore.ts +++ b/src/solver/cooperationCore.ts @@ -16,7 +16,7 @@ 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 } from './statementReview'; +import { isStatementAction, statementReviewSummary, type StatementReview } from './statementReview'; import { type ProofReferences } from './proofReferences'; import { attributeTaskReferences } from './taskReferenceAttribution'; import { buildProofContinuation } from './progress'; @@ -24,11 +24,14 @@ 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'; @@ -123,6 +126,7 @@ export abstract class CooperationCore { 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; @@ -144,6 +148,34 @@ export abstract class CooperationCore { 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']); @@ -494,6 +526,46 @@ export abstract class CooperationCore { 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); @@ -526,6 +598,7 @@ export abstract class CooperationCore { 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'); @@ -549,8 +622,10 @@ export abstract class CooperationCore { 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') occupy(taskGroup(active.action.task), id); - for (const publication of this.proofPublications.values()) occupy(taskGroup(publication.action.task), publication.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 review of this.archive.statementReviews ?? []) { const node = nodes.get(review.taskId); if (node && ['translating', 'reviewing'].includes(review.status)) occupy(taskGroup(node.task), review.workerId); @@ -607,6 +682,13 @@ export abstract class CooperationCore { 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, + } 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 => { @@ -874,7 +956,8 @@ export abstract class CooperationCore { return Boolean(review && review.status === 'running' && review.commit === action.seedCommit && review.sourceDigest === action.sourceDigest && review.assignmentId === action.assignmentId); } - return action.kind !== 'task' || this.archive.tasks.some(node => node.assignment === action.assignment && digest(node.task) === action.assignment.taskDigest && + return action.kind !== 'task' || !this.actionRouteRetired(action) && + this.archive.tasks.some(node => node.assignment === action.assignment && digest(node.task) === action.assignment.taskDigest && (!node.nextCheckId || this.archive.nextChecks?.some(record => record.id === node.nextCheckId && record.status === 'pending' && currentNextCheck(record, this.archive, { problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest }))) && diff --git a/src/solver/cooperationInputs.ts b/src/solver/cooperationInputs.ts index 689e7c9e..983e170e 100644 --- a/src/solver/cooperationInputs.ts +++ b/src/solver/cooperationInputs.ts @@ -1,17 +1,19 @@ 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 } from '../math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest, 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, readDeliveryLines, readMathResponse, parseMathResponse } from './deliveries'; -import { committedSource, git } from './problem'; +import { assertSolverSources, committedSource, commitSolverProjection, git, withSolverWorktree } from './problem'; import { isStatementAction } from './statementReview'; import { captureDeliveryArtifacts } from './deliveryArtifacts'; import { bindMathematicalGap } from './mathematicalGaps'; -import { assignmentDeliveryFile, leadPlanDeliveryFile, type TaskRecord, type CooperativeAction } from './tasks'; +import { assignmentDeliveryFile, isFeasibilityReview, isFinalCandidateReview, leadPlanDeliveryFile, type TaskRecord, type CooperativeAction } from './tasks'; import { directDeliveryRejections, rejectionCode, HumanEditRecord, TaskVersions, bounded, leadPlanPublicationFeedback, parseLeadPlan, type PlanPublicationRejection } from './cooperationShared'; import { CooperationPlanning } from './cooperationPlanning'; @@ -20,6 +22,7 @@ import { acceptContextCheckpoint, contextCheckpointRejection, contextCheckpointR 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 { @@ -457,6 +460,37 @@ export abstract class CooperationInputs extends CooperationPlanning { 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', diff --git a/src/solver/cooperationIntegration.ts b/src/solver/cooperationIntegration.ts index 45d7eefc..35eac393 100644 --- a/src/solver/cooperationIntegration.ts +++ b/src/solver/cooperationIntegration.ts @@ -14,6 +14,7 @@ import { CooperationTaskProofs, type ProofDeliveryAnnotation, type ProofDelivery 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']); @@ -34,6 +35,51 @@ function expectedRejection(error: unknown, expected: ReadonlySet): 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); + 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) })) }; diff --git a/src/solver/cooperationPlanning.ts b/src/solver/cooperationPlanning.ts index e50c750a..1d626332 100644 --- a/src/solver/cooperationPlanning.ts +++ b/src/solver/cooperationPlanning.ts @@ -16,6 +16,7 @@ import { keepRespacedObjectives, taskGroup, taskVersion, taskProofContractVersio import { digest, HumanEditRecord, InitialPlanPublication, RETRY_DISPATCH, DispatchResult, bounded, 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'; @@ -25,6 +26,20 @@ 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 { @@ -56,9 +71,12 @@ export abstract class CooperationPlanning extends CooperationIntegration { const rebased = Boolean(action?.kind === 'lead' && this.current(action) && this.publishedPlans.has(action) && action.planVersion && action.planVersion !== base?.version); // A rebased repeat of an applied publication already answered the review it was written against. - return readCooperationPlan(this.input.state.problem, this.lead.worktree, base, { - acceptedBaseVersions: [...(base ? [base.version] : []), ...(rebased ? [(action as { planVersion: string }).planVersion] : [])], - rebased, restoring: !action, ...(rebased ? {} : { goalPath: this.goalPathReview() }) }); + const goalPath = rebased ? undefined : this.goalPathReview(); + try { + return readCooperationPlan(this.input.state.problem, this.lead.worktree, base, { + acceptedBaseVersions: [...(base ? [base.version] : []), ...(rebased ? [(action as { planVersion: string }).planVersion] : [])], + 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. @@ -165,14 +183,14 @@ export abstract class CooperationPlanning extends CooperationIntegration { } protected proposedPlanDigest(source?: string) { try { - const { tasks, groups, proofRoutes, upsert, remove, baseVersion, goalPath, progressReview, + 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; + 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 })); + 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. @@ -185,13 +203,18 @@ export abstract class CooperationPlanning extends CooperationIntegration { // 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 stalled = previous?.proposalDigest === proposalDigest && previous.inputDigest === inputDigest && previous.error === reason; + 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') return; + if (stalled && recoveryKind === 'restore' && previous?.proposalDigest === proposalDigest) return; this.archive.error = reason; - this.archive.planRejection = { proposalDigest, inputDigest, error: reason, stalled }; - // A repeated rejection of the same proposal for the same input answers its wake-ups; it is not new input. - if (stalled) dropLeadWakes(this.archive.leadWakes!); else this.wakeLead('plan-rejected'); + 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 } : {}) }); } @@ -211,11 +234,13 @@ export abstract class CooperationPlanning extends CooperationIntegration { return merged; }); } - protected preserveLeadDraft(commit: string, seedCommit: string | undefined, reason: string, requestDecision = true) { - const summary = `Saved Lead draft pending integration: ${reason}. ` + + 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 (!this.archive.deliveries?.some(record => record.producer === this.lead.id && record.kind === 'progress' && + 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 }); } @@ -278,6 +303,9 @@ export abstract class CooperationPlanning extends CooperationIntegration { /** 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) : []); @@ -322,7 +350,7 @@ export abstract class CooperationPlanning extends CooperationIntegration { throw new Error('math_plan_group_engineer_unavailable'); return { ...group }; }); - return { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown }; + return { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown, retirement }; } protected async acceptPlan(planInput?: LeadPlan, edit?: HumanEditRecord, publication?: { action: Extract; @@ -330,7 +358,7 @@ export abstract class CooperationPlanning extends CooperationIntegration { leadAction?: Extract) { const decidingAction = publication?.action ?? leadAction; const restoringPlan = !decidingAction && !edit && this.archive.tasks.length > 0; - const { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown } = this.preparePlan( + const { plan, nextCheckDecisions, researchDecisions, progressDecision, configuredGroups, shown, retirement } = this.preparePlan( planInput ?? this.readLeadPlan(leadAction), decidingAction, restoringPlan); const { tasks, proofRoutes } = plan; const publicationResponseDigest = publication ? this.proposedPlanDigest( @@ -367,10 +395,21 @@ export abstract class CooperationPlanning extends CooperationIntegration { }); 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) { 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); @@ -421,7 +460,7 @@ export abstract class CooperationPlanning extends CooperationIntegration { 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) this.archive.planEdited = true; + 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; @@ -441,12 +480,15 @@ export abstract class CooperationPlanning extends CooperationIntegration { 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.statementReview && + 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(); @@ -456,6 +498,45 @@ export abstract class CooperationPlanning extends CooperationIntegration { } 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); @@ -523,6 +604,7 @@ export abstract class CooperationPlanning extends CooperationIntegration { 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 } : {}) })); } /** diff --git a/src/solver/cooperationRoutes.ts b/src/solver/cooperationRoutes.ts new file mode 100644 index 00000000..94cf514d --- /dev/null +++ b/src/solver/cooperationRoutes.ts @@ -0,0 +1,64 @@ +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/cooperationShared.ts b/src/solver/cooperationShared.ts index 2e7e0815..2980f4a8 100644 --- a/src/solver/cooperationShared.ts +++ b/src/solver/cooperationShared.ts @@ -1,13 +1,15 @@ -import { parseCooperationPlan } from './tasks'; +import { parseCooperationPlan, type CooperationPlanProblem } from './tasks'; import { assertPlanTaskTypeContracts } from './taskTypeContract'; import { limitMathOutput } from '../math/mathProcess'; -import { type SolverProblem } from './problem'; import { type ProofCheck } from './modules/evidence'; import { readMathResponse as block, type DeliveryRecord } from './deliveries'; +import type { LandedHelper } from './incrementalHelpers'; import { type TaskProof } from './cooperativeProof'; import { type StatementReview } from './statementReview'; import { type DeliveryArtifactManifest } from './deliveryArtifacts'; -import { type BlockerBasis, type RouteBlocker } from './routeControl'; +import { routeRetirementSchema, type BlockerBasis, type RouteBlocker, type RetiredRoute, type RouteRetirement } from './routeControl'; +import { z } from 'zod'; +import { invalidPlanField, PlanValidationError, planFieldPath, type PlanIssue } from './planDiagnostics'; import { type ProofRoute } from './proofRoutes'; import { type ObligationSnapshot, type ObligationProgressReceipt } from './obligationProgress'; import { type TaskConsumerProjection } from './taskConsumers'; @@ -77,6 +79,7 @@ export type FailedTaskInput = { id: string; taskId: string; taskDigest: string; canonicalSourceDigest: string; canonicalTargetDigest: string; feedback: string; repair?: { taskId: string; taskDigest: string; workerId: string; pending: boolean; startedAttempt?: number } }; export type CooperationState = { tasks: TaskRecord[]; groups?: RouteRecord[]; canonicalCommit?: string; leadSeedCommit?: string; review?: ReviewRecord; error?: string; + landedHelpers?: LandedHelper[]; /** Context-only notes actually delivered to this worker; decisions remain separate from proof state. */ humanGuidance?: HumanGuidanceRecord[]; /** Context-only reverse uses, projected from the full archive without expanding execution visibility. */ @@ -108,7 +111,7 @@ export type CooperationState = { tasks: TaskRecord[]; groups?: RouteRecord[]; ca planPublicationRejection?: PlanPublicationRejection; /** Worker-private projection of the current checkpoint request's diagnostic. */ contextCheckpointRejection?: ContextCheckpointRejection; - planRejection?: { proposalDigest: string; inputDigest: string; error: string; stalled: boolean }; + planRejection?: { proposalDigest: string; inputDigest: string; error: string; stalled: boolean; malformed?: true; issues?: PlanIssue[] }; lastLeadInputDigest?: string; /** Durable Lead wake-ups; a restart re-asks those whose dispatch did not settle. */ leadWakes?: import('./leadWakes').LeadWakes; @@ -141,6 +144,9 @@ export type CooperationState = { tasks: TaskRecord[]; groups?: RouteRecord[]; ca targetTaskId: string; taskId: string }[]; failedTaskInputs?: FailedTaskInput[]; blockers?: RouteBlocker[]; + retiredRoutes?: RetiredRoute[]; + /** Branch-exclusive members are kept by task ID after their proof route leaves the graph. */ + retiredRouteTasks?: Record; proofRoutes?: ProofRoute[]; progressSnapshot?: ObligationSnapshot; progressReceipts?: ObligationProgressReceipt[]; @@ -172,6 +178,10 @@ export function leadPlanPublicationTarget(action: CooperativeAction | undefined) return { file, kind: 'plan' as const, dispatchNonce: nonce, baseVersion: action.planVersion }; } +export const LEAD_PLAN_REPAIR_INSTRUCTION = + 'Validate the candidate JSON from the Lead worktree with theorem-os plan-validate --file .scratch/plan.json. ' + + 'Use theorem-os plan-apply --file .scratch/plan.json to save a validated plan in RESEARCH.md.'; + /** Reuse the saved diagnostic across turns while always targeting the current dispatch. */ export function leadPlanPublicationFeedback(action: CooperativeAction | undefined, state: Pick): string | undefined { @@ -182,7 +192,8 @@ export function leadPlanPublicationFeedback(action: CooperativeAction | undefine JSON.stringify(target) + '. ' + 'Preserve the log and use the current assignment protocol; a saved rejection may come from an earlier dispatch. ' + 'Keep kind:"plan", baseVersion and any dispatchNonce at the top level of the same event as tasks or upsert/remove; ' + - 'a bare plan patch is not a publication event. Only the first valid publication in a dispatch is accepted. This intake feedback grants no proof acceptance.'; + 'a bare plan patch is not a publication event. Only the first valid publication in a dispatch is accepted. This intake feedback grants no proof acceptance. ' + + LEAD_PLAN_REPAIR_INSTRUCTION; } export const deliveryInputFields = (record: DeliveryRecord) => ({ taskId: record.taskId, taskDigest: record.taskDigest, kind: record.kind, status: record.status, @@ -193,15 +204,29 @@ export const deliveryInputFields = (record: DeliveryRecord) => ({ sourceUses: record.sourceUses, searchCheckpoint: record.searchCheckpoint, }); export type LeadPlan = ReturnType & { fromPatch?: boolean; goalPathDecisions?: GoalPathDecisions; - goalProgressDecision?: GoalProgressDecision; researchDecisions?: unknown; nextCheckDecisions?: NextCheckDecision[] }; + goalProgressDecision?: GoalProgressDecision; researchDecisions?: unknown; nextCheckDecisions?: NextCheckDecision[]; + retireRoutes?: RouteRetirement[] }; type LeadPlanOptions = Parameters[2] & { goalPath?: GoalPathReview; restoring?: boolean }; /** * Model proposes tasks or a revision of the accepted graph; the host validates coverage, exact targets and an acyclic * dependency graph. A revision may answer the current goal-path review, whose mechanical candidates expand first. */ -export function parseLeadPlan(problem: SolverProblem, value: unknown, base?: PlanPatchBase, options: LeadPlanOptions = {}): LeadPlan { +export function parseLeadPlan(problem: CooperationPlanProblem, value: unknown, base?: PlanPatchBase, options: LeadPlanOptions = {}): LeadPlan { const { goalPath, restoring, ...patchOptions } = options; value = liftNestedPlanPatch(value); + const retirement = value && typeof value === 'object' && 'retireRoutes' in value + ? z.array(routeRetirementSchema).min(1).max(32).safeParse(value.retireRoutes) : undefined; + if (retirement && !retirement.success) { + const issues = retirement.error.issues.map(issue => ({ path: planFieldPath(['retireRoutes', ...issue.path]), message: issue.message })); + throw new PlanValidationError('math_plan_invalid_retire_routes', + issues.map(issue => `${issue.path}: ${issue.message}`).join('\n'), issues); + } + if (retirement?.success) { + const routes = retirement.data.map(item => item.routeId); + const repeated = routes.findIndex((route, index) => routes.indexOf(route) !== index); + if (repeated >= 0) throw invalidPlanField('math_plan_invalid_retire_routes', `retireRoutes[${repeated}].routeId`, + 'Each retired route ID may appear only once.'); + } const progressDecision = parseGoalProgressDecision(value, restoring); const nextCheckDecisions = parseNextCheckDecisions(value); const answered = applyGoalPathDecisions(value, goalPath, base); @@ -213,8 +238,9 @@ export function parseLeadPlan(problem: SolverProblem, value: unknown, base?: Pla const patched = isPlanPatch(answered.value); const plan = parseCooperationPlan(problem, isPlanPatch(answered.value) ? expandPlanPatch(answered.value, base, patchOptions) : answered.value); assertPlanTaskTypeContracts(plan.tasks, base?.tasks); - return { ...plan, ...(patched ? { fromPatch: true } : {}), ...decisions }; + return { ...plan, ...(patched ? { fromPatch: true } : {}), ...decisions, + ...(retirement?.success ? { retireRoutes: retirement.data } : {}) }; } -export function readCooperationPlan(problem: SolverProblem, worktree: string, base?: PlanPatchBase, options?: LeadPlanOptions): LeadPlan { +export function readCooperationPlan(problem: CooperationPlanProblem, worktree: string, base?: PlanPatchBase, options?: LeadPlanOptions): LeadPlan { return parseLeadPlan(problem, block(worktree, 'math-plan'), base, options); } diff --git a/src/solver/cooperationStatements.ts b/src/solver/cooperationStatements.ts index 35c1dbc3..432eab8a 100644 --- a/src/solver/cooperationStatements.ts +++ b/src/solver/cooperationStatements.ts @@ -6,11 +6,12 @@ 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, type StatementReview } from './statementReview'; + 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 { @@ -51,13 +52,10 @@ export abstract class CooperationStatements extends CooperationCore { } /** 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 && this.dependencies(node.task, nodes) + 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 supersedeStatementReview(review: StatementReview) { - review.status = 'superseded'; - for (const record of this.archive.deliveries ?? []) if (record.statementReviewId === review.id) record.status = 'superseded'; - } protected prepareStatementContexts(nodes: readonly TaskRecord[] = this.archive.tasks, canonical = this.archive.canonicalCommit!, checkEnvironment?: { environment: NodeJS.ProcessEnv; digest: string; current?: () => boolean }): Promise | undefined { diff --git a/src/solver/cooperativeProof.ts b/src/solver/cooperativeProof.ts index b829fd29..9ad64582 100644 --- a/src/solver/cooperativeProof.ts +++ b/src/solver/cooperativeProof.ts @@ -338,7 +338,8 @@ export function createTaskSourceProjector(problem: SolverProblem, worktree: stri ?.qualifiedName ?? dependency.theoremName!).replace(/^_root_\./u, ''), type: dependency.type!, })); const project = (task: CooperativeTask, retainedGoals: readonly string[], conditions: readonly CooperativeTask[] = [], - observe?: (hints: readonly ProjectionDependencyHint[], context: readonly ProjectionDeclaration[]) => void): Map => { + observe?: (hints: readonly ProjectionDependencyHint[], context: readonly ProjectionDeclaration[], + closure: readonly ProjectionDeclaration[]) => void): Map => { assertTaskTypeContract(task); conditions.forEach(assertTaskTypeContract); const inputs = conditionalInputs(conditions); @@ -699,7 +700,7 @@ export function createTaskSourceProjector(problem: SolverProblem, worktree: stri } pendingContext.push(...syntaxDependencies!.get(id) ?? []); } - observe(hints, context); + observe(hints, context, syntaxConsumers.filter(item => item.name && unique.has(item.id)).map(describe)); // Hint callers consume only observations. Building and compacting acceptance sources here // repeats every owned-file edit for each transitive original input, then discards the result. return sources; @@ -784,12 +785,13 @@ export function createTaskSourceProjector(problem: SolverProblem, worktree: stri } return options.compact ? compactTaskSources(problem, sources, task, retainedGoals, options.preserved) : sources; }; - const observations = new Map(); + const observations = new Map(); const observe = (task: CooperativeTask, retainedGoals: readonly string[], conditions: readonly CooperativeTask[]) => { const key = canonicalMathJson({ task, retainedGoals, conditions }); let value = observations.get(key); if (!value) { - project(task, retainedGoals, conditions, (hints, context) => { value = { hints, context }; }); + project(task, retainedGoals, conditions, (hints, context, closure) => { value = { hints, context, closure }; }); observations.set(key, value!); } return value!; @@ -805,6 +807,10 @@ export function createTaskSourceProjector(problem: SolverProblem, worktree: stri possibleContextGoals(task: CooperativeTask, retainedGoals: readonly string[], conditions: readonly CooperativeTask[] = []): readonly ProjectionDeclaration[] { return structuredClone(observe(task, retainedGoals, conditions).context); }, + /** Source-based selection for a standalone helper. Independent proof checking is still required. */ + helperClosure(task: CooperativeTask): readonly ProjectionDeclaration[] { + return structuredClone(observe(task, [], []).closure); + }, expectedType(task: CooperativeTask, conditions: readonly CooperativeTask[]): string | undefined { return task.kind === 'lemma' ? conditions.length ? conditionalExpectedType(task.theoremName!, task.type!, conditionalInputs(conditions)) : task.type : undefined; diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index d3b48917..52bcb7f1 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -247,6 +247,8 @@ export async function checkDeclarationArtifacts(input: { state: DeclarationArtifactIdentity; worktree: string; commit: string; declarations: DeclarationSubmission['declarations']; env: NodeJS.ProcessEnv; signal: AbortSignal; timeoutMs?: number; allowAuxiliaryDefinitions?: boolean; + /** Only for host-selected declarations whose signature comes from independently checked source. */ + inferredExpectedTypes?: ReadonlySet; assertWriterStopped: () => void; }): Promise { const declarations = parseDeclarationSubmission({ declarations: input.declarations }).declarations; @@ -281,19 +283,25 @@ export async function checkDeclarationArtifacts(input: { const original = problem.targets.some(target => target.proofPath === declaration.file && target.theoremName === declaration.name); if (definition && original) return submissionFail('definition_must_be_auxiliary'); // A transient projection request reuses source isolation, not cooperation state or scheduling. + const checkHelperInDraft = input.inferredExpectedTypes?.has(declaration.file + '\0' + declaration.name) === true; + const type = checkHelperInDraft ? undefined : declaration.type; const task: CooperativeTask = { id: `declaration-${declarationDigest}`, kind: original ? 'goal' : 'lemma', ...(definition && { declaration: 'definition' }), objective: declaration.description || `Check ${declaration.name}`, proofPath: declaration.file, - theoremName: declaration.name, type: declaration.type, dependsOn: [], revision: 0 }; - const project = createTaskSourceProjector(problem, checkout, commit, { compact: true }); - const sources = submissionContent(() => project(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); - const checkedCommit = commitSolverProjection(problem, checkout, `Check declaration ${declaration.name}`); + 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', + 'math_task_ambiguous_declaration', 'math_task_requires_theorem', 'math_task_requires_definition', 'math_task_helper_is_original_declaration']); + for (const [file, text] of sources) fs.writeFileSync(path.join(checkout, problem.projectRelative, file), text); + checkedCommit = commitSolverProjection(problem, checkout, `Check declaration ${declaration.name}`); + } const result = await checkProjectedDeclarations(problem, checkout, worktree, checkedCommit, [{ proofPath: declaration.file, theoremName: declaration.name, digest: declarationDigest, missingError: 'math_declaration_artifact_declaration_missing' }], { env: environment.env, signal, timeoutMs: input.timeoutMs ?? Infinity, - expectedDeclarationType: declaration.type, prepareLocalDependencies: problem.kind === 'lean-eval', + expectedDeclarationType: type, prepareLocalDependencies: checkHelperInDraft || problem.kind === 'lean-eval', + ...(checkHelperInDraft ? { checkDeclarationsInDraft: true } : {}), collectDeclarationReferences: true }).catch(error => { if (error instanceof Error && error.message === 'math_declaration_artifact_declaration_missing') throw new DeclarationSubmissionError(error.message, { cause: error }); diff --git a/src/solver/formalization.ts b/src/solver/formalization.ts index 358b3b9d..34ad010c 100644 --- a/src/solver/formalization.ts +++ b/src/solver/formalization.ts @@ -487,7 +487,7 @@ export async function runFormalization(directory: string, root: string, options: 'Implement the supplied plan as declarations with erased theorem proofs. The host compiles your submission and returns diagnostics for repair. Inspect declarations only for a specific unresolved library fact or mathematical meaning; do not compile extra scratch copies merely to duplicate that host check. Submit OUTPUT.json atomically once the statement and coverage are ready.', 'Name universe parameters when introducing an existential ambient carrier for embeddings. Inside a definition, an existential E : Type* introduces an independent universe parameter; it does not mean some sufficiently large universe. For carriers A : Type u and B : Type v embedded into E, use E : Type (max u v), or another explicitly justified compatible universe. Do not leave the ambient universe unrelated to the embedded carriers or restrict the original carriers to Type 0. If the inferred parameters are uncertain, inspect the elaborated declaration once in a separate scratch file; compilation alone does not check this mathematical requirement.', ...(!direct ? ['For a tower or nested family, include the successive inclusions and define each relative construction over the preceding object, rather than repeatedly over the original base. Quantified ambient carriers must have universes compatible with the required embeddings; an independently quantified smaller universe can change an existence claim. Check these statement choices before submitting, without proving the theorem.'] : []), - ...(request.environment === 'standard' ? [] : ['Use the narrowest known imports that supply the statement symbols. For ordinary real arithmetic, Mathlib.Data.Real.Basic supplies ℝ and its arithmetic/order operations. Avoid the full import Mathlib when a known narrower module suffices: every independent Lean check must load those imports.']), + ...(request.environment === 'standard' ? [] : ['Use import Mathlib or explicit Mathlib modules that supply the statement symbols. Prefer narrower imports when known, since every independent Lean check loads them. For ordinary real arithmetic, Mathlib.Data.Real.Basic supplies ℝ and its arithmetic/order operations. During proving, workers must keep the statement imports and may add import Mathlib or any pinned Mathlib.* import.']), ] : []), ...(request.fidelityPolicy && role === 'backtranslate' ? [ 'Use the host-observed elaborated types, binder dependencies, actual instances and supplied definition context as the primary evidence. Inspect an installed definition only to resolve a specific semantic uncertainty left by that context; do not repeat observations already supplied or recompile the snapshot merely to confirm it elaborates.', diff --git a/src/solver/incrementalHelpers.ts b/src/solver/incrementalHelpers.ts new file mode 100644 index 00000000..61811d7e --- /dev/null +++ b/src/solver/incrementalHelpers.ts @@ -0,0 +1,234 @@ +import path from 'node:path'; +import { z } from 'zod'; +import { inspectScopedLeanDeclarations } from '../math/leanSource'; +import { isSimpleLeanName, maskLeanComments } from '../math/leanSyntax'; +import { mathDigest } from '../math/mathRuntimeIo'; +import { importAgentTeamCommit } from './agentTeamWorkspace'; +import { applyTaskChanges, createTaskSourceProjector, taskChanges, type DeclarationChange } from './cooperativeProof'; +import type { DeclarationArtifactIdentity } from './declarationArtifacts'; +import { checkProjectedDeclarations } from './modules/evidence'; +import { assertSolverSources, committedSource, commitSolverSources, git, solverProofImports, + SolverSourceError, withSolverWorktree } from './problem'; +import { proofReuseEnvironment } from './proofReuse'; +import { solverSourceContext } from './sourceContext'; +import { allowedKnowledgeFile, locateKnowledgeDeclaration } from './theoremKnowledge'; +import type { CooperativeTask } from './tasks'; + +const leanName = z.string().min(1).max(1000).refine(isSimpleLeanName); +const leanFile = z.string().refine(value => value.endsWith('.lean') && allowedKnowledgeFile(value)); +const commitHash = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u); +export const helperNominationsSchema = z.array(z.object({ + file: leanFile, name: leanName, type: z.string().trim().min(1).max(12_000).optional(), + kind: z.literal('definition').optional(), +}).strict()).min(1).max(32); +export type HelperNomination = z.infer[number]; +export const landedHelperSchema = z.object({ + file: leanFile, qualifiedName: leanName, commit: commitHash, type: z.string().min(1).max(1000), + kind: z.literal('definition').optional(), +}).strict(); +export type LandedHelper = z.infer; + +export class IncrementalHelperRejection extends Error { + constructor(reason: string, details?: string, options?: ErrorOptions) { + super(`math_incremental_helper_${reason}${details ? ': ' + details : ''}`, options); + this.name = 'IncrementalHelperRejection'; + } +} + +type VerifiedHelpersInput = { + state: DeclarationArtifactIdentity; + sourceWorktree: string; sourceCommit: string; seedCommit: string; + worktree: string; expectedCommit: string; + declarations: readonly HelperNomination[]; + env: NodeJS.ProcessEnv; signal: AbortSignal; timeoutMs?: number; + assertCurrent?: () => void; + allowHelper?: (helper: HelperNomination) => boolean; +}; +type VerifiedHelpers = { commit: string; helpers: LandedHelper[]; declarations: Array; + changes: DeclarationChange[]; + imports: { file: string; module: string }[] }; +const id = (file: string, name: string) => file + '\0' + name; +const allowedAxioms = new Set(['propext', 'Classical.choice', 'Quot.sound']); +const reject = (reason: string, details?: string): never => { throw new IncrementalHelperRejection(reason, details); }; + +function sourceContract(check: () => void) { + try { check(); } + catch (error) { + if (error instanceof SolverSourceError || error instanceof Error && + /^(?:math_trusted_source_changed|math_source_outside_ownership)$/u.test(error.message)) + throw new IncrementalHelperRejection('source_rejected', error.message, { cause: error }); + throw error; + } +} + +function rejectKnownSourceError(error: unknown): never { + if (error instanceof Error && /^(?:math_task_|math_knowledge_declaration_missing_or_ambiguous)/u.test(error.message)) + throw new IncrementalHelperRejection('source_rejected', error.message, { cause: error }); + throw error; +} + +/** Stage a checked canonical descendant without writing either worker's live checkout. */ +export async function landVerifiedHelpers(input: VerifiedHelpersInput): Promise { + const { state, worktree, sourceWorktree, sourceCommit, seedCommit, expectedCommit, signal } = input; + const { problem } = state; + const nominations = helperNominationsSchema.safeParse(input.declarations); + if (!nominations.success) return reject('invalid_nomination', nominations.error.message); + const current = () => { signal.throwIfAborted(); input.assertCurrent?.(); }; + current(); + for (const commit of [sourceCommit, seedCommit, expectedCommit]) commitHash.parse(commit); + git(sourceWorktree, ['merge-base', '--is-ancestor', seedCommit, sourceCommit]); + git(worktree, ['merge-base', '--is-ancestor', problem.baseCommit, expectedCommit]); + // Native team peers can have a separate Git repository. Fetch the authorized + // snapshot without changing the target repository's working tree or branches. + try { git(worktree, ['cat-file', '-e', sourceCommit + '^{commit}']); } + catch { importAgentTeamCommit(sourceWorktree, worktree, sourceCommit); } + + const selection = await withSolverWorktree(worktree, sourceCommit, async snapshot => { + sourceContract(() => assertSolverSources(problem, snapshot)); + const base = new Map(), sources = new Map(); + const canonical = new Map(); + for (const file of problem.ownedFiles.filter(file => file.endsWith('.lean'))) { + const relative = path.join(problem.projectRelative, file); + base.set(file, committedSource(snapshot, problem.baseCommit, relative)); + sources.set(file, committedSource(snapshot, sourceCommit, relative)); + canonical.set(file, committedSource(worktree, expectedCommit, relative)); + } + const originals = new Set([...base].flatMap(([file, source]) => inspectScopedLeanDeclarations(source) + .map(declaration => id(file, declaration.qualifiedName)))); + const names = new Map([...canonical].map(([file, source]) => [file, new Set(inspectScopedLeanDeclarations(source) + .map(declaration => declaration.qualifiedName))])); + const locate = (name: string, source: string) => { + try { return locateKnowledgeDeclaration(source, name); } + catch (error) { return rejectKnownSourceError(error); } + }; + const task = ({ file, name, type, kind }: HelperNomination): CooperativeTask => ({ + id: 'standalone-helper', kind: 'lemma', objective: `Check standalone helper ${name}`, proofPath: file, theoremName: name, + type, dependsOn: [], revision: 0, ...(kind === 'definition' ? { declaration: 'definition' as const } : {}), + }); + const selected = new Map(); + const add = (declaration: HelperNomination, nominated: boolean) => { + const source = sources.get(declaration.file); + if (source === undefined || Object.hasOwn(problem.frozenFiles ?? {}, declaration.file)) + return reject('outside_ownership', declaration.file); + const located = locate(declaration.name, source); + const key = id(declaration.file, located.qualifiedName); + if (originals.has(key)) return reject('original_declaration', located.qualifiedName); + if (located.kind !== 'theorem' && (located.kind !== 'definition' || + !/^(?:def|abbrev)\s/u.test(source.slice(located.startOffset, located.bodyOffset)))) + return reject('unsupported_declaration', located.qualifiedName); + const normalized = { ...declaration, name: located.qualifiedName, + ...(located.kind === 'definition' ? { kind: 'definition' as const } : {}) }; + if (input.allowHelper?.(normalized) === false) return reject('outside_scope', normalized.name); + if (selected.has(key) && nominated) return reject('duplicate_nomination', normalized.name); + if (!selected.has(key)) selected.set(key, normalized); + return normalized; + }; + const project = createTaskSourceProjector(problem, snapshot, sourceCommit); + const roots = nominations.data.map(declaration => add(declaration, true)); + const closures = new Map>(); + const closureFor = (declaration: HelperNomination) => { + try { return project.helperClosure(task(declaration)); } + catch (error) { return rejectKnownSourceError(error); } + }; + for (const root of roots) { + const closure = closureFor(root); + closures.set(id(root.file, root.name), closure); + for (const dependency of closure) { + const key = id(dependency.file, dependency.name); + if (originals.has(key) || selected.has(key)) continue; + if (dependency.file !== root.file) { + if (names.get(dependency.file)?.has(dependency.name)) continue; + return reject('dependency_outside_file', dependency.name); + } + const included = add(dependency, false); + closures.set(key, closureFor(included)); + } + } + let patches: DeclarationChange[]; + try { patches = taskChanges(problem, snapshot, sourceCommit, undefined, { seedCommit: problem.baseCommit }); } + catch (error) { return rejectKnownSourceError(error); } + const changes: DeclarationChange[] = []; + const added: HelperNomination[] = []; + const files = new Set(); + const ordered = [...selected.values()].sort((a, b) => a.file.localeCompare(b.file) || + locate(a.name, sources.get(a.file)!).startOffset - locate(b.name, sources.get(b.file)!).startOffset); + for (const declaration of ordered) { + const { file, name } = declaration; + const source = sources.get(file)!, candidate = locate(name, source); + const patch = patches.find(change => change.file === file && change.before === undefined && + (change.name === candidate.name || change.name === name)); + if (!patch) return reject('missing_addition', name); + if (names.get(file)!.has(name)) { + const retained = canonical.get(file)!, existing = locate(name, retained); + const line = retained.lastIndexOf('\n', existing.startOffset - 1) + 1; + if (retained.slice(line, existing.endOffset).trimEnd() + '\n' !== patch.after) + return reject('conflicting_definition', name); + continue; + } + // Where the original context and dependencies permit, make the helper visible to + // the first original target in its scope, even when a worker appended it later. + const retained = canonical.get(file)!; + const context = (text: string, offset: number) => solverSourceContext(maskLeanComments(text.slice(0, offset)), [], + problem.sourceImports?.[file], solverProofImports(problem, text)); + const required = new Set((closures.get(id(file, name)) ?? []).filter(ref => ref.file === file && ref.name !== name).map(ref => ref.name)); + const precedingInputs = [...required].filter(ref => names.get(file)!.has(ref)) + .map(ref => locate(ref, retained).endOffset); + const first = inspectScopedLeanDeclarations(retained).find(target => problem.targets.some(original => + original.proofPath === file && original.theoremName === target.qualifiedName) && + precedingInputs.every(end => end <= target.startOffset) && + context(retained, target.startOffset) === context(source, candidate.startOffset)); + changes.push(first ? { file, name: patch.name, after: patch.after, beforeName: first.name } : patch); + added.push(declaration); files.add(file); + } + const imports = [...files].flatMap(file => { + const retained = new Set(solverProofImports(problem, canonical.get(file)!)); + return solverProofImports(problem, sources.get(file)!).filter(module => !retained.has(module)).map(module => ({ file, module })); + }); + return { changes, imports, added, ordered }; + }); + current(); + return withSolverWorktree(worktree, expectedCommit, async staging => { + sourceContract(() => { + assertSolverSources(problem, staging); + try { applyTaskChanges(problem, staging, selection.changes, selection.imports); } + catch (error) { return rejectKnownSourceError(error); } + }); + const commit = selection.changes.length ? commitSolverSources(problem, staging) : expectedCommit; + const environment = proofReuseEnvironment(path.join(worktree, problem.projectRelative), input.env); + const checked = new Map(); + // Check the staged canonical bytes. A tactic can select a different lemma or instance + // when a source projection removes original goals, so projected evidence cannot bind this merge. + for (let offset = 0; offset < selection.ordered.length; offset += 64) { + current(); + const batch = selection.ordered.slice(offset, offset + 64); + const expectedTypes: Record = Object.create(null); + for (const declaration of batch) if (declaration.type) expectedTypes[declaration.name] = declaration.type; + const verification = await checkProjectedDeclarations(problem, staging, worktree, commit, + batch.map(({ file, name }) => ({ proofPath: file, theoremName: name, digest: mathDigest(id(file, name)), + missingError: 'math_incremental_helper_source_missing' })), + { env: environment.env, signal, timeoutMs: input.timeoutMs ?? Infinity, checkDeclarationsInDraft: true, + ...(Object.keys(expectedTypes).length ? { expectedDeclarationTypes: expectedTypes } : {}), + prepareLocalDependencies: true }).catch(error => { + if (error instanceof Error && error.message === 'math_incremental_helper_source_missing') + return reject('source_rejected', error.message); + throw error; + }); + for (const [index, declaration] of batch.entries()) { + const result = verification.verification.results[index]; + if (result?.status !== 'kernel_verified' || result.verifier !== 'lean-kernel' || result.cleanupError || result.sorryCount !== 0 || + result.admitCount !== 0 || !result.axioms.every(axiom => allowedAxioms.has(axiom)) || !result.elaboratedDeclarationType) + return reject('kernel_rejected', `${declaration.name}: ${result?.error ?? verification.verification.status}`); + checked.set(id(declaration.file, declaration.name), result.elaboratedDeclarationType); + } + if (!verification.passed) return reject('kernel_rejected', verification.verification.status); + } + current(); + const declarations = selection.added.map(declaration => ({ + ...declaration, type: checked.get(id(declaration.file, declaration.name))!, + })); + const helpers = declarations.map(({ file, name, type, kind }) => landedHelperSchema.parse({ + file, qualifiedName: name, type: type.replace(/\s+/gu, ' ').slice(0, 1000), commit, ...(kind ? { kind } : {}), + })); + return { commit, helpers, declarations, changes: selection.changes, imports: selection.imports }; + }); +} diff --git a/src/solver/inspection.ts b/src/solver/inspection.ts index 3b8ca298..dd4cbf1b 100644 --- a/src/solver/inspection.ts +++ b/src/solver/inspection.ts @@ -14,6 +14,7 @@ import { planApprovalInspection } from './planApproval'; import { agentTeamOverview } from './agentTeamViews'; import { buildAgentTeamContributions, teamContributionsSchema } from './agentTeamContributions'; import { projectAgentTeamBudget } from './agentTeamBudget'; +import { portfolioUsageRecords } from './portfolioExploration'; /** Binds a report to the stored observation; this does not replay or accept its proof evidence. */ export function runInspectionSnapshot(state: SolverRunState, result?: Record) { @@ -58,7 +59,8 @@ function dispatchWaitRecord(state: SolverRunState, observation?: DispatchWaitObs export function buildRunInspection(state: SolverRunState, result?: Record) { const skillMode = state.researchMode === 'skill' && !state.workers; const teamMode = state.researchDelegation?.mode === 'team'; - const usageRecords = [...(state.workers ?? [state]), ...(state.agentTeam?.workers ?? [])]; + const scouts = portfolioUsageRecords(state); + const usageRecords = [...(state.workers ?? [state]), ...(state.agentTeam?.workers ?? []), ...scouts]; const receiptObservation = summarizeUsageObservation([{ runId: state.runId, observedAt: 0, records: usageRecords }], { runId: state.runId, startedAt: 0, endedAt: Number.MAX_SAFE_INTEGER }); const tokenBudget = buildTokenBudget(state.tokenBudget?.maxTotalTokens ?? state.agentTeam?.hostLimits?.maxTotalTokens ?? 0, @@ -109,7 +111,7 @@ export function buildRunInspection(state: SolverRunState, result?: Record; -export type ResearchDispatchOptions = Readonly<{ continuation?: boolean; checkpointInstruction?: string }>; +export type ResearchDispatchOptions = Readonly<{ continuation?: boolean; taskSwitch?: boolean; checkpointInstruction?: string }>; const dispatchPrefix = (text?: string): ContextSection[] => text ? [{ id: 'dispatch-checkpoint-instruction', kind: 'checkpoint', text, }] : []; /** Finalize the exact message before the host saves its manifest or opens a model turn. */ function compileCustomDispatch(context: ContextBundle, options: ResearchDispatchOptions, preserveInventory = true): CompiledContext { - const previous = options.continuation ? context.continuationManifest ?? context.manifest : context.manifest; - const message = options.continuation ? context.continuationMessage ?? context.message : context.message; - const sourceManifest = preserveInventory ? options.continuation && context.continuationMessage !== context.message + const continued = options.continuation || options.taskSwitch && context.continuationMessage !== undefined; + const previous = continued ? context.continuationManifest ?? context.manifest : context.manifest; + const message = continued ? context.continuationMessage ?? context.message : context.message; + const sourceManifest = preserveInventory ? continued && context.continuationMessage !== context.message ? context.continuationManifest : context.manifest : undefined; let compiled = compileContextSections({ instructions: context.instructions, mandatory: [...dispatchPrefix(options.checkpointInstruction), { id: 'dispatch-message', kind: 'continuation', text: message }], @@ -162,9 +163,10 @@ export function buildResearchContext(task: SolverProblem, state: Readonly target.proofPath))]; @@ -224,19 +226,20 @@ export function buildResearchContext(task: SolverProblem, state: Readonly !Object.hasOwn(task.frozenFiles ?? {}, file))), 'RESEARCH.md', ...(deliveryFile ? [deliveryFile] : [])])}. ` + + (taskLogPath ? 'You may append to ' + taskLogPath + '. ' : '') + (readOnlySources ? 'Leave every Lean source unchanged. ' : '') + taskRules) + '\n' + (['M1', 'M3', 'M4', 'M5'] as const).map(slot => strategyAdvice(access, slot, '', slot !== 'M5' || cooperative)).join('\n') : `${responsibility} Work only in this isolated worktree. -Edit only ${[...(readOnlySources ? [] : editableOwnedFiles(task.ownedFiles, file => path.join(access.worktree, task.projectRelative, file), task.frozenFiles)), path.join(access.worktree, 'RESEARCH.md'), ...(deliveryFile ? [path.join(access.worktree, deliveryFile)] : [])].join(', ')}. +Edit only ${[...(readOnlySources ? [] : editableOwnedFiles(task.ownedFiles, file => path.join(access.worktree, task.projectRelative, file), task.frozenFiles)), path.join(access.worktree, 'RESEARCH.md'), ...(deliveryFile ? [path.join(access.worktree, deliveryFile)] : []), ...(taskLogPath ? [taskLogPath] : [])].join(', ')}. ${access.assignment ? 'Save RESEARCH.md and delivery logs at these exact worktree-root paths' : 'Save RESEARCH.md at its exact worktree-root path'}, including when a diagnostic command runs inside the Lean project subdirectory. Temporary ${planningLead ? 'mathematical notes and tool output' : 'probes, backups and diagnostic output'} may be written under ${path.join(access.worktree, '.scratch', 'tmp')} or the Lean project's .scratch/tmp directory. The shell's TMPDIR points to the worktree-local directory; run mkdir -p "$TMPDIR" before creating temporary files. /tmp is read-only. Untracked regular scratch files stay advisory and remain outside formal proof checkpoints. Do not git add scratch files or use symlinks there. ${planningLead ? 'Retain useful mathematical findings in RESEARCH.md before returning.' : 'Retain reusable proof code and findings in RESEARCH.md or owned Lean files before returning.'} -Preserve original declaration kinds, names, parameters, types, assumptions, existing imports, options and namespace/section context. ${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.' : 'You may add explicit Mathlib.* imports from the pinned library, installed frozen Submission.Library.* modules, frozen local modules already imported by the original owned files, or other owned modules, without import cycles; 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. +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)} ${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)}${fixedReview ? '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.`} +${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.`} ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspace ${shellArgument(access.retrievalRoot)} --corpus ${shellArgument(access.corpusFile)} --sha256 ${shellArgument(access.environment.DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS_SHA256!)} --query 'KEYWORDS' --query 'OTHER_KEYWORDS'. Batch up to 8 short queries; use --goal 'LEAN_GOAL_AND_CONTEXT' for local variables and types. Ranking is advisory. ${planningLead ? 'Read complete source context and saved elaboration evidence before expanding a search; delegate an uncertain Lean application check to an assigned worker.' : 'Confirm types and known names with Lean #check before expanding a search: generated and core declarations may have no Mathlib source header.'}\n` : ''}${access.mathTools ? mathToolsInstruction(access.mathTools, access.worktree) : ''}${mathematicsRuntimeInstruction(access.environment.DEEPSCIENTIST_MATH_ENV_FILE)}`; const originalProblem = `${access.taskText}\n\nOriginal problem:\n${task.contract.formalStatement}`; let message = access.sourceFeedback || (state.check && !state.check.passed @@ -296,7 +299,8 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac frozenContexts: readFrozenContexts(task, access), maxContextBytes: access.maxContextBytes, maxOptionalContextBytes: access.maxOptionalContextBytes, environmentDigest: state.environmentDigest, - mandatory: [...(continuation ? [continuationContextSection(continuation, command, task.projectRelative)] : []), + mandatory: [...(fixedReview ? [] : portfolioContextSections(state)), + ...(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) }] : []), @@ -330,12 +334,13 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac // Spreading a built-in context must not let its captured compiler overwrite a custom M4 prompt. const changedMessage = current.message !== result.message; const inheritedContinuation = current.continuationMessage === result.continuationMessage; - const selected = options.continuation && changedMessage && inheritedContinuation + const continued = options.continuation || options.taskSwitch; + const selected = continued && changedMessage && inheritedContinuation ? { ...current, continuationMessage: current.message, continuationManifest: current.manifest } : current; - const changedBody = options.continuation + const changedBody = continued ? selected.continuationMessage !== result.continuationMessage : changedMessage; - const inventory = options.continuation ? selected.continuationManifest : selected.manifest; - const originalInventory = options.continuation ? result.continuationManifest : result.manifest; + const inventory = continued ? selected.continuationManifest : selected.manifest; + const originalInventory = continued ? result.continuationManifest : result.manifest; return compileCustomDispatch(selected, options, !changedBody || inventory !== originalInventory && inventory !== result.manifest); } }; } @@ -378,7 +383,7 @@ function theoryModuleRules(task: SolverProblem): string { return `${modules[0]}${modules.length > 1 ? ` … ${modules.at(-1)}` : ''} are owned theory-library modules; each starts as an empty namespace ${THEORY_MODULE_NAMESPACE} block. ` + 'Give each mathematical topic its own module: its definitions, their basic API and sanity lemmas, then the theorems built on them. Small modules compile and are cached separately, and later runs reuse them. ' + `Write declarations between the existing namespace and end lines, so a theorem named Foo.bar there is ${THEORY_MODULE_NAMESPACE}.Foo.bar; never add top-level open, variable, section or nested namespace lines, and keep open … in or set_option … in inside proofs. ` + - 'Add explicit Mathlib.* imports and import earlier theory modules or the frozen modules already imported by original files; import a theory module from a consumer without import cycles. Record which module holds which topic in RESEARCH.md.\n'; + 'Keep existing imports. In a Mathlib project, add import Mathlib or any pinned Mathlib.* import as needed. Import earlier theory modules or the frozen modules already imported by original files. Import a theory module from a consumer without creating a cycle. Record which module holds which topic in RESEARCH.md.\n'; } function kernelCertificateRules(task: SolverProblem, command: string, project: string): string { @@ -472,7 +477,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ? `A finite case table may be one family lemma task: add family:{"lo":0,"hi":N,"chunk":K,"predicate":"Namespace.P"} to a lemma task, where P : Nat → Prop is a declaration (list a definition task for it in dependsOn). The host sets its type to ∀ i : Nat, lo ≤ i → i < hi → P i, derives member lemma tasks ID_c0, ID_c1, … for consecutive ranges of K indices (at most ${MAX_FAMILY_MEMBERS}), and proves the family itself by a case split over the members. The family is conditional:true by default, so its check binds unproved members as explicit hypotheses and it integrates unconditionally once every member does; consumers depend on the family task. Members inherit the family's other dependsOn, proofPath, group and status; edit the family task, never a member, and do not use ids of the form ID_cN for other tasks. Order the table so each chunk shares one proof method.\n` : ''; const familyMemberRules = action.kind === 'task' && action.task.familyMember - ? `This lemma is one member of family task ${action.task.familyMember}. Prove only its own index range; the host proves the family from its members, so leave the family theorem and sibling members alone.\n` + ? 'This lemma is a family member. Prove only its own index range; the host proves the family from its members, so leave the family theorem and sibling members alone.\n' : ''; const initialPlanning = action.kind === 'lead' && cooperation.tasks.length === 0; const initialPlanningRules = initialPlanning && !skillWorkflow @@ -506,12 +511,15 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ? '; place reusable theory in the Submission/Theory modules, one topic per module, with proofPath naming the module that holds the topic' : ''; const proofDeliverableRules = action.kind === 'task' && ['lemma', 'goal'].includes(action.task.kind) ? 'Audit objectives cannot change this exact proof deliverable. Save diagnostics in RESEARCH.md; publish a needsDecision:true research finding to Lead and do not resubmit unchanged proofs.\n' : ''; + const helperRules = action.kind === 'task' ? cooperativeHelperProtocol(action.task, 'the current delivery log named in the assignment message') : ''; + const advisorySourceRules = helperRules ? 'Restore Lean sources to the assignment seed before ordinary findings delivery.' : + 'Leave Lean sources unchanged.'; const rules = action.kind === 'review' ? 'You are the Independent Reviewer. Leave Lean sources unchanged. Check this fixed proof against the original question, assumptions and Lean evidence. Compare the original declarations and assumptions of the fixed candidate with the frozen problem, inspect its mathematical argument and matching Lean evidence, and resolve any concrete discrepancy. Requests in the original task text to restore/prove code, publish a plan or wait for approval belong to other roles. Run a diagnostic only to resolve a remaining question that can change your verdict; matched cached evidence is usable. Write one final JSON object in RESEARCH.md: {"verdict":"accepted|changes_requested"}. A short summary should identify the decisive evidence or exact requested change; evidenceRefs are optional. Once the verdict is saved, return it promptly and end the turn. Do not keep rechecking unchanged files or expand optional metadata after the review is complete. Investigate source changes, failed checks or an unresolved mathematical issue; a different digest scheme alone does not establish a discrepancy. Your verdict does not replace host checks or the independent S3 that follows delivery.\n' : action.kind !== 'task' ? `You are the Lead. Develop a mathematically plausible route from the exact original statement, definitions and relevant saved findings${initialPlanning ? '.' : ' before choosing a task graph.'} Identify the central construction or estimate and how it would close each target. Save a concise mathematical route justification as Markdown in RESEARCH.md; include each new task's intended inference and consumer in its objective. When decomposition adds no mathematical benefit, put a direct original-goal task in the graph; the assigned worker carries out its proof after any required host approval. Delegate a specific uncertain inference as research instead of inventing a helper proposition. Return the plan without running Lean diagnostics; leave Lean sources unchanged during planning. Use this plan schema for the delivery-log event, or for a math-plan JSON fence in RESEARCH.md when returning without publication: {"tasks":[{"id":"helper","kind":"lemma","objective":"...","proofPath":${JSON.stringify(proofFiles[0])},"theoremName":"Namespace.helper","type":"∀ (P : Prop), P → P"},{"id":"goal","kind":"goal","objective":"...","theoremName":"Original.target","dependsOn":["helper"]}]}. Include every original target once. This example shows the task graph schema only; include every decision field required by current Lead decision requirements in that same JSON object. Replace its names, objectives and sample type with actual tasks and full closed Lean types, including all parameters and hypotheses. Never copy placeholder types. If no exact helper proposition is known, use an untyped research/sketch task. Choose proofPath from ${JSON.stringify(proofFiles)}${proofFiles.length < leanFiles.length ? '; workers generate Submission/Certificates modules and import them from these files' : ''}${theoryPlanning}; goals infer it from theoremName, and lemmas may omit it only when one Lean file is owned. Use lemma tasks whenever workers should save proofs; research/sketch tasks without an exact typed target only return advisory findings and restore temporary probes. Typed research tasks are normalized to lemma tasks. dependsOn defaults to []; revision to 0. Keep accepted task definitions stable; record progress in notes rather than rewriting objectives, which invalidates their checked deliveries. Revise a mathematical contract to change a route; changing only prose or revision does not resolve a recorded blocker. conditional:true allows fixed typed lemma premises. statementReview:true with informalStatement requests meaning review. Optional blueprint fields informalProof (the intended argument in at most 2000 characters) and citations (up to 8 short source references such as "Bhargava–Hanke 2005, Thm 2") guide the assigned worker; they never change the task contract or act as premises. A new concept is a lemma task with declaration:"definition" and its Lean type (e.g. "ℕ → ℕ → Prop"); put its intended meaning in objective, and list it in the dependsOn of lemmas whose types mention it. Consumers wait for its checked body. Pair each definition with a typed sanity lemma in the same proofPath that pins its intended meaning on a characterizing or small case, so a vacuous or mistaken body fails before consumers rely on it. Optional groups set ownership, sharing and budgets.\n` : ['research', 'sketch'].includes(action.task.kind) - ? 'You are a Mathematical Researcher. Explore the assigned mathematical question and leave Lean sources unchanged. Deliver a concise mathematical argument or counterexample with its exact assumptions, unresolved inference and intended original-goal application, so another solver can continue the work. Use library searches to resolve specific uncertainties in that argument. Save a scoped negative library result or a classification gap in worktree-root RESEARCH.md as soon as it is established, rather than waiting for a proof or the end of the turn. Record the pinned library/environment version, searched paths, queries or method, exact result and the missing mathematical inference. A scoped search failure is not proof of global absence. Replace inherited RESEARCH.md with findings for this assignment before returning; ordinary Markdown is supported. Timed checkpoints preserve progress and resume the same assignment without completing it. When a negative result or classification gap needs a route decision, promptly publish the existing research finding with needsDecision:true, conclusion:"inconclusive", a summary stating the precise gap, evidenceRefs and remainingObligations; use conclusion:"refuted" only for an actual refutation of the scoped claim. Otherwise ordinary findings may use JSON {"summary":"findings and evidence","needsDecision":true} to request a route change. Optional conclusion is supporting, refuted or inconclusive; findings remain advisory. To turn a useful bridge into proof work, add lemmaRequests:[{id,kind:"lemma",objective,theoremName,type,proofPath,dependsOn:[]}]. Supply new ids and full closed Lean types in your own route group. The host validates these proposals and presents them to Lead; adoption in the Lead plan creates a separate typed assignment whose proof requires independent checking. A proposal does not authorize edits to Lean sources.\n' + ? 'You are a Mathematical Researcher. Explore the assigned mathematical question. ' + advisorySourceRules + ' Deliver a concise mathematical argument or counterexample with its exact assumptions, unresolved inference and intended original-goal application, so another solver can continue the work. Use library searches to resolve specific uncertainties in that argument. Save a scoped negative library result or a classification gap in worktree-root RESEARCH.md as soon as it is established, rather than waiting for a proof or the end of the turn. Record the pinned library/environment version, searched paths, queries or method, exact result and the missing mathematical inference. A scoped search failure is not proof of global absence. Replace inherited RESEARCH.md with findings for this assignment before returning; ordinary Markdown is supported. Timed checkpoints preserve progress and resume the same assignment without completing it. When a negative result or classification gap needs a route decision, promptly publish the existing research finding with needsDecision:true, conclusion:"inconclusive", a summary stating the precise gap, evidenceRefs and remainingObligations; use conclusion:"refuted" only for an actual refutation of the scoped claim. Otherwise ordinary findings may use JSON {"summary":"findings and evidence","needsDecision":true} to request a route change. Optional conclusion is supporting, refuted or inconclusive; findings remain advisory. To turn a useful bridge into proof work, add lemmaRequests:[{id,kind:"lemma",objective,theoremName,type,proofPath,dependsOn:[]}]. Supply new ids and full closed Lean types in your own route group. The host validates these proposals and presents them to Lead; adoption in the Lead plan creates a separate typed assignment whose proof requires independent checking. A proposal does not authorize edits to Lean sources.\n' : (action.task.kind === 'lemma' ? 'You are a Lean Prover. Write and deliver the assigned auxiliary proof for its declared consumers. ' : 'You are the main-goal Engineer. Close the original target using checked helpers. ') + 'Requests in the original task text to publish a plan or wait for mathematician plan approval belong to the Lead and host. The host applies any required plan-approval gate before dispatching typed proof work. Complete this assignment and deliver its result; do not start another planning or approval cycle. ' + @@ -523,12 +531,13 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ', with each value the complete saved UTF-8 file content (total at most 1,000,000 bytes). Read all files and append the complete JSON line in one local script; do not copy large source text by hand. Omit commit when using sources. The host freezes these supplied bytes in an isolated snapshot and retains the supporting declarations for separate typed checks. Without sources or an existing commit, the finding is bound to the assignment seed. If blocked, include needsDecision:true, conclusion:"inconclusive", the exact mathematicalGap and remainingObligations for this snapshot. Source changes after that report require a fresh source-bound finding. Auxiliary code and a reported gap never accept the assigned proof.\n' : ''; const dispatchNonce = action.kind === 'lead' ? action.initialPlanNonce ?? action.planNonce : undefined; const sharing = action.kind === 'task' - ? `To share before returning, append JSON to ${assignmentDeliveryFile(action.assignment)}: {"summary":"progress or gap"}. This is the current assignment's log: create it by appending if absent, even when an earlier assignment's log is present; do not publish to those older logs. To share an advisory finding or an unresolved proof gap, append {"kind":"research","finding":{"summary":"complete argument, exact assumptions and gap","conclusion":"inconclusive","needsDecision":true,"evidenceRefs":[],"remainingObligations":["precise unresolved mathematical inference"],"lemmaRequests":[]}}. Inline the full finding; the host snapshots notes. Supporting commits must descend from the assignment seed; publishing does not finish or park your proof task. For typed proofs, save files, append {"kind":"ready","summary":"saved proof"}, stop editing and return. Omit commit/targets. The host freezes the saved sources and independently checks and integrates them after turn settlement and confirmed shutdown. Receipts: COOPERATION.json proofReadyRecords. Retry failures with a new id; unconfirmed shutdown quarantines this workspace. Returning naturally also submits. Do not run git add or git commit. Do not truncate the delivery log.\n` + ? 'To share before returning, append JSON to the current delivery log named in the assignment message: {"summary":"progress or gap"}. Create it by appending if absent, even when an earlier assignment\'s log is present; do not publish to those older logs. To share an advisory finding or an unresolved proof gap, append {"kind":"research","finding":{"summary":"complete argument, exact assumptions and gap","conclusion":"inconclusive","needsDecision":true,"evidenceRefs":[],"remainingObligations":["precise unresolved mathematical inference"],"lemmaRequests":[]}}. Inline the full finding; the host snapshots notes. Supporting commits must descend from the assignment seed; publishing does not finish or park your proof task. For typed proofs, save files, append {"kind":"ready","summary":"saved proof"}, stop editing and return. Omit commit/targets. The host freezes the saved sources and independently checks and integrates them after turn settlement and confirmed shutdown. Receipts: COOPERATION.json proofReadyRecords. Retry failures with a new id; unconfirmed shutdown quarantines this workspace. Returning naturally also submits. Do not run git add or git commit. Do not truncate the delivery log.\n' : leadPlanDeliveryFile(action) ? `Once a useful executable plan is ready, publish it promptly: append one complete JSON line to ${leadPlanDeliveryFile(action)}. Create this current dispatch log by appending if absent; its absence is normal and does not require searching older logs. ` + `Use {"kind":"plan","baseVersion":${JSON.stringify(action.kind === 'lead' ? action.planVersion : '')},` + (dispatchNonce ? `"dispatchNonce":${JSON.stringify(dispatchNonce)},` : '') + '"summary":"mathematical route and intended consumers","tasks":[...],"groups":[...],"proofRoutes":[...]}. ' + 'Inline the complete valid graph covering every original target exactly once as the tasks array, or omit tasks and put a revision of the accepted graph (upsert/remove as described for RESEARCH.md) at the top level of the same line; optional groups and proofRoutes may be omitted. The host freezes the line and can start peers before you return. ' + + 'For a shared construction or estimate, dispatch small typed foundation lemmas first and connect their consumers through dependsOn. Delegate exploratory computations. To retire a refuted group or proof route, add retireRoutes:[{routeId,reason,evidenceRefs}] to the plan. ' + 'Only the first valid publication in this dispatch is accepted. A partial line, ordinary RESEARCH.md save, or an external file reference does not publish a plan. Do not truncate the log. ' + 'Copy the dispatchNonce and baseVersion fields exactly as shown; a human edit or another accepted revision supersedes stale work. Preserve checked contracts and unrelated active assignments. ' + 'After publication, return promptly; a notes-only final keeps the published graph. Further changes in this dispatch use the normal final response, as a revision against this dispatch baseVersion that may repeat the published changes. The next Lead dispatch may publish its own revision.\n' : ''; @@ -617,7 +626,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio 'The assignment canonicalProbe records a check of the existing declaration at its sourceCommit in the recorded environment, before a model started. ' + 'Compare its full type and additional assumptions with the assigned type before choosing a repair, and recheck the current saved file after editing. ' + 'This is a historical source diagnostic, not a model failure or a mathematical refutation; it grants no proof acceptance.\n' : ''; - const instructions = researchSkill ? context.instructions + '\n' + roleText + cooperativeDeliveryProtocol(action) + '\n' + + const instructions = researchSkill ? context.instructions + '\n' + roleText + cooperativeDeliveryProtocol(action, 'the current delivery log named in the assignment message') + '\n' + `Cooperation reference: ${path.join(path.dirname(researchSkill.path), 'references/cooperation.md')}. ` + 'Read shared rules and your role section once per session; consult other sections for current decisions or feedback. ' + 'Current assignments, contracts and feedback supply the exact runtime values; examples are placeholders.\n' + @@ -626,7 +635,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio (action.kind === 'task' && ['lemma', 'goal'].includes(action.task.kind) ? 'Source-bound research findings require sources with exactly these Lean file keys: ' + JSON.stringify(leanFiles) + '.\n' : '') + connectionRules + familyMemberRules + canonicalProbeRules - : context.instructions + '\n' + initialPlanningRules + rules + organizationRules + leadDeliveryRules + planRevisionRules + familyRules + feasibilityRules + earlyRouteRules + connectionRules + familyMemberRules + attemptRules + focusRules + gapRules + nextCheckRules + observationRules + checkpointRules + mathematicalInterfaceRules + inheritedFindingRules + researchSourcesRules + canonicalProbeRules + + : context.instructions + '\n' + initialPlanningRules + rules + helperRules + organizationRules + leadDeliveryRules + planRevisionRules + familyRules + feasibilityRules + earlyRouteRules + connectionRules + familyMemberRules + attemptRules + focusRules + gapRules + nextCheckRules + observationRules + checkpointRules + mathematicalInterfaceRules + inheritedFindingRules + researchSourcesRules + canonicalProbeRules + (action.kind === 'lead' || action.kind === 'task' && !isFeasibilityReview(action.task) ? 'For parallel work, assign distinct proof, feasibility/counterexample, library-connection or consumer questions. Inspect in-flight work and reuse saved results; do not duplicate an unchanged question. Keep backup routes testing different inferences. Leave a slot waiting for input when no independent useful work exists. Do not manufacture helpers. Route priority reflects recorded inputs and obstructions, not predicted ease.\n' : '') + (action.kind === 'lead' ? 'Use the proof-continuation snapshot to identify the original goal\'s current mathematical frontier. Prefer consuming relevant checked lemmas before creating more auxiliary work; give each new helper an intended consumer and explicitly assign every substantive missing premise. Keep useful alternative routes visible. A lemma without a recorded consumer may still be useful; investigate its connection rather than deleting it. Planned dependencies, actual Lean proof references and conditional references are reported separately. Do not count auxiliary lemma totals as completion of the original problem. The host obtains fixed-candidate review after the complete proof is checked; mark any advisory final-candidate task with reviewScope:"final-candidate" so it waits for freshly checked original goals. Use a distinct task with reviewScope:"feasibility" for independent mathematical route checks before a complete candidate exists. Inspect validated lemmaRequests in deliveries and adopt useful exact proposals as separate lemma tasks; proposals and their local checks are advisory. Advisory research may start before its planned dependencies are proved; use typed proof tasks when a consumer must wait for checked premises. Set consumerGoalIds on advisory tasks to the original goals their effort serves; these attribution links never add proof premises or dependency waits.\n' : '') + @@ -654,7 +663,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio { id: 'statement-reviews', kind: 'statement-review', text: 'Statement reviews: ' + JSON.stringify(cooperation.statementReviews?.filter(review => review.status !== 'superseded') .map(statementReviewSummary) ?? []) }, ]; - const taskContinuation = action.kind === 'task' && !isFeasibilityReview(action.task); + const taskContinuation = action.kind === 'task' && !isFeasibilityReview(action.task) && !isFinalCandidateReview(action.task); const assignedNode = action.kind === 'task' ? cooperation.tasks.find(node => node.task.id === action.task.id) : undefined; const taskReceipts = action.kind === 'task' ? cooperation.deliveryReceipts?.filter(receipt => receipt.status === 'needs-correction' && receipt.workerId === action.assignment.workerId && receipt.taskId === action.task.id && @@ -680,9 +689,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio optional.push(...receiptDetails); const taskInbox = taskContinuation ? { file: 'COOPERATION.json', - deliveries: (cooperation.deliveries ?? []).slice(-16).map(record => ({ id: record.id, taskId: record.taskId, - taskDigest: record.taskDigest, kind: record.kind, status: record.status, findingDigest: record.findingDigest, - commit: record.commit, sourceDigest: record.sourceDigest })), + deliveries: (cooperation.deliveries ?? []).slice(-16).map(record => deliveryIndexRow(record)), gaps: (cooperation.mathematicalGaps ?? []).map(gap => ({ deliveryId: gap.deliveryId, consumer: gap.consumer, scopeStatus: gap.scopeStatus })), parallelQuestions: (cooperation.parallelQuestions ?? []).map(question => ({ taskId: question.taskId, taskDigest: question.taskDigest })), @@ -721,7 +728,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ].filter(Boolean).join('\n\n') : taskContinuation ? [ 'Continue the current task responsibility in this saved thread. Its frozen problem, exact interfaces, and unchanged source rules are already in the thread history.', 'Current cooperative assignment:\n' + JSON.stringify(action), - skillWorkflow && action.kind === 'task' ? 'Current delivery log: ' + assignmentDeliveryFile(action.assignment) : '', + 'Current delivery log: ' + assignmentDeliveryFile(action.assignment), 'Current host work contract:\n' + JSON.stringify(workContract), gapContext, nextCheckContext, progressCheckContext, @@ -742,7 +749,7 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio ? { id: 'lead-decision-requirements', kind: 'assignment' as const, text: 'Current Lead decision requirements (this dispatch only):\n' + cooperation.leadDecisionInstruction } : undefined; - const compileFull = (checkpointInstruction?: string) => compileTaskContext({ ...compilation, instructions, optional, + const compileFull = (checkpointInstruction?: string, taskSwitch?: boolean) => compileTaskContext({ ...compilation, instructions, optional, taskSwitch, mandatory: [...dispatchPrefix(checkpointInstruction), ...(leadDecision ? [leadDecision] : []), ...(compilation.mandatory ?? []), ...receiptIndex, { id: 'work-contract', kind: 'assignment', text: 'Host work contract (one product; completion is not proof acceptance):\n' + JSON.stringify(workContract) }, @@ -772,10 +779,12 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio const currentLibraryHint = (section: ContextSection) => ['installed-library:', 'knowledge:', 'knowledge-application:', 'knowledge-application-hints:'].some(prefix => section.id.startsWith(prefix)); const continuationOptional = (compilation.optional ?? []).filter(section => section.kind === 'feedback' || currentLibraryHint(section)); + const helperIndex = landedHelperSection(cooperation); const compileContinuation = (checkpointInstruction?: string) => compileContextSections({ instructions, mandatory: [...dispatchPrefix(checkpointInstruction), ...(leadDecision ? [leadDecision] : []), { id: 'same-thread-continuation', kind: 'continuation', - text: continuationText! }, ...(researchInputs ? [researchInputs] : []), ...(planRejection ? [planRejection] : []), ...receiptIndex], + text: continuationText! }, ...(researchInputs ? [researchInputs] : []), ...(planRejection ? [planRejection] : []), + ...(helperIndex ? [helperIndex] : []), ...receiptIndex], optional: [...receiptDetails, ...continuationOptional].sort((a, b) => (a.priority ?? 20) - (b.priority ?? 20)), omitted: (compilation.optional ?? []).filter(section => !continuationOptional.includes(section)) .map(section => ({ id: section.id, kind: section.kind, reason: 'outside-task-scope' as const })), @@ -785,7 +794,8 @@ function buildCooperativeContext(problem: SolverProblem, cooperation: Cooperatio const compiledContinuation = continuationText === undefined ? undefined : compileContinuation(); return { ...context, assignment: action, workContract, instructions, ...full, continuationMessage: compiledContinuation?.message, continuationManifest: compiledContinuation?.manifest, - compileDispatch: options => options.continuation && compiledContinuation + compileDispatch: options => options.taskSwitch && taskContinuation ? compileFull(options.checkpointInstruction, true) : + options.continuation && compiledContinuation ? options.checkpointInstruction ? compileContinuation(options.checkpointInstruction) : compiledContinuation : options.checkpointInstruction ? compileFull(options.checkpointInstruction) : full }; } diff --git a/src/solver/planDiagnostics.ts b/src/solver/planDiagnostics.ts new file mode 100644 index 00000000..aa1e6443 --- /dev/null +++ b/src/solver/planDiagnostics.ts @@ -0,0 +1,25 @@ +export type PlanIssue = { path: string; message: string }; + +/** Keep the established Lead error text and provide fields for structured command output. */ +export class PlanValidationError extends Error { + constructor(readonly code: string, message: string, readonly issues: PlanIssue[]) { + super(message ? `${code}: ${message}` : code); + this.name = 'PlanValidationError'; + } +} + +export const invalidPlanField = (code: string, path: string, message: string) => + new PlanValidationError(code, message, [{ path, message }]); + +export function planFieldPath(keys: readonly (string | number)[]): string { + return keys.map((key, index) => typeof key === 'number' ? `[${key}]` : (index ? '.' : '') + key).join(''); +} + +export function planError(code: string, detail: Record, hint = '') { + const task = typeof detail.taskId === 'string' ? `tasks[${detail.taskId}]` : undefined; + const group = typeof detail.index === 'number' && code.includes('group') ? `groups[${detail.index}]` : undefined; + const field = typeof detail.field === 'string' ? detail.field : undefined; + const path = [task ?? group, field].filter(Boolean).join('.') || '$'; + const message = JSON.stringify(detail) + (hint ? '. ' + hint : ''); + return new PlanValidationError(code, message, [{ path, message }]); +} diff --git a/src/solver/planPatch.ts b/src/solver/planPatch.ts index c4fdaa79..95bd0e19 100644 --- a/src/solver/planPatch.ts +++ b/src/solver/planPatch.ts @@ -1,6 +1,7 @@ import type { CooperativeTask, RouteGroup } from './tasks'; import type { ProofRoute } from './proofRoutes'; import { canonicalMathJson } from '../math/mathRuntimeIo'; +import { invalidPlanField, PlanValidationError } from './planDiagnostics'; /** The accepted Lead graph a revision is written against. */ export type PlanPatchBase = { version: string; tasks: readonly CooperativeTask[]; groups: readonly RouteGroup[]; @@ -17,15 +18,17 @@ export function liftNestedPlanPatch(value: unknown): unknown { if (!record(value) || !record(value.tasks) || (value.tasks.upsert === undefined && value.tasks.remove === undefined)) return value; const { tasks: nested, ...rest } = value; const clash = Object.keys(nested).find(key => rest[key] !== undefined && rest[key] !== nested[key]); - if (clash) throw new Error(`math_plan_patch_invalid: ${clash} appears both at the top level and inside tasks; ` + + if (clash) throw invalidPlanField('math_plan_patch_invalid', `tasks.${clash}`, `${clash} appears both at the top level and inside tasks; ` + 'put baseVersion, upsert and remove at the top level and omit tasks.'); return { ...rest, ...nested }; } /** A revision names only changed tasks; a complete `tasks` list remains the full-graph form. */ export function isPlanPatch(value: unknown): value is Record { - if (!record(value) || (value.upsert === undefined && value.remove === undefined)) return false; - if (value.tasks !== undefined) throw new Error('math_plan_patch_invalid: use either a complete tasks list or upsert/remove, not both.'); + if (!record(value) || (value.upsert === undefined && value.remove === undefined && + (value.retireRoutes === undefined || value.tasks !== undefined))) return false; + if (value.tasks !== undefined) throw invalidPlanField('math_plan_patch_invalid', 'tasks', + 'use either a complete tasks list or upsert/remove, not both.'); return true; } @@ -37,25 +40,39 @@ export function isPlanPatch(value: unknown): value is Record { */ export function expandPlanPatch(value: Record, base: PlanPatchBase | undefined, options: { acceptedBaseVersions?: readonly string[]; rebased?: boolean } = {}): Record { - if (!base || !base.tasks.length) throw new Error('math_plan_patch_without_base: publish a complete tasks list for the first plan.'); + if (!base || !base.tasks.length) throw invalidPlanField('math_plan_patch_without_base', 'baseVersion', + 'Publish a complete tasks list for the first plan.'); const { upsert = [], remove = [] } = value as { upsert?: unknown; remove?: unknown }; - if (typeof value.baseVersion !== 'string' || !Array.isArray(upsert) || !Array.isArray(remove) || - upsert.some(task => !record(task) || typeof task.id !== 'string') || remove.some(id => typeof id !== 'string')) - throw new Error('math_plan_patch_invalid: use {"baseVersion":"...","upsert":[{"id":"...",...}],"remove":["id"]}.'); + if (typeof value.baseVersion !== 'string') throw invalidPlanField('math_plan_patch_invalid', 'baseVersion', + 'Set baseVersion to the current accepted plan version.'); + if (!Array.isArray(upsert)) throw invalidPlanField('math_plan_patch_invalid', 'upsert', 'Supply an array of task objects.'); + if (!Array.isArray(remove)) throw invalidPlanField('math_plan_patch_invalid', 'remove', 'Supply an array of task IDs.'); + const invalidUpsert = upsert.findIndex(task => !record(task) || typeof task.id !== 'string'); + if (invalidUpsert >= 0) throw invalidPlanField('math_plan_patch_invalid', `upsert[${invalidUpsert}].id`, 'Supply a task ID.'); + const invalidRemove = remove.findIndex(id => typeof id !== 'string'); + if (invalidRemove >= 0) throw invalidPlanField('math_plan_patch_invalid', `remove[${invalidRemove}]`, 'Supply a task ID.'); const accepted = options.acceptedBaseVersions ?? [base.version]; if (!accepted.includes(value.baseVersion)) - throw new Error(`math_plan_patch_version_conflict: baseVersion ${value.baseVersion} is not the accepted plan ${base.version}; ` + + throw invalidPlanField('math_plan_patch_version_conflict', 'baseVersion', + `baseVersion ${value.baseVersion} is not the accepted plan ${base.version}; ` + 'rewrite this patch against the current accepted graph.'); const upserts = upsert as Record[], removals = remove as string[]; const upsertIds = upserts.map(task => task.id as string); - if (new Set(upsertIds).size !== upsertIds.length || new Set(removals).size !== removals.length) - throw new Error('math_plan_patch_duplicate_task'); - const both = removals.find(id => upsertIds.includes(id)); - if (both) throw new Error(`math_plan_patch_conflicting_task: ${both} is both upserted and removed.`); + const changedIds = new Set(upsertIds); + const duplicateUpsert = changedIds.size < upsertIds.length ? upsertIds.findIndex((id, index) => upsertIds.indexOf(id) !== index) : -1; + const duplicateRemoval = new Set(removals).size < removals.length ? removals.findIndex((id, index) => removals.indexOf(id) !== index) : -1; + if (duplicateUpsert >= 0 || duplicateRemoval >= 0) throw new PlanValidationError('math_plan_patch_duplicate_task', '', [{ + path: duplicateUpsert >= 0 ? `upsert[${duplicateUpsert}].id` : `remove[${duplicateRemoval}]`, + message: 'List each task ID only once.', + }]); + const both = removals.findIndex(id => changedIds.has(id)); + if (both >= 0) throw invalidPlanField('math_plan_patch_conflicting_task', `remove[${both}]`, + `${removals[both]} is both upserted and removed.`); const current = new Map(base.tasks.map(task => [task.id, task])); // A rebased patch was already applied by this dispatch's own publication. - const unknown = removals.find(id => !current.has(id)); - if (unknown && !options.rebased) throw new Error(`math_plan_patch_unknown_task: ${unknown} is not in the accepted graph.`); + const unknown = removals.findIndex(id => !current.has(id)); + if (unknown >= 0 && !options.rebased) throw invalidPlanField('math_plan_patch_unknown_task', `remove[${unknown}]`, + `${removals[unknown]} is not in the accepted graph.`); const removed = new Set(removals); const changed = new Map(upserts.map(patch => { const previous = current.get(patch.id as string); @@ -77,9 +94,12 @@ export function expandPlanPatch(value: Record, base: PlanPatchB const tasks: unknown[] = [...base.tasks.filter(task => !removed.has(task.id)).map(task => changed.get(task.id) ?? task), ...upserts.filter(patch => !current.has(patch.id as string)).map(patch => changed.get(patch.id as string)!)]; const ids = new Set(tasks.map(task => (task as { id: string }).id)); - for (const task of tasks) for (const id of (task as { dependsOn?: unknown }).dependsOn as unknown[] ?? []) - if (typeof id === 'string' && removed.has(id) && !ids.has(id)) + for (const task of tasks) { + const dependencies = (task as { dependsOn?: unknown }).dependsOn; + if (!Array.isArray(dependencies)) continue; // The ordinary graph parser reports the type error. + for (const id of dependencies) if (typeof id === 'string' && removed.has(id) && !ids.has(id)) throw new Error(`math_plan_patch_dangling_dependency: ${(task as { id: string }).id} still depends on removed ${id}.`); + } const replace = (key: 'groups' | 'proofRoutes', fallback: T) => value[key] === undefined ? fallback : value[key] ?? []; return { tasks, groups: replace('groups', base.groups), proofRoutes: replace('proofRoutes', base.proofRoutes ?? []) }; } diff --git a/src/solver/planTool.ts b/src/solver/planTool.ts new file mode 100644 index 00000000..c32ae892 --- /dev/null +++ b/src/solver/planTool.ts @@ -0,0 +1,116 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { canonicalMathJson, mathDigest, readMathText, writeMathTextDurable } from '../math/mathRuntimeIo'; +import { assertMathCanonicalPath } from '../math/paths'; +import { parseLeadPlan } from './cooperationShared'; +import { isPlanFence, MAX_RESEARCH_NOTES_BYTES, parseMathResponse } from './deliveries'; +import type { GoalPathReview } from './goalPathReview'; +import { invalidPlanField, PlanValidationError, type PlanIssue } from './planDiagnostics'; +import { liftNestedPlanPatch, type PlanPatchBase } from './planPatch'; +import { readSolverProblem } from './problem'; +import type { CooperationPlanProblem } from './tasks'; + +/** Lead-only snapshot. The running host still validates every proposal against live state. */ +export type PlanToolContext = { problem: CooperationPlanProblem; base?: PlanPatchBase; goalPath?: GoalPathReview }; +type PlanValidation = { ok: true; planVersion: string; baseVersion?: string; summary: string; tasksCount: number; + groupsCount: number; retireRoutesCount: number }; +type PlanFailure = { ok: false; error: string; issues: PlanIssue[] }; +type PlanInput = { workspace: string; file: string } | { workspace: string; text: string }; + +function failure(error: unknown, field = '$'): PlanFailure { + if (error instanceof PlanValidationError) return { ok: false, error: error.code, issues: error.issues }; + const message = error instanceof Error ? error.message : 'Could not read the plan.'; + return { ok: false, error: /^math_[\w-]+/u.exec(message)?.[0] ?? 'math_plan_tool_failed', issues: [{ path: field, message }] }; +} + +function validated(value: unknown, context: PlanToolContext) { + const candidate = liftNestedPlanPatch(value); + 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 }; +} + +export function validateCooperationPlan(value: unknown, context: PlanToolContext): PlanValidation | PlanFailure { + try { return validated(value, context).result; } catch (error) { return failure(error); } +} + +function readCandidate(input: PlanInput): unknown { + let text: string; + try { text = 'text' in input ? input.text : readMathText(input.file, MAX_RESEARCH_NOTES_BYTES); } + catch { throw invalidPlanField('math_plan_file_unreadable', '--file', 'Use a readable regular JSON file of at most 1 MB.'); } + if (Buffer.byteLength(text) > MAX_RESEARCH_NOTES_BYTES) + throw invalidPlanField('math_plan_file_too_large', '--file', 'Keep the plan JSON at or below 1 MB.'); + try { return JSON.parse(text); } + catch (error) { + throw invalidPlanField('math_plan_json_invalid', '$', + 'Supply JSON without Markdown fences. ' + (error instanceof Error ? error.message : 'Invalid JSON.')); + } +} + +function workspacePlanContext(worktree: string): PlanToolContext { + const cooperationFile = path.join(worktree, 'COOPERATION.json'); + assertMathCanonicalPath(cooperationFile); + if (fs.existsSync(cooperationFile)) { + const cooperation = JSON.parse(readMathText(cooperationFile, 32_000_000)) as { planTool?: PlanToolContext }; + if (cooperation.planTool) return cooperation.planTool; + throw invalidPlanField('math_plan_workspace_context_missing', '--workspace', + 'Run this command in the cooperative Lead worktree with its current COOPERATION.json.'); + } + const receipt = path.join(worktree, 'active-problem.json'); + assertMathCanonicalPath(receipt); + if (!fs.existsSync(receipt)) throw invalidPlanField('math_plan_workspace_context_missing', '--workspace', + 'Use the cooperative Lead worktree or a prepared workspace containing active-problem.json.'); + return { problem: readSolverProblem(worktree, receipt) }; +} + +function prepare(input: PlanInput) { + const candidate = readCandidate(input); + const worktree = fs.realpathSync(input.workspace); + assertMathCanonicalPath(worktree); + return { worktree, ...validated(candidate, workspacePlanContext(worktree)) }; +} + +export function validateCooperationPlanFile(input: PlanInput): PlanValidation | PlanFailure { + try { return prepare(input).result; } catch (error) { return failure(error); } +} + +function replacePlanFence(source: string, fence: string): string { + // The complete bare JSON response from an older Lead is also a plan block. + if (isPlanFence('json', source.trim()) && source.trimStart().startsWith('{')) { + try { JSON.parse(source); return fence + '\n'; } catch { /* Preserve surrounding prose. */ } + } + let replaced = false; + const notes = source.replace(/```([a-z-]+)\s*\n([\s\S]*?)\n```/gu, (block, label: string, body: string) => { + if (!isPlanFence(label, body)) return block; + if (replaced) return ''; + replaced = true; + return fence; + }); + return replaced ? notes : fence + '\n' + (source ? '\n' + source : ''); +} + +/** 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 = replacePlanFence(source, '```math-plan\n' + canonical + '\n```'); + 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'); } +} diff --git a/src/solver/portfolioExploration.ts b/src/solver/portfolioExploration.ts new file mode 100644 index 00000000..8f73ff18 --- /dev/null +++ b/src/solver/portfolioExploration.ts @@ -0,0 +1,277 @@ +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 } from '../math/paths'; +import type { MathAgentOptions, MathAgentSession } from '../runtime/agentSession'; +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'; + +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 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(); +export const portfolioFoundationLemmaSchema = z.object({ + id: routeId, proofPath: text(256), theoremName: text(256).refine(isSimpleLeanName), + type: text(4_000), objective: text(750), +}).strict(); +const falsificationEvidence = z.object({ + kind: z.enum(['counterexample', 'obstruction']), claim: text(500), probe: text(1_000), result: text(1_000), +}).strict(); +const reportBodySchema = z.object({ + routeId, status: z.enum(['proposed', 'refuted', 'inconclusive']), blueprintSummary: text(1_200), + keyTransformations: z.array(text(350)).max(6), proposedFoundationLemmas: z.array(portfolioFoundationLemmaSchema).max(6), + falsificationEvidence: z.array(falsificationEvidence).max(3).default([]), + obstructions: z.array(text(500)).max(4).default([]), probeRefs: z.array(probeName).max(4).default([]), +}).strict(); +const reportSchema = reportBodySchema.extend({ profile: profileSchema }); +export type PortfolioScoutReport = z.infer; + +export const portfolioGateSchema = z.object({ + primaryRouteId: routeId.optional(), backupRouteId: routeId.optional(), + retiredRoutes: z.array(retiredRouteSchema), foundationLemmas: z.array(portfolioFoundationLemmaSchema), +}).strict(); +export const portfolioScoutSchema = z.object({ + profile: profileSchema, status: z.enum(['pending', 'running', 'reported', 'failed', 'timed-out']), + turns: timestamp, reports: z.array(reportSchema).max(3).optional(), + probes: z.array(z.object({ ref: probeName, digest: z.string().regex(/^[a-f0-9]{64}$/u), text: z.string().max(8192) })).max(12).optional(), + usage: z.record(z.unknown()).optional(), usageBeforeThread: z.record(z.unknown()).optional(), + lastInputTokens: timestamp.optional(), +}).strict(); +export const portfolioExplorationSchema = z.object({ + phase: z.enum(['exploring', 'completed', 'skipped']), + durationMs: z.number().int().positive().max(PORTFOLIO_MAX_SECONDS * 1000), + scouts: z.array(portfolioScoutSchema).max(3), deadlineAt: timestamp.optional(), gate: portfolioGateSchema.optional(), +}).strict(); +type PortfolioScout = z.infer & { + turns: number; + usageAccounting?: UsageAccounting; requestUsageAccounting?: RequestUsageAccounting; +}; +export type PortfolioExploration = Omit, 'scouts'> & { scouts: PortfolioScout[] }; + +export const portfolioUsageRecords = (state: Pick) => + 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; + 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[]) => { + 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], + '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 signal = AbortSignal.any([input.signal, AbortSignal.timeout(Math.ceil(remainingMs()))]); + let falsifier: MathAgentSession | undefined; + const proposals = () => portfolio.scouts.flatMap(scout => (scout.reports ?? []).filter(report => report.status === 'proposed') + .map(({ routeId, blueprintSummary, keyTransformations }) => ({ routeId, blueprintSummary, keyTransformations }))); + 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; + // 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; + const usage = new ResearchUsage({ state, research: scout, maxTotalTokens: input.maxTotalTokens, + signal, remainingMs, changed, emit: (event, details) => emit(event, { ...details, profile }) }); + const sessionId = randomUUID(); + try { + signal.throwIfAborted(); + session = await input.open({ executable: input.executable, profile: input.profile, workspace: worktree, + proofProjectRoot: prepared.project, model: state.model, effort: state.effort, isolateProcess: true, + environment: { ...prepared.environment, DEEPSCIENTIST_MATH_WORKER_ID: 'portfolio-' + profile, + DEEPSCIENTIST_MATH_WORKER_WORKTREE: worktree }, + instructions: instructions(profile, state.problem.ownedFiles), signal, + turnTimeoutMs: Math.max(1, Math.min(input.maxTurnMs, remainingMs())), + ...usage.bindSession(sessionId, () => session?.lastInputTokens) }); + signal.throwIfAborted(); + if (!modelDispatchAllowed(state.tokenBudget!) || !remainingMs()) { + scout.status = remainingMs() ? 'failed' : 'timed-out'; + 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 }); + const attacks = profile === 'falsification-obstruction'; + const currentProposals = attacks ? proposals() : []; + result = await session.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 = session; }); + } finally { + 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); + } + } + } + // Only accept validated advisory files. Reports atomically saved before a deadline remain useful. + if (fs.existsSync(path.join(worktree, reportFile)) && !input.signal.aborted) { + 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) scout.status = signal.aborted ? 'timed-out' : 'failed'; + }); + } catch (error) { + if (!input.signal.aborted) scout.status = signal.aborted ? 'timed-out' : 'failed'; + emit('portfolio_scout_unavailable', { profile, status: scout.status, + reason: error instanceof Error && error.message === 'math_portfolio_scout_stop_unconfirmed' ? error.message : 'missing-or-invalid-scout-result' }); + } finally { changed(); } + emit('portfolio_scout_finished', { profile, status: scout.status, reports: scout.reports?.length ?? 0 }); + })); + const failure = outcomes.find(outcome => outcome.status === 'rejected'); + if (failure?.status === 'rejected') throw failure.reason; + 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/problem.ts b/src/solver/problem.ts index 10e0cefa..5c0aa16c 100644 --- a/src/solver/problem.ts +++ b/src/solver/problem.ts @@ -19,7 +19,7 @@ import { libraryDeclarationConflict } from '../math/libraryPacks'; import { maskLeanComments } from '../math/leanSyntax'; import type { EffectiveLibraryBinding } from '../math/libraryEffectivePack'; import type { LibraryHostTaskIdentity } from '../math/libraryHostConfig'; -import { originalDeclarationRegions, solverSourceContext as sourceContext } from './sourceContext'; +import { isSolverMathlibImport, originalDeclarationRegions, solverSourceContext as sourceContext } from './sourceContext'; import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills'; export { originalDeclarationRegions, solverMathlibImports } from './sourceContext'; @@ -55,7 +55,7 @@ export class SolverSourceError extends Error { return `${this.declarationName ?? 'This declaration'} is already declared by a frozen Submission/Library module. Remove or rename the copy and use the library declaration by importing its module.`; return this.message === 'math_original_context_changed' ? 'Restore the original imports, namespace/section placement, variables, opens, scopes and options from the seed commit. ' + - 'Keep new helpers; move helper-specific scopes and instances inside their proofs. Added imports may use explicit Mathlib.* modules, frozen local modules already imported by the original owned sources, or other owned modules; avoid import cycles.' + 'Keep new helpers; move helper-specific scopes and instances inside their proofs. Added imports may use Mathlib or any pinned Mathlib.* module, frozen local modules already imported by the original owned sources, or other owned modules; avoid import cycles.' : `Restore the original name, parameters, type and any frozen proof or definition body${this.declarationName ? ` of ${this.declarationName}` : ''} from the seed commit. Preserve new proof work.`; } } @@ -117,8 +117,7 @@ export function solverProofImports(problem: SolverSourceConstraints, source: str for (const file of Object.keys(problem.declarations)) if (isAllowedMathProofSource(file) && /^[A-Z][A-Za-z0-9_]*(?:\/[A-Z][A-Za-z0-9_]*)*\.lean$/u.test(file)) local.add(file.slice(0, -'.lean'.length).replaceAll('/', '.')); - return mathConstructionImports(source).filter(module => local.has(module) || - /^Mathlib(?:\.[A-Za-z_][A-Za-z0-9_']*)+$/u.test(module)); + return mathConstructionImports(source).filter(module => local.has(module) || isSolverMathlibImport(module)); } /** Ignore comments and spacing outside literals; strings and every effective context command remain bound. */ @@ -232,7 +231,7 @@ export function readSolverProblem(workspacePath: string, receiptFile: string): S /** Shared source preflight; diagnostic copies remain advisory, host checks use the frozen state. */ export function assertSolverProjectSources(problem: SolverSourceConstraints, project: string): void { - let addedLocalImportFile: string | undefined; + let addedImportFile: string | undefined; for (const [relative, digest] of Object.entries(problem.trustedFiles)) { const target = path.join(project, relative); assertMathCanonicalPath(target); @@ -253,8 +252,8 @@ export function assertSolverProjectSources(problem: SolverSourceConstraints, pro const source = fs.readFileSync(file, 'utf8'); ownedSources[relative] = source; const allowedImports = solverProofImports(problem, source); - if (allowedImports.some(module => !module.startsWith('Mathlib.') && !problem.sourceImports?.[relative]?.includes(module))) - addedLocalImportFile = relative; + if (allowedImports.some(module => !problem.sourceImports?.[relative]?.includes(module))) + addedImportFile = relative; const changedDeclaration = (regions: ReturnType) => { const matching = originalDeclarationRegions(source, regions); return originals.find(original => { @@ -286,11 +285,12 @@ export function assertSolverProjectSources(problem: SolverSourceConstraints, pro } const conflict = Object.keys(frozenSources).length ? libraryDeclarationConflict(frozenSources, ownedSources) : undefined; if (conflict) throw new SolverSourceError(conflict.file, 'math_library_declaration_redeclared', conflict.name); - if (addedLocalImportFile) { + if (addedImportFile) { + // Only project-local modules enter this graph, including any local module named like a package import. try { mathLocalModuleBuildOrder(project, Object.keys(problem.declarations)); } catch (error) { if (error instanceof Error && error.message === 'math_local_module_import_cycle') - throw new SolverSourceError(addedLocalImportFile, 'math_local_module_import_cycle'); + throw new SolverSourceError(addedImportFile, 'math_local_module_import_cycle'); throw error; } } diff --git a/src/solver/research.ts b/src/solver/research.ts index 9df284b0..08878aab 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -51,12 +51,16 @@ import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/ag import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext'; import { stopProofWriter } from './proofWriter'; import { createSkillProofLifecycle } from './skillProofLifecycle'; +import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; +import { portfolioUsageRecords } from './portfolioExploration'; // 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. @@ -141,10 +145,14 @@ export async function runResearchWorkers(input: { 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; + 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 milestoneSettings = softSliceSettings(input.softSlice ?? {}); + const leadMaxPlanningCommands = input.leadMaxPlanningCommands ?? LEAD_MAX_PLANNING_COMMANDS; assertAgentTeamProcessesStopped(state); const parallel = Boolean(state.workers); const skillResearch = state.researchMode === 'skill'; @@ -179,7 +187,8 @@ export async function runResearchWorkers(input: { ': recover into a new isolated workspace before starting another writer.'); for (const { research } of records) initializeUsageAccounting(research); const enforcement = state.tokenBudget?.enforcement; - state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [...records.map(record => record.research), ...(state.agentTeam?.workers ?? [])], enforcement); + state.tokenBudget = buildTokenBudget(input.maxTotalTokens, + [...records.map(record => record.research), ...(state.agentTeam?.workers ?? []), ...portfolioUsageRecords(state)], 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) && @@ -225,14 +234,14 @@ export async function runResearchWorkers(input: { 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, - prepareWorker: input.prepareTeamWorker, save, emit: input.emit, exclusiveCheck, + prepareWorker: input.prepareTeamWorker, softSlice: input.softSlice, save, emit: input.emit, exclusiveCheck, }) : undefined; 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 ?? [])]; + 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 (state.tokenBudget.status !== previous && !dispatchAllowed()) input.emit('model_budget_stopped', { ...state.tokenBudget }); @@ -284,8 +293,9 @@ export async function runResearchWorkers(input: { recovery.waitedMs += Math.max(0, Date.now() - started); save(); } }; - const contextResearchBases = new WeakMap(); + const contextResearchBases = new WeakMap { + basis: ResearchBasis; publishedBasis?: ResearchBasis; dispatchDigest: string; + }>(); const context = (feedback?: string, previousCheck?: ProofCheck, previousFailures = research.failures, assignment?: CooperativeAction) => { access.assertKnowledgeCurrent?.(); @@ -313,28 +323,28 @@ export async function runResearchWorkers(input: { tasks: scoped.tasks, deliveries: scoped.deliveries, }); const previous = assignment.assignment.researchBasis; - const included = new Set(currentContext.manifest?.included.map(item => item.id)); - const missing = currentContext.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}`))); - }); 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}`); } - // Thread freshness records what was dispatched, independently of consumption provenance. - // Selection matters too: a previously omitted finding may now fit without changing its basis. - const dispatchDigest = mathDigest(canonicalMathJson({ basis, included: currentContext.manifest?.included - .filter(item => dependencySections.has(item.id)).map(item => item.id).sort() })); - // Omitted new advisory material cannot retroactively become a consumed input. - contextResearchBases.set(currentContext, { basis, publishedBasis: missing ? previous : basis, dispatchDigest }); + 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; }; @@ -347,6 +357,8 @@ export async function runResearchWorkers(input: { let cooperativeCheckpoint = false; let proofHandoffCheckpoint = 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; @@ -463,6 +475,7 @@ export async function runResearchWorkers(input: { cooperativeCheckpoint = false; proofHandoffCheckpoint = false; contextSchedulingCheckpoint = false; + softSliceCheckpoint = false; advisoryTurn = undefined; usage.begin(assignment); team?.beginLeadTurn(); @@ -506,8 +519,9 @@ export async function runResearchWorkers(input: { 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 proofNoticeDelivered = false; + 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)); @@ -527,17 +541,49 @@ export async function runResearchWorkers(input: { // close() retains research.threadId; the next session resumes the saved thread. void close().catch(() => {}); }; - const interruptForCheckpoint = (event: string, details: Record) => { - if (!current() || checkpointRequested || readyRequested) return false; + 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 (current()) await activeSession.interrupt(); + 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 = assignment?.kind === 'task' + ? 'Publish standalone helpers as a helpers event in the assignment delivery log. ' + : skillMode ? 'Nominate standalone helpers for host checking in .scratch/declaration-submission.json. ' + : '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(() => { @@ -551,6 +597,17 @@ export async function runResearchWorkers(input: { 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') { @@ -567,11 +624,15 @@ export async function runResearchWorkers(input: { 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')) dispatchedContexts.clear(); + 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(); @@ -631,6 +692,8 @@ export async function runResearchWorkers(input: { const started = (turnId: string) => { usage.turnStarted(turnId); onStarted(turnId); + milestoneTurnId = turnId; + milestone?.start(); if (armed || !current()) return; armed = true; if (assignment && !isStatementAction(assignment)) { @@ -877,8 +940,10 @@ export async function runResearchWorkers(input: { }; scheduleSlice(); watchCompaction(); if (researchAssignment && activeSession.advisoryNotifications === 'native-history' && activeSession.notify) { + const handoffAfter = Date.now() + (input.minAdvisorySliceMs ?? MIN_ADVISORY_SLICE_MS); const proofTarget = () => { - if (compactionStartedAt !== undefined || !current() || checkpointRequested || readyRequested) return; + if (Date.now() < handoffAfter || compactionStartedAt !== undefined || !current() || + checkpointRequested || readyRequested || stopRequested) return; return cooperation?.proofHandoffTarget(worker, researchAssignment); }; const sameTarget = () => { @@ -888,7 +953,7 @@ export async function runResearchWorkers(input: { if (activeSession.usageSource === 'upstream-requests') { checkpointAtModelBoundary = () => { if (!proofNoticeDelivered || toolsRunning || !sameTarget() || !researchHandoffNotes()) return false; - proofHandoffCheckpoint = true; + handoffAtBoundary = true; return true; }; } @@ -927,24 +992,18 @@ export async function runResearchWorkers(input: { 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; // A natural return after the save request preserves an unfinished draft. A relay // checkpoint confirms the same successor and a current draft at the unpaid boundary. - proofHandoffCheckpoint ||= Boolean(proofNoticeDelivered && resultStatus === 'completed'); + proofHandoffCheckpoint = handoffAtBoundary || Boolean(proofNoticeDelivered && resultStatus === 'completed'); cooperativeCheckpoint = proofHandoffCheckpoint || checkpointRequested && (resultStatus === 'interrupted' || resultStatus === 'checkpoint' || checkpointClosing && resultStatus === 'failed' && researchFailureReason(detail) === 'math_codex_transport_closed'); completed = resultStatus === 'completed'; - if (proofHandoffCheckpoint && researchAssignment && requestedProof) { - const target = cooperation?.proofHandoffTarget(worker, researchAssignment); - const valid = target?.taskId === requestedProof.taskId && target?.taskDigest === requestedProof.taskDigest; - 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 (completed) 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 && @@ -953,6 +1012,8 @@ export async function runResearchWorkers(input: { } finally { finished = true; + milestone?.stop(); + softSliceAtModelBoundary = undefined; clearTimeout(noticeTimer); clearTimeout(checkpointTimer); clearTimeout(interruptTimer); clearTimeout(requestWaitTimer); cutAtRequestBoundary = undefined; afterNotice = undefined; @@ -962,6 +1023,16 @@ export async function runResearchWorkers(input: { // 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); } @@ -1066,7 +1137,7 @@ export async function runResearchWorkers(input: { const resumingThread = research.threadId; const usageCallbacks = usage.bindSession(sessionId, () => session?.lastInputTokens); if (usageCallbacks.requestGate) usageCallbacks.requestGate.checkpoint = () => - checkpointAtModelBoundary?.() ?? false; + (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, @@ -1107,6 +1178,18 @@ export async function runResearchWorkers(input: { if (team && session.processIdentity) { state.writerProcess = session.processIdentity; save(); } } catch (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; @@ -1186,6 +1269,11 @@ export async function runResearchWorkers(input: { }; 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) research.previousThreadIds = [...(research.previousThreadIds ?? []), previous]; @@ -1340,10 +1428,12 @@ export async function runResearchWorkers(input: { 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 feasibility = assignment.kind === 'task' && isFeasibilityReview(assignment.task); - const role = assignment.kind === 'review' || isStatementAction(assignment) || feasibility ? 'reviewer' : + 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; @@ -1351,19 +1441,27 @@ export async function runResearchWorkers(input: { // 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 groupChanged = record.sessionGroupId && record.sessionGroupId !== groupId; + 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}` : undefined; - const reviewAssignmentChanged = feasibility && record.sessionAssignmentId !== sessionAssignmentId; - const reviewTargetChanged = (feasibility || record.sessionRole === 'reviewer') && + const reviewAssignmentChanged = taskReview && 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; } @@ -1455,6 +1553,12 @@ export async function runResearchWorkers(input: { 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, @@ -1462,22 +1566,27 @@ export async function runResearchWorkers(input: { : assignment?.kind === 'lead' ? canonicalMathJson({ planVersion: assignment.planVersion, initial: Boolean(assignment.initialPlanNonce), problemReceiptDigest: state.problem.receiptDigest, environmentDigest: state.environmentDigest }) - : assignment?.kind === 'task' && !isFeasibilityReview(assignment.task) ? canonicalMathJson({ + : 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 contextBasis = contextResearchBases.get(currentContext); + const selectBasis = contextResearchBases.get(currentContext); + const fullContextBasis = selectBasis?.(currentContext.manifest); const dispatchedContext = responsibility === undefined ? undefined : dispatchedContexts.get(responsibility); - const researchInputsChanged = contextBasis && dispatchedContext?.researchInputDigest !== contextBasis.dispatchDigest; + const researchInputsChanged = fullContextBasis && dispatchedContext?.researchInputDigest !== fullContextBasis.dispatchDigest; const continuation = access.nativeContinuity !== false && !researchInputsChanged && responsibility !== undefined && Boolean(research.threadId) && currentContext.continuationMessage !== undefined && dispatchedContext?.threadId === research.threadId; + const taskSwitch = access.nativeContinuity !== false && sameRouteSwitch && !dispatchedContext && + Boolean(research.threadId && dispatchedContexts.size) && currentContext.continuationMessage !== undefined; Object.assign(currentContext, finalizeResearchDispatch(currentContext, { continuation, + taskSwitch, checkpointInstruction: research.threadId && research.contextCheckpoint?.threadId === research.threadId && !currentCheckpointNotesDigest() ? contextCheckpointInstruction(assignment) : undefined, })); - // Resume the same thread with new instructions, preserving its history and cumulative usage. + 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; } @@ -1494,8 +1603,11 @@ export async function runResearchWorkers(input: { try { candidate = await modelTurn(started => modules.M1.execute(state.problem, currentContext, operation, worker, turnSession, signal, turnId => { executedTurnId = turnId; - if (!continuation && assignment?.kind === 'task' && contextBasis && cooperation!.current(assignment)) { - assignment.assignment.researchBasis = contextBasis.publishedBasis; + 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) { @@ -1504,7 +1616,7 @@ export async function runResearchWorkers(input: { researchInputDigest: contextBasis?.dispatchDigest }); if (dispatchedContexts.size > 32) dispatchedContexts.delete(dispatchedContexts.keys().next().value!); } else dispatchedContexts.clear(); - emit('context_dispatched', { mode: continuation ? 'continuation' : 'full', threadId: turnSession.threadId, + emit('context_dispatched', { mode: taskSwitch ? 'task-switch' : continuation ? 'continuation' : 'full', threadId: turnSession.threadId, messageBytes: Buffer.byteLength(currentContext.message), messageDigest: mathDigest(currentContext.message), compiledContentDigest: currentContext.manifest?.contentDigest }); started(turnId); @@ -1512,12 +1624,13 @@ export async function runResearchWorkers(input: { } catch (error) { signal.throwIfAborted(); executionError = failureDetail(error, turnSession.lastError, turnSession.lastFailureDiagnostic); - if (!recoverableResearchFailure(executionError) && !locallyStopped(executionError)) throw error; + 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)) candidate = { ...candidate, status: 'checkpoint' }; + 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; @@ -1599,6 +1712,7 @@ export async function runResearchWorkers(input: { ...(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' } : cooperativeCheckpoint ? { reason: 'math_cooperative_scheduling_checkpoint' } : {}) }); @@ -1637,12 +1751,12 @@ export async function runResearchWorkers(input: { } } if (cooperation && assignment?.kind === 'task' && turn === 'checkpoint' && - !['research', 'sketch'].includes(assignment.task.kind) && (contextSchedulingCheckpoint || + !['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 = contextSchedulingCheckpoint ? 'context' : 'connection'; + const reason = softSliceCheckpoint || contextSchedulingCheckpoint ? 'context' : 'connection'; recordAdvisoryOutput(true); cooperation.retainContextDraft(worker, assignment, commit, reason); cooperation.interrupted(worker, assignment); diff --git a/src/solver/researchGuidance.ts b/src/solver/researchGuidance.ts index 92a4190a..07c665e0 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, type ContextSection } from './contextCompiler'; +import { compileContextSections, compileTaskContext, portfolioContextSections, type ContextSection } from './contextCompiler'; import { continuationContextSection, readContinuationSnapshot } from './continuationInput'; import { solverProofFeedback } from './feedback'; import type { ContextAccess, ContextBundle, ResearchDispatchOptions } from './modules/context'; @@ -15,7 +15,7 @@ import { materializeResearchToolHelp } from './researchToolHelp'; import { buildResearchToolGuide } from './researchToolGuide'; import { researchSkillIdentity } from './researchSkill'; import { skillResearchContinuationSection } from './skillResearchContext'; -import { assignmentDeliveryFile, isAdvisoryTask, leadPlanDeliveryFile } from './tasks'; +import { assignmentDeliveryFile, isAdvisoryTask, isFeasibilityReview, isFinalCandidateReview, leadPlanDeliveryFile, type CooperativeTask } from './tasks'; /** Static shared guidance also serves a native single-task baseline without manufacturing solver state. */ export function buildCommonResearchGuide(problem: SolverProblem, @@ -30,7 +30,8 @@ export function buildCommonResearchGuide(problem: SolverProblem, : 'Choose mathematical methods using the pinned skill; the host retains the current workflow and delivery contracts. ') + `Lean project: ${path.join(access.worktree, problem.projectRelative)}. Owned Lean paths: ${JSON.stringify(editable)}. ` + `Save public research notes at ${path.join(access.worktree, 'RESEARCH.md')}; scratch experiments belong under .scratch/tmp. ` + - 'For original declarations, keep kinds, names, types, hypotheses, imports, options and scopes fixed; edit only permitted proof/definition bodies. ' + + 'For original declarations, keep kinds, names, types, hypotheses, options and scopes fixed. Edit only permitted proof or definition bodies. ' + + 'Keep all existing imports. When the assignment permits source edits in a Mathlib project, you may add import Mathlib or any pinned Mathlib.* import in owned files without creating import cycles. ' + 'Independent helper declarations may be added inside editable owned Lean files when the current assignment permits source edits; any narrower assignment restrictions still apply. ' + 'Preserve trusted and frozen source. Accepted proofs cannot use sorry, admit, native_decide, unsafe or new axioms. ' + 'Do not read external candidate solutions or alter host skill, help, configuration, receipts or run state. ' + @@ -56,8 +57,10 @@ export function buildCommonResearchContext(problem: SolverProblem, state: Readon if (Boolean(access.continuation) !== Boolean(state.continuationDigest)) throw new Error('math_continuation_identity_missing'); const { instructions: commonInstructions, command } = buildCommonResearchGuide(problem, access, state.environmentDigest); const action = access.assignment, cooperation = state.cooperation; - const readOnly = action?.kind === 'lead' || action?.kind === 'review'; - const mandatory: ContextSection[] = [{ id: 'common-guidance-identity', kind: 'assignment', + 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)), + { 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. ' + 'Saved notes and source references are advisory until independently checked.' }]; @@ -67,6 +70,7 @@ export function buildCommonResearchContext(problem: SolverProblem, state: Readon ? solverProofFeedback(state.check, access.previousCheck, access.previousFailures ?? state.failures) : undefined].filter(Boolean).join('\n\n'); let protocol: string; let workContract: ContextBundle['workContract']; + const taskContinuation = action?.kind === 'task' && !isFeasibilityReview(action.task) && !isFinalCandidateReview(action.task); if (action && cooperation) { // deliveryGuidance contains legacy mathematical heuristics. The comparison keeps // the actual ownership/evidence contract and obtains methods solely from the shared skill. @@ -77,7 +81,8 @@ export function buildCommonResearchContext(problem: SolverProblem, state: Readon text: 'Required fields for this host decision:\n' + cooperation.leadDecisionInstruction }); protocol = 'Perform only the current assignment and preserve unrelated sources from its seed commit. ' + 'The host owns task selection, workspaces and integration; do not start another agent yourself. ' + - (readOnly ? 'Leave all Lean sources unchanged. ' : '') + cooperativeDeliveryProtocol(action); + (readOnly ? 'Leave all Lean sources unchanged. ' : '') + + cooperativeDeliveryProtocol(action, 'the current delivery log named in the assignment message'); } else { protocol = 'Save source and RESEARCH.md, stop writing and return at a natural delivery point. ' + 'When every original target is complete, a successful check-lean covering its files also hands writing back to the host. ' + @@ -91,7 +96,7 @@ export function buildCommonResearchContext(problem: SolverProblem, state: Readon if (state.researchMode === 'skill' && fs.existsSync(declarationFeedback)) mandatory.push({ id: 'declaration-feedback', kind: 'feedback', text: `Read current host declaration feedback from ${declarationFeedback} before resubmitting.` }); const instructions = commonInstructions + '\nExecution and delivery protocol:\n' + protocol; - const compile = (options: ResearchDispatchOptions = {}) => state.researchMode === 'skill' && options.continuation + const compile = (options: ResearchDispatchOptions = {}) => !action && state.researchMode === 'skill' && options.continuation ? compileContextSections({ instructions, mandatory: [skillResearchContinuationSection(problem, state), ...mandatory, ...(feedback ? [{ id: 'host-feedback', kind: 'feedback' as const, text: feedback }] : []), @@ -100,17 +105,27 @@ export function buildCommonResearchContext(problem: SolverProblem, state: Readon maxContextBytes: access.maxContextBytes, maxOptionalContextBytes: access.maxOptionalContextBytes, inlineManifest: false }) : compileTaskContext({ problem, cooperation, action, instructions, taskText: access.taskText, feedback, frozenContexts, environmentDigest: state.environmentDigest, + taskSwitch: taskContinuation && (options.taskSwitch || options.continuation), maxContextBytes: access.maxContextBytes, maxOptionalContextBytes: access.maxOptionalContextBytes, mandatory: [...mandatory, ...(options.checkpointInstruction ? [{ id: 'dispatch-checkpoint', kind: 'checkpoint' as const, text: options.checkpointInstruction }] : [])] }); - const continued = state.researchMode === 'skill' ? compile({ continuation: true }) : undefined; + const continued = taskContinuation || !action && state.researchMode === 'skill' ? compile({ continuation: true }) : undefined; return { instructions, ...compile(), ...(continued ? { continuationMessage: continued.message, continuationManifest: continued.manifest } : {}), compileDispatch: compile, assignment: action, workContract, scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } }; } -export function cooperativeDeliveryProtocol(action: NonNullable): string { +export function cooperativeHelperProtocol(task: CooperativeTask, log: string): string { + if (isFeasibilityReview(task) || isFinalCandidateReview(task)) return ''; + return 'To share completed standalone helpers during this assignment, save them in owned Lean files and append ' + + '{"kind":"helpers","declarations":[{"file":"Submission.lean","name":"Qualified.helper"}],"summary":"What the helper proves"} ' + + 'as one JSON line to ' + log + '. Nominate new declarations with no unresolved premises from unproved declarations. ' + + 'The host verifies them independently and can land them while your assigned target remains unfinished. ' + + (isAdvisoryTask(task) ? 'Restore your temporary Lean edits after the host acknowledges the submission and before ordinary findings delivery. ' : ''); +} + +export function cooperativeDeliveryProtocol(action: NonNullable, taskLog?: string): string { if (action.kind === 'review') return 'Review the fixed candidate and matching evidence without editing it. ' + 'Save one JSON object in RESEARCH.md: {"verdict":"accepted|changes_requested","summary":"...","evidenceRefs":[]}, then return. '; if (action.kind === 'lead') { @@ -122,19 +137,21 @@ export function cooperativeDeliveryProtocol(action: NonNullable; maxTotalTokens: number; signal: AbortSignal; remainingMs: () => number; changed: () => void; emit: (event: string, details: Record) => void; }) {} diff --git a/src/solver/routeControl.ts b/src/solver/routeControl.ts index a92f2eef..8c782949 100644 --- a/src/solver/routeControl.ts +++ b/src/solver/routeControl.ts @@ -1,6 +1,20 @@ +import { z } from 'zod'; import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; import { freshlyAccepted, hasTaskAcceptance, isAdvisoryTask, taskGroup, taskVersion, type CooperativeTask, type TaskRecord } from './tasks'; +export const portfolioRouteIdSchema = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/u); +export const routeRetirementSchema = z.object({ + routeId: portfolioRouteIdSchema, + reason: z.string().trim().min(1).max(3000), + evidenceRefs: z.array(z.string().trim().min(1).max(1000)).max(16).optional(), +}).strict(); +export const retiredRouteSchema = routeRetirementSchema.extend({ + retiredAt: z.number().int().nonnegative(), + source: z.enum(['portfolio', 'lead']), +}); +export type RouteRetirement = z.infer; +export type RetiredRoute = z.infer; + export type ReopenCondition = { kind: 'contract-changed' } | { kind: 'environment-changed' } | { kind: 'dependency-checked'; taskId: string }; export type BlockerProposal = { mechanism: string; scope: string; blockerId?: string; evidenceRefs?: readonly string[]; diff --git a/src/solver/run.ts b/src/solver/run.ts index 584f1048..b56587ee 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -31,7 +31,7 @@ import { readPersonalExperts } from './personalExperts'; import { evaluateSolverProof } from './evaluation'; import { solverProofIsCurrent } from './modules/evidence'; import { checkCodexProviderConnectivity } from '../runtime/codexConnectivity'; -import { buildTokenBudget } from './usageBudget'; +import { aggregateUsage, buildTokenBudget } from './usageBudget'; import { selectedDeepSeekProfile } from '../runtime/deepseek'; import { selectedWestlakeProfile } from '../runtime/westlake'; import { selectedSub2apiProfile } from '../runtime/sub2api'; @@ -59,6 +59,7 @@ 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 ? [ @@ -66,12 +67,13 @@ const runSummary = (state: SolverRunState | undefined) => { ] : undefined); return { turns: state?.turns, dispatchCounts: state?.dispatchCounts, ...(state?.verifierFailure ? { verifierFailure: state.verifierFailure } : {}), - usage: state?.teamUsage ?? state?.usage, tokenBudget: state?.tokenBudget, + usage: state?.teamUsage ?? (state && portfolioUsageRecords(state).length + ? aggregateUsage([...(state.workers ?? [state]), ...portfolioUsageRecords(state)]) : 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): Promise { +export async function runSolver(args: string[], root: string, customModules?: SolverModules, hostSignal?: AbortSignal): 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' }, @@ -94,12 +96,16 @@ export async function runSolver(args: string[], root: string, customModules?: So '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' }, } }); 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.`); 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. Omit the preset to retain ordinary solver dispatch.'); 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.'); @@ -118,6 +124,15 @@ export async function runSolver(args: string[], root: string, customModules?: So return 0; } const specified = (key: string) => args.some(arg => arg === '--' + key || arg.startsWith('--' + key + '=')); + if (values['agent-team'] !== undefined) { + if (values['research-mode'] !== undefined && values['research-mode'] !== 'skill' || + values['skill-delegation'] !== undefined && values['skill-delegation'] !== 'team' || + values['skill-max-agents'] !== undefined && values['skill-max-agents'] !== values['agent-team']) + throw new Error('conflicting --agent-team and Skill research options'); + values['research-mode'] = 'skill'; + values['skill-delegation'] = 'team'; + values['skill-max-agents'] = values['agent-team']; + } let savedConfiguration: SolverRunState | undefined; if (values.resume && values.output) { try { savedConfiguration = readSolverRunState(`${path.resolve(values.output)}.runtime/state.json`); } @@ -201,6 +216,8 @@ export async function runSolver(args: string[], root: string, customModules?: So 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'); @@ -222,6 +239,9 @@ export async function runSolver(args: string[], root: string, customModules?: So const stateFile = path.join(directory, 'state.json'); const controller = new AbortController(); const abort = () => controller.abort(); + const hostAbort = () => controller.abort(hostSignal?.reason); + hostSignal?.addEventListener('abort', hostAbort, { once: true }); + if (hostSignal?.aborted) hostAbort(); process.once('SIGINT', abort); process.once('SIGTERM', abort); const preparationStarted = Date.now(); @@ -302,6 +322,12 @@ export async function runSolver(args: string[], root: string, customModules?: So const knowledge = values['knowledge-base'] ? readAuthorizedKnowledgeCatalog(values['knowledge-base'], workspace, values['receipt-file'] || path.join(workspace, 'active-problem.json')) : undefined; const resumedState = values.resume ? readSolverRunState(stateFile) : 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'); @@ -442,13 +468,15 @@ export async function runSolver(args: string[], root: string, customModules?: So git(workspace, ['worktree', 'add', '--detach', state.worktree, problem.baseCommit]); writeSolverRunState(stateFile, state); } + 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 ?? [])], state.tokenBudget?.enforcement); + [...(state.workers ?? [state]), ...(state.agentTeam?.workers ?? []), ...portfolioUsageRecords(state)], 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]); @@ -672,6 +700,12 @@ 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, @@ -763,6 +797,7 @@ export async function runSolver(args: string[], root: string, customModules?: So } finally { executionClock?.stop(); clearTimeout(timer); + hostSignal?.removeEventListener('abort', hostAbort); process.removeListener('SIGINT', abort); process.removeListener('SIGTERM', abort); } } diff --git a/src/solver/skillResearchContext.ts b/src/solver/skillResearchContext.ts index 8dd21bbd..2bad8a9f 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, type ContextSection } from './contextCompiler'; +import { compileContextSections, portfolioContextSections, type ContextSection } from './contextCompiler'; import { continuationContextSection, readContinuationSnapshot } from './continuationInput'; import { DECLARATION_INDEX_FILE } from './declarationIndex'; import { solverProofFeedback } from './feedback'; @@ -84,7 +84,8 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl 'Optional description and premises describe scope, not additional proof authority. The host verifies each actual declaration and complete type independently. ' + 'Other incomplete goals may remain; a helper that depends on them or on new axioms is rejected. ' + 'The request is consumed after the turn, and its host feedback is saved at .scratch/declaration-feedback.json. ' + - 'It never claims the original problem is solved. No task graph, role acknowledgment or fabricated receipt is required.'; + 'It never claims the original problem is solved. No task graph, role acknowledgment or fabricated receipt is required. ' + + 'When the host requests a soft milestone handoff, submit available standalone helpers, record progress and the exact obstruction in fewer than 20 lines in RESEARCH.md, then return.'; help.section('delivery', teamWorker ? agentTeamWorkerDeliveryHelp() : team ? 'Member delivery contract, supplied by the host: ' + agentTeamWorkerDeliveryHelp() + '\n\n' + 'The following declaration-submission file is only for your own Lead worktree; do not assign it to a member. ' + ownDelivery : ownDelivery, ''); @@ -115,9 +116,9 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl 'Only these paths may contain submitted Lean source; add helpers inside them instead of creating another Lean file. ' + (team ? 'Every member has a separate worktree. Identical relative filenames belong to different copies; Lead does not own the member\'s copy. ' : '') + `Public research notes: ${path.join(access.worktree, 'RESEARCH.md')}. Temporary experiments and requests belong in .scratch/tmp or the documented .scratch paths.\n` + - 'For original declarations, keep kinds, names, types, hypotheses, imports, options and scopes fixed; edit only permitted proof/definition bodies. ' + + 'For original declarations, keep kinds, names, types, hypotheses, options and scopes fixed. Edit only permitted proof/definition bodies. ' + 'You may add independent helper declarations inside the editable owned Lean files; the original-declaration restriction does not prohibit these additions. ' + - 'Preserve trusted files and frozen definitions. New imports must be permitted by the frozen source policy. ' + + 'Preserve trusted files, frozen definitions and all existing imports. In a Mathlib project, you may add import Mathlib or any pinned Mathlib.* import in editable files without creating import cycles. ' + 'Accepted proofs cannot use sorry, admit, native_decide, unsafe or new axioms. Independent helpers may be submitted while other goals remain unfinished. ' + '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. ' + @@ -136,7 +137,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[] = []; + const mandatory: ContextSection[] = portfolioContextSections(state); 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 }); diff --git a/src/solver/softSlice.ts b/src/solver/softSlice.ts new file mode 100644 index 00000000..0c5e60fc --- /dev/null +++ b/src/solver/softSlice.ts @@ -0,0 +1,71 @@ +export const SOFT_SLICE_MS = 30 * 60_000; +export const MAX_COMPACTIONS_PER_SLICE = 2; +const SOFT_SLICE_GRACE_MS = 60_000; +const BOUNDARY_WAIT_MS = 30_000; + +export type SoftSliceSettings = { + softSliceMs?: number; + maxCompactionsPerSlice?: number; + softSliceGraceMs?: number; +}; + +export function softSliceSettings(options: SoftSliceSettings, environment: NodeJS.ProcessEnv = process.env) { + const setting = (option: number | undefined, name: string, fallback: number) => { + const raw = option ?? (environment[name]?.trim() ? Number(environment[name]) : fallback); + return Number.isSafeInteger(raw) && raw >= 0 && raw <= 2_147_483_647 ? raw : fallback; + }; + return { + timeMs: setting(options.softSliceMs, 'THEOREMOS_SOFT_SLICE_MS', SOFT_SLICE_MS), + compactions: setting(options.maxCompactionsPerSlice, 'THEOREMOS_MAX_COMPACTIONS_PER_SLICE', MAX_COMPACTIONS_PER_SLICE), + graceMs: setting(options.softSliceGraceMs, 'THEOREMOS_SOFT_SLICE_GRACE_MS', SOFT_SLICE_GRACE_MS), + }; +} + +/** One turn owns the notice, grace period, and bounded wait for its next request boundary. */ +export function createSoftSlice(settings: ReturnType, hooks: { + current(): boolean; + notice(reason: 'time' | 'compaction', completedCompactions: number): void; + interrupt(): void; +}) { + let completedCompactions = 0, started = false, requested = false, waiting = false, stopped = false; + let timer: ReturnType | undefined; + const schedule = (callback: () => void, ms: number) => { + timer = setTimeout(callback, ms); + timer.unref(); + }; + const request = (reason: 'time' | 'compaction') => { + if (stopped || requested || !hooks.current()) return; + requested = true; + clearTimeout(timer); + hooks.notice(reason, completedCompactions); + schedule(() => { + if (!hooks.current()) return; + waiting = true; + schedule(() => { + waiting = false; + if (hooks.current()) hooks.interrupt(); + }, BOUNDARY_WAIT_MS); + }, settings.graceMs); + }; + const useBoundary = () => { + if (!waiting || !hooks.current()) return false; + waiting = false; + clearTimeout(timer); + return true; + }; + return { + start() { + if (started || stopped) return; + started = true; + if (settings.compactions && completedCompactions >= settings.compactions) request('compaction'); + else if (settings.timeMs) schedule(() => request('time'), settings.timeMs); + }, + compacted() { + completedCompactions++; + if (started && settings.compactions && completedCompactions >= settings.compactions) request('compaction'); + }, + useBoundary, + get requested() { return requested; }, + stop() { stopped = true; waiting = false; clearTimeout(timer); }, + }; +} diff --git a/src/solver/sourceContext.ts b/src/solver/sourceContext.ts index 82f3dc29..0f192540 100644 --- a/src/solver/sourceContext.ts +++ b/src/solver/sourceContext.ts @@ -1,9 +1,11 @@ import { inspectLeanDeclarationRegions, inspectScopedLeanDeclarations } from '../math/leanSource'; import { mathConstructionImports } from '../math/mathConstructionSources'; -/** Only explicit modules from the pinned Mathlib package may extend proof imports. */ +export const isSolverMathlibImport = (module: string): boolean => /^Mathlib(?:\.[A-Za-z_][A-Za-z0-9_']*)*$/u.test(module); + +/** Allow the root module and explicit submodules of the pinned Mathlib package. */ export function solverMathlibImports(source: string): string[] { - return mathConstructionImports(source).filter(module => /^Mathlib(?:\.[A-Za-z_][A-Za-z0-9_']*)+$/u.test(module)); + return mathConstructionImports(source).filter(isSolverMathlibImport); } /** Regions of `source` holding an original: the same written name and, for a repeated one, the same qualified name. */ diff --git a/src/solver/taskLifecycle.ts b/src/solver/taskLifecycle.ts index 3c5d955b..4fdee8b9 100644 --- a/src/solver/taskLifecycle.ts +++ b/src/solver/taskLifecycle.ts @@ -31,6 +31,8 @@ const RULES = { invalidated: { from: ['integrated', 'conditional', 'delivered'], to: ['blocked'] }, /** Host advisory capacity expired with its frozen inputs. */ expired: { from: ['pending', 'running', 'blocked', 'completed'], to: ['blocked'] }, + /** A retired route stops every unintegrated obligation on that branch. */ + 'route-retired': { from: ['pending', 'running', 'blocked', 'completed', 'conditional', 'delivered'], to: ['blocked'] }, /** Offline reconstruction (continuation seeding, snapshot recovery) rebuilds statuses from checked evidence. */ reconstructed: { from: ['pending', 'running', 'blocked', 'conditional', 'delivered', 'integrated', 'completed'], to: ['pending', 'blocked', 'conditional', 'integrated', 'completed'] }, diff --git a/src/solver/taskTypeContract.ts b/src/solver/taskTypeContract.ts index 4ae31654..14872913 100644 --- a/src/solver/taskTypeContract.ts +++ b/src/solver/taskTypeContract.ts @@ -1,5 +1,6 @@ import { maskLeanCommentsAndStrings } from '../math/leanSyntax'; import type { CooperativeTask } from './tasks'; +import { invalidPlanField } from './planDiagnostics'; type TypedTask = Pick; @@ -26,6 +27,6 @@ export function assertPlanTaskTypeContracts(tasks: readonly CooperativeTask[], p const before = previous.get(task.id); if (before?.kind === task.kind && before.type === task.type) continue; const reason = taskTypeContractError(task); - if (reason) throw new Error('math_plan_invalid_helper_type: ' + reason); + if (reason) throw invalidPlanField('math_plan_invalid_helper_type', `tasks[${task.id}].type`, reason); } } diff --git a/src/solver/tasks.ts b/src/solver/tasks.ts index db58f28c..489a389a 100644 --- a/src/solver/tasks.ts +++ b/src/solver/tasks.ts @@ -10,6 +10,8 @@ import type { CapacityExploration } from './capacityExploration'; import type { ResearchBasis, ResearchRecord } from './researchRecords'; import { expandTaskFamilies, type TaskFamily } from './taskFamilies'; import type { researchSourceKinds } from './researchReferences'; +import { planError, PlanValidationError } from './planDiagnostics'; +export { planError } from './planDiagnostics'; export type CooperativeTask = Readonly<{ id: string; kind: 'research' | 'sketch' | 'lemma' | 'goal'; objective: string; dependsOn: readonly string[]; revision: number; proofPath?: string; theoremName?: string; type?: string; @@ -195,16 +197,15 @@ export function parseWaitsOn(value: unknown, deferred: boolean, task: (id: strin const validId = (value: unknown) => typeof value === 'string' && /^[a-zA-Z0-9_-]{1,64}$/u.test(value); /** Blueprint prose travels with every plan copy, so it stays short; full sources belong in references. */ export const MAX_INFORMAL_PROOF_CHARS = 2000, MAX_CITATIONS = 8, MAX_CITATION_CHARS = 300; -/** Name the rejected plan element so a Lead can repair it without reading the validator. */ -export const planError = (code: string, detail: Record, hint = '') => - new Error(`${code}: ${JSON.stringify(detail)}${hint ? '. ' + hint : ''}`); const optionalFields = (value: any, keys: readonly string[]) => Object.fromEntries(keys.filter(key => value[key] !== undefined).map(key => [key, value[key]])); /** A null field means "unset", as it does in a revision upsert; Leads write `"ownerId": null` for an unowned task. */ const withoutNulls = (value: unknown) => value && typeof value === 'object' && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== null)) : value; -export function parseCooperationPlan(problem: SolverProblem, value: any): { tasks: CooperativeTask[]; groups: RouteGroup[]; proofRoutes?: ProofRoute[] } { +export type CooperationPlanProblem = Pick; + +export function parseCooperationPlan(problem: CooperationPlanProblem, value: any): { tasks: CooperativeTask[]; groups: RouteGroup[]; proofRoutes?: ProofRoute[] } { if (value?.tasks && typeof value.tasks === 'object' && !Array.isArray(value.tasks)) throw planError('math_plan_invalid', { field: 'tasks' }, 'tasks must be the complete array of task objects; a revision omits tasks and puts baseVersion, upsert and remove at the top level'); @@ -212,8 +213,10 @@ export function parseCooperationPlan(problem: SolverProblem, value: any): { task throw planError('math_plan_invalid', { field: 'tasks' }, 'include the complete tasks array, or use a revision with baseVersion and upsert/remove; ' + 'when only answering decisions, use {"baseVersion":"CURRENT_PLAN_VERSION","upsert":[]} plus the required decisions in the same JSON object'); - if (!value || !Array.isArray(value.tasks) || value.tasks.length < 1) - throw new Error('math_plan_invalid'); + if (value && !Array.isArray(value.tasks)) + throw planError('math_plan_invalid', { field: 'tasks' }, 'Supply the complete array of task objects.'); + if (!value || value.tasks.length < 1) + throw new PlanValidationError('math_plan_invalid', '', [{ path: 'tasks', message: 'Supply a nonempty array of task objects.' }]); // Leads routinely serialize an empty explicit list; it carries the same meaning as omitting it. const rawGroups = !Array.isArray(value.groups) || !value.groups.length ? [{ id: 'main', objective: 'Prove the original problem' }] : value.groups.map(withoutNulls); @@ -274,8 +277,10 @@ export function parseCooperationPlan(problem: SolverProblem, value: any): { task 'Use a declared group id and sharing "group" or "problem".'); if (!isAdvisoryTask(task) && (!problem.ownedFiles.includes(task.proofPath) || !isSimpleLeanName(task.theoremName))) - throw new Error('math_plan_invalid_proof_target: ' + JSON.stringify({ taskId: task.id, - proofPath: task.proofPath, theoremName: task.theoremName }) + '. Use an owned proofPath and an ordinary qualified Lean name.'); + throw planError('math_plan_invalid_proof_target', { taskId: task.id, + proofPath: task.proofPath, theoremName: task.theoremName, + field: !problem.ownedFiles.includes(task.proofPath) ? 'proofPath' : 'theoremName' }, + 'Use an owned proofPath and an ordinary qualified Lean name.'); if (!isAdvisoryTask(task) && Object.hasOwn(problem.frozenFiles ?? {}, task.proofPath)) throw planError('math_plan_frozen_proof_path', { taskId, proofPath: task.proofPath }, 'Submission/Library modules are frozen host libraries; put the task in another owned file that imports the module.'); @@ -283,7 +288,8 @@ export function parseCooperationPlan(problem: SolverProblem, value: any): { task throw planError('math_plan_changed_original_target', { taskId, proofPath: task.proofPath, theoremName: task.theoremName }, 'A goal task must name an original target exactly; use a lemma task for a helper statement.'); if (task.kind === 'lemma' && typeof task.type === 'string' && task.type.trim() === 'FULL_CLOSED_LEAN_TYPE') - throw new Error('math_plan_placeholder_helper_type: supply the actual closed Lean type, or use an untyped research/sketch task for advisory findings.'); + throw planError('math_plan_placeholder_helper_type', { taskId, field: 'type' }, + 'Supply the actual closed Lean type, or use an untyped research/sketch task for advisory findings.'); if (task.kind === 'lemma' && (typeof task.type !== 'string' || !task.type.trim())) throw planError('math_plan_invalid_helper_type', { taskId, field: 'type' }, 'Supply the closed Lean type of the helper.'); if (task.kind === 'lemma') { diff --git a/tests/agentResearchTeam.test.ts b/tests/agentResearchTeam.test.ts index f84a11ca..3cfa7f67 100644 --- a/tests/agentResearchTeam.test.ts +++ b/tests/agentResearchTeam.test.ts @@ -273,9 +273,9 @@ describe('Agent-led sustained collaboration with real Git and Lean', () => { 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: expect.arrayContaining([ - 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'history', 'yield', 'submit']) } } }); - expect((fast.options.tools!.definitions[0]!.inputSchema.properties as Record).operation!.enum).toHaveLength(9); + .toMatchObject({ properties: { operation: { enum: [ + 'progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', + 'submit_helpers', '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)); @@ -992,9 +992,9 @@ describe('Agent-led sustained collaboration with real Git and Lean', () => { 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: expect.arrayContaining([ - 'spawn', 'assign', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate']) } } }); - expect((f.team.tools('lead').definitions[0]!.inputSchema.properties as Record).operation!.enum).toHaveLength(17); + .toMatchObject({ properties: { operation: { enum: [ + 'spawn', 'assign', 'amend', 'finish', 'coordinate', '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'); diff --git a/tests/agentTeamNativeControl.test.ts b/tests/agentTeamNativeControl.test.ts index 98537356..cc9aab0f 100644 --- a/tests/agentTeamNativeControl.test.ts +++ b/tests/agentTeamNativeControl.test.ts @@ -278,9 +278,9 @@ describe('native AgentControl mathematical-team host routing', () => { expect(operations).not.toContain(operation); expect(agentTeamOperationAllowed('lead', false, 'native-agent-control', operation)).toBe(false); } - expect(operations).toEqual(['finish', 'history', 'inspect', 'inspect-research', 'adopt']); + expect(operations).toEqual(['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary']); const memberTool = agentTeamToolDefinition('analyst', false, 'native-agent-control'); - expect((memberTool.inputSchema.properties as Json).operation.enum).toEqual(['yield', 'history', 'inspect', 'inspect-research', 'submit']); + expect((memberTool.inputSchema.properties as Json).operation.enum).toEqual(['yield', 'history', 'inspect', 'inspect-research', 'submit', 'submit_helpers', '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'); diff --git a/tests/agentTeamNativeTools.test.ts b/tests/agentTeamNativeTools.test.ts index 0d71b3ad..5501c4a9 100644 --- a/tests/agentTeamNativeTools.test.ts +++ b/tests/agentTeamNativeTools.test.ts @@ -21,9 +21,29 @@ const nativeAvailable = spawnSync(executable, ['--version'], { env: { PATH: process.env.PATH }, timeout: 5000, stdio: 'ignore', }).status === 0; const operations = ['spawn', 'assign', 'amend', 'finish', 'coordinate', 'budget', 'resume', 'history', 'publish', 'cancel', - 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop']; -const nativeLeadOperations = ['finish', 'history', 'inspect', 'inspect-research', 'adopt']; -const nativeMemberOperations = ['yield', 'history', 'inspect', 'inspect-research', 'submit']; + 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'retire_route', 'route_summary']; +const memberOperations = ['progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', + 'submit_helpers', 'route_summary']; +const nativeLeadOperations = ['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary']; +const nativeMemberOperations = ['yield', 'history', 'inspect', 'inspect-research', 'submit', 'submit_helpers', 'route_summary']; + +/** Codex may normalize validation keywords, but it must preserve every branch and field. */ +function expectAdvertisedOperations(host: Json, expected: string[], schema: Json) { + expect(host).toBeDefined(); + const parameters = host.parameters; + expect(parameters).toMatchObject({ type: 'object', required: ['operation'], additionalProperties: false, + properties: { operation: { type: 'string', enum: expected } } }); + expect(Object.keys(parameters.properties).sort()).toEqual(Object.keys(schema.properties).sort()); + if (expected.length > 16) expect(parameters).not.toHaveProperty('oneOf'); + else { + expect(parameters.oneOf.map((branch: Json) => branch.properties.operation.enum[0])).toEqual(expected); + for (const [index, branch] of schema.oneOf.entries()) { + expect(parameters.oneOf[index]).toMatchObject({ type: 'object', required: branch.required, additionalProperties: false }); + expect(Object.keys(parameters.oneOf[index].properties).sort()).toEqual(Object.keys(branch.properties).sort()); + } + } + for (const operation of expected) expect(host.description).toContain(operation + ': required '); +} let directory: string | undefined, session: MathAgentSession | undefined, server: Server | undefined; afterEach(async () => { @@ -158,25 +178,24 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou // 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' ? ['history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'progress'] : + const allowed = actor === 'member' ? memberOperations : finiteBudget ? operations : operations.filter(name => name !== 'budget'); - expect(advertised?.parameters.properties.operation.enum).toEqual(actor === 'member' - ? expect.arrayContaining(allowed) : allowed); + 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 (finiteBudget) expect(advertised?.parameters).not.toHaveProperty('oneOf'); - else { - expect(advertised?.parameters.oneOf).toHaveLength(advertised?.parameters.properties.operation.enum.length); + 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).toContain('coordinate: required decision, reason, nextStep;'); - if (!finiteBudget) { - const coordinateSchema = advertised?.parameters.oneOf.find((branch: Json) => branch.properties.operation.enum[0] === 'coordinate'); - expect(coordinateSchema).toMatchObject({ required: ['operation', 'decision', 'reason', 'nextStep'], additionalProperties: false }); - } + expect(advertised?.description).toContain('retire_route: required routeId, reason; optional evidenceRefs; other fields forbidden.'); + expect(advertised?.parameters.properties).toMatchObject({ decision: { type: 'string', enum: ['defer', 'continue'] }, + reason: { type: 'string' }, nextStep: { type: 'string' }, evidenceRefs: { type: 'array', items: { type: 'string' } } }); } else { expect(advertised?.description).toContain('submit: required summary, declarations; optional objectiveRevision; other fields forbidden.'); const submitSchema = advertised?.parameters.oneOf.find((branch: Json) => branch.properties.operation.enum[0] === 'submit'); @@ -306,7 +325,7 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou 'theoremos_team', 'ordinary_research_probe', 'exec_command', ])); const host = advertised.find(tool => tool.name === 'theoremos_team'); - expect([...host!.parameters.properties.operation.enum].sort()).toEqual([...nativeLeadOperations].sort()); + expectAdvertisedOperations(host!, nativeLeadOperations, tools.definitions[0]!.inputSchema); for (const property of ['decision', 'nextStep', 'budget', 'leadReserve', 'objectiveRevision']) expect(host!.parameters.properties).not.toHaveProperty(property); } @@ -388,7 +407,7 @@ describe.skipIf(!nativeAvailable)('real Codex dynamic team tool transport withou const host = declaredTools(body).find(tool => tool.name === 'theoremos_team'); const child = text.includes('NATIVE_ACTUAL_CHILD_FIXTURE'); const allowed = child ? nativeMemberOperations : nativeLeadOperations; - expect([...host!.parameters.properties.operation.enum].sort()).toEqual([...allowed].sort()); + expectAdvertisedOperations(host!, allowed, team.tools(child ? 'member' : 'lead').definitions[0]!.inputSchema); const mode = effectiveMultiAgentMode(body); expect(mode).toBeDefined(); expect(mode).not.toContain('Any earlier instruction enabling proactive multi-agent delegation no longer applies'); diff --git a/tests/agentTeamRouteSummary.test.ts b/tests/agentTeamRouteSummary.test.ts new file mode 100644 index 00000000..4d166d50 --- /dev/null +++ b/tests/agentTeamRouteSummary.test.ts @@ -0,0 +1,112 @@ +import fs from 'node:fs'; +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 { 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) { + const { directory, workspace, problem } = localExample('agent-team-route-summary-'); + roots.push(directory); + const commit = problem.baseCommit, deliveryId = 'a'.repeat(64); + const tasks: AgentTeamTask[] = [ + { id: 'foundation', status: 'running', workKind: 'proof', routeId: 'live', message: 'Prove the identity.\nUse the substitution.', sequence: 1 }, + { id: 'queued', status: 'queued', workKind: 'research', routeId: 'live', message: 'Check the boundary.', sequence: 2 }, + { id: 'paused', status: 'paused', workKind: 'review', routeId: 'live', message: 'Review the shared lemma.', sequence: 3 }, + { id: 'delivered', status: 'completed', workKind: 'proof', routeId: 'live', message: 'Check the reduction.', sequence: 4, + deliveryId, summary: 'Checked the reduction.', declarations: [{ file: 'Submission.lean', name: 'reduce', type: 'True' }] }, + { 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, + 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 }], + landedHelpers: [{ file: 'Submission.lean', qualifiedName: 'base', type: '∀ n : Nat,\n n = n', commit, landedAt: 12 }], + deliveries: [{ id: deliveryId, agentId: 'member', taskId: 'delivered', path: '/unused' }], events: [], adoptions: [], operations: [], + researchState: { revision: 3, summary: 'Explore\n the live route.', publishedAt: 13 }, + } }); + const save = vi.fn(); + const signal = new AbortController().signal; + const team = new AgentResearchTeam({ state, root: process.cwd(), executable: 'offline', profile: 'offline', + taskText: 'Offline route summary fixture', leadAccess: { environment: {}, retrievalRoot: workspace }, signal, + modules: directSolverModules, maxAgents: 2, maxTurnMs: 1_000, maxTurns: Infinity, maxTotalTokens: 0, + remainingMs: () => 1_000, save, emit: () => {}, exclusiveCheck: operation => operation() }); + const call = (actor: string, filters: Record = {}) => team.tools(actor).call( + 'theoremos_team', { operation: 'route_summary', ...filters }, + { signal, threadId: 'thread', turnId: 'turn', callId: 'route-summary' }); + return { team, save, call, commit, deliveryId }; +} + +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); + const full = await call('lead'); + expect(await call('member')).toEqual(full); + expect(full).toMatchObject({ ok: true, canonicalCommit: commit, + routes: [{ routeId: 'live', running: 1, queued: 1, paused: 1, completed: 1 }], + retiredRoutes: [{ routeId: 'dead', source: 'lead', reason: 'A boundary counterexample. See probe.', evidenceRefCount: 1 }], + tasks: expect.arrayContaining([{ taskId: 'foundation', workerId: 'member', routeId: 'live', status: 'running', + workKind: 'proof', objective: 'Prove the identity. Use the substitution.' }]), + landedHelpers: [{ file: 'Submission.lean', qualifiedName: 'base', signature: '∀ n : Nat, n = n', landedAt: 12 }], + recentDeliveries: [{ id: deliveryId, producer: 'member', kind: 'proof', declarationCount: 1, summary: 'Checked the reduction.' }], + research: { revision: 3, summary: 'Explore the live route.' } }); + expect(await call('member', { routeId: 'dead' })).toMatchObject({ + ok: true, routes: [], retiredRoutes: [{ routeId: 'dead' }], recentDeliveries: [], + }); + expect(await call('lead', { routeId: 'dead', includeRetired: false })).toMatchObject({ tasks: [], retiredRoutes: [] }); + expect(await call('member', { includeRetired: 'false' })).toMatchObject({ ok: false, error: 'math_team_arguments_invalid' }); + expect(team.archive.operations).toEqual([]); + expect(save).not.toHaveBeenCalled(); + }); + + it('keeps large Unicode archives under 8 KiB and preserves newest checked references', async () => { + const { team, call, commit } = fixture('host-tools'); + 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 }); + team.archive.retiredRoutes!.push({ routeId: 'old-' + i, source: 'portfolio', reason: long, retiredAt: i }); + team.archive.landedHelpers!.push({ file: 'Submission.lean', qualifiedName: 'helper' + i, type: long, commit, landedAt: i }); + team.archive.deliveries.push({ id: 'checked-' + i, agentId: 'member', taskId: 'task-' + i, + path: '/unused', declarationCount: 1, kind: 'helpers', summary: long.slice(0, 200) }); + } + team.archive.researchState!.summary = long; + const summary = await call('member'); + expect(Buffer.byteLength(JSON.stringify(summary))).toBeLessThan(8 * 1024); + expect(summary).toMatchObject({ + tasks: expect.arrayContaining([expect.objectContaining({ taskId: 'task-200' })]), + landedHelpers: expect.arrayContaining([expect.objectContaining({ qualifiedName: 'helper200' })]), + recentDeliveries: expect.arrayContaining([expect.objectContaining({ id: 'checked-200', declarationCount: 1 })]), + omitted: { tasks: expect.any(Number), landedHelpers: expect.any(Number), recentDeliveries: expect.any(Number) }, + }); + expect(JSON.stringify(summary)).not.toContain('\\n'); + }); +}); + +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; + expect(schema.oneOf).toHaveLength(count); + expect(schema.oneOf.map((branch: Record) => branch.properties.operation.enum[0])).toEqual(schema.properties.operation.enum); + 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 c34bbadc..02adb534 100644 --- a/tests/agentTeamSolver.test.ts +++ b/tests/agentTeamSolver.test.ts @@ -248,9 +248,12 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP 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(); - expect(childStart.params.dynamicTools[0].inputSchema.properties.operation.enum) - .toEqual(expect.arrayContaining(['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history'])); - expect(childStart.params.dynamicTools[0].inputSchema.properties.operation.enum).toHaveLength(9); + const childToolSchema = childStart.params.dynamicTools[0].inputSchema; + const childOperations = ['progress', 'yield', 'history', 'message', 'poll', 'wait', 'inspect', 'inspect-research', + 'submit', 'submit_helpers', '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); @@ -268,9 +271,11 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP expect(childTrace.some(frame => frame.observation === 'worker-followup-context')).toBe(true); const leadTrace = trace(worktree), leadFrames = leadTrace.filter(frame => frame.direction === 'host'); - expect(leadFrames.find(frame => frame.method === 'thread/start')!.params.dynamicTools[0].inputSchema.properties.operation.enum) - .toEqual(expect.arrayContaining(['spawn', 'assign', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate'])); - expect(leadFrames.find(frame => frame.method === 'thread/start')!.params.dynamicTools[0].inputSchema.properties.operation.enum).toHaveLength(17); + const leadToolSchema = leadFrames.find(frame => frame.method === 'thread/start')!.params.dynamicTools[0].inputSchema; + expect(leadToolSchema.properties.operation.enum).toEqual(['spawn', 'assign', 'amend', 'finish', 'coordinate', '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', @@ -478,12 +483,11 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP const args = ['--workspace', receipt.workspaceRoot, '--task-file', taskFile, '--output', output, '--build-manifest', buildFile, '--harness', 'codex', '--harness-profile', profile, '--harness-executable', executable, - '--model', 'fixture-model', '--effort', 'high', '--research-mode', 'skill', - '--skill-delegation', 'team', '--skill-max-agents', '3', '--no-explanations', + '--model', 'fixture-model', '--effort', 'high', '--no-explanations', '--prepare-timeout-seconds', '30', '--max-run-seconds', '60', '--max-turns', '8', '--max-turn-seconds', '30', '--max-total-tokens', '1000', '--proof-timeout-seconds', '30', '--evaluator-timeout-seconds', '30']; - expect(await runSolver([...args, '--startup-only'], root)).toBe(0); + expect(await runSolver([...args, '--agent-team', '3', '--startup-only'], root)).toBe(0); const historicalFile = path.join(output + '.runtime', 'state.json'); const historical = readSolverRunState(historicalFile); expect(historical.agentTeam?.transport).toBe('native-agent-control'); @@ -491,7 +495,7 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP // saved runs retain it even when the current default uses AgentControl. delete historical.agentTeam!.transport; writeSolverRunState(historicalFile, historical); - const code = await runSolver([...args, '--resume'], root); + 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, diff --git a/tests/agentTeamSourceRecovery.test.ts b/tests/agentTeamSourceRecovery.test.ts index 87c9379b..58283799 100644 --- a/tests/agentTeamSourceRecovery.test.ts +++ b/tests/agentTeamSourceRecovery.test.ts @@ -12,6 +12,7 @@ import { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; import { directSolverModules } from '../src/solver/modules'; import { git, readSolverProblem } from '../src/solver/problem'; import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; +import type { SoftSliceSettings } from '../src/solver/softSlice'; import { deferred } from './helpers/async'; import { temporaryDirectory } from './helpers/files'; import { solverState } from './helpers/solver'; @@ -25,7 +26,7 @@ const helper = 'theorem helper : True := by trivial\n'; const declarations = [{ file: 'Submission.lean', name: 'Recovery.helper', type: 'True' }]; const fixtures: ReturnType[] = []; -function fixture(maxAgents = 2) { +function fixture(maxAgents = 2, softSlice?: SoftSliceSettings, stallInterrupt = false) { 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('.'); @@ -40,27 +41,30 @@ function fixture(maxAgents = 2) { 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(), teams: AgentResearchTeam[] = []; - const sessions: { options: MathAgentOptions; message: string; complete: () => void }[] = []; + const sessions: { options: MathAgentOptions; message: string; notices: string[]; complete: () => void }[] = []; const events: { event: string; details?: Record }[] = []; const stateFile = path.join(directory, 'run-state.json'); const makeTeam = (current: SolverRunState) => { const team = new AgentResearchTeam({ state: current, root, taskText: 'Prove True.', leadAccess: { environment, retrievalRoot: path.join(current.worktree, problem.projectRelative), researchSkill: skill }, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: async options => { - const outcome = deferred(), record = { options, message: '', complete: () => outcome.resolve('completed') }; + 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', usageSource: 'upstream-requests', run: async (message, _id, _workspace, started) => { record.message = message; started('source-recovery-turn-' + sessions.length); return outcome.promise; }, - notify: async () => {}, interrupt: async () => { outcome.resolve('interrupted'); }, - stopForFreeze: async () => ({ status: 'stopped' }), close: async () => {}, + 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'); }, }; return session; } } }, executable: 'offline-no-model', profile: 'offline-no-credentials', signal: controller.signal, maxAgents, maxTurns: Infinity, maxTurnMs: Infinity, maxTotalTokens: 0, remainingMs: () => Infinity, + softSlice, save: () => writeSolverRunState(stateFile, current), emit: (event, details) => { events.push({ event, details }); }, exclusiveCheck: operation => operation(), }); @@ -91,6 +95,99 @@ async function idle(team: AgentResearchTeam) { } describe('recoverable team source rejections', () => { + 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 session = await f.session(0), worker = f.team.archive.workers[0]!; + const activity = session.options.onActivity!; + activity({ event: 'item_started', itemType: 'contextCompaction' }); + activity({ event: 'item_completed', itemType: 'contextCompaction' }); + expect(session.notices).toEqual([]); + activity({ event: 'item_completed', itemType: 'contextCompaction' }); + expect(session.notices).toEqual([expect.stringContaining('submit_helpers')]); + expect(f.events).toContainEqual({ event: 'compaction_circuit_breaker_triggered', details: expect.objectContaining({ + workerId: worker.id, taskId: worker.tasks[0]!.id, completedCompactions: 2, + }) }); + const notes = path.join(worker.worktree, 'RESEARCH.md'); + fs.writeFileSync(notes, 'The remaining step is the original goal.\n'); + session.complete(); await idle(f.team); + expect(worker.tasks[0]).toMatchObject({ status: 'paused', researchArtifactId: expect.any(String), + pauseRequested: { kind: 'handoff', reason: 'math_soft_slice_milestone' } }); + expect(fs.readFileSync(notes, 'utf8')).toContain('remaining step'); + }); + + 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 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'] }); + try { + session.options.onActivity!({ event: 'item_completed', itemType: 'contextCompaction' }); + await vi.advanceTimersByTimeAsync(30_001); + expect(f.events).toContainEqual({ event: 'soft_slice_checkpoint_requested', + details: expect.objectContaining({ workerId: worker.id, boundary: 'wait-limit' }) }); + expect(worker.tasks[0]!.status).toBe('running'); + await vi.advanceTimersByTimeAsync(10_000); + expect(f.events).toContainEqual({ event: 'soft_slice_session_closed', + details: expect.objectContaining({ workerId: worker.id, reason: 'interrupt-not-settled' }) }); + } finally { vi.useRealTimers(); } + await idle(f.team); + expect(worker.tasks[0]).toMatchObject({ status: 'paused', researchArtifactId: expect.any(String), + pauseRequested: { kind: 'handoff', reason: 'math_soft_slice_checkpoint' } }); + expect(worker.writerStopUnconfirmed).toBeUndefined(); + }); + + 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 a = await f.session(0), producer = f.team.archive.workers[0]!; + await f.call({ operation: 'spawn', agentId: 'peer', message: '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'; + fs.writeFileSync(f.source(producer.worktree), original.replace('theorem goal', helperProofs + 'theorem goal')); + fs.writeFileSync(f.source(consumer.worktree), original.replace('end Recovery', draft + 'end Recovery')); + const names = [...declarations, { ...declarations[0]!, name: 'Recovery.second' }]; + expect(await f.call({ operation: 'submit_helpers', summary: 'Verified standalone facts.', declarations: names }, 'member')) + .toMatchObject({ ok: true, status: 'pending-writer-stop' }); + expect(f.team.archive.canonicalCommit).toBeUndefined(); + expect(a.options.requestGate!.checkpoint!()).toBe(true); + a.complete(); + await expect.poll(() => f.team.archive.canonicalCommit, { timeout: 20_000 }).toBeTruthy(); + const commit = f.team.archive.canonicalCommit!; + expect(readSolverRunState(f.stateFile).agentTeam!.landedHelpers?.map(item => item.qualifiedName)) + .toEqual(['Recovery.helper', 'Recovery.second']); + expect(git(f.state.worktree, ['show', commit + ':' + f.problem.projectRelative + '/Submission.lean'])) + .toBe(original.replace('theorem goal', helperProofs + 'theorem goal').trimEnd()); + expect(producer.tasks[0]).toMatchObject({ status: 'paused' }); + expect(producer.tasks[0]!.deliveryId).toBeUndefined(); + expect(f.state.check).toBeUndefined(); + expect(b.notices.some(message => message.includes('Recovery.second') && !message.includes(':= '))).toBe(true); + expect(consumer.tasks[0]!.status).toBe('running'); + expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).not.toContain('theorem second'); + b.complete(); await idle(f.team); + + await f.team.flushAdoptions(); + 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); + 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)) + .toEqual(['Recovery.helper', 'Recovery.second', 'Recovery.goal', 'Recovery.draft']); + expect(f.state.check).toBeUndefined(); + }, 60_000); + 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 first = await f.session(0), worker = f.team.archive.workers[0]!; diff --git a/tests/agentTeamTool.test.ts b/tests/agentTeamTool.test.ts index fff32a79..f9a4fef2 100644 --- a/tests/agentTeamTool.test.ts +++ b/tests/agentTeamTool.test.ts @@ -88,7 +88,7 @@ describe('operation-specific team tool contracts', () => { expect(unlimited.properties.operation.enum).not.toContain('budget'); expect(unlimited.properties).not.toHaveProperty('budget'); expect(unlimited.properties).not.toHaveProperty('leadReserve'); - for (const option of unlimited.oneOf) expect(option.properties).not.toHaveProperty('budget'); + expect(unlimited).not.toHaveProperty('oneOf'); const finite = agentTeamToolDefinition('lead', true); expect(finite.inputSchema).not.toHaveProperty('oneOf'); expect(finite.inputSchema.properties).toHaveProperty('budget'); diff --git a/tests/agentTeamTransportFallback.test.ts b/tests/agentTeamTransportFallback.test.ts new file mode 100644 index 00000000..6502e2aa --- /dev/null +++ b/tests/agentTeamTransportFallback.test.ts @@ -0,0 +1,105 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { readMathAgentSkill } from '../src/runtime/codexSkills'; +import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; +import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; +import { directSolverModules } from '../src/solver/modules'; +import { runResearchWorkers } from '../src/solver/research'; +import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; +import { leadWorker, localExample, solverState } from './helpers/solver'; + +vi.mock(import('../src/math/mathBuildManifest'), async original => + ({ ...await original(), readMathBuildManifest: vi.fn() })); + +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 }) { + const { problem, workspace, directory } = localExample('agent-team-transport-'); + roots.push(directory); + const root = path.resolve('.'); + const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); + const state = solverState(problem, workspace, { runId: 'agent-team-transport', phase: 'prepared', + researchMode: 'skill', researchSkillWorkflow: 'full', researchSkill: identity, + 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, + }); + const researchSkill = prepareResearchSkill(root, workspace, identity, problem); + const worker = leadWorker(problem, workspace), controller = new AbortController(); + const stateFile = path.join(directory, 'state.json'); + const emit = vi.fn(); + const start = vi.fn((options: MathAgentOptions) => open(options, controller)); + const check = vi.fn(async () => ({ + commit: problem.baseCommit, sourceDigest: 'incomplete', passed: false, + 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 }]]), + modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: start }, + M2: { ...directSolverModules.M2, check } }, root, buildFile: path.join(directory, 'build.json'), + taskText: 'Prove the frozen targets.', executable: 'offline', profile: 'offline', signal: controller.signal, + deadline: Infinity, maxTurns: (previous?.turns ?? 0) + 1, maxTurnMs: Infinity, maxTotalTokens: 0, + save: () => writeSolverRunState(stateFile, state), emit }); + return { run, state, stateFile, start, emit, controller }; +} + +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'; }); + 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' }, + }); + }); + 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 }], + ]); + }); + + it.each(['abort', 'auth', 'auth-wrapped', 'prior-turn', 'shutdown-unconfirmed'] as const)('preserves transport on %s', async mode => { + const error = mode === 'auth' ? new Error('math_codex_authentication_failed') : + mode === 'auth-wrapped' ? new Error('math_native_agent_control_backend_required', + { cause: new Error('math_codex_authentication_failed') }) : + mode === 'shutdown-unconfirmed' ? new Error('math_codex_startup_shutdown_unconfirmed') : new Error(startupError); + const f = fixture(async (_options, controller) => { + if (mode === 'abort') controller.abort(new Error('user cancelled')); + throw error; + }, mode === 'prior-turn' ? { turns: 1, threadId: 'previous-lead' } : undefined); + await expect(f.run()).rejects.toThrow(mode === 'abort' ? 'user cancelled' : error.message); + expect(f.start).toHaveBeenCalledOnce(); + expect(readSolverRunState(f.stateFile).agentTeam?.transport).toBe('native-agent-control'); + expect(f.emit.mock.calls.map(([event]) => event)).not.toContain('team_transport_fallback'); + }); +}); diff --git a/tests/agentTools.test.ts b/tests/agentTools.test.ts index c9debff5..241e32d5 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', - 'proof-search', 'research-observe', 'search-lean']; + 'plan-apply', 'plan-validate', 'proof-search', 'research-observe', 'search-lean']; const fixture = path.resolve('examples/finite/old-b1-nine-constraints.json'); let directory = ''; let tools = ''; diff --git a/tests/commonResearchGuidance.test.ts b/tests/commonResearchGuidance.test.ts index b2572ad6..b87df4aa 100644 --- a/tests/commonResearchGuidance.test.ts +++ b/tests/commonResearchGuidance.test.ts @@ -159,7 +159,9 @@ describe('common mathematical guidance across research strategies', () => { const context = buildResearchContext(f.problem, f.state, { ...f.access, assignment: { kind: 'task', task, assignment } }); expect(context.message).toContain(task.type); expect(context.message).toContain(taskVersion(task)); - expect(context.instructions).toContain(assignmentDeliveryFile(assignment)); + expect(context.message).toContain('Current delivery log: ' + assignmentDeliveryFile(assignment)); + expect(context.instructions).toContain('the current delivery log named in the assignment message'); + expect(context.instructions).toContain('"kind":"helpers"'); expect(context.instructions).toContain('preserve other original goals'); expect(context.instructions).toContain('"kind":"ready"'); expect(context.instructions).not.toContain('mathematicalInterfaceRules'); diff --git a/tests/contextCompiler.test.ts b/tests/contextCompiler.test.ts index 1be0d97e..6730f7ef 100644 --- a/tests/contextCompiler.test.ts +++ b/tests/contextCompiler.test.ts @@ -296,7 +296,7 @@ it('keeps a goal worker on its assigned proof when unrelated seed goals are unfi const state = { environmentDigest: 'environment', cooperation: { tasks: [node(task)] } } as SolverRunState; const context = buildResearchContext(problem, state, { root: '/runtime', worktree: '/proof', environment: {}, taskText: 'Prove the original target', retrievalRoot: '/library', assignment: assign(task), frozenContexts: input([]).frozenContexts }); - expect(context.instructions).toContain('This assignment proves only Original.target'); + expect(context.instructions).toContain('Prove only the original declaration named in the current assignment.'); expect(context.instructions).toContain('including existing sorry placeholders'); expect(context.instructions).toContain('do not prove or rewrite them to make the whole file pass'); expect(context.instructions).toContain('checks the full candidate after integration'); diff --git a/tests/definitionTasks.test.ts b/tests/definitionTasks.test.ts index ff3c2f87..ce68370b 100644 --- a/tests/definitionTasks.test.ts +++ b/tests/definitionTasks.test.ts @@ -94,11 +94,11 @@ describe('definition tasks', () => { maxOptionalContextBytes: 0, frozenContexts: { 'Submission.lean': 'theorem main : True := by sorry' } }; const worker = buildResearchContext(problem, state, { ...access, assignment: { kind: 'task', task: tasks[0], assignment: { taskId: tasks[0].id, taskDigest: taskVersion(tasks[0]), workerId: 'worker', seedCommit: 'fixed-commit' } } }); - expect(worker.instructions).toContain('This task defines Submission.coprimePair: save one def of exactly the requested type with a complete body'); - expect(worker.instructions).not.toContain('This is a lemma task for'); + expect(worker.instructions).toContain('Define the declaration named in the current assignment: save one def of exactly the requested type with a complete body'); + expect(worker.instructions).not.toContain('Prove the lemma named'); const lemma = buildResearchContext(problem, state, { ...access, assignment: { kind: 'task', task: tasks[1], assignment: { taskId: tasks[1].id, taskDigest: taskVersion(tasks[1]), workerId: 'worker', seedCommit: 'fixed-commit' } } }); - expect(lemma.instructions).toContain('This is a lemma task for Submission.coprimePair_symm.'); + expect(lemma.instructions).toContain('Prove the lemma named in the current assignment.'); const lead = buildResearchContext(problem, state, { ...access, assignment: { kind: 'lead', seedCommit: 'fixed-commit' } }); expect(lead.instructions).toContain('A new concept is a lemma task with declaration:"definition" and its Lean type'); expect(lead.instructions).toContain('Consumers wait for its checked body.'); diff --git a/tests/fixtures/agentTeamFollowupPeer.cjs b/tests/fixtures/agentTeamFollowupPeer.cjs index 4bf1ee22..e0d90f3f 100644 --- a/tests/fixtures/agentTeamFollowupPeer.cjs +++ b/tests/fixtures/agentTeamFollowupPeer.cjs @@ -48,8 +48,8 @@ function complete(stage, text, status = 'completed') { 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', 'coordinate'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress']; + const expected = lead ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate', 'retire_route', 'route_summary'] + : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'submit_helpers', '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'); diff --git a/tests/fixtures/agentTeamHandoffPeer.cjs b/tests/fixtures/agentTeamHandoffPeer.cjs index b4b5d603..f7960c0b 100644 --- a/tests/fixtures/agentTeamHandoffPeer.cjs +++ b/tests/fixtures/agentTeamHandoffPeer.cjs @@ -47,8 +47,8 @@ function complete(stage, text, status = 'completed') { 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', 'coordinate'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress']; + ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate', 'retire_route', 'route_summary'] + : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'submit_helpers', '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') { diff --git a/tests/fixtures/agentTeamPeer.cjs b/tests/fixtures/agentTeamPeer.cjs index c2846700..c9db691c 100644 --- a/tests/fixtures/agentTeamPeer.cjs +++ b/tests/fixtures/agentTeamPeer.cjs @@ -158,8 +158,8 @@ stream.on('line', line => { 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', 'coordinate'] - : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'yield', 'history', 'progress']; + ? ['spawn', 'assign', 'amend', 'finish', 'message', 'poll', 'wait', 'inspect', 'inspect-research', 'adopt', 'stop', 'publish', 'cancel', 'budget', 'resume', 'history', 'coordinate', 'retire_route', 'route_summary'] + : ['message', 'poll', 'wait', 'inspect', 'inspect-research', 'submit', 'submit_helpers', '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'); diff --git a/tests/fixtures/web-cooperative-codex.mjs b/tests/fixtures/web-cooperative-codex.mjs index 14e92a55..2cc2a009 100644 --- a/tests/fixtures/web-cooperative-codex.mjs +++ b/tests/fixtures/web-cooperative-codex.mjs @@ -30,7 +30,7 @@ export function createCooperativeFixture({ workspace, source, message, instructi fs.writeFileSync(source, original.replace(before, after)); notes({ summary: `Offline exact proof for ${taskId}.`, fixture: { task: contract.input, guidanceReceived: receivedGuidance ?? null, editedPlanObserved: edited(), independentModelCall: false } }); - const file = instructions.match(/append JSON to (DELIVERIES-[a-f0-9]{64}\.jsonl)/u)?.[1]; + const file = message.match(/Current delivery log: (DELIVERIES-[a-f0-9]{64}\.jsonl)/u)?.[1]; if (!file) throw new Error('web_fixture_missing_proof_delivery_protocol'); fs.appendFileSync(path.join(workspace, file), JSON.stringify({ kind: 'ready', summary: `Saved ${taskId} for independent host checking.` }) + '\n'); complete(); diff --git a/tests/frontierPriorityContext.test.ts b/tests/frontierPriorityContext.test.ts index 10456b5b..34d20114 100644 --- a/tests/frontierPriorityContext.test.ts +++ b/tests/frontierPriorityContext.test.ts @@ -58,7 +58,8 @@ it.each(['lemma', 'goal', 'research', 'sketch'] as const)( expect(context.manifest).toMatchObject({ maxOptionalBytes: 0, optionalBytes: 0 }); expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'assignment-policy', required: true })); - expect(context.instructions).toContain(assignmentDeliveryFile(action.assignment)); + expect(context.message).toContain('Current delivery log: ' + assignmentDeliveryFile(action.assignment)); + expect(context.instructions).toContain('"kind":"helpers","declarations":'); expect(context.instructions).toContain('"kind":"research","finding":'); expect(context.instructions).toContain('publishing does not finish or park your proof task'); expect(context.instructions).toContain('The host freezes the saved sources and independently checks and integrates them'); diff --git a/tests/helpers/solverAtomicPlanRejection.ts b/tests/helpers/solverAtomicPlanRejection.ts new file mode 100644 index 00000000..fea1ee33 --- /dev/null +++ b/tests/helpers/solverAtomicPlanRejection.ts @@ -0,0 +1,91 @@ +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('theorem-os plan-validate'); + 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 new file mode 100644 index 00000000..5026b7a2 --- /dev/null +++ b/tests/helpers/solverTeamRouteRetirement.ts @@ -0,0 +1,176 @@ +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/installedLibraryContext.test.ts b/tests/installedLibraryContext.test.ts index 4111a730..79ceb5cf 100644 --- a/tests/installedLibraryContext.test.ts +++ b/tests/installedLibraryContext.test.ts @@ -447,7 +447,7 @@ describe('installed library retrieval in actual task context', () => { expect(context.instructions).toContain('respect the frozen assumptions'); expect(context.instructions).toContain('intended consumer and exact remaining inference'); for (const writableAdvice of ['library request --worktree', 'adapt only needed declarations', - 'You may add explicit Mathlib.* imports', 'Add helpers in owned modules', 'check-lean --workspace', + '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)!)}.`); @@ -479,7 +479,7 @@ describe('installed library retrieval in actual task context', () => { expect(context.instructions).toContain('do not import, request or copy modules during review'); expect(context.instructions).not.toContain('library request --worktree'); expect(context.instructions).not.toContain('adapt only needed declarations'); - expect(context.instructions).not.toContain('You may add explicit Mathlib.* imports'); + expect(context.instructions).not.toContain('you may add import Mathlib or any pinned Mathlib.* import'); expect(context.instructions).not.toContain('Add helpers in owned modules'); expect(context.instructions.split('\n').find(line => line.startsWith('Edit only '))) .toBe(`Edit only ${path.join(f.receipt.workspaceRoot, 'RESEARCH.md')}.`); diff --git a/tests/leadPlanRejectionFeedback.test.ts b/tests/leadPlanRejectionFeedback.test.ts index 020cc32c..c01810ea 100644 --- a/tests/leadPlanRejectionFeedback.test.ts +++ b/tests/leadPlanRejectionFeedback.test.ts @@ -121,7 +121,8 @@ it('updates only the Lead inbox on plan rejection and clears it when a repaired try { await deliver({ tasks: [] }); expect(state.cooperation!.error).toBe('math_plan_invalid'); - expect(state.cooperation!.planRejection).toBeDefined(); + 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'); diff --git a/tests/solver.test.ts b/tests/solver.test.ts index cb79e234..e0270901 100644 --- a/tests/solver.test.ts +++ b/tests/solver.test.ts @@ -266,6 +266,38 @@ 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); @@ -1379,24 +1411,31 @@ describe('isolated solver and host acceptance', () => { expect(host.verify).not.toHaveBeenCalled(); }); - it('allows explicit Mathlib imports while preserving original imports and trusted inputs', () => { + it('allows root and explicit Mathlib imports while preserving original imports, declarations and trusted inputs', () => { const file = path.join(project, 'Submission.lean'); - const baseline = 'import Mathlib.Data.Nat.Basic\n' + original; + const imports = ['Mathlib.MeasureTheory.Integral.Bochner.Basic', 'Mathlib.MeasureTheory.Measure.Lebesgue.Basic', + 'Mathlib.Analysis.SpecialFunctions.Log.Basic']; + const baseline = imports.map(module => `import ${module}\n`).join('') + original; fs.writeFileSync(file, baseline); commitSolverSources(problem, workspace); problem = readSolverProblem(workspace, problem.activeProblemPath); - expect(problem.sourceImports?.['Submission.lean']).toEqual(['Mathlib.Data.Nat.Basic']); - const candidate = 'import Mathlib.Analysis.SpecialFunctions.Trigonometric.InverseDeriv\n' + baseline; + expect(problem.sourceImports?.['Submission.lean']).toEqual(imports); + const candidate = 'import Mathlib\nimport Mathlib.Analysis.Calculus.Deriv.Basic\n' + baseline; fs.writeFileSync(file, candidate); + expect(() => assertSolverProjectSources(problem, project)).not.toThrow(); expect(() => assertSolverSources(problem, workspace)).not.toThrow(); const { sourceImports: _imports, ...legacy } = problem; expect(() => assertSolverProjectSources(legacy, project)).toThrow('math_original_context_changed'); - for (const source of [original, candidate.replace('import Mathlib.Data.Nat.Basic\n', ''), - ...['import Other', 'import Solution', 'import Mathlib', 'import Mathlib.Data.Real.Basic variable (h : False)'] + for (const source of [original, candidate.replace(`import ${imports[0]}\n`, ''), + ...['import Other', 'import Solution', 'import MathlibExtra', 'import Mathlib.Data.Real.Basic variable (h : False)'] .map(command => command + '\n' + baseline)]) { fs.writeFileSync(file, source); expect(() => assertSolverProjectSources(problem, project)).toThrow('math_original_context_changed'); } + for (const source of [candidate.replace('first : True', 'first : False'), candidate.replace('fixed : Nat := 2', 'fixed : Nat := 3')]) { + fs.writeFileSync(file, source); + expect(() => assertSolverProjectSources(problem, project)).toThrow('math_original_declaration_changed'); + } fs.writeFileSync(file, candidate); fs.writeFileSync(path.join(project, 'Challenge.lean'), 'import Mathlib.Data.Nat.Basic\n' + original); expect(() => assertSolverSources(problem, workspace)).toThrow('math_trusted_source_changed'); diff --git a/tests/solverAdvisoryPriority.test.ts b/tests/solverAdvisoryPriority.test.ts index a70cfc1f..a292e90a 100644 --- a/tests/solverAdvisoryPriority.test.ts +++ b/tests/solverAdvisoryPriority.test.ts @@ -146,6 +146,25 @@ describe('advisory turns yielding to executable proof work', () => { 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)); @@ -268,7 +287,7 @@ describe('advisory turns yielding to executable proof work', () => { 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, save: () => {}, + goalProgressReviewMs: 24 * 3_600_000, minAdvisorySliceMs: 5_000, save: () => {}, emit: event => { if (event === 'feasibility_review_checkpoint_saved') saved.resolve(); }, }); try { diff --git a/tests/solverAtomicPlanApply.test.ts b/tests/solverAtomicPlanApply.test.ts new file mode 100644 index 00000000..1a05cdaf --- /dev/null +++ b/tests/solverAtomicPlanApply.test.ts @@ -0,0 +1,123 @@ +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'; + +const roots: string[] = []; +const notes = '## Current argument\nKeep this explanation.\n\n```json\n{"example":42}\n```\n'; +const malformed = '```math-plan\n{ malformed }\n```\n'; + +afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); + +function fixture() { + const example = localExample('atomic-plan-apply-'); + roots.push(example.directory); + const { workspace, problem } = example; + const plan = { tasks: problem.targets.map(({ proofPath, theoremName }, index) => ({ + id: `goal_${index}`, kind: 'goal', objective: `Prove ${theoremName}.`, proofPath, theoremName, + })) }; + const file = path.join(workspace, 'RESEARCH.md'); + fs.writeFileSync(file, notes + '\n' + malformed); + return { example, workspace, problem, plan, file }; +} + +describe('atomic cooperative plan commands', () => { + 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' }] }; + const invalidRetirement = { ...plan, retireRoutes: [{ routeId: 'dead', reason: '', evidenceRefs: [0] }] }; + expect(validateCooperationPlan(invalidTask, { problem })).toMatchObject({ ok: false, error: 'math_plan_invalid_task', + issues: [{ path: 'tasks[goal_0].status', message: expect.stringContaining('Host scheduling and proof-acceptance') }] }); + + const cases = [ + { text: '{"tasks": [}', error: 'math_plan_json_invalid', fields: ['$'] }, + { text: JSON.stringify(invalidTask), error: 'math_plan_invalid_task', fields: ['tasks[goal_0].status'] }, + { text: JSON.stringify(invalidRetirement), error: 'math_plan_invalid_retire_routes', + fields: ['retireRoutes[0].reason', 'retireRoutes[0].evidenceRefs[0]'] }, + ]; + const candidate = path.join(workspace, 'candidate.json'); + for (const item of cases) { + fs.writeFileSync(candidate, item.text); + const input = { workspace, file: candidate }; + 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); + 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(); } + }); +}); diff --git a/tests/solverContext.test.ts b/tests/solverContext.test.ts index 2c296f27..8d2450f6 100644 --- a/tests/solverContext.test.ts +++ b/tests/solverContext.test.ts @@ -2,6 +2,7 @@ import { expect, it } from 'vitest'; import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; import type { SolverProblem } from '../src/solver/problem'; import type { SolverRunState } from '../src/solver/archive'; +import { mathDigest } from '../src/math/mathRuntimeIo'; import type { DeliveryReceipt } from '../src/solver/deliveryReceipts'; import { deliveryDetails, parseMathResponse, type DeliveryRecord } from '../src/solver/deliveries'; import { assignmentDeliveryFile, leadPlanDeliveryFile, taskVersion, type CooperativeAction, type CooperativeTask } from '../src/solver/tasks'; @@ -50,6 +51,58 @@ it('deduplicates repeated findings and progress while preserving exact Lean type expect(JSON.parse(graph)[0].type).toBe(exactType); }); +it('indexes an 80-task and 100-delivery archive while retaining current planning inputs', () => { + const exactType = '∀ n : Nat, n = n'; + const formalStatement = 'theorem target : True := by sorry\n' + '-- Frozen background.\n'.repeat(800); + const problem = { projectRelative: 'problem', ownedFiles: ['Submission.lean'], targets: [], + declarations: { 'Submission.lean': [{ name: 'target', header: 'theorem target : True' }] }, + baseCommit: 'fixed-commit', receiptDigest: 'problem', trustedFiles: { 'Challenge.lean': mathDigest(formalStatement) }, + contract: { formalStatement, assumptions: [] } } as unknown as SolverProblem; + const goal: CooperativeTask = { id: 'goal', kind: 'goal', objective: 'Prove the target', dependsOn: ['open-certificate'], + revision: 0, theoremName: 'target', proofPath: 'Submission.lean', type: 'True' }; + const helper: CooperativeTask = { id: 'open-certificate', kind: 'lemma', objective: 'Build the certificate', + dependsOn: [], revision: 0, theoremName: 'certificate', proofPath: 'Submission.lean', type: exactType }; + const archived = Array.from({ length: 78 }, (_, i): CooperativeTask => ({ id: 'search-' + i, kind: 'research', + objective: 'Archive body ' + 'Old mathematical route rationale. '.repeat(70), dependsOn: [], revision: 0 })); + const deliveries: DeliveryRecord[] = Array.from({ length: 100 }, (_, i) => { + const task = archived[i % archived.length]; + return { id: 'delivery-' + i, kind: 'progress', status: 'advisory', taskId: task.id, taskDigest: taskVersion(task), + summary: 'Past progress ' + i + '\n' + 'Long old delivery argument. '.repeat(70), + producer: 'peer', statement: '', premises: [], dependencies: [], remainingObligations: [], evidenceRefs: [], + createdAt: i, commit: 'saved-notes-commit' }; + }); + const action: CooperativeAction = { kind: 'lead', seedCommit: 'fixed-commit', planVersion: 'current-plan', + planNonce: 'receipt', planningInputDigest: 'decision' }; + const state = { cooperation: { tasks: [goal, helper, ...archived].map((task, i) => ({ + task, status: i < 2 ? 'pending' : 'completed', attempts: 1, + ...(i >= 2 ? { finding: 'Historical reasoning '.repeat(140) } : {}), + })), deliveries } } as unknown as SolverRunState; + const context = buildResearchContext(problem, state, { root: '/runtime', worktree: '/proof', environment: {}, + taskText: 'Prove the target', retrievalRoot: '/library', frozenContexts: { 'Submission.lean': formalStatement }, + assignment: action }); + expect(Buffer.byteLength(context.message)).toBeLessThan(32 * 1024); + expect(context.message).toContain(exactType); + expect(context.message).toContain('theorem target : True'); + expect(context.message).toContain('current-plan'); + expect(context.manifest!.included).toContainEqual(expect.objectContaining({ id: 'task-record-index', required: true })); + expect(context.message).toContain('saved-notes-commit'); + expect(context.message).not.toContain('Long old delivery argument. '.repeat(20)); +}); + +it('compiles a same-route task switch from exact interfaces and the new delivery path', () => { + const first = gapContext('lemma', 'Large frozen problem. '.repeat(350)); + const second = gapContext('lemma', 'Large frozen problem. '.repeat(350), 'Prove a distinct estimate.'); + const switched = finalizeResearchDispatch(second, { taskSwitch: true }); + const assignment = second.assignment as Extract; + expect(first.instructions).toBe(switched.instructions); + expect(switched.message).toContain('Switch to the assignment below'); + expect(switched.message).toContain(JSON.stringify(assignment)); + expect(switched.message).toContain(assignmentDeliveryFile(assignment.assignment)); + expect(switched.message).toContain(JSON.stringify(second.workContract)); + expect(switched.message).not.toContain('Large frozen problem.'); + expect(switched.message.length).toBeLessThan(second.message.length / 2); +}); + it('names the bundled Agent commands instead of the application when the shell cannot read it', () => { const problem = { projectRelative: '.', ownedFiles: ['Submission.lean'], declarations: {}, targets: [], receiptDigest: 'problem', baseCommit: 'fixed-commit', contract: { formalStatement: 'theorem target : True := by sorry', assumptions: [] } } as unknown as SolverProblem; @@ -79,6 +132,8 @@ it.each(['cooperative', 'independent'] as const)('gives a single solver a comple customModuleRules: [{ id: 'team-rule', name: 'Team rule', slot: 'M5', mode: 'append', enabled: true, instructions: 'TEAM_ONLY_SENTINEL' }] }); const instructions = context.instructions; + expect(instructions).toContain('Keep all existing imports'); + expect(instructions).toContain('you may add import Mathlib or any pinned Mathlib.* import'); expect(instructions).toContain('save all proof files and a concise worktree-root RESEARCH.md before the final diagnostic'); expect(instructions).toContain("check-lean --worktree '/proof' --file 'Submission.lean' --file 'Other.lean' --timeout-seconds 0"); expect(instructions).not.toContain("--file 'Submission.lean' --file 'Submission.lean'"); @@ -145,10 +200,10 @@ it.each([false, true])('keeps the Lead on read-only planning and prompt delivery expect(dispatched.instructions).toContain('put a direct original-goal task in the graph; the assigned worker carries out its proof'); expect(dispatched.instructions).toContain('Return the plan without running Lean diagnostics'); expect(dispatched.instructions).toContain('Leave all Lean source files, imports and environment configuration unchanged'); - expect(dispatched.instructions).toContain('names, parameters, types, assumptions, existing imports'); + expect(dispatched.instructions).toContain('Keep all existing imports'); expect(dispatched.instructions).toContain('Plan a shared helper before its consumers when needed; assigned workers implement it'); expect(dispatched.instructions).toContain('only a further substantive change requires another final plan response'); - for (const writableAdvice of ['bodies must be filled', 'You may add explicit Mathlib.* imports', 'Add helpers in owned modules', + for (const writableAdvice of ['bodies must be filled', 'you may add import Mathlib or any pinned Mathlib.* import', 'Add helpers in owned modules', 'For diagnostics, run', 'check-lean --workspace', 'proof-search --workspace', 'Repair the earliest error', 'restore the offending context', 'For type lookup, add single-name #check']) expect(dispatched.instructions).not.toContain(writableAdvice); @@ -281,8 +336,9 @@ it.each(['lemma', 'goal'] as const)('keeps Lead planning requests out of a dispa expect(dispatched.instructions).toContain('plan approval belong to the Lead and host'); expect(dispatched.instructions).toContain('before dispatching typed proof work'); expect(dispatched.instructions).toContain('do not start another planning or approval cycle'); - expect(dispatched.instructions).toContain(`append JSON to ${deliveryFile}`); - expect(dispatched.instructions).toContain('create it by appending if absent'); + expect(dispatched.instructions).toContain('append JSON to the current delivery log'); + expect(dispatched.message).toContain(`Current delivery log: ${deliveryFile}`); + expect(dispatched.instructions).toContain('Create it by appending if absent'); expect(dispatched.message).toContain(JSON.stringify(context.assignment)); expect(dispatched.workContract).toEqual(context.workContract); expect(dispatched.manifest!.usedBytes).toBeLessThanOrEqual(dispatched.manifest!.maxBytes); @@ -351,7 +407,8 @@ it('asks researchers to save scoped negative evidence and publish a schema-valid expect(deliveryDetails(finding)).toMatchObject({ evidenceRefs: [], remainingObligations: ['precise unresolved mathematical inference'] }); expect(context.instructions).toContain('publishing does not finish or park your proof task'); - expect(context.instructions).toContain('leave Lean sources unchanged'); + expect(context.instructions).toContain('Restore Lean sources to the assignment seed before ordinary findings delivery.'); + expect(context.instructions).toContain('after the host acknowledges the submission'); expect(context.instructions).toContain('visible kind:"goal" original consumer'); expect(context.instructions).toContain('ordinary research delivery IDs are not prior gap references'); expect(context.instructions).toContain('omit only previousDeliveryId and keep the required previousGap description'); @@ -397,7 +454,7 @@ it('keeps fixed-candidate review read-only and ends delivery after the evidence expect(dispatched.instructions).not.toContain('Add helpers in owned modules'); expect(dispatched.instructions).not.toContain('def declarations whose bodies must be filled'); expect(dispatched.instructions).not.toContain('Extract their shared argument into a newly named lemma'); - expect(dispatched.instructions).not.toContain('You may add explicit Mathlib.* imports'); + expect(dispatched.instructions).not.toContain('you may add import Mathlib or any pinned Mathlib.* import'); expect(dispatched.instructions).not.toContain('restore the offending context or declaration'); expect(dispatched.instructions).not.toContain('Before any checkpoint, recovery decision or context rotation'); expect(dispatched.instructions).toContain('it is not the file SHA256 or the host owned-source digest'); diff --git a/tests/solverCooperativeCheckpoints.test.ts b/tests/solverCooperativeCheckpoints.test.ts index dd8cc9e4..2b00cda5 100644 --- a/tests/solverCooperativeCheckpoints.test.ts +++ b/tests/solverCooperativeCheckpoints.test.ts @@ -100,7 +100,9 @@ describe('cooperative advisory scheduling checkpoints', () => { }; } }, }); - const run = (open: (options: MathAgentOptions) => Promise, maxTurns = 2) => { + 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.', @@ -108,7 +110,8 @@ describe('cooperative advisory scheduling checkpoints', () => { 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, - save: () => {}, emit: (event, details) => events.push({ event, details }), + softSlice, + save: () => {}, emit: (event, details) => { events.push({ event, details }); onEvent?.(event, details); }, }); running.push(completion); return completion; }; @@ -452,21 +455,35 @@ describe('cooperative advisory scheduling checkpoints', () => { expect(vi.getTimerCount()).toBe(0); }); - it.each(['ready', 'compacting', 'claimed-elsewhere'] as const)( + it.each(['ready', 'compacting', 'claimed-elsewhere', 'target-lost-at-boundary', 'dispatch-mismatch'] as const)( 'only checkpoints at the request boundary with a saved draft and the same proof (%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 completion = run(open, Infinity); void completion.catch(() => {}); + 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(); + } + }); + 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!(); - const goal = state.cooperation!.tasks.find(node => node.task.id === 'goal_1')!; 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); @@ -485,8 +502,7 @@ describe('cooperative advisory scheduling checkpoints', () => { if (outcome === 'claimed-elsewhere') { // The existing handoff is stale by the time the model asks for another request. - goal.task = { ...goal.task, ownerId: 'a-different-worker' }; - wake(); + 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. @@ -497,11 +513,20 @@ describe('cooperative advisory scheduling checkpoints', () => { 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); - expect(held.actions[1].task.id).toBe('goal_1'); - expect(events).toContainEqual({ event: 'advisory_yielded_for_typed_work', - details: expect.objectContaining({ workerId: 'researcher', successorTaskId: 'goal_1', reason: 'typed-work-ready' }) }); + 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); } const audit = state.cooperation!.tasks.find(node => node.task.id === 'investigate')!; const draft = state.cooperation!.researchDrafts!.investigate; @@ -912,7 +937,7 @@ describe('cooperative advisory scheduling checkpoints', () => { controller.abort(new Error('fixture_complete')); await expect(completion).rejects.toThrow('fixture_complete'); }); - it.each(['unchanged', 'compaction', 'environment', 'instructions', 'dependency'] as const)( + 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')!; @@ -921,6 +946,28 @@ describe('cooperative advisory scheduling checkpoints', () => { 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); @@ -935,11 +982,19 @@ describe('cooperative advisory scheduling checkpoints', () => { 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']); - expect(held.threads).toEqual(Array(3).fill('continuation-thread-1')); - expect(held.messages.map(message => message.mode)).toEqual(['full', 'full', change === 'unchanged' ? 'short' : 'full']); + 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').at(-1)?.details?.mode) - .toBe(change === 'unchanged' ? 'continuation' : 'full'); + 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); }); @@ -1000,7 +1055,7 @@ describe('cooperative advisory scheduling checkpoints', () => { 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 === 'task' ? 'continuation-thread-2' : 'continuation-thread-1']); + 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; @@ -1467,7 +1522,7 @@ describe('cooperative advisory scheduling checkpoints', () => { expect(vi.getTimerCount()).toBe(0); }); - it('yields an unfinished Lead plan to original-goal work and leaves the proof writer unlimited', async () => { + 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(); @@ -1488,7 +1543,7 @@ describe('cooperative advisory scheduling checkpoints', () => { return done.promise; } }; }); - const completion = run(open); void completion.catch(() => {}); + 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); @@ -1735,7 +1790,7 @@ describe('cooperative advisory scheduling checkpoints', () => { onStarted(`proof-context-turn-${turn}`); started[turn].resolve(); return done[turn].promise; } }; }); - const completion = run(open, Infinity); void completion.catch(() => {}); + 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); diff --git a/tests/solverIncrementalHelperLanding.test.ts b/tests/solverIncrementalHelperLanding.test.ts new file mode 100644 index 00000000..96f6f46d --- /dev/null +++ b/tests/solverIncrementalHelperLanding.test.ts @@ -0,0 +1,152 @@ +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/solverPortfolioGate.test.ts b/tests/solverPortfolioGate.test.ts new file mode 100644 index 00000000..4b75bdb3 --- /dev/null +++ b/tests/solverPortfolioGate.test.ts @@ -0,0 +1,165 @@ +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/agentSession'; +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 { localExample, solverState } from './helpers/solver'; + +const roots: string[] = []; +afterEach(() => { 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 fixture(durationMs = 1000, capacity = 3) { + const { directory, workspace, problem } = localExample('portfolio-gate-'); + 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 input = { state, taskText: 'Prove the original statement.', executable: 'offline', profile: 'offline', 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); + 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('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/solverRouteRetirement.test.ts b/tests/solverRouteRetirement.test.ts new file mode 100644 index 00000000..cafe4314 --- /dev/null +++ b/tests/solverRouteRetirement.test.ts @@ -0,0 +1,204 @@ +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 { deferred } from './helpers/async'; +import { workerAccess, workerDeliveryModules } from './helpers/cooperation'; +import { leadWorker, localExample, peerWorker, solverState } from './helpers/solver'; +import './helpers/solverTeamRouteRetirement'; + +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())); + } +} + +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 }; +} + +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(); } + }); + + 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(); } + }); + + 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(); } + }); +}); + +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 })], + ]); + } finally { + controller.abort(new Error('fixture_complete')); + await expect(completion).rejects.toThrow('fixture_complete'); + } +}); diff --git a/tests/solverSoftSliceCompaction.test.ts b/tests/solverSoftSliceCompaction.test.ts new file mode 100644 index 00000000..2dd7fd82 --- /dev/null +++ b/tests/solverSoftSliceCompaction.test.ts @@ -0,0 +1,111 @@ +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/agentSession'; +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 { MAX_COMPACTIONS_PER_SLICE, SOFT_SLICE_MS, softSliceSettings } from '../src/solver/softSlice'; +import { deferred } from './helpers/async'; +import { leadWorker, localExample, solverState } from './helpers/solver'; + +vi.mock(import('../src/math/mathBuildManifest'), async importOriginal => + ({ ...await importOriginal(), readMathBuildManifest: vi.fn() })); + +describe('soft research milestones', () => { + afterEach(() => vi.useRealTimers()); + + it.each(['time', 'compaction', 'fallback', 'natural-return', 'independent'] as const)('yields an unlimited research turn after %s', async trigger => { + vi.useFakeTimers(); + const { directory, workspace, problem } = localExample('soft-slice-'); + const controller = new AbortController(); + const started = deferred(), done = deferred(); + const notify = vi.fn(async () => {}); + 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 }); + fs.cpSync(path.resolve('skills/theoremos-research'), skillRoot, { recursive: true }); + return readMathAgentSkill(path.join(skillRoot, 'SKILL.md')); + })(); + const state = solverState(problem, workspace, { runId: 'soft-slice-fixture', phase: 'prepared', + ...(skill ? { researchMode: 'skill', researchSkill: { name: skill.name, digest: skill.digest, loading: skill.loading } } : {}) }); + const modules: typeof directSolverModules = { ...directSolverModules, + M2: { ...directSolverModules.M2, check: async () => { + const commit = commitSolverSources(problem, workspace); + return { commit, sourceDigest: 'unproved-fixture', passed: false, + verification: { schema: 'deepscientist.mathematics.verification-batch/v1', status: 'failed', targetCommit: commit, + sessionId: 'offline-check', results: [], events: [], startedAt: 0, checkedAt: 0, durationMs: 0 } }; + } }, + 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) => { + begin('held-turn'); + started.resolve(options); + return done.promise; + }, + }) }, + }; + const completion = runResearchWorkers({ state, workers: [worker], modules, + access: new Map([[worker.id, { 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, + softSlice: { softSliceMs: trigger === 'compaction' ? 0 : 1_000, softSliceGraceMs: 100 }, + save: () => {}, emit: (event, details) => { events.push({ event, details }); }, + }); + try { + const options = await Promise.race([started.promise, completion.then(() => { throw new Error('fixture did not dispatch'); })]); + const event = trigger === 'compaction' ? 'compaction_circuit_breaker_triggered' : 'soft_slice_milestone_requested'; + if (trigger === 'compaction') { + options.onActivity?.({ event: 'item_started', itemType: 'contextCompaction' }); + options.onActivity?.({ event: 'item_completed', itemType: 'contextCompaction' }); + expect(notify).not.toHaveBeenCalled(); + options.onActivity?.({ event: 'item_started', itemType: 'contextCompaction' }); + options.onActivity?.({ event: 'item_completed', itemType: 'contextCompaction' }); + } else { + await vi.advanceTimersByTimeAsync(999); + expect(notify).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + } + expect(events).toContainEqual({ event, details: expect.objectContaining({ turnId: 'held-turn', + completedCompactions: trigger === 'compaction' ? 2 : 0 }) }); + expect(notify.mock.calls).toEqual([[expect.stringMatching(/standalone helpers.*fewer than 20 lines.*RESEARCH\.md/u), { mode: 'advisory' }]]); + expect(options.requestGate?.checkpoint?.()).toBe(false); + expect(interrupt).not.toHaveBeenCalled(); + fs.writeFileSync(path.join(workspace, 'RESEARCH.md'), 'Established the first reduction. The induction step remains open.\n'); + await vi.advanceTimersByTimeAsync(100); + if (trigger === 'natural-return') { + done.resolve('completed'); + } else if (trigger === 'fallback') { + await vi.advanceTimersByTimeAsync(30_000); + expect(interrupt).toHaveBeenCalledOnce(); + } else { + expect(options.requestGate?.checkpoint?.()).toBe(true); + expect(options.requestGate?.checkpoint?.()).toBe(false); + expect(interrupt).not.toHaveBeenCalled(); + done.resolve('checkpoint'); + } + await completion; + expect(events).toContainEqual({ event: 'turn_checkpoint', details: expect.objectContaining({ reason: 'math_soft_slice_checkpoint' }) }); + expect(events.some(entry => entry.event === (skill ? 'research_saved' : 'proof_checked'))).toBe(true); + expect(fs.readFileSync(path.join(workspace, 'RESEARCH.md'), 'utf8')).toContain('The induction step remains open.'); + } finally { + controller.abort(); + done.resolve('interrupted'); + await completion.catch(() => {}); + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + + it('requires an explicit zero to disable either trigger', () => { + expect(softSliceSettings({}, {})).toMatchObject({ timeMs: SOFT_SLICE_MS, compactions: MAX_COMPACTIONS_PER_SLICE }); + expect(softSliceSettings({ maxCompactionsPerSlice: 0 }, { THEOREMOS_SOFT_SLICE_MS: '0' })) + .toMatchObject({ timeMs: 0, compactions: 0 }); + }); +}); diff --git a/tests/webAgentActions.test.ts b/tests/webAgentActions.test.ts index a6ac42f3..c7cb2cd8 100644 --- a/tests/webAgentActions.test.ts +++ b/tests/webAgentActions.test.ts @@ -423,17 +423,20 @@ describe('Agent actions as the run owner sees them', () => { expect(sent).toHaveLength(1); expect(sent[0]).toMatchObject({ workerId: 'engineer', itemId: '1:r', phase: 'started', status: 'running', kind: 'reasoning', textSource: 'summary', text: 'Inspect ./Submission.lean with key [REDACTED]' }); - for (let index = 0; index < 100; index++) update(`Public revision ${index}`); + for (let index = 0; index < 100; index++) update(`${'推理'.repeat(1_500)} Public revision ${index}`); expect(sent).toHaveLength(1); - await vi.advanceTimersByTimeAsync(999); expect(sent).toHaveLength(1); + await vi.advanceTimersByTimeAsync(3_999); expect(sent).toHaveLength(1); await vi.advanceTimersByTimeAsync(1); expect(sent).toHaveLength(2); - expect(sent.at(-1)!.text).toBe('Public revision 99'); + expect(sent.at(-1)!.text).toMatch(/^…[推理]+ Public revision 99$/u); + expect(sent.at(-1)!.textClipped).toBe(true); + expect(Buffer.byteLength(sent.at(-1)!.text!)).toBeLessThanOrEqual(2_048); update('A pending old snapshot'); - observer.onItem!('completed', { id: 'r', type: 'reasoning', summary: ['Authoritative final summary'], content: ['raw final'] }); + const final = 'Authoritative final summary. ' + '推理'.repeat(1_500); + observer.onItem!('completed', { id: 'r', type: 'reasoning', summary: [final], content: ['raw final'] }); update('A late snapshot'); - await vi.advanceTimersByTimeAsync(1_000); + await vi.advanceTimersByTimeAsync(4_000); expect(sent).toHaveLength(3); - expect(sent.at(-1)).toMatchObject({ itemId: '1:r', phase: 'completed', status: 'done', text: 'Authoritative final summary', textSource: 'summary' }); + expect(sent.at(-1)).toMatchObject({ itemId: '1:r', phase: 'completed', status: 'done', text: final, textSource: 'summary' }); expect(sent.every(isWebAgentActionBody)).toBe(true); expect(JSON.stringify(sent)).not.toMatch(/raw|sk-agent-actions|\/opt\/|\/work\//); } finally { await session?.close(); vi.useRealTimers(); } @@ -458,7 +461,7 @@ describe('Agent actions as the run owner sees them', () => { observer.onItemUpdate!({ id: 'cancelled', type: 'reasoning', summary: ['First public snapshot'] }); observer.onItemUpdate!({ id: 'cancelled', type: 'reasoning', summary: ['Pending public snapshot'] }); const count = sent.length; - await session.interrupt(); await vi.advanceTimersByTimeAsync(1_000); + await session.interrupt(); await vi.advanceTimersByTimeAsync(4_000); observer.onItemUpdate!({ id: 'cancelled', type: 'reasoning', summary: ['Late after cancellation'] }); expect(sent).toHaveLength(count); } finally { await session?.close(); vi.useRealTimers(); } diff --git a/tests/webFormalizationActivity.test.ts b/tests/webFormalizationActivity.test.ts index 4ab26362..d5c70887 100644 --- a/tests/webFormalizationActivity.test.ts +++ b/tests/webFormalizationActivity.test.ts @@ -104,7 +104,7 @@ describe('formalization process view for its owner', () => { expect(actions()).toHaveLength(1); for (let index = 0; index < 100; index++) observer.onItemUpdate!({ id: 'r', type: 'reasoning', summary: [`Public step ${index}. ${PROTOCOL}`] }); expect(actions()).toHaveLength(1); - await vi.advanceTimersByTimeAsync(1_000); + await vi.advanceTimersByTimeAsync(4_000); expect(actions()).toHaveLength(2); expect(actions().at(-1)!.text).toBe('Public step 99. …'); observer.onItemUpdate!({ id: 'r', type: 'reasoning', summary: ['Pending summary'] }); observer.onItem!('completed', { id: 'r', type: 'reasoning', summary: ['Final public summary'] }); diff --git a/tests/webFormalizationWorker.test.ts b/tests/webFormalizationWorker.test.ts index 834adc79..56b8255c 100644 --- a/tests/webFormalizationWorker.test.ts +++ b/tests/webFormalizationWorker.test.ts @@ -86,13 +86,19 @@ describe('formalization worker input and protocol', () => { expect(formalizationWorkerInputSchema.parse(request)).toEqual(request); const prepared = webFormalizationPreparation(request, '/private/profile', '/private/manifest.json'); expect(prepared).toMatchObject({ problemId: request.id, statement: request.original, model: request.model, - effort: request.effort, reviewMode: 'direct', execution: 'model', contextProtocol: LEAN_STATEMENT_CONTEXT_PROTOCOL, + effort: request.effort, reviewMode: 'direct', execution: 'model', contextProtocol: LEAN_STATEMENT_CONTEXT_PROTOCOL, outputDelivery: 'file', maxRunSeconds: 0, maxTotalTokens: 0, maxTurnSeconds: 0, maxCompileSeconds: 0, maxRounds: 0 }); expect(prepared).not.toHaveProperty('workflow'); expect(prepared).not.toHaveProperty('fidelityPolicy'); expect(JSON.stringify(prepared)).not.toContain(request.apiKey); expect(formalizationWorkerInputSchema.safeParse({ ...request, reviewMode: 'unchecked' }).success).toBe(false); }); + it('retains explicit native schema delivery', () => { + const request = { ...input(), reviewMode: 'direct' as const, outputDelivery: 'native-schema' as const }; + expect(webFormalizationPreparation(formalizationWorkerInputSchema.parse(request), '/private/profile', '/private/manifest.json') + .outputDelivery).toBe('native-schema'); + }); + it('passes unlimited execution, generation and planning budgets to the core formalizer', () => { const prepared = webFormalizationPreparation({ ...input(), maxRunSeconds: 0, maxTotalTokens: 0, maxRounds: 0, maxPlanningRounds: 0 }, '/private/profile', '/private/manifest.json'); diff --git a/tests/webRunner.test.ts b/tests/webRunner.test.ts index be9e3095..96743de7 100644 --- a/tests/webRunner.test.ts +++ b/tests/webRunner.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it, vi } from 'vitest'; import { readWebConfig, webDefaults } from '../apps/web/config'; import { DockerWebRunner, parseWorkerMessage, webPrivateImagePaths } from '../apps/web/runner'; import { webProofMessageSink } from '../apps/web/proofJournal'; +import { createWebHostDisconnectWatchdog, webWorkerHeartbeatMs } from '../apps/web/workerDisconnect'; +import { writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import type { WorkerExplanationInput, WorkerExplanationMessage, WorkerInput, WorkerMessage } from '../apps/web/shared'; function candidateCheckDocker(reply: { severity?: string; wrongMarker?: boolean; plain?: boolean; exitCode: number }) { @@ -115,6 +117,102 @@ main().catch(() => process.exit(1)); } finally { fs.rmSync(directory, { recursive: true, force: true }); } }); + it.each(['stdout error', 'stdout close', 'missed control heartbeat'] as const) + ('aborts after the disconnect grace period and flushes the journal for %s', async transport => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-worker-disconnect-')); + const output = new Writable({ write(_chunk, _encoding, done) { done(); } }); + const sink = webProofMessageSink(output, 'sk-offline-fixture', { directory, webRunId: 'journal-fixture' }); + const forcedExit = vi.fn(); + vi.useFakeTimers(); + const watchdog = createWebHostDisconnectWatchdog(output, { graceMs: 100, onAbort: forcedExit }); + const stateFile = path.join(directory, 'state.json'); + const run = (async () => { + try { + await new Promise((_, reject) => watchdog.signal.addEventListener('abort', + () => reject(watchdog.signal.reason), { once: true })); + } finally { + writeMathJsonDurable(stateFile, { phase: 'finished', reason: watchdog.signal.reason }); + sink({ type: 'result', result: { status: 'limit_reached', proof: '', + report: { reason: 'math_host_disconnected' } } }); + watchdog.stop(); + } + })().catch(error => error); + try { + if (transport === 'stdout error') output.emit('error', Object.assign(new Error('broken pipe'), { code: 'EPIPE' })); + if (transport === 'stdout close') output.emit('close'); + if (transport === 'missed control heartbeat') { + watchdog.heartbeat(); + await vi.advanceTimersByTimeAsync(80); + watchdog.heartbeat(); + } + await vi.advanceTimersByTimeAsync(99); + expect(watchdog.signal.aborted).toBe(false); + expect(fs.existsSync(stateFile)).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(await run).toBe('host_disconnected'); + expect(forcedExit).toHaveBeenCalledTimes(1); + expect(JSON.parse(fs.readFileSync(stateFile, 'utf8'))).toEqual({ phase: 'finished', reason: 'host_disconnected' }); + expect(JSON.parse(fs.readFileSync(path.join(directory, 'terminal.json'), 'utf8'))).toMatchObject({ + webRunId: 'journal-fixture', messages: [{ type: 'result', result: { status: 'limit_reached' } }], + }); + expect(vi.getTimerCount()).toBe(0); + } finally { + watchdog.stop(); + vi.useRealTimers(); + fs.rmSync(directory, { recursive: true, force: true }); + } + }); + + it('keeps the proof input pipe open for heartbeats when the image advertises support', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-worker-heartbeat-')); + fs.writeFileSync(path.join(root, 'docker'), `#!${process.execPath} +const args = process.argv.slice(2); +if (args[0] === 'image') process.stdout.write('v1|v1|v1|v1\\n'); +else if (args[0] === 'create') { + if (!args.includes('THEOREMOS_WORKER_CONTROL=1')) process.exit(1); +} else if (args[0] === 'start') { + const lines = require('node:readline').createInterface({ input: process.stdin }); + let request; + lines.on('line', line => { + if (!request) { + request = JSON.parse(line); + process.stdout.write(JSON.stringify({ type: 'progress', event: 'ready', message: 'Ready' }) + '\\n'); + } else if (line === '') { + process.stdout.write(JSON.stringify({ type: 'result', result: { status: 'incomplete', proof: '', report: {} } }) + '\\n'); + lines.close(); process.stdin.destroy(); + } + }); +} else if (args[0] !== 'rm' && args[0] !== 'exec') process.exit(1); +`, { mode: 0o700 }); + vi.stubEnv('PATH', root); + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const controller = new AbortController(), config = readWebConfig({}); + let run: Promise | undefined; + try { + const runner = new DockerWebRunner(config); + expect((await runner.readiness()).ready).toBe(true); + const messages: WorkerMessage[] = []; + let ready!: () => void; + const receivedRequest = new Promise(resolve => { ready = resolve; }); + run = runner.run({ id: 'worker-control-fixture', provider: config.providers[0], input: { + ...webDefaults, providerId: config.providers[0].id, apiKey: 'sk-offline-fixture', + source: 'theorem goal : True := by sorry', task: 'Offline heartbeat fixture', maxRunSeconds: 0, + } }, message => { messages.push(message); if (message.type === 'progress') ready(); }, controller.signal); + await Promise.race([receivedRequest, run.then(() => { throw new Error('worker_closed_before_request'); })]); + expect(messages.map(message => message.type)).toEqual(['progress']); + await vi.advanceTimersByTimeAsync(webWorkerHeartbeatMs); + await run; + expect(messages.map(message => message.type)).toEqual(['progress', 'result']); + expect(vi.getTimerCount()).toBe(0); + } finally { + controller.abort(); + await run?.catch(() => {}); + vi.useRealTimers(); + vi.unstubAllEnvs(); + fs.rmSync(root, { recursive: true, force: true }); + } + }); + it('delivers Lean acceptance over stdout when its journal cannot be written', () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'theoremos-proof-output-')); const file = path.join(directory, 'blocked'); @@ -231,6 +329,7 @@ main().catch(() => process.exit(1)); const calls = fs.readFileSync(path.join(root, 'calls.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); expect(calls.filter(args => args[0] === 'create')).toHaveLength(1); expect(calls.filter(args => args[0] === 'start')).toHaveLength(1); + expect(calls.filter(args => args[0] === 'rm')).toHaveLength(1); expect(fs.existsSync(path.join(root, 'container'))).toBe(false); expect(messages.map(message => message.type === 'progress' ? message.event : message.type)).toEqual(decision === 'approve' ? ['plan_approval_wait_started', 'plan_approval_wait_ended', 'result'] : ['plan_approval_wait_started']); @@ -295,7 +394,7 @@ main().catch(() => process.exit(1)); expect(fs.existsSync(path.join(root, 'container'))).toBe(false); const received = JSON.parse(fs.readFileSync(path.join(root, 'private-input.json'), 'utf8')); - expect(received).toEqual(request); + expect(received).toEqual({ ...request, observationSourceRefs: true }); expect(received).toMatchObject({ provider: { id: 'sub2api', baseUrl: 'http://host.docker.internal:8080/v1' }, input: { model: 'deepseek-flash', effort: 'high' }, diff --git a/tests/webSkillResearch.test.ts b/tests/webSkillResearch.test.ts index f27acc72..abedf7d1 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 { webResearchArguments, webResearchModeError } from '../apps/web/researchMode'; +import { webAgentTeamPreset, webPortfolioPreset, 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'; @@ -15,11 +15,14 @@ import { leanProblemDraft } from '../apps/web/client/problemDrafts'; import { matchesProblemRun } from '../apps/web/problemDraftSubmission'; 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 { mathDigest } from '../src/math/mathRuntimeIo'; import { personalExpertCardsDigest } from '../src/solver/personalExperts'; import { defaultResearchModulePlan } from '../src/solver/modules/policy'; +import { buildRunInspection } from '../src/solver/inspection'; +import { localExample, solverState } from './helpers/solver'; const provider: WebProvider = { id: 'fixture', name: 'Offline fixture', baseUrl: 'http://127.0.0.1:1/v1' }; const input = (overrides: Partial = {}): WebRunInput => ({ providerId: provider.id, apiKey: 'sk-disposable-fixture', @@ -50,11 +53,29 @@ 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('restores a native team with the chosen capacity, rejects host scheduling, and binds observations to the same team', async () => { const selected = { ...draft(), nativeTeamCapacity: 3 }; expect(decodeTaskDraft(JSON.parse(encodeTaskDraft(selected)))).toEqual(selected); expect(leanProblemDraft(selected).draft.nativeTeamCapacity).toBe(3); - const team = input({ nativeTeamCapacity: 3, skillLoading: 'file' }); + 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 }]) @@ -66,6 +87,17 @@ describe('Web Skill research arrangement and frozen identity', () => { const record = observation(run.id, 1); fixture.send({ type: 'observation', observation: record }); expect(run.observation).toBeUndefined(); record.inspection.configuration.researchDelegation = { mode: 'team', maxAgents: 3 }; + // A startup downgrade of the tool transport leaves the team arrangement frozen. + const { directory, workspace, problem } = localExample('web-team-fallback-'); roots.push(directory); + const state = solverState(problem, workspace, { runId: record.solverRunId, + researchDelegation: { mode: 'team', maxAgents: 3 }, agentTeam: { + schema: 'theorem-os.agent-team.v1', transport: 'host-tools', workers: [], events: [], deliveries: [], adoptions: [], operations: [], + } }); + record.inspection.nativeTeam = projectWebNativeTeam(state, directory, buildRunInspection(state).agentTeam!, () => { + throw new Error('There are no proof commits in this fixture'); + }); + expect(record.inspection.nativeTeam).toMatchObject({ transport: 'host-tools', maxAgents: 3, taskCount: 0 }); + expect(isWebObservation(record)).toBe(true); fixture.send({ type: 'observation', observation: record }); expect(run.observation?.sequence).toBe(1); expect(() => jobs.replay('owner', { ...team, nativeTeamCapacity: 4 }, provider, 'native-team')).toThrow(/不同/); }); diff --git a/tests/webWorkerBridge.test.ts b/tests/webWorkerBridge.test.ts index 677e5ddf..74edeb99 100644 --- a/tests/webWorkerBridge.test.ts +++ b/tests/webWorkerBridge.test.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; +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'; @@ -12,12 +13,79 @@ import type { WorkerInput, WorkerMessage } from '../apps/web/shared'; import { webWorkerFixture } from './helpers/webWorkerBridge'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { webGuidanceSchema } from '../apps/web/collaborationValidation'; +import { parseWorkerMessage } from '../apps/web/runner'; +import { WebStorage } from '../apps/web/storage'; +import type { WebObservation } from '../apps/web/collaboration'; +import { webProofMessageSink } from '../apps/web/proofJournal'; const roots: string[] = []; const fixture = () => { const value = webWorkerFixture(); roots.push(value.directory); return value; }; afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); describe('isolated Web worker bridge', () => { + it('streams unchanged megabyte sources by reference and serves complete current and legacy records', async () => { + const f = fixture(), dependency = 'Bridge.lean'; + const source = f.source + '\n/- ' + 'a'.repeat(640_000) + ' -/\n'; + const dependencySource = '/- ' + 'b'.repeat(520_000) + ' -/\n'; + fs.writeFileSync(path.join(f.project, 'Submission.lean'), source); + fs.writeFileSync(path.join(f.project, dependency), dependencySource); + f.state.problem.ownedFiles = ['Submission.lean', dependency]; + f.state.cooperation!.canonicalCommit = f.commit(); + f.state.cooperation!.tasks = f.state.cooperation!.tasks.slice(1); + f.state.cooperation!.history = []; + f.save(); + + const webRunId = 'web-fixture', owner = 'offline-owner'; + const root = path.join(f.directory, 'storage'), storage = new WebStorage(root); + const journal = path.join(f.directory, 'journal'); fs.mkdirSync(journal); + let line = ''; + const sink = webProofMessageSink(new Writable({ + write(chunk: Buffer, _encoding, done) { line = chunk.toString('utf8'); done(); }, + }), '', { directory: journal, webRunId }); + const stream = { runId: webRunId, sources: new Map() }; + const observations: WebObservation[] = []; + let inlineBytes = 0, wireBytes = 0; + const options = { webRunId, directory: f.directory, output: f.output }; + const bridge = createWebWorkerBridge({ ...options, onMessage(message, frame) { + if (message.type !== 'observation') return; + sink(message, frame); + inlineBytes += Buffer.byteLength(JSON.stringify(message)); + wireBytes += Buffer.byteLength(line); + if (observations.length) expect(frame?.sourceBlobs).toEqual({}); + const decoded = parseWorkerMessage(line, stream); + expect(decoded).toEqual(message); + observations.push((decoded as Extract).observation); + } }); + for (let index = 0; index < 24; index++) { + f.state.turns++; f.save(); + await bridge.capture(); + } + expect(observations).toHaveLength(24); + expect(wireBytes / inlineBytes).toBeLessThan(0.10); + expect(observations.at(-1)!.sources).toMatchObject([{ source, dependencySources: [{ file: dependency, source: dependencySource }] }]); + const backup = JSON.parse(fs.readFileSync(path.join(journal, 'observation.json'), 'utf8')).messages[0]; + expect(parseWorkerMessage(JSON.stringify(backup))).toEqual({ type: 'observation', observation: observations.at(-1) }); + const directory = ['owners', mathDigest(owner), 'runs', webRunId]; + storage.saveRecord([...directory, 'observations', '1.json'], observations[0], true); + for (const observation of observations) storage.saveObservation(owner, observation); + + const reopened = new WebStorage(root); + expect(reopened.listRecords([...directory, 'source-blobs'])).toHaveLength(2); + expect(reopened.getObservation(owner, webRunId, 1)).toEqual(observations[0]); + expect(reopened.getObservation(owner, webRunId)).toEqual(observations.at(-1)); + expect(reopened.listObservationsAfter(owner, webRunId, 22, 2)).toEqual(observations.slice(-2)); + expect(reopened.getTaskSource(owner, webRunId, f.goal.id)).toEqual(observations.at(-1)!.sources[0]); + + await createWebWorkerBridge({ ...options, onMessage(message, frame) { + if (message.type !== 'observation') return; + const line = JSON.stringify(frame); + expect(parseWorkerMessage(line)).toEqual(message); + expect(parseWorkerMessage(JSON.stringify({ ...frame, sourceBlobs: {} }))).toBeUndefined(); + const digest = Object.keys(frame!.sourceBlobs)[0]!; + expect(parseWorkerMessage(JSON.stringify({ ...frame, sourceBlobs: { ...frame!.sourceBlobs, [digest]: 'wrong text' } }))).toBeUndefined(); + } }).capture({ force: true }); + }, 30_000); + it('binds current and historical source/checks to one real checkpoint, with distinct Web/solver ids', async () => { const f = fixture(), messages: WorkerMessage[] = []; fs.writeFileSync(path.join(f.project, 'Submission.lean'), 'mutable source must never become checked source');