From 37b9ca7c518cfd3213685b735b256cd6dc1ebccb Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:29:39 +0800 Subject: [PATCH 1/4] Use Codex native teams and simplify the solver harness --- .github/workflows/codex-backend-linux.yml | 51 - .github/workflows/verify.yml | 13 +- AGENTS.md | 4 +- LICENSES/project-scope.md | 2 +- NOTICE | 3 +- README.md | 2 +- README.zh-CN.md | 2 +- apps/web/Dockerfile | 23 +- apps/web/libraryResearch.ts | 149 +- apps/web/nativeTeamObservation.ts | 7 +- apps/web/researchMode.ts | 2 +- apps/web/runner.ts | 186 +- apps/web/server.ts | 179 +- apps/web/worker.ts | 93 +- docs/README.md | 2 +- docs/codex-skill-runtime.md | 77 +- docs/harness-portability.md | 2 +- docs/solver-modules.md | 4 +- docs/usage.md | 16 +- examples/imo2026/README.md | 3 +- package.json | 1 - research/PROTOCOL.md | 16 +- .../0002-persistent-proof-workers.md | 2 +- .../decisions/0016-no-per-agent-worktree.md | 17 + scripts/build-codex-backend.sh | 253 -- scripts/codex-backend/LICENSE.codex | 201 - scripts/codex-backend/NOTICE.codex | 6 - scripts/codex-backend/README.md | 121 - scripts/codex-backend/agent-control.patch | 3994 ----------------- scripts/codex-backend/check-capabilities.py | 132 - scripts/codex-backend/derived-lock.patch | 1547 ------- scripts/codex-backend/git-fetch-pinned.py | 22 - scripts/codex-backend/protocol.md | 184 - scripts/codex-backend/upstream.json | 23 - scripts/mathematics/compareMathRuns.ts | 25 +- scripts/package-codex-backend.sh | 71 - scripts/test-codex-backend-delivery.ts | 781 ---- scripts/test-codex-backend.ts | 888 ---- src/math/nativeProcess.ts | 22 - src/math/verifier.ts | 44 +- src/runtime/agentSession.ts | 20 +- src/runtime/agentSessionPlan.ts | 4 +- src/runtime/codexOutputWatch.ts | 122 + src/runtime/codexRpc.ts | 338 ++ src/runtime/codexSession.ts | 1354 ++---- src/runtime/codexTurnRequests.ts | 209 + src/runtime/nativeAgentControl.ts | 270 -- src/runtime/providerProfile.ts | 33 +- src/solver/agentTeam.ts | 2510 ----------- src/solver/agentTeamContext.ts | 102 - src/solver/agentTeamContributions.ts | 29 +- src/solver/agentTeamForwarding.ts | 37 +- src/solver/agentTeamNative.ts | 782 ---- src/solver/agentTeamOperations.ts | 24 - src/solver/agentTeamProfiles.ts | 28 - src/solver/agentTeamProof.ts | 596 +-- src/solver/agentTeamState.ts | 2 +- src/solver/agentTeamTool.ts | 198 - src/solver/agentTeamViews.ts | 400 +- src/solver/agentTeamWorkspace.ts | 126 - src/solver/continuationSeed.ts | 5 +- src/solver/cooperationShared.ts | 11 +- src/solver/evaluation.ts | 5 +- src/solver/incrementalHelpers.ts | 381 -- src/solver/inspection.ts | 99 +- src/solver/modules/context.ts | 6 +- src/solver/modules/evidence.ts | 2 - src/solver/planApproval.ts | 78 +- src/solver/prepareSolverLean.ts | 131 + src/solver/proofWriter.ts | 8 + src/solver/research.ts | 1252 ++---- src/solver/researchRetirement.ts | 5 +- src/solver/researchToolGuide.ts | 17 +- src/solver/researchTurnCheckpoint.ts | 136 + src/solver/run.ts | 683 ++- src/solver/singleContinuationSeed.ts | 61 +- src/solver/skillProofLifecycle.ts | 37 +- src/solver/skillResearchContext.ts | 138 +- src/solver/teamMemberSchedule.ts | 26 - tests/agentTeamContext.test.ts | 196 - tests/agentTeamContextContract.test.ts | 353 -- tests/agentTeamHandoffs.test.ts | 196 - tests/agentTeamNativeControl.test.ts | 693 --- tests/agentTeamNativeLifecycle.test.ts | 1587 ------- tests/agentTeamNativeTools.test.ts | 1602 ------- tests/agentTeamProof.test.ts | 1327 ------ tests/agentTeamRouteSummary.test.ts | 244 - tests/agentTeamSolver.test.ts | 241 +- tests/agentTeamSourceRecovery.test.ts | 1527 ------- tests/agentTeamTool.test.ts | 184 - tests/agentTeamTransportFallback.test.ts | 162 +- tests/agentTeamViews.test.ts | 167 +- tests/agentTeamWorkspace.test.ts | 138 - tests/campaignLibraryNative.test.ts | 1 + tests/codexSession.test.ts | 35 +- tests/codexSessionAgentControl.test.ts | 656 --- tests/codexSessionCheckpoint.test.ts | 57 + tests/codexSessionNativeMailbox.test.ts | 315 -- tests/codexSessionNotifications.test.ts | 43 +- tests/comparisonSkillBaseline.test.ts | 12 +- tests/declarationArtifacts.test.ts | 99 +- tests/evaluatorExecution.test.ts | 3 +- tests/evaluatorRun.test.ts | 5 +- tests/helpers/buildManifest.ts | 9 + tests/helpers/nativeDirectContext.ts | 86 - tests/researchToolGuide.test.ts | 9 +- tests/runLeaseSafety.test.ts | 34 +- tests/singleContinuationSeed.test.ts | 4 +- tests/skillContextContinuation.test.ts | 277 +- tests/skillResearchRuntime.test.ts | 21 +- tests/skillSolver.test.ts | 52 +- tests/solver.test.ts | 6 +- tests/solverRouteRetirement.test.ts | 297 -- tests/solverSoftSliceCompaction.test.ts | 16 +- tests/webAgentActions.test.ts | 11 +- tests/webLibraryNative.test.ts | 5 +- tests/webLibraryResearch.test.ts | 80 +- tests/webRunner.test.ts | 25 +- tests/workerRecovery.test.ts | 5 +- 119 files changed, 3226 insertions(+), 26989 deletions(-) delete mode 100644 .github/workflows/codex-backend-linux.yml create mode 100644 research/decisions/0016-no-per-agent-worktree.md delete mode 100755 scripts/build-codex-backend.sh delete mode 100644 scripts/codex-backend/LICENSE.codex delete mode 100644 scripts/codex-backend/NOTICE.codex delete mode 100644 scripts/codex-backend/README.md delete mode 100644 scripts/codex-backend/agent-control.patch delete mode 100644 scripts/codex-backend/check-capabilities.py delete mode 100644 scripts/codex-backend/derived-lock.patch delete mode 100755 scripts/codex-backend/git-fetch-pinned.py delete mode 100644 scripts/codex-backend/protocol.md delete mode 100644 scripts/codex-backend/upstream.json delete mode 100755 scripts/package-codex-backend.sh delete mode 100644 scripts/test-codex-backend-delivery.ts delete mode 100644 scripts/test-codex-backend.ts create mode 100644 src/runtime/codexOutputWatch.ts create mode 100644 src/runtime/codexRpc.ts create mode 100644 src/runtime/codexTurnRequests.ts delete mode 100644 src/runtime/nativeAgentControl.ts delete mode 100644 src/solver/agentTeam.ts delete mode 100644 src/solver/agentTeamContext.ts delete mode 100644 src/solver/agentTeamNative.ts delete mode 100644 src/solver/agentTeamOperations.ts delete mode 100644 src/solver/agentTeamTool.ts delete mode 100644 src/solver/agentTeamWorkspace.ts delete mode 100644 src/solver/incrementalHelpers.ts create mode 100644 src/solver/prepareSolverLean.ts create mode 100644 src/solver/researchTurnCheckpoint.ts delete mode 100644 src/solver/teamMemberSchedule.ts delete mode 100644 tests/agentTeamContext.test.ts delete mode 100644 tests/agentTeamContextContract.test.ts delete mode 100644 tests/agentTeamHandoffs.test.ts delete mode 100644 tests/agentTeamNativeControl.test.ts delete mode 100644 tests/agentTeamNativeLifecycle.test.ts delete mode 100644 tests/agentTeamNativeTools.test.ts delete mode 100644 tests/agentTeamProof.test.ts delete mode 100644 tests/agentTeamRouteSummary.test.ts delete mode 100644 tests/agentTeamSourceRecovery.test.ts delete mode 100644 tests/agentTeamTool.test.ts delete mode 100644 tests/agentTeamWorkspace.test.ts delete mode 100644 tests/codexSessionAgentControl.test.ts delete mode 100644 tests/codexSessionNativeMailbox.test.ts create mode 100644 tests/helpers/buildManifest.ts delete mode 100644 tests/helpers/nativeDirectContext.ts delete mode 100644 tests/solverRouteRetirement.test.ts diff --git a/.github/workflows/codex-backend-linux.yml b/.github/workflows/codex-backend-linux.yml deleted file mode 100644 index 163c7fb0..00000000 --- a/.github/workflows/codex-backend-linux.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: Codex Backend Linux - -on: - push: - branches: [main, migration/rust] - paths: - - .github/workflows/codex-backend-linux.yml - - scripts/build-codex-backend.sh - - scripts/package-codex-backend.sh - - scripts/codex-backend/** - workflow_dispatch: - -permissions: - contents: read - -jobs: - linux-backend: - runs-on: ubuntu-24.04 - timeout-minutes: 120 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - name: Install build prerequisites - run: | - # Free space for the locked Cargo build on this disposable runner. - sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /usr/local/share/boost - sudo apt-get update - sudo apt-get install --yes --no-install-recommends build-essential cmake pkg-config libssl-dev libcap-dev libasound2-dev - if [ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then - sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 - fi - rustup toolchain install "$(jq -er .toolchain scripts/codex-backend/upstream.json)" --profile minimal - - name: Build the pinned Codex and Code Mode host - run: | - bash scripts/build-codex-backend.sh --source "$RUNNER_TEMP/codex-source" \ - --downloads "$RUNNER_TEMP/codex-downloads" --output "$RUNNER_TEMP/codex-build" --jobs 3 - - name: Check AgentControl and Code Mode from the archive - run: | - package=$(bash scripts/package-codex-backend.sh "$RUNNER_TEMP/codex-package" "$RUNNER_TEMP/codex-build") - (cd "$(dirname "$package")" && sha256sum --check "$(basename "$package").sha256") - install_dir="$RUNNER_TEMP/codex-install" - mkdir -p "$install_dir" - tar -xzf "$package" -C "$install_dir" --strip-components=1 - timeout 60s python3 scripts/codex-backend/check-capabilities.py "$install_dir/bin/codex" - - uses: actions/upload-artifact@v4 - with: - name: codex-backend-linux-x86_64 - path: ${{ runner.temp }}/codex-package/theoremos-codex-backend-*.tar.gz* - compression-level: 0 - if-no-files-found: error diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index eed9f0b9..746734ab 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -170,19 +170,24 @@ jobs: - name: Install Lean 4.33.0 for historical source recovery fixtures if: matrix.lean == '4.36.0' run: elan toolchain install leanprover/lean4:v4.33.0 - - name: Verify recovery, proof checking and Codex team handoffs without models + - name: Verify recovery, proof checking and historical source recovery without models if: matrix.lean == '4.36.0' run: | THEOREMOS_TEST_REFERENCE_LEAN=1 bunx vitest run tests/informalizationLean.test.ts THEOREMOS_TEST_RECOVERY_LEAN=1 bunx vitest run tests/recovery.test.ts THEOREMOS_TEST_SEED_LEAN=1 bunx vitest run tests/singleContinuationSeed.test.ts - bunx vitest run tests/agentTeamWorkspace.test.ts tests/agentTeamNativeControl.test.ts tests/agentTeamNativeLifecycle.test.ts tests/agentTeamSourceRecovery.test.ts - bunx vitest run tests/solverCompactProjection.test.ts tests/taskSourceProjection.test.ts tests/exactSourceIntegration.test.ts tests/leanDeclarationIdentity.test.ts tests/agentTeamProof.test.ts tests/solverSourceRecovery.test.ts + bunx vitest run tests/solverCompactProjection.test.ts tests/taskSourceProjection.test.ts tests/exactSourceIntegration.test.ts tests/leanDeclarationIdentity.test.ts tests/declarationArtifacts.test.ts tests/solverSourceRecovery.test.ts - name: Verify dependency snapshots and receipt cache bindings run: bunx vitest run --maxWorkers=4 tests/verifierSealedEnvironmentCache.test.ts tests/mathProofEnvironment.test.ts tests/leanProbeSnapshot.test.ts + - name: Install the standard Codex CLI used by the Web worker + if: matrix.lean == '4.36.0' + run: | + npm install --prefix "$RUNNER_TEMP/codex" @openai/codex@0.172.0 + "$RUNNER_TEMP/codex/node_modules/.bin/codex" --version + echo "THEOREMOS_TEST_STOCK_CODEX=$RUNNER_TEMP/codex/node_modules/.bin/codex" >> "$GITHUB_ENV" - name: Verify sealed roles, native team sessions and historical inspection without models if: matrix.lean == '4.36.0' - run: bunx vitest run --maxWorkers=1 tests/formalizationSandbox.test.ts tests/formalizationAudit.test.ts tests/agentSessionPlan.test.ts tests/codexSession.test.ts tests/skillRunInspection.test.ts tests/workflowHarness.test.ts tests/agentTeamTransportFallback.test.ts tests/codexSessionAgentControl.test.ts + run: bunx vitest run --maxWorkers=1 tests/formalizationSandbox.test.ts tests/formalizationAudit.test.ts tests/agentSessionPlan.test.ts tests/codexSession.test.ts tests/skillRunInspection.test.ts tests/workflowHarness.test.ts tests/agentTeamTransportFallback.test.ts tests/agentTeamSolver.test.ts tests/codexSessionCheckpoint.test.ts - name: Verify projected proof contracts and retained source contexts run: bunx vitest run --maxWorkers=4 tests/taskTypeContract.test.ts tests/projectionNotation.test.ts tests/taskSourceImplicitInstances.test.ts tests/taskSourceMacroProjection.test.ts tests/taskSourceNotationHints.test.ts tests/taskSourceNotationContext.test.ts - name: Verify search tools, failure reuse and completed research delivery diff --git a/AGENTS.md b/AGENTS.md index 0ed969e4..7e0591a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,9 +4,9 @@ Keep the CLI and mathematics proof behavior independent of the original DeepScie The CLI, solver, and workbench use the TypeScript runtime. The standalone Rust CLI and its build live on the migration/rust branch. -`src/math` owns mathematics services. `src/solver/run.ts` prepares and evaluates proof runs, `src/solver/research.ts` runs researcher sessions with shared budgets and checkpoints, and `src/solver/agentTeam.ts` connects Codex collaboration to isolated proof writers and checked handoffs. Codex Lead assigns responsibilities using the pinned Skill. `src/solver/archive.ts` owns S1 records and `src/solver/evaluation.ts` owns fixed S3 final acceptance. `src/runtime/codexSession.ts` connects to Codex through stdio. Keep historical collaboration records readable. Resume and reproduce retired host scheduling workflows with their pinned historical runtime. Do not reintroduce the original Core, Team services, HTTP services, role queues, or MCP orchestration into the runtime. S2 learning remains a future extension. +`src/math` owns mathematics services. `src/solver/run.ts` prepares and evaluates proof runs, `src/solver/research.ts` runs researcher sessions with shared budgets and checkpoints. The Codex Lead and its team share one solver checkout. Codex Lead assigns responsibilities using the pinned Skill. `src/solver/archive.ts` owns S1 records and `src/solver/evaluation.ts` owns fixed S3 final acceptance. `src/runtime/codexSession.ts` connects to Codex through stdio. Keep historical collaboration records readable. Resume and reproduce retired host scheduling workflows with their pinned historical runtime. Do not reintroduce the original Core, Team services, HTTP services, role queues, or MCP orchestration into the runtime. S2 learning remains a future extension. -Preserve frozen problem/source identities, isolated solver worktrees, Lean receipts, independent evaluation, and resumable runs. A model's completed message is never proof acceptance. +Preserve frozen problem/source identities, per-run solver worktrees, Lean receipts, independent evaluation, and resumable runs. A model's completed message is never proof acceptance. New formalization requests and proof runs default to `high` reasoning. Web records can freeze a separate `researchEffort`; explicit effort selections, saved drafts and frozen tasks retain their configuration, including `max`. Older records without this field inherit their original effort; CLI resumes without `--effort` keep their frozen effort. Both use `deepseek-flash` through the local sub2api gateway (`http://127.0.0.1:8080/v1`) and the profile at `~/.config/deepscientist/math-sol-codex`. This local profile uses an auth command to read the existing Sub2API Westlake pool key; generated per-attempt Sub2API profiles require `SUB2API_WESTLAKE_API_KEY`. The previous direct Westlake profile is preserved as `~/.config/deepscientist/math-sol-codex-westlake`, and the `my_codex` / `gpt-6.1-sol` profile as `~/.config/deepscientist/math-sol-codex-my_codex`, for resuming older runs via `CODEX_HOME`. Do not copy credentials, alter global Codex configuration, or call real models merely to validate a local extraction. diff --git a/LICENSES/project-scope.md b/LICENSES/project-scope.md index c49e59de..55a02258 100644 --- a/LICENSES/project-scope.md +++ b/LICENSES/project-scope.md @@ -32,7 +32,7 @@ On 2026-11-23, the project maintainer confirmed authority to publish the contrib ## Materials with separate terms - The [44 enumerated Lean modules and their listed adaptations](../resources/theorem-os-library/REDISTRIBUTION.md) have a separate AGPL-3.0-only grant. It does not relicense other contents of the upstream library, cited papers, or a research archive containing copies. -- DeepScientist and AionUi credits, the Apache-licensed files, and the modified OpenAI Codex backend retain their applicable notices. See [NOTICE](../NOTICE) and the [Codex backend attribution](../scripts/codex-backend/README.md). +- DeepScientist and AionUi credits, the Apache-licensed files, and the modified OpenAI Codex backend retain their applicable notices. See [NOTICE](../NOTICE) and the Codex backend notices on `archive/isolated-codex-teams`. - Problems, datasets, proofs supplied by third parties, fonts, icons and third-party packages remain subject to their respective terms. A recorded source URL, checksum, or author name identifies provenance; it does not itself grant redistribution rights. When distributing copies or operating a modified network-accessible version, consult the license, particularly sections 4–6 and 13, for notice and corresponding-source obligations. Forks may identify their origin; they should not claim official endorsement. diff --git a/NOTICE b/NOTICE index 34cabb42..8634a533 100644 --- a/NOTICE +++ b/NOTICE @@ -54,7 +54,8 @@ Third-party components: The modified Codex backend is based on OpenAI Codex. The pinned revision, TheoremOS modifications and upstream notices, including Ratatui credits, are in scripts/codex-backend/README.md, - LICENSE.codex and NOTICE.codex in that directory. + LICENSE.codex and NOTICE.codex in that directory on the + archive/isolated-codex-teams branch (c9439d06). The First Proof batch 3 problem texts have their own attribution and CC BY-SA 4.0 terms in examples/first-proof/batch3/DATA-LICENSE.md. diff --git a/README.md b/README.md index e061ea41..d14fbbf4 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ Lean rejects the first candidate on `0 + n = n`. The second uses `Nat.zero_add` | --- | --- | | Submit a problem, inspect diagnostics or resume a run | [CLI guide](docs/usage.md) · [Web workbench](docs/web-workbench.md) | | Review a formal statement before proving it | [Formalization](docs/formalization.md) · [Statement fidelity](docs/formalization-fidelity.md) | -| Understand how the solver works | [Run lifecycle](src/solver/run.ts) · [Research team](src/solver/agentTeam.ts) · [Final acceptance](src/solver/evaluation.ts) | +| Understand how the solver works | [Run lifecycle](src/solver/run.ts) · [Research sessions](src/solver/research.ts) · [Final acceptance](src/solver/evaluation.ts) | | Change a research policy or run a benchmark | [M1–M5 interfaces](docs/solver-modules.md) · [Examples](examples/README.md) | | Make and test a change | [Contributing](CONTRIBUTING.md) · [CI workflow](.github/workflows/verify.yml) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 70612f7d..9f081f1d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -37,7 +37,7 @@ bun run math inspect --run "$THEOREMOS_REPLAY/result.json" | --- | --- | | 提交题目、读诊断、恢复运行 | [CLI 指南](docs/usage.md) · [网页工作台](docs/web-workbench.md) | | 在证明前核对形式化题意 | [形式化流程](docs/formalization.md) · [题意保持](docs/formalization-fidelity.md) | -| 阅读求解器代码 | [运行入口](src/solver/run.ts) · [研究团队](src/solver/agentTeam.ts) · [最终验收](src/solver/evaluation.ts) | +| 阅读求解器代码 | [运行入口](src/solver/run.ts) · [研究会话](src/solver/research.ts) · [最终验收](src/solver/evaluation.ts) | | 替换研究策略、复验基准 | [M1–M5 模块接口](docs/solver-modules.md) · [示例索引](examples/README.md) | | 修改代码并运行检查 | [贡献指南](CONTRIBUTING.zh-CN.md) · [CI 工作流](.github/workflows/verify.yml) | diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 96476f88..71f06040 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -1,22 +1,6 @@ FROM oven/bun:1.4.0 AS bun FROM docker:29-cli AS docker-cli -# Compile against the worker's libc; a binary from the development host may -# require a newer glibc even when the Codex source and architecture match. -FROM rust:1.99.1-bookworm AS codex-backend -RUN apt-get update && apt-get install -y --no-install-recommends \ - python3 curl cmake pkg-config libssl-dev libcap-dev libasound2-dev \ - && rm -rf /var/lib/apt/lists/* -WORKDIR /build -COPY scripts/build-codex-backend.sh scripts/build-codex-backend.sh -COPY scripts/codex-backend/ scripts/codex-backend/ -ARG CODEX_BUILD_JOBS=4 -RUN --mount=type=cache,id=theoremos-codex-registry,target=/usr/local/cargo/registry,sharing=locked \ - --mount=type=cache,id=theoremos-codex-git,target=/usr/local/cargo/git,sharing=locked \ - --mount=type=cache,id=theoremos-bookworm-codex-target,target=/build/artifacts/target,sharing=locked \ - bash scripts/build-codex-backend.sh --source /build/upstream --downloads /build/downloads \ - --output /build/artifacts --jobs "$CODEX_BUILD_JOBS" - FROM node:22-bookworm-slim AS base COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun RUN apt-get update && apt-get install -y --no-install-recommends \ @@ -104,13 +88,8 @@ ENV DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT_SOURCE_SEED=/opt/theoremos-proof-source ARG THEOREMOS_SOURCE_COMMIT=unknown LABEL org.opencontainers.image.revision=$THEOREMOS_SOURCE_COMMIT ENV THEOREMOS_SOURCE_COMMIT=$THEOREMOS_SOURCE_COMMIT -COPY --from=codex-backend /build/artifacts/bin/codex /opt/theoremos-codex-backend/codex -COPY --from=codex-backend /build/artifacts/bin/codex-code-mode-host /opt/theoremos-codex-backend/codex-code-mode-host -ENV THEOREMOS_CODEX_BACKEND_EXECUTABLE=/opt/theoremos-codex-backend/codex USER 10001:10001 -RUN timeout 30s python3 scripts/codex-backend/check-capabilities.py "$THEOREMOS_CODEX_BACKEND_EXECUTABLE" -LABEL org.theoremos.native-agent-control=v1 -LABEL org.theoremos.native-team-workflow=v1 +LABEL org.theoremos.native-team-workflow=v2 LABEL org.theoremos.team-profile-preferences=v1 LABEL org.theoremos.team-expert-cards=v1 LABEL org.theoremos.worker-control=v1 diff --git a/apps/web/libraryResearch.ts b/apps/web/libraryResearch.ts index e212e7dd..c6b4a137 100644 --- a/apps/web/libraryResearch.ts +++ b/apps/web/libraryResearch.ts @@ -2,19 +2,21 @@ import fs from 'node:fs'; import path from 'node:path'; import { mathDigest, readMathJson, readMathText, writeMathJsonDurable } from '../../src/math/mathRuntimeIo'; import { assertMathCanonicalPath, isMathPathWithin } from '../../src/math/paths'; -import { assertAgentTeamProcessesStopped } from '../../src/solver/agentTeam'; import { readSolverRunState, type SolverRunState } from '../../src/solver/archive'; import { MAX_CONTINUATION_ATTACHMENT_BYTES, MAX_CONTINUATION_ATTACHMENTS, MAX_CONTINUATION_TOTAL_BYTES, + readContinuationContents, readContinuationInput, type ContinuationAttachmentKind, + type ContinuationIdentity, } from '../../src/solver/continuationInput'; import { requestedLibraryPack, type LibraryAccess, type LibraryRequest } from '../../src/solver/libraryAccess'; import type { LibrarySelection } from '../../src/solver/libraryCatalog'; import { nativeApprovalPlanBrief, planApprovalStatus } from '../../src/solver/planApproval'; import { git, readSolverProblem } from '../../src/solver/problem'; +import { assertProofWriterStopped } from '../../src/solver/proofWriter'; import { aggregateUsage, buildTokenBudget } from '../../src/solver/usageBudget'; import { prepareWebProblem } from './formalizationSeed'; import { summarizeWebLibraryUsage } from './libraryUsage'; @@ -91,7 +93,7 @@ function packResearch(materials: Attachment[]): Attachment[] { } /** Library changes create new receipts. Prior proof work is carried only as advisory reading material. */ -function writeResearchContinuation(directory: string, seed: Seed, materials: Attachment[]) { +function writeResearchContinuation(directory: string, identity: ContinuationIdentity, materials: Attachment[]) { if (!materials.length) return; const attachments = packResearch(materials).map(({ text, ...item }, index) => { const file = `research-${index}.txt`; @@ -99,10 +101,6 @@ function writeResearchContinuation(directory: string, seed: Seed, materials: Att return { id: `research-${index}`, path: file, ...item }; }); const file = path.join(directory, 'continuation-input.json'); - const identity = { - taskDigest: mathDigest(readMathText(seed.taskFile)), - problemReceiptDigest: readSolverProblem(seed.workspaceRoot, seed.activeProblemPath).receiptDigest, - }; writeMathJsonDurable(file, { schema: 'theorem-os.continuation-input.v1', ...identity, attachments }); // Apply the same attachment limits and byte checks as the next solver before publishing the transition. readContinuationInput(file, identity); @@ -124,47 +122,24 @@ function readAdvisoryFile(file: string, maxBytes: number, optional = false) { } } -function roundParticipants(state: SolverRunState) { - const nativeTeam = state.agentTeam?.transport === 'native-agent-control' ? state.agentTeam : undefined; - const workers = nativeTeam?.workers ?? state.workers ?? []; - return { - native: Boolean(nativeTeam), - trees: [...new Set([state.worktree, ...workers.map(worker => worker.worktree)])], - usageRecords: nativeTeam || !workers.length ? [state, ...workers] : workers, +function collectResearch(state: SolverRunState, remember: (item: Material) => void) { + const tree = state.worktree; + assertMathCanonicalPath(tree); + const provenance: Material['provenance'] = { + source: 'Library continuation from the saved proof workspace', + evidence: 'recorded-not-replayed', + runId: state.runId, + commit: git(tree, ['rev-parse', 'HEAD']), }; -} - -function collectResearch( - state: SolverRunState, - directory: string, - participants: ReturnType, - remember: (item: Material) => void, -) { - if (participants.native) assertAgentTeamProcessesStopped(state); const files = state.problem.ownedFiles.filter(file => !state.problem.frozenFiles?.[file]); - for (const [index, tree] of participants.trees.entries()) { - if (!isMathPathWithin(directory, tree)) throw new Error('math_library_request_worktree_outside_run'); - assertMathCanonicalPath(tree); - const member = participants.native && tree !== state.worktree; - // A native spawn can be recorded before the host creates its worktree. - if (member && !fs.existsSync(tree)) continue; - const commit = git(tree, ['rev-parse', 'HEAD']); - const provenance: Material['provenance'] = { - source: `Library continuation, worker ${index}; saved draft, not proof evidence`, - evidence: 'recorded-not-replayed', - runId: state.runId, - commit, - }; - // Writers have all stopped. Keep saved drafts as well as committed work, without copying frozen library modules. - for (const file of files) { - const full = path.join(tree, state.problem.projectRelative, file); - const header = `-- Saved file: ${file}\n`; - const text = readAdvisoryFile(full, MAX_CONTINUATION_ATTACHMENT_BYTES - Buffer.byteLength(header), member); - if (text !== undefined) remember({ kind: 'proof-source', text: header + text, provenance }); - } - const notes = readAdvisoryFile(path.join(tree, 'RESEARCH.md'), MAX_CONTINUATION_ATTACHMENT_BYTES, true); - if (notes) remember({ kind: 'research-notes', text: notes, provenance }); + for (const file of files) { + const full = path.join(tree, state.problem.projectRelative, file); + const header = `-- Saved file: ${file}\n`; + const text = readAdvisoryFile(full, MAX_CONTINUATION_ATTACHMENT_BYTES - Buffer.byteLength(header)); + if (text !== undefined) remember({ kind: 'proof-source', text: header + text, provenance }); } + const notes = readAdvisoryFile(path.join(tree, 'RESEARCH.md'), MAX_CONTINUATION_ATTACHMENT_BYTES, true); + if (notes) remember({ kind: 'research-notes', text: notes, provenance }); } /** Supervise child runs with one total budget and the exact original problem across all library installations. */ @@ -192,16 +167,8 @@ export async function runWebLibraryResearch(options: { planApproval: options.request.input.planApproval, }; const materials: Attachment[] = []; - if (options.continuationFile) { - const input = readContinuationInput(options.continuationFile, { - taskDigest: mathDigest(readMathText(options.seed.taskFile)), - problemReceiptDigest: readSolverProblem(options.seed.workspaceRoot, options.seed.activeProblemPath).receiptDigest, - }); - for (const { sha256, bytes, kind, provenance } of input.manifest.attachments) - materials.push({ sha256, bytes, kind, provenance, text: input.contents.get(sha256)! }); - } - const materialDigests = new Set(materials.map(item => item.sha256)); - let remainingBytes = MAX_CONTINUATION_TOTAL_BYTES - materials.reduce((total, item) => total + item.bytes, 0); + const materialDigests = new Set(); + let remainingBytes = MAX_CONTINUATION_TOTAL_BYTES; const remember = (item: Material) => { const bytes = Buffer.byteLength(item.text); if (bytes > remainingBytes || bytes > MAX_CONTINUATION_ATTACHMENT_BYTES) return; @@ -214,7 +181,8 @@ export async function runWebLibraryResearch(options: { let turns = 0, solveWallMs = 0, solveExecutionMs = 0; - const records: ReturnType['usageRecords'][number][] = []; + const records: SolverRunState[] = []; + const reportFile = path.join(options.directory, 'library-research.json'); const rounds: { round: number; runId?: string; @@ -232,7 +200,8 @@ export async function runWebLibraryResearch(options: { await options.run(current); const raw = readMathJson(current.output) as Record; const problem = readSolverProblem(current.seed.workspaceRoot, current.seed.activeProblemPath); - const stateFile = `${current.output}.runtime/state.json`; + const runtimeDirectory = `${current.output}.runtime`; + const stateFile = path.join(runtimeDirectory, 'state.json'); const state = fs.existsSync(stateFile) ? readSolverRunState(stateFile) : undefined; if (state && (state.runId !== raw.runId || state.problem.receiptDigest !== problem.receiptDigest)) throw new Error('math_library_request_run_identity_changed'); @@ -255,8 +224,7 @@ export async function runWebLibraryResearch(options: { turns += usedTurns; solveWallMs += usedMs; solveExecutionMs += executedMs; - const participants = state && roundParticipants(state); - if (participants) records.push(...participants.usageRecords); + if (state) records.push(state); rounds.push({ round: current.round, runId: state?.runId, @@ -269,34 +237,30 @@ export async function runWebLibraryResearch(options: { installedModules: Object.keys(problem.frozenFiles ?? {}).sort(), }); const tokenBudget = buildTokenBudget(allowance.maxTotalTokens, records); + const research = { schema: 'theorem-os.library-research.v1', rounds }; + const consumption = { turns, solveWallMs, solveExecutionMs }; const finish = (result = raw) => { const report: Record = { ...result, - turns, - solveWallMs, - solveExecutionMs, + ...consumption, solveWaitingMs: solveWallMs - solveExecutionMs, ...(state ? { usage: aggregateUsage(records), tokenBudget } : {}), ...(options.libraryCatalog ? { libraryUsage: summarizeWebLibraryUsage(problem, options.libraryCatalog, result, current.round) } : {}), - libraryResearch: { schema: 'theorem-os.library-research.v1', rounds }, + libraryResearch: research, }; - writeMathJsonDurable(path.join(options.directory, 'library-research.json'), report); - return { seed: current.seed, output: current.output, raw: report }; + writeMathJsonDurable(reportFile, report); + return { seed: current.seed, output: current.output, state, raw: report }; }; if (raw.status !== 'library_requested') return finish(); - if (!options.libraryCatalog || !state || !participants || !state.solveStartedAt || !state.solveFinishedAt) + if (!options.libraryCatalog || !state || !state.solveStartedAt || !state.solveFinishedAt) throw new Error('math_library_request_run_incomplete'); const value = raw.libraryRequest as { request?: unknown; worktree?: unknown } | undefined; - if ( - !value || - typeof value.worktree !== 'string' || - !participants.trees.includes(value.worktree) || - !isMathPathWithin(options.directory, value.worktree) - ) + if (!value || value.worktree !== state.worktree || !isMathPathWithin(options.directory, value.worktree)) throw new Error('math_library_request_worker_changed'); const initialNativeApproval = options.request.input.nativeTeamCapacity && current.planApproval; + let approvedRoute: Material | undefined; if (initialNativeApproval) { const approved = state.cooperation?.planApproval; if ( @@ -309,7 +273,7 @@ export async function runWebLibraryResearch(options: { const text = `This route was approved before proof work began. Continue the research with the installed library.\n` + nativeApprovalPlanBrief(state.cooperation.tasks); - remember({ + approvedRoute = { kind: 'research-notes', text, provenance: { @@ -317,8 +281,9 @@ export async function runWebLibraryResearch(options: { evidence: 'recorded-not-replayed', runId: state.runId, }, - }); + }; } + assertProofWriterStopped(state); const next = requestedLibraryPack(problem, value.request, options.libraryCatalog, value.worktree); Object.assign(rounds.at(-1)!, { libraryRequest: next.request, librarySelection: next.selection }); const limits: Limits = { @@ -338,26 +303,40 @@ export async function runWebLibraryResearch(options: { ? 'math_run_stopped' : tokenBudget.reason; if (reason) return finish({ ...raw, status: 'limit_reached', run_outcome: 'limit_reached', reason }); - collectResearch(state, options.directory, participants, remember); + if (current.round === 0 && state.continuationDigest) { + // Carry forward what the solver froze, with the original attachments taking priority. + const { snapshot, contents } = readContinuationContents( + path.join(runtimeDirectory, 'continuation.json'), + state.continuationDigest, + { taskDigest: state.taskDigest, problemReceiptDigest: problem.receiptDigest }, + ); + for (const { sha256, bytes, kind, provenance } of snapshot.manifest.attachments) { + materials.push({ sha256, bytes, kind, provenance, text: contents.get(sha256)! }); + materialDigests.add(sha256); + remainingBytes -= bytes; + } + } + if (approvedRoute) remember(approvedRoute); + collectResearch(state, remember); const round = current.round + 1, directory = path.join(options.directory, 'rounds', String(round)); fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); const seed = prepareWebProblem(directory, options.request, { libraryPack: next.pack }); - const original = readSolverProblem(options.seed.workspaceRoot, options.seed.activeProblemPath); const continued = readSolverProblem(seed.workspaceRoot, seed.activeProblemPath); if ( - continued.contract.formalStatement !== original.contract.formalStatement || - continued.contract.informalStatement !== original.contract.informalStatement || - readMathText(seed.taskFile) !== readMathText(options.seed.taskFile) + continued.contract.formalStatement !== problem.contract.formalStatement || + continued.contract.informalStatement !== problem.contract.informalStatement || + mathDigest(readMathText(seed.taskFile)) !== state.taskDigest ) throw new Error('math_library_request_original_changed'); - const continuationFile = writeResearchContinuation(directory, seed, materials); - writeMathJsonDurable(path.join(options.directory, 'library-research.json'), { - schema: 'theorem-os.library-research.v1', - rounds, - turns, - solveWallMs, - solveExecutionMs, + const continuationFile = writeResearchContinuation( + directory, + { taskDigest: state.taskDigest, problemReceiptDigest: continued.receiptDigest }, + materials, + ); + writeMathJsonDurable(reportFile, { + ...research, + ...consumption, tokenBudget, pending: { round, diff --git a/apps/web/nativeTeamObservation.ts b/apps/web/nativeTeamObservation.ts index 462751f4..9718a89e 100644 --- a/apps/web/nativeTeamObservation.ts +++ b/apps/web/nativeTeamObservation.ts @@ -24,7 +24,12 @@ export function projectWebNativeTeam( committed: (archive: string, commit: string) => { files: Record; digest: string }, ): WebNativeTeam | undefined { const team = state.agentTeam; - if (!team || (team.transport !== 'native-agent-control' && state.researchDelegation?.mode !== 'team')) return; + if ( + !team || + team.transport === 'codex-shared' || + (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'), diff --git a/apps/web/researchMode.ts b/apps/web/researchMode.ts index dac0fdff..d9cb94b8 100644 --- a/apps/web/researchMode.ts +++ b/apps/web/researchMode.ts @@ -6,7 +6,7 @@ export const nativeTeamCapacitySchema = z.number().int().min(MIN_TEAM_AGENTS).ma 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. */ +/** Team preset for Web callers. Capacity counts the Lead and all members. */ export function webAgentTeamPreset( capacity = DEFAULT_TEAM_AGENTS, ): Pick { diff --git a/apps/web/runner.ts b/apps/web/runner.ts index 5e5f2434..c56cb7fd 100644 --- a/apps/web/runner.ts +++ b/apps/web/runner.ts @@ -880,15 +880,15 @@ export class DockerWebRunner implements WebRunner { 'image', 'inspect', '--format', - '{{index .Config.Labels "org.theoremos.native-agent-control"}}|{{index .Config.Labels "org.theoremos.team-profile-preferences"}}|{{index .Config.Labels "org.theoremos.team-expert-cards"}}|{{index .Config.Labels "org.theoremos.worker-control"}}|{{index .Config.Labels "org.theoremos.native-team-workflow"}}|{{.Id}}', + '{{index .Config.Labels "org.theoremos.team-profile-preferences"}}|{{index .Config.Labels "org.theoremos.team-expert-cards"}}|{{index .Config.Labels "org.theoremos.worker-control"}}|{{index .Config.Labels "org.theoremos.native-team-workflow"}}|{{.Id}}', this.config.workerImage, ], { timeout: 5_000, maxBuffer: 4096 }, ).catch(() => undefined); const ready = Boolean(metadata); - const [team, preferences, expertCards, workerControl, workflow, id] = metadata?.stdout.trim().split('|') ?? []; + const [preferences, expertCards, workerControl, workflow, id] = metadata?.stdout.trim().split('|') ?? []; const imageId = /^sha256:[a-f0-9]{64}$/u.test(id ?? '') ? id : undefined; - const nativeTeam = team === 'v1' && workflow === 'v1' && Boolean(imageId); + const nativeTeam = workflow === 'v2' && Boolean(imageId); const result = { ready, nativeTeam, @@ -908,7 +908,7 @@ export class DockerWebRunner implements WebRunner { await this.readiness(); const capability = this.cached; if (!capability?.result.nativeTeam || !capability.imageId) - throw new Error('当前运行镜像未安装支持原生团队与路线审批的 worker,请更新运行镜像。'); + throw new Error('当前运行镜像不支持共享工作区团队与路线审批,请更新运行镜像。'); // Launch the checked image even if a local tag changes while the run is queued. workerImage = capability.imageId; signal.throwIfAborted(); @@ -1094,107 +1094,11 @@ export class DockerWebRunner implements WebRunner { onMessage: (message: WorkerExplanationMessage) => void, signal: AbortSignal, ): Promise { - signal.throwIfAborted(); - const name = `theoremos-explain-${input.id}`, - mathlib = input.environment === 'mathlib'; - const memory = mathlib ? '12g' : '4g'; - const remove = () => - execute('docker', ['rm', '--force', '--volumes', name], { timeout: 15_000 }).then( - () => {}, - () => {}, - ); - try { - await execute( - 'docker', - [ - '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', - '--security-opt=seccomp=unconfined', - '--security-opt=apparmor=unconfined', - '--security-opt=systempaths=unconfined', - '--cpus=2', - `--memory=${memory}`, - `--memory-swap=${memory}`, - '--pids-limit=512', - '--tmpfs', - '/work:rw,nosuid,nodev,size=67108864,uid=10001,gid=10001,mode=0700', - '--tmpfs', - '/tmp:rw,exec,nosuid,nodev,size=134217728,mode=1777', - '--ulimit', - 'nofile=4096:4096', - '--mount', - 'type=volume,destination=/var/tmp', - ...(mathlib ? ['--device=/dev/fuse:/dev/fuse:rw'] : []), - this.config.workerImage, - input.environment, - 'explain', - ], - { timeout: 30_000, maxBuffer: 8_192 }, - ); - } catch { - await remove(); - throw new Error('explanation_container_failed'); - } - try { - signal.throwIfAborted(); - await new Promise((resolve, reject) => { - const child = spawn('docker', ['start', '--attach', '--interactive', name], { - stdio: ['pipe', 'pipe', 'ignore'], - }); - let buffer = '', - finished = false, - received = false; - const finish = (error?: Error) => { - if (finished) return; - finished = true; - clearTimeout(timer); - signal.removeEventListener('abort', abort); - if (error) { - child.kill('SIGKILL'); - reject(error); - } else resolve(); - }; - const abort = () => finish(new Error('explanation_cancelled')); - const timer = - input.maxRunSeconds === 0 - ? undefined - : setTimeout( - () => finish(new Error('explanation_timeout')), - (input.maxRunSeconds + (mathlib ? 1_200 : 600)) * 1_000, - ); - signal.addEventListener('abort', abort, { once: true }); - child.stdout.setEncoding('utf8'); - child.stdout.on('data', chunk => { - if (finished) return; - buffer += chunk; - for (let newline = buffer.indexOf('\n'); newline >= 0; newline = buffer.indexOf('\n')) { - const line = buffer.slice(0, newline); - if (Buffer.byteLength(line) > maxExplanationMessageBytes) - return finish(new Error('explanation_output_too_large')); - const message = parseExplanationMessage(line); - buffer = buffer.slice(newline + 1); - if (message?.type === 'result') received = true; - if (message && !finished) onMessage(message); - } - if (buffer.length > maxExplanationMessageBytes) finish(new Error('explanation_output_too_large')); - }); - child.stdin.on('error', () => {}); - child.once('error', () => finish(new Error('explanation_container_failed'))); - child.once('close', () => finish(received ? undefined : new Error('explanation_worker_exited'))); - // Credentials travel over the private input pipe, never Docker args, env or logs. - child.stdin.end(JSON.stringify(input) + '\n'); - }); - } finally { - await remove(); - } + return this.runModelWorker('explain', input, signal, line => { + const message = parseExplanationMessage(line); + if (message) onMessage(message); + return message?.type === 'result'; + }); } /** Foreground generation and background review have separate container lifetimes. */ @@ -1203,36 +1107,39 @@ export class DockerWebRunner implements WebRunner { onMessage: (message: WorkerFormalizationMessage) => void, signal: AbortSignal, ): Promise { - return this.formalizationContainer( - input, - message => { - if (message.type === 'progress' || message.type === 'activity' || message.type === 'result') onMessage(message); - }, - signal, - ); + return this.runModelWorker('formalize', input, signal, line => { + const message = parseFormalizationMessage(line); + if (message?.type === 'progress' || message?.type === 'activity' || message?.type === 'result') + onMessage(message); + return message?.type === 'result'; + }); } async auditFormalization( input: WorkerFormalizationAuditInput, onMessage: (message: WorkerFormalizationAuditMessage) => void, signal: AbortSignal, ): Promise { - return this.formalizationContainer( - input, - message => { - if (message.type === 'audit-progress' || message.type === 'audit-result' || message.type === 'audit-error') - onMessage(message); - }, - signal, - ); + return this.runModelWorker('formalize', input, signal, line => { + const message = parseFormalizationMessage(line); + if (message?.type === 'audit-progress') onMessage(message); + if (message?.type !== 'audit-result' && message?.type !== 'audit-error') return false; + onMessage(message); + return true; + }); } - private async formalizationContainer( - input: WorkerFormalizationInput | WorkerFormalizationAuditInput, - onMessage: (message: WorkerFormalizationMessage | WorkerFormalizationAuditMessage) => void, + private async runModelWorker( + operation: 'explain' | 'formalize', + input: WorkerExplanationInput | WorkerFormalizationInput | WorkerFormalizationAuditInput, signal: AbortSignal, + readLine: (line: string) => boolean, ): Promise { signal.throwIfAborted(); - const name = `theoremos-formalize-${'operation' in input ? 'audit-' : ''}${input.id}`, + const name = `theoremos-${operation}-${'operation' in input ? 'audit-' : ''}${input.id}`, mathlib = input.environment === 'mathlib'; + const explains = operation === 'explain'; + const errorPrefix = explains ? 'explanation' : 'formalization'; + const fail = (reason: string) => new Error(`${errorPrefix}_${reason}`); + const maxMessageBytes = explains ? maxExplanationMessageBytes : 32 * 1024 * 1024; const memory = mathlib ? '12g' : '4g'; const remove = () => execute('docker', ['rm', '--force', '--volumes', name], { timeout: 15_000 }).then( @@ -1271,13 +1178,13 @@ export class DockerWebRunner implements WebRunner { ...(mathlib ? ['--device=/dev/fuse:/dev/fuse:rw'] : []), this.config.workerImage, input.environment, - 'formalize', + operation, ], { timeout: 30_000, maxBuffer: 8_192 }, ); } catch { await remove(); - throw new Error('formalization_container_failed'); + throw fail('container_failed'); } try { signal.throwIfAborted(); @@ -1298,34 +1205,27 @@ export class DockerWebRunner implements WebRunner { reject(error); } else resolve(); }; - const abort = () => finish(new Error('formalization_cancelled')); + const abort = () => finish(fail('cancelled')); const timer = input.maxRunSeconds === 0 ? undefined - : setTimeout( - () => finish(new Error('formalization_timeout')), - (input.maxRunSeconds + (mathlib ? 1_200 : 600)) * 1_000, - ); + : setTimeout(() => finish(fail('timeout')), (input.maxRunSeconds + (mathlib ? 1_200 : 600)) * 1_000); signal.addEventListener('abort', abort, { once: true }); child.stdout.setEncoding('utf8'); child.stdout.on('data', chunk => { + if (finished) return; buffer += chunk; - for (let newline = buffer.indexOf('\n'); newline >= 0; newline = buffer.indexOf('\n')) { - const message = parseFormalizationMessage(buffer.slice(0, newline)); + for (let newline = buffer.indexOf('\n'); !finished && newline >= 0; newline = buffer.indexOf('\n')) { + const line = buffer.slice(0, newline); + if (explains && Buffer.byteLength(line) > maxMessageBytes) return finish(fail('output_too_large')); buffer = buffer.slice(newline + 1); - if ( - 'operation' in input - ? message?.type === 'audit-result' || message?.type === 'audit-error' - : message?.type === 'result' - ) - received = true; - if (message && !finished) onMessage(message); + if (readLine(line)) received = true; } - if (buffer.length > 32 * 1024 * 1024) finish(new Error('formalization_output_too_large')); + if (buffer.length > maxMessageBytes) finish(fail('output_too_large')); }); child.stdin.on('error', () => {}); - child.once('error', () => finish(new Error('formalization_container_failed'))); - child.once('close', () => finish(received ? undefined : new Error('formalization_worker_exited'))); + child.once('error', () => finish(fail('container_failed'))); + child.once('close', () => finish(received ? undefined : fail('worker_exited'))); // Credentials travel over the private input pipe, never Docker args, env or logs. child.stdin.end(JSON.stringify(input) + '\n'); }); diff --git a/apps/web/server.ts b/apps/web/server.ts index df4e5151..69384123 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -86,8 +86,10 @@ import { WebFormalizations } from './formalizations'; import { webFormalizationDefaults, webFormalizationLimits, + type WebFormalization, type WebFormalizationCapabilities, type WebFormalizationRequest, + type WorkerFormalizationInput, } from './formalizationTypes'; import { SUB2API_PROVIDER } from '../../src/runtime/sub2api'; import { inspectScopedLeanDeclarations } from '../../src/math/leanSource'; @@ -95,6 +97,8 @@ import { formalizationCompiledCandidate, formalizationCompiledCandidateDigest, formalizationDigest, + type FormalizationCompiledCandidate, + type FormalizationEvidence, } from '../../src/math/formalization'; import { isStatementReviewed } from './presentation'; import { WebConversations } from './conversations'; @@ -654,114 +658,79 @@ export function createWebService( }); const trajectories = new WebTrajectories(storage); const research = new WebResearchApi(storage, jobs, knowledge, runner); - const formalizations = new WebFormalizations( - runner, - storage, - webFormalizationLimits, - (owner, formalization, evidence, input) => { - const digest = formalizationCompiledCandidateDigest(formalizationCompiledCandidate(evidence)); - const existing = jobs - .list(owner) - .find( - run => - run.formalizationId === formalization.id && - !run.continueFrom && - run.source === evidence.candidate.source && - run.environment === evidence.request.environment && - !['rejected', 'interrupted', 'superseded'].includes(run.formalization?.confirmation ?? '') && - (!run.formalization?.candidateDigest || run.formalization.candidateDigest === digest), - ); - if (existing) return existing.id; - const run = jobs.create( - owner, - { - ...webDefaults, - ...webFormalizationDefaults.research, - ...formalization.research, - ...webAgentTeamPreset(), - ...(formalization.humanReview ? { planApproval: true } : {}), - providerId: input.provider.id, - apiKey: input.apiKey, - autoExplain: formalization.autoExplain, - explanationLanguage: formalization.explanationLanguage, - model: input.model, - effort: formalization.researchEffort ?? input.effort, - source: evidence.candidate.source, - environment: evidence.request.environment, - task: '依据自然语言原题及其 Lean 陈述,证明全部目标,保留所有定义、假设与声明。', - formalizationId: formalization.id, - }, - input.provider, - undefined, - undefined, - { - evidence, - provenance: { - id: formalization.id, - evidenceSha256: formalizationDigest(evidence), - original: formalization.original, - candidateDigest: digest, - confirmedAt: formalization.confirmedAt!, - confirmation: formalization.confirmation ?? 'automatic', - ...(formalization.reviewMode ? { reviewMode: formalization.reviewMode } : {}), - }, - }, - ); - milestone(owner, 'firstRunAt'); - return run.id; - }, - { - start: (owner, formalization, compiled, input) => { - const digest = formalizationCompiledCandidateDigest(compiled); - const existing = jobs - .list(owner) - .find( - run => - run.formalizationId === formalization.id && - !run.continueFrom && - run.formalization?.candidateDigest === digest && - run.source === compiled.candidate.source && - run.environment === compiled.request.environment, - ); - if (existing) return existing.id; - const run = jobs.create( - owner, - { - ...webDefaults, - ...webFormalizationDefaults.research, - ...formalization.research, - ...webAgentTeamPreset(), - providerId: input.provider.id, - apiKey: input.apiKey, - model: input.model, - effort: formalization.researchEffort ?? input.effort, - autoExplain: formalization.autoExplain, - explanationLanguage: formalization.explanationLanguage, - source: compiled.candidate.source, - environment: compiled.request.environment, - formalizationId: formalization.id, - task: '证明编译通过的固定候选陈述的全部目标,保留所有定义、假设与声明。原题含义审核正在后台进行。', - }, - input.provider, - undefined, - undefined, - { - compiled, + const startFormalizedProof = ( + owner: string, + formalization: WebFormalization, + statement: FormalizationEvidence | FormalizationCompiledCandidate, + input: WorkerFormalizationInput, + ) => { + const { source } = statement.candidate; + const { environment } = statement.request; + const pendingReview = statement.schema === 'theorem-os.formalization-compiled-candidate.v1'; + const digest = formalizationCompiledCandidateDigest( + pendingReview ? statement : formalizationCompiledCandidate(statement), + ); + const existing = jobs.list(owner).find(run => { + if ( + run.formalizationId !== formalization.id || + run.continueFrom || + run.source !== source || + run.environment !== environment + ) + return false; + const previousDigest = run.formalization?.candidateDigest; + return pendingReview + ? previousDigest === digest + : !['rejected', 'interrupted', 'superseded'].includes(run.formalization?.confirmation ?? '') && + (!previousDigest || previousDigest === digest); + }); + if (existing) return existing.id; + const provenance = { id: formalization.id, original: formalization.original, candidateDigest: digest }; + const proof = jobs.create( + owner, + { + ...webDefaults, + ...webFormalizationDefaults.research, + ...formalization.research, + ...webAgentTeamPreset(), + ...(!pendingReview && formalization.humanReview ? { planApproval: true } : {}), + providerId: input.provider.id, + apiKey: input.apiKey, + autoExplain: formalization.autoExplain, + explanationLanguage: formalization.explanationLanguage, + model: input.model, + effort: formalization.researchEffort ?? input.effort, + source, + environment, + task: pendingReview + ? '证明编译通过的固定候选陈述的全部目标,保留所有定义、假设与声明。原题含义审核正在后台进行。' + : '依据自然语言原题及其 Lean 陈述,证明全部目标,保留所有定义、假设与声明。', + formalizationId: formalization.id, + }, + input.provider, + undefined, + undefined, + pendingReview + ? { compiled: statement, provenance: { ...provenance, confirmation: 'pending' } } + : { + evidence: statement, provenance: { - id: formalization.id, - original: formalization.original, - candidateDigest: digest, - confirmation: 'pending', + ...provenance, + evidenceSha256: formalizationDigest(statement), + confirmedAt: formalization.confirmedAt!, + confirmation: formalization.confirmation ?? 'automatic', + ...(formalization.reviewMode ? { reviewMode: formalization.reviewMode } : {}), }, }, - ); - milestone(owner, 'firstRunAt'); - return run.id; - }, - update: (owner, id, digest, confirmation, approved) => - jobs.reviewFormalization(owner, id, digest, confirmation, approved), - }, - ); + ); + milestone(owner, 'firstRunAt'); + return proof.id; + }; + const formalizations = new WebFormalizations(runner, storage, webFormalizationLimits, startFormalizedProof, { + start: startFormalizedProof, + update: (owner, id, digest, confirmation, approved) => + jobs.reviewFormalization(owner, id, digest, confirmation, approved), + }); const prechecker = runner.check ? new WebPrechecker(runner.check.bind(runner)) : undefined; const community = new WebCommunity(storage, runner.check?.bind(runner)); const communityActor = (session?: Session): CommunityActor | undefined => { diff --git a/apps/web/worker.ts b/apps/web/worker.ts index 2b746ab6..65717b75 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -313,9 +313,7 @@ export function webSolverModules( tool: isolation?.tools ?? path.join(root, 'bin/math.ts'), apiKey: request.input.apiKey, solverRunId: actions.solverRunId?.(), - ...(options.nativeAgentControl && { - nativeRole: options.nativeAgentControl.initialInput ? ('member' as const) : ('lead' as const), - }), + ...(options.sharedProofTeam && { nativeRole: 'lead' as const }), } : undefined; // Native item ids are scoped to one session; a restarted session may number its own. @@ -449,9 +447,17 @@ async function main(watchdog: ReturnType } const workspaceRoot = process.env.THEOREMOS_WORKER_ROOT || '/work'; const directory = fs.mkdtempSync(path.join(workspaceRoot, 'run-')); + const activeRunFile = path.join(workspaceRoot, 'active-run.json'); + const activateRound = ( + output: string, + libraryRestart?: Parameters[0]['libraryRestart'], + ) => { + const active = { webRunId: request.id, directory, output, libraryRestart }; + writeWebActiveRun(active, activeRunFile); + return createWebWorkerBridge({ ...active, apiKey: key, onMessage: send }); + }; let output = path.join(directory, 'result.json'); - writeWebActiveRun({ webRunId: request.id, directory, output }, path.join(workspaceRoot, 'active-run.json')); - let bridge = createWebWorkerBridge({ webRunId: request.id, directory, output, apiKey: key, onMessage: send }); + let bridge = activateRound(output); const profile = path.join(directory, 'codex'); prepareWebProviderProfile(profile, request); fs.mkdirSync(process.env.HOME || '/work/home', { recursive: true, mode: 0o700 }); @@ -463,21 +469,20 @@ async function main(watchdog: ReturnType let artifactSampler: ReturnType | undefined; let observationTimer: ReturnType | undefined; let capturePending: Promise | undefined; - const capture = (final = false) => - (capturePending ??= bridge + const capture = async (final = false) => { + if (final) await capturePending; + const stateFile = `${output}.runtime/state.json`; + return (capturePending ??= bridge .capture({ includeCatalog: final, force: final }) .catch(error => { // The marker exists during preparation, before the first solver checkpoint is available. - if ( - fs.existsSync(`${output}.runtime/state.json`) && - error instanceof Error && - error.message !== 'math_runtime_lease_busy' - ) + if (fs.existsSync(stateFile) && error instanceof Error && error.message !== 'math_runtime_lease_busy') send({ type: 'progress', event: 'observation_unavailable', message: `研究观察暂不可用:${error.message}。` }); }) .finally(() => { capturePending = undefined; })); + }; let solverRunId: string | undefined; const forwardProgress = createWebProgressForwarder(send); console.log = (...args: unknown[]) => { @@ -538,14 +543,14 @@ async function main(watchdog: ReturnType { sink: action => send({ type: 'action', action }), solverRunId: () => solverRunId, - // The application, its build state (…/builds//manifest.json) and this run's directory: the other Agents' worktrees, - // the Codex profile and the solver's state. An Agent's own worktree inside the run directory is shown relative. + // Keep the application, build state, Codex profile and solver state private. + // The proof workspace inside the run directory is shown relative. hidden: [ root, buildState, buildFile, directory, - path.join(workspaceRoot, 'active-run.json'), + activeRunFile, ...(journalDirectory ? [journalDirectory] : []), ], }, @@ -560,18 +565,11 @@ async function main(watchdog: ReturnType libraryCatalog: webAgentLibraryAccess(environment.id), run: async round => { watchdog.signal.throwIfAborted(); - output = round.output; - solverRunId = undefined; - const active = { - webRunId: request.id, - directory, - output, - ...(round.previousSolverRunId - ? { libraryRestart: { previousSolverRunId: round.previousSolverRunId, round: round.round } } - : {}), - }; - writeWebActiveRun(active, path.join(workspaceRoot, 'active-run.json')); - bridge = createWebWorkerBridge({ ...active, apiKey: key, onMessage: send }); + if (round.previousSolverRunId) { + output = round.output; + solverRunId = undefined; + bridge = activateRound(output, { previousSolverRunId: round.previousSolverRunId, round: round.round }); + } artifactSampler = createWebArtifactSampler({ directory, output, @@ -644,12 +642,11 @@ async function main(watchdog: ReturnType watchdog.signal, ); artifactSampler.sample(); - await capturePending; await capture(true); }, }); clearInterval(observationTimer); - const raw = completed.raw; + const { raw, state } = completed; const report = Object.fromEntries( [ 'schema', @@ -688,28 +685,23 @@ async function main(watchdog: ReturnType dependencyDigest: environment.dependencyDigest, ...(environment.mathlibRevision ? { mathlibRevision: environment.mathlibRevision } : {}), }; - const stateFile = `${output}.runtime/state.json`; - const state = fs.existsSync(stateFile) ? (readMathJson(stateFile) as WebWorkerState) : undefined; - if (state) { - if (state.check) - report.candidateCheck = { - passed: state.check.passed, - status: state.check.verification?.status, - results: state.check.verification?.results?.slice(0, 64).map(result => - Object.fromEntries( - ['theoremName', 'status', 'sorryCount', 'admitCount', 'error', 'stdoutPreview', 'stderrPreview'] - .filter(field => Object.hasOwn(result, field)) - .map(field => [ - field, - typeof result[field] !== 'string' - ? result[field] - : (field.endsWith('Preview') ? withoutCheckMarkers(result[field]) : result[field]).slice(0, 2_000), - ]) - .filter(([, value]) => value !== ''), - ), + if (state?.check) + report.candidateCheck = { + passed: state.check.passed, + status: state.check.verification?.status, + results: state.check.verification?.results?.slice(0, 64).map(result => + Object.fromEntries( + ['theoremName', 'status', 'sorryCount', 'admitCount', 'error', 'stdoutPreview', 'stderrPreview'] + .filter(field => Object.hasOwn(result, field)) + .map(field => { + const value: unknown = result[field as keyof typeof result]; + if (typeof value !== 'string') return [field, value]; + return [field, (field.endsWith('Preview') ? withoutCheckMarkers(value) : value).slice(0, 2_000)]; + }) + .filter(([, value]) => value !== ''), ), - }; - } + ), + }; const proof = readWebResultProof({ directory, workspace: completed.seed.workspaceRoot, @@ -720,7 +712,6 @@ async function main(watchdog: ReturnType send({ type: 'result', result: { status: String(raw.status || 'runtime_error'), proof, report } }); } catch (error) { clearInterval(observationTimer); - await capturePending; await capture(true); send({ type: 'error', diff --git a/docs/README.md b/docs/README.md index 921b2db4..5a691968 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,7 +14,7 @@ ## 理解和修改运行时 -从 [CLI 入口](../bin/math.ts) 到[求解器](../src/solver/run.ts):[研究会话](../src/solver/research.ts)负责执行和恢复,[团队接口](../src/solver/agentTeam.ts)把任务和交付关联到隔离工作区。运行过程写入 [S1 档案](../src/solver/archive.ts),候选交由 [S3 验收器](../src/solver/evaluation.ts)复查完整原题。可选的 [Web 服务](../apps/web/)调用同一运行时。 +从 [CLI 入口](../bin/math.ts) 到[求解器](../src/solver/run.ts):[研究会话](../src/solver/research.ts)负责执行和恢复,团队由 Codex 在同一工作区内分工。运行过程写入 [S1 档案](../src/solver/archive.ts),候选交由 [S3 验收器](../src/solver/evaluation.ts)复查完整原题。可选的 [Web 服务](../apps/web/)调用同一运行时。 | 修改方向 | 对应文档 | | --- | --- | diff --git a/docs/codex-skill-runtime.md b/docs/codex-skill-runtime.md index ad83e3b4..2b601e32 100644 --- a/docs/codex-skill-runtime.md +++ b/docs/codex-skill-runtime.md @@ -1,6 +1,6 @@ # TheoremOS proof workflow -The CLI and Web use the same proof workflow for new runs. The host freezes the problem and Lean environment, starts a researcher in an isolated worktree, then checks saved sources after the writer stops. The pinned project Skill supplies research methods and role guidance. Codex Lead can delegate when the backend supports native collaboration. See [Codex configuration](harness-portability.md) for profile and executable selection. +The CLI and Web use the same proof workflow for new runs. The host freezes the problem and Lean environment, then gives the Lead and its native Codex subagents one shared checkout. The host independently verifies the original targets after the team stops. The pinned project Skill supplies research methods and role guidance. See [Codex configuration](harness-portability.md). ## Start and resume @@ -12,7 +12,7 @@ bun bin/math.ts run \ --output NEW_RESULT_FILE --build-manifest BUILD_MANIFEST ``` -New Codex runs start one Lead who can delegate up to three members. Set `--agent-team N` to change capacity or `--workers 1` to disable delegation. In Web, the same workflow can run with one researcher when the worker image lacks native collaboration. Choose `--plan-approval` to have Lead wait for approval of the initial route before starting proof work. +New Codex runs start one Lead who can delegate up to seven members in the shared checkout. Set `--agent-team N` to change capacity or `--workers 1` to run solo. Choose `--plan-approval` to have Lead wait for approval of the initial route before starting proof work. The `--resume` command continues solo runs and native teams with their saved research mode, Skill loading, provider and environment. The host checks the frozen identities before resuming the thread. New runs save `researchSkillWorkflow: full` and an execution plan. Historical single-researcher checkpoints without that marker keep their original workflow. Inspect older host-scheduled archives with the current CLI and use the original pinned runtime to resume them. A new strategy can start a separate run from the saved artifacts. @@ -20,7 +20,7 @@ The Codex provider connectivity probe runs during `--startup-only` and `doctor`. For Codex sessions metered by upstream request receipts, the host sends `excludeTurns: true` on resume. Codex restores the thread internally and returns metadata without sending the full transcript over stdio. Direct providers whose budget gate uses native thread totals still request turn history so Codex can replay saved usage. If that reply exceeds the 8 MiB stdio frame limit, the host reopens the thread once with `excludeTurns: true`; the next turn's cumulative total still includes the skipped replay. In continuous cooling, an oversized frame that recurs after one cooldown stops the run instead of cooling again. -New standalone Codex runs with `--workers 1` use a short Lean prompt and a local reference to the pinned Skill. They keep the same native process for ordinary incomplete drafts. The host stops the writer before freezing a candidate, checking a nominated declaration or closing an ordinary terminal turn. Team runs and explicitly selected `--skill-loading native` check Codex discovery and send native skill input on ordinary host turns. `--skill-loading file` explicitly directs Codex to read the same pinned file. Native child communication carries the host's frozen context and explicit pinned-file reading instructions; its execution plan records file loading because Codex's typed input cannot combine an inter-agent communication with a skill input. Discovery and an accepted request do not prove that a provider followed the skill; that requires separate execution evidence. +New standalone Codex runs with `--workers 1` use a short Lean prompt and a local reference to the pinned Skill. They keep the same native process for ordinary incomplete drafts. The host stops the writer before freezing a candidate, checking a nominated declaration or closing an ordinary terminal turn. Team runs and explicitly selected `--skill-loading native` check Codex discovery and send native skill input on ordinary host turns. `--skill-loading file` explicitly directs Codex to read the same pinned file. In historical AgentControl runs, native child communication carries the host's frozen context and explicit pinned-file reading instructions; its execution plan records file loading because Codex's typed input cannot combine an inter-agent communication with a skill input. Discovery and an accepted request do not prove that a provider followed the skill; that requires separate execution evidence. ## Codex adapter boundary @@ -34,18 +34,6 @@ New Codex report workflows prefer native `outputSchema` and the final response b The non-Skill solo path uses native `thread/compact/start` between settled turns before rotating a thread for context capacity. The adapter waits for the `contextCompaction` item and the successful terminal event before it resumes research. Its maintenance requests are accounted for separately from proof turns. Failed compaction retains the existing fresh-thread recovery. Skill research keeps Codex's own automatic compaction behavior. -Native teams deliver through Codex's mailbox and attributed input. Queue-only delivery leaves an idle turn waiting. Codex accepting a message confirms queue ownership. The receiver's read status is tracked separately. Anchoring an active update to its turn prevents a late notification from starting another writer. Delivery can remain uncertain after worker loss. - -Native team runs use the separately built [Codex AgentControl backend](../scripts/codex-backend/README.md). Official `spawn_agent`, `send_message`, `followup_task`, `list_agents`, `wait_agent` and `interrupt_agent` handlers stay installed. The adapter connects them over stdio to TheoremOS's isolated writer lifecycle. The host prepares a separate process and worktree before the first child model request; trusted bootstrap preserves native tree identity, captured instructions, parent lineage and native fork history. Workspace relocation revokes the parent's writable worktree and permits the destination isolated workspace while retaining other restrictions. Per-worker provider settings stay local to the worker process. - -Codex's generic root/subagent role messages are deliberately suppressed: their defaults assume a shared working directory and allow recursive child teams. TheoremOS supplies the actual flat-team identities, isolated workspace permissions and native usage guidance through the pinned context instead. This does not remove native tool descriptions. Deferred mailbox preemption preserves delivery at the next model boundary after the current response and tools settle; it does not require a host coordination acknowledgment. - -Native team sessions set Codex's `features.multi_agent_v2.multi_agent_mode_hint_text`. Lead receives authorization to delegate useful complementary work. Members can exchange messages. Lead alone can dispatch or interrupt members. The override is recorded with the runtime configuration and reapplied on new and resumed writer sessions. - -Build the pinned backend to start a native team. It defaults to `out/codex-backend/codex`. Set `THEOREMOS_CODEX_BACKEND_EXECUTABLE` to select another build. The run pins the executable's real path and digest. Native teams require a compatible profile such as the Responses gateway. The host confirms writer shutdown before freezing sources, checking them in Lean and making them available for Lead adoption. See the [backend startup rules](../scripts/codex-backend/README.md). - -The backend's real-binary [loopback fixture](../scripts/test-codex-backend.ts) covers isolated native spawn, attributed messages, idle queues, cold resume with first-request FIFO mail, full-history fork, loaded-agent listing, mailbox wakeup, changes to a running member's expertise and idle/active interruption. It verifies writer shutdown, checked delivery, adoption and final proof references. Provider responses are fixed local data. Installing the CLI backend does not upgrade an existing Web worker image. - Real installed-Codex tests with local fixed Responses replies cover native shell refusal/correction and concurrent advisory injection, preservation of parallel tool results, and idle injection without model work. These verify transport and lifecycle behavior; no mathematical speedup is inferred from them. ## Agent-organized proof-writing team @@ -58,59 +46,21 @@ bun bin/math.ts run --agent-team 3 \ --output NEW_RESULT_FILE --build-manifest BUILD_MANIFEST ``` -`--agent-team` sets capacity from 2 to 8, including Lead, and defaults to 4. An idle or interrupted member retains its place. Lead can use `followup_task` to give that member a new assignment. Use `--plan-approval` to review the initial route before proof work. Native teams require the pinned Codex backend. Other harnesses can start solo runs. +`--agent-team` sets the capacity from 2 to 8, including Lead, and defaults to 4. Lead delegates and communicates with Codex's native tools. `--plan-approval` gives Lead a read-only planning turn before proof work. Other harnesses can start solo runs. Before starting a team, optionally select preferred roles in the Web form or pass a comma-separated list, e.g. `--skill-preferred-profiles researcher,engineer,D011`. Work roles and domain specialties come from the [pinned Skill catalogue](../skills/theoremos-research/references/team-roles.md); a domain ID or its slug is accepted. A preference tells the Lead what expertise you would like considered. It does not reserve seats, start members, restrict other roles, or mark any expertise as used. The run saves these preferences for resume. Leave the list empty for ordinary autonomous selection. You can also select a released personal Skill or Agent as a source of expertise. The web service checks access and freezes the selected version, including relevant material from its referenced Skills. It uses descriptions, areas, inputs, outputs and examples. To make a source available to an expert, include its citation or link in one of those fields. Legacy steps, execution instructions, module overrides, model and staffing choices are not imported. Put knowledge that you want to reuse from an old instruction block in the description or examples and publish a new version. -For CLI runs, `--skill-expert-cards-file FILE` takes a JSON array with string fields `assetId`, `version`, `digest` (the release's SHA-256), `name`, `summary` and `knowledge`. Lead sees the available names and summaries; a dispatch such as `Profiles: researcher, asset:topology` supplies the selected knowledge to that assignment. The run retains its frozen cards on resume. A card supplies background; it cannot grant tools or certify a claim. - -Lead chooses the mathematical decomposition, delegates proof work, changes routes and selects results for adoption. The default Skill guidance uses a flat team working on complementary gaps in the shared proof effort, with alternative-route investigations when useful. Members can discuss findings and interfaces directly. Each child has an isolated writable worktree, the same pinned Skill and a native thread that persists across assignments. Codex tools handle delegation, instructions and communication. The host's `theoremos_team` handles mathematical evidence, source handoffs and checked-result adoption. - -The Skill guides Lead to look for complementary work early. A useful research question can be assigned before a complete proof route or exact helper type is known. Lead chooses tasks, methods, when to reassess and team size within capacity. `send_message` carries findings, route changes and status. `followup_task` supplies further instructions, and `interrupt_agent` stops a member's turn. - -Lead and member contexts report active time limits and refresh the remaining run time on continuation. A finite `--max-turn-seconds` remains a hard ceiling. Team turns start handing back control at 80% of that limit. New paid requests stop at the next admission boundary, after the in-flight response and its native tools have finished. For a 300-second turn, the stage checkpoint is at 240 seconds, leaving up to 60 seconds for settlement. A checkpoint preserves the saved thread and sources. The hard turn deadline, overall deadline and explicit cancellation can interrupt an unfinished request. Missing usage blocks finite-budget continuation. - -Team identity is stable: Lead owns the original problem and may also write proofs; each child is a mathematical researcher and Lean proof writer. The pinned Skill's [specialist profiles](../skills/theoremos-research/references/domain-experts.md) supply specialized knowledge: concepts and structures, relevant theories with their conditions, important distinctions and connections to neighboring subjects. Each member chooses its reasoning and proof approach for the assigned question. The catalog contains 100 domain profiles and 24 work or supporting-expertise profiles; these can be combined and are separate from the runtime's agent capacity. Lead provides the question and members read the relevant knowledge sections. The [work profiles](../skills/theoremos-research/references/team-roles.md), including Researcher, Lean Prover, Lean Engineer and Reviewer, describe responsibilities that can accompany a specialization. Lead selects, combines or changes expertise and responsibilities in native spawn and followup messages; no separate `role` or `domain` parameter or host authority is added. Independent review requires a non-producing member and fixed evidence; a role change alone does not make the producing thread independent. This is a Skill collaboration requirement, not an additional host review gate. The host refreshes developer identity and source permissions, while the pinned Skill supplies domain knowledge and collaboration guidance. Each child dispatch starts with a bounded current-assignment section containing its task ID, objective, source and delivery baselines, own prior feedback, peer work and addressed inbox. The inbox cursor advances only after turn-start acknowledgment. See the [source research and prompt design](../research/agent-team-prompts.md). - -Start a specialized `spawn_agent` or `followup_task` message with `Profiles:` followed by comma-separated domain and work-profile IDs or slugs selected for the gap. A work profile alone is valid. The child receives the selected profile text and the locations of local reading notes. When Lead changes the expertise of a running member, the same attributed followup delivers the new profile context to the current turn. The host records the pinned Skill digest, the requested and loaded IDs, and any unresolved names after the native backend accepts the input. The record establishes which material was supplied. - -The Lead charter assigns concrete gaps with a consumer and first usable result, with one owner per active obligation including Lead. While a member owns a gap, Lead advances its consumer or other work; different methods for proving the same target still overlap. Whole-target delegation has one owner while others provide targeted support, integration or review. Alternative routes start with the smallest finding that resolves a specific uncertainty. Members receive the original problem as background to their current assignment and send useful intermediate findings before the complete proof. These are Skill and native role instructions, without a host scheduler or delegation gate. - -Native followup retains the member's workspace, thread and draft while the adapter records the latest accepted task instructions and retains earlier instructions in history. A new `Profiles:` header changes the selection. The host binds a `submit` call to the member's current task. Profile records retain exact loaded passage identities. A member can explain a passage's application in its messages or saved research notes. - -Members use independent Git object stores; each writer's namespace hides the peer-workspace parent and rebinds only its own workspace. Checked fixed commits and evidence are archived outside writer visibility and imported by exact version for explicit adoption. `inspect` records exposure to a peer delivery, and completed adoption records reuse. These records persist across tasks and accompany later deliveries with the source producer, task and commit. They record explicit source transfers, not complete reasoning independence or independent authorship of reused declarations. - -Before a team Lead or member starts Codex, the host runs `check-lean --health` through the same PID/mount isolation, environment, profile and hidden roots. It checks the sealed mapping, lease and pinned compiler without compiling proofs or admitting a model request. Readiness is retained in the isolation receipt and emitted as `lean_environment_ready`; a failure produces structured infrastructure diagnostics and stops that launch. A missing mapping is a namespace visibility fault and does not establish that a host process died. Canonical check-lean returns a nonzero structured error when Lean cannot start; a shell pipeline's final status remains distinct from the compiler result. - -Each domain profile also links [collected domain materials](../skills/theoremos-research/references/domain-materials.md). The Skill pins original knowledge notes with source identities, exact reading locations and coverage limits, so these notes are available in the isolated workspace without fetching a book. Full third-party documents and retrieval evidence stay outside the repository; reading an original online follows the run's network policy. The collection supplies domain background and leaves proof approaches to the members. It does not install formal declarations or import literature into the checked theorem catalog. - -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. - -Codex collaboration tools handle identity, dispatch, instructions, messaging, waiting and interruption. Lead and members can call `history`, `inspect`, `inspect-research` and `route_summary` through `theoremos_team`. Lead can also call `finish`, `adopt` and `retire_route`. When first-route approval is enabled, Lead calls `publish_plan` with a route covering every original goal, then waits for approval before writing proofs or dispatching members. Members can call `yield` and `submit`. Set `helpersOnly: true` on `submit` to share standalone helpers and keep the assignment open. `followup_task` resumes a yielded draft or assigns work to a completed member. `list_agents` lists loaded agents. The saved overview retains members and their task and evidence identities after their writer process stops. - -Lead and member contexts use a bounded [overview projection](../src/solver/agentTeamViews.ts) of current and recent assignments, research and proof references, and integration status. `activity` reports execution states such as preparing, running, checking and paused. `history(agentId?, offset?, limit?)` pages through complete task instructions and saved summaries with source and evidence IDs. `inspect` returns checked declaration interfaces, source excerpts, commits and proof evidence for adoption decisions. Share route changes through native messages and save reproducible findings in `RESEARCH.md`. - -After an executed child task's writer stops, its result records the stable `sourceCommit` and `researchArtifactId`. The artifact contains the task's summary and status, plus the root RESEARCH.md when present; missing notes return `notes:null`. The `researchArtifacts` index exposes artifact ID, producer, task and commit without host storage paths. Any member can use `inspect-research(artifactId, offset?, limit?)` to read paginated saved notes at that fixed commit, using Unicode code point offsets and `nextOffset`. This preserves inspectable counterexamples, literature mappings, calculations and failed routes even when no Lean declaration was submitted. An artifact remains advisory and separate from a checked proof delivery. Historical checkpoints can omit these new fields; the context then has no invented summary or artifact. - -For a temporary dependency or Lead decision, a child saves its draft and notes, calls `yield(reason)` and returns. The host confirms writer shutdown before marking the task paused. Lead can adopt needed results and use `followup_task` to continue in the same worktree and thread, with the original delivery baseline and cumulative usage. A normal return completes the investigation, and a submitted proof enters checking. - -Any configured token, turn or solving-time allowance is shared by the run. The default is unlimited and usage is recorded independently of limits. Token caps govern subsequent requests based on observed receipts, so an admitted request may finish beyond the cap. Removing a saved token limit on resume requires `--max-total-tokens 0`. - -A child saves its sources, calls submit with exact declarations and returns. Submission and yield also checkpoint at the next unpaid request boundary, after the current paid response and tool group settle; submission enters checking, while yielding retains the task for resume. The host confirms writer shutdown, freezes those bytes and checks the delivery independently. Adopt defaults to Lead and queues integration. Lead saves sources and notes before requesting it; a pending Lead adoption triggers an automatic checkpoint before the next model request. Lead normally saves the complete proof and returns for independent checking. Lead can call `finish(summary)` after saving to request early handoff. Remaining holes or errors return normal feedback. The paid response and its tools finish and usage settles before confirmed writer shutdown; the host then freezes sources, rechecks and integrates the delivery and continues the saved thread. No token, time or turn allowance is added. Adoption into an idle child also queues and returns immediately; its safe work loop integrates before dispatching the next assignment, allowing native messages and interruption during slow checking. Lead can send the consumer instructions after requesting adoption and inspect the resulting status and feedback. Changed source versions, conflicts or failed checks return feedback. Checked declarations and completed adoptions never replace independent whole-problem acceptance. - -`send_message` binds the sender to the issuing native thread. Use `/root` for Lead and canonical paths or native IDs for peers. Relative paths follow Codex resolution. - -For native teams, `result.teamContributions` and `inspect` distinguish checked declarations and their adoption from use in each original proof. The report ties a delivered source version to its transfer into Lead's worktree and to final Lean evidence. Where the evidence permits, it distinguishes a delivered target proof, a direct reference, an indirect reference, and a declaration absent from the proof's references. An older receipt may establish a reference without its depth; missing or ambiguous evidence stays unknown. Member messages are separate advisory records, not proof of adoption or mathematical use. +For CLI runs, `--skill-expert-cards-file FILE` freezes a JSON array of cards with string fields `assetId`, `version`, `digest` (the release SHA-256), `name`, `summary` and `knowledge`. Lead can read the cards in the local tool help and point a member to relevant material. Cards supply background. -For long declarations, `inspect` returns a preview for each source change. Pass the same `deliveryId`, its `changeIndex` and `offset: nextOffset` to read the next page at the fixed commit without adopting it. Native spawn evidence distinguishes a fresh thread, a thread with parent history and an unknown history. A parent's inspection before a full-history fork is recorded as possible exposure through the parent. It is neither a direct read by the child nor proof that the source reached the model after context compaction. +Lead assigns at most one writer to each file at a time. When the problem has one editable proof file, one member or Lead writes it while others can research or review. Members use separate scratch files for probes, run local Lean checks and send their findings through Codex. The sources are already in the shared checkout when a member returns. Lead waits for the remaining members to finish or interrupts them before returning. Once the host confirms the writer process namespace stopped, it freezes the sources and runs independent Lean acceptance on the original targets. -Team writers use Linux bubblewrap isolation with separate PID namespaces. On recovery, the host uses saved process identities to confirm previous writers stopped before reusing their sources. Native threads, messages, tasks, delivery identities and adoption progress persist on resume. Lead explicitly reassigns interrupted work. Pending proof checks and adoption use their saved source identities. An unconfirmed writer stop blocks further use of that workspace. +`--max-turns` counts the host's dispatches to Lead. The elapsed-time limit applies to the whole run. A finite shared token budget requires a metered Responses profile such as the default Sub2API profile or the Web relay. They count Lead and member requests and block new ones when the threshold is reached. Requests already admitted can finish. A direct Responses profile can run a team without a finite token budget and reports incomplete usage. The direct Westlake Chat bridge supports solo runs. -Deferred or rejected source drafts keep their original delivery baseline across assignments, so a corrected helper remains transferable. A stopped child can adopt checked peer work while retaining its own unpublished draft. The host merges against fixed commits, preserves the child's draft and baseline, tracks adopted peer declarations and freshly checks the subsequent combined delivery; the child still names all its own unpublished declarations. Each submit accepts up to 32 declarations. For larger sets assembled by the host, source changes and duplicates are checked across the full set. Each declaration receives an independent Lean check against the same frozen source and environment. Conflicts and unconfirmed writer shutdown remain explicit failures. Successful deliveries advance the baseline. Lead adoption completion durably records the next source freeze. If the host exits before whole-proof checking, resume verifies a complete adopted original candidate before admitting another model turn, including when the turn allowance is exhausted. +## Historical AgentControl teams -Child completion and its proof nomination are saved in one transition. A durable submit acknowledged before a crash is also recovered when the final model response was not saved: after confirming writer shutdown, the host freezes and checks the nomination while leaving the interrupted task's status truthful. Historical completion-before-pending checkpoints are repaired only when their fixed source commit is still the current HEAD. The run inspection includes the same bounded runtime overview, fresh aggregate usage, task allowances, pending delivery identities and message provenance; these observations never confer original-problem acceptance. +Current TheoremOS can inspect archived teams and read their checked evidence. To resume or reproduce a saved AgentControl run, use the revision and executable pinned by that run. The local branch `archive/isolated-codex-teams` (`c9439d06`) preserves the per-member worktree implementation, patched Codex build, license notices and test suite. ## Skill and host responsibilities @@ -120,7 +70,7 @@ First installation copies into advisory scratch, checks the complete directory i Precise command examples are generated at `.scratch/theoremos-help.md`, using the existing local-help implementation. References route to this help and existing command `--help`; they do not maintain a second tool registry. Research sources, probes and public notes stay in the existing worktree and scratch storage. Internal chain of thought is neither required nor treated as an artifact. -Skill, team and native-baseline preparation save the Lean project location at `.scratch/worker-project.json`, so `check-lean --worktree` and other shared project tools work without a cooperative assignment. Older cooperative workspaces retain their `COOPERATION.json` fallback. The location is advisory; canonical paths, frozen source policies and environment validation still apply. Team help omits the cooperative-only `research-observe` entry point and uses the team submission interface. +Skill, team and native-baseline preparation save the Lean project location at `.scratch/worker-project.json`, so `check-lean --worktree` and other shared project tools work without a cooperative assignment. Older cooperative workspaces retain their `COOPERATION.json` fallback. The location is advisory; canonical paths, frozen source policies and environment validation still apply. Team help omits the cooperative-only `research-observe` entry point. It describes shared checkout collaboration. Single Skill research, complete Skill workflows and common-guidance/native comparisons generate optional tool references through the same `researchToolGuide.ts` implementation. It selects the actual projected executable and available corpus, knowledge and library resources. Complete workflows reuse the existing context compiler for tasks, consumers, required feedback, routes, definitions, families and fixed-source review. Workflow guidance and comparison guidance retain distinct purposes. The shared reference does not enable native delegation. The durable writer avoids rewriting unchanged help bytes. @@ -164,7 +114,6 @@ After successful host persistence, consumption is marked completed in host-owned Only explicitly classified submission-content errors and deterministic proof failures produce correctable rejection feedback. Host filesystem, Git, source-integrity and verifier-initialization exceptions propagate with the pending request retained; they do not consume the helper or start a mathematical correction turn. -Within a native team run, an unchanged declaration submission can return its previous deterministic Lean rejection. The host first checks ownership and the proposed patch, then matches the problem, project and baseline trees, declaration list, verifier settings and toolchain. A changed type, dependency or environment triggers a new check. The diagnostic identifies reuse; it does not count as a new Lean receipt. Timeouts and infrastructure failures are retried normally. The cache is local to the running host process. The existing knowledge interface imports this sidecar alongside legacy cooperative records: @@ -201,7 +150,7 @@ Saved records of the old fixed task graph, `host-tools` teams and `theoremos_inv ## Web workflow -New collaborative Web proof requests use the Codex native team. Capacity is 2–8 including Lead. Web starts one host Lead and requires a Codex provider and a worker image with both `org.theoremos.native-agent-control=v1` and `org.theoremos.native-team-workflow=v1`. The runner starts the image ID it checked. The owner can enable initial route approval for direct Lean input and after natural-language formalization. Historical cooperative requests can still be viewed, including their saved plan and approval records. Resuming them requires the original service and Worker versions. +New collaborative Web proof requests use the shared Codex team on a worker image labeled `org.theoremos.native-team-workflow=v2`. The runner starts the verified image ID. Historical v1 images are used with their archived runtime. The owner can enable initial route approval for direct Lean input and after natural-language formalization. Historical cooperative requests can still be viewed with their saved plan and approval records. Resuming them requires the original service and worker versions. The Skill view displays the researcher and declaration source, full type, premises, checked commit, environment and receipt references. Recorded evidence requires a fresh consumer check. Large collections report omitted declaration records. Single researchers keep their declaration workflow. Capture and archive remain supported. Context builders use the host-projected agent tools, including when Docker hides application source. @@ -209,8 +158,6 @@ The Skill view displays the researcher and declaration source, full type, premis | 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 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. | @@ -228,4 +175,4 @@ The 2026-11-16 real-model Putnam 1963 A4 diagnostic used runtime `7284f3b`, `dee Historical archives can retain coordination decisions, observations and presentation identities. These remain recorded data and advance neither an inbox cursor nor a Lead decision. Current team execution does not use them to require acknowledgments, restrict tools or schedule coordination-only handoffs. -Deterministic source-policy rejection is corrective feedback, including exact outside-ownership paths when available. Team members retain invalid draft files and notes in their own workspace, clear the rejected nomination and can receive an explicit correction assignment against the last actual source commit. Invalid drafts create no proof/research acceptance artifact. Lead receives the same precise feedback and can correct its workspace; arbitrary Git, I/O and environment faults retain their error behavior. +Deterministic source-policy rejection is corrective feedback, including exact outside-ownership paths when available. Lead receives the source-policy feedback and can correct the shared workspace. Git, I/O and environment faults retain their error behavior. diff --git a/docs/harness-portability.md b/docs/harness-portability.md index 317bb741..ed132d06 100644 --- a/docs/harness-portability.md +++ b/docs/harness-portability.md @@ -4,6 +4,6 @@ The CLI and workbench use Codex to run proofs, formalize statements, review evid For CLI runs, use `--codex FILE` or `--harness-executable FILE` for a custom binary. Use `--harness-profile DIR` to pin an explicit profile. The existing executable and configuration fingerprints remain compatible with saved Codex runs. -A solo proof can use the standard Codex binary. A proof-writing team uses the project's Codex build to link native delegation to isolated proof worktrees, checked handoffs and the shared budget. The host freezes the problem and runs a separate Lean check before accepting a proof. See the [proof workflow](codex-skill-runtime.md). +New solo and team runs use standard Codex. A team shares one proof checkout, and the host independently checks all original targets after the team stops. Use a Responses profile for team runs. The default Sub2API profile and the Web Responses relay support a shared token limit. Other direct Responses profiles have no team-wide token accounting. See the [proof workflow](codex-skill-runtime.md). Saved runs from retired executors remain readable. To continue one, run the harness revision that created it with its original configuration. diff --git a/docs/solver-modules.md b/docs/solver-modules.md index 2966f830..6981ef0e 100644 --- a/docs/solver-modules.md +++ b/docs/solver-modules.md @@ -24,7 +24,7 @@ M1–M5 表示运行时的决策边界,不是五个依次执行的解题步骤 | `src/solver/skillProofLifecycle.ts` | 管理单人 Skill 工作区的停写、源码冻结与待检查证明恢复 | | `src/solver/researchUsage.ts` | 管理当前模型轮次和会话的用量事件、请求准入与收据结算 | | `src/solver/usageBudget.ts` | 计算累计用量与共享预算状态,不执行模型或证明检查 | -| `src/solver/agentTeam.ts` | 把 Codex 原生团队连接到各自的隔离工作树和证明交付,保存任务与成果来源 | +| `src/runtime/codexSession.ts` | 启动 Codex 原生团队,成员使用同一个求解工作区 | | `src/math/verifier.ts` | 核对固定源码与目标身份,执行 Lean 检查和官方验收,生成回执 | | `src/math/verifierCheckout.ts` | 负责验证工作树的创建与回收;失败、异常和取消均进入同一清理路径 | @@ -159,7 +159,7 @@ seed 中没有可复用的已证声明时,M2 的可选 `closeTask` 会在模 ## 提案如何进入证明 -当前原生团队由 Codex Lead 分工,成员通过[团队接口](../src/solver/agentTeam.ts)交付研究结果;[研究产物实现](../src/solver/agentTeamResearch.ts)负责保存与读取研究笔记。完整流程见[原生团队协议](codex-skill-runtime.md#agent-organized-proof-writing-team)。 +当前原生团队由 Codex Lead 按文件分工。成员在共享工作区编辑、检查源码并通过 Codex 报告结果。完整流程见[原生团队协议](codex-skill-runtime.md#agent-organized-proof-writing-team)。 下面的 `lemmaRequests` 与 `handoffDecisions` 描述历史宿主调度协议,用于解读旧档案。旧提案处理器 `researchHandoffs.ts` 已在提交 `5d8643b4` 中移除;复现这套流程请使用对应运行固定的历史版本。 diff --git a/docs/usage.md b/docs/usage.md index bb77bebb..aa3129c7 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -101,7 +101,7 @@ bun run math run \ --output "$MATH_RUN_ROOT/result.json" ``` -新建 Codex 运行默认使用原生团队,最多四人(含 Lead)。设置 `--plan-approval` 可在开工前审批 Lead 提交的路线。CLI 默认不限制解题时间、模型调度次数和 token 用量。需要限制时,可设置 `--max-run-seconds`、`--max-turns` 或 `--max-total-tokens`。Web worker 会传入该次运行的预算。运行向标准输出发送 JSON 进度事件,并将结果写入 `result.json`。 +新建 Codex 运行默认使用标准 Codex 的原生团队,最多四人(含 Lead)。每题只有一个工作目录。Lead 按文件分配写入责任,成员就地编辑和运行 Lean。整队停止后,宿主冻结源码并独立验收全部原始目标。设置 `--plan-approval` 可在开工前审批 Lead 提交的路线。CLI 默认不限制解题时间、模型调度次数和 token 用量。需要限制时,可设置 `--max-run-seconds`、`--max-turns` 或 `--max-total-tokens`。Web worker 会传入该次运行的预算。运行向标准输出发送 JSON 进度事件,并将结果写入 `result.json`。 首次配置环境时,可在上述命令末尾加 `--startup-only`,只检查准备条件,不调用模型。预检会创建运行状态;之后使用相同参数加 `--resume` 开始求解。 @@ -231,7 +231,7 @@ bun run math batch \ ## 协作方式 -新建协作由 Codex Lead 通过原生工具派工、通信和恢复任务。TheoremOS 提供隔离工作区、证明交付检查、成果采纳、共享预算和独立 Lean 验收。Lead 按题目选择角色和分工,团队人数参数设置名额上限。 +Codex Lead 通过原生工具派工和通信,并给每个文件指定一名写者。成员在共享工作区保存和检查源码,完成后向 Lead 汇报。宿主负责整个运行的隔离、预算和最终 Lean 验收。旧版逐成员交付与采纳的记录仍可读取。 ### 历史宿主调度器 @@ -306,8 +306,8 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 | 输出 | 内容 | | --- | --- | | `` | 最终结果、评测状态、证明提交、轮次与用量 | -| `.runtime/state.json` | 可恢复状态,包括任务图、负责人、固定版本、检查反馈和审阅 | -| `.runtime/worktree*` | 各 Agent 的独立求解工作区 | +| `.runtime/state.json` | 可恢复状态,包括固定版本、检查反馈和审阅 | +| `.runtime/worktree` | 本次求解的共享工作区 | | `.runtime/explanations//*/artifact/` | 每个原始目标的自动讲解 `proof.md` 与审核证据 `informalization.json` | | 标准输出 | JSON 进度事件 | @@ -332,7 +332,7 @@ Lead 的普通规划和初始规划执行 90 秒后收到保存提醒,120 秒 | `--continuation-manifest` | 无 | 新建时绑定显式历史附件;恢复时沿用同一只读快照 | | `--prepare-timeout-seconds` | `0` | 环境准备与依赖预编译预算 | | `--max-run-seconds` | `0` | 准备完成后的共享解题时间预算 | -| `--max-turns` | `0` | 所有 Agent 合计模型调度次数 | +| `--max-turns` | `0` | 宿主派发给 Lead 的轮数,新团队的子代理由 Codex 调度 | | `--max-total-tokens` | `0` | 全部角色累计的 provider 报告 token 阈值;`0` 不限。达到后停止新模型请求,在途请求仍可完成并产生超额 | | `--max-turn-seconds` | `0` | 单轮时间限制;停止写入后检查已保存源码 | | `--proof-timeout-seconds` | `0` | 单次宿主证明检查预算;超时保存可恢复检查点 | @@ -342,6 +342,8 @@ CLI 先用 `inspect --run RESULT --format plan` 查看待审路线和版本, `--prepare-timeout-seconds`、`--max-run-seconds`、`--max-turns`、`--max-turn-seconds`、`--proof-timeout-seconds` 与 `--evaluator-timeout-seconds` 在 CLI 中均默认为 `0`,表示不限。可以分别设置解题、证明检查和最终评测的时限。显式设置证明检查时限后,同一源码、任务和环境的检查超时会保留候选,恢复时逐次延长检查时间,最多 24 小时。 +共享团队的有限 token 预算需要可计量的 Responses profile,例如默认 Sub2API 网关或 Web 中继。直接连接的 Responses profile 可用于不限 token 的团队运行,并标记用量不完整。直连 Westlake Chat 可用于单人运行。 + `--max-total-tokens` 包含规划、研究、证明和审阅角色,按跨线程累计消费计算;恢复时继续使用历史用量,省略参数时保留已存额度。它依据 provider 的事后通知阻止新请求,不能保证并发在途消费不超过阈值。报告保留超额与用量完整性;有限额度下缺失已执行请求的用量会停止继续派发。旧运行未记录逐轮用量完整性,不能直接当作严格 token 对照。默认不限 token,不为已有长跑增加停止条件。原生 provider 的用量按完整 turn 记账:turn 被 `--max-turn-seconds` 截断时该轮用量记为不完整,有限额度会以 usage-unavailable 停止;需要有限 token 额度时应同时放宽 `--max-turn-seconds`(或设为 0)。 ### 环境配置 @@ -413,7 +415,7 @@ bun run math check-lean \ `check-lean` 默认超时为 `0`(等待完成),保留失败退出码和最早错误;其诊断仅用于局部修复。 -旧任务图的 `proof-search` 与 `research-observe` 依赖固定的 worker assignment。复现实验时使用对应历史运行时。原生团队可在独立工作树运行 Lean 探针,通过 Codex 消息分享诊断,并保存可复查的源码与研究笔记。 +旧任务图的 `proof-search` 与 `research-observe` 依赖固定的 worker assignment。复现实验时使用对应历史运行时。原生团队在同一个工作区运行 Lean 探针,通过 Codex 消息分享诊断,并保存可复查的源码与研究笔记。 数学 worker 的临时目录为工作树根的 `.scratch/tmp`,由 shell 的 `TMPDIR` 指向;`/tmp` 在沙箱内只读。创建探针前运行 `mkdir -p "$TMPDIR"`,并把临时 Lean 文件、备份和诊断输出保存在该目录。宿主检查前会清理 `.scratch`,可复用代码和结论需先保存在根目录 `RESEARCH.md` 或已有的 owned Lean 文件中。 @@ -438,7 +440,7 @@ bun run math check-lean \ ## 架构与开发 -运行入口在 [run.ts](../src/solver/run.ts),会话执行和恢复在 [research.ts](../src/solver/research.ts),原生团队的隔离与交付在 [agentTeam.ts](../src/solver/agentTeam.ts)。旧任务图实验的契约与验收边界见[解题模块与交接协议](solver-modules.md)。 +运行入口在 [run.ts](../src/solver/run.ts),会话执行和恢复在 [research.ts](../src/solver/research.ts),原生团队接入在 [codexSession.ts](../src/runtime/codexSession.ts)。旧团队档案仍可查看。逐成员隔离的 AgentControl 团队请用 `archive/isolated-codex-teams` 分支和原先固定的运行环境续跑。旧任务图实验的契约与验收边界见[解题模块与交接协议](solver-modules.md)。 | 模块 | 职责 | 实现 | | --- | --- | --- | diff --git a/examples/imo2026/README.md b/examples/imo2026/README.md index 84c50cfc..a8ef308f 100644 --- a/examples/imo2026/README.md +++ b/examples/imo2026/README.md @@ -41,8 +41,7 @@ zstd-capable `squashfuse`/`snapfuse` and complete the actual startup preflight. Install dependencies with `bun install --frozen-lockfile` from the project root. Authenticate your existing Codex profile separately. The default profile is `~/.config/deepscientist/math-sol-codex`; `CODEX_HOME` can select another existing -profile with access to the configured model. Use the -[native team backend](../../scripts/codex-backend/README.md) for this example. +profile with access to the configured model. Team runs use the [standard Codex CLI](../../docs/codex-skill-runtime.md#agent-organized-proof-writing-team). The [environment template](math.env.example) describes tool and cache settings. Copy it to a local file, replace the paths, and set diff --git a/package.json b/package.json index fcf8e619..23ba9e57 100644 --- a/package.json +++ b/package.json @@ -113,7 +113,6 @@ "test:web-admin": "bun scripts/frontend.ts run bash -c 'bun scripts/e2e/test-web-admin.ts'", "smoke:web-precheck": "bun scripts/smoke-web-precheck.ts", "test": "vitest run", - "test:codex-backend": "bun scripts/test-codex-backend.ts", "test:solver-reliability": "THEOREMOS_TEST_REQUIRE_LEAN=1 vitest run --maxWorkers=4 tests/leanTestEnvironment.test.ts tests/continuationInput.test.ts tests/continuationContext.test.ts tests/continuationSearch.test.ts tests/taskSourceProjection.test.ts tests/taskTypePreflight.test.ts tests/leanTypeDiagnostics.test.ts tests/leanTypeDiagnosticsEnvironment.test.ts tests/verificationCheckpoint.test.ts tests/proofReuseEnvironment.test.ts", "test:formalization": "bun scripts/test-formalization.ts", "typecheck": "tsc --noEmit", diff --git a/research/PROTOCOL.md b/research/PROTOCOL.md index f85f1399..00d1f763 100644 --- a/research/PROTOCOL.md +++ b/research/PROTOCOL.md @@ -2,7 +2,7 @@ Version: v1 Status: Implemented(隔离分支的本地功能验收;未启用真实求解) -Updated: 2026-12-03 +Updated: 2026-12-05 ## 已确认的目标 @@ -10,6 +10,8 @@ Updated: 2026-12-03 依据:[决策 0001](decisions/0001-agent-led-skill-multiagent.md)、[决策 0002](decisions/0002-persistent-proof-workers.md)。 +新团队共享每道题的求解工作区。Lead 按文件分工,成员直接保存源码并用 Lean 检查。宿主在全队停写后冻结源码、独立验收全部原始目标。以下逐成员工作区、交付和采纳协议适用于历史团队。见[决策 0016](decisions/0016-no-per-agent-worktree.md)。 + 新版解题协作使用 Codex 原生团队,默认由 Lead 自主推进。开启人工路线审核时,Lead 发布固定初始路线,获得这一版本的批准后才开工。宿主仍核验全部原始 Lean 目标。旧调度的档案继续可读,续跑和对照实验使用各自固定的历史版本。见[决策 0010](decisions/0010-native-team-runtime-only.md)。 ## 角色与成果语义 @@ -17,7 +19,7 @@ Updated: 2026-12-03 | 对象 | 职责与含义 | | --- | --- | | Lead Agent | 决定数学分解、分工、后续任务、路线调整及成果采纳。 | -| 子 Agent | 在独立隔离工作区持续研究、编写 Lean、保存笔记并交付成果;可以继续接收后续任务。 | +| 子 Agent | 在本题共享工作区中按 Lead 分配的文件研究、编写 Lean、保存笔记并通过原生消息汇报;可以继续接收后续任务。 | | 宿主 | 执行 Agent 提出的合法协作操作,保存状态并检查源码、预算和交付证据;独立检查后整合成果和验收原题。 | | 异步交付 | 一份成果就绪后即可向 Lead 提供,无需等待同批其他 Agent 全部结束。 | | 共同研究摘要 | Lead 发布的带修订号和时间的路线、判断及缺口摘要,向成员通知并在上下文中明确标为 advisory;不是已检查的数学结论。 | @@ -58,9 +60,9 @@ Updated: 2026-12-03 数学工具的首轮功能验收在本地原生团队进行:检查 Lead 和成员能否按任务选用当前环境中的工具、实际执行并使用结果。Web worker 的依赖与部署单独验收;本地协议回放也不能说明真实模型的选用质量。另以两道不点名工具的新题观察真实模型,一题适合精确计算、一题直接 Lean 证明即可,分别报告自主选用与整题验收。见[决策 0006](decisions/0006-local-native-math-tools-first.md)、[决策 0007](decisions/0007-blind-local-tool-selection.md)。 -当前先验收协作功能。以下场景由已确认目标和既有验收保证导出;本地验证使用受控会话和实际协议进程,不调用真实模型。 +当前先验收协作功能。新团队的成员共享一个工作区,文件写入由 Lead 分配,整队停止后由宿主独立验收。以下场景由已确认目标和既有验收保证导出;本地验证使用受控会话和实际协议进程,不调用真实模型。 -1. Lead 可派发至少两个并行研究任务;子 Agent 有各自的会话和可写工作区,能保存不同的 Lean 证明。 +1. Lead 可派发至少两个并行研究任务;子 Agent 有各自的会话,在共享工作区中按文件独占写入,能保存并检查 Lean 证明。 2. 一个子 Agent 先完成时,Lead 可接收它的交付并安排后续工作,另一子 Agent 可继续研究。 3. 子 Agent 能接收后续消息或任务并继续工作;已保存源码、笔记和交付状态支持恢复。 4. 一个子 Agent 的成果经当前检查后可供另一个 Agent 继续使用,最终由宿主整合并验收原题。 @@ -74,13 +76,15 @@ Updated: 2026-12-03 下一轮求证流程比较以自主完成整题为主。求证从冻结题面和固定的通用环境开始,由宿主独立验收全部原始 Lean 目标。首条经检查且可复用的引理及其耗时用于定位瓶颈。题目的现成证明、证书与定向提示留作离线对照。依据[决策 0008](decisions/0008-autonomous-full-proof-endpoint.md)。 -## 实现与接口 +## 历史实现与接口 + +以下接口说明保留用于读取旧档案和历史回放。新团队使用原生 Codex 的 spawn_agent、send_message、followup_task、wait_agent 和 interrupt_agent,并在共享工作区写入。 新增 `--research-mode skill --skill-delegation team --skill-max-agents 3`,总容量含 Lead,接受 2–8、CLI 默认 4;最多 1 名 Lead 与 7 名成员。该路径使用一个宿主 Lead(`--workers 1 --coordination independent`),当前依赖 Codex 动态工具和 Linux bubblewrap。既有 cooperative 和 read-only 调查路径继续独立保留。 `theoremos_team` 有十六个操作:`spawn`、`assign`、`budget`、`resume`、`cancel`、`publish`、`message`、`poll`、`wait`、`history`、`inspect`、`inspect-research`、`submit`、`yield`、`adopt`、`stop`。Lead 可用十四个(除 submit/yield),子 Agent 可用八个(message/poll/wait/history/inspect/inspect-research/submit/yield),仍不能派工或自行采纳。完整参数见[固定 Skill 协作约定](../skills/theoremos-research/references/parallel-work.md),运行入口见[运行文档](../docs/codex-skill-runtime.md)。 -子 Agent 保留独立 Git worktree、原生 thread、任务与消息;每次交付均先停止写者,再冻结源码、检查精确 theorem/lemma 声明并保存证据。Lead 可以查看交付的声明、源码片段和检查证据,再选择采纳到自己或空闲子 Agent。Lead 采纳在其返回并释放写者后执行,整合使用临时 worktree 和新的 Lean 检查,不覆盖正在写入的工作区。采纳到空闲子 Agent 也先排队返回,由该成员的安全工作循环完成整合后再派下一任务,慢检查期间消息和取消操作仍可处理。此操作不授予整题验收。 +历史 AgentControl 团队的独立 Git worktree、交付和采纳协议保存在 archive/isolated-codex-teams 分支。新团队使用共享工作区,Lead 按文件分配唯一写者,成员就地检查并汇报。整队停写后,宿主冻结源码并独立验收全部原始目标。历史协议不适用于新团队,也不授予整题验收。 `yield(reason)` 保存当前任务后请求停写,确认停止后才进入 paused。Lead 用 `resume(agentId,taskId)` 恢复同一任务,区别于 assign 新建后续任务和 cancel 撤销旧任务。spawn/assign 可带 `budget:{tokens?,turns?}`;Lead 用 budget 替换任务额度或 `leadReserve:{tokens?,turns?}`,已消耗量按原 taskId 累计,调整额度不会自动恢复任务。提供的额度对象整体替换旧值,空对象解除该局部限制或保留量。总运行额度仍适用,token 限制依据已观察回执控制后续请求准入,已准入请求可能超出额度。观察投影区分实际额度、累计用量和回执不可用,不把资源暂停当作数学失败。 diff --git a/research/decisions/0002-persistent-proof-workers.md b/research/decisions/0002-persistent-proof-workers.md index 032b1895..74117cfd 100644 --- a/research/decisions/0002-persistent-proof-workers.md +++ b/research/decisions/0002-persistent-proof-workers.md @@ -1,7 +1,7 @@ --- id: "0002" title: 子 Agent 在隔离工作区持续产出证明,先验收协作功能 -status: accepted +status: superseded by 0016 date: "2026-11-16" decided_by: 用户(本次对话 Q2、Q3) related: diff --git a/research/decisions/0016-no-per-agent-worktree.md b/research/decisions/0016-no-per-agent-worktree.md new file mode 100644 index 00000000..2e4c989d --- /dev/null +++ b/research/decisions/0016-no-per-agent-worktree.md @@ -0,0 +1,17 @@ +--- +id: "0016" +title: 新团队不要求每个成员有独立 worktree +status: accepted +date: "2026-12-05" +decided_by: 用户 +related: + - research/PROTOCOL.md + - research/decisions/0002-persistent-proof-workers.md + - research/decisions/0010-native-team-runtime-only.md +--- + +# 0016 — 新团队不要求每个成员有独立 worktree + +用户确认团队内的子 Agent 无需各自绑定一个 Git worktree,以降低 TheoremOS 接入 Codex 原生团队的复杂度。本决定替代 0002 对每个成员独立工作区的要求。成员可以继续编写 Lean 和交付成果,Lead 自主分工,宿主独立验收整题。 + +每个求解运行仍有自己的工作区。Lead 为各个文件安排一名写者,成员直接保存源码、运行本地 Lean 检查并汇报。宿主在整队停写后冻结共享源码,独立验收整题。已有证据仍对应产生该证据的运行方式。 diff --git a/scripts/build-codex-backend.sh b/scripts/build-codex-backend.sh deleted file mode 100755 index df84cf99..00000000 --- a/scripts/build-codex-backend.sh +++ /dev/null @@ -1,253 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Use host build tools ahead of optional user wrappers (for example a Python -# launcher that executes in a container without this source checkout). -export PATH="/usr/bin:/bin:$PATH" - -usage() { - cat <<'USAGE' -Usage: scripts/build-codex-backend.sh --source DIR --downloads DIR --output DIR [--jobs N] [--host-tools DIR] [--prepare-only] - -Fetch the pinned official Codex release, apply the checked-in build patches, -and build Codex and its Code Mode host with locked dependencies and pinned Rust. -All target files, logs, both executables and their provenance stay under --output. ---prepare-only verifies the upstream identity without applying the patch. ---host-tools uses an extracted Debian sysroot for build-only native dependencies. -No global Codex profile or default Rust toolchain is changed. -USAGE -} - -source_dir= downloads_dir= output_dir= host_tools= jobs=16 prepare_only=0 -while (($#)); do - case "$1" in - --source|--downloads|--output|--jobs|--host-tools) - if (($# < 2)); then usage >&2; exit 2; fi - case "$1" in - --source) source_dir=$2 ;; - --downloads) downloads_dir=$2 ;; - --output) output_dir=$2 ;; - --jobs) jobs=$2 ;; - --host-tools) host_tools=$2 ;; - esac - shift 2 ;; - --prepare-only) prepare_only=1; shift ;; - --help|-h) usage; exit 0 ;; - *) usage >&2; exit 2 ;; - esac -done -if [[ -z $source_dir || -z $downloads_dir || -z $output_dir || ! $jobs =~ ^[1-9][0-9]*$ ]]; then - usage >&2; exit 2 -fi - -script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) -pin_file=$script_dir/codex-backend/upstream.json -pin() { - python3 - "$pin_file" "$1" <<'PY' -import json, sys -with open(sys.argv[1], encoding="utf-8") as stream: - print(json.load(stream)[sys.argv[2]]) -PY -} -repository=$(pin repository) -tag=$(pin tag) -revision=$(pin revision) -tag_object=$(pin tagObject) -toolchain=$(pin toolchain) -lock_digest=$(pin cargoLockSha256) -derived_lock_digest=$(pin derivedCargoLockSha256) -lock_patch_file=$script_dir/codex-backend/$(pin lockPatch) -lock_patch_digest=$(pin lockPatchSha256) -patch_file=$script_dir/codex-backend/$(pin patch) -package=$(pin package) -binary=$(pin binary) -code_mode_host=codex-code-mode-host -profile=$(pin profile) - -mkdir -p -- "$downloads_dir" "$output_dir" "$(dirname -- "$source_dir")" -downloads_dir=$(cd -- "$downloads_dir" && pwd) -output_dir=$(cd -- "$output_dir" && pwd) -download=$downloads_dir/codex-$tag -if [[ ! -e $download ]]; then - git clone --depth 1 --single-branch --branch "$tag" "$repository" "$download" -fi -if [[ $(git -C "$download" rev-parse "refs/tags/$tag") != "$tag_object" || - $(git -C "$download" rev-parse "refs/tags/$tag^{commit}") != "$revision" ]]; then - echo 'Official Codex tag does not match the pinned release.' >&2; exit 1 -fi -if [[ ! -e $source_dir ]]; then - git -C "$download" worktree add --detach "$source_dir" "$revision" -fi -source_dir=$(cd -- "$source_dir" && pwd) -if [[ $(git -C "$source_dir" rev-parse HEAD) != "$revision" ]]; then - echo 'Source checkout HEAD differs from the pinned Codex revision.' >&2; exit 1 -fi -actual_lock=$(sha256sum "$source_dir/codex-rs/Cargo.lock") -if [[ ${actual_lock%% *} != "$lock_digest" && ${actual_lock%% *} != "$derived_lock_digest" ]]; then - echo 'Codex Cargo.lock differs from the pinned upstream and derived lockfiles.' >&2; exit 1 -fi -rustup run "$toolchain" rustc --version -if ((prepare_only)); then - echo "Pinned upstream source ready: $source_dir" - exit 0 -fi - -if [[ ! -s $patch_file ]]; then - echo "AgentControl patch is missing: $patch_file" >&2; exit 1 -fi -actual_lock_patch=$(sha256sum "$lock_patch_file") -if [[ ${actual_lock_patch%% *} != "$lock_patch_digest" ]]; then - echo 'Derived lock patch differs from its frozen digest.' >&2; exit 1 -fi -if [[ ${actual_lock%% *} == "$lock_digest" ]]; then - git -C "$source_dir" apply --check "$lock_patch_file" - git -C "$source_dir" apply "$lock_patch_file" -fi -if ! git -C "$source_dir" apply --reverse --check "$patch_file" 2>/dev/null; then - git -C "$source_dir" apply --check --index "$patch_file" - git -C "$source_dir" apply --index "$patch_file" -fi -# Build precisely the reviewable patch. Extra edits are preserved and rejected, -# so re-running this script never resets a developer's source worktree. -# Match the checked-in index width even when a shallow clone uses shorter IDs. -git -C "$source_dir" diff --binary --abbrev=8 --no-ext-diff HEAD -- . ':(exclude)codex-rs/Cargo.lock' > "$output_dir/agent-control-source.patch" -git -C "$source_dir" diff --binary --abbrev=8 --no-ext-diff HEAD -- codex-rs/Cargo.lock > "$output_dir/derived-lock-source.patch" -if ! cmp -s "$patch_file" "$output_dir/agent-control-source.patch" || - ! cmp -s "$lock_patch_file" "$output_dir/derived-lock-source.patch" || - [[ -n $(git -C "$source_dir" ls-files --others --exclude-standard) ]]; then - echo 'Source worktree differs from the checked-in build patches.' >&2; exit 1 -fi -git -C "$source_dir" diff --binary --abbrev=8 --no-ext-diff HEAD > "$output_dir/source.patch" - -export CARGO_TARGET_DIR=$output_dir/target -export CARGO_PROFILE_DEV_DEBUG=$(pin devDebug) -export CARGO_INCREMENTAL=$(pin incremental) -if [[ -n $host_tools ]]; then - host_tools=$(cd -- "$host_tools" && pwd) - host_arch=$(cc -dumpmachine) - export PKG_CONFIG=$host_tools/usr/bin/pkgconf - export PKG_CONFIG_SYSROOT_DIR=$host_tools - export PKG_CONFIG_LIBDIR=$host_tools/usr/lib/$host_arch/pkgconfig:$host_tools/usr/share/pkgconfig - export LD_LIBRARY_PATH=$host_tools/usr/lib/$host_arch${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} - export CFLAGS="${CFLAGS:+$CFLAGS }-I$host_tools/usr/include/$host_arch" - export CXXFLAGS="${CXXFLAGS:+$CXXFLAGS }-I$host_tools/usr/include/$host_arch" - "$PKG_CONFIG" --modversion openssl -fi -# Cargo resolves all workspace manifests, including the separate V8 host. Its -# default submodule fetch downloads every Chromium branch. Keep the exact -# gitlink commits while fetching only their required history. -read -r metadata_repository metadata_revision < <(python3 - "$pin_file" <<'PY' -import json, sys -metadata = json.load(open(sys.argv[1]))["submoduleMetadata"] -print(metadata["repository"], metadata["revision"]) -PY -) -metadata_dir=$downloads_dir/codex-rusty-v8-$metadata_revision -if [[ ! -d $metadata_dir/.git ]]; then - git init --quiet "$metadata_dir" - git -C "$metadata_dir" fetch --depth 1 "$metadata_repository" "$metadata_revision" - git -C "$metadata_dir" checkout --detach "$metadata_revision" -fi -if [[ $(git -C "$metadata_dir" rev-parse HEAD) != "$metadata_revision" ]]; then - echo 'V8 submodule metadata differs from the locked dependency revision.' >&2; exit 1 -fi -python3 - "$metadata_dir" "$output_dir/submodule-pins.json" <<'PY' -import json, pathlib, subprocess, sys -source, output = sys.argv[1:] -git = lambda *arguments: subprocess.check_output(["git", "-C", source, *arguments], text=True).strip() -pins = {} -for line in git("config", "-f", ".gitmodules", "--get-regexp", r"^submodule\..*\.path$").splitlines(): - key, path = line.split(maxsplit=1) - entry = git("ls-tree", "HEAD", "--", path).split() - if entry[:2] != ["160000", "commit"]: - raise SystemExit("V8 submodule is missing its pinned gitlink: " + path) - pins[git("config", "-f", ".gitmodules", "--get", key.removesuffix(".path") + ".url")] = entry[2] -pathlib.Path(output).write_text(json.dumps(pins, indent=2, sort_keys=True) + "\n") -PY -build_tools=$output_dir/build-tools -mkdir -p -- "$build_tools" -export THEOREMOS_BUILD_REAL_GIT=$(command -v git) -export THEOREMOS_BUILD_SUBMODULE_PINS=$output_dir/submodule-pins.json -ln -sfn -- "$script_dir/codex-backend/git-fetch-pinned.py" "$build_tools/git" -export PATH="$build_tools:$PATH" -export CARGO_NET_GIT_FETCH_WITH_CLI=true - -# Build the Code Mode host with the same V8 release pair as upstream Cargo CI. -# The crate's default download site does not publish this pair. -v8_version=$(python3 "$source_dir/.github/scripts/rusty_v8_bazel.py" resolved-v8-crate-version) -rust_target=$(rustup run "$toolchain" rustc -vV | awk '$1 == "host:" {print $2}') -v8_dir=$downloads_dir/codex-rusty-v8-$v8_version -v8_checksums=$source_dir/third_party/v8/rusty_v8_${v8_version//./_}.sha256 -v8_archive=librusty_v8_ptrcomp_sandbox_release_$rust_target.a.gz -v8_binding=src_binding_ptrcomp_sandbox_release_$rust_target.rs -mkdir -p -- "$v8_dir" -for artifact in "$v8_archive" "$v8_binding"; do - expected=$(awk -v name="$artifact" '$2 == name {print $1}' "$v8_checksums") - if [[ ! $expected =~ ^[0-9a-f]{64}$ ]]; then - echo "No pinned V8 asset: $artifact" >&2; exit 1 - fi - if [[ ! -f $v8_dir/$artifact ]] || ! sha256sum --check --status <<< "$expected $v8_dir/$artifact"; then - download_file=$(mktemp "$v8_dir/$artifact.XXXXXX") - if ! curl --fail --silent --show-error --location --retry 3 \ - "https://github.com/openai/codex/releases/download/rusty-v8-v$v8_version/$artifact" --output "$download_file" || - ! sha256sum --check --status <<< "$expected $download_file"; then - rm -f -- "$download_file" - echo "Could not fetch the pinned V8 asset: $artifact" >&2; exit 1 - fi - mv -f -- "$download_file" "$v8_dir/$artifact" - fi -done -export RUSTY_V8_ARCHIVE=$v8_dir/$v8_archive -export RUSTY_V8_SRC_BINDING_PATH=$v8_dir/$v8_binding - -build_log=$output_dir/build.log -echo "Building $package/$binary and $code_mode_host; log: $build_log" -if ! (cd -- "$source_dir/codex-rs" && rustup run "$toolchain" cargo build --locked \ - --profile "$profile" -p "$package" --bin "$binary" \ - -p "$code_mode_host" --bin "$code_mode_host" --jobs "$jobs") > "$build_log" 2>&1; then - tail -n 60 "$build_log" >&2 - exit 1 -fi -mkdir -p -- "$output_dir/bin" -# Codex resolves its companion next to the real executable, including when -# started through the runtime symlink. -for artifact in "$code_mode_host" "$binary"; do - install -m 755 "$CARGO_TARGET_DIR/debug/$artifact" "$output_dir/bin/$artifact.new" - mv -f -- "$output_dir/bin/$artifact.new" "$output_dir/bin/$artifact" -done -runtime_link=$script_dir/../out/codex-backend/codex -mkdir -p -- "$(dirname -- "$runtime_link")" -ln -sfn -- "$output_dir/bin/$binary" "$runtime_link" -python3 - "$pin_file" "$source_dir" "$output_dir" "$patch_file" "$jobs" "$runtime_link" "$host_tools" "$code_mode_host" <<'PY' -import datetime, hashlib, json, pathlib, subprocess, sys -pin_file, source, output, patch_file, jobs, runtime_link, host_tools, code_mode_host = sys.argv[1:] -pin = json.loads(pathlib.Path(pin_file).read_text()) -artifact = pathlib.Path(output, "bin", pin["binary"]) -companion = artifact.with_name(code_mode_host) -digest = lambda file: hashlib.file_digest(pathlib.Path(file).open("rb"), "sha256").hexdigest() -version = lambda command: subprocess.check_output(["rustup", "run", pin["toolchain"], *command], text=True).strip() -record = { - "schema": "theoremos.codex-backend-build.v1", - "builtAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), - "upstream": pin, "source": source, - "sourceRevision": subprocess.check_output(["git", "-C", source, "rev-parse", "HEAD"], text=True).strip(), - "patchSha256": digest(patch_file), "cargoLockSha256": digest(pathlib.Path(source, "codex-rs/Cargo.lock")), - "lockPatchSha256": digest(pathlib.Path(pin_file).parent / pin["lockPatch"]), - "sourcePatchSha256": digest(pathlib.Path(output, "source.patch")), - "executable": str(artifact), "executableSha256": digest(artifact), - "codeModeHost": str(companion), "codeModeHostSha256": digest(companion), - "rustc": version(["rustc", "--version", "--verbose"]), "cargo": version(["cargo", "--version"]), - "jobs": int(jobs), "targetDirectory": str(pathlib.Path(output, "target")), - "log": str(pathlib.Path(output, "build.log")), - "runtimeLink": str(pathlib.Path(runtime_link).absolute()), - "submodulePinsSha256": digest(pathlib.Path(output, "submodule-pins.json")), -} -if host_tools: - host_manifest = pathlib.Path(host_tools, "manifest.json") - record["hostTools"] = {"directory": host_tools, - "manifest": json.loads(host_manifest.read_text()) if host_manifest.exists() else None, - "manifestSha256": digest(host_manifest) if host_manifest.exists() else None} -pathlib.Path(output, "backend-build.json").write_text(json.dumps(record, indent=2) + "\n") -print(json.dumps({"executable": str(artifact), "sha256": record["executableSha256"], - "manifest": str(pathlib.Path(output, "backend-build.json"))})) -PY diff --git a/scripts/codex-backend/LICENSE.codex b/scripts/codex-backend/LICENSE.codex deleted file mode 100644 index 4606e72e..00000000 --- a/scripts/codex-backend/LICENSE.codex +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright 2025 OpenAI - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/scripts/codex-backend/NOTICE.codex b/scripts/codex-backend/NOTICE.codex deleted file mode 100644 index 2805899d..00000000 --- a/scripts/codex-backend/NOTICE.codex +++ /dev/null @@ -1,6 +0,0 @@ -OpenAI Codex -Copyright 2025 OpenAI - -This project includes code derived from [Ratatui](https://github.com/ratatui/ratatui), licensed under the MIT license. -Copyright (c) 2016-2022 Florian Dehau -Copyright (c) 2023-2025 The Ratatui Developers diff --git a/scripts/codex-backend/README.md b/scripts/codex-backend/README.md deleted file mode 100644 index 5dd4641f..00000000 --- a/scripts/codex-backend/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# TheoremOS Codex backend build - -`upstream.json` pins the official Codex tag, commit, lockfiles and Rust toolchain. -The build applies two reviewable patches: - -- `derived-lock.patch` aligns 174 local workspace package versions with the - release's `0.172.0` workspace version. The upstream lock already includes - `codex-rollout-trace` for `codex-app-server`. External dependencies, - sources and checksums are unchanged. -- `agent-control.patch` adds the TheoremOS protocol adapter to the official - AgentControl implementation. It also batches plugin manifest metadata requests - during native Skill discovery using the scan's filesystem permissions. The - nearest valid manifest still determines the namespace. If the filesystem - cannot serve the batch, discovery retries with individual requests. When - matching local filesystem permissions, the backend resolves the rule paths - and their depths once per operation. - -These patches are changes made by TheoremOS. The upstream code shown in them -comes from [OpenAI Codex at the pinned revision](https://github.com/openai/codex/tree/3d86e43b075adeba2193ec5c22ac92f55afd82e6). -This directory includes the upstream [Apache-2.0 license](LICENSE.codex) and -[NOTICE](NOTICE.codex), including its credit to Ratatui. Both files also ship in -the Web worker at `/opt/theorem-os/scripts/codex-backend/`. For a separate -distribution of the patched binary, include these files and the applicable -notices for the dependencies included in that build. - -Run from the repository root: - -```bash -scripts/build-codex-backend.sh \ - --source /data/lzh/workspace/projects/theoremos-codex-backend \ - --downloads /data/lzh/downloads \ - --output /data/lzh/workspace/outputs/theoremos-codex-backend-20261117 \ - --jobs 16 -``` - -Install the explicitly pinned toolchain with `rustup toolchain install 1.99.1 ---profile minimal` if needed. The script does not change the default toolchain, -Codex configuration or model credentials. `--prepare-only` fetches and verifies -the official source without applying patches or compiling. - -Native prerequisites include a C/C++ compiler, `pkg-config` and OpenSSL development -headers/libraries. When global packages are unavailable, pass `--host-tools DIR` -with Debian packages extracted into `DIR` using `dpkg-deb --extract`. This uses -the local `usr/bin/pkgconf`, multiarch headers, libraries and package metadata -only in the build subprocess. A local `manifest.json`, when present, is embedded -with its digest in the build provenance. The current Ubuntu 24.04 environment -uses `pkgconf-bin` and `libpkgconf3` version `1.8.1-2build1`, plus `libssl-dev` -and `libssl3t64` version `3.0.13-0ubuntu3.16`. - -Large asynchronous core tests require `RUST_MIN_STACK=8388608`, matching the -upstream Bazel test configuration. Set it only on the test subprocess. - -All Cargo targets, logs and binaries stay under `--output`. The build installs -`codex` and `codex-code-mode-host` together in `bin/` and records both digests in -`backend-build.json`. Keep the pair together when moving the backend. The local -`out/codex-backend/codex` link points to the built CLI. Existing sessions are not -restarted. Source edits beyond the checked-in patches are preserved and rejected, -so freeze the adapter patch before running a final build. - -The [Codex Backend Linux workflow](https://github.com/HuggingMath/theorem-os/actions/workflows/codex-backend-linux.yml) -publishes an x86-64 archive for Ubuntu 24.04. To archive a local build, pass its -output directory as the second argument. - -```bash -bash scripts/package-codex-backend.sh /path/to/packages /path/to/backend-build -``` - -The script matches both binaries and the adapter against the pinned build -record. The tarball includes the patch files, licenses and build record. The -workflow verifies the checksum after packaging and probes AgentControl and -Code Mode from the extracted archive against fixed loopback Responses. - -New team runs pin the executable's real path and digest and record -`agentTeam.transport: native-agent-control`. Startup failures are reported -through the native backend. Use a compatible provider profile such as the -Responses gateway. Resume native team checkpoints with their pinned backend. -Resume historical host-tool team checkpoints with the original TheoremOS build. - -After the ordinary headless runtime build, exercise the real binary with fixed -loopback Responses and independent process/workspace isolation: - -```bash -bun scripts/test-codex-backend.ts --executable out/codex-backend/codex \ - --output /data/lzh/workspace/outputs/theoremos-codex-backend-verification -``` - -This disposable fixture checks native spawn, full-history fork, attributed -messages, queue-only idle behavior, the first resumed request's mailbox order, -cold child resume, busy followup, effective task amendment, mailbox wakeup and -idle/active interruption. It confirms shutdown of every writer process. It does -not call a paid model or alter a running mathematical solve. -Mathematical nominations, source freezing, Lean checks and adoption remain host -operations; a native final answer does not create a proof delivery. - -Pass `--team-capacity` to exercise eight writers with seven simultaneous member -requests. Pass `--large-fork` to verify that an oversized full-history fork -returns a tool error and Lead can retry with `fork_turns: "none"`. Pass -`--web-provider` to exercise proof delivery through the generated Web provider -profile, including metered requests before and after Lead cold resume. - -The built runtime link installs this backend for new local CLI team runs. -The Web worker Dockerfile builds the same pinned source on Debian Bookworm and -installs both executables in `/opt/theoremos-codex-backend/`. Solo runs use -stock Codex by default. To use batched discovery in a new solo run, pass -`--harness-executable /absolute/path/to/bin/codex` with the backend built above. -The worker build probes AgentControl and executes a Code -Mode call as the worker user with fixed loopback responses before labeling the image -`org.theoremos.native-agent-control=v1`. The Web service also checks -`org.theoremos.native-team-workflow=v1`, which identifies support for native -team scheduling and initial route approval. It launches the image by its -verified ID. Rebuild both Web and worker images to roll out this workflow. - -The Code Mode host uses the V8 archive and Rust bindings from the matching Codex -release. The build verifies them against the pinned checkout's checksums. The -build-local Git helper fetches the exact locked submodule commits and records -their official gitlink pins in `submodule-pins.json`. - -If downloads fail with `Proxy CONNECT aborted`, check the configured proxy. A -confirmed direct connection can be used for this build by invoking the script -with `env -u HTTPS_PROXY -u HTTP_PROXY -u ALL_PROXY -u https_proxy -u http_proxy --u all_proxy`; this changes only the build subprocess environment. diff --git a/scripts/codex-backend/agent-control.patch b/scripts/codex-backend/agent-control.patch deleted file mode 100644 index e8d39a20..00000000 --- a/scripts/codex-backend/agent-control.patch +++ /dev/null @@ -1,3994 +0,0 @@ -diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs -index a1c6feec..dfa8869e 100644 ---- a/codex-rs/app-server-protocol/src/protocol/common.rs -+++ b/codex-rs/app-server-protocol/src/protocol/common.rs -@@ -569,7 +569,37 @@ client_request_definitions! { - response: v2::UserVerificationCancelResponse, - }, - -- /// NEW APIs -+ #[experimental("theoremos/agentControl/capabilities")] -+ /// Opt-in trusted host AgentControl capabilities. -+ TheoremosAgentControlCapabilities => "theoremos/agentControl/capabilities" { -+ params: v2::TheoremosAgentControlCapabilitiesParams, -+ serialization: None, -+ response: v2::TheoremosAgentControlCapabilitiesResponse, -+ }, -+ #[experimental("theoremos/agentControl/start")] -+ TheoremosAgentControlStart => "theoremos/agentControl/start" { -+ params: v2::TheoremosAgentControlStartParams, -+ serialization: None, -+ response: v2::TheoremosAgentControlStartResponse, -+ }, -+ #[experimental("theoremos/agentControl/input")] -+ TheoremosAgentControlInput => "theoremos/agentControl/input" { -+ params: v2::TheoremosAgentControlInputParams, -+ serialization: None, -+ response: v2::TheoremosAgentControlInputResponse, -+ }, -+ #[experimental("theoremos/agentControl/update")] -+ TheoremosAgentControlUpdate => "theoremos/agentControl/update" { -+ params: v2::TheoremosAgentControlUpdateParams, -+ serialization: None, -+ response: v2::TheoremosAgentControlUpdateResponse, -+ }, -+ #[experimental("theoremos/agentControl/snapshot")] -+ TheoremosAgentControlSnapshot => "theoremos/agentControl/snapshot" { -+ params: v2::TheoremosAgentControlSnapshotParams, -+ serialization: None, -+ response: v2::TheoremosAgentControlSnapshotResponse, -+ }, - // Thread lifecycle - // Uses `inspect_params` because only some fields are experimental. - ThreadStart => "thread/start" { -@@ -1928,6 +1958,12 @@ impl TryFrom for ServerRequest { - } - - server_request_definitions! { -+ #[experimental("theoremos/agentControl/request")] -+ /// Trusted execution backend callback, available only in explicit host mode. -+ TheoremosAgentControlRequest => "theoremos/agentControl/request" { -+ params: v2::TheoremosAgentControlRequestParams, -+ response: v2::TheoremosAgentControlRequestResponse, -+ }, - /// NEW APIs - /// Sent when approval is requested for a specific command execution. - /// This request is used for Turns started via turn/start. -diff --git a/codex-rs/app-server-protocol/src/protocol/v2/mod.rs b/codex-rs/app-server-protocol/src/protocol/v2/mod.rs -index d9fd7553..5b1d6688 100644 ---- a/codex-rs/app-server-protocol/src/protocol/v2/mod.rs -+++ b/codex-rs/app-server-protocol/src/protocol/v2/mod.rs -@@ -40,6 +40,7 @@ mod thread_data; - mod thread_prediction; - mod thread_sample; - mod thread_usage; -+mod theoremos_agent_control; - mod turn; - mod user_verification; - mod windows_sandbox; -@@ -85,6 +86,7 @@ pub use thread_data::*; - pub use thread_prediction::*; - pub use thread_sample::*; - pub use thread_usage::*; -+pub use theoremos_agent_control::*; - pub use turn::*; - pub use user_verification::*; - pub use windows_sandbox::*; -diff --git a/codex-rs/app-server-protocol/src/protocol/v2/theoremos_agent_control.rs b/codex-rs/app-server-protocol/src/protocol/v2/theoremos_agent_control.rs -new file mode 100644 -index 00000000..e3ad31c9 ---- /dev/null -+++ b/codex-rs/app-server-protocol/src/protocol/v2/theoremos_agent_control.rs -@@ -0,0 +1,73 @@ -+//! Opt-in trusted host transport for an external AgentControl execution backend. -+//! -+//! These envelopes are decoded and validated by the opted-in backend. They are -+//! not dynamic model tools, and do not grant mathematical acceptance. -+ -+use crate::JsonSchema; -+use crate::TS; -+use serde::Deserialize; -+use serde::Serialize; -+use serde_json::Value; -+ -+macro_rules! host_envelope { -+ ($($name:ident),+ $(,)?) => {$( -+ #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema, TS)] -+ #[serde(transparent)] -+ #[ts(type = "unknown", export_to = "v2/")] -+ pub struct $name { -+ pub value: Value, -+ } -+ )+}; -+} -+ -+host_envelope!( -+ TheoremosAgentControlCapabilitiesParams, -+ TheoremosAgentControlCapabilitiesResponse, -+ TheoremosAgentControlStartParams, -+ TheoremosAgentControlStartResponse, -+ TheoremosAgentControlInputParams, -+ TheoremosAgentControlInputResponse, -+ TheoremosAgentControlUpdateParams, -+ TheoremosAgentControlUpdateResponse, -+ TheoremosAgentControlSnapshotParams, -+ TheoremosAgentControlSnapshotResponse, -+ TheoremosAgentControlRequestParams, -+ TheoremosAgentControlRequestResponse, -+); -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use crate::ClientRequest; -+ use crate::RequestId; -+ use crate::ServerRequest; -+ use crate::ServerResponse; -+ use serde_json::json; -+ -+ #[test] -+ fn native_host_requests_preserve_the_trusted_wire_envelope() { -+ let value = json!({"version":1,"threadId":"child","bootstrap":{"sessionId":"root"}, -+ "thread":{"cwd":"/isolated/worker"}}); -+ let request = ClientRequest::TheoremosAgentControlStart { -+ request_id: RequestId::Integer(7), -+ params: TheoremosAgentControlStartParams { value: value.clone() }, -+ }; -+ assert_eq!(serde_json::to_value(request).unwrap(), json!({"id":7, -+ "method":"theoremos/agentControl/start","params":value})); -+ } -+ -+ #[test] -+ fn native_backend_callbacks_decode_host_results_without_tool_wrappers() { -+ let request = ServerRequest::TheoremosAgentControlRequest { -+ request_id: RequestId::Integer(8), -+ params: TheoremosAgentControlRequestParams { value: json!({"version":1, -+ "sessionId":"root","threadId":"root","operationId":"stable-id", -+ "operation":"spawn","payload":{}}) }, -+ }; -+ let response = request.response_from_result(json!({"result":{"submissionId":"turn"}})).unwrap(); -+ let ServerResponse::TheoremosAgentControlRequest { response, .. } = response else { -+ panic!("wrong callback response"); -+ }; -+ assert_eq!(response.value, json!({"result":{"submissionId":"turn"}})); -+ } -+} -diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml -index 5e6ecb80..5ce2d0fe 100644 ---- a/codex-rs/app-server/Cargo.toml -+++ b/codex-rs/app-server/Cargo.toml -@@ -93,6 +93,7 @@ codex-app-server-transport = { workspace = true } - codex-feedback = { workspace = true } - codex-rmcp-client = { workspace = true } - codex-rollout = { workspace = true } -+codex-rollout-trace = { workspace = true } - codex-sandboxing = { workspace = true } - codex-state = { workspace = true } - codex-thread-store = { workspace = true } -diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs -index ba0ad991..7242e001 100644 ---- a/codex-rs/app-server/src/lib.rs -+++ b/codex-rs/app-server/src/lib.rs -@@ -148,6 +148,7 @@ mod request_serialization; - mod server_request_error; - mod skills_watcher; - mod startup_warnings; -+mod theoremos_agent_control; - mod thread_sample; - mod thread_state; - mod thread_status; -diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs -index 0e9354b1..4c825ccb 100644 ---- a/codex-rs/app-server/src/message_processor.rs -+++ b/codex-rs/app-server/src/message_processor.rs -@@ -154,6 +154,7 @@ fn reject_removed_permission_profile(request: &JSONRPCRequest) -> Result<(), JSO - - pub(crate) struct MessageProcessor { - pub(crate) turn_admission: TurnAdmission, -+ native_agent_bridge: Option>, - user_verification: Arc, - outgoing: Arc, - startup_warnings: StartupWarnings, -@@ -370,6 +371,8 @@ impl MessageProcessor { - app_server_extension_event_sink(outgoing.clone(), thread_state_manager.clone()); - let mut queue_service = None; - let sample_responses = Arc::new(crate::thread_sample::SampleResponseRegistry::default()); -+ let native_agent_bridge = -+ crate::theoremos_agent_control::NativeAgentBridge::new(outgoing.clone()); - let thread_manager = Arc::new_cyclic(|thread_manager| { - queue_service = queue_store.map(|queue| { - Arc::new(QueuedItemService::new( -@@ -422,11 +425,20 @@ impl MessageProcessor { - )), - None, - ); -+ let manager = if let Some(bridge) = &native_agent_bridge { -+ let bridge = bridge.clone(); -+ manager.with_agent_control_factory(move |id| bridge.clone().controller(id)) -+ } else { -+ manager -+ }; - match code_mode_session_provider { - Some(provider) => manager.with_code_mode_session_provider(provider), - None => manager, - } - }); -+ if let Some(bridge) = &native_agent_bridge { -+ bridge.bind_manager(&thread_manager); -+ } - let runtime_auth = thread_manager.runtime_auth_manager(); - if let (Some(slot), Some(runtime)) = (runtime_auth_slot, &runtime_auth) { - // Analytics starts before the harness. Bind its requests to the harness registration. -@@ -643,6 +655,7 @@ impl MessageProcessor { - - Self { - turn_admission, -+ native_agent_bridge, - user_verification, - outgoing, - startup_warnings: StartupWarnings { -@@ -1424,6 +1437,102 @@ impl MessageProcessor { - .model_provider_capabilities_read() - .await - .map(|response| Some(response.into())), -+ ClientRequest::TheoremosAgentControlCapabilities { .. } => { -+ self.native_agent_bridge.as_ref().ok_or_else(|| { -+ method_not_found("TheoremOS native AgentControl is not enabled") -+ })?; -+ Ok(Some(codex_app_server_protocol::TheoremosAgentControlCapabilitiesResponse { value: serde_json::json!({"version":1,"backend":"theoremos-host","nativeTools":true,"isolatedChildBootstrap":true}) }.into())) -+ } -+ ClientRequest::TheoremosAgentControlInput { params, .. } => { -+ let bridge = self.native_agent_bridge.as_ref().ok_or_else(|| { -+ method_not_found("TheoremOS native AgentControl is not enabled") -+ })?; -+ Ok(Some( -+ codex_app_server_protocol::TheoremosAgentControlInputResponse { -+ value: bridge.input(params.value).await?, -+ } -+ .into(), -+ )) -+ } -+ ClientRequest::TheoremosAgentControlUpdate { params, .. } => { -+ let bridge = self.native_agent_bridge.as_ref().ok_or_else(|| { -+ method_not_found("TheoremOS native AgentControl is not enabled") -+ })?; -+ Ok(Some( -+ codex_app_server_protocol::TheoremosAgentControlUpdateResponse { -+ value: bridge.update(params.value)?, -+ } -+ .into(), -+ )) -+ } -+ ClientRequest::TheoremosAgentControlSnapshot { params, .. } => { -+ let bridge = self.native_agent_bridge.as_ref().ok_or_else(|| { -+ method_not_found("TheoremOS native AgentControl is not enabled") -+ })?; -+ Ok(Some( -+ codex_app_server_protocol::TheoremosAgentControlSnapshotResponse { -+ value: bridge.snapshot(params.value).await?, -+ } -+ .into(), -+ )) -+ } -+ ClientRequest::TheoremosAgentControlStart { params, .. } => { -+ let bridge = self.native_agent_bridge.as_ref().ok_or_else(|| { -+ method_not_found("TheoremOS native AgentControl is not enabled") -+ })?; -+ #[derive(serde::Deserialize)] -+ #[serde(deny_unknown_fields)] -+ struct Start { -+ version: u8, -+ bootstrap: codex_core::NativeChildBootstrap, -+ thread: Option, -+ resume: Option, -+ } -+ let start: Start = serde_json::from_value(params.value) -+ .map_err(|error| invalid_params(error.to_string()))?; -+ if start.version != 1 { -+ return Err(invalid_params("unsupported native child start version")); -+ } -+ let bootstrap_value = serde_json::to_value(&start.bootstrap) -+ .map_err(|error| invalid_params(error.to_string()))?; -+ bridge.register_bootstrap(start.bootstrap)?; -+ match (start.thread, start.resume) { -+ (Some(mut thread), None) => { -+ thread.config.get_or_insert_with(Default::default).insert( -+ crate::theoremos_agent_control::BOOTSTRAP_CONFIG_KEY.into(), -+ bootstrap_value, -+ ); -+ self.thread_processor -+ .thread_start( -+ request_id.clone(), -+ thread, -+ app_server_client_name.clone(), -+ client_version.clone(), -+ client_mcp_extensions.clone(), -+ request_context, -+ ) -+ .await -+ } -+ (None, Some(mut resume)) => { -+ resume.config.get_or_insert_with(Default::default).insert( -+ crate::theoremos_agent_control::BOOTSTRAP_CONFIG_KEY.into(), -+ bootstrap_value, -+ ); -+ self.thread_processor -+ .thread_resume( -+ ThreadResumeTarget::Client(request_id.clone()), -+ resume, -+ app_server_client_name.clone(), -+ client_version.clone(), -+ client_mcp_extensions.clone(), -+ ) -+ .await -+ } -+ _ => Err(invalid_params( -+ "native start requires exactly one thread or resume request", -+ )), -+ } -+ } - ClientRequest::ThreadStart { params, .. } => { - self.thread_processor - .thread_start( -diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs -index 7c9cded4..1dada718 100644 ---- a/codex-rs/app-server/src/request_processors/thread_processor.rs -+++ b/codex-rs/app-server/src/request_processors/thread_processor.rs -@@ -1527,6 +1527,23 @@ impl ThreadRequestProcessor { - initial_config_warnings: Arc>, - ) -> Result<(), JSONRPCErrorError> { - let thread_start_started_at = std::time::Instant::now(); -+ let mut config_overrides = config_overrides; -+ let native_bootstrap: Option = config_overrides -+ .as_mut() -+ .and_then(|values| values.remove(crate::theoremos_agent_control::BOOTSTRAP_CONFIG_KEY)) -+ .map(serde_json::from_value) -+ .transpose() -+ .map_err(|error| invalid_params(format!("invalid native bootstrap: {error}")))?; -+ if native_bootstrap.is_some() -+ && std::env::var("THEOREMOS_HOST_AGENT_CONTROL") -+ .ok() -+ .as_deref() -+ != Some("1") -+ { -+ return Err(invalid_request( -+ "native child bootstrap requires host AgentControl", -+ )); -+ } - let requested_cwd = typesafe_overrides.cwd.clone(); - let mut config = config_manager - .load_with_overrides(config_overrides.clone(), typesafe_overrides.clone()) -@@ -1673,7 +1690,10 @@ impl ThreadRequestProcessor { - ) - .await? - }; -- let thread_id = reserved_thread_id -+ let thread_id = native_bootstrap -+ .as_ref() -+ .and_then(|bootstrap| bootstrap.thread_id) -+ .or(reserved_thread_id) - .unwrap_or_else(|| listener_task_context.thread_manager.reserve_thread_id()); - start_options.reserved_thread_id = Some(thread_id); - // Startup can prewarm the Responses socket before start_thread returns. -@@ -1683,28 +1703,33 @@ impl ThreadRequestProcessor { - .try_add_connection_to_thread(thread_id, request_id.connection_id) - .await; - let create_thread_started_at = std::time::Instant::now(); -+ let mut start_options = StartThreadOptions { -+ allow_provider_model_fallback, -+ initial_history: match session_start_source -+ .unwrap_or(codex_app_server_protocol::ThreadStartSource::Startup) -+ { -+ codex_app_server_protocol::ThreadStartSource::Startup => InitialHistory::New, -+ codex_app_server_protocol::ThreadStartSource::Clear => InitialHistory::Cleared, -+ }, -+ history_mode, -+ thread_source, -+ dynamic_tools, -+ metrics_service_name: service_name, -+ parent_trace: request_trace, -+ environments: Some(environment_requests), -+ thread_extension_init, -+ prevent_daybreak_program_propagation_enrollment: daybreak_program_propagation_enrolled -+ == Some(false), -+ client_mcp_extensions, -+ ..start_options -+ }; -+ if let Some(bootstrap) = native_bootstrap.clone() { -+ codex_core::apply_native_child_bootstrap(&mut start_options, bootstrap) -+ .map_err(|error| invalid_request(error.to_string()))?; -+ } - let new_thread = listener_task_context - .thread_manager -- .start_thread(StartThreadOptions { -- allow_provider_model_fallback, -- initial_history: match session_start_source -- .unwrap_or(codex_app_server_protocol::ThreadStartSource::Startup) -- { -- codex_app_server_protocol::ThreadStartSource::Startup => InitialHistory::New, -- codex_app_server_protocol::ThreadStartSource::Clear => InitialHistory::Cleared, -- }, -- history_mode, -- thread_source, -- dynamic_tools, -- metrics_service_name: service_name, -- parent_trace: request_trace, -- environments: Some(environment_requests), -- thread_extension_init, -- prevent_daybreak_program_propagation_enrollment: -- daybreak_program_propagation_enrolled == Some(false), -- client_mcp_extensions, -- ..start_options -- }) -+ .start_thread(start_options) - .instrument(tracing::info_span!( - "app_server.thread_start.create_thread", - otel.name = "app_server.thread_start.create_thread", -@@ -1752,6 +1777,15 @@ impl ThreadRequestProcessor { - otel.name = "app_server.thread_start.config_snapshot", - )) - .await; -+ let native_agent_snapshot = if native_bootstrap.is_some() { -+ Some( -+ codex_core::native_agent_snapshot(thread.as_ref()) -+ .await -+ .map_err(|error| internal_error(error.to_string()))?, -+ ) -+ } else { -+ None -+ }; - let mut thread = build_thread_from_loaded_snapshot(&thread, &config_snapshot)?; - thread.project_id = project_id.clone(); - thread.daybreak_enabled = daybreak_enabled; -@@ -1821,14 +1855,27 @@ impl ThreadRequestProcessor { - multi_agent_mode: MultiAgentMode::ExplicitRequestOnly, - }; - let notif = thread_started_notification(thread); -- listener_task_context -- .outgoing -- .send_response_with_thread_originator(request_id, response, thread_originator) -- .instrument(tracing::info_span!( -- "app_server.thread_start.send_response", -- otel.name = "app_server.thread_start.send_response", -- )) -- .await; -+ if let Some(snapshot) = native_agent_snapshot { -+ let mut value = serde_json::to_value(response) -+ .map_err(|error| internal_error(error.to_string()))?; -+ value -+ .as_object_mut() -+ .ok_or_else(|| internal_error("invalid native start response"))? -+ .insert("agentControl".into(), snapshot); -+ listener_task_context -+ .outgoing -+ .send_response_with_thread_originator( -+ request_id, -+ codex_app_server_protocol::TheoremosAgentControlStartResponse { value }, -+ thread_originator, -+ ) -+ .await; -+ } else { -+ listener_task_context -+ .outgoing -+ .send_response_with_thread_originator(request_id, response, thread_originator) -+ .await; -+ } - - listener_task_context - .outgoing -@@ -4154,6 +4201,22 @@ impl ThreadRequestProcessor { - initial_turns_page, - } = params.clone(); - let include_turns = !exclude_turns; -+ let native_bootstrap: Option = request_overrides -+ .as_mut() -+ .and_then(|values| values.remove(crate::theoremos_agent_control::BOOTSTRAP_CONFIG_KEY)) -+ .map(serde_json::from_value) -+ .transpose() -+ .map_err(|error| invalid_params(format!("invalid native resume bootstrap: {error}")))?; -+ if native_bootstrap.is_some() -+ && std::env::var("THEOREMOS_HOST_AGENT_CONTROL") -+ .ok() -+ .as_deref() -+ != Some("1") -+ { -+ return Err(invalid_request( -+ "native child resume requires host AgentControl", -+ )); -+ } - - let prepared_model_context = retry - .prepared_config -@@ -4258,8 +4321,11 @@ impl ThreadRequestProcessor { - .await; - } - -- // Parent-owned V2 children must resume through their owner, not caller configuration. -- if let InitialHistory::Resumed(resumed_history) = &thread_history -+ // Parent-owned V2 children normally resume through their local owner. The -+ // explicit host transport restores the child's own persisted history in -+ // a separate process and validates its captured identity before startup. -+ if native_bootstrap.is_none() -+ && let InitialHistory::Resumed(resumed_history) = &thread_history - && let Some((source, _)) = thread_history.get_resumed_session_sources() - && !can_accept_direct_input(thread_history.get_multi_agent_version(), &source) - { -@@ -4508,21 +4574,22 @@ impl ThreadRequestProcessor { - } - let response_history = thread_history.clone(); - -- match self -- .thread_manager -- .start_thread(StartThreadOptions { -- initial_history: thread_history, -- parent_trace: match target { -- ThreadResumeTarget::Client(request_id) => { -- self.request_trace_context(request_id).await -- } -- ThreadResumeTarget::DaemonRecovery(_) => None, -- }, -- client_mcp_extensions, -- ..StartThreadOptions::new(config) -- }) -- .await -- { -+ let mut start_options = StartThreadOptions { -+ initial_history: thread_history, -+ parent_trace: match target { -+ ThreadResumeTarget::Client(request_id) => { -+ self.request_trace_context(request_id).await -+ } -+ ThreadResumeTarget::DaemonRecovery(_) => None, -+ }, -+ client_mcp_extensions, -+ ..StartThreadOptions::new(config) -+ }; -+ if let Some(bootstrap) = native_bootstrap.clone() { -+ codex_core::apply_native_child_resume_bootstrap(&mut start_options, bootstrap) -+ .map_err(|error| invalid_request(error.to_string()))?; -+ } -+ match self.thread_manager.start_thread(start_options).await { - Ok(NewThread { - thread_id, - thread: codex_thread, -@@ -4733,9 +4800,32 @@ impl ThreadRequestProcessor { - }; - - let connection_id = request_id.connection_id; -- self.outgoing -- .send_response_with_thread_originator(request_id, response, thread_originator) -- .await; -+ if native_bootstrap.is_some() { -+ let snapshot = codex_core::native_agent_snapshot(codex_thread.as_ref()) -+ .await -+ .map_err(|error| internal_error(error.to_string()))?; -+ let mut value = serde_json::to_value(response) -+ .map_err(|error| internal_error(error.to_string()))?; -+ value -+ .as_object_mut() -+ .ok_or_else(|| internal_error("invalid native resume response"))? -+ .insert("agentControl".into(), snapshot); -+ self.outgoing -+ .send_response_with_thread_originator( -+ request_id, -+ codex_app_server_protocol::TheoremosAgentControlStartResponse { value }, -+ thread_originator, -+ ) -+ .await; -+ } else { -+ self.outgoing -+ .send_response_with_thread_originator( -+ request_id, -+ response, -+ thread_originator, -+ ) -+ .await; -+ } - // `excludeTurns` is explicitly the cheap resume path, so avoid - // rebuilding history only to attribute a replayed usage update. - if let Some(token_usage_turn_id) = token_usage_turn_id { -diff --git a/codex-rs/app-server/src/theoremos_agent_control.rs b/codex-rs/app-server/src/theoremos_agent_control.rs -new file mode 100644 -index 00000000..7917d178 ---- /dev/null -+++ b/codex-rs/app-server/src/theoremos_agent_control.rs -@@ -0,0 +1,876 @@ -+//! Opt-in stdio transport for the native AgentControl execution contract. -+//! The model still invokes upstream collaboration handlers. The trusted host owns -+//! isolated runtimes and durable membership; it is never a dynamic-tool facade. -+ -+use crate::error_code::{internal_error, invalid_params, invalid_request}; -+use crate::outgoing_message::OutgoingMessageSender; -+use codex_app_server_protocol::{ -+ JSONRPCErrorError, ServerRequestPayload, TheoremosAgentControlRequestParams, -+}; -+use codex_core::{ -+ AgentConfigUpdate, AgentControl, AgentExecutionGuard, AgentInfo, AgentMetadata, AgentRef, -+ AgentRuntimeOwnership, AgentServiceTier, AgentSessionReader, AgentTarget, AgentTurnAdmission, -+ AgentTurnAdmissionRequest, AgentTurnOutcome, AgentTurnOutcomeReporter, AgentUsageAccounting, -+ AgentUsageReport, DeliveryReceipt, LiveAgent, NativeAgentInput, NativeChildBootstrap, -+ NativeTurnStartOptions, PendingAgentMessage, RolloutBudgetReminder, SendRequest, SpawnRequest, -+ ThreadConfigSnapshot, ThreadManager, UsageAccountingDecision, -+}; -+use codex_extension_api::ExtensionDataInit; -+use codex_protocol::error::{CodexErr, Result}; -+use codex_protocol::models::ResponseItem; -+use codex_protocol::protocol::{ -+ InterAgentCommunication, MultiAgentVersion, SessionSource, TokenUsage, -+}; -+use codex_protocol::{AgentPath, SessionId, ThreadId}; -+use codex_rollout_trace::ThreadTraceContext; -+use futures::future::BoxFuture; -+use serde::Deserialize; -+use serde_json::{Value, json}; -+use std::collections::{HashMap, HashSet}; -+use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; -+use tokio::sync::watch; -+ -+pub(crate) const BOOTSTRAP_CONFIG_KEY: &str = "__theoremos_native_agent_bootstrap"; -+ -+pub(crate) struct NativeAgentBridge { -+ outgoing: Arc, -+ manager: OnceLock>, -+ bootstraps: Mutex>, -+ controls: Mutex>, -+ input_locks: tokio::sync::Mutex>>>, -+} -+ -+impl NativeAgentBridge { -+ pub(crate) fn new(outgoing: Arc) -> Option> { -+ (std::env::var("THEOREMOS_HOST_AGENT_CONTROL") -+ .ok() -+ .as_deref() -+ == Some("1")) -+ .then(|| { -+ Arc::new(Self { -+ outgoing, -+ manager: OnceLock::new(), -+ bootstraps: Mutex::new(HashMap::new()), -+ controls: Mutex::new(HashMap::new()), -+ input_locks: tokio::sync::Mutex::new(HashMap::new()), -+ }) -+ }) -+ } -+ pub(crate) fn bind_manager(&self, manager: &Arc) { -+ let _ = self.manager.set(Arc::downgrade(manager)); -+ } -+ fn manager(&self) -> Result> { -+ self.manager.get().and_then(Weak::upgrade).ok_or_else(|| { -+ CodexErr::InvalidRequest("native host thread manager is unavailable".into()) -+ }) -+ } -+ -+ pub(crate) async fn controller( -+ self: Arc, -+ thread_id: ThreadId, -+ ) -> Result> { -+ let bootstrap = self -+ .bootstraps -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .get(&thread_id) -+ .cloned(); -+ let session_id = bootstrap -+ .as_ref() -+ .map(|b| b.session_id) -+ .unwrap_or_else(|| thread_id.into()); -+ let mut control = NativeHostControl { -+ bridge: Arc::downgrade(&self), -+ thread_id, -+ session_id, -+ local: Arc::new(Mutex::new(LocalState::default())), -+ }; -+ self.controls -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .insert(thread_id, control.clone()); -+ let response = match control -+ .rpc( -+ "attach", -+ json!({"threadId":thread_id,"sessionId":session_id}), -+ ) -+ .await -+ { -+ Ok(response) => response, -+ Err(error) => { -+ self.controls -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .remove(&thread_id); -+ return Err(error); -+ } -+ }; -+ control.session_id = serde_json::from_value( -+ response -+ .get("sessionId") -+ .cloned() -+ .ok_or_else(|| CodexErr::InvalidRequest("host attach omitted sessionId".into()))?, -+ ) -+ .map_err(decode_error)?; -+ self.controls -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .insert(thread_id, control.clone()); -+ Ok(Arc::new(control)) -+ } -+ -+ pub(crate) fn register_bootstrap( -+ &self, -+ bootstrap: NativeChildBootstrap, -+ ) -> std::result::Result<(), JSONRPCErrorError> { -+ let id = bootstrap -+ .thread_id -+ .ok_or_else(|| invalid_params("native child threadId must be reserved"))?; -+ let mut entries = self -+ .bootstraps -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner); -+ if entries.contains_key(&id) { -+ return Err(invalid_request("native child startup is already reserved")); -+ } -+ entries.insert(id, bootstrap); -+ Ok(()) -+ } -+ -+ pub(crate) async fn input( -+ &self, -+ value: Value, -+ ) -> std::result::Result { -+ #[derive(Deserialize)] -+ #[serde(rename_all = "camelCase", deny_unknown_fields)] -+ struct Input { -+ version: u8, -+ thread_id: ThreadId, -+ author: AgentPath, -+ input: NativeAgentInput, -+ #[serde(default)] -+ start_options: NativeTurnStartOptions, -+ expected_turn_id: Option, -+ #[serde(default)] -+ context_items: Vec, -+ } -+ let input: Input = -+ serde_json::from_value(value).map_err(|error| invalid_params(error.to_string()))?; -+ if input.version != 1 { -+ return Err(invalid_params("unsupported native input version")); -+ } -+ let lock = self -+ .input_locks -+ .lock() -+ .await -+ .entry(input.thread_id) -+ .or_default() -+ .clone(); -+ let _lock = lock.lock().await; -+ let thread = self -+ .manager() -+ .map_err(rpc_error)? -+ .get_thread(input.thread_id) -+ .await -+ .map_err(rpc_error)?; -+ codex_core::native_submit_agent_input( -+ thread.as_ref(), -+ input.author, -+ input.input, -+ input.start_options, -+ input.context_items, -+ input.expected_turn_id, -+ ) -+ .await -+ .map_err(rpc_error) -+ } -+ -+ pub(crate) async fn snapshot( -+ &self, -+ value: Value, -+ ) -> std::result::Result { -+ let thread_id: ThreadId = serde_json::from_value( -+ value -+ .get("threadId") -+ .cloned() -+ .ok_or_else(|| invalid_params("threadId is required"))?, -+ ) -+ .map_err(|error| invalid_params(error.to_string()))?; -+ let thread = self -+ .manager() -+ .map_err(rpc_error)? -+ .get_thread(thread_id) -+ .await -+ .map_err(rpc_error)?; -+ codex_core::native_agent_snapshot(thread.as_ref()) -+ .await -+ .map_err(rpc_error) -+ } -+ -+ pub(crate) fn update(&self, value: Value) -> std::result::Result { -+ #[derive(Deserialize)] -+ #[serde(rename_all = "camelCase", deny_unknown_fields)] -+ struct Update { -+ version: u8, -+ session_id: SessionId, -+ thread_id: ThreadId, -+ sequence: u64, -+ #[serde(default)] -+ mailbox: Vec, -+ #[serde(default)] -+ service_tier: Option>, -+ admission: Option, -+ } -+ #[derive(Deserialize)] -+ struct Mail { -+ id: String, -+ author: AgentPath, -+ recipient: AgentPath, -+ message: Option, -+ communication: Option, -+ } -+ #[derive(Deserialize)] -+ struct Admission { -+ allowed: bool, -+ reason: Option, -+ } -+ let tier_update = value -+ .get("serviceTier") -+ .map(|value| serde_json::from_value::>(value.clone())) -+ .transpose() -+ .map_err(|error| invalid_params(error.to_string()))?; -+ let update: Update = -+ serde_json::from_value(value).map_err(|error| invalid_params(error.to_string()))?; -+ let _ = &update.service_tier; -+ if update.version != 1 { -+ return Err(invalid_params("unsupported native update version")); -+ } -+ let controls = self.controls.lock().unwrap_or_else(PoisonError::into_inner); -+ let control = controls -+ .get(&update.thread_id) -+ .ok_or_else(|| invalid_request("native runtime is not attached"))?; -+ if update.session_id != control.session_id { -+ return Err(invalid_request("native session identity mismatch")); -+ } -+ let mut local = control.local.lock().unwrap_or_else(PoisonError::into_inner); -+ if update.sequence <= local.sequence { -+ return Ok(json!({"acceptedSequence":local.sequence})); -+ } -+ // Decode the complete batch before ownership transfer; malformed mail is never partially accepted. -+ let mut batch = Vec::new(); -+ for mail in update.mailbox { -+ if local.mail_ids.contains(&mail.id) { -+ continue; -+ } -+ let communication = if let Some(communication) = mail.communication { -+ if communication.author != mail.author -+ || communication.recipient != mail.recipient -+ || communication.trigger_turn -+ { -+ return Err(invalid_params( -+ "invalid queue-only native communication attribution", -+ )); -+ } -+ communication -+ } else { -+ let input:NativeAgentInput=serde_json::from_value(json!({"kind":"message","message":mail.message.ok_or_else(||invalid_params("mail message is required"))?,"mode":"queueOnly"})).map_err(|error|invalid_params(error.to_string()))?; -+ let NativeAgentInput::Message { message, mode } = input else { -+ unreachable!() -+ }; -+ message.into_communication(mail.author, mail.recipient, mode) -+ }; -+ batch.push((mail.id, PendingAgentMessage::from(communication))); -+ } -+ for (id, message) in batch { -+ if local.mail_ids.insert(id) { -+ local.mailbox.push(message); -+ } -+ } -+ if let Some(tier) = tier_update { -+ local.service_tier = tier; -+ } -+ if let Some(admission) = update.admission { -+ local.allowed = admission.allowed; -+ local.denial = admission.reason; -+ } -+ local.sequence = update.sequence; -+ local.watch.send_replace(!local.mailbox.is_empty()); -+ Ok(json!({"acceptedSequence":local.sequence})) -+ } -+} -+ -+struct LocalState { -+ sequence: u64, -+ mailbox: Vec, -+ mail_ids: HashSet, -+ watch: watch::Sender, -+ service_tier: Option, -+ allowed: bool, -+ denial: Option, -+} -+impl Default for LocalState { -+ fn default() -> Self { -+ Self { -+ sequence: 0, -+ mailbox: Vec::new(), -+ mail_ids: HashSet::new(), -+ watch: watch::channel(false).0, -+ service_tier: None, -+ allowed: true, -+ denial: None, -+ } -+ } -+} -+ -+#[derive(Clone)] -+struct NativeHostControl { -+ bridge: Weak, -+ thread_id: ThreadId, -+ session_id: SessionId, -+ local: Arc>, -+} -+ -+impl NativeHostControl { -+ async fn rpc(&self, operation: &str, payload: Value) -> Result { -+ let bridge = self -+ .bridge -+ .upgrade() -+ .ok_or_else(|| CodexErr::InvalidRequest("native host transport is closed".into()))?; -+ let params = TheoremosAgentControlRequestParams { -+ value: json!({"version":1,"sessionId":self.session_id,"threadId":self.thread_id,"operationId":uuid::Uuid::now_v7().to_string(),"operation":operation,"payload":payload}), -+ }; -+ if operation == "spawn" { -+ // Match the host's stdio frame limit, reserving space for the -+ // request envelope and the maximum-width integer request ID. -+ const HOST_FRAME_BYTES: usize = 8 * 1024 * 1024; -+ const WIRE_OVERHEAD: usize = -+ br#"{"id":-9223372036854775808,"method":"theoremos/agentControl/request","params":}"# -+ .len(); -+ if serde_json::to_vec(¶ms).map_err(decode_error)?.len() + WIRE_OVERHEAD -+ > HOST_FRAME_BYTES -+ { -+ return Err(CodexErr::InvalidRequest( -+ "Native spawn exceeds the 8 MiB transport limit. Retry with fork_turns=none and a short assignment." -+ .into(), -+ )); -+ } -+ } -+ let (request_id, receiver) = bridge -+ .outgoing -+ .send_request(ServerRequestPayload::TheoremosAgentControlRequest(params)) -+ .await; -+ struct Pending { -+ outgoing: Arc, -+ id: Option, -+ } -+ impl Drop for Pending { -+ fn drop(&mut self) { -+ if let Some(id) = self.id.take() { -+ let outgoing = self.outgoing.clone(); -+ if let Ok(runtime) = tokio::runtime::Handle::try_current() { -+ runtime.spawn(async move { -+ outgoing.cancel_request(&id).await; -+ }); -+ } -+ } -+ } -+ } -+ let mut pending = Pending { -+ outgoing: bridge.outgoing.clone(), -+ id: Some(request_id), -+ }; -+ let response = receiver -+ .await -+ .map_err(|_| CodexErr::InvalidRequest("native host callback disconnected".into()))? -+ .map_err(|error| { -+ CodexErr::InvalidRequest(format!("native host {operation}: {}", error.message)) -+ })?; -+ pending.id = None; -+ response.get("result").cloned().ok_or_else(|| { -+ CodexErr::InvalidRequest(format!("native host {operation} omitted result")) -+ }) -+ } -+ fn spawn_rpc(&self, operation: &'static str, payload: Value) { -+ let control = self.clone(); -+ tokio::spawn(async move { -+ if let Err(error) = control.rpc(operation, payload).await { -+ tracing::warn!(%error,operation,"native host background handoff failed"); -+ } -+ }); -+ } -+ async fn target(&self, target: AgentTarget) -> Result { -+ match target { -+ AgentTarget::Id(id) => Ok(json!({"kind":"id","threadId":id})), -+ AgentTarget::Reference(reference) => { -+ let bridge = self.bridge.upgrade().ok_or_else(|| { -+ CodexErr::InvalidRequest("native host transport closed".into()) -+ })?; -+ let thread = bridge.manager()?.get_thread(self.thread_id).await?; -+ let base = thread -+ .session_source() -+ .get_agent_path() -+ .unwrap_or_else(AgentPath::root); -+ let path = base -+ .resolve(&reference) -+ .map_err(CodexErr::UnsupportedOperation)?; -+ Ok(json!({"kind":"reference","reference":path})) -+ } -+ } -+ } -+} -+ -+impl AgentControl for NativeHostControl { -+ fn identity(&self) -> SessionId { -+ self.session_id -+ } -+ fn configure_startup(&self, data: &mut ExtensionDataInit, config: &codex_core::config::Config) { -+ self.local -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .service_tier = config.service_tier.clone(); -+ data.insert(AgentRuntimeOwnership::Host); -+ data.insert(Arc::new(self.clone()) as Arc); -+ data.insert(Arc::new(self.clone()) as Arc); -+ data.insert(Arc::new(self.clone()) as Arc); -+ data.insert(Arc::new(self.clone()) as Arc); -+ if self.session_id == SessionId::from(self.thread_id) { -+ data.insert(Arc::new(self.clone()) as Arc); -+ } -+ } -+ fn resolve<'a>( -+ &'a self, -+ caller: ThreadId, -+ parent: Option, -+ source: &'a SessionSource, -+ target: &'a str, -+ ) -> BoxFuture<'a, Result> { -+ Box::pin(async move { -+ let target = match ThreadId::from_string(target) { -+ Ok(id) => json!({"kind":"id","threadId":id}), -+ Err(_) => { -+ json!({"kind":"reference","reference":source.get_agent_path().unwrap_or_else(AgentPath::root).resolve(target).map_err(CodexErr::UnsupportedOperation)?}) -+ } -+ }; -+ let value = self -+ .rpc( -+ "resolve", -+ json!({"caller":caller,"parent":parent,"source":source,"target":target}), -+ ) -+ .await?; -+ serde_json::from_value(value.get("threadId").cloned().unwrap_or(Value::Null)) -+ .map_err(decode_error) -+ }) -+ } -+ fn spawn( -+ &self, -+ request: SpawnRequest, -+ ) -> BoxFuture<'_, Result<(LiveAgent, ThreadConfigSnapshot)>> { -+ Box::pin(async move { -+ let caller = request.caller; -+ let source = request.source.clone(); -+ let bridge = self -+ .bridge -+ .upgrade() -+ .ok_or_else(|| CodexErr::InvalidRequest("native host transport closed".into()))?; -+ let parent = bridge.manager()?.get_thread(caller).await?; -+ let (bootstrap, input, start) = codex_core::prepare_native_child_bootstrap( -+ parent.as_ref(), -+ self.session_id, -+ request, -+ ) -+ .await?; -+ let value=self.rpc("spawn",json!({"caller":caller,"source":source,"bootstrap":bootstrap,"input":input,"startOptions":start})).await?; -+ Ok(( -+ serde_json::from_value(value.get("agent").cloned().unwrap_or(Value::Null)) -+ .map_err(decode_error)?, -+ serde_json::from_value(value.get("configSnapshot").cloned().unwrap_or(Value::Null)) -+ .map_err(decode_error)?, -+ )) -+ }) -+ } -+ fn send(&self, request: SendRequest) -> BoxFuture<'_, Result> { -+ Box::pin(async move { -+ let target = self.target(request.target).await?; -+ let value=self.rpc("send",json!({"caller":request.caller,"target":target,"input":codex_core::native_agent_input_value(request.input),"startOptions":NativeTurnStartOptions::from(request.start_options)})).await?; -+ #[derive(Deserialize)] -+ #[serde(rename_all = "camelCase")] -+ struct Receipt { -+ thread_id: ThreadId, -+ metadata: AgentMetadata, -+ submission_id: String, -+ } -+ let receipt: Receipt = serde_json::from_value(value).map_err(decode_error)?; -+ Ok(DeliveryReceipt { -+ thread_id: receipt.thread_id, -+ metadata: receipt.metadata, -+ submission_id: receipt.submission_id, -+ }) -+ }) -+ } -+ fn take_mailbox(&self, _agent: ThreadId) -> Vec { -+ let mut local = self.local.lock().unwrap_or_else(PoisonError::into_inner); -+ let messages = std::mem::take(&mut local.mailbox); -+ local.watch.send_replace(false); -+ messages -+ } -+ fn watch_mailbox(&self, _agent: ThreadId) -> watch::Receiver { -+ self.local -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .watch -+ .subscribe() -+ } -+ fn ensure_child_loaded(&self, parent: ThreadId, child: ThreadId) -> BoxFuture<'_, Result<()>> { -+ Box::pin(async move { -+ self.rpc("ensureChildLoaded", json!({"parent":parent,"child":child})) -+ .await?; -+ Ok(()) -+ }) -+ } -+ fn interrupt( -+ &self, -+ caller: ThreadId, -+ target: AgentTarget, -+ version: MultiAgentVersion, -+ ) -> BoxFuture<'_, Result> { -+ Box::pin(async move { -+ let value = self -+ .rpc( -+ "interrupt", -+ json!({"caller":caller,"target":self.target(target).await?,"version":version}), -+ ) -+ .await?; -+ match value.get("kind").and_then(Value::as_str) { -+ Some("loaded") => Ok(AgentInfo::Loaded { -+ agent: serde_json::from_value(value["agent"].clone()).map_err(decode_error)?, -+ config: Box::new( -+ serde_json::from_value(value["configSnapshot"].clone()) -+ .map_err(decode_error)?, -+ ), -+ }), -+ Some("unloaded") => Ok(AgentInfo::Unloaded( -+ serde_json::from_value(value["metadata"].clone()).map_err(decode_error)?, -+ )), -+ _ => Err(CodexErr::InvalidRequest( -+ "host interrupt returned invalid observation".into(), -+ )), -+ } -+ }) -+ } -+ fn list<'a>( -+ &'a self, -+ caller: ThreadId, -+ parent: Option, -+ source: &'a SessionSource, -+ path_prefix: Option<&'a str>, -+ ) -> BoxFuture<'a, Result>> { -+ Box::pin(async move { -+ let path = path_prefix -+ .map(|prefix| { -+ source -+ .get_agent_path() -+ .unwrap_or_else(AgentPath::root) -+ .resolve(prefix) -+ .map_err(CodexErr::UnsupportedOperation) -+ }) -+ .transpose()?; -+ let value = self -+ .rpc( -+ "list", -+ json!({"caller":caller,"parent":parent,"source":source,"pathPrefix":path}), -+ ) -+ .await?; -+ serde_json::from_value(value["agents"].clone()).map_err(decode_error) -+ }) -+ } -+ fn child_agent_paths(&self, parent: ThreadId) -> BoxFuture<'_, Vec> { -+ Box::pin(async move { -+ match self -+ .rpc("childPaths", json!({"parent":parent})) -+ .await -+ .and_then(|v| serde_json::from_value(v["paths"].clone()).map_err(decode_error)) -+ { -+ Ok(paths) => paths, -+ Err(error) => { -+ tracing::warn!(%error,"native host roster unavailable"); -+ Vec::new() -+ } -+ } -+ }) -+ } -+ fn check_turn_admission( -+ &self, -+ _version: MultiAgentVersion, -+ _source: &SessionSource, -+ ) -> Result<()> { -+ let state = self.local.lock().unwrap_or_else(PoisonError::into_inner); -+ if state.allowed { -+ Ok(()) -+ } else { -+ Err(CodexErr::InvalidRequest( -+ state -+ .denial -+ .clone() -+ .unwrap_or_else(|| "native host admission denied".into()), -+ )) -+ } -+ } -+ fn admit_turn( -+ &self, -+ _version: MultiAgentVersion, -+ _source: &SessionSource, -+ ) -> Option { -+ None -+ } -+ fn record_usage( -+ &self, -+ usage: Option, -+ _hook_charge: codex_core::HookCharge, -+ ) -> BoxFuture<'_, Result<()>> { -+ Box::pin(async move { -+ self.rpc( -+ "recordUsage", -+ json!({"usage":usage,"codexRolloutBudgetUnits":usage.as_ref().and_then(|usage| usage.codex_rollout_budget_units.as_ref())}), -+ ) -+ .await?; -+ Ok(()) -+ }) -+ } -+ fn turn_finished<'a>( -+ &'a self, -+ outcome: AgentTurnOutcome, -+ _trace: &'a ThreadTraceContext, -+ ) -> BoxFuture<'a, ()> { -+ Box::pin(async move { -+ let completion = codex_core::native_completion_communication(&outcome); -+ let payload = json!({"outcome":{"threadId":outcome.thread_id,"turnId":outcome.turn_id,"source":outcome.source,"parentTurnId":outcome.parent_turn_id,"initiatingAgentPath":outcome.initiating_agent_path,"status":outcome.status,"errorInfo":outcome.error_info},"parentThreadId":completion.as_ref().map(|(id,_)|id),"completionMessage":completion.map(|(_,communication)|communication)}); -+ if let Err(error) = self.rpc("turnFinished", payload).await { -+ tracing::warn!(%error,"native host completion handoff failed"); -+ } -+ }) -+ } -+ fn service_tier(&self) -> Option { -+ self.local -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .service_tier -+ .clone() -+ } -+ fn propagate_config_update(&self, update: AgentConfigUpdate) { -+ let AgentConfigUpdate::ServiceTier(tier) = update; -+ self.local -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .service_tier = tier.clone(); -+ self.spawn_rpc("configUpdate", json!({"serviceTier":tier})); -+ } -+ fn get_guardian_package( -+ &self, -+ _agent: ThreadId, -+ ) -> BoxFuture<'_, Option> { -+ Box::pin(async { None }) -+ } -+ fn pending_budget_reminder<'a>( -+ &'a self, -+ _agent: ThreadId, -+ _window: &'a str, -+ ) -> BoxFuture<'a, Option> { -+ Box::pin(async { None }) -+ } -+ fn mark_budget_reminder_delivered<'a>( -+ &'a self, -+ _agent: ThreadId, -+ _window: &'a str, -+ _reminder: RolloutBudgetReminder, -+ ) -> BoxFuture<'a, ()> { -+ Box::pin(async {}) -+ } -+} -+ -+impl AgentTurnAdmission for NativeHostControl { -+ fn admit_turn( -+ &self, -+ request: AgentTurnAdmissionRequest, -+ ) -> BoxFuture<'_, Result> { -+ Box::pin(async move { -+ let payload = json!({"threadId":request.thread_id,"turnId":request.turn_id}); -+ let result = self.rpc("admitTurn", payload.clone()).await?; -+ if result.get("admitted") != Some(&Value::Bool(true)) { -+ return Err(CodexErr::new( -+ codex_protocol::error::CodexErrorDetails::AgentLimitReached { max_threads: 0 }, -+ )); -+ } -+ struct Permit { -+ control: NativeHostControl, -+ payload: Value, -+ } -+ impl Drop for Permit { -+ fn drop(&mut self) { -+ self.control.spawn_rpc("releaseTurn", self.payload.clone()); -+ } -+ } -+ Ok(AgentExecutionGuard::new(Permit { -+ control: self.clone(), -+ payload, -+ })) -+ }) -+ } -+} -+impl AgentUsageAccounting for NativeHostControl { -+ fn report_usage( -+ &self, -+ report: AgentUsageReport, -+ ) -> BoxFuture<'_, Result> { -+ Box::pin(async move { -+ self.rpc("recordUsage",json!({"threadId":report.thread_id,"turnId":report.turn_id,"usage":report.usage,"codexRolloutBudgetUnits":report.usage.as_ref().and_then(|usage| usage.codex_rollout_budget_units.as_ref())})).await?; -+ Ok(UsageAccountingDecision::Continue) -+ }) -+ } -+} -+impl AgentServiceTier for NativeHostControl { -+ fn current(&self) -> BoxFuture<'_, Option> { -+ Box::pin(async move { AgentControl::service_tier(self) }) -+ } -+ fn update(&self, tier: Option) -> BoxFuture<'static, std::result::Result<(), String>> { -+ let control = self.clone(); -+ self.local -+ .lock() -+ .unwrap_or_else(PoisonError::into_inner) -+ .service_tier = tier.clone(); -+ let task = tokio::spawn(async move { -+ control -+ .rpc("configUpdate", json!({"serviceTier":tier})) -+ .await -+ .map(|_| ()) -+ .map_err(|error| error.to_string()) -+ }); -+ Box::pin(async move { task.await.map_err(|error| error.to_string())? }) -+ } -+} -+impl AgentTurnOutcomeReporter for NativeHostControl { -+ fn report(&self, outcome: AgentTurnOutcome) -> BoxFuture<'_, ()> { -+ Box::pin(async move { -+ AgentControl::turn_finished(self, outcome, &ThreadTraceContext::disabled()).await; -+ }) -+ } -+} -+impl AgentSessionReader for NativeHostControl { -+ fn root(&self) -> BoxFuture<'_, Result> { -+ Box::pin(async move { -+ Ok(AgentRef { -+ thread_id: self.session_id.into(), -+ path: AgentPath::root(), -+ }) -+ }) -+ } -+ fn parent(&self) -> BoxFuture<'_, Result>> { -+ Box::pin(async move { -+ let bridge = self -+ .bridge -+ .upgrade() -+ .ok_or_else(|| CodexErr::InvalidRequest("native host transport closed".into()))?; -+ let thread = bridge.manager()?.get_thread(self.thread_id).await?; -+ let Some(parent) = thread.session_source().parent_thread_id() else { -+ return Ok(None); -+ }; -+ let path = thread -+ .session_source() -+ .get_agent_path() -+ .and_then(|path| { -+ path.as_str() -+ .rsplit_once('/') -+ .and_then(|(parent, _)| AgentPath::try_from(parent).ok()) -+ }) -+ .ok_or_else(|| { -+ CodexErr::InvalidRequest("native child parent path missing".into()) -+ })?; -+ Ok(Some(AgentRef { -+ thread_id: parent, -+ path, -+ })) -+ }) -+ } -+ fn children(&self) -> BoxFuture<'_, Result>> { -+ Box::pin(async move { -+ let value = self -+ .rpc("childPaths", json!({"parent":self.thread_id})) -+ .await?; -+ let paths: Vec = -+ serde_json::from_value(value["paths"].clone()).map_err(decode_error)?; -+ let mut children = Vec::with_capacity(paths.len()); -+ for path in paths { -+ let response=self.rpc("resolve",json!({"caller":self.thread_id,"parent":Value::Null,"source":SessionSource::Cli,"target":{"kind":"reference","reference":path}})).await?; -+ let thread_id: ThreadId = -+ serde_json::from_value(response["threadId"].clone()).map_err(decode_error)?; -+ children.push(AgentRef { thread_id, path }); -+ } -+ Ok(children) -+ }) -+ } -+} -+ -+fn decode_error(error: serde_json::Error) -> CodexErr { -+ CodexErr::InvalidRequest(format!("invalid native host response: {error}")) -+} -+fn rpc_error(error: CodexErr) -> JSONRPCErrorError { -+ internal_error(error.to_string()) -+} -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ fn control() -> NativeHostControl { -+ let thread_id = ThreadId::from_string("01900000-0000-7000-8000-000000000001").unwrap(); -+ NativeHostControl { -+ bridge: Weak::new(), -+ thread_id, -+ session_id: thread_id.into(), -+ local: Arc::new(Mutex::new(LocalState::default())), -+ } -+ } -+ #[test] -+ fn synchronous_mailbox_transfer_clears_watch_without_losing_subscription() { -+ let control = control(); -+ let receiver = control.watch_mailbox(control.thread_id); -+ let communication = InterAgentCommunication::new( -+ AgentPath::root(), -+ AgentPath::root(), -+ Vec::new(), -+ "queued".into(), -+ false, -+ ); -+ { -+ let mut local = control.local.lock().unwrap(); -+ local.mailbox.push(communication.into()); -+ local.watch.send_replace(true); -+ } -+ assert!(*receiver.borrow()); -+ let messages = control.take_mailbox(control.thread_id); -+ assert_eq!(messages.len(), 1); -+ assert_eq!(messages[0].content, "queued"); -+ assert!(!*receiver.borrow()); -+ assert!(control.take_mailbox(control.thread_id).is_empty()); -+ // A later handoff reuses the same watch subscription. -+ control.local.lock().unwrap().watch.send_replace(true); -+ assert!(*receiver.borrow()); -+ } -+ #[tokio::test] -+ async fn native_admission_failure_does_not_fall_back_to_local_capacity() { -+ let control = control(); -+ control.local.lock().unwrap().allowed = false; -+ assert!( -+ control -+ .check_turn_admission(MultiAgentVersion::V2, &SessionSource::Cli) -+ .is_err() -+ ); -+ let request = AgentTurnAdmissionRequest { -+ thread_id: control.thread_id, -+ turn_id: "actual-turn".into(), -+ }; -+ assert!( -+ AgentTurnAdmission::admit_turn(&control, request) -+ .await -+ .is_err() -+ ); -+ } -+} -diff --git a/codex-rs/core/src/agent/api.rs b/codex-rs/core/src/agent/api.rs -index b4c0a8c5..52f98f03 100644 ---- a/codex-rs/core/src/agent/api.rs -+++ b/codex-rs/core/src/agent/api.rs -@@ -47,6 +47,15 @@ pub trait AgentControl: Send + Sync { - - fn identity(&self) -> SessionId; - -+ /// Install backend-owned providers before root, child, or cold-resumed startup. -+ /// The default preserves controller-owned execution. -+ fn configure_startup( -+ &self, -+ _data: &mut codex_extension_api::ExtensionDataInit, -+ _config: &Config, -+ ) { -+ } -+ - /// Resolve an ID or a name relative to the caller's captured source, without loading. - /// The local backend lazily registers callers with no parent before resolving, including - /// for direct IDs. Keeping resolution separate preserves tool error and analytics ordering. -diff --git a/codex-rs/core/src/agent/host/mod.rs b/codex-rs/core/src/agent/host/mod.rs -index 06a15b39..55a3ad08 100644 ---- a/codex-rs/core/src/agent/host/mod.rs -+++ b/codex-rs/core/src/agent/host/mod.rs -@@ -36,3 +36,5 @@ pub use types::RestrictRootCapabilities; - pub use usage::AgentUsageAccounting; - pub use usage::AgentUsageReport; - pub use usage::UsageAccountingDecision; -+ -+pub(crate) mod wire; -diff --git a/codex-rs/core/src/agent/host/spawn.rs b/codex-rs/core/src/agent/host/spawn.rs -index 40e96627..690508e1 100644 ---- a/codex-rs/core/src/agent/host/spawn.rs -+++ b/codex-rs/core/src/agent/host/spawn.rs -@@ -29,7 +29,7 @@ use codex_protocol::protocol::MultiAgentVersion; - use codex_protocol::protocol::ThreadSource; - use std::sync::Arc; - --async fn prepare_spawn_inputs( -+pub(super) async fn prepare_spawn_inputs( - parent: &CodexThread, - request: ChildSpawnSettings, - ) -> Result<( -diff --git a/codex-rs/core/src/agent/host/wire.rs b/codex-rs/core/src/agent/host/wire.rs -new file mode 100644 -index 00000000..d9434be2 ---- /dev/null -+++ b/codex-rs/core/src/agent/host/wire.rs -@@ -0,0 +1,961 @@ -+//! Narrow transport snapshots for a trusted host running each native child in its own process. -+//! Provider credentials and Config never cross this boundary. -+ -+use super::RestrictRootCapabilities; -+use super::spawn::prepare_spawn_inputs; -+use crate::agent::api::{AgentInput, AgentTurnOutcome, SpawnRequest}; -+use crate::agent::types::{AgentMessage, AgentMetadata, LiveAgent, MessageDeliveryMode}; -+use crate::codex_thread::CodexThread; -+use crate::thread_manager::StartThreadOptions; -+use crate::thread_spawn::ChildSpawnSettings; -+use codex_execpolicy::{Policy, RequirementsExecPolicy}; -+use codex_extension_api::{Instructions, LoadedUserInstructions}; -+use codex_history::InitialHistory; -+use codex_network_proxy::EnvironmentNetworkPolicy; -+use codex_protocol::config_types::{ApprovalsReviewer, Personality, ReasoningSummary}; -+use codex_protocol::dynamic_tools::DynamicToolSpec; -+use codex_protocol::error::{CodexErr, Result}; -+use codex_protocol::models::{PermissionProfile, ResponseItem}; -+use codex_protocol::openai_models::ReasoningEffort; -+use codex_protocol::permissions::{FileSystemAccessMode, FileSystemPath}; -+use codex_protocol::protocol::{ -+ AgentStatus, AskForApproval, InterAgentCommunication, SessionSource, ThreadHistoryMode, -+ ThreadSource, TurnEnvironmentRequest, -+}; -+use codex_protocol::turn_input::{ -+ TurnInput, TurnInputRequest, TurnInputSubmission, TurnStartOptions, -+}; -+use codex_protocol::user_input::UserInput; -+use codex_protocol::{AgentPath, SessionId, ThreadId, intersect_effective_permission_profiles}; -+use codex_utils_absolute_path::AbsolutePathBuf; -+use serde::{Deserialize, Serialize}; -+use serde_json::{Value, json}; -+use std::sync::Arc; -+ -+#[derive(Clone, Debug, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase")] -+pub struct NativeChildSettings { -+ pub model: Option, -+ pub reasoning_effort: Option, -+ pub service_tier: Option, -+ pub reasoning_summary: Option, -+ pub personality: Option, -+ pub base_instructions: Option, -+ pub developer_instructions: Option, -+ pub approval_policy: AskForApproval, -+ pub approvals_reviewer: ApprovalsReviewer, -+ pub permission_profile: PermissionProfile, -+ #[serde(default)] -+ pub network_policy: Option, -+ pub cwd: AbsolutePathBuf, -+} -+ -+#[derive(Clone, Debug, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase", deny_unknown_fields)] -+pub struct NativeWorkspaceRelocation { -+ pub from: AbsolutePathBuf, -+ pub to: AbsolutePathBuf, -+} -+ -+#[derive(Clone, Debug, Default, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase", deny_unknown_fields)] -+pub struct NativeHostOverrides { -+ pub cwd: Option, -+ pub environments: Option>, -+ pub developer_instructions: Option, -+ #[serde(default, deserialize_with = "deserialize_host_dynamic_tools")] -+ pub dynamic_tools: Option>, -+ pub permission_profile: Option, -+ /// Trusted host capability: move workspace authority to an isolated destination. -+ pub workspace_relocation: Option, -+} -+ -+#[derive(Clone, Debug, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase")] -+pub struct NativeChildBootstrap { -+ pub version: u8, -+ pub session_id: SessionId, -+ pub thread_id: Option, -+ pub source: SessionSource, -+ pub config: NativeChildSettings, -+ pub initial_history: InitialHistory, -+ pub history_mode: Option, -+ pub user_instructions: Option, -+ pub thread_instructions: Option, -+ pub exec_policy: Policy, -+ pub exec_policy_source_requirements: Option, -+ pub environments: Vec, -+ pub dynamic_tools: Vec, -+ pub disabled_plugin_ids: Option>, -+ pub originator: String, -+ #[serde(default)] -+ pub host_overrides: NativeHostOverrides, -+} -+ -+#[derive(Clone, Debug, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase")] -+pub struct NativeInstructions { -+ pub text: String, -+ pub source: Option, -+} -+impl From for NativeInstructions { -+ fn from(value: Instructions) -> Self { -+ Self { -+ text: value.text, -+ source: value.source, -+ } -+ } -+} -+impl From for Instructions { -+ fn from(value: NativeInstructions) -> Self { -+ Self { -+ text: value.text, -+ source: value.source, -+ } -+ } -+} -+pub(crate) struct TransportedAgentOriginator(pub(crate) String); -+/// Only the trusted native transport requests synchronous turn acceptance for attributed mail. -+#[derive(Clone, Debug)] -+pub(crate) struct NativeAgentTransportInput; -+ -+fn deserialize_host_dynamic_tools<'de, D: serde::Deserializer<'de>>( -+ deserializer: D, -+) -> std::result::Result>, D::Error> { -+ let values = Option::>::deserialize(deserializer)?; -+ values -+ .map(codex_protocol::dynamic_tools::normalize_dynamic_tool_specs) -+ .transpose() -+ .map_err(serde::de::Error::custom) -+} -+ -+pub fn apply_native_child_resume_bootstrap( -+ options: &mut StartThreadOptions, -+ bootstrap: NativeChildBootstrap, -+) -> Result<()> { -+ validate_native_resume_identity( -+ &options.initial_history, -+ bootstrap.thread_id, -+ bootstrap.session_id, -+ &bootstrap.source, -+ )?; -+ let history = options.initial_history.clone(); -+ apply_native_child_bootstrap(options, bootstrap)?; -+ options.initial_history = history; -+ options.reserved_thread_id = None; -+ Ok(()) -+} -+ -+fn validate_native_resume_identity( -+ initial_history: &InitialHistory, -+ thread_id: Option, -+ session_id: SessionId, -+ source: &SessionSource, -+) -> Result<()> { -+ let InitialHistory::Resumed(history) = initial_history else { -+ return Err(CodexErr::InvalidRequest( -+ "native resume requires persisted history".into(), -+ )); -+ }; -+ if Some(history.conversation_id) != thread_id { -+ return Err(CodexErr::InvalidRequest( -+ "native resume thread identity mismatch".into(), -+ )); -+ } -+ let metadata = history.history.iter().find_map(|item| match item { -+ codex_history::RolloutItem::SessionMeta(line) => Some(&line.meta), -+ _ => None, -+ }); -+ if !metadata.is_some_and(|metadata| { -+ metadata.id == history.conversation_id -+ && metadata.session_id == session_id -+ && &metadata.source == source -+ }) { -+ return Err(CodexErr::InvalidRequest( -+ "native resume persisted session or source identity mismatch".into(), -+ )); -+ } -+ Ok(()) -+} -+ -+pub async fn prepare_native_child_bootstrap( -+ parent: &CodexThread, -+ session_id: SessionId, -+ request: SpawnRequest, -+) -> Result<(NativeChildBootstrap, Value, NativeTurnStartOptions)> { -+ if request.caller != parent.session.thread_id { -+ return Err(CodexErr::InvalidRequest( -+ "spawn caller does not match runtime".into(), -+ )); -+ } -+ let start = NativeTurnStartOptions::from(TurnStartOptions { -+ parent_turn_id: request.options.parent_turn_id.clone(), -+ root_turn_id: request.options.root_turn_id.clone(), -+ turn_trigger: request.options.turn_trigger.clone(), -+ initiating_agent_path: request.source.get_agent_path().and_then(|path| { -+ path.as_str() -+ .rsplit_once('/') -+ .and_then(|(parent, _)| AgentPath::try_from(parent).ok()) -+ }), -+ ..Default::default() -+ }); -+ let input = native_agent_input_value(request.input); -+ let settings = NativeChildSettings { -+ model: request.config.model.clone(), -+ reasoning_effort: request.config.model_reasoning_effort.clone(), -+ service_tier: request.config.service_tier.clone(), -+ reasoning_summary: request.config.model_reasoning_summary, -+ personality: request.config.personality, -+ base_instructions: request.config.base_instructions.clone(), -+ developer_instructions: request.config.developer_instructions.clone(), -+ approval_policy: request.config.permissions.approval_policy.value(), -+ approvals_reviewer: request.config.approvals_reviewer, -+ permission_profile: request.config.permissions.effective_permission_profile(), -+ network_policy: request -+ .config -+ .permissions -+ .network -+ .as_ref() -+ .map(|network| network.environment_policy()), -+ cwd: request.config.cwd.clone(), -+ }; -+ let (options, inheritance, _) = prepare_spawn_inputs( -+ parent, -+ ChildSpawnSettings { -+ config: request.config, -+ source: request.source.clone(), -+ options: request.options, -+ }, -+ ) -+ .await?; -+ let (exec_policy, requirements) = match inheritance.exec_policy { -+ Some(manager) => manager.snapshot(), -+ None => parent.session.services.exec_policy.snapshot(), -+ }; -+ let environments = options -+ .inherited_environments -+ .as_ref() -+ .map(|snapshot| snapshot.inheritable_requests()) -+ .unwrap_or_default(); -+ Ok(( -+ NativeChildBootstrap { -+ version: 1, -+ session_id, -+ thread_id: None, -+ source: request.source, -+ config: settings, -+ initial_history: options.initial_history, -+ history_mode: options.history_mode, -+ user_instructions: inheritance.instructions.user.map(Into::into), -+ thread_instructions: inheritance.instructions.thread.map(Into::into), -+ exec_policy: (*exec_policy).clone(), -+ exec_policy_source_requirements: requirements.as_deref().cloned(), -+ environments, -+ dynamic_tools: options.dynamic_tools, -+ disabled_plugin_ids: options.disabled_plugin_ids, -+ originator: inheritance.originator, -+ host_overrides: NativeHostOverrides::default(), -+ }, -+ input, -+ start, -+ )) -+} -+ -+pub fn apply_native_child_bootstrap( -+ options: &mut StartThreadOptions, -+ bootstrap: NativeChildBootstrap, -+) -> Result<()> { -+ if bootstrap.version != 1 || !bootstrap.source.is_non_root_agent() { -+ return Err(CodexErr::InvalidRequest( -+ "unsupported native child bootstrap".into(), -+ )); -+ } -+ let child_id = bootstrap.thread_id.ok_or_else(|| { -+ CodexErr::InvalidRequest("native child thread ID must be reserved by host".into()) -+ })?; -+ if SessionId::from(child_id) == bootstrap.session_id { -+ return Err(CodexErr::InvalidRequest( -+ "child cannot use root identity".into(), -+ )); -+ } -+ let dest_cwd = bootstrap -+ .host_overrides -+ .cwd -+ .clone() -+ .unwrap_or_else(|| options.config.cwd.clone()); -+ if options.config.cwd != dest_cwd { -+ return Err(CodexErr::InvalidRequest( -+ "bootstrap cwd must match destination profile cwd".into(), -+ )); -+ } -+ let mut authority = bootstrap.config.permission_profile.clone(); -+ if let Some(relocation) = &bootstrap.host_overrides.workspace_relocation { -+ if relocation.from != bootstrap.config.cwd -+ || relocation.to != dest_cwd -+ || relocation.from == relocation.to -+ { -+ return Err(CodexErr::InvalidRequest( -+ "invalid trusted workspace relocation".into(), -+ )); -+ } -+ authority = relocate_workspace_authority(&authority, &relocation.from, &relocation.to)?; -+ } -+ let destination_network = options -+ .config -+ .permissions -+ .network -+ .as_ref() -+ .map(|network| network.environment_policy()); -+ validate_native_network_policy( -+ bootstrap.config.network_policy.as_ref(), -+ destination_network.as_ref(), -+ )?; -+ let destination = options.config.permissions.effective_permission_profile(); -+ let mut permissions = -+ intersect_effective_permission_profiles(&authority, &destination, dest_cwd.as_path()) -+ .map_err(|error| { -+ CodexErr::InvalidRequest(format!("native child permission intersection: {error}")) -+ })?; -+ if let Some(requested) = &bootstrap.host_overrides.permission_profile { -+ permissions = -+ intersect_effective_permission_profiles(&permissions, requested, dest_cwd.as_path()) -+ .map_err(|error| { -+ CodexErr::InvalidRequest(format!( -+ "native child host permission restriction: {error}" -+ )) -+ })?; -+ } -+ options -+ .config -+ .permissions -+ .set_permission_profile(permissions) -+ .map_err(|error| { -+ CodexErr::InvalidRequest(format!( -+ "destination rejected inherited permissions: {error}" -+ )) -+ })?; -+ options -+ .config -+ .permissions -+ .approval_policy -+ .set(bootstrap.config.approval_policy) -+ .map_err(|error| { -+ CodexErr::InvalidRequest(format!("destination rejected approval policy: {error}")) -+ })?; -+ options.config.approvals_reviewer = bootstrap.config.approvals_reviewer; -+ options.config.model = bootstrap.config.model; -+ options.config.model_reasoning_effort = bootstrap.config.reasoning_effort; -+ options.config.service_tier = bootstrap.config.service_tier; -+ options.config.model_reasoning_summary = bootstrap.config.reasoning_summary; -+ options.config.personality = bootstrap.config.personality; -+ options.config.base_instructions = bootstrap.config.base_instructions; -+ options.config.developer_instructions = bootstrap -+ .host_overrides -+ .developer_instructions -+ .or(bootstrap.config.developer_instructions); -+ options.initial_history = bootstrap.initial_history; -+ options.history_mode = bootstrap.history_mode; -+ options.session_source = Some(bootstrap.source); -+ options.thread_source = Some(ThreadSource::Subagent); -+ options.reserved_thread_id = Some(child_id); -+ options.user_instructions = Some(LoadedUserInstructions { -+ instructions: bootstrap.user_instructions.map(Into::into), -+ warnings: Vec::new(), -+ }); -+ options.set_inherited_thread_instructions( -+ bootstrap -+ .thread_instructions -+ .map(Into::into) -+ .unwrap_or(Instructions { -+ text: String::new(), -+ source: None, -+ }), -+ ); -+ // The captured policy already includes the parent's user/project rules. The isolated -+ // destination must not re-read a different worktree's user/project policy. Managed -+ // requirements and system policy sources remain subject to native compatibility checks. -+ options.config.config_layer_stack = options -+ .config -+ .config_layer_stack -+ .clone() -+ .with_user_and_project_exec_policy_rules_ignored(true); -+ options.set_inherited_exec_policy( -+ Arc::new(bootstrap.exec_policy), -+ bootstrap.exec_policy_source_requirements.map(Arc::new), -+ ); -+ options.dynamic_tools = bootstrap -+ .host_overrides -+ .dynamic_tools -+ .unwrap_or(bootstrap.dynamic_tools); -+ options.disabled_plugin_ids = bootstrap.disabled_plugin_ids; -+ if let Some(environments) = bootstrap.host_overrides.environments { -+ options.environments = Some(environments); -+ } else if bootstrap.host_overrides.workspace_relocation.is_none() { -+ options.environments = Some(bootstrap.environments); -+ } -+ // Relocated environments come from the destination's trusted profile, never parent bindings. -+ // Native subagents get the shared session identity from their attached -+ // AgentControl (or persisted metadata on resume). InheritedSessionId is only -+ // valid for fresh host-root threads and must not be installed for this path. -+ options -+ .thread_extension_init -+ .insert(RestrictRootCapabilities); -+ options -+ .thread_extension_init -+ .insert(TransportedAgentOriginator(bootstrap.originator)); -+ Ok(()) -+} -+ -+// Proxy listeners, credentials and URLs belong to the destination. The current -+// transport supports the same captured traffic policy, plus an independently -+// restrictive destination when the parent did not use a proxy. Different proxy -+// allowlists fail closed rather than guessing whether wildcard rules are subsets. -+fn validate_native_network_policy( -+ captured: Option<&EnvironmentNetworkPolicy>, -+ destination: Option<&EnvironmentNetworkPolicy>, -+) -> Result<()> { -+ if let Some(captured) = captured -+ && Some(captured) != destination -+ { -+ return Err(CodexErr::InvalidRequest( -+ "native child destination network policy differs from captured authority".into(), -+ )); -+ } -+ Ok(()) -+} -+ -+fn relocate_workspace_authority( -+ profile: &PermissionProfile, -+ from: &AbsolutePathBuf, -+ to: &AbsolutePathBuf, -+) -> Result { -+ let (mut filesystem, network) = profile.to_runtime_permissions(); -+ let mut saw_workspace_grant = false; -+ filesystem.entries.retain(|entry| { -+ let FileSystemPath::Path { path } = &entry.path else { -+ return true; -+ }; -+ let Ok(path) = path.to_abs_path() else { -+ return true; -+ }; -+ if entry.access == FileSystemAccessMode::Write && path.as_path().starts_with(from.as_path()) -+ { -+ saw_workspace_grant = true; -+ return false; -+ } -+ // The trusted host rebinds this subtree in an independent namespace. Other denies survive. -+ !(entry.access == FileSystemAccessMode::Deny && to.as_path().starts_with(path.as_path())) -+ }); -+ if !saw_workspace_grant { -+ return Err(CodexErr::InvalidRequest( -+ "relocation requires captured workspace write authority".into(), -+ )); -+ } -+ filesystem -+ .entries -+ .push(codex_protocol::permissions::FileSystemSandboxEntry::new( -+ FileSystemPath::Path { -+ path: codex_utils_path_uri::PathUri::from_abs_path(to), -+ }, -+ FileSystemAccessMode::Write, -+ )); -+ Ok( -+ PermissionProfile::from_runtime_permissions_with_enforcement( -+ profile.enforcement(), -+ &filesystem, -+ network, -+ ), -+ ) -+} -+ -+#[derive(Clone, Debug, Default, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase")] -+pub struct NativeTurnStartOptions { -+ pub parent_turn_id: Option, -+ pub root_turn_id: Option, -+ pub turn_trigger: Option, -+ pub initiating_agent_path: Option, -+ pub final_output_json_schema: Option, -+ pub service_tier: Option, -+} -+impl From for NativeTurnStartOptions { -+ fn from(value: TurnStartOptions) -> Self { -+ Self { -+ parent_turn_id: value.parent_turn_id, -+ root_turn_id: value.root_turn_id, -+ turn_trigger: value.turn_trigger, -+ initiating_agent_path: value.initiating_agent_path, -+ final_output_json_schema: value.final_output_json_schema, -+ service_tier: value.service_tier, -+ } -+ } -+} -+impl From for TurnStartOptions { -+ fn from(value: NativeTurnStartOptions) -> Self { -+ Self { -+ parent_turn_id: value.parent_turn_id, -+ root_turn_id: value.root_turn_id, -+ turn_trigger: value.turn_trigger, -+ initiating_agent_path: value.initiating_agent_path, -+ final_output_json_schema: value.final_output_json_schema, -+ service_tier: value.service_tier, -+ ..Default::default() -+ } -+ } -+} -+ -+#[derive(Clone, Debug, Serialize, Deserialize)] -+#[serde(tag = "kind", rename_all = "camelCase")] -+pub enum NativeAgentInput { -+ Message { -+ message: NativeMessage, -+ mode: NativeDeliveryMode, -+ }, -+ UserInput { -+ items: Vec, -+ }, -+ Communication { -+ communication: InterAgentCommunication, -+ }, -+} -+#[derive(Clone, Debug, Serialize, Deserialize)] -+#[serde(tag = "kind", content = "text", rename_all = "camelCase")] -+pub enum NativeMessage { -+ Plaintext(String), -+ Encrypted(String), -+} -+#[derive(Clone, Copy, Debug, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase")] -+pub enum NativeDeliveryMode { -+ QueueOnly, -+ TriggerTurn, -+} -+impl NativeMessage { -+ pub fn into_communication( -+ self, -+ author: AgentPath, -+ recipient: AgentPath, -+ mode: NativeDeliveryMode, -+ ) -> InterAgentCommunication { -+ let message = match self { -+ Self::Plaintext(text) => AgentMessage::Plaintext(text), -+ Self::Encrypted(text) => AgentMessage::Encrypted(text), -+ }; -+ message.into_communication( -+ author, -+ recipient, -+ match mode { -+ NativeDeliveryMode::QueueOnly => MessageDeliveryMode::QueueOnly, -+ NativeDeliveryMode::TriggerTurn => MessageDeliveryMode::TriggerTurn, -+ }, -+ ) -+ } -+} -+pub fn native_agent_input_value(input: AgentInput) -> Value { -+ let input = match input { -+ AgentInput::UserInput(items) => NativeAgentInput::UserInput { -+ items: items.iter().map(|item| item.to_user_input()).collect(), -+ }, -+ AgentInput::Message { message, mode } => NativeAgentInput::Message { -+ message: match message { -+ AgentMessage::Plaintext(text) => NativeMessage::Plaintext(text), -+ AgentMessage::Encrypted(text) => NativeMessage::Encrypted(text), -+ }, -+ mode: match mode { -+ MessageDeliveryMode::QueueOnly => NativeDeliveryMode::QueueOnly, -+ MessageDeliveryMode::TriggerTurn => NativeDeliveryMode::TriggerTurn, -+ }, -+ }, -+ }; -+ serde_json::to_value(input).expect("native agent input is serializable") -+} -+ -+pub fn native_completion_communication( -+ outcome: &AgentTurnOutcome, -+) -> Option<(ThreadId, InterAgentCommunication)> { -+ let codex_protocol::protocol::SessionSource::SubAgent( -+ codex_protocol::protocol::SubAgentSource::ThreadSpawn { -+ parent_thread_id, -+ agent_path: Some(child), -+ .. -+ }, -+ ) = &outcome.source -+ else { -+ return None; -+ }; -+ let parent = AgentPath::try_from(child.as_str().rsplit_once('/')?.0).ok()?; -+ let text = match (&outcome.status, &outcome.error_info) { -+ ( -+ AgentStatus::Errored(error), -+ Some(codex_protocol::protocol::CodexErrorInfo::TooManyDenials), -+ ) => Some(crate::session_prefix::format_guardian_interruption_message( -+ parent.clone(), -+ child.clone(), -+ error, -+ )), -+ _ => crate::session_prefix::format_inter_agent_completion_message( -+ parent.clone(), -+ child.clone(), -+ &outcome.status, -+ ), -+ }?; -+ Some(( -+ *parent_thread_id, -+ InterAgentCommunication::new(child.clone(), parent, Vec::new(), text, false), -+ )) -+} -+ -+pub async fn native_agent_snapshot(thread: &CodexThread) -> Result { -+ let snapshot = crate::agent::control::effective_spawn_config(thread).await?; -+ let source = &snapshot.session_source; -+ let agent = LiveAgent { -+ thread_id: thread.session.thread_id, -+ metadata: AgentMetadata { -+ agent_id: Some(thread.session.thread_id), -+ agent_path: Some(source.get_agent_path().unwrap_or_else(AgentPath::root)), -+ agent_nickname: source.get_nickname(), -+ agent_role: source.get_agent_role(), -+ }, -+ status: thread.io.agent_status.borrow().clone(), -+ }; -+ Ok(json!({"sessionId":thread.session.session_id(), "agent":agent, "configSnapshot":snapshot})) -+} -+ -+/// Called under the transport's per-thread lock, after observers are registered. -+pub async fn native_submit_agent_input( -+ thread: &CodexThread, -+ author: AgentPath, -+ input: NativeAgentInput, -+ start: NativeTurnStartOptions, -+ context_items: Vec, -+ expected_turn_id: Option, -+) -> Result { -+ if let Some(expected) = &expected_turn_id { -+ let active = thread -+ .session -+ .active_turn_context_and_cancellation_token() -+ .await; -+ if active.as_ref().map(|(turn, _)| turn.sub_id.as_str()) != Some(expected.as_str()) { -+ return Err(CodexErr::InvalidRequest( -+ "expected native turn is no longer active".into(), -+ )); -+ } -+ } -+ if !context_items.is_empty() { -+ thread.inject_response_items_for_turn(context_items).await?; -+ } -+ let id = uuid::Uuid::now_v7().to_string(); -+ let recipient = thread -+ .session_source -+ .get_agent_path() -+ .unwrap_or_else(AgentPath::root); -+ let turn = match input { -+ NativeAgentInput::UserInput { items } => { -+ let request = TurnInputRequest::user_input(items).on_start(start.into()); -+ if let Some(expected) = expected_turn_id { -+ match thread.steer_turn(request, expected).await? { -+ codex_protocol::turn_input::SteerSubmission::Steered { turn_id } => { -+ Some(turn_id) -+ } -+ codex_protocol::turn_input::SteerSubmission::NotSubmitted { reason } => { -+ return Err(CodexErr::InvalidRequest(format!( -+ "native input not steered: {reason:?}" -+ ))); -+ } -+ } -+ } else { -+ match thread.start_or_steer_turn(request).await? { -+ TurnInputSubmission::Started { turn_id, .. } -+ | TurnInputSubmission::Steered { turn_id, .. } => Some(turn_id), -+ TurnInputSubmission::Accepted => None, -+ TurnInputSubmission::NotSubmitted { reason } => { -+ return Err(CodexErr::InvalidRequest(format!( -+ "native input not submitted: {reason:?}" -+ ))); -+ } -+ } -+ } -+ } -+ NativeAgentInput::Message { message, mode } => { -+ let communication = message.into_communication(author, recipient, mode); -+ deliver_communication(thread, communication, start.into(), expected_turn_id).await? -+ } -+ NativeAgentInput::Communication { communication } => { -+ if communication.author != author || communication.recipient != recipient { -+ return Err(CodexErr::InvalidRequest( -+ "native communication attribution mismatch".into(), -+ )); -+ } -+ deliver_communication(thread, communication, start.into(), expected_turn_id).await? -+ } -+ }; -+ Ok( -+ json!({"threadId":thread.session.thread_id, "submissionId":id, "accepted":true, "turn":turn.map(|id|json!({"id":id,"status":"inProgress","items":[]}))}), -+ ) -+} -+ -+async fn deliver_communication( -+ thread: &CodexThread, -+ communication: InterAgentCommunication, -+ start: TurnStartOptions, -+ expected_turn_id: Option, -+) -> Result> { -+ if !communication.trigger_turn && expected_turn_id.is_none() { -+ thread -+ .session -+ .input_queue -+ .enqueue_mailbox_communication(communication.into(), start) -+ .await; -+ return Ok(None); -+ } -+ let mut init = thread.config_snapshot().await.turn_extension_init; -+ init.insert(NativeAgentTransportInput); -+ let request = crate::WithTurnExtensionData::new( -+ TurnInputRequest::new(TurnInput::InterAgentCommunication(communication)).on_start(start), -+ init, -+ ); -+ if let Some(expected) = expected_turn_id { -+ match thread.steer_turn(request, expected).await? { -+ codex_protocol::turn_input::SteerSubmission::Steered { turn_id } => Ok(Some(turn_id)), -+ codex_protocol::turn_input::SteerSubmission::NotSubmitted { reason } => Err( -+ CodexErr::InvalidRequest(format!("native message not steered: {reason:?}")), -+ ), -+ } -+ } else { -+ match thread.start_or_steer_turn(request).await? { -+ TurnInputSubmission::Started { turn_id, .. } -+ | TurnInputSubmission::Steered { turn_id, .. } => Ok(Some(turn_id)), -+ TurnInputSubmission::Accepted => Err(CodexErr::InvalidRequest( -+ "native message lost synchronous acceptance".into(), -+ )), -+ TurnInputSubmission::NotSubmitted { reason } => Err(CodexErr::InvalidRequest(format!( -+ "native message not submitted: {reason:?}" -+ ))), -+ } -+ } -+} -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ use codex_protocol::permissions::{ -+ FileSystemSandboxEntry, FileSystemSandboxPolicy, NetworkSandboxPolicy, -+ }; -+ use codex_utils_path_uri::PathUri; -+ -+ fn path(value: &str) -> AbsolutePathBuf { -+ AbsolutePathBuf::from_absolute_path(value).unwrap() -+ } -+ fn entry(value: &str, access: FileSystemAccessMode) -> FileSystemSandboxEntry { -+ FileSystemSandboxEntry::new( -+ FileSystemPath::Path { -+ path: PathUri::from_abs_path(&path(value)), -+ }, -+ access, -+ ) -+ } -+ -+ #[test] -+ fn native_resume_requires_owned_persisted_thread_session_and_source() { -+ use codex_history::{ResumedHistory, RolloutItem}; -+ use codex_protocol::protocol::{SessionMeta, SessionMetaLine, SubAgentSource}; -+ -+ let root = ThreadId::default(); -+ let child = ThreadId::default(); -+ let session_id = SessionId::from(root); -+ let source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn { -+ parent_thread_id: root, -+ depth: 1, -+ agent_path: Some(AgentPath::try_from("/root/algebra").unwrap()), -+ agent_nickname: None, -+ agent_role: Some("algebra".into()), -+ }); -+ let metadata = RolloutItem::SessionMeta(Box::new(SessionMetaLine { -+ meta: SessionMeta { -+ id: child, -+ session_id, -+ source: source.clone(), -+ ..Default::default() -+ }, -+ git: None, -+ })); -+ let persisted = InitialHistory::Resumed(ResumedHistory { -+ conversation_id: child, -+ history: Arc::new(vec![metadata.clone()]), -+ history_revision: None, -+ rollout_path: None, -+ }); -+ assert!( -+ validate_native_resume_identity(&persisted, Some(child), session_id, &source).is_ok() -+ ); -+ assert!( -+ validate_native_resume_identity(&persisted, Some(root), session_id, &source).is_err() -+ ); -+ assert!( -+ validate_native_resume_identity(&persisted, Some(child), child.into(), &source) -+ .is_err() -+ ); -+ assert!( -+ validate_native_resume_identity( -+ &persisted, -+ Some(child), -+ session_id, -+ &SessionSource::Cli -+ ) -+ .is_err() -+ ); -+ let missing_metadata = InitialHistory::Resumed(ResumedHistory { -+ conversation_id: child, -+ history: Arc::new(Vec::new()), -+ history_revision: None, -+ rollout_path: None, -+ }); -+ assert!( -+ validate_native_resume_identity(&missing_metadata, Some(child), session_id, &source) -+ .is_err() -+ ); -+ for copied_history in [InitialHistory::New, InitialHistory::Forked(vec![metadata])] { -+ assert!( -+ validate_native_resume_identity(&copied_history, Some(child), session_id, &source) -+ .is_err() -+ ); -+ } -+ } -+ -+ #[test] -+ fn trusted_relocation_preserves_secret_denies_and_revokes_source_write() { -+ let workspace = tempfile::tempdir().unwrap(); -+ let from = AbsolutePathBuf::from_absolute_path(workspace.path().join("lead")).unwrap(); -+ let agents = AbsolutePathBuf::from_absolute_path(workspace.path().join("agents")).unwrap(); -+ let to = AbsolutePathBuf::from_absolute_path(agents.join("algebra")).unwrap(); -+ let peer = AbsolutePathBuf::from_absolute_path(agents.join("topology")).unwrap(); -+ let secret = AbsolutePathBuf::from_absolute_path(workspace.path().join("secrets")).unwrap(); -+ for directory in [&from, &to, &peer, &secret] { -+ std::fs::create_dir_all(directory).unwrap(); -+ } -+ let local_entry = |path: &AbsolutePathBuf, access| { -+ FileSystemSandboxEntry::new( -+ FileSystemPath::Path { -+ path: PathUri::from_abs_path(path), -+ }, -+ access, -+ ) -+ }; -+ let parent = PermissionProfile::from_runtime_permissions( -+ &FileSystemSandboxPolicy::restricted(vec![ -+ entry("/", FileSystemAccessMode::Read), -+ local_entry(&from, FileSystemAccessMode::Write), -+ local_entry(&agents, FileSystemAccessMode::Deny), -+ local_entry(&secret, FileSystemAccessMode::Deny), -+ ]), -+ NetworkSandboxPolicy::Restricted, -+ ); -+ let relocated = relocate_workspace_authority(&parent, &from, &to).unwrap(); -+ let fs = relocated.file_system_sandbox_policy(); -+ assert!(fs.can_write_local_path_with_cwd(to.as_path(), to.as_path())); -+ assert!(!fs.can_write_local_path_with_cwd(from.as_path(), to.as_path())); -+ assert!( -+ fs.entries -+ .contains(&local_entry(&secret, FileSystemAccessMode::Deny)) -+ ); -+ assert_eq!( -+ relocated.network_sandbox_policy(), -+ NetworkSandboxPolicy::Restricted -+ ); -+ let destination = PermissionProfile::from_runtime_permissions( -+ &FileSystemSandboxPolicy::restricted(vec![ -+ entry("/", FileSystemAccessMode::Read), -+ local_entry(&to, FileSystemAccessMode::Write), -+ local_entry(&from, FileSystemAccessMode::Deny), -+ local_entry(&peer, FileSystemAccessMode::Deny), -+ ]), -+ NetworkSandboxPolicy::Enabled, -+ ); -+ let bounded = -+ intersect_effective_permission_profiles(&relocated, &destination, to.as_path()) -+ .unwrap(); -+ assert!( -+ bounded -+ .file_system_sandbox_policy() -+ .can_write_local_path_with_cwd(to.as_path(), to.as_path()) -+ ); -+ assert!( -+ !bounded -+ .file_system_sandbox_policy() -+ .can_write_local_path_with_cwd(from.as_path(), to.as_path()) -+ ); -+ assert!( -+ !bounded -+ .file_system_sandbox_policy() -+ .can_read_local_path_with_cwd(peer.as_path(), to.as_path()) -+ ); -+ assert_eq!( -+ bounded.network_sandbox_policy(), -+ NetworkSandboxPolicy::Restricted -+ ); -+ } -+ -+ #[test] -+ fn relocation_requires_an_actual_workspace_write_grant() { -+ let read_only = PermissionProfile::from_runtime_permissions( -+ &FileSystemSandboxPolicy::restricted(vec![entry("/", FileSystemAccessMode::Read)]), -+ NetworkSandboxPolicy::Restricted, -+ ); -+ assert!( -+ relocate_workspace_authority(&read_only, &path("/work/lead"), &path("/work/child")) -+ .is_err() -+ ); -+ } -+ -+ #[test] -+ fn host_override_tools_use_upstream_legacy_normalizer_and_reject_unknown_authority() { -+ let overrides:NativeHostOverrides=serde_json::from_value(json!({"dynamicTools":[{"name":"lean_check","description":"check proof","inputSchema":{"type":"object"}}]})).unwrap(); -+ assert!( -+ matches!(overrides.dynamic_tools.unwrap().as_slice(),[DynamicToolSpec::Function(tool)] if tool.name=="lean_check") -+ ); -+ assert!( -+ serde_json::from_value::(json!({"modelProvider":"parent-relay"})) -+ .is_err() -+ ); -+ } -+ -+ #[test] -+ fn native_network_policy_cannot_lose_proxy_denials_or_import_listener_credentials() { -+ let mut config = codex_network_proxy::NetworkProxyConfig::default(); -+ config.enabled = true; -+ config.upsert_domain_permission( -+ "private.example".into(), -+ codex_network_proxy::NetworkDomainPermission::Deny, -+ codex_network_proxy::normalize_host, -+ ); -+ let captured = EnvironmentNetworkPolicy::from_config(&config, false); -+ let destination = EnvironmentNetworkPolicy::from_config( -+ &codex_network_proxy::NetworkProxyConfig::default(), -+ false, -+ ); -+ assert!(validate_native_network_policy(Some(&captured), Some(&destination)).is_err()); -+ assert!(validate_native_network_policy(Some(&captured), None).is_err()); -+ assert!(validate_native_network_policy(Some(&captured), Some(&captured)).is_ok()); -+ let transport = serde_json::to_value(&captured).unwrap(); -+ assert!(transport.get("proxyUrl").is_none()); -+ assert!(transport.get("credentialBroker").is_none()); -+ } -+ -+ #[test] -+ fn native_messages_preserve_encryption_and_delivery_mode() { -+ let input:NativeAgentInput=serde_json::from_value(json!({"kind":"message","message":{"kind":"encrypted","text":"ciphertext"},"mode":"queueOnly"})).unwrap(); -+ let NativeAgentInput::Message { message, mode } = input else { -+ panic!("wrong input") -+ }; -+ let communication = message.into_communication( -+ AgentPath::root(), -+ AgentPath::try_from("/root/algebra").unwrap(), -+ mode, -+ ); -+ assert_eq!( -+ communication.encrypted_content.as_deref(), -+ Some("ciphertext") -+ ); -+ assert!(!communication.trigger_turn); -+ } -+} -diff --git a/codex-rs/core/src/agent/types.rs b/codex-rs/core/src/agent/types.rs -index 34abb01f..0841745c 100644 ---- a/codex-rs/core/src/agent/types.rs -+++ b/codex-rs/core/src/agent/types.rs -@@ -11,7 +11,8 @@ use std::collections::HashMap; - - /// Registry identity shared by loaded and unloaded agents. - /// Registered agents have an `agent_id`; a reserved spawn can still be awaiting its ID. --#[derive(Clone, Debug, Default)] -+#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] -+#[serde(rename_all = "camelCase")] - pub struct AgentMetadata { - pub agent_id: Option, - pub agent_path: Option, -@@ -56,7 +57,8 @@ pub struct SpawnAgentOptions { - } - - /// Identity and status observed from a loaded agent, without a handle to its runtime. --#[derive(Clone, Debug)] -+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -+#[serde(rename_all = "camelCase")] - pub struct LiveAgent { - pub thread_id: ThreadId, - pub metadata: AgentMetadata, -diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs -index 4b8e0b3c..d5f4442a 100644 ---- a/codex-rs/core/src/codex_thread.rs -+++ b/codex-rs/core/src/codex_thread.rs -@@ -106,11 +106,14 @@ use codex_rollout::state_db::StateDbHandle; - - static LIVE_THREADS: Gauge = Gauge::new("core.threads.live"); - --#[derive(Clone, Debug)] -+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] -+#[serde(rename_all = "camelCase")] - pub struct ThreadConfigSnapshot { - /// Trusted host country inherited by future turns. -+ #[serde(skip)] - pub request_country: RequestCountry, - /// Host data inherited by future turns; not included in persisted settings. -+ #[serde(skip)] - pub turn_extension_init: codex_extension_api::ExtensionDataInit, - pub model: String, - pub model_provider_id: String, -diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs -index d9d87c6e..b9d39bd4 100644 ---- a/codex-rs/core/src/lib.rs -+++ b/codex-rs/core/src/lib.rs -@@ -306,3 +306,10 @@ pub use environment_selection::validate_environment_ids_and_cwds; - - mod runtime_auth; - pub use runtime_auth::build_runtime_auth_manager; -+ -+// Trusted, isolated host-owned native agent transport. -+pub use agent::host::wire::{ -+ NativeAgentInput, NativeChildBootstrap, NativeTurnStartOptions, apply_native_child_bootstrap, -+ apply_native_child_resume_bootstrap, native_agent_input_value, native_agent_snapshot, -+ native_completion_communication, native_submit_agent_input, prepare_native_child_bootstrap, -+}; -diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs -index 912b03fd..06e40706 100644 ---- a/codex-rs/core/src/session/mod.rs -+++ b/codex-rs/core/src/session/mod.rs -@@ -3207,7 +3207,7 @@ impl Session { - .map(|task| Arc::clone(&task.turn_context)) - } - -- async fn active_turn_context_and_cancellation_token( -+ pub(crate) async fn active_turn_context_and_cancellation_token( - &self, - ) -> Option<(Arc, CancellationToken)> { - let active = self.active_turn.lock().await; -diff --git a/codex-rs/core/src/session/turn_input.rs b/codex-rs/core/src/session/turn_input.rs -index ab79e360..a2130097 100644 ---- a/codex-rs/core/src/session/turn_input.rs -+++ b/codex-rs/core/src/session/turn_input.rs -@@ -460,10 +460,15 @@ pub(super) async fn start_or_steer( - submission_id: String, - realtime_handoff_id: Option, - ) -> CodexResult { -+ let host_transport_input = request.turn_extension_init.as_ref().is_some_and(|data| { -+ data.get::() -+ .is_some() -+ }); - if matches!( - request.request.input, - SubmittedTurnInput::InterAgentCommunication(_) -- ) { -+ ) && !host_transport_input -+ { - return agent::submit(session, request, submission_id).await; - } - let WithTurnExtensionData { -@@ -480,6 +485,7 @@ pub(super) async fn start_or_steer( - .. - } = request; - let has_explicit_input = match &input { -+ SubmittedTurnInput::InterAgentCommunication(_) if host_transport_input => true, - SubmittedTurnInput::UserInput { content, .. } => !content.is_empty(), - SubmittedTurnInput::ResponseItem(ResponseItem::FunctionCallOutput { - call_id: None, -@@ -562,6 +568,14 @@ pub(super) async fn start_or_steer( - .await; - let mut task_input = - merge_additional_context_input(session, &turn_context, additional_context).await; -+ if host_transport_input { -+ // Mail accepted before this native trigger belongs to its first -+ // sampling batch. Leaving it in pending_input would defer it -+ // until after the explicit trigger has already been sampled. -+ let mut mailbox_input = session.input_queue.drain_mailbox_input_items().await.0; -+ mailbox_input.extend(task_input); -+ task_input = mailbox_input; -+ } - if has_explicit_input { - task_input.push( - pending_turn_input( -@@ -774,6 +788,10 @@ async fn steer( - submission_id: String, - realtime_handoff_id: Option, - ) -> CodexResult { -+ let host_transport_input = request.turn_extension_init.as_ref().is_some_and(|data| { -+ data.get::() -+ .is_some() -+ }); - let WithTurnExtensionData { - mut request, - turn_extension_init, -@@ -787,7 +805,10 @@ async fn steer( - responsesapi_client_metadata, - .. - } = request; -- if !matches!(&input, SubmittedTurnInput::UserInput { .. }) { -+ if !matches!(&input, SubmittedTurnInput::UserInput { .. }) -+ && !(host_transport_input -+ && matches!(&input, SubmittedTurnInput::InterAgentCommunication(_))) -+ { - return Err(CodexErr::InvalidRequest( - "only user input can steer a turn".to_string(), - )); -diff --git a/codex-rs/core/src/session/turn_input_tests.rs b/codex-rs/core/src/session/turn_input_tests.rs -index 5e51ce40..9b51532c 100644 ---- a/codex-rs/core/src/session/turn_input_tests.rs -+++ b/codex-rs/core/src/session/turn_input_tests.rs -@@ -114,6 +114,215 @@ async fn submit_steer_only( - .expect("steer-only submission should be valid") - } - -+#[tokio::test] -+async fn native_message_steer_preserves_author_and_requires_matching_active_turn() { -+ use crate::agent::host::wire::NativeAgentTransportInput; -+ use crate::agent::types::{AgentMessage, MessageDeliveryMode}; -+ use codex_extension_api::ExtensionDataInit; -+ -+ let (session, turn_context, _events) = make_session_and_context_with_rx().await; -+ session -+ .spawn_task( -+ Arc::clone(&turn_context), -+ Vec::new(), -+ NeverEndingTask { -+ kind: TaskKind::Regular, -+ listen_to_cancellation_token: true, -+ }, -+ ) -+ .await; -+ let communication = AgentMessage::Encrypted("amended objective".into()).into_communication( -+ AgentPath::try_from("/root/expert").unwrap(), -+ AgentPath::root(), -+ MessageDeliveryMode::TriggerTurn, -+ ); -+ let request = || { -+ let mut init = ExtensionDataInit::default(); -+ init.insert(NativeAgentTransportInput); -+ WithTurnExtensionData::new( -+ TurnInputRequest::new(SubmittedTurnInput::InterAgentCommunication( -+ communication.clone(), -+ )), -+ init, -+ ) -+ }; -+ let ordinary = handle( -+ &session, -+ TurnInputRequest::new(SubmittedTurnInput::InterAgentCommunication( -+ communication.clone(), -+ )), -+ TurnInputMode::Steer { -+ expected_turn_id: turn_context.sub_id.clone(), -+ }, -+ "untrusted-message".into(), -+ ) -+ .await -+ .expect_err("ordinary message steering remains unsupported"); -+ assert!( -+ ordinary -+ .to_string() -+ .contains("only user input can steer a turn") -+ ); -+ let mismatch = handle( -+ &session, -+ request(), -+ TurnInputMode::Steer { -+ expected_turn_id: "wrong-turn".into(), -+ }, -+ "native-mismatch".into(), -+ ) -+ .await -+ .unwrap(); -+ assert_eq!( -+ mismatch, -+ TurnInputSubmission::NotSubmitted { -+ reason: NotSubmittedReason::ExpectedTurnMismatch { -+ expected: "wrong-turn".into(), -+ actual: turn_context.sub_id.clone(), -+ }, -+ } -+ ); -+ assert!( -+ session -+ .input_queue -+ .get_pending_input(&session.active_turn) -+ .await -+ .0 -+ .is_empty() -+ ); -+ let accepted = handle( -+ &session, -+ request(), -+ TurnInputMode::Steer { -+ expected_turn_id: turn_context.sub_id.clone(), -+ }, -+ "native-notice".into(), -+ ) -+ .await -+ .unwrap(); -+ assert_eq!( -+ accepted, -+ TurnInputSubmission::Steered { -+ turn_id: turn_context.sub_id.clone(), -+ root_turn_id: turn_context.root_turn_id(), -+ } -+ ); -+ assert_eq!( -+ session -+ .input_queue -+ .get_pending_input(&session.active_turn) -+ .await -+ .0, -+ vec![TurnInput::InterAgentCommunication( -+ communication.clone().into() -+ )], -+ ); -+ session.abort_all_tasks(TurnAbortReason::Interrupted).await; -+ let idle = handle( -+ &session, -+ request(), -+ TurnInputMode::Steer { -+ expected_turn_id: turn_context.sub_id.clone(), -+ }, -+ "native-idle-notice".into(), -+ ) -+ .await -+ .unwrap(); -+ assert_eq!( -+ idle, -+ TurnInputSubmission::NotSubmitted { -+ reason: NotSubmittedReason::NoActiveTurn -+ } -+ ); -+ assert!(session.active_turn.lock().await.is_none()); -+} -+ -+#[tokio::test] -+async fn native_trigger_samples_queued_mail_before_its_first_response() { -+ use crate::agent::host::wire::NativeAgentTransportInput; -+ use crate::agent::types::{AgentMessage, MessageDeliveryMode}; -+ use crate::session::tests::make_session_and_context_with_auth_and_config_and_rx; -+ use codex_extension_api::ExtensionDataInit; -+ use core_test_support::responses; -+ -+ let server = responses::start_mock_server().await; -+ let requests = responses::mount_sse_once( -+ &server, -+ responses::sse(vec![ -+ responses::ev_response_created("native-mailbox"), -+ responses::ev_completed("native-mailbox"), -+ ]), -+ ) -+ .await; -+ let mut provider = codex_model_provider_info::built_in_model_providers(None)["openai"].clone(); -+ provider.base_url = Some(format!("{}/v1", server.uri())); -+ provider.supports_websockets = false; -+ let (session, _turn_context, events) = make_session_and_context_with_auth_and_config_and_rx( -+ codex_login::CodexAuth::from_api_key("offline-native-mailbox"), -+ Vec::new(), -+ move |config| { -+ config.model = Some("gpt-5.2".into()); -+ config.model_provider = provider; -+ config.features.enable(Feature::MultiAgentV2).unwrap(); -+ config.features.disable(Feature::TokenBudget).unwrap(); -+ }, -+ ) -+ .await; -+ let message = |text: &str, mode| { -+ AgentMessage::Encrypted(text.into()).into_communication( -+ AgentPath::root(), -+ AgentPath::root(), -+ mode, -+ ) -+ }; -+ session -+ .input_queue -+ .enqueue_mailbox_communication( -+ message("queued-before-trigger", MessageDeliveryMode::QueueOnly).into(), -+ Default::default(), -+ ) -+ .await; -+ let mut init = ExtensionDataInit::default(); -+ init.insert(NativeAgentTransportInput); -+ let submission = handle( -+ &session, -+ WithTurnExtensionData::new( -+ TurnInputRequest::new(SubmittedTurnInput::InterAgentCommunication(message( -+ "current-native-trigger", -+ MessageDeliveryMode::TriggerTurn, -+ ))), -+ init, -+ ), -+ TurnInputMode::StartOrSteer, -+ "native-mailbox-turn".into(), -+ ) -+ .await -+ .expect("native trigger accepted"); -+ assert!(matches!(submission, TurnInputSubmission::Started { .. })); -+ tokio::time::timeout(std::time::Duration::from_secs(10), async { -+ loop { -+ let event = events.recv().await.expect("turn events open"); -+ if matches!(event.msg, EventMsg::TurnComplete(_)) { -+ break; -+ } -+ } -+ }) -+ .await -+ .expect("loopback native turn completed"); -+ let input = serde_json::to_string(&requests.single_request().input()).unwrap(); -+ let queued = input -+ .find("queued-before-trigger") -+ .expect("queued mail in first request"); -+ let trigger = input -+ .find("current-native-trigger") -+ .expect("trigger in first request"); -+ assert!( -+ queued < trigger, -+ "accepted native mailbox order must be preserved" -+ ); -+ assert!(!session.input_queue.has_pending_mailbox_items().await); -+} -+ - #[tokio::test] - #[expect( - clippy::await_holding_invalid_type, -diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs -index b11e9bfa..c1c360b7 100644 ---- a/codex-rs/core/src/thread_manager.rs -+++ b/codex-rs/core/src/thread_manager.rs -@@ -2828,6 +2828,9 @@ impl ThreadManagerState { - } - (_, control) => control, - }; -+ if let AgentControlInit::Provided { control, .. } = &agent_control { -+ control.configure_startup(&mut thread_extension_init, &config); -+ } - // Both resume entry points must restore identities before children can be loaded lazily. - if let InitialHistory::Resumed(resumed) = &initial_history - && initial_history.get_multi_agent_version() == Some(MultiAgentVersion::V2) -@@ -2875,6 +2878,8 @@ impl ThreadManagerState { - .await, - ), - }; -+ let transported_originator = -+ thread_extension_init.get::(); - let (originator, attachment_source) = match prepared_child { - Some(child) => (child.originator, child.attachment_source), - None => ( -@@ -2891,6 +2896,14 @@ impl ThreadManagerState { - .filter(|_| matches!(&initial_history, InitialHistory::Forked(_))), - ), - }; -+ let multi_agent_version = if transported_originator.is_some() { -+ Some(MultiAgentVersion::V2) -+ } else { -+ multi_agent_version -+ }; -+ let originator = transported_originator -+ .map(|value| value.0.clone()) -+ .unwrap_or(originator); - let startup_context = ThreadStartupContext { - history_initialization, - instructions, -diff --git a/codex-rs/exec-server/src/lib.rs b/codex-rs/exec-server/src/lib.rs -index 6240e8ab..65fe2e39 100644 ---- a/codex-rs/exec-server/src/lib.rs -+++ b/codex-rs/exec-server/src/lib.rs -@@ -100,6 +100,7 @@ pub use codex_file_system::FileSystemReadStream; - pub use codex_file_system::FileSystemResult; - pub use codex_file_system::FileSystemSandboxContext; - pub use codex_file_system::GetMetadataOptions; -+pub use codex_file_system::MAX_METADATA_BATCH_PROBES; - pub use codex_file_system::ReadDirectoryEntry; - pub use codex_file_system::ReadFileOptions; - pub use codex_file_system::RemoveOptions; -@@ -110,6 +111,7 @@ pub use codex_file_system::WalkOptions; - pub use codex_file_system::WalkOutcome; - pub use codex_file_system::WindowsSandboxSelection; - pub use codex_file_system::WriteFileOptions; -+pub use codex_file_system::metadata_batch_fits; - pub use codex_network_proxy::TcpUpstreamProxy; - pub use codex_protocol::shell_environment::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR; - pub use environment::CODEX_EXEC_SERVER_NOISE_CHATGPT_ACCOUNT_ID_ENV_VAR; -diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs -index 2907eb56..5258a3fa 100644 ---- a/codex-rs/exec/src/lib.rs -+++ b/codex-rs/exec/src/lib.rs -@@ -2386,6 +2386,15 @@ async fn handle_server_request( - ) { - let method = server_request_method_name(&request); - let handle_result = match request { -+ ServerRequest::TheoremosAgentControlRequest { request_id, .. } => { -+ reject_server_request( -+ client, -+ request_id, -+ &method, -+ "TheoremOS AgentControl requires its trusted stdio host".into(), -+ ) -+ .await -+ } - ServerRequest::McpServerElicitationRequest { request_id, params } => { - // Exec auto-cancels elicitation instead of surfacing it - // interactively. Preserve that behavior for attached subagent -diff --git a/codex-rs/execpolicy/src/policy.rs b/codex-rs/execpolicy/src/policy.rs -index 206094f3..47be6946 100644 ---- a/codex-rs/execpolicy/src/policy.rs -+++ b/codex-rs/execpolicy/src/policy.rs -@@ -35,11 +35,66 @@ pub struct Policy { - } - - /// A requirements-owned execution policy with order-independent equality. --#[derive(Debug, Clone)] -+#[derive(Debug, Clone, Serialize, Deserialize)] - pub struct RequirementsExecPolicy { - policy: Policy, - } - -+/// Complete trusted transport snapshot. Unknown executable rule implementations fail export. -+#[derive(Serialize, Deserialize)] -+#[serde(rename_all = "camelCase")] -+struct PolicySnapshot { -+ prefix_rules: Vec, -+ network_rules: Vec, -+ host_executables: HashMap>, -+} -+ -+impl Serialize for Policy { -+ fn serialize( -+ &self, -+ serializer: S, -+ ) -> std::result::Result { -+ let prefix_rules = self -+ .rules_by_program -+ .iter_all() -+ .flat_map(|(_, rules)| rules) -+ .map(|rule| { -+ rule.as_any() -+ .downcast_ref::() -+ .cloned() -+ .ok_or_else(|| { -+ ::custom( -+ "unsupported transported exec-policy rule", -+ ) -+ }) -+ }) -+ .collect::, _>>()?; -+ PolicySnapshot { -+ prefix_rules, -+ network_rules: self.network_rules.clone(), -+ host_executables: self.host_executables_by_name.clone(), -+ } -+ .serialize(serializer) -+ } -+} -+ -+impl<'de> Deserialize<'de> for Policy { -+ fn deserialize>( -+ deserializer: D, -+ ) -> std::result::Result { -+ let snapshot = PolicySnapshot::deserialize(deserializer)?; -+ let mut rules = MultiMap::new(); -+ for rule in snapshot.prefix_rules { -+ rules.insert(rule.pattern.first.to_string(), Arc::new(rule) as RuleRef); -+ } -+ Ok(Self::from_parts( -+ rules, -+ snapshot.network_rules, -+ snapshot.host_executables, -+ )) -+ } -+} -+ - impl RequirementsExecPolicy { - pub fn new(policy: Policy) -> Self { - Self { policy } -@@ -593,3 +648,44 @@ impl Evaluation { - } - } - } -+ -+#[cfg(test)] -+mod host_transport_tests { -+ use super::*; -+ #[test] -+ fn policy_snapshot_roundtrip_keeps_canonical_rules_and_host_executables() { -+ let mut rules = MultiMap::new(); -+ rules.insert( -+ "Git".to_string(), -+ Arc::new(PrefixRule { -+ pattern: PrefixPattern { -+ canonical_matching: true, -+ first: Arc::from("Git"), -+ rest: vec![PatternToken::Alts(vec!["status".into(), "diff".into()])].into(), -+ }, -+ decision: Decision::Allow, -+ justification: Some("captured rule".into()), -+ }) as RuleRef, -+ ); -+ let policy = Policy::from_parts( -+ rules, -+ vec![NetworkRule { -+ host: "example.com".into(), -+ protocol: NetworkRuleProtocol::Https, -+ decision: Decision::Forbidden, -+ justification: None, -+ }], -+ HashMap::from([( -+ "git".into(), -+ vec![AbsolutePathBuf::from_absolute_path("/usr/bin/git").unwrap()].into(), -+ )]), -+ ); -+ let encoded = serde_json::to_value(&policy).unwrap(); -+ let decoded: Policy = serde_json::from_value(encoded).unwrap(); -+ assert_eq!(policy.rules().len(), decoded.rules().len()); -+ assert_eq!( -+ serde_json::to_value(&policy).unwrap(), -+ serde_json::to_value(&decoded).unwrap() -+ ); -+ } -+} -diff --git a/codex-rs/execpolicy/src/rule.rs b/codex-rs/execpolicy/src/rule.rs -index 92d94baa..36a1d609 100644 ---- a/codex-rs/execpolicy/src/rule.rs -+++ b/codex-rs/execpolicy/src/rule.rs -@@ -19,7 +19,7 @@ pub(crate) fn canonical_key(token: &str) -> impl Iterator + '_ { - } - - /// Matches a single command token, either a fixed string or one of several allowed alternatives. --#[derive(Clone, Debug, Eq, PartialEq)] -+#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] - pub enum PatternToken { - Single(String), - Alts(Vec), -@@ -36,7 +36,7 @@ impl PatternToken { - - /// Prefix matcher for commands with support for alternative match tokens. - /// First token is fixed since we key by the first token in policy. --#[derive(Clone, Debug, Eq, PartialEq)] -+#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] - pub struct PrefixPattern { - pub canonical_matching: bool, - pub first: Arc, -@@ -120,14 +120,14 @@ impl RuleMatch { - } - } - --#[derive(Clone, Debug, Eq, PartialEq)] -+#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] - pub struct PrefixRule { - pub pattern: PrefixPattern, - pub decision: Decision, - pub justification: Option, - } - --#[derive(Clone, Copy, Debug, Eq, PartialEq)] -+#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] - pub enum NetworkRuleProtocol { - Http, - Https, -@@ -158,7 +158,7 @@ impl NetworkRuleProtocol { - } - } - --#[derive(Clone, Debug, Eq, PartialEq)] -+#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] - pub struct NetworkRule { - pub host: String, - pub protocol: NetworkRuleProtocol, -diff --git a/codex-rs/ext/skills/src/loader/io_test_support.rs b/codex-rs/ext/skills/src/loader/io_test_support.rs -index 3abebbe5..be879377 100644 ---- a/codex-rs/ext/skills/src/loader/io_test_support.rs -+++ b/codex-rs/ext/skills/src/loader/io_test_support.rs -@@ -24,6 +24,7 @@ use tokio::sync::Semaphore; - #[derive(Clone, Copy)] - pub(super) enum ManifestMetadataBehavior { - Immediate, -+ Batch, - WaitForSkillRead, - } - -@@ -31,6 +32,7 @@ pub(super) struct RecordingFileSystem<'a> { - inner: &'a dyn ExecutorFileSystem, - read_files: Mutex>, - metadata_files: Mutex>, -+ pub(super) metadata_batches: Mutex>>, - pub(super) walks: AtomicUsize, - manifest_metadata_behavior: ManifestMetadataBehavior, - skill_read_started: AtomicBool, -@@ -56,6 +58,7 @@ impl<'a> RecordingFileSystem<'a> { - inner, - read_files: Mutex::new(Vec::new()), - metadata_files: Mutex::new(Vec::new()), -+ metadata_batches: Mutex::new(Vec::new()), - walks: AtomicUsize::new(/*v*/ 0), - manifest_metadata_behavior, - skill_read_started: AtomicBool::new(/*v*/ false), -@@ -169,6 +172,29 @@ impl ExecutorFileSystem for RecordingFileSystem<'_> { - self.inner.get_metadata(path, options, sandbox) - } - -+ fn get_metadata_batch<'a>( -+ &'a self, -+ paths: &'a [PathUri], -+ options: GetMetadataOptions, -+ sandbox: Option<&'a FileSystemSandboxContext>, -+ ) -> ExecutorFileSystemFuture<'a, Vec>> { -+ self.metadata_batches.lock().unwrap().push(paths.to_vec()); -+ if matches!( -+ self.manifest_metadata_behavior, -+ ManifestMetadataBehavior::Batch -+ ) { -+ Box::pin(async move { -+ let mut results = Vec::with_capacity(paths.len()); -+ for path in paths { -+ results.push(self.inner.get_metadata(path, options, sandbox).await); -+ } -+ Ok(results) -+ }) -+ } else { -+ Box::pin(async { Err(std::io::ErrorKind::Unsupported.into()) }) -+ } -+ } -+ - fn read_directory<'a>( - &'a self, - path: &'a PathUri, -diff --git a/codex-rs/ext/skills/src/loader/namespace.rs b/codex-rs/ext/skills/src/loader/namespace.rs -index d991b6c4..07d66e4a 100644 ---- a/codex-rs/ext/skills/src/loader/namespace.rs -+++ b/codex-rs/ext/skills/src/loader/namespace.rs -@@ -2,7 +2,12 @@ use std::collections::HashMap; - use std::collections::HashSet; - - use codex_exec_server::EnvironmentAccess; -+use codex_exec_server::GetMetadataOptions; -+use codex_exec_server::MAX_METADATA_BATCH_PROBES; -+use codex_exec_server::metadata_batch_fits; - use codex_utils_path_uri::PathUri; -+use codex_utils_plugins::DISCOVERABLE_PLUGIN_MANIFEST_PATHS; -+use codex_utils_plugins::plugin_namespace::plugin_namespace_from_manifest_uri; - use codex_utils_plugins::plugin_namespace_for_root_uri; - use futures::StreamExt; - -@@ -71,6 +76,13 @@ impl SkillNamespaceResolver { - let lookup_roots = std::iter::once(root.clone()) - .chain(namespace_roots.iter().cloned()) - .collect::>(); -+ let candidate_roots = lookup_roots -+ .iter() -+ .flat_map(PathUri::ancestors) -+ .chain(plugin_roots.iter().cloned()) -+ .collect::>(); -+ let manifest_files = probe_manifest_files(fs, candidate_roots).await; -+ let manifest_files = manifest_files.as_ref(); - let mut pending_lookups = lookup_roots - .iter() - .cloned() -@@ -89,7 +101,21 @@ impl SkillNamespaceResolver { - namespaces_by_root.extend( - futures::stream::iter(probe_roots) - .map(|manifest_root| async move { -- let namespace = plugin_namespace_for_root_uri(fs, &manifest_root).await; -+ let namespace = match manifest_files { -+ Some(files) => { -+ let first = DISCOVERABLE_PLUGIN_MANIFEST_PATHS -+ .iter() -+ .find_map(|path| files.get(&manifest_root.join(path).ok()?)); -+ match first { -+ Some(path) => { -+ plugin_namespace_from_manifest_uri(fs, &manifest_root, path) -+ .await -+ } -+ None => None, -+ } -+ } -+ None => plugin_namespace_for_root_uri(fs, &manifest_root).await, -+ }; - (manifest_root, namespace) - }) - .buffered(MAX_CONCURRENT_SKILL_LOADS) -@@ -163,6 +189,48 @@ impl SkillNamespaceResolver { - } - } - -+/// Each eligible root is probed once per scan. Only metadata is prefetched: -+/// namespace resolution still reads the closest applicable manifest first. -+async fn probe_manifest_files( -+ fs: &dyn EnvironmentAccess, -+ roots: HashSet, -+) -> Option> { -+ let candidates = roots -+ .into_iter() -+ .flat_map(|root| { -+ DISCOVERABLE_PLUGIN_MANIFEST_PATHS -+ .iter() -+ .filter_map(move |path| root.join(path).ok()) -+ }) -+ .collect::>(); -+ let mut remaining = candidates.as_slice(); -+ let mut files = HashSet::new(); -+ while !remaining.is_empty() { -+ let mut len = remaining.len().min(MAX_METADATA_BATCH_PROBES); -+ while !metadata_batch_fits(&remaining[..len]) { -+ len /= 2; -+ if len == 0 { -+ return None; -+ } -+ } -+ let (batch, rest) = remaining.split_at(len); -+ let results = fs -+ .get_metadata_batch(batch, GetMetadataOptions::default()) -+ .await -+ .ok()?; -+ if results.len() != batch.len() { -+ return None; -+ } -+ for (path, result) in batch.iter().zip(results) { -+ if result.is_ok_and(|metadata| metadata.is_file) { -+ files.insert(path.clone()); -+ } -+ } -+ remaining = rest; -+ } -+ Some(files) -+} -+ - /// The completed namespace resolution for a skill root. - #[derive(Clone, Debug, Eq, PartialEq)] - pub(crate) enum ResolvedSkillNamespace { -diff --git a/codex-rs/ext/skills/src/loader/namespace_tests.rs b/codex-rs/ext/skills/src/loader/namespace_tests.rs -index d5e172c9..9daa94b3 100644 ---- a/codex-rs/ext/skills/src/loader/namespace_tests.rs -+++ b/codex-rs/ext/skills/src/loader/namespace_tests.rs -@@ -1,3 +1,4 @@ -+use codex_exec_server::ExecutorFileSystem; - use codex_exec_server::FileSystemEnvironmentAccessor; - use codex_exec_server::LOCAL_FS; - #[cfg(unix)] -@@ -9,6 +10,7 @@ use pretty_assertions::assert_eq; - use std::collections::HashSet; - use std::fs; - use std::path::Path; -+use std::sync::Arc; - use tempfile::TempDir; - - #[cfg(unix)] -@@ -17,6 +19,8 @@ use crate::loader::HostSkillRoot; - use crate::loader::load_host_skill_root; - - use super::SkillNamespaceResolver; -+use crate::loader::io_test_support::ManifestMetadataBehavior; -+use crate::loader::io_test_support::RecordingFileSystem; - - fn canonical_uri(path: &Path) -> PathUri { - PathUri::from_host_native_path(fs::canonicalize(path).expect("canonical path")) -@@ -91,6 +95,9 @@ async fn nearest_valid_manifest_overrides_or_falls_back_to_outer_namespace() { - write_manifest(&plugin_root, r#"{"name":"outer"}"#); - let nested_root = write_manifest(&nested_plugin, r#"{"name":"nested"}"#); - let invalid_root = write_manifest(&invalid_plugin, "not json"); -+ let secondary = invalid_plugin.join(".claude-plugin/plugin.json"); -+ fs::create_dir_all(secondary.parent().unwrap()).unwrap(); -+ fs::write(&secondary, r#"{"name":"lower-priority"}"#).unwrap(); - let direct_skill = write_skill(&skills_root, "direct"); - let nested_skill = write_skill(&nested_plugin, "skills/search"); - let fallback_skill = write_skill(&invalid_plugin, "skills/fallback"); -@@ -109,6 +116,63 @@ async fn nearest_valid_manifest_overrides_or_falls_back_to_outer_namespace() { - ); - } - -+#[tokio::test] -+async fn shared_ancestors_are_batched_and_a_failed_text_read_falls_back_to_the_parent() { -+ let temp = TempDir::new().unwrap(); -+ let outer = temp.path().join("outer"); -+ let nested = outer.join("nested"); -+ let outer_uri = write_manifest(&outer, r#"{"name":"outer"}"#); -+ let nested_uri = write_manifest(&nested, ""); -+ let unreadable = nested.join(".codex-plugin/plugin.json"); -+ fs::write(&unreadable, [0xff]).unwrap(); -+ let secondary = nested.join(".claude-plugin/plugin.json"); -+ fs::create_dir_all(secondary.parent().unwrap()).unwrap(); -+ fs::write(&secondary, r#"{"name":"lower-priority"}"#).unwrap(); -+ let left = write_skill(&nested, "left"); -+ let right = write_skill(&nested, "right"); -+ let roots = HashSet::from([left.parent().unwrap(), right.parent().unwrap()]); -+ for behavior in [ -+ ManifestMetadataBehavior::Batch, -+ ManifestMetadataBehavior::Immediate, -+ ] { -+ let recording = Arc::new(RecordingFileSystem::new(LOCAL_FS.as_ref(), behavior)); -+ let executor: Arc = recording.clone(); -+ let resolver = SkillNamespaceResolver::discover( -+ &FileSystemEnvironmentAccessor::unrestricted(&executor), -+ &nested_uri, -+ &[left.clone(), right.clone()], -+ HashSet::new(), -+ roots.clone(), -+ ) -+ .await; -+ for skill in [&left, &right] { -+ assert_eq!( -+ resolver.for_skill(&nested_uri, skill).qualify("skill"), -+ "outer:skill" -+ ); -+ } -+ let calls = recording.calls(); -+ let mut reads = vec![ -+ canonical_uri(&unreadable), -+ outer_uri.join(".codex-plugin/plugin.json").unwrap(), -+ ]; -+ reads.sort_by_key(ToString::to_string); -+ assert_eq!(calls.read_files, reads); -+ let batches = recording.metadata_batches.lock().unwrap(); -+ assert!(batches.iter().any(|paths| paths.len() > 1)); -+ if matches!(behavior, ManifestMetadataBehavior::Batch) { -+ let paths = batches.iter().flatten().collect::>(); -+ assert_eq!( -+ paths.iter().copied().collect::>().len(), -+ paths.len() -+ ); -+ assert!(calls.metadata_files.is_empty()); -+ } else { -+ assert!(calls.metadata_files.contains(&canonical_uri(&unreadable))); -+ } -+ } -+} -+ - #[cfg(unix)] - #[tokio::test] - async fn symlinked_external_directories_do_not_inherit_plugin_namespace() { -diff --git a/codex-rs/protocol/src/capabilities.rs b/codex-rs/protocol/src/capabilities.rs -index 651861e4..2f48fe20 100644 ---- a/codex-rs/protocol/src/capabilities.rs -+++ b/codex-rs/protocol/src/capabilities.rs -@@ -22,7 +22,7 @@ pub struct SelectedCapabilityRoot { - /// The index is each root's position in the original thread list. Executor skills assign - /// aliases (`e0`, `e1`, ...) in root order. Keeping the index lets us split roots across - /// environments and combine them again without changing those aliases. --#[derive(Clone, Debug, Default, PartialEq, Eq)] -+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] - pub struct EnvironmentCapabilityRoots(Arc<[(usize, SelectedCapabilityRoot)]>); - - impl EnvironmentCapabilityRoots { -diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs -index 87ffe6dc..9d1098ec 100644 ---- a/codex-rs/protocol/src/config_types.rs -+++ b/codex-rs/protocol/src/config_types.rs -@@ -236,7 +236,7 @@ pub type EnvironmentVariablePattern = WildMatchPattern<'*', '?'>; - /// 3. If `exclude` is not empty, filter the map using the provided patterns. - /// 4. Insert any entries from `r#set` into the map. - /// 5. If non-empty, filter the map using the `include_only` patterns. --#[derive(Debug, Clone, PartialEq)] -+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] - pub struct ShellEnvironmentPolicy { - /// Starting point when building the environment. - pub inherit: ShellEnvironmentPolicyInherit, -@@ -246,12 +246,14 @@ pub struct ShellEnvironmentPolicy { - pub ignore_default_excludes: bool, - - /// Environment variable names to exclude from the environment. -+ #[serde(with = "environment_variable_patterns")] - pub exclude: Vec, - - /// (key, value) pairs to insert in the environment. - pub r#set: HashMap, - - /// Environment variable names to retain in the environment. -+ #[serde(with = "environment_variable_patterns")] - pub include_only: Vec, - - /// If true, the shell profile will be used to run the command. -@@ -978,3 +980,26 @@ mod tests { - assert_eq!(expected, base.merge(&overlay)); - } - } -+ -+mod environment_variable_patterns { -+ use super::EnvironmentVariablePattern; -+ use serde::{Deserialize, Serialize}; -+ pub fn serialize( -+ patterns: &[EnvironmentVariablePattern], -+ serializer: S, -+ ) -> Result { -+ patterns -+ .iter() -+ .map(EnvironmentVariablePattern::pattern) -+ .collect::>() -+ .serialize(serializer) -+ } -+ pub fn deserialize<'de, D: serde::Deserializer<'de>>( -+ deserializer: D, -+ ) -> Result, D::Error> { -+ Ok(Vec::::deserialize(deserializer)? -+ .iter() -+ .map(|pattern| EnvironmentVariablePattern::new(pattern)) -+ .collect()) -+ } -+} -diff --git a/codex-rs/protocol/src/environment.rs b/codex-rs/protocol/src/environment.rs -index b5ad7ae2..75fc773d 100644 ---- a/codex-rs/protocol/src/environment.rs -+++ b/codex-rs/protocol/src/environment.rs -@@ -14,13 +14,14 @@ use codex_execpolicy::RequirementsExecPolicy; - use codex_network_proxy::EnvironmentNetworkPolicy; - use codex_utils_absolute_path::AbsolutePathBuf; - use codex_utils_path_uri::PathUri; -+use serde::{Deserialize, Serialize}; - - /// An environment requested by a caller, before attaching the receiving thread's roots. - /// - /// Callers choose the environment and paths, but startup may still need to load roots from - /// saved history or inherited attachments. Keeping this input separate lets the receiving - /// thread construct a complete selection instead of filling in missing roots later. --#[derive(Debug, Clone, PartialEq)] -+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] - pub struct TurnEnvironmentRequest { - pub environment_id: String, - pub cwd: PathUri, -@@ -32,7 +33,7 @@ pub struct TurnEnvironmentRequest { - /// - /// Runtime snapshots carry this value so capability discovery uses the roots captured - /// with the environment. Construct it from a request and the receiving thread's roots. --#[derive(Debug, Clone, PartialEq)] -+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] - pub struct TurnEnvironmentSelection { - pub environment_id: String, - pub cwd: PathUri, -@@ -82,7 +83,7 @@ impl TurnEnvironmentSelection { - } - - /// The environments captured by a thread and its fallback working directory. --#[derive(Debug, Clone, PartialEq)] -+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] - pub struct TurnEnvironmentSelections { - pub legacy_fallback_cwd: AbsolutePathBuf, - pub environments: Vec, -@@ -147,7 +148,7 @@ impl TurnEnvironmentRequests { - - /// Configuration supplied for a thread's selected environment. - #[allow(clippy::large_enum_variant)] --#[derive(Clone, Debug, PartialEq)] -+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] - pub enum EnvironmentConfigState { - /// Preserve the existing thread-derived environment configuration. - FromThread, -@@ -188,7 +189,7 @@ pub fn has_full_access<'a>( - } - - /// Resolved configuration for a thread/environment attachment. --#[derive(Clone, PartialEq)] -+#[derive(Clone, PartialEq, Serialize, Deserialize)] - pub struct EnvironmentConfig { - /// Hooks from this environment's effective managed requirements. - pub environment_hooks: crate::hooks::HookEventsToml, -diff --git a/codex-rs/protocol/src/mcp_policy.rs b/codex-rs/protocol/src/mcp_policy.rs -index cb371c0c..6a02c3c4 100644 ---- a/codex-rs/protocol/src/mcp_policy.rs -+++ b/codex-rs/protocol/src/mcp_policy.rs -@@ -1,14 +1,15 @@ - use serde::Deserialize; -+use serde::Serialize; - use std::collections::BTreeMap; - - /// Additional managed MCP restrictions supplied by an environment owner. --#[derive(Debug, Clone, Default, PartialEq, Eq)] -+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] - pub struct EnvironmentMcpPolicy { - pub servers: Option>, - pub plugins: Option>, - } - --#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] -+#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] - #[serde(untagged)] - pub enum McpServerIdentity { - Command { command: String }, -@@ -16,7 +17,7 @@ pub enum McpServerIdentity { - } - - /// String matching operations available to managed MCP server matchers. --#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] -+#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] - #[serde(tag = "match", rename_all = "snake_case", deny_unknown_fields)] - pub enum McpServerValueMatcher { - Exact { value: String }, -@@ -24,7 +25,7 @@ pub enum McpServerValueMatcher { - Regex { expression: String }, - } - --#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] -+#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] - #[serde(deny_unknown_fields)] - pub struct McpServerCommandMatcher { - pub executable: String, -@@ -55,6 +56,20 @@ pub enum McpServerRequirement { - Url(McpServerValueMatcher), - } - -+impl Serialize for McpServerRequirement { -+ fn serialize(&self, serializer: S) -> Result { -+ let identity = match self { -+ Self::Identity { identity } => serde_json::to_value(identity), -+ Self::Command(command) => { -+ serde_json::to_value(command).map(|command| serde_json::json!({"command":command})) -+ } -+ Self::Url(url) => serde_json::to_value(url).map(|url| serde_json::json!({"url":url})), -+ } -+ .map_err(serde::ser::Error::custom)?; -+ serde_json::json!({"identity":identity}).serialize(serializer) -+ } -+} -+ - #[derive(Deserialize)] - struct RawMcpServerRequirement { - identity: RawMcpServerIdentity, -@@ -84,7 +99,7 @@ impl<'de> Deserialize<'de> for McpServerRequirement { - } - - /// Managed MCP server requirements for one plugin. --#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)] -+#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)] - pub struct PluginMcpRequirements { - pub mcp_servers: Option>, - } -diff --git a/codex-rs/protocol/src/permission_profile_snapshot.rs b/codex-rs/protocol/src/permission_profile_snapshot.rs -index 34fe6fdb..5f625ca8 100644 ---- a/codex-rs/protocol/src/permission_profile_snapshot.rs -+++ b/codex-rs/protocol/src/permission_profile_snapshot.rs -@@ -2,6 +2,7 @@ - - use codex_utils_absolute_path::AbsolutePathBuf; - use codex_utils_path_uri::PathUri; -+use serde::{Deserialize, Serialize}; - - use crate::models::ActivePermissionProfile; - use crate::models::PermissionProfile; -@@ -11,7 +12,8 @@ use crate::models::PermissionProfile; - /// Local and remote roots share the same URI representation. Snapshot equality - /// compares the stored URI spelling without folding Windows case, so a spelling - /// change still propagates through settings. --#[derive(Debug, Clone, Eq)] -+#[derive(Debug, Clone, Eq, Serialize, Deserialize)] -+#[serde(transparent)] - pub struct ProfileWorkspaceRoot(PathUri); - - impl PartialEq for ProfileWorkspaceRoot { -@@ -45,7 +47,8 @@ impl From for ProfileWorkspaceRoot { - /// profile-defined workspace roots together for atomic installation. Callers - /// handling user-selected profile ids must resolve those ids before - /// constructing a snapshot. --#[derive(Debug, Clone, PartialEq, Eq)] -+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -+#[serde(rename_all = "camelCase")] - pub struct PermissionProfileSnapshot { - permission_profile: PermissionProfile, - active_permission_profile: Option, -diff --git a/codex-rs/protocol/src/permissions.rs b/codex-rs/protocol/src/permissions.rs -index 96e590c8..9dbe0b08 100644 ---- a/codex-rs/protocol/src/permissions.rs -+++ b/codex-rs/protocol/src/permissions.rs -@@ -293,6 +293,67 @@ pub struct FileSystemSandboxPolicyContext<'a> { - pub temporary_directories: Option<&'a [PathUri]>, - } - -+/// Lexical roots used to select the deepest matching rule. All environment -+/// bindings belong to one policy context; native alias checks stay at the call site. -+enum PreparedAccessRules { -+ Unrestricted, -+ Restricted { -+ convention: PathConvention, -+ entries: Vec<(PathUri, FileSystemAccessMode, usize)>, -+ }, -+ Invalid, -+} -+ -+impl PreparedAccessRules { -+ fn new(policy: &FileSystemSandboxPolicy, context: &FileSystemSandboxPolicyContext<'_>) -> Self { -+ match policy.kind { -+ FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => { -+ return Self::Unrestricted; -+ } -+ FileSystemSandboxKind::Restricted => {} -+ } -+ let Some(convention) = context.cwd.infer_path_convention() else { -+ return Self::Invalid; -+ }; -+ if context.cwd.lexical_depth().is_none() { -+ return Self::Invalid; -+ } -+ -+ let mut entries = Vec::new(); -+ for (root, access) in policy.resolved_entries(context) { -+ match root.lexical_depth() { -+ Some(depth) => entries.push((root, access, depth)), -+ None if root.is_opaque() => {} -+ None => return Self::Invalid, -+ } -+ } -+ Self::Restricted { -+ convention, -+ entries, -+ } -+ } -+ -+ fn resolve(&self, path: &PathUri) -> FileSystemAccessMode { -+ match self { -+ Self::Unrestricted => FileSystemAccessMode::Write, -+ Self::Restricted { -+ convention, -+ entries, -+ } if path.infer_path_convention() == Some(*convention) -+ && path.lexical_depth().is_some() => -+ { -+ entries -+ .iter() -+ .filter(|(root, _, _)| path.starts_with(root)) -+ .max_by_key(|(_, access, depth)| (*depth, *access)) -+ .map(|(_, access, _)| *access) -+ .unwrap_or(FileSystemAccessMode::Deny) -+ } -+ Self::Restricted { .. } | Self::Invalid => FileSystemAccessMode::Deny, -+ } -+ } -+} -+ - #[derive(Debug, Clone, PartialEq, Eq)] - struct ResolvedFileSystemEntry { - path: AbsolutePathBuf, -@@ -1037,43 +1098,7 @@ impl FileSystemSandboxPolicy { - path: &PathUri, - context: &FileSystemSandboxPolicyContext<'_>, - ) -> FileSystemAccessMode { -- match self.kind { -- FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => { -- return FileSystemAccessMode::Write; -- } -- FileSystemSandboxKind::Restricted => {} -- } -- -- let Some(convention) = context.cwd.infer_path_convention() else { -- return FileSystemAccessMode::Deny; -- }; -- if path.infer_path_convention() != Some(convention) -- || path.lexical_depth().is_none() -- || context.cwd.lexical_depth().is_none() -- { -- return FileSystemAccessMode::Deny; -- } -- -- let Some(entries) = self.resolved_entries(context).into_iter().try_fold( -- Vec::new(), -- |mut entries, (root, access)| { -- match root.lexical_depth() { -- Some(depth) => entries.push((root, access, depth)), -- None if root.is_opaque() => {} -- None => return None, -- } -- Some(entries) -- }, -- ) else { -- return FileSystemAccessMode::Deny; -- }; -- -- entries -- .into_iter() -- .filter(|(root, _, _)| path.starts_with(root)) -- .max_by_key(|(_, access, depth)| (*depth, *access)) -- .map(|(_, access, _)| access) -- .unwrap_or(FileSystemAccessMode::Deny) -+ PreparedAccessRules::new(self, context).resolve(path) - } - - pub fn can_write_path( -@@ -1081,11 +1106,18 @@ impl FileSystemSandboxPolicy { - path: &PathUri, - context: &FileSystemSandboxPolicyContext<'_>, - ) -> bool { -- if !self.resolve_access(path, context).can_write() { -- return false; -- } -- self.has_full_disk_write_access_with_context(context) -- || self.metadata_write_denial(path, context).is_none() -+ self.can_write_with_access(path, context, self.resolve_access(path, context)) -+ } -+ -+ fn can_write_with_access( -+ &self, -+ path: &PathUri, -+ context: &FileSystemSandboxPolicyContext<'_>, -+ access: FileSystemAccessMode, -+ ) -> bool { -+ access.can_write() -+ && (self.has_full_disk_write_access_with_context(context) -+ || self.metadata_write_denial(path, context).is_none()) - } - - fn metadata_write_denial( -diff --git a/codex-rs/protocol/src/permissions/local_aliases.rs b/codex-rs/protocol/src/permissions/local_aliases.rs -index c3badbb3..d2ccd33c 100644 ---- a/codex-rs/protocol/src/permissions/local_aliases.rs -+++ b/codex-rs/protocol/src/permissions/local_aliases.rs -@@ -11,10 +11,13 @@ use super::FileSystemSandboxPolicyContext; - use super::FileSystemSpecialPath; - #[cfg(target_os = "macos")] - use super::PROTECTED_METADATA_PATH_NAMES; -+use super::PreparedAccessRules; - use super::local_temporary_directories; - use codex_utils_absolute_path::AbsolutePathBuf; -+use codex_utils_path_uri::PathConvention; - use codex_utils_path_uri::PathUri; - use std::borrow::Cow; -+use std::collections::HashSet; - #[cfg(target_os = "macos")] - use std::ffi::CString; - use std::io; -@@ -58,6 +61,8 @@ impl LocalPolicyContext { - /// case aliases without changing executor-independent path comparisons. - pub struct LocalFileSystemPolicyMatcher<'a> { - policy: Cow<'a, FileSystemSandboxPolicy>, -+ access: PreparedAccessRules, -+ exact_denials: HashSet, - context: FileSystemSandboxPolicyContext<'a>, - } - -@@ -104,7 +109,21 @@ impl FileSystemSandboxPolicy { - .push(FileSystemSandboxEntry::new(normalized.into(), access)); - } - } -+ let access = PreparedAccessRules::new(&policy, context); -+ let exact_denials = match &access { -+ PreparedAccessRules::Restricted { -+ convention: PathConvention::Posix, -+ entries, -+ } => entries -+ .iter() -+ .filter(|(_, mode, _)| *mode == FileSystemAccessMode::Deny) -+ .map(|(root, _, _)| root.clone()) -+ .collect(), -+ _ => HashSet::new(), -+ }; - Ok(LocalFileSystemPolicyMatcher { -+ access, -+ exact_denials, - policy, - context: *context, - }) -@@ -115,7 +134,11 @@ impl LocalFileSystemPolicyMatcher<'_> { - /// Check write access, preserving failures to establish native path equivalence. - pub fn can_write_path(&self, path: &PathUri) -> io::Result { - self.with_path(path, |path| -> io::Result { -- let writable = self.policy.can_write_path(path, &self.context); -+ let writable = self.policy.can_write_with_access( -+ path, -+ &self.context, -+ self.resolve_normalized_access(path), -+ ); - #[cfg(target_os = "macos")] - if writable - && !self -@@ -154,10 +177,19 @@ impl LocalFileSystemPolicyMatcher<'_> { - } - - pub(super) fn resolve_access(&self, path: &PathUri) -> FileSystemAccessMode { -- self.with_path(path, |path| self.policy.resolve_access(path, &self.context)) -+ self.with_path(path, |path| self.resolve_normalized_access(path)) - .unwrap_or(FileSystemAccessMode::Deny) - } - -+ fn resolve_normalized_access(&self, path: &PathUri) -> FileSystemAccessMode { -+ // A validated root equal to the target has the greatest possible match depth. -+ // Deny wins every tie, including equivalent spellings of the same POSIX path. -+ if !self.exact_denials.is_empty() && self.exact_denials.contains(path) { -+ return FileSystemAccessMode::Deny; -+ } -+ self.access.resolve(path) -+ } -+ - fn with_path(&self, path: &PathUri, evaluate: impl FnOnce(&PathUri) -> T) -> io::Result { - let path = if cfg!(target_os = "macos") { - Cow::Owned(PathUri::from( -diff --git a/codex-rs/protocol/src/permissions_tests.rs b/codex-rs/protocol/src/permissions_tests.rs -index 11293b34..1765359b 100644 ---- a/codex-rs/protocol/src/permissions_tests.rs -+++ b/codex-rs/protocol/src/permissions_tests.rs -@@ -258,6 +258,89 @@ fn uri_matcher_resolves_selected_executor_paths() { - ); - } - -+#[test] -+fn prepared_access_matches_single_path_resolution_for_nested_rules() -> anyhow::Result<()> { -+ let cwd = PathUri::parse("file:///workspace")?; -+ let context = FileSystemSandboxPolicyContext { -+ cwd: &cwd, -+ workspace_roots: std::slice::from_ref(&cwd), -+ user_home_dir: None, -+ temporary_directories: None, -+ }; -+ let mut entries = vec![ -+ FileSystemSandboxEntry::new(cwd.clone().into(), FileSystemAccessMode::Read), -+ FileSystemSandboxEntry::new(cwd.join("draft")?.into(), FileSystemAccessMode::Write), -+ FileSystemSandboxEntry::new(cwd.join("draft")?.into(), FileSystemAccessMode::Read), -+ FileSystemSandboxEntry::new(cwd.join("draft/notes")?.into(), FileSystemAccessMode::Deny), -+ FileSystemSandboxEntry::new(cwd.join("draft/notes")?.into(), FileSystemAccessMode::Read), -+ FileSystemSandboxEntry::new( -+ cwd.join("draft/notes/public")?.into(), -+ FileSystemAccessMode::Write, -+ ), -+ ]; -+ let paths = [ -+ "file:///", -+ "file:///workspace", -+ "file:///workspace/draft", -+ "file:///workspace/drafts/todo", -+ "file:///workspace/draft/notes", -+ "file:///workspace/draft/notes/ideas.txt", -+ "file:///workspace/draft/notes/public/final.txt", -+ "file:///workspace/draft/meeting%20notes.txt", -+ "file:///unrelated", -+ ] -+ .map(|p| PathUri::parse(p).unwrap()); -+ for _ in 0..2 { -+ let policy = FileSystemSandboxPolicy::restricted(entries.clone()); -+ let prepared = policy.prepare_local_matching(&context)?; -+ for path in &paths { -+ assert_eq!( -+ prepared.resolve_access(path), -+ policy.resolve_access(path, &context), -+ "resolving {path}" -+ ); -+ } -+ entries.reverse(); -+ } -+ Ok(()) -+} -+ -+#[test] -+fn local_matcher_rebinds_workspace_roots_between_operations() -> anyhow::Result<()> { -+ let temp = TempDir::new()?; -+ let cwd = PathUri::from_host_native_path(temp.path().canonicalize()?)?; -+ let first = cwd.join("first")?; -+ let second = cwd.join("second")?; -+ let mut policy = FileSystemSandboxPolicy::restricted(vec![ -+ FileSystemSandboxEntry::new( -+ FileSystemPath::Special { -+ value: FileSystemSpecialPath::ProjectRoots { subpath: None }, -+ }, -+ FileSystemAccessMode::Write, -+ ), -+ FileSystemSandboxEntry::new(first.clone().into(), FileSystemAccessMode::Deny), -+ ]); -+ for _ in 0..2 { -+ for (active, writable) in [(&first, None), (&second, Some(&second))] { -+ let context = FileSystemSandboxPolicyContext { -+ cwd: &cwd, -+ workspace_roots: std::slice::from_ref(active), -+ user_home_dir: None, -+ temporary_directories: None, -+ }; -+ let matcher = policy.prepare_local_matching(&context)?; -+ for root in [&first, &second] { -+ assert_eq!( -+ matcher.can_write_path(&root.join("child")?)?, -+ writable == Some(root) -+ ); -+ } -+ } -+ policy.entries.reverse(); -+ } -+ Ok(()) -+} -+ - #[test] - fn uri_matcher_uses_validated_native_components_for_precedence() { - let path = |path| PathUri::parse(path).expect("valid path URI"); -diff --git a/codex-rs/tui/src/app/app_server_event_targets.rs b/codex-rs/tui/src/app/app_server_event_targets.rs -index 34e923a0..85f94820 100644 ---- a/codex-rs/tui/src/app/app_server_event_targets.rs -+++ b/codex-rs/tui/src/app/app_server_event_targets.rs -@@ -24,7 +24,8 @@ pub(super) fn server_request_thread_id(request: &ServerRequest) -> Option { - ThreadId::from_string(¶ms.thread_id).ok() - } -- ServerRequest::ChatgptAuthTokensRefresh { .. } -+ ServerRequest::TheoremosAgentControlRequest { .. } -+ | ServerRequest::ChatgptAuthTokensRefresh { .. } - | ServerRequest::AttestationGenerate { .. } - | ServerRequest::ApplyPatchApproval { .. } - | ServerRequest::ExecCommandApproval { .. } => None, -diff --git a/codex-rs/tui/src/app/app_server_events.rs b/codex-rs/tui/src/app/app_server_events.rs -index a23c09a1..1f5bb319 100644 ---- a/codex-rs/tui/src/app/app_server_events.rs -+++ b/codex-rs/tui/src/app/app_server_events.rs -@@ -804,7 +804,8 @@ impl App { - } - let unsupported_request = matches!( - &request, -- ServerRequest::DynamicToolCall { .. } -+ ServerRequest::TheoremosAgentControlRequest { .. } -+ | ServerRequest::DynamicToolCall { .. } - | ServerRequest::AttestationGenerate { .. } - | ServerRequest::ApplyPatchApproval { .. } - | ServerRequest::ExecCommandApproval { .. } -diff --git a/codex-rs/tui/src/app/app_server_requests.rs b/codex-rs/tui/src/app/app_server_requests.rs -index 0ee0dd2d..b5b71313 100644 ---- a/codex-rs/tui/src/app/app_server_requests.rs -+++ b/codex-rs/tui/src/app/app_server_requests.rs -@@ -195,6 +195,12 @@ impl PendingAppServerRequests { - ); - None - } -+ ServerRequest::TheoremosAgentControlRequest { request_id, .. } => { -+ Some(UnsupportedAppServerRequest { -+ request_id: request_id.clone(), -+ message: "TheoremOS AgentControl requires its trusted stdio host".into(), -+ }) -+ } - ServerRequest::DynamicToolCall { .. } => None, - ServerRequest::ChatgptAuthTokensRefresh { .. } => None, - ServerRequest::AttestationGenerate { request_id, .. } => { -@@ -522,7 +528,8 @@ impl PendingAppServerRequests { - }) - } - ServerRequest::ChatgptAuthTokensRefresh { .. } => None, -- ServerRequest::DynamicToolCall { .. } -+ ServerRequest::TheoremosAgentControlRequest { .. } -+ | ServerRequest::DynamicToolCall { .. } - | ServerRequest::AttestationGenerate { .. } - | ServerRequest::ApplyPatchApproval { .. } - | ServerRequest::ExecCommandApproval { .. } => None, -diff --git a/codex-rs/tui/src/app/side.rs b/codex-rs/tui/src/app/side.rs -index 3e20f832..fa07a3a3 100644 ---- a/codex-rs/tui/src/app/side.rs -+++ b/codex-rs/tui/src/app/side.rs -@@ -65,7 +65,8 @@ impl SideParentStatus { - | ServerRequest::PermissionsRequestApproval { .. } - | ServerRequest::ApplyPatchApproval { .. } - | ServerRequest::ExecCommandApproval { .. } => Some(SideParentStatus::NeedsApproval), -- ServerRequest::DynamicToolCall { .. } -+ ServerRequest::TheoremosAgentControlRequest { .. } -+ | ServerRequest::DynamicToolCall { .. } - | ServerRequest::AttestationGenerate { .. } - | ServerRequest::ChatgptAuthTokensRefresh { .. } => None, - } -diff --git a/codex-rs/tui/src/chatwidget/protocol_requests.rs b/codex-rs/tui/src/chatwidget/protocol_requests.rs -index bae49e84..31b257ec 100644 ---- a/codex-rs/tui/src/chatwidget/protocol_requests.rs -+++ b/codex-rs/tui/src/chatwidget/protocol_requests.rs -@@ -48,7 +48,8 @@ impl ChatWidget { - ServerRequest::ToolRequestUserInput { params, .. } => { - self.on_request_user_input(params); - } -- ServerRequest::DynamicToolCall { .. } -+ ServerRequest::TheoremosAgentControlRequest { .. } -+ | ServerRequest::DynamicToolCall { .. } - | ServerRequest::AttestationGenerate { .. } - | ServerRequest::ChatgptAuthTokensRefresh { .. } - | ServerRequest::ApplyPatchApproval { .. } -diff --git a/codex-rs/utils/plugins/src/plugin_namespace.rs b/codex-rs/utils/plugins/src/plugin_namespace.rs -index f64c3897..cbe832a1 100644 ---- a/codex-rs/utils/plugins/src/plugin_namespace.rs -+++ b/codex-rs/utils/plugins/src/plugin_namespace.rs -@@ -105,8 +105,17 @@ pub async fn plugin_namespace_for_root_uri( - Ok(_) | Err(_) => {} - } - } -+ plugin_namespace_from_manifest_uri(fs, plugin_root, &manifest_path?).await -+} -+ -+/// Read the selected manifest through the same filesystem that identified it. -+pub async fn plugin_namespace_from_manifest_uri( -+ fs: &dyn EnvironmentAccess, -+ plugin_root: &PathUri, -+ manifest: &PathUri, -+) -> Option { - let contents = fs -- .read_file_text(&manifest_path?, ReadFileOptions::default()) -+ .read_file_text(manifest, ReadFileOptions::default()) - .await - .ok()?; - let RawPluginManifestName { name: raw_name } = serde_json::from_str(&contents).ok()?; diff --git a/scripts/codex-backend/check-capabilities.py b/scripts/codex-backend/check-capabilities.py deleted file mode 100644 index 86e83043..00000000 --- a/scripts/codex-backend/check-capabilities.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Probe AgentControl and Code Mode against a fixed loopback Responses fixture.""" - -from http.server import BaseHTTPRequestHandler, HTTPServer -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -from threading import Thread - - -class ProbeResponses(BaseHTTPRequestHandler): - calls = 0 - tool_output = None - - def do_POST(self): - if self.path != "/v1/responses": - self.send_error(404) - return - body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) - fixture = type(self) - fixture.calls += 1 - if fixture.calls == 1: - item = {"type": "custom_tool_call", "call_id": "probe-exec", "name": "exec", - "input": "text('theoremos-' + (17 + 25));"} - elif fixture.calls == 2: - fixture.tool_output = next( - (item["output"] for item in body["input"] - if item["type"] == "custom_tool_call_output" and item["call_id"] == "probe-exec"), - None, - ) - item = {"type": "message", "id": "probe-done", "role": "assistant", - "content": [{"type": "output_text", "text": "Probe completed."}]} - else: - self.send_error(500, "unexpected additional Responses request") - return - response = {"id": f"probe-{fixture.calls}"} - events = [ - {"type": "response.created", "response": response}, - {"type": "response.output_item.done", "item": item}, - {"type": "response.completed", "response": response}, - ] - payload = "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" - for event in events).encode() - self.send_response(200) - self.send_header("Content-Type", "text/event-stream") - self.send_header("Content-Length", str(len(payload))) - self.end_headers() - self.wfile.write(payload) - - def log_message(self, *_): - pass - - -def check_agent_control(executable, profile, environment): - with subprocess.Popen( - [executable, "app-server", "--listen", "stdio://"], - stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, - cwd=profile, env={**environment, "THEOREMOS_HOST_AGENT_CONTROL": "1"}, - ) as server: - def send(message): - server.stdin.write(json.dumps(message) + "\n") - server.stdin.flush() - - def request(request_id, method, params): - send({"id": request_id, "method": method, "params": params}) - for line in server.stdout: - reply = json.loads(line) - if reply.get("id") == request_id: - if "error" in reply: - raise RuntimeError(f"{method}: {reply['error']}") - return reply["result"] - raise RuntimeError(f"app-server closed before {method} returned") - - try: - request(1, "initialize", {"clientInfo": {"name": "theoremos-worker-build", "version": "1"}, - "capabilities": {"experimentalApi": True}}) - send({"method": "initialized"}) - result = request(2, "theoremos/agentControl/capabilities", {}) - if (result.get("version") != 1 or result.get("backend") != "theoremos-host" - or result.get("nativeTools") is not True or result.get("isolatedChildBootstrap") is not True): - raise RuntimeError(f"incompatible AgentControl backend: {result}") - return result - finally: - server.terminate() - - -def check_code_mode(executable, profile, environment): - with HTTPServer(("127.0.0.1", 0), ProbeResponses) as responses: - base_url = f"http://127.0.0.1:{responses.server_port}" - Path(profile, "config.toml").write_text(f"""model = "theoremos-probe" -model_provider = "fixture" -approval_policy = "never" -sandbox_mode = "read-only" -chatgpt_base_url = "{base_url}" -[analytics] -enabled = false -[features] -code_mode_only = true -code_mode_host = true -[model_providers.fixture] -name = "Code Mode probe" -base_url = "{base_url}/v1" -wire_api = "responses" -supports_websockets = false -request_max_retries = 0 -stream_max_retries = 0 -""", encoding="utf-8") - serving = Thread(target=responses.serve_forever, daemon=True) - serving.start() - try: - run = subprocess.run( - [executable, "exec", "--ephemeral", "--skip-git-repo-check", "Run the Code Mode probe."], - cwd=profile, env=environment, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15, - ) - if run.returncode != 0: - raise RuntimeError(f"Code Mode probe failed: {run.stderr.strip()}") - if "theoremos-42" not in json.dumps(ProbeResponses.tool_output): - raise RuntimeError(f"Code Mode probe returned: {ProbeResponses.tool_output}") - finally: - responses.shutdown() - serving.join() - - -if __name__ == "__main__": - executable = str(Path(sys.argv[1]).resolve()) - with tempfile.TemporaryDirectory() as profile: - environment = {"HOME": profile, "CODEX_HOME": profile, "PATH": os.environ["PATH"]} - capabilities = check_agent_control(executable, profile, environment) - check_code_mode(executable, profile, environment) - print(json.dumps({**capabilities, "codeModeProbe": "passed"})) diff --git a/scripts/codex-backend/derived-lock.patch b/scripts/codex-backend/derived-lock.patch deleted file mode 100644 index b340fc02..00000000 --- a/scripts/codex-backend/derived-lock.patch +++ /dev/null @@ -1,1547 +0,0 @@ -diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock -index 2e557339..b751234a 100644 ---- a/codex-rs/Cargo.lock -+++ b/codex-rs/Cargo.lock -@@ -287,7 +287,7 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" - - [[package]] - name = "app_test_support" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -1900,7 +1900,7 @@ dependencies = [ - - [[package]] - name = "codex-agent-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-core", -@@ -1912,7 +1912,7 @@ dependencies = [ - - [[package]] - name = "codex-agent-graph-store" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "codex-state", -@@ -1927,7 +1927,7 @@ dependencies = [ - - [[package]] - name = "codex-agent-identity" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -1947,7 +1947,7 @@ dependencies = [ - - [[package]] - name = "codex-agent-message-board-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chrono", -@@ -1970,7 +1970,7 @@ dependencies = [ - - [[package]] - name = "codex-agent-message-board-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-agent-message-board-client", - "codex-config", -@@ -1989,7 +1989,7 @@ dependencies = [ - - [[package]] - name = "codex-agent-message-board-host" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "chrono", - "codex-agent-message-board-client", -@@ -2006,7 +2006,7 @@ dependencies = [ - - [[package]] - name = "codex-agent-roles" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-config", - "codex-file-system", -@@ -2019,7 +2019,7 @@ dependencies = [ - - [[package]] - name = "codex-analytics" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-app-server-protocol", - "codex-features", -@@ -2047,7 +2047,7 @@ dependencies = [ - - [[package]] - name = "codex-ansi-escape" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "ansi-to-tui", - "pretty_assertions", -@@ -2058,7 +2058,7 @@ dependencies = [ - - [[package]] - name = "codex-api" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "assert_matches", -@@ -2098,7 +2098,7 @@ dependencies = [ - - [[package]] - name = "codex-app-server" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "app_test_support", -@@ -2220,7 +2220,7 @@ dependencies = [ - - [[package]] - name = "codex-app-server-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-api", - "codex-app-server", -@@ -2257,7 +2257,7 @@ dependencies = [ - - [[package]] - name = "codex-app-server-daemon" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "blake3", -@@ -2287,7 +2287,7 @@ dependencies = [ - - [[package]] - name = "codex-app-server-protocol" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-app-server-protocol-noop-macros", -@@ -2322,11 +2322,11 @@ dependencies = [ - - [[package]] - name = "codex-app-server-protocol-noop-macros" --version = "0.0.0" -+version = "0.172.0" - - [[package]] - name = "codex-app-server-test-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "clap", -@@ -2349,7 +2349,7 @@ dependencies = [ - - [[package]] - name = "codex-app-server-transport" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "axum", -@@ -2397,7 +2397,7 @@ dependencies = [ - - [[package]] - name = "codex-apply-patch" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "assert_cmd", -@@ -2417,7 +2417,7 @@ dependencies = [ - - [[package]] - name = "codex-arg0" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-apply-patch", -@@ -2440,7 +2440,7 @@ dependencies = [ - - [[package]] - name = "codex-async-utils" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - "rand 0.9.3", -@@ -2450,7 +2450,7 @@ dependencies = [ - - [[package]] - name = "codex-attachment-store" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - "serde", -@@ -2460,7 +2460,7 @@ dependencies = [ - - [[package]] - name = "codex-aws-auth" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "aws-config", - "aws-credential-types", -@@ -2486,7 +2486,7 @@ dependencies = [ - - [[package]] - name = "codex-backend-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -2513,7 +2513,7 @@ dependencies = [ - - [[package]] - name = "codex-backend-openapi-models" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "serde", - "serde_json", -@@ -2522,7 +2522,7 @@ dependencies = [ - - [[package]] - name = "codex-build-info" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-install-context", - "pretty_assertions", -@@ -2535,7 +2535,7 @@ dependencies = [ - - [[package]] - name = "codex-bwrap" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "cc", - "libc", -@@ -2544,7 +2544,7 @@ dependencies = [ - - [[package]] - name = "codex-chatgpt" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -2572,7 +2572,7 @@ dependencies = [ - - [[package]] - name = "codex-cli" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "app_test_support", -@@ -2677,7 +2677,7 @@ dependencies = [ - - [[package]] - name = "codex-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-http-client", - "eventsource-stream", -@@ -2691,7 +2691,7 @@ dependencies = [ - - [[package]] - name = "codex-cloud-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "async-stream", -@@ -2717,7 +2717,7 @@ dependencies = [ - - [[package]] - name = "codex-cloud-config" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "chrono", -@@ -2747,7 +2747,7 @@ dependencies = [ - - [[package]] - name = "codex-cloud-tasks" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -2789,7 +2789,7 @@ dependencies = [ - - [[package]] - name = "codex-cloud-tasks-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chrono", -@@ -2804,7 +2804,7 @@ dependencies = [ - - [[package]] - name = "codex-cloud-tasks-mock-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "chrono", - "codex-cloud-tasks-client", -@@ -2813,7 +2813,7 @@ dependencies = [ - - [[package]] - name = "codex-code-mode" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-code-mode-protocol", - "codex-http-client", -@@ -2837,7 +2837,7 @@ dependencies = [ - - [[package]] - name = "codex-code-mode-host" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "axum", -@@ -2869,7 +2869,7 @@ dependencies = [ - - [[package]] - name = "codex-code-mode-protocol" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "glob", -@@ -2887,7 +2887,7 @@ dependencies = [ - - [[package]] - name = "codex-code-mode-runtime" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-code-mode-protocol", -@@ -2909,11 +2909,11 @@ dependencies = [ - - [[package]] - name = "codex-collaboration-mode-templates" --version = "0.0.0" -+version = "0.172.0" - - [[package]] - name = "codex-config" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -2967,7 +2967,7 @@ dependencies = [ - - [[package]] - name = "codex-config-schema" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "clap", -@@ -2976,7 +2976,7 @@ dependencies = [ - - [[package]] - name = "codex-connectors" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "arc-swap", -@@ -2998,7 +2998,7 @@ dependencies = [ - - [[package]] - name = "codex-connectors-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-connectors", - "codex-core-plugins", -@@ -3012,7 +3012,7 @@ dependencies = [ - - [[package]] - name = "codex-context-fragments" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "codex-protocol-test-support", -@@ -3023,7 +3023,7 @@ dependencies = [ - - [[package]] - name = "codex-core" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "arc-swap", -@@ -3178,7 +3178,7 @@ dependencies = [ - - [[package]] - name = "codex-core-api" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-analytics", - "codex-app-server-protocol", -@@ -3202,7 +3202,7 @@ dependencies = [ - - [[package]] - name = "codex-core-plugin-common" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-utils-absolute-path", - "semver", -@@ -3213,7 +3213,7 @@ dependencies = [ - - [[package]] - name = "codex-core-plugins" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -3274,7 +3274,7 @@ dependencies = [ - - [[package]] - name = "codex-diagnostics" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "libc", - "pretty_assertions", -@@ -3282,7 +3282,7 @@ dependencies = [ - - [[package]] - name = "codex-direct-tool-timing" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-utils-critical-path", - "pretty_assertions", -@@ -3293,7 +3293,7 @@ dependencies = [ - - [[package]] - name = "codex-exec" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "assert_cmd", -@@ -3347,7 +3347,7 @@ dependencies = [ - - [[package]] - name = "codex-exec-server" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "arc-swap", -@@ -3419,7 +3419,7 @@ dependencies = [ - - [[package]] - name = "codex-exec-server-cli" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "assert_matches", -@@ -3463,7 +3463,7 @@ dependencies = [ - - [[package]] - name = "codex-exec-server-protocol" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-file-system", -@@ -3481,7 +3481,7 @@ dependencies = [ - - [[package]] - name = "codex-exec-server-test-support" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-exec-server", -@@ -3496,7 +3496,7 @@ dependencies = [ - - [[package]] - name = "codex-execpolicy" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "caseless", -@@ -3516,7 +3516,7 @@ dependencies = [ - - [[package]] - name = "codex-experimental-api-macros" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "proc-macro2", - "quote", -@@ -3525,7 +3525,7 @@ dependencies = [ - - [[package]] - name = "codex-extension-api" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-api", - "codex-config", -@@ -3548,7 +3548,7 @@ dependencies = [ - - [[package]] - name = "codex-extension-items" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-utils-absolute-path", - "pretty_assertions", -@@ -3560,7 +3560,7 @@ dependencies = [ - - [[package]] - name = "codex-external-agent-migration" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "chrono", - "codex-analytics", -@@ -3591,7 +3591,7 @@ dependencies = [ - - [[package]] - name = "codex-features" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-network-proxy", - "codex-protocol", -@@ -3605,7 +3605,7 @@ dependencies = [ - - [[package]] - name = "codex-feedback" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "bytes", -@@ -3633,7 +3633,7 @@ dependencies = [ - - [[package]] - name = "codex-file-search" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "clap", -@@ -3649,7 +3649,7 @@ dependencies = [ - - [[package]] - name = "codex-file-system" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "bytes", - "codex-protocol", -@@ -3663,7 +3663,7 @@ dependencies = [ - - [[package]] - name = "codex-file-watcher" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "notify", - "pretty_assertions", -@@ -3674,7 +3674,7 @@ dependencies = [ - - [[package]] - name = "codex-git-attribution" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-backend-client", - "codex-extension-api", -@@ -3690,7 +3690,7 @@ dependencies = [ - - [[package]] - name = "codex-git-utils" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chrono", -@@ -3718,7 +3718,7 @@ dependencies = [ - - [[package]] - name = "codex-goal-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chrono", -@@ -3743,7 +3743,7 @@ dependencies = [ - - [[package]] - name = "codex-guardian-context" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-context-fragments", - "codex-history", -@@ -3757,7 +3757,7 @@ dependencies = [ - - [[package]] - name = "codex-guardian-reviewer" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-analytics", -@@ -3794,7 +3794,7 @@ dependencies = [ - - [[package]] - name = "codex-guardian-v2" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -3837,7 +3837,7 @@ dependencies = [ - - [[package]] - name = "codex-guardian-v3" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chrono", -@@ -3878,7 +3878,7 @@ dependencies = [ - - [[package]] - name = "codex-history" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-protocol", -@@ -3893,7 +3893,7 @@ dependencies = [ - - [[package]] - name = "codex-history-notes-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-analytics", - "codex-client", -@@ -3921,7 +3921,7 @@ dependencies = [ - - [[package]] - name = "codex-home" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-extension-api", - "codex-utils-absolute-path", -@@ -3933,7 +3933,7 @@ dependencies = [ - - [[package]] - name = "codex-hooks" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "async-channel", -@@ -3963,7 +3963,7 @@ dependencies = [ - - [[package]] - name = "codex-http-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "bytes", - "codex-utils-cargo-bin", -@@ -4003,7 +4003,7 @@ dependencies = [ - - [[package]] - name = "codex-http-headers-helper" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-utils-process", -@@ -4016,7 +4016,7 @@ dependencies = [ - - [[package]] - name = "codex-image-generation-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-api", -@@ -4048,7 +4048,7 @@ dependencies = [ - - [[package]] - name = "codex-install-context" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-utils-absolute-path", - "codex-utils-home-dir", -@@ -4061,7 +4061,7 @@ dependencies = [ - - [[package]] - name = "codex-keyring-store" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "keyring", - "pretty_assertions", -@@ -4072,7 +4072,7 @@ dependencies = [ - - [[package]] - name = "codex-linux-sandbox" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "async-lock", - "clap", -@@ -4108,7 +4108,7 @@ dependencies = [ - - [[package]] - name = "codex-lmstudio" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-core", - "codex-http-client", -@@ -4122,7 +4122,7 @@ dependencies = [ - - [[package]] - name = "codex-login" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -4171,7 +4171,7 @@ dependencies = [ - - [[package]] - name = "codex-mcp" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "arc-swap", -@@ -4222,7 +4222,7 @@ dependencies = [ - - [[package]] - name = "codex-mcp-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "axum", -@@ -4255,7 +4255,7 @@ dependencies = [ - - [[package]] - name = "codex-memories-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-core", - "codex-extension-api", -@@ -4277,7 +4277,7 @@ dependencies = [ - - [[package]] - name = "codex-memories-read" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "codex-shell-command", -@@ -4287,7 +4287,7 @@ dependencies = [ - - [[package]] - name = "codex-memories-write" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -4326,7 +4326,7 @@ dependencies = [ - - [[package]] - name = "codex-mermaid" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "insta", - "pretty_assertions", -@@ -4335,7 +4335,7 @@ dependencies = [ - - [[package]] - name = "codex-message-board" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "caseless", -@@ -4360,7 +4360,7 @@ dependencies = [ - - [[package]] - name = "codex-message-board-mcp" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "axum", -@@ -4388,7 +4388,7 @@ dependencies = [ - - [[package]] - name = "codex-message-history" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-config", - "memchr", -@@ -4402,7 +4402,7 @@ dependencies = [ - - [[package]] - name = "codex-model-provider" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -4442,7 +4442,7 @@ dependencies = [ - - [[package]] - name = "codex-model-provider-info" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-client", - "codex-http-client", -@@ -4460,7 +4460,7 @@ dependencies = [ - - [[package]] - name = "codex-models-manager" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "chrono", - "codex-http-client", -@@ -4479,7 +4479,7 @@ dependencies = [ - - [[package]] - name = "codex-multi-env-copy-file" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-config", -@@ -4505,7 +4505,7 @@ dependencies = [ - - [[package]] - name = "codex-mxc-sandbox" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-network-proxy", -@@ -4525,7 +4525,7 @@ dependencies = [ - - [[package]] - name = "codex-network-proxy" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "aws-credential-types", -@@ -4576,7 +4576,7 @@ dependencies = [ - - [[package]] - name = "codex-ollama" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "assert_matches", - "async-stream", -@@ -4596,7 +4596,7 @@ dependencies = [ - - [[package]] - name = "codex-otel" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "bytes", - "chrono", -@@ -4636,7 +4636,7 @@ dependencies = [ - - [[package]] - name = "codex-otel-trace-websocket" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "axum", -@@ -4647,7 +4647,7 @@ dependencies = [ - - [[package]] - name = "codex-plugin" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-config", - "codex-core-plugin-common", -@@ -4662,7 +4662,7 @@ dependencies = [ - - [[package]] - name = "codex-plugin-host" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-utils-cargo-bin", - "codex-utils-process", -@@ -4679,7 +4679,7 @@ dependencies = [ - - [[package]] - name = "codex-process-hardening" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "libc", - "pretty_assertions", -@@ -4687,7 +4687,7 @@ dependencies = [ - - [[package]] - name = "codex-prompts" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-collaboration-mode-templates", -@@ -4706,7 +4706,7 @@ dependencies = [ - - [[package]] - name = "codex-protocol" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chardetng", -@@ -4753,7 +4753,7 @@ dependencies = [ - - [[package]] - name = "codex-protocol-test-support" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "uuid", -@@ -4761,7 +4761,7 @@ dependencies = [ - - [[package]] - name = "codex-queue-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-core", -@@ -4783,7 +4783,7 @@ dependencies = [ - - [[package]] - name = "codex-realtime-webrtc" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-build-info", -@@ -4802,7 +4802,7 @@ dependencies = [ - - [[package]] - name = "codex-response-debug-context" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-api", -@@ -4813,7 +4813,7 @@ dependencies = [ - - [[package]] - name = "codex-responses-api-proxy" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "bytes", -@@ -4837,7 +4837,7 @@ dependencies = [ - - [[package]] - name = "codex-rmcp-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "axum", -@@ -4890,7 +4890,7 @@ dependencies = [ - - [[package]] - name = "codex-rollout" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chrono", -@@ -4924,7 +4924,7 @@ dependencies = [ - - [[package]] - name = "codex-rollout-trace" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-code-mode", -@@ -4942,7 +4942,7 @@ dependencies = [ - - [[package]] - name = "codex-runtime-agent-instance" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "bytes", -@@ -4971,7 +4971,7 @@ dependencies = [ - - [[package]] - name = "codex-sandboxing" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-mxc-sandbox", -@@ -4998,7 +4998,7 @@ dependencies = [ - - [[package]] - name = "codex-secrets" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "age", - "anyhow", -@@ -5019,7 +5019,7 @@ dependencies = [ - - [[package]] - name = "codex-shell-command" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -5042,7 +5042,7 @@ dependencies = [ - - [[package]] - name = "codex-skills" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "codex-shell-command", -@@ -5059,7 +5059,7 @@ dependencies = [ - - [[package]] - name = "codex-skills-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "assert_matches", - "blake3", -@@ -5099,7 +5099,7 @@ dependencies = [ - - [[package]] - name = "codex-state" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "chrono", -@@ -5130,7 +5130,7 @@ dependencies = [ - - [[package]] - name = "codex-tcp-tunnel" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "bytes", -@@ -5154,7 +5154,7 @@ dependencies = [ - - [[package]] - name = "codex-terminal-detection" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - "tracing", -@@ -5162,7 +5162,7 @@ dependencies = [ - - [[package]] - name = "codex-test-binary-support" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-arg0", - "tempfile", -@@ -5170,7 +5170,7 @@ dependencies = [ - - [[package]] - name = "codex-thread-manager-sample" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "clap", -@@ -5181,7 +5181,7 @@ dependencies = [ - - [[package]] - name = "codex-thread-store" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "caseless", - "chrono", -@@ -5214,7 +5214,7 @@ dependencies = [ - - [[package]] - name = "codex-tools" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "bitflags 2.13.1", - "codex-attachment-store", -@@ -5240,7 +5240,7 @@ dependencies = [ - - [[package]] - name = "codex-tui" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "app_test_support", -@@ -5378,7 +5378,7 @@ dependencies = [ - - [[package]] - name = "codex-uds" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "async-io", - "libc", -@@ -5392,7 +5392,7 @@ dependencies = [ - - [[package]] - name = "codex-user-input" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-protocol", -@@ -5406,7 +5406,7 @@ dependencies = [ - - [[package]] - name = "codex-user-verification" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "block2", -@@ -5427,7 +5427,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-absolute-path" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "dirs", - "dunce", -@@ -5441,14 +5441,14 @@ dependencies = [ - - [[package]] - name = "codex-utils-approval-presets" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - ] - - [[package]] - name = "codex-utils-audio" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-protocol", -@@ -5462,7 +5462,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-cache" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "lru", - "sha1 0.10.6", -@@ -5471,7 +5471,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-cargo-bin" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "assert_cmd", - "runfiles", -@@ -5480,7 +5480,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-cli" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "clap", - "codex-protocol", -@@ -5492,22 +5492,22 @@ dependencies = [ - - [[package]] - name = "codex-utils-critical-path" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - ] - - [[package]] - name = "codex-utils-elapsed" --version = "0.0.0" -+version = "0.172.0" - - [[package]] - name = "codex-utils-fuzzy-match" --version = "0.0.0" -+version = "0.172.0" - - [[package]] - name = "codex-utils-git-discovery" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-git-utils", - "codex-utils-absolute-path", -@@ -5520,14 +5520,14 @@ dependencies = [ - - [[package]] - name = "codex-utils-head-tail-buffer" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - ] - - [[package]] - name = "codex-utils-home-dir" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-utils-absolute-path", - "dirs", -@@ -5537,7 +5537,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-image" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-utils-cache", -@@ -5552,7 +5552,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-json-to-toml" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - "serde_json", -@@ -5561,7 +5561,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-model-facing-id" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "blake3", - "pretty_assertions", -@@ -5574,7 +5574,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-oss" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-core", - "codex-lmstudio", -@@ -5584,7 +5584,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-output-truncation" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "codex-utils-string", -@@ -5594,7 +5594,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-path" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-utils-absolute-path", - "dunce", -@@ -5605,7 +5605,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-path-uri" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-utils-absolute-path", -@@ -5621,7 +5621,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-plugins" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-exec-server", - "codex-exec-server-protocol", -@@ -5635,7 +5635,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-process" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - "tokio", -@@ -5643,7 +5643,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-pty" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-utils-cargo-bin", -@@ -5663,7 +5663,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-readiness" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "assert_matches", - "thiserror 2.0.18", -@@ -5673,7 +5673,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-redacted-string" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "schemars 0.8.22", - "serde", -@@ -5681,14 +5681,14 @@ dependencies = [ - - [[package]] - name = "codex-utils-rustls-provider" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "rustls", - ] - - [[package]] - name = "codex-utils-sandbox-summary" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-protocol", - "codex-utils-absolute-path", -@@ -5698,7 +5698,7 @@ dependencies = [ - - [[package]] - name = "codex-utils-sleep-inhibitor" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "core-foundation 0.9.4", - "libc", -@@ -5708,14 +5708,14 @@ dependencies = [ - - [[package]] - name = "codex-utils-stream-parser" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - ] - - [[package]] - name = "codex-utils-string" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - "regex-lite", -@@ -5725,14 +5725,14 @@ dependencies = [ - - [[package]] - name = "codex-utils-template" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - ] - - [[package]] - name = "codex-v8-poc" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "pretty_assertions", - "v8", -@@ -5740,7 +5740,7 @@ dependencies = [ - - [[package]] - name = "codex-voice-host" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-install-context", -@@ -5767,7 +5767,7 @@ dependencies = [ - - [[package]] - name = "codex-web-search-extension" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-api", - "codex-core", -@@ -5791,7 +5791,7 @@ dependencies = [ - - [[package]] - name = "codex-websocket-auth" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -5810,7 +5810,7 @@ dependencies = [ - - [[package]] - name = "codex-websocket-client" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "codex-http-client", - "codex-utils-rustls-provider", -@@ -5826,7 +5826,7 @@ dependencies = [ - - [[package]] - name = "codex-windows-sandbox" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "base64 0.22.1", -@@ -5857,7 +5857,7 @@ dependencies = [ - - [[package]] - name = "codex-windows-sandbox-service" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-cloud-config", -@@ -5875,14 +5875,14 @@ dependencies = [ - - [[package]] - name = "codex-windows-sandbox-test-support" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "dirs", - ] - - [[package]] - name = "codex-workload-identity" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "base64 0.22.1", - "codex-http-client", -@@ -5904,7 +5904,7 @@ dependencies = [ - - [[package]] - name = "codex-worktree" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "codex-git-utils", -@@ -6179,7 +6179,7 @@ dependencies = [ - - [[package]] - name = "core_test_support" --version = "0.0.0" -+version = "0.172.0" - dependencies = [ - "anyhow", - "assert_cmd", diff --git a/scripts/codex-backend/git-fetch-pinned.py b/scripts/codex-backend/git-fetch-pinned.py deleted file mode 100755 index 4b0ab858..00000000 --- a/scripts/codex-backend/git-fetch-pinned.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env python3 -"""Fetch locked V8 submodules without their unrelated Chromium branch history.""" -import json -import os -import sys - -git = os.environ["THEOREMOS_BUILD_REAL_GIT"] -arguments = sys.argv[1:] -command = 0 -# Cargo passes Git configuration options before the fetch subcommand. -while command + 1 < len(arguments) and arguments[command] == "-c": - command += 2 -if arguments[command:command + 1] == ["fetch"]: - with open(os.environ["THEOREMOS_BUILD_SUBMODULE_PINS"], encoding="utf-8") as stream: - pins = json.load(stream) - for argument in arguments[command + 1:]: - if argument in pins: - revision = pins[argument] - print(f"Fetching pinned submodule {argument} at {revision}", file=sys.stderr) - os.execv(git, [git, *arguments[:command], "fetch", "--force", "--update-head-ok", - "--depth", "1", argument, revision]) -os.execv(git, [git, *arguments]) diff --git a/scripts/codex-backend/protocol.md b/scripts/codex-backend/protocol.md deleted file mode 100644 index 4b1c4640..00000000 --- a/scripts/codex-backend/protocol.md +++ /dev/null @@ -1,184 +0,0 @@ -# Native AgentControl stdio v1 - -The patched official Codex app-server retains its native collaboration handlers. -Only `THEOREMOS_HOST_AGENT_CONTROL=1` installs this host transport. Children run -in separate host-owned processes and filesystem namespaces. A missing handshake -fails startup; the runtime does not fall back to model dynamic collaboration tools. - -## Client endpoints - -All methods require the initialized experimental API connection. Requests and -responses below are JSON-RPC payloads, without the outer `id`/`result` envelope. - -| Method | Params | Response | -| --- | --- | --- | -| `theoremos/agentControl/capabilities` | `{}` | `{version:1,backend:"theoremos-host",nativeTools:true,isolatedChildBootstrap:true}` | -| `theoremos/agentControl/snapshot` | `{threadId}` | `{sessionId,agent,configSnapshot}` | -| `theoremos/agentControl/start` | `{version:1,bootstrap,thread?:ThreadStartParams,resume?:ThreadResumeParams}` | Normal native start/resume fields, plus `agentControl:{sessionId,agent,configSnapshot}` | -| `theoremos/agentControl/input` | Input below | `{threadId,submissionId,accepted:true,turn:{id,status:"inProgress",items:[]}|null}` | -| `theoremos/agentControl/update` | Update below | `{acceptedSequence}` | - -Start requires exactly one of `thread` and `resume`. It creates or resumes an idle -child without a model call or initial task. The host registers usage/completion -observers before sending input. Resume reads the child's persisted history; -it never replays the bootstrap's copied fork history. Its persisted thread, -session and source must match the captured bootstrap. This explicit transport -loads the child in its own process rather than attaching through a locally -loaded parent. Ordinary `thread/resume` retains the upstream parent-owned guard. -Root start/resume retain -normal upstream endpoints, followed by `snapshot` to bind their actual identity. - -`agent` is native `{threadId,metadata,status}`. Metadata is -`{agentId,agentPath,agentNickname,agentRole}`. `configSnapshot` is the actual -native effective worker snapshot; hosts forward it opaque in spawn receipts. -It is not a host prediction of worker configuration. - -## Bootstrap - -Rust exports `NativeChildBootstrap` from the prepared native SpawnRequest. It -captures session/source identity, model/reasoning/service-tier/instruction -settings, user/thread instruction snapshots, native filtered fork history and -provenance, execution policy and managed source requirements, environment -requests, inherited dynamic tools, disabled plugins, and originator. It never -serializes `Config`, auth, provider URLs/settings, or relay capabilities. The -child uses its own destination provider/profile. - -The trusted host reserves `bootstrap.threadId`. Only `bootstrap.hostOverrides` -may replace `cwd`, `environments`, `developerInstructions`, `dynamicTools`, or -further restrict `permissionProfile`. It also accepts an explicit -`workspaceRelocation:{from,to}` capability. `from` must equal captured -`bootstrap.config.cwd`, and `to` must equal the destination effective cwd. -The importer removes the captured source workspace write grants, moves workspace -authority to `to`, removes captured ancestor denies obstructing that namespace -binding, retains other denies/network restrictions, then intersects with the -destination profile. The destination's peer/secret denies remain effective. -This is a trusted host action; model spawn arguments cannot supply overrides. -OS namespace/bind isolation remains the host's responsibility. -Applying this computed permission intersection clears the destination's named -active-profile identity under upstream semantics. A child may therefore report -no `activePermissionProfile` ID; `configSnapshot.permissionProfile` carries the -actual effective authority. Ordinary root profile checks are unaffected. - -`bootstrap.config.networkPolicy` captures only the official traffic-policy DTO, -including domain/socket rules, never local proxy URLs or credentials. If the -parent had a proxy policy, the destination must provide the same traffic policy. -Missing or different policies fail explicitly; this version does not infer -subset relationships between different wildcard allowlists. The child's local -proxy setup remains destination-owned. Filesystem relocation cannot discard -parent network denials. - -The destination ignores its user/project exec-policy files when importing the -captured parent policy. The Lead's policy loader is unchanged, and its captured -user/project rules travel with the snapshot. Official managed-source compatibility -and requirement checks still run. Extra destination system `.rules` files are -rejected by the upstream inherited-policy contract, not silently skipped. -Captured instructions replace parent snapshots while repository instructions are -discovered in the destination worktree. Dynamic tools use upstream normalization -and retain their host execution routes. Native child startup installs root-capability -restrictions and gets the shared session identity from its attached controller. -Cold resume restores the persisted identity; upstream rejects a mismatch with the -attached controller. The ordinary host-root `InheritedSessionId` guard is unchanged. - -## Native input - -```ts -type Input = { - version: 1; - threadId: string; - author: string; // canonical native AgentPath - input: - | {kind:"userInput";items:UserInput[]} - | {kind:"message";message:{kind:"plaintext"|"encrypted";text:string}; - mode:"queueOnly"|"triggerTurn"} - | {kind:"communication";communication:InterAgentCommunication}; - startOptions?: { - parentTurnId?:string;rootTurnId?:string;turnTrigger?:string; - initiatingAgentPath?:string;finalOutputJsonSchema?:unknown;serviceTier?:string; - }; - contextItems?: ResponseItem[]; - expectedTurnId?:string; -}; -``` - -The transport holds a per-thread operation lock, injects context items, and uses -native turn acceptance. Triggered messages preserve native attribution and return -the real started/steered turn ID. `expectedTurnId` steers only that active turn; -it cannot start an idle replacement. Queue-only input is enqueued without starting -a model turn and returns `turn:null`. The raw communication variant preserves the -official completion formatter and avoids wrapping it as a new plaintext task. -When a trusted native trigger starts an idle recipient, previously accepted -mailbox items precede the trigger in its first model request. Ordinary user-input -turns retain upstream sampling and pending-input behavior. - -## Host callbacks - -Server request `theoremos/agentControl/request`: - -```ts -{version:1,sessionId:string,threadId:string,operationId:string, - operation:string,payload:unknown} -``` - -Every operation gets a fresh UUID `operationId`; the host retains it across -uncertain publication/recovery. Every successful callback response is -`{result:unknown}`. Errors are JSON-RPC errors. - -| Operation | Payload | `result` | -| --- | --- | --- | -| `attach` | `{threadId,sessionId}` | `{sessionId}` | -| `resolve` | `{caller,parent,source,target}` | `{threadId}` | -| `spawn` | `{caller,source,bootstrap,input,startOptions}` | `{agent,configSnapshot,submissionId}` | -| `send` | `{caller,target,input,startOptions}` | `{threadId,metadata,submissionId}` | -| `ensureChildLoaded` | `{parent,child}` | `{}` | -| `interrupt` | `{caller,target,version}` | `{kind:"loaded",agent,configSnapshot}` or `{kind:"unloaded",metadata}` | -| `list` | `{caller,parent,source,pathPrefix}` | `{agents}` | -| `childPaths` | `{parent}` | `{paths}` | -| `admitTurn` | `{threadId,turnId}` | `{admitted:true}` | -| `releaseTurn` | `{threadId,turnId}` | `{}` | -| `recordUsage` | `{threadId?,turnId?,usage,codexRolloutBudgetUnits}` | `{}` | -| `turnFinished` | `{outcome,parentThreadId?,completionMessage?}` | `{}` | -| `configUpdate` | `{serviceTier}` | `{}` | - -`target` is `{kind:"id",threadId}` or `{kind:"reference",reference}`. -Rust canonicalizes references and list prefixes with the official -`AgentPath::resolve`; the host validates registered membership in the same tree. -`source`, status, `TokenUsage`, and communication retain upstream serde shapes. -Rollout budget units travel separately because native TokenUsage skips them in -serde. Native admission is asynchronous before task execution and its official -guard owns `releaseTurn`; root and child turns use the same host authority. -No token/time budget is added by this adapter. - -`outcome` contains native `threadId`, `turnId`, `source`, `parentTurnId`, -`initiatingAgentPath`, `status`, and `errorInfo`. `completionMessage` is an -upstream `InterAgentCommunication` object rendered by the official completion -formatter. It is already attributed and queue-only. Ordinary interruptions do -not emit upstream terminal result callbacks; their execution guard still drops. -The native terminal event precedes the callback, so the host must await the -matching completion handoff and guard release before freezing a finished writer. - -Spawn retains provisional process ownership until the initial input receipt. -Cancellation before acceptance reaps the provisional child; cancellation after -acceptance does not retract its work. Follow-up input cannot target the root. -Unloaded interrupt observations preserve known identity and never mean completed. -The host routes child resume to its own app-server process, because a foreign -thread cannot be loaded through the parent's local ThreadManager. - -## Mailbox/shared updates - -```ts -{version:1,sessionId,threadId,sequence, - mailbox?:Array<{id,author,recipient, - message?:{kind:"plaintext"|"encrypted",text}, - communication?:InterAgentCommunication}>, - serviceTier?:string|null,admission?:{allowed:boolean,reason?:string}} -``` - -A native communication must match the envelope's author/recipient and be -queue-only. The runtime holds the synchronous mailbox and watch subscription. -An acknowledged sequence transfers ownership; repeats never enqueue mail twice. -The host persists accepted/uncertain states and does not label accepted mail read -or replay an uncertain worker task as new work. A sequence covers a complete -validated batch. An update can clear the shared service tier with explicit null. - -Native output is research output. Lean verification, proof delivery, source -freezing, adoption, and mathematical acceptance stay in TheoremOS host tools. diff --git a/scripts/codex-backend/upstream.json b/scripts/codex-backend/upstream.json deleted file mode 100644 index 92d27188..00000000 --- a/scripts/codex-backend/upstream.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "schema": "theoremos.codex-backend-upstream.v1", - "repository": "https://github.com/openai/codex.git", - "tag": "rust-v0.172.0", - "tagObject": "fc3036dba44468096953f0e832f3fecd3adc0228", - "revision": "3d86e43b075adeba2193ec5c22ac92f55afd82e6", - "toolchain": "1.99.1", - "cargoLockSha256": "42a8f334ee469aeeb6fccda4bd468f5addbe6d4e564e2780a90473090112c5ab", - "derivedCargoLockSha256": "0c017d96dae581ea09834ddbda7c572dd48e771cf86e9f87f8b3bcb4ab16f686", - "lockPatch": "derived-lock.patch", - "lockPatchSha256": "8abad44adc878a2ca22624ab788f8b774af177d7702ba59e3f4e59411b547b5c", - "lockPatchReason": "Align 174 local workspace package versions with release 0.172.0. The existing lock entry already records codex-app-server -> codex-rollout-trace. External dependencies remain unchanged.", - "patch": "agent-control.patch", - "package": "codex-cli", - "binary": "codex", - "profile": "dev", - "devDebug": "0", - "incremental": "0", - "submoduleMetadata": { - "repository": "https://github.com/openai-oss-forks/rusty_v8.git", - "revision": "90a65f887a0c0f048f3784afbcb320b373c8a2e0" - } -} diff --git a/scripts/mathematics/compareMathRuns.ts b/scripts/mathematics/compareMathRuns.ts index 5bc0789b..581f5d01 100644 --- a/scripts/mathematics/compareMathRuns.ts +++ b/scripts/mathematics/compareMathRuns.ts @@ -23,24 +23,10 @@ import { researchFailureCategory } from '../../src/solver/modules/search'; import { summarizeKnowledgeFunnel } from '../../src/solver/knowledgeFunnel'; import { buildTokenBudget, reportedTotalTokens } from '../../src/solver/usageBudget'; import { MAX_RESEARCH_WORKERS } from '../../src/solver/modules/organization'; -import { - DEEPSEEK_PROVIDER, - deepSeekProfileDigest, - expectedDeepSeekProfileDigest, - selectedDeepSeekProfile, -} from '../../src/runtime/deepseek'; -import { - WESTLAKE_PROVIDER, - westlakeProfileDigest, - expectedWestlakeProfileDigest, - selectedWestlakeProfile, -} from '../../src/runtime/westlake'; -import { - SUB2API_PROVIDER, - sub2apiProfileDigest, - expectedSub2apiProfileDigest, - selectedSub2apiProfile, -} from '../../src/runtime/sub2api'; +import { DEEPSEEK_PROVIDER, deepSeekProfileDigest, expectedDeepSeekProfileDigest } from '../../src/runtime/deepseek'; +import { WESTLAKE_PROVIDER, westlakeProfileDigest, expectedWestlakeProfileDigest } from '../../src/runtime/westlake'; +import { SUB2API_PROVIDER, sub2apiProfileDigest, expectedSub2apiProfileDigest } from '../../src/runtime/sub2api'; +import { selectedProviderProfile } from '../../src/runtime/providerProfile'; import { assertExperimentKnowledge, type ExperimentKnowledge } from './experimentKnowledge'; import type { ResearchSkillIdentity } from '../../src/solver/researchSkill'; import type { ResearchHarnessIdentity } from '../../src/runtime/researchHarness'; @@ -204,8 +190,7 @@ function assertComparisonHarnesses(plan: Plan): void { } function currentProviderProfile(profile: string) { - const selected = - selectedDeepSeekProfile(profile) ?? selectedSub2apiProfile(profile) ?? selectedWestlakeProfile(profile); + const selected = selectedProviderProfile(profile, Object.keys(providerProfiles)); if (!selected) throw new Error('comparison_common_provider_unverified'); return { profile: selected.profile, digest: selected.digest }; } diff --git a/scripts/package-codex-backend.sh b/scripts/package-codex-backend.sh deleted file mode 100755 index fca79554..00000000 --- a/scripts/package-codex-backend.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -if (( $# != 2 )); then - printf 'Usage: %s OUTPUT_DIRECTORY BACKEND_BUILD_DIRECTORY\n' "$0" >&2 - exit 2 -fi - -config=$(cd -- "$(dirname -- "$0")/codex-backend" && pwd -P) -output=$(realpath -m -- "$1") -build=$(realpath -- "$2") -target="$(uname -m)-linux-gnu" -if [[ $(uname -s) != Linux || $target != x86_64-linux-gnu ]]; then - printf 'The Codex backend package targets x86_64 Linux with glibc.\n' >&2 - exit 1 -fi - -mkdir -p -- "$output" -stage=$(mktemp -d "$output/.theoremos-codex-backend.XXXXXX") -trap 'rm -rf -- "$stage"' EXIT -install -d -- "$stage/package/bin" -install -m 0755 -- "$build/bin/codex" "$build/bin/codex-code-mode-host" "$stage/package/bin/" -install -m 0644 -- "$config/LICENSE.codex" "$config/NOTICE.codex" \ - "$config/upstream.json" "$config/agent-control.patch" "$config/derived-lock.patch" "$stage/package/" - -# Verify the staged bytes against the build record before publishing the archive. -build_id=$(/usr/bin/python3 - "$build/backend-build.json" "$stage/package" <<'PY' -import hashlib -import json -from pathlib import Path -import sys - -manifest = json.loads(Path(sys.argv[1]).read_text()) -package = Path(sys.argv[2]) -pin = json.loads((package / "upstream.json").read_text()) - -def digest(path): - with path.open("rb") as file: - return hashlib.file_digest(file, "sha256").hexdigest() - -checks = { - "schema": "theoremos.codex-backend-build.v1", - "upstream": pin, - "sourceRevision": pin["revision"], - "cargoLockSha256": pin["derivedCargoLockSha256"], - "lockPatchSha256": pin["lockPatchSha256"], - "patchSha256": digest(package / pin["patch"]), - "executableSha256": digest(package / "bin/codex"), - "codeModeHostSha256": digest(package / "bin/codex-code-mode-host"), -} -for field, expected in checks.items(): - if manifest.get(field) != expected: - raise SystemExit(f"Codex backend build record does not match {field}.") -if digest(package / pin["lockPatch"]) != pin["lockPatchSha256"]: - raise SystemExit("Codex backend lock patch does not match the pinned checksum.") - -record = {**checks, "builtAt": manifest["builtAt"], "rustc": manifest["rustc"], - "cargo": manifest["cargo"], "sourcePatchSha256": manifest["sourcePatchSha256"], - "submodulePinsSha256": manifest["submodulePinsSha256"], - "executable": "bin/codex", "codeModeHost": "bin/codex-code-mode-host"} -(package / "backend-build.json").write_text(json.dumps(record, indent=2) + "\n") -print(f'{pin["tag"].removeprefix("rust-")}-{checks["patchSha256"][:12]}') -PY -) -name="theoremos-codex-backend-$target-$build_id" -archive="$name.tar.gz" -mv -- "$stage/package" "$stage/$name" -tar -C "$stage" -I 'gzip -1' -cf "$stage/$archive" -- "$name" -(cd "$stage" && sha256sum -- "$archive" > "$archive.sha256") -mv -- "$stage/$archive" "$stage/$archive.sha256" "$output/" -printf '%s\n' "$output/$archive" diff --git a/scripts/test-codex-backend-delivery.ts b/scripts/test-codex-backend-delivery.ts deleted file mode 100644 index 041301cc..00000000 --- a/scripts/test-codex-backend-delivery.ts +++ /dev/null @@ -1,781 +0,0 @@ -import assert from 'node:assert/strict'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { createServer, type ServerResponse } from 'node:http'; -import { buildSync } from 'esbuild'; -import { prepareWebProviderProfile, webSolverModules } from '../apps/web/worker'; -import type { WebAgentActionBody, WorkerInput } from '../apps/web/shared'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { mathBuildFile, mathBuildSource, MATH_BUILD_INPUTS, MATH_RUNTIME_BUNDLES } from '../src/math/mathBuildManifest'; -import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { confirmHarnessProcessStopped, type HarnessProcessIdentity } from '../src/runtime/harnessProcess'; -import { admitResponsesRequest } from '../src/runtime/formalizationRelay'; -import { prepareSub2apiProfile, SUB2API_PROVIDER } from '../src/runtime/sub2api'; -import type { SolverRunState } from '../src/solver/archive'; -import { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; -import { buildAgentTeamContributions } from '../src/solver/agentTeamContributions'; -import { evaluateSolverProof } from '../src/solver/evaluation'; -import { directSolverModules } from '../src/solver/modules'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { runResearchLead } from '../src/solver/research'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; - -type Json = Record; - -// Freeze a disposable runtime exactly as the ordinary dispatch gate expects. -// The production runtime and independent Lean checker remain unmocked. -function freezeRuntime(repository: string, runtime: string) { - fs.mkdirSync(runtime); - for (const relative of [...MATH_BUILD_INPUTS, 'src', 'scripts', 'bin', 'resources', 'skills']) { - const destination = path.join(runtime, relative); - fs.mkdirSync(path.dirname(destination), { recursive: true }); - fs.cpSync(path.join(repository, relative), destination, { recursive: true }); - } - const bundleRoot = path.join(runtime, 'out/main'); - buildSync({ - entryPoints: Object.fromEntries( - ['runMathProof', 'searchLean', 'checkLean'].map((name, index) => [ - MATH_RUNTIME_BUNDLES[index].replace(/\.js$/u, ''), - path.join(runtime, 'scripts/mathematics', name + '.ts'), - ]), - ), - outdir: bundleRoot, - bundle: true, - platform: 'node', - format: 'cjs', - nodePaths: [path.join(repository, 'node_modules')], - loader: { '.py': 'text', '.lean': 'text' }, - logLevel: 'silent', - }); - const manifest = path.join(runtime, 'build-manifest.json'), - now = new Date().toISOString(); - writeMathJsonDurable(manifest, { - schema: 'deepscientist.math.build-manifest.v1', - buildId: crypto.randomUUID(), - startedAt: now, - finishedAt: now, - source: mathBuildSource(runtime), - bundleRoot, - bundles: MATH_RUNTIME_BUNDLES.map(name => mathBuildFile(path.join(bundleRoot, name))), - }); - fs.chmodSync(manifest, 0o400); - return manifest; -} - -/** Offline provider, real Codex process, production team runtime and real Lean acceptance. */ -export async function verifyNativeProofDelivery(input: { - repository: string; - executable: string; - output: string; - signal: AbortSignal; - webProvider?: boolean; -}) { - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - fs.mkdirSync(input.output, { recursive: true }); - const directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'native-proof-delivery-'))); - const requests: Json[] = [], - events: Json[] = [], - processes = new Map(); - const responseIds = new Map(), - concurrentWriters = new Set(); - const writerPaths = ['/root', '/root/proof_writer', '/root/proof_observer']; - const result: Json = { status: 'running', paidModelCalls: 0, providerProfile: input.webProvider ? 'web' : 'cli' }; - const apiKey = 'synthetic-offline-key'; - const webRequest: WorkerInput = { - id: 'offline-native-proof-delivery', - provider: { id: 'sub2api', name: 'Fixture gateway', baseUrl: 'http://host.docker.internal:8080/v1' }, - input: { - apiKey, - providerId: 'sub2api', - model: 'deepseek-flash', - effort: 'high', - task: 'Prove the frozen original using one checked child helper.', - source: '', - workers: 1, - coordination: 'independent', - maxTurns: 0, - maxRunSeconds: 0, - researchMode: 'skill', - nativeTeamCapacity: writerPaths.length, - }, - }; - const controller = new AbortController(); - const signal = AbortSignal.any([input.signal, controller.signal]); - const originalFetch = globalThis.fetch; - const leadProcesses: HarnessProcessIdentity[] = []; - const webActions: WebAgentActionBody[] = []; - let state: SolverRunState | undefined, - sequence = 0; - const quote = (value: string) => "'" + value.replace(/'/gu, "'\\''") + "'"; - const call = (id: string, name: string, args: Json, namespace?: string) => ({ - type: 'function_call', - id, - call_id: id, - ...(namespace ? { namespace } : {}), - name, - arguments: JSON.stringify(args), - status: 'completed', - }); - const message = (text: string) => ({ - type: 'message', - id: 'msg_proof_' + ++sequence, - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text, annotations: [] }], - }); - const until = async (predicate: () => boolean, response: ServerResponse) => { - while (!predicate()) { - signal.throwIfAborted(); - if (response.destroyed) return false; - const failed = state?.agentTeam?.workers.find(worker => worker.tasks.some(task => task.status === 'failed')); - if (failed) throw new Error('native-proof-member-failed:' + JSON.stringify(failed.tasks)); - await new Promise(resolve => setTimeout(resolve, 20)); - } - return true; - }; - // A proof placeholder on its own unindented line is legal Lean source. - const originalTarget = 'theorem original (n : Nat) : n + 0 = n ∧ True :=\nsorry\n'; - const consumerDraft = - 'namespace NativeProof\n' + - originalTarget.replace(':=\nsorry', ':= by\n constructor\n · exact helper n\n · sorry') + - 'end NativeProof\n'; - const sourceWithHelper = - 'namespace NativeProof\n' + - 'theorem helper (n : Nat) : n + 0 = n := by rfl\n' + - 'theorem side (n : Nat) : n = n := by rfl\n' + - originalTarget + - 'end NativeProof\n'; - const finding = 'NativeProof.helper is saved in my owned file; the original target remains unfinished.'; - const server = createServer(async (request, response) => { - try { - assert.equal(request.url, '/v1/responses'); - assert.equal(request.headers.authorization, 'Bearer ' + apiKey); - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - const body = JSON.parse(Buffer.concat(chunks).toString()); - admitResponsesRequest(body, 'deepseek-flash', 'high'); - requests.push(body); - const expectedWriter = JSON.parse(body.client_metadata['x-codex-turn-metadata']).agent_name as string; - assert.ok(writerPaths.includes(expectedWriter), 'Native request must identify its writer.'); - const text = body.input - .filter((item: Json) => ['message', 'agent_message'].includes(item.type)) - .flatMap((item: Json) => item.content ?? []) - .map((part: Json) => part.text ?? part.encrypted_content ?? '') - .join('\n'); - const receipts = new Set( - body.input.filter((item: Json) => item.type === 'function_call_output').map((item: Json) => item.call_id), - ); - const childRequest = text.includes('Current native task instructions'); - assert.equal(childRequest, expectedWriter !== '/root'); - const declarations = [ - ...(body.tools ?? []), - ...body.input.filter((item: Json) => item.type === 'additional_tools').flatMap((item: Json) => item.tools), - ].flatMap((tool: Json) => (tool.type === 'namespace' ? tool.tools : [tool])); - const host = declarations.find((tool: Json) => tool.name === 'theoremos_team'); - if (!childRequest) - assert.doesNotMatch( - host.description, - /\bD\d{3}\b/u, - 'The shared Lead tool must not preselect a domain expert for unrelated assignments.', - ); - assert.deepEqual( - [...host.parameters.properties.operation.enum].sort(), - (childRequest - ? ['yield', 'history', 'inspect', 'inspect-research', 'submit', 'route_summary'] - : ['finish', 'history', 'inspect', 'inspect-research', 'adopt', 'retire_route', 'route_summary'] - ).sort(), - 'Native host operations must stay limited to proof delivery, route management and inspection.', - ); - assert.equal(body.tool_choice, 'auto', 'The host must not impose a collaboration decision.'); - if (!childRequest && JSON.stringify(body.input).includes(finding)) result.nativeFindingReceived = true; - const overlap = - expectedWriter === '/root' - ? receipts.has('proof_spawn_observer') && !receipts.has('proof_draft') - : !responseIds.has(expectedWriter); - if (overlap) { - concurrentWriters.add(expectedWriter); - if (concurrentWriters.size === writerPaths.length) { - const records = [state!, ...state!.agentTeam!.workers]; - assert.deepEqual( - records.map(record => record.requestUsageAccounting?.pendingRequests), - [1, 1, 1], - 'The real Lead and both native members must be in flight through the relay at the same time.', - ); - result.simultaneousWriters = [...concurrentWriters].sort(); - } - if (!(await until(() => concurrentWriters.size === writerPaths.length, response))) return; - } - let items: Json[]; - if (expectedWriter === '/root/proof_observer') items = [message('Read only review complete.')]; - else if (childRequest) { - assert.deepEqual(state!.agentTeam!.workers[0]!.tasks[0]!.profileEvidence?.loaded, ['prover']); - assert.match(text, /### Lean Prover/u, 'The corrected specialty must reach the actual writer request.'); - for (const contradictoryHint of [ - 'All agents share the same directory', - 'There are 4 available concurrency slots', - 'You can spawn sub-agents to handle subtasks', - ]) - assert.equal( - text.includes(contradictoryHint), - false, - 'Host role context must replace generic multi-agent hints.', - ); - result.childContextsChecked = (result.childContextsChecked ?? 0) + 1; - if (!receipts.has('proof_child_write')) - items = [ - call('proof_child_write', 'exec_command', { - login: false, - cmd: - 'test -s .agents/skills/theoremos-research/SKILL.md && cat .agents/skills/theoremos-research/SKILL.md >/dev/null && printf %s ' + - quote(sourceWithHelper) + - ' > generated/problem/Submission.lean && printf %s ' + - quote('One independent helper is ready for the Lead.\n') + - ' > RESEARCH.md', - }), - ]; - else if (!receipts.has('proof_child_finding')) - items = [ - call( - 'proof_child_finding', - 'send_message', - { - target: '/root', - message: finding, - }, - 'collaboration', - ), - ]; - else if (!receipts.has('proof_child_submit')) { - // Exercise the ordering from the real run: Lead writes the consumer while the member still owns the helper. - if ( - !(await until( - () => - fs.readFileSync(path.join(state!.worktree, 'generated/problem/Submission.lean'), 'utf8') === - consumerDraft, - response, - )) - ) - return; - result.consumerDraftBeforeSubmit = true; - items = [ - call('proof_child_submit', 'theoremos_team', { - operation: 'submit', - summary: 'Independent identity helper for the Lead.', - declarations: [ - { file: 'Submission.lean', name: 'NativeProof.helper', type: '∀ n : Nat, n + 0 = n' }, - { file: 'Submission.lean', name: 'NativeProof.side', type: '∀ n : Nat, n = n' }, - ], - }), - ]; - } else items = [message('Helper submitted; release writing for independent checking.')]; - } else if (!receipts.has('proof_opening_read')) - items = [ - call('proof_opening_read', 'exec_command', { - login: false, - cmd: 'cat generated/problem/Submission.lean', - }), - ]; - else if (!receipts.has('proof_bad_profile')) - items = [ - call( - 'proof_bad_profile', - 'spawn_agent', - { - task_name: 'proof_writer', - fork_turns: 'none', - message: 'Profiles: prover (Lean prover, Mathlib).\nProve the helper.', - }, - 'collaboration', - ), - ]; - else if (!receipts.has('proof_spawn')) { - const rejection = body.input.find( - (item: Json) => item.type === 'function_call_output' && item.call_id === 'proof_bad_profile', - ); - assert.match( - JSON.stringify(rejection.output), - /math_team_profile_unresolved.*Profiles: prover/u, - 'The Lead must receive the rejected selection and the correction through the native tool.', - ); - assert.equal(state!.agentTeam!.workers.length, 0, 'A rejected dispatch must not occupy a team slot.'); - result.rejectedDispatchFeedback = rejection.output; - items = [ - call( - 'proof_spawn', - 'spawn_agent', - { - task_name: 'proof_writer', - fork_turns: 'none', - message: - 'Profiles: prover\nProve an independent NativeProof.helper (n : Nat) : n + 0 = n in your owned file. Lead consumes it in NativeProof.original. Report the first useful result and submit the helper; leave the original target unfinished.', - }, - 'collaboration', - ), - ]; - } else if (!receipts.has('proof_spawn_observer')) - items = [ - call( - 'proof_spawn_observer', - 'spawn_agent', - { - task_name: 'proof_observer', - fork_turns: 'none', - message: - 'Inspect the frozen original independently. Return an advisory review without editing any files.', - }, - 'collaboration', - ), - ]; - else if (!receipts.has('proof_draft')) - items = [ - call('proof_draft', 'exec_command', { - login: false, - cmd: - 'printf %s ' + - quote(consumerDraft) + - ' > generated/problem/Submission.lean && printf %s ' + - quote('The first conjunct calls the agreed helper. Lead owns the remaining conjunct.\n') + - ' > RESEARCH.md', - }), - ]; - else if (!receipts.has('proof_wait')) - items = [call('proof_wait', 'wait_agent', { timeout_ms: 10000 }, 'collaboration')]; - else if (!receipts.has('proof_history')) { - if (!(await until(() => Boolean(state?.agentTeam?.deliveries.length), response))) return; - items = [call('proof_history', 'theoremos_team', { operation: 'history' })]; - } else if (!receipts.has('proof_inspect')) - items = [ - call('proof_inspect', 'theoremos_team', { - operation: 'inspect', - deliveryId: state!.agentTeam!.deliveries[0].id, - }), - ]; - else if (!receipts.has('proof_adopt')) - items = [ - call('proof_adopt', 'theoremos_team', { - operation: 'adopt', - deliveryId: state!.agentTeam!.deliveries[0].id, - }), - ]; - else if (!receipts.has('proof_consume')) { - assert.equal(state!.agentTeam!.adoptions[0].status, 'completed', 'Lead must resume only after host adoption'); - const adoptedEvent = state!.agentTeam!.events.find(event => event.kind === 'adopted')!; - const adoptedMail = state!.agentTeam!.nativeControl!.mailbox.find( - mail => - mail.author === '/morpheus' && - mail.message?.kind === 'plaintext' && - mail.message.text === 'Mathematical host update (advisory):\n' + canonicalMathJson(adoptedEvent), - )!; - assert.ok(adoptedMail, 'The host adoption event must enter the native mailbox.'); - assert.equal(adoptedMail.author, '/morpheus'); - assert.equal(adoptedMail.status, 'accepted', 'The resumed native Lead must receive its host adoption event.'); - result.adoptedHostMessage = { - author: adoptedMail.author, - status: adoptedMail.status, - kind: adoptedEvent.kind, - deliveryId: adoptedEvent.deliveryId, - }; - const adopted = fs.readFileSync(path.join(state!.worktree, 'generated/problem/Submission.lean'), 'utf8'); - assert.match(adopted, /theorem helper/u); - assert.ok( - adopted.includes(consumerDraft.slice('namespace NativeProof\n'.length)), - 'Adoption must preserve the consumer proof drafted before submission.', - ); - items = [ - call('proof_consume', 'exec_command', { - login: false, - cmd: - 'printf %s ' + - quote(adopted.replace(' · sorry\n', ' · trivial\n')) + - ' > generated/problem/Submission.lean && printf %s ' + - quote('The original consumes the host-checked child helper.\n') + - ' > RESEARCH.md', - }), - ]; - } else if (!receipts.has('proof_finish')) - items = [ - call('proof_finish', 'theoremos_team', { - operation: 'finish', - summary: 'Original theorem saved using the adopted helper; ready for independent host acceptance.', - }), - ]; - else items = [message('Original proof is saved.')]; - const base = { - id: 'resp_proof_' + ++sequence, - object: 'response', - created_at: 1, - model: 'deepseek-flash', - status: 'in_progress', - output: [], - }; - const ids = responseIds.get(expectedWriter) ?? []; - ids.push(base.id); - responseIds.set(expectedWriter, ids); - const emit = (value: Json) => - response.write('event: ' + value.type + '\ndata: ' + JSON.stringify(value) + '\n\n'); - response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); - emit({ type: 'response.created', response: base }); - for (const [output_index, item] of items.entries()) { - emit({ - type: 'response.output_item.added', - output_index, - item: { - ...item, - status: 'in_progress', - ...(item.type === 'function_call' ? { arguments: '' } : { content: [] }), - }, - }); - if (item.type === 'function_call') { - emit({ - type: 'response.function_call_arguments.delta', - item_id: item.id, - output_index, - delta: item.arguments, - }); - emit({ - type: 'response.function_call_arguments.done', - item_id: item.id, - output_index, - arguments: item.arguments, - }); - } else { - emit({ - type: 'response.output_text.delta', - item_id: item.id, - output_index, - content_index: 0, - delta: item.content[0].text, - }); - emit({ - type: 'response.output_text.done', - item_id: item.id, - output_index, - content_index: 0, - text: item.content[0].text, - }); - } - emit({ type: 'response.output_item.done', output_index, item }); - } - emit({ - type: 'response.completed', - response: { - ...base, - status: 'completed', - output: items, - usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, - }, - }); - response.end(); - } catch (error) { - result.providerFailure ??= String(error); - if (!response.headersSent) response.writeHead(500); - response.end('Offline proof fixture failed.'); - controller.abort(error); - } - }); - try { - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - // Keep the production provider profile and request gate. Only its upstream - // network destination is replaced; no request can reach a real provider. - const endpoint = `http://127.0.0.1:${(server.address() as any).port}/v1/responses`; - globalThis.fetch = (async (resource, options) => { - const url = typeof resource === 'string' ? resource : resource instanceof URL ? resource.href : resource.url; - assert.equal( - url, - (input.webProvider ? webRequest.provider.baseUrl : SUB2API_PROVIDER.baseUrl) + '/responses', - 'Only the fixed production relay endpoint may be requested.', - ); - result.relayRequests = (result.relayRequests ?? 0) + 1; - return originalFetch(endpoint, options); - }) as typeof fetch; - const runtime = path.join(directory, 'runtime'), - buildFile = freezeRuntime(input.repository, runtime); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { - task: 'Prove the frozen original using one checked child helper.', - source: 'namespace NativeProof\n' + originalTarget + 'end NativeProof\n', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), - worktree = path.join(directory, 'lead'); - git(receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const identity = researchSkillIdentity( - readMathAgentSkill(path.join(runtime, 'skills/theoremos-research/SKILL.md')), - ); - const skill = prepareResearchSkill(runtime, worktree, identity, problem); - state = { - schema: 'deepscientist.math.solver.v1', - runId: 'offline-native-proof-delivery', - phase: 'prepared', - problem, - worktree, - model: 'deepseek-flash', - effort: 'high', - turns: 0, - taskDigest: mathDigest('proof-fixture'), - buildDigest: 'fixture', - environmentDigest: mathDigest('native-proof-delivery'), - evaluatorDigest: 'fixture', - researchMode: 'skill', - researchSkillWorkflow: 'full', - researchSkill: identity, - researchDelegation: { mode: 'team', maxAgents: writerPaths.length }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }; - const profile = path.join(directory, 'profile'); - if (input.webProvider) prepareWebProviderProfile(profile, webRequest); - else prepareSub2apiProfile(profile, state.model, state.effort); - const userHome = os.homedir(); - const elanHome = process.env.ELAN_HOME || path.join(userHome, '.elan'); - const toolchain = path.join(elanHome, 'toolchains/leanprover--lean4---v4.36.0'); - assert.ok(fs.existsSync(path.join(toolchain, 'bin/lean')), 'Native delivery acceptance requires Lean 4.36.0.'); - const environment = { - HOME: userHome, - PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: elanHome, - LEAN_PATH: '', - LEAN_SYSROOT: '', - NO_PROXY: '127.0.0.1,localhost', - ...(!input.webProvider && { SUB2API_WESTLAKE_API_KEY: apiKey }), - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env'), - }; - const modules = input.webProvider - ? webSolverModules(webRequest, { - sink: action => webActions.push(action), - hidden: [directory], - solverRunId: () => state?.runId, - }) - : directSolverModules; - const winner = await runResearchLead({ - state, - root: runtime, - buildFile, - taskText: 'Prove NativeProof.original by consuming one independently checked child declaration.', - executable: input.executable, - profile, - modules: { - ...modules, - M1: { - ...modules.M1, - open: async options => { - const session = await modules.M1.open(options); - if (options.workspace === worktree && session.processIdentity) { - const previous = leadProcesses.at(-1); - if (previous) - assert.equal( - confirmHarnessProcessStopped(previous).status, - 'stopped', - 'Previous Lead writer must stop before reopening.', - ); - leadProcesses.push(session.processIdentity); - } - return session; - }, - }, - }, - signal, - deadline: Infinity, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - access: { environment, researchSkill: skill, retrievalRoot: path.join(worktree, problem.projectRelative) }, - save: () => { - for (const current of [ - state!.writerProcess, - ...(state!.agentTeam?.workers.map(worker => worker.writerProcess) ?? []), - ]) - if (current) processes.set(current.pid + ':' + current.startTime, current); - writeMathJsonDurable(path.join(input.output, 'state.json'), state); - }, - emit: (event, details) => { - events.push({ event, ...details }); - }, - }); - assert.equal(result.providerFailure, undefined); - if (input.webProvider) { - const toolActions = webActions.filter( - action => action.kind === 'tool' && action.tool?.startsWith('collaboration.'), - ); - assert.ok(toolActions.some(action => action.tool === 'collaboration.wait_agent' && action.status === 'running')); - assert.ok( - toolActions.some( - action => action.tool === 'collaboration.agent_started' && action.arguments === '/root/proof_writer', - ), - ); - result.webCollaborationActions = toolActions.length; - } - assert.ok(result.childContextsChecked > 0); - assert.equal( - result.relayRequests, - requests.length, - 'Every upstream fixture request must cross the production relay.', - ); - const writerRecords = [state, ...state.agentTeam!.workers]; - assert.deepEqual(result.simultaneousWriters, [...writerPaths].sort()); - result.writerAccounting = writerRecords.map(record => { - const accounting = record.requestUsageAccounting!; - assert.ok(accounting, 'Each native writer must report production request accounting.'); - assert.equal(accounting.incomplete, false); - assert.equal(accounting.pendingRequests, 0); - assert.equal(accounting.reportedRequests, accounting.startedRequests); - const writerPath = 'native' in record ? record.native!.agentPath : '/root'; - const taskId = 'tasks' in record ? record.tasks[0]!.id : undefined; - const threadId = 'native' in record ? record.native!.threadId : state!.agentTeam!.nativeControl!.rootThreadId; - const receipts = accounting.receipts!; - assert.deepEqual(receipts.map(receipt => receipt.providerRequestId).sort(), responseIds.get(writerPath)!.sort()); - assert.ok( - receipts.every( - receipt => receipt.threadId === threadId && receipt.taskId === taskId && receipt.status === 'reported', - ), - ); - return { writer: writerPath, threadId, taskId, reportedRequests: accounting.reportedRequests }; - }); - assert.equal( - result.writerAccounting.reduce((total: number, record: Json) => total + record.reportedRequests, 0), - requests.length, - ); - assert.equal(state.tokenBudget?.status, 'unlimited'); - assert.equal(state.tokenBudget?.reportedTotalTokens, requests.length * 12); - assert.equal(winner?.check.passed, true, 'The original must pass independent production M2 checking.'); - assert.equal(winner.check.verification.status, 'kernel_verified'); - assert.deepEqual( - winner.check.verification.results.map(item => item.theoremName), - ['NativeProof.original'], - ); - assert.equal(state.agentTeam!.deliveries.length, 1); - const reference = state.agentTeam!.deliveries[0], - delivery = readAgentTeamProofDelivery(reference.path, state); - assert.equal(delivery.artifacts[0].proof.verification.status, 'kernel_verified'); - assert.equal(delivery.declarations[0].name, 'NativeProof.helper'); - assert.equal(state.agentTeam!.adoptions[0].status, 'completed'); - assert.equal( - result.nativeFindingReceived, - true, - 'The child finding must reach the Lead through the native mailbox.', - ); - assert.equal( - state.agentTeam!.coordination, - undefined, - 'Native dispatch must not write an adapter coordination journal.', - ); - assert.deepEqual( - events.filter(event => event.event.startsWith('team_coordination') || event.event === 'team_research_observed'), - [], - 'Native collaboration must not create host coordination checkpoints.', - ); - assert.ok(leadProcesses.length >= 2, 'Adoption must stop the first writer and resume its saved native thread.'); - assert.equal(result.consumerDraftBeforeSubmit, true); - fs.copyFileSync( - path.join(worktree, 'generated/problem/Submission.lean'), - path.join(input.output, 'Submission.lean'), - ); - writeMathJsonDurable(path.join(input.output, 'delivery.json'), delivery); - writeMathJsonDurable(path.join(input.output, 'original-check.json'), winner.check); - assert.ok( - state.agentTeam!.leadExposures?.some( - exposure => exposure.kind === 'inspected' && exposure.deliveryId === reference.id, - ), - ); - assert.ok( - state.agentTeam!.leadExposures?.some( - exposure => exposure.kind === 'adopted' && exposure.deliveryId === reference.id, - ), - ); - assert.equal( - git(receipt.workspaceRoot, ['rev-parse', 'HEAD']), - problem.baseCommit, - 'Research must not publish into the original workspace.', - ); - const evaluation = await evaluateSolverProof(problem, winner.check, environment, signal, { - timeoutMs: Infinity, - teamContributions: true, - }); - assert.equal(evaluation.status, 'passed'); - const contributions = buildAgentTeamContributions(state, evaluation); - assert.ok(contributions); - assert.deepEqual( - contributions.advisoryMessages.map(item => ({ from: item.from, to: item.to, text: item.text })), - [{ from: '/root/proof_writer', to: '/root', text: finding }], - 'Only member messages should be reported here; the host delivery notice is separate.', - ); - for (const [name, relation] of [ - ['NativeProof.helper', 'direct'], - ['NativeProof.side', 'not-referenced'], - ]) { - const declaration = contributions.declarations.find( - item => item.deliveryId === reference.id && item.name === name, - ); - assert.ok( - declaration?.targets.some(target => target.name === 'NativeProof.original' && target.relation === relation), - 'Expected ' + relation + ' evidence for ' + name, - ); - } - writeMathJsonDurable(path.join(input.output, 'final-contributions.json'), contributions); - result.status = 'passed'; - result.requests = requests.length; - result.usageComplete = state.tokenBudget?.usageComplete; - result.deliveryId = reference.id; - result.adoption = state.agentTeam!.adoptions[0]; - result.leadWriterProcesses = leadProcesses; - result.originalCheck = { - passed: winner.check.passed, - status: winner.check.verification.status, - commit: winner.check.commit, - declarations: winner.check.verification.results.map(item => item.theoremName), - }; - result.checks = [ - 'production-relay', - 'simultaneous-writer-request-accounting', - 'minimal-native-host-operations', - 'native-role-context', - 'pinned-skill-read', - 'native-spawn', - 'native-source-write', - 'native-finding-message', - 'native-wait', - 'submit', - 'writer-stop', - 'adopted-host-mail', - 'independent-helper-check', - 'inspect', - 'adopt', - 'native-source-consumption', - 'independent-original-check', - 'final-s3-check', - 'final-uses-one-of-two-adopted-declarations', - ]; - return result; - } catch (error) { - result.status = 'failed'; - result.error = error instanceof Error ? { message: error.message, stack: error.stack } : String(error); - throw error; - } finally { - globalThis.fetch = originalFetch; - result.processes = [...processes.values()].map(identity => ({ - ...identity, - stop: confirmHarnessProcessStopped(identity), - })); - if (result.processes.some((process: Json) => process.stop.status !== 'stopped')) result.status = 'failed'; - writeMathJsonDurable(path.join(input.output, 'verification.json'), result); - writeMathJsonDurable(path.join(input.output, 'trace.json'), { requests, events }); - server.closeAllConnections(); - await new Promise(resolve => server.close(() => resolve())); - fs.rmSync(directory, { recursive: true, force: true }); - assert.equal( - result.processes.some((process: Json) => process.stop.status !== 'stopped'), - false, - 'All native writers must stop.', - ); - } -} diff --git a/scripts/test-codex-backend.ts b/scripts/test-codex-backend.ts deleted file mode 100644 index ed947e0a..00000000 --- a/scripts/test-codex-backend.ts +++ /dev/null @@ -1,888 +0,0 @@ -#!/usr/bin/env bun -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { createServer, type ServerResponse } from 'node:http'; -import { fileURLToPath } from 'node:url'; -import { parse, stringify } from 'smol-toml'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { mathDigest, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { createCodexMathSession } from '../src/runtime/codexSession'; -import { admitResponsesRequest } from '../src/runtime/formalizationRelay'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; -import { confirmHarnessProcessStopped, type HarnessProcessIdentity } from '../src/runtime/harnessProcess'; -import { prepareSub2apiProfile } from '../src/runtime/sub2api'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { agentTeamInstructions } from '../src/solver/agentTeamContext'; -import type { SolverRunState } from '../src/solver/archive'; -import { directSolverModules } from '../src/solver/modules'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { verifyNativeProofDelivery } from './test-codex-backend-delivery'; - -// Real Codex collaboration handlers and isolated writer processes. All Responses -// are deterministic fixture messages on this process's loopback server. -const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const flag = (name: string) => { - const index = process.argv.indexOf(name); - return index < 0 ? undefined : process.argv[index + 1]; -}; -const capacityTest = process.argv.includes('--team-capacity'); -const largeForkTest = process.argv.includes('--large-fork'); -assert.ok(!capacityTest || !largeForkTest, 'Select only one fixture mode.'); -const maxAgents = capacityTest ? 8 : 3; -const requestedExecutable = - flag('--executable') ?? process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? path.join(root, 'out/codex-backend/codex'); -if (!fs.existsSync(requestedExecutable)) - throw new Error( - 'Native backend acceptance requires a real Codex binary. ' + - 'Pass --executable PATH or THEOREMOS_TEST_CODEX_EXECUTABLE; missing: ' + - requestedExecutable, - ); -const executable = fs.realpathSync(requestedExecutable); -const version = spawnSync(executable, ['--version'], { encoding: 'utf8', timeout: 5000 }); -if (version.status !== 0) throw new Error('Native backend acceptance could not execute Codex: ' + executable); -const output = path.resolve( - flag('--output') ?? path.join(process.env.TMPDIR ?? '/data/lzh/default-storage/tmp', 'codex-backend-verification'), -); -fs.mkdirSync(output, { recursive: true, mode: 0o700 }); -const directory = fs.mkdtempSync( - path.join(process.env.TMPDIR ?? '/data/lzh/default-storage/tmp', 'codex-backend-e2e-'), -); -const requests: Record[] = [], - events: Record[] = []; -const processes = new Map(); -const observations: Record = { - schema: 'theorem-os.codex-backend-verification.v1', - executable, - version: version.stdout.trim(), - executableDigest: mathDigest(fs.readFileSync(executable)), - paidModelCalls: 0, - status: 'running', -}; -let team: AgentResearchTeam | undefined, lead: MathAgentSession | undefined; -let sequence = 0, - rootStep = 0; -const memberSteps = new Map(); -let state: SolverRunState; -const controller = new AbortController(); -// A disposable integration-test timeout, independent of solving/model budgets. -const deadline = setTimeout(() => controller.abort(new Error('offline-native-backend-test-timeout')), 240_000); -const until = async (predicate: () => boolean) => { - while (!predicate()) { - controller.signal.throwIfAborted(); - await new Promise(resolve => setTimeout(resolve, 20)); - } -}; -const quote = (value: string) => "'" + value.replace(/'/gu, "'\\''") + "'"; -const message = (text: string) => ({ - type: 'message', - id: 'msg_' + ++sequence, - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text, annotations: [] }], -}); -const call = (id: string, name: string, args: unknown, namespace?: string) => ({ - type: 'function_call', - id, - call_id: id, - ...(namespace ? { namespace } : {}), - name, - arguments: JSON.stringify(args), - status: 'completed', -}); -const nativeCall = (id: string, name: string, args: unknown) => call(id, name, args, 'collaboration'); - -async function largeForkResponse(body: Record, text: string, mode: string) { - if (mode.includes('You are a member')) { - assert.match(text, /LARGE_FORK_FRESH_WORKER/u); - assert.doesNotMatch(text, /LARGE_FORK_HISTORY/u); - return [message('Fresh worker completed.')]; - } - if (!text.includes('LARGE_FORK_ACTION')) return [message('Stored a disposable history segment.')]; - const receipts = new Map( - body.input - .filter((item: any) => item.type === 'function_call_output') - .map((item: any) => [item.call_id, item.output]), - ); - if (!receipts.has('oversized_fork')) - return [ - nativeCall('oversized_fork', 'spawn_agent', { - task_name: 'large_fork', - fork_turns: 'all', - message: 'Try an oversized history transfer.', - }), - ]; - const rejection = receipts.get('oversized_fork')!; - assert.match(rejection, /exceeds the 8 MiB transport limit.*fork_turns=none/u); - if (!receipts.has('fresh_after_oversized_fork')) - return [ - nativeCall('fresh_after_oversized_fork', 'spawn_agent', { - task_name: 'large_fork', - fork_turns: 'none', - message: 'LARGE_FORK_FRESH_WORKER Continue this disposable fixture.', - }), - ]; - assert.equal(JSON.parse(receipts.get('fresh_after_oversized_fork')!).task_name, '/root/large_fork'); - await until(() => !team!.hasActiveWorkers); - observations.largeFork = { - rejection, - leadThreadId: lead!.threadId, - workerStatus: state.agentTeam!.workers[0]?.tasks.at(-1)?.status, - }; - return [message('Lead finished after recovering from the oversized fork.')]; -} - -const pendingMembers = new Set(); -let releaseMembers = false; -async function capacityResponse(body: Record, text: string, mode: string) { - if (mode.includes('You are a member')) { - const name = text.match(/NATIVE_CAPACITY_MEMBER (seat_[1-7])\b/u)?.[1]; - assert.ok(name && !pendingMembers.has(name), 'one real writer request per accepted seat'); - pendingMembers.add(name); - try { - await until(() => releaseMembers); - } finally { - pendingMembers.delete(name); - } - return [message('Capacity fixture worker finished.')]; - } - const receipts = new Map( - body.input - .filter((item: any) => item.type === 'function_call_output') - .map((item: any) => [item.call_id, item.output]), - ); - for (let n = 1; n <= 7; n++) { - const name = 'seat_' + n, - receipt = receipts.get(name); - if (!receipt) - return [ - nativeCall(name, 'spawn_agent', { - task_name: name, - fork_turns: 'none', - message: 'NATIVE_CAPACITY_MEMBER ' + name + ' Hold this disposable fixture assignment.', - }), - ]; - assert.equal(JSON.parse(receipt).task_name, '/root/' + name, 'native spawn must accept ' + name + ': ' + receipt); - } - await until(() => pendingMembers.size === 7 || releaseMembers); - if (!receipts.has('capacity_roster')) return [nativeCall('capacity_roster', 'list_agents', {})]; - const roster = JSON.parse(receipts.get('capacity_roster')!).agents; - const expected = ['/root', ...Array.from({ length: 7 }, (_, i) => '/root/seat_' + (i + 1))]; - assert.deepEqual( - roster - .filter((agent: any) => agent.agent_status === 'running') - .map((agent: any) => agent.agent_name) - .sort(), - expected, - ); - if (!receipts.has('overflow')) - return [ - nativeCall('overflow', 'spawn_agent', { - task_name: 'overflow', - fork_turns: 'none', - message: 'Overflow fixture; must never reach a writer.', - }), - ]; - const overflow = receipts.get('overflow')!; - assert.match(overflow, /math_team_capacity_exceeded/u); - assert.equal(processes.size, maxAgents, 'one isolated writer process per occupied seat'); - assert.equal(state.agentTeam!.workers.length, 7, 'overflow must not allocate a worker'); - observations.capacity = { - maxAgents, - activeNativeAgents: expected, - simultaneousMemberRequests: 7, - writerProcesses: processes.size, - overflowReceipt: overflow, - }; - releaseMembers = true; - await until(() => !team!.hasActiveWorkers); - return [message('Capacity verified.')]; -} - -/** Native resumes/full forks preserve history; a later mode supersedes older hints. */ -const effectiveMultiAgentMode = (body: Record): string | undefined => { - const messages = [ - body.instructions, - ...body.input - .filter((item: any) => ['system', 'developer'].includes(item.role)) - .map((item: any) => - typeof item.content === 'string' - ? item.content - : (item.content ?? []).map((part: any) => part.text ?? '').join('\n'), - ), - ]; - return messages - .filter((text): text is string => typeof text === 'string') - .flatMap(text => - [...text.matchAll(/([\s\S]*?)<\/multi_agent_mode>/gu)].map(match => match[1]!.trim()), - ) - .at(-1); -}; - -function sendResponse(response: ServerResponse, items: any[]) { - const base = { - id: 'resp_' + ++sequence, - object: 'response', - created_at: 1, - model: 'deepseek-flash', - status: 'in_progress', - output: [], - }; - const emit = (value: unknown) => - response.write('event: ' + (value as any).type + '\ndata: ' + JSON.stringify(value) + '\n\n'); - response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); - emit({ type: 'response.created', response: base }); - for (const [output_index, item] of items.entries()) { - emit({ - type: 'response.output_item.added', - output_index, - item: { - ...item, - status: 'in_progress', - ...(item.type === 'function_call' ? { arguments: '' } : { content: [] }), - }, - }); - if (item.type === 'function_call') { - emit({ type: 'response.function_call_arguments.delta', item_id: item.id, output_index, delta: item.arguments }); - emit({ - type: 'response.function_call_arguments.done', - item_id: item.id, - output_index, - arguments: item.arguments, - }); - } else { - emit({ - type: 'response.output_text.delta', - item_id: item.id, - output_index, - content_index: 0, - delta: item.content[0].text, - }); - emit({ - type: 'response.output_text.done', - item_id: item.id, - output_index, - content_index: 0, - text: item.content[0].text, - }); - } - emit({ type: 'response.output_item.done', output_index, item }); - } - emit({ - type: 'response.completed', - response: { - ...base, - status: 'completed', - output: items, - usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, - }, - }); - response.end(); -} - -const server = createServer(async (request, response) => { - try { - assert.equal(request.url, '/v1/responses'); - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - const body = JSON.parse(Buffer.concat(chunks).toString()); - // Exercise the production relay's contract against actual native requests, - // including child message history. A permissive fixture server hid this boundary. - admitResponsesRequest(body, 'deepseek-flash', 'high'); - requests.push(largeForkTest ? { bytes: chunks.reduce((total, chunk) => total + chunk.length, 0) } : body); - const text = body.input - .filter((item: any) => ['message', 'agent_message'].includes(item.type)) - .flatMap((item: any) => item.content ?? []) - .map((part: any) => part.text ?? part.encrypted_content ?? '') - .join('\n'); - let items: any[]; - const member = /NATIVE_INTERRUPT_TEST/u.test(text) - ? 'interrupt' - : /NATIVE_FORK_TEST/u.test(text) - ? 'forked' - : /NATIVE_FOLLOWUP_TEST/u.test(text) - ? 'followup' - : /NATIVE_WORKER_TEST/u.test(text) - ? 'expert' - : undefined; - const mode = effectiveMultiAgentMode(body); - assert.ok(mode, 'Every native writer request must carry an effective multi-agent mode.'); - assert.doesNotMatch( - mode, - /Any earlier instruction enabling proactive multi-agent delegation no longer applies|Do not spawn sub-agents unless/u, - 'The current native mode must honor the explicitly requested team.', - ); - assert.equal(body.tool_choice, 'auto', 'Native collaboration must remain a model choice.'); - if (capacityTest) return sendResponse(response, await capacityResponse(body, text, mode)); - if (largeForkTest) return sendResponse(response, await largeForkResponse(body, text, mode)); - if (member) { - assert.match(mode, /You are a member of an explicitly requested flat team\./u); - assert.match(mode, /Do not spawn sub-agents or dispatch, redirect or interrupt other members\./u); - assert.match(mode, /first usable finding, probe result or blocker without waiting for a complete proof/u); - assert.doesNotMatch( - mode, - /Proactively delegate useful complementary work|You are the Lead/u, - 'A cold resume or full-history fork must not inherit Lead authority as its current mode.', - ); - } else { - assert.match(mode, /You are the Lead of an explicitly requested flat team\./u); - assert.match(mode, /Use native delegation for distinct gaps/u); - assert.match(mode, /Follow the pinned Lead charter for scouting, review and formal assignments/u); - assert.match(mode, /Only Lead dispatches or interrupts members/u); - } - const modeChecks = (observations.modeChecks ??= {}); - modeChecks[member ?? 'lead'] = (modeChecks[member ?? 'lead'] ?? 0) + 1; - if (member) { - const id = ['followup', 'interrupt'].includes(member) ? 'expert' : member; - const worker = state.agentTeam!.workers.find(worker => worker.id === id)!; - assert.ok(worker, 'native bootstrap must reserve the host worker before model startup'); - const step = memberSteps.get(member) ?? 0; - memberSteps.set(member, step + 1); - if (member === 'interrupt') { - const history = JSON.stringify(body.input); - observations.busySteerSeen ||= history.includes('FIXTURE_BUSY_FOLLOWUP'); - observations.effectiveFollowupSeen ||= history.includes('FIXTURE_EFFECTIVE_FOLLOWUP'); - if (observations.effectiveFollowupSeen) { - assert.match( - text, - /The ideal class group measures the obstruction to principality/u, - 'The changed specialty must reach the actual busy writer request with its native followup.', - ); - assert.ok( - text.includes( - path.join( - worker.worktree, - '.agents/skills/theoremos-research/references/domain-materials/number-theory.md', - ), - ), - 'Domain reading must be located in the recipient workspace.', - ); - observations.hotProfileSeen = true; - } - } - if (step === 0) { - assert.equal( - text.includes('NATIVE_ROOT_TEST'), - member === 'forked', - 'only a full-history fork inherits the parent turn', - ); - if (member === 'followup') - assert.match(text, /Queue only; stay idle\./u, 'cold resume must receive its saved mailbox'); - } - if (member === 'interrupt' && step === 1) await until(() => observations.waitRequested === true); - if (member === 'interrupt' && step >= 2) { - observations.interruptModelPending = true; - // Native followups finish the current response and tools first. - // Give each steering action that boundary, then hold the final response for interruption. - if (!observations.busySteerSeen || !observations.effectiveFollowupSeen) { - const busy = !observations.busySteerSeen; - await until( - () => - response.destroyed || - (busy ? observations.busyFollowupAccepted === true : worker.tasks.at(-1)!.objectiveRevision === 3), - ); - if (response.destroyed) return; - items = [ - call((busy ? 'busy' : 'followup') + '_boundary_' + step, 'exec_command', { - login: false, - cmd: 'printf continuation-boundary', - }), - ]; - } else { - await new Promise(resolve => response.once('close', resolve)); - return; - } - } else - items = [ - step === 0 - ? call('shell_' + member, 'exec_command', { - login: false, - cmd: - 'test "$PWD" = ' + - quote(worker.worktree) + - ' && test ! -r ' + - quote(path.join(state.worktree, 'lead-private')) + - ' && test ! -r ' + - quote( - path.join(directory, 'team-workspaces', id === 'expert' ? 'forked' : 'expert', '.scratch/own.txt'), - ) + - ' && mkdir -p .scratch && printf fixture > .scratch/own.txt && printf isolation-ok', - }) - : step === 1 - ? nativeCall('peer_' + member, 'send_message', { - target: '/root', - message: 'Native member result ' + member, - }) - : message('Independent member research saved.'), - ]; - } else { - // Resume and full-history forks retain prior tool calls. Advance the scripted - // workflow only after the original tool's actual receipt is in history. - const receipts = new Map( - body.input - .filter((item: any) => item.type === 'function_call_output') - .map((item: any) => [item.call_id, item.output]), - ); - if (!receipts.has('spawn_wrong_effort')) - return sendResponse(response, [ - nativeCall('spawn_wrong_effort', 'spawn_agent', { - task_name: 'expert', - message: 'This assignment should be rejected before a writer opens.', - fork_turns: 'none', - reasoning_effort: 'low', - }), - ]); - assert.match(receipts.get('spawn_wrong_effort')!, /math_team_native_run_config_frozen/u); - if (!receipts.has('spawn_fresh')) { - assert.equal(state.agentTeam!.workers.length, 0, 'Changing the frozen effort must not reserve a worker.'); - assert.equal(processes.size, 1, 'Changing the frozen effort must not open a writer.'); - } - const stages = [ - 'spawn_fresh', - 'queue_idle', - 'followup', - 'spawn_fork', - 'native_list', - 'interrupt_idle', - 'followup_interrupt', - 'native_wait', - 'followup_busy', - 'followup_effective', - 'interrupt_active', - ]; - let step = 0; - while (receipts.has(stages[step])) step++; - rootStep = Math.max(rootStep, step + 1); - if (step === 0) - items = [ - nativeCall('spawn_fresh', 'spawn_agent', { - task_name: 'expert', - message: 'NATIVE_WORKER_TEST Read the fixed skill and inspect this disposable fixture.', - fork_turns: 'none', - }), - ]; - else if (step === 1) { - assert.ok( - state.agentTeam!.workers.some(worker => worker.id === 'expert'), - 'native spawn must create its host worker', - ); - await until(() => !team!.hasActiveWorkers); - assert.equal( - state.agentTeam!.workers.find(worker => worker.id === 'expert')!.tasks.at(-1)!.status, - 'completed', - ); - observations.opensBeforeIdleQueue = processes.size; - items = [ - nativeCall('queue_idle', 'send_message', { target: '/root/expert', message: 'Queue only; stay idle.' }), - ]; - } else if (step === 2) { - observations.opensAfterIdleQueue = processes.size; - assert.equal( - observations.opensBeforeIdleQueue, - observations.opensAfterIdleQueue, - 'queue-only must not start an idle worker', - ); - items = [ - nativeCall('followup', 'followup_task', { - target: '/root/expert', - message: 'NATIVE_FOLLOWUP_TEST Continue the disposable fixture.', - }), - ]; - } else if (step === 3) { - await until(() => !team!.hasActiveWorkers); - assert.equal(state.agentTeam!.workers.find(worker => worker.id === 'expert')!.tasks.length, 2); - assert.equal( - state.agentTeam!.workers.find(worker => worker.id === 'expert')!.tasks.at(-1)!.status, - 'completed', - 'native cold followup must complete', - ); - assert.ok( - processes.size > observations.opensAfterIdleQueue, - 'The cold followup must open a new isolated writer.', - ); - items = [ - nativeCall('spawn_fork', 'spawn_agent', { - task_name: 'forked', - message: 'NATIVE_FORK_TEST Retain the parent history in this disposable fixture.', - fork_turns: 'all', - }), - ]; - } else if (step === 4) { - assert.ok( - state.agentTeam!.workers.some(worker => worker.id === 'forked'), - 'native fork must create its host worker', - ); - items = [nativeCall('native_list', 'list_agents', {})]; - } else if (step === 5) { - await until(() => !team!.hasActiveWorkers); - observations.opensBeforeIdleInterrupt = processes.size; - items = [nativeCall('interrupt_idle', 'interrupt_agent', { target: '/root/expert' })]; - } else if (step === 6) { - assert.equal( - processes.size, - observations.opensBeforeIdleInterrupt, - 'interrupting an unloaded member must not launch it', - ); - items = [ - nativeCall('followup_interrupt', 'followup_task', { - target: '/root/expert', - message: 'NATIVE_INTERRUPT_TEST Inspect this fixture until interrupted.', - }), - ]; - } else if (step === 7) { - observations.waitRequested = true; - items = [nativeCall('native_wait', 'wait_agent', { timeout_ms: 10000 })]; - } else if (step === 8) { - await until(() => observations.interruptModelPending === true); - items = [ - nativeCall('followup_busy', 'followup_task', { - target: '/root/expert', - message: 'FIXTURE_BUSY_FOLLOWUP Adjust this fixture within its current task.', - }), - ]; - } else if (step === 9) { - await until(() => observations.busySteerSeen === true); - const worker = state.agentTeam!.workers.find(worker => worker.id === 'expert')!; - assert.equal(worker.tasks.length, 3, 'busy followup must retain the current task'); - items = [ - nativeCall('followup_effective', 'followup_task', { - target: '/root/expert', - message: - 'Profiles: D012, engineer\nNATIVE_INTERRUPT_TEST FIXTURE_EFFECTIVE_FOLLOWUP Inspect the updated disposable fixture.', - }), - ]; - } else if (step === 10) { - await until(() => observations.effectiveFollowupSeen === true); - items = [nativeCall('interrupt_active', 'interrupt_agent', { target: '/root/expert' })]; - } else { - await until(() => !team!.hasActiveWorkers); - items = [message('Native backend fixture complete.')]; - } - } - sendResponse(response, items); - } catch (error) { - observations.providerFailure ??= String(error); - controller.abort(error); - response.writeHead(500); - response.end('Offline fixture failed.'); - } -}); - -try { - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { - task: 'Disposable native execution integration fixture.', - source: 'theorem native_backend_fixture : True := by sorry\n', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const worktree = path.join(directory, 'lead'); - git(receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - fs.writeFileSync(path.join(worktree, 'lead-private'), 'private fixture canary'); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const skill = prepareResearchSkill(root, worktree, identity, problem); - state = { - schema: 'deepscientist.math.solver.v1', - runId: 'offline-native-backend', - phase: 'prepared', - problem, - worktree, - model: 'deepseek-flash', - effort: 'high', - turns: 0, - taskDigest: mathDigest('fixture'), - buildDigest: 'fixture', - environmentDigest: mathDigest('offline-native-backend'), - evaluatorDigest: 'fixture', - researchMode: 'skill', - researchSkillWorkflow: 'full', - researchSkill: identity, - researchDelegation: { mode: 'team', maxAgents }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }; - const profile = path.join(directory, 'profile'); - prepareSub2apiProfile(profile, state.model, state.effort); - const configFile = path.join(profile, 'config.toml'), - config = parse(fs.readFileSync(configFile, 'utf8')) as any; - config.model_provider = 'offline_native_backend'; - config.model_providers = { - offline_native_backend: { - ...config.model_providers.sub2api, - base_url: `http://127.0.0.1:${(server.address() as any).port}/v1`, - env_key: 'OFFLINE_NATIVE_BACKEND_KEY', - }, - }; - if (largeForkTest) { - // Each user-message notification stays under the stdio frame limit. The - // scripted provider accepts their combined history without auto-compacting. - const window = 8_000_000; - config.model_context_window = window; - config.model_auto_compact_token_limit = window; - const catalogFile = path.resolve(profile, config.model_catalog_json); - const catalog = JSON.parse(fs.readFileSync(catalogFile, 'utf8')); - for (const model of catalog.models) Object.assign(model, { context_window: window, max_context_window: window }); - fs.chmodSync(catalogFile, 0o600); - fs.writeFileSync(catalogFile, JSON.stringify(catalog)); - } - fs.chmodSync(configFile, 0o600); - fs.writeFileSync(configFile, stringify(config)); - const userHome = os.homedir(); - const elanHome = process.env.ELAN_HOME || path.join(userHome, '.elan'); - const toolchain = path.join(elanHome, 'toolchains/leanprover--lean4---v4.36.0'); - const environment = { - HOME: userHome, - PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: elanHome, - LEAN_PATH: '', - LEAN_SYSROOT: '', - NO_PROXY: '127.0.0.1,localhost', - OFFLINE_NATIVE_BACKEND_KEY: 'synthetic-offline-key', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env'), - }; - const save = () => { - for (const current of [ - state.writerProcess, - ...(state.agentTeam?.workers.map(worker => worker.writerProcess) ?? []), - ]) - if (current) processes.set(current.pid + ':' + current.startTime, current); - writeMathJsonDurable(path.join(output, 'state.json'), state); - }; - const open = async (options: MathAgentOptions) => { - const native = options.nativeAgentControl; - const session = await createCodexMathSession({ - ...options, - ...(native - ? { - nativeAgentControl: { - ...native, - connected: async connection => { - const update = connection.update; - Object.defineProperty(connection, 'update', { - value: async (params: Record) => { - try { - const result = await update(params); - events.push({ event: 'native_mailbox_update', params, result }); - return result; - } catch (error) { - events.push({ - event: 'native_mailbox_update_failed', - params, - error: error instanceof Error ? { message: error.message, cause: error.cause } : String(error), - }); - throw error; - } - }, - }); - await native.connected?.(connection); - }, - request: async (request, connection, context) => { - try { - const result = await native.request(request, connection, context); - const input = request.payload.input as any; - if (request.operation === 'send' && input?.message?.text?.includes('FIXTURE_BUSY_FOLLOWUP')) - observations.busyFollowupAccepted = true; - events.push({ - event: 'native_host_callback', - operation: request.operation, - threadId: request.threadId, - payload: request.payload, - result, - }); - return result; - } catch (error) { - events.push({ - event: 'native_host_callback_failed', - operation: request.operation, - threadId: request.threadId, - payload: request.payload, - error: error instanceof Error ? { message: error.message, stack: error.stack } : String(error), - }); - throw error; - } - }, - }, - } - : {}), - }).catch(error => { - events.push({ - event: 'native_writer_open_failed', - workspace: options.workspace, - error: error instanceof Error ? { message: error.message, cause: error.cause } : String(error), - }); - throw error; - }); - if (session.processIdentity) - processes.set(session.processIdentity.pid + ':' + session.processIdentity.startTime, session.processIdentity); - return session; - }; - team = new AgentResearchTeam({ - state, - root, - taskText: 'Disposable integration fixture.', - leadAccess: { - environment, - researchSkill: skill, - retrievalRoot: path.join(worktree, problem.projectRelative), - }, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, - executable, - profile, - signal: controller.signal, - maxAgents, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save, - emit: (event, details) => { - events.push({ event, ...details }); - }, - exclusiveCheck: async operation => operation(), - }); - lead = await open({ - executable, - profile, - workspace: worktree, - proofProjectRoot: path.join(worktree, problem.projectRelative), - model: state.model, - effort: state.effort, - environment, - skills: [skill], - tools: team.tools(), - nativeAgentControl: team.nativeAgentControlOptions(), - isolateProcess: true, - hiddenRoots: team.hiddenRoots, - instructions: agentTeamInstructions({ id: 'lead', role: 'lead' }, maxAgents), - signal: controller.signal, - onUsage: () => {}, - }); - team.setLeadSession(lead); - state.writerProcess = lead.processIdentity; - save(); - if (largeForkTest) - for (const index of [1, 2, 3, 4]) { - const text = `LARGE_FORK_HISTORY ${index} ` + '界'.repeat(800_000); - assert.equal(await lead.run(text, 'history-' + index, worktree, () => {}), 'completed'); - } - observations.rootStatus = await lead.run( - largeForkTest ? 'LARGE_FORK_ACTION' : 'NATIVE_ROOT_TEST Execute the scripted disposable backend fixture.', - 'root-task', - worktree, - () => {}, - ); - assert.equal(observations.rootStatus, 'completed'); - if (capacityTest) { - assert.ok(observations.capacity, 'must reach the full team and observe the failed overflow spawn'); - assert.ok(state.agentTeam!.workers.every(w => w.tasks.at(-1)?.status === 'completed')); - observations.loopbackRequests = requests.length; - } else if (largeForkTest) { - assert.equal(observations.largeFork?.workerStatus, 'completed'); - assert.equal(state.agentTeam!.workers.length, 1, 'The oversized fork must not reserve a worker.'); - assert.equal( - events.filter(event => event.event === 'native_host_callback' && event.operation === 'spawn').length, - 1, - ); - } else checkLifecycle(worktree, problem.projectRelative); - await team.close(); - await lead.close(); - team = undefined; - lead = undefined; - if (!capacityTest && !largeForkTest) - observations.proofDelivery = await verifyNativeProofDelivery({ - repository: root, - executable, - output: path.join(output, 'proof-delivery'), - signal: controller.signal, - webProvider: process.argv.includes('--web-provider'), - }); - observations.status = 'passed'; -} catch (error) { - observations.status = 'failed'; - observations.error = error instanceof Error ? { message: error.message, stack: error.stack } : String(error); - process.exitCode = 1; -} finally { - clearTimeout(deadline); - controller.abort(); - await team?.close(); - await lead?.close(); - observations.processes = [...processes.values()].map(identity => ({ - ...identity, - stop: confirmHarnessProcessStopped(identity), - })); - if (observations.processes.some((process: any) => process.stop.status !== 'stopped')) { - observations.status = 'failed'; - process.exitCode = 1; - } - writeMathJsonDurable(path.join(output, 'verification.json'), observations); - writeMathJsonDurable(path.join(output, 'trace.json'), { requests, events }); - server.closeAllConnections(); - await new Promise(resolve => server.close(() => resolve())); - fs.rmSync(directory, { recursive: true, force: true }); -} -console.log(JSON.stringify(observations, null, 2)); - -function checkLifecycle(worktree: string, projectRelative: string) { - assert.equal(rootStep, 12); - assert.deepEqual(state.agentTeam!.workers.map(worker => worker.native!.agentPath).sort(), [ - '/root/expert', - '/root/forked', - ]); - const expert = state.agentTeam!.workers.find(worker => worker.id === 'expert')!; - assert.equal(expert.native!.spawnHistory, 'fresh'); - assert.equal(state.agentTeam!.workers.find(worker => worker.id === 'forked')!.native!.spawnHistory, 'parent-history'); - assert.equal(expert.tasks.length, 3); - assert.equal(expert.tasks.at(-1)!.status, 'interrupted'); - assert.equal(expert.tasks.at(-1)!.objectiveRevision, 3); - assert.deepEqual(expert.tasks.at(-1)!.profileEvidence?.loaded, ['D012', 'engineer']); - assert.equal(observations.hotProfileSeen, true); - for (const role of ['lead', 'expert', 'followup', 'forked', 'interrupt']) - assert.ok(observations.modeChecks[role] > 0, 'Actual provider requests must validate the current mode for ' + role); - assert.match( - state.agentTeam!.nativeControl!.rootRuntimeConfiguration!.overrides.multiAgentModeHintText!, - /You are the Lead/u, - ); - for (const worker of state.agentTeam!.workers) - assert.match(worker.native!.runtimeConfiguration!.overrides.multiAgentModeHintText!, /You are a member/u); - assert.ok(expert.tasks.at(-1)!.sourceCommit, 'interruption must preserve the stopped writer draft'); - assert.equal(state.agentTeam!.deliveries.length, 0, 'native completed replies must not become Lean deliveries'); - assert.match(fs.readFileSync(path.join(worktree, projectRelative, 'Submission.lean'), 'utf8'), /sorry/u); - const outputs = requests.flatMap(body => body.input ?? []).filter(item => item.type === 'function_call_output'); - // Native forks mark the parent's unfinished tool as aborted in copied history. - // Retain the original producer's receipt before later inherited copies. - observations.toolOutputs = {}; - for (const item of outputs) observations.toolOutputs[item.call_id] ??= item.output; - for (const member of ['expert', 'followup', 'forked', 'interrupt']) - assert.match(String(observations.toolOutputs['shell_' + member]), /isolation-ok/u); - assert.equal(JSON.parse(observations.toolOutputs.native_wait).timed_out, false); - assert.equal(JSON.parse(observations.toolOutputs.interrupt_idle).previous_status, 'not_found'); - assert.equal(JSON.parse(observations.toolOutputs.interrupt_active).previous_status, 'running'); - observations.nativePaths = state.agentTeam!.workers.map(worker => worker.native!.agentPath); - observations.taskCounts = state.agentTeam!.workers.map(worker => ({ id: worker.id, count: worker.tasks.length })); - observations.loopbackRequests = requests.length; - observations.relayAdmission = { - acceptedRequests: requests.length, - namespaceRequests: requests.filter(body => body.tools?.some((tool: any) => tool.type === 'namespace')).length, - agentMessageRequests: requests.filter(body => body.input?.some((item: any) => item.type === 'agent_message')) - .length, - }; - assert.ok( - observations.relayAdmission.namespaceRequests > 0, - 'native namespaces must pass production relay admission', - ); - assert.ok( - observations.relayAdmission.agentMessageRequests > 0, - 'native child messages must pass production relay admission', - ); -} diff --git a/src/math/nativeProcess.ts b/src/math/nativeProcess.ts index a5bfec9e..42d620f5 100644 --- a/src/math/nativeProcess.ts +++ b/src/math/nativeProcess.ts @@ -11,7 +11,6 @@ import type { NativeBudgetObservation, TokenBudget } from '../solver/usageBudget import type { NativeTeamBudgetInput, AgentTeamBudgetProjection } from '../solver/agentTeamBudget'; import type { RunValues, Strategy } from '../solver/runOptions'; -import type { TeamMemberInputs, TeamMemberStep } from '../solver/teamMemberSchedule'; import type { ResearchObservation, ResearchStep } from '../solver/researchLoop'; import type { FinalEvaluationPolicy } from '../solver/evaluation'; @@ -357,14 +356,7 @@ type NativeProcess = Readonly<{ handoff(thread: string, indices: number[]): number; confirm(thread: string, sequence: number, ack: unknown, connected: boolean, indices: number[]): void; }; - teamSessionBinding(event: Record): unknown; prepareWorkerProject(worktree: string, problem: SolverProblem): string; - teamTurnCallback(params: Record): string | null; - TeamTurnHandoff: new () => { - acknowledge(operation: string, reply: Record): void; - ready(interrupted: boolean): boolean; - }; - nextTeamMember(input: TeamMemberInputs): TeamMemberStep; saveTeamResearchCheckpoint(input: { directory: string; worktree: string; @@ -377,12 +369,6 @@ type NativeProcess = Readonly<{ summary: string; status: import('../solver/agentTeamResearch').AgentTeamResearchArtifactStatus; }): import('../solver/agentTeamResearch').AgentTeamResearchArtifactReference; - teamWorkspace( - request: - | { action: 'import'; source: string; target: string; commit: string } - | { action: 'archive'; directory: string; source: string; commits: readonly string[] } - | { action: 'prepare'; sourceWorktree: string; worktree: string; seedCommit: string; migrationDirectory: string }, - ): void; nextResearchStep(event: ResearchObservation): ResearchStep; projectMathEnvironment(source: NodeJS.ProcessEnv): Record; resolveMathEnvironment(source: NodeJS.ProcessEnv, file: string, homes: string[]): NodeJS.ProcessEnv; @@ -837,18 +823,10 @@ type NativeProcess = Readonly<{ metadataOnly: boolean, settings: Record, tools?: readonly unknown[], - bootstrap?: Record, ): { method: string; params: Record; }; - codexMemberInput( - envelope: Record, - threadId: string, - message: string, - first: boolean, - skills: readonly { name: string; path: string; loading: string }[], - ): Record; codexTurnDispatch(spec: unknown): Record; codexBindThread(spec: unknown, result: Record): string; CodexChild: new ( diff --git a/src/math/verifier.ts b/src/math/verifier.ts index ea9e1396..5e537195 100644 --- a/src/math/verifier.ts +++ b/src/math/verifier.ts @@ -132,8 +132,6 @@ export type MathematicsVerifierExecutionOptions = { dependencyCandidates?: readonly string[]; /** Export actual references to declarations in project-local modules, separately for type and proof. */ collectDeclarationReferences?: boolean; - /** For team attribution, distinguish immediate constants in the final elaborated term from the closure. */ - collectDirectProofReferences?: boolean; }; export type MathematicsVerifierResult = { @@ -152,6 +150,7 @@ export type MathematicsVerifierResult = { sourceDeclarationHash?: string; usedDeclarationDependencies?: string[]; declarationReferences?: LeanDeclarationReferences; + /** Immediate references emitted by the historical team evaluator. */ directProofReferences?: LeanDeclarationReferences['proof']; statementBinding: 'caller-bound-to-committed-declaration'; toolchain: MathematicsVerificationToolchain; @@ -259,7 +258,6 @@ type PreparedFile = { axiomDependencies: Map; usedDeclarationDependencies?: Map; declarationReferences?: Map; - directProofReferences?: Map; proofHash: string; inspection: Pick; declarationInspections?: Map; @@ -2122,7 +2120,6 @@ type LeanDeclarationQuery = Readonly<{ axioms?: Map; usedDependencies?: Map; references?: Map; - direct?: Map; error?: string; }; }>; @@ -2138,7 +2135,6 @@ const prepareLeanDeclarationQuery = async ( forbiddenImportModules?: readonly string[]; dependencyCandidates?: readonly string[]; referenceModules?: readonly { module: string; file: string }[]; - directProof?: boolean; }>, privateMarkers = false, ): Promise => { @@ -2286,20 +2282,6 @@ const prepareLeanDeclarationQuery = async ( ), ) : []), - ...(options.directProof && options.referenceModules - ? theoremNames.flatMap(name => [ - 'run_cmd do', - ' let env <- Lean.getEnv', - ` let modules : List (String × String) := [${options.referenceModules!.map(item => `(${JSON.stringify(item.module)}, ${JSON.stringify(item.file)})`).join(', ')}]`, - ` let root <- Lean.getConstInfo (${JSON.stringify(leanNameWithoutRoot(name))}.toName)`, - ' let some proof := root.value? (allowOpaque := true) | return', - ' let refs := (Lean.Expr.getUsedConstants proof).toList.filterMap fun n => Id.run do', - ' let m := match env.getModuleIdxFor? n with | some i => env.header.moduleNames[i.toNat]!.toString | none => ""', - ' return (modules.find? (fun e => e.1 == m)).map fun e => (n.toString, e.2)', - ' let report := (Lean.toJson (([] : List (String × String)), refs)).compress', - ` Lean.logInfo m!"${referenceMarkers.get(name)!.replace('DS_DECL_REFERENCES_', 'DS_DIRECT_REFERENCES_')}{if report.utf8ByteSize <= 8000 then report else "null"}"`, - ]) - : []), ].join('\n') : file.source; await fs.promises.writeFile(queryAbsolutePath, `${externalChecks}\n${queries}\n`, 'utf8'); @@ -2312,7 +2294,6 @@ const prepareLeanDeclarationQuery = async ( if (nativeProcess) { const parsed = nativeProcess.leanDeclarationExports(stdout, queriesWithMarkers, { files: options?.referenceModules?.map(module => module.file), - directProof: options?.directProof, dependencyCandidates, }); if ('error' in parsed) return parsed; @@ -2322,7 +2303,6 @@ const prepareLeanDeclarationQuery = async ( axioms: new Map(Object.entries(parsed.axioms)), usedDependencies: new Map(Object.entries(parsed.usedDependencies)), references: new Map(Object.entries(parsed.references)), - direct: new Map(Object.entries(parsed.direct)), }; } const hashes = new Map(); @@ -2330,7 +2310,6 @@ const prepareLeanDeclarationQuery = async ( const axioms = new Map(); const usedDependencies = new Map(); const references = new Map(); - const direct = new Map(); if (options?.referenceModules) for (const [name, marker] of referenceMarkers) { const report = parseLeanReferences( @@ -2339,19 +2318,6 @@ const prepareLeanDeclarationQuery = async ( options.referenceModules.map(module => module.file), ); if (report) references.set(name, report); - if (options.directProof) { - const immediate = parseLeanReferences( - stdout, - marker.replace('DS_DECL_REFERENCES_', 'DS_DIRECT_REFERENCES_'), - options.referenceModules.map(module => module.file), - ); - if ( - immediate && - report && - immediate.proof.every(item => report.proof.some(ref => ref.file === item.file && ref.name === item.name)) - ) - direct.set(name, immediate.proof); - } } if (dependencyCandidates) { for (const [theoremName, dependencyMarker] of dependencyMarkers) { @@ -2409,7 +2375,7 @@ const prepareLeanDeclarationQuery = async ( axioms.set(query.name, dependencies); if (query.localName) axioms.set(query.localName, dependencies); } - return { hashes, types, axioms, usedDependencies, references, direct }; + return { hashes, types, axioms, usedDependencies, references }; }, }; }; @@ -2829,7 +2795,6 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat referenceModules: options.collectDeclarationReferences ? (localModules ?? [{ module: '', file: file.relativeProofPath }]) : undefined, - directProof: options.collectDirectProofReferences, } : undefined, options.checkDeclarationsInDraft || options.continuationDeclarations, @@ -2942,7 +2907,6 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat if (declarationExport?.axioms) file.axiomDependencies = declarationExport.axioms; if (declarationExport?.usedDependencies) file.usedDeclarationDependencies = declarationExport.usedDependencies; if (declarationExport?.references) file.declarationReferences = declarationExport.references; - if (declarationExport?.direct) file.directProofReferences = declarationExport.direct; const axiomDependenciesFor = (item: PreparedItem): string[] => (item.theoremName && declarationNamed(file.axiomDependencies, item.theoremName)) || file.inspection.axioms; @@ -3117,9 +3081,6 @@ async function checkManyFormalVerificationsUnbounded( ...(file.declarationReferences?.has(theoremName) ? { declarationReferences: file.declarationReferences.get(theoremName) } : {}), - ...(file.directProofReferences?.has(theoremName) - ? { directProofReferences: file.directProofReferences.get(theoremName) } - : {}), } : {}), statementBinding: 'caller-bound-to-committed-declaration', @@ -3672,7 +3633,6 @@ async function buildFormalVerificationCacheKey( forbiddenImportModules: options.forbiddenImportModules ?? [], dependencyCandidates: options.dependencyCandidates ?? null, collectDeclarationReferences: options.collectDeclarationReferences ?? false, - ...(options.collectDirectProofReferences ? { collectDirectProofReferences: true } : {}), verifierExecutable, environment, toolchainFiles, diff --git a/src/runtime/agentSession.ts b/src/runtime/agentSession.ts index d753664e..ffebf7f7 100644 --- a/src/runtime/agentSession.ts +++ b/src/runtime/agentSession.ts @@ -8,8 +8,6 @@ import type { MathAgentTools } from './agentTeamTools'; export type { MathAgentTools, MathAgentToolDefinition, MathAgentToolContext } from './agentTeamTools'; import type { HarnessProcessIdentity } from './harnessProcess'; import type { LeanEnvironmentHealth } from '../math/leanEnvironmentHealth'; -import type { NativeAgentControlOptions, NativeAgentControlConnection } from './nativeAgentControl'; -export type { NativeAgentControlOptions, NativeAgentControlConnection } from './nativeAgentControl'; type Json = Record; @@ -39,10 +37,10 @@ export type MathAgentOptions = { instructions: string; /** The host supplies the workspace and tool guidance for a solo proof writer. */ soloProofWorkspace?: boolean; + /** Stock Codex manages Lead and its children in one isolated proof workspace. */ + sharedProofTeam?: { capacity: number; requireMetering: boolean }; skills?: readonly MathAgentSkill[]; tools?: MathAgentTools; - /** Host backend for Codex's built-in collaboration tools, with isolated native children. */ - nativeAgentControl?: NativeAgentControlOptions; /** Tie the complete native writer tree to this host with a dedicated PID namespace. */ isolateProcess?: boolean; /** Native planning can read the proof workspace and write only to its scratch directory. */ @@ -99,9 +97,6 @@ export type MathAgentSession = { readonly advisoryNotifications?: 'native-history'; readonly isolationReceipt?: Record; readonly processIdentity?: HarnessProcessIdentity; - readonly nativeAgentControl?: NativeAgentControlConnection; - /** Safe startup overrides acknowledged by thread creation, not an effective-config readback. */ - readonly nativeConfiguration?: MathNativeConfiguration; /** Selected execution contracts, not a claim of mathematical acceptance or complete usage. */ readonly executionPlan?: MathAgentSessionPlan; run: (message: string, messageId: string, workspace: string, onStarted: (turnId: string) => void) => Promise; @@ -116,17 +111,6 @@ export type MathAgentSession = { >; }; -export type MathNativeConfiguration = Readonly<{ - source: 'thread-start-overrides'; - overrides: Readonly<{ - includeSkillInstructions: false; - deferMailboxPreemption?: true; - rootAgentUsageHintText?: ''; - subagentUsageHintText?: ''; - multiAgentModeHintText?: string; - }>; -}>; - export type MathAgentHarnessId = 'codex' | 'claude-code' | 'opencode' | 'cli'; /** Only contracts consumed by current workflows belong here. Native accounting and diff --git a/src/runtime/agentSessionPlan.ts b/src/runtime/agentSessionPlan.ts index 25224045..bb010c2a 100644 --- a/src/runtime/agentSessionPlan.ts +++ b/src/runtime/agentSessionPlan.ts @@ -1,6 +1,8 @@ import type { MathAgentOptions, MathAgentSessionPlan } from './agentSession'; -type Request = Pick; +type Request = Pick & { + completedOutput?: MathAgentOptions['completedOutput'] | boolean; +}; export function planMathAgentSession(request: Request): MathAgentSessionPlan { if (request.readIsolation && request.skills?.length) throw new Error('math_codex_skill_read_isolation_unsupported'); diff --git a/src/runtime/codexOutputWatch.ts b/src/runtime/codexOutputWatch.ts new file mode 100644 index 00000000..dc3f5c51 --- /dev/null +++ b/src/runtime/codexOutputWatch.ts @@ -0,0 +1,122 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { mathDigest, readMathText } from '../math/mathRuntimeIo'; +import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; +import type { MathAgentOptions, MathAgentSession } from './agentSession'; +import type { CodexMessage, CodexRpc } from './codexRpc'; + +const maxOutputBytes = 2_000_000; + +/** Watches each turn's output. Invalid bytes receive repair feedback at most once per session. */ +export function createCodexOutputWatch(input: { + output: NonNullable; + workspace: string; + isolatedWorkspace?: string; + signal?: AbortSignal; + usesRequestReceipts: boolean; + request: CodexRpc['request']; + notify: NonNullable; + phase(): 'running' | 'stopping' | 'settled'; +}) { + const { output, workspace, isolatedWorkspace, signal, usesRequestReceipts, request, notify, phase } = input; + const reportedInvalidOutputs = new Set(); + return async function watchTurn(checkpointed: () => boolean, reject: (error: Error) => void) { + const file = path.resolve(output.file); + const parent = path.dirname(file); + if (isolatedWorkspace && !isMathPathWithin(workspace, file)) + throw new Error('math_codex_output_watch_outside_workspace'); + assertMathCanonicalPath(parent); + fs.mkdirSync(parent, { recursive: true }); + assertMathCanonicalPath(parent); + const nativeFile = isolatedWorkspace ? path.join(isolatedWorkspace, path.relative(workspace, file)) : file; + const watchId = randomUUID(); + // Watch the parent before starting the writer. Atomic writes replace the file's inode. + const watched = await request('fs/watch', { watchId, path: path.dirname(nativeFile) }); + if (typeof watched.path !== 'string' || !path.isAbsolute(watched.path)) + throw new Error('math_codex_output_watch_path_missing'); + const watchedFile = path.join(watched.path, path.basename(nativeFile)); + + let reviewedDigest: string | undefined; + if (output.reviewIncomplete) { + try { + reviewedDigest = mathDigest(readMathText(file, maxOutputBytes)); + } catch { + // A prior diagnostic is optional. Only review new output from this turn. + } + } + let turn: { id: string; stopAfterRequests(): void } | undefined; + let submittedDigest: string | undefined; + let feedbackPending = false; + return { + close: () => request('fs/unwatch', { watchId }), + matches: (params: CodexMessage) => + params.watchId === watchId && Array.isArray(params.changedPaths) && params.changedPaths.includes(watchedFile), + bind: (id: string, stopAfterRequests: () => void) => { + turn = { id, stopAfterRequests }; + }, + get submitted() { + return submittedDigest !== undefined; + }, + check(mode: 'accept' | 'review' | 'watch' | 'settled' = 'accept') { + if (!turn || signal?.aborted) return; + const settled = mode === 'settled'; + if (!settled && (submittedDigest || checkpointed())) return; + const { id, stopAfterRequests } = turn; + let text: string, value: unknown; + try { + text = readMathText(output.file, maxOutputBytes); + // Once accepted, compare bytes after settlement without invoking the validator again. + if (submittedDigest) { + if (mathDigest(text) !== submittedDigest) submittedDigest = undefined; + return; + } + value = JSON.parse(text); + } catch { + if (settled) submittedDigest = undefined; + return; // Missing, partial or unsafe files are not submissions. + } + try { + output.validate(value); + } catch (error) { + if (phase() !== 'running' || (mode !== 'watch' && mode !== 'review')) return; + const digest = mathDigest(text); + if (output.reviewIncomplete && digest !== reviewedDigest) { + reviewedDigest = digest; + const message = output.reviewIncomplete(value, id); + if (message) + void notify(message, usesRequestReceipts ? { waitForRequest: true } : { mode: 'advisory' }).catch( + () => {}, + ); + } + if ( + mode !== 'watch' || + !output.validationFeedback || + phase() !== 'running' || + feedbackPending || + reportedInvalidOutputs.has(digest) + ) + return; + reportedInvalidOutputs.add(digest); + let message: string; + try { + message = output.validationFeedback(error, { text, turnId: id }); + } catch (cause) { + reject(cause instanceof Error ? cause : new Error('math_codex_validation_feedback_failed')); + return; + } + feedbackPending = true; + void notify(message) + .catch(() => {}) + .finally(() => { + feedbackPending = false; + }); + return; + } + submittedDigest = mathDigest(text); + // Keep the receipt of an admitted model request before interrupting the writer. + if (phase() !== 'settled') stopAfterRequests(); + }, + }; + }; +} diff --git a/src/runtime/codexRpc.ts b/src/runtime/codexRpc.ts new file mode 100644 index 00000000..4e6c8da6 --- /dev/null +++ b/src/runtime/codexRpc.ts @@ -0,0 +1,338 @@ +import { spawn, type ChildProcessByStdio } from 'node:child_process'; +import type { Readable, Writable } from 'node:stream'; +import { getSystemErrorName } from 'node:util'; +import { constants as osConstants } from 'node:os'; +import { nativeProcess } from '../math/nativeProcess'; +import { + closeMathProcess, + confirmMathProcessStopped, + trackMathProcessSession, + watchMathProcessNamespace, + type MathProcessStopReceipt, +} from '../math/mathProcess'; +import type { HarnessProcessIdentity } from './harnessProcess'; + +export type CodexMessage = Record; +export const codexObject = (value: unknown): CodexMessage => { + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('math_codex_invalid_message'); + return value as CodexMessage; +}; + +/** One persistent Codex app-server; all protocol traffic stays on stdio. */ +export class CodexRpc { + private child?: ChildProcessByStdio; + private nativeChild?: InstanceType['CodexChild']>; + private readonly nativeInput?: InstanceType['CodexStdin']>; + private readonly requests = nativeProcess && new nativeProcess.CodexRequests(); + private nextId = 0; + private pending = new Map< + number, + { method?: string; resolve: (result: CodexMessage) => void; reject: (error: Error) => void; timer: NodeJS.Timeout } + >(); + private readonly outputDrained: Promise; + private nativeOutput?: InstanceType['CodexStdout']>; + private failure?: Error; + private closing?: Promise; + readonly processIdentity: Promise; + onNotification: (method: string, params: CodexMessage) => void = () => {}; + onRequest: (method: string, params: CodexMessage) => Promise = async () => undefined; + onFailure: (error: Error) => void = () => {}; + + constructor( + executable: string, + profile: string, + environment: NodeJS.ProcessEnv = process.env, + launch?: { command: string; args: string[]; inheritedFds?: readonly number[]; infoDescriptor?: number }, + ) { + const extras: ('pipe' | number)[] = [...(launch?.inheritedFds ?? [])]; + if (launch?.infoDescriptor !== undefined) { + if (launch.infoDescriptor !== extras.length + 3) throw new Error('math_harness_info_descriptor_invalid'); + extras.push('pipe'); + } + const fail = (reason: string) => this.fail(new Error(`math_codex_transport_closed:${reason}`)); + const errorCode = (error: NodeJS.ErrnoException) => + /^[A-Z0-9_]{1,32}$/u.test(error.code ?? '') ? error.code : 'unknown'; + const receive = (line: Buffer) => { + try { + const message = codexObject(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(line))); + if (message.method !== undefined && typeof message.method !== 'string') throw new Error(); + if (message.method && message.id !== undefined) { + // Only explicitly registered host tools are handled. Permission requests + // and all other interactive calls still receive no grant. + void Promise.resolve() + .then(() => this.onRequest(message.method as string, codexObject(message.params ?? {}))) + .then( + result => + this.write( + result === undefined + ? { + id: message.id, + error: { + code: -32601, + message: 'Interactive requests are unavailable in headless mathematics', + }, + } + : { id: message.id, result }, + ), + () => + this.write({ + id: message.id, + error: { code: -32603, message: 'Headless tool request failed' }, + }), + ) + .catch(() => {}); + } else if (message.method) { + this.onNotification(message.method as string, codexObject(message.params ?? {})); + } else { + if (typeof message.id !== 'number') return; + const call = this.pending.get(message.id); + if (!call) return; + const error = message.error ? codexObject(message.error) : undefined; + const result = error ? undefined : codexObject(message.result ?? {}); + // A malformed reply above must fail this call along with the rest of the transport. + const method = this.requests ? this.requests.take(message.id) : call.method; + if (method == null) throw new Error('math_codex_untracked_request'); + this.pending.delete(message.id); + clearTimeout(call.timer); + const code = + typeof error?.code === 'number' && Number.isSafeInteger(error.code) ? error.code : 'invalid_code'; + const startup = method === 'thread/start' || method === 'initialize'; + 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}:${method}`)); + else call.resolve(result!); + } + } catch { + fail('invalid_frame'); + } + }; + let parts: Buffer[] = [], + bytes = 0; + const onData = (chunk: Buffer) => { + if (this.failure) return; + let start = 0; + while (start < chunk.length) { + const newline = chunk.indexOf(10, start), + end = newline < 0 ? chunk.length : newline; + bytes += end - start; + if (bytes > 8 * 1024 * 1024) { + parts = []; + fail('frame_too_large'); + return; + } + parts.push(chunk.subarray(start, end)); + if (newline < 0) break; + const line = Buffer.concat(parts, bytes); + parts = []; + bytes = 0; + receive(line); + if (this.failure) return; + start = newline + 1; + } + }; + let nativeIdentity: Promise | undefined; + let finishOutput = () => {}; + this.outputDrained = nativeProcess + ? new Promise(resolve => { + finishOutput = resolve; + }) + : Promise.resolve(); + try { + this.nativeOutput = + nativeProcess && + new nativeProcess.CodexStdout((frames, eof, tooLarge, errno) => { + if (!this.child && !this.nativeChild) return; + for (const frame of frames) { + if (this.failure) break; + receive(frame); + } + if (!eof) return; + finishOutput(); + if (tooLarge) fail('frame_too_large'); + else if (errno) fail('stdout_error:code=' + getSystemErrorName(-errno)); + else void this.close(); + }); + this.nativeInput = + nativeProcess && + new nativeProcess.CodexStdin(errno => { + if (!this.closing) + this.fail(new Error('math_codex_transport_closed:stdin_error:code=' + getSystemErrorName(-errno))); + }); + const childEnvironment = { ...environment, CODEX_HOME: profile }; + if (nativeProcess && this.nativeInput && this.nativeOutput) { + try { + let onIdentity: ((result: { identity?: HarnessProcessIdentity; error?: string }) => void) | undefined; + if (launch?.infoDescriptor !== undefined) { + nativeIdentity = new Promise((resolve, reject) => { + onIdentity = result => + result.identity + ? resolve(result.identity) + : reject(new Error(result.error ?? 'math_harness_process_identity_unavailable')); + }); + void nativeIdentity.catch(() => {}); + } + this.nativeChild = new nativeProcess.CodexChild( + launch?.command ?? executable, + childEnvironment, + this.nativeInput, + this.nativeOutput, + (code, signal) => { + const signame = + signal && + Object.keys(osConstants.signals).find( + s => osConstants.signals[s as keyof typeof osConstants.signals] === signal, + ); + void this.close(); + void this.outputDrained.then(() => + fail(`process_exit:code=${code ?? 'none'}:signal=${signame ?? 'none'}`), + ); + }, + launch && { + args: launch.args, + descriptors: launch.inheritedFds ?? [], + infoDescriptor: launch.infoDescriptor, + }, + onIdentity, + ); + } catch (cause) { + const errno = /^math_codex_spawn_errno:(\d+)$/u.exec((cause as Error).message); + if (errno) + throw new Error('math_codex_transport_closed:spawn_error:code=' + getSystemErrorName(-Number(errno[1]))); + throw cause; + } + } else { + this.child = spawn(launch?.command ?? executable, launch?.args ?? ['app-server', '--listen', 'stdio://'], { + env: childEnvironment, + stdio: [this.nativeInput?.childFd() ?? 'pipe', this.nativeOutput?.childFd() ?? 'pipe', 'pipe', ...extras], + detached: process.platform !== 'win32', + }) as ChildProcessByStdio; + } + } catch (error) { + this.nativeInput?.close(); + finishOutput(); + this.nativeOutput?.close(); + throw error; + } finally { + this.nativeInput?.spawned(); + this.nativeOutput?.spawned(); + } + if (!this.child) { + this.processIdentity = nativeIdentity ?? Promise.resolve(undefined); + return; + } + trackMathProcessSession(this.child); + const infoDescriptor = launch?.infoDescriptor; + this.processIdentity = + infoDescriptor === undefined ? Promise.resolve(undefined) : watchMathProcessNamespace(this.child, infoDescriptor); + void this.processIdentity.catch(() => {}); + // Do not forward provider diagnostics, which can contain credentials or task text. + this.child.stderr.resume(); + this.child.once('error', error => fail(`spawn_error:code=${errorCode(error)}`)); + // Descendants may retain the pipes after their parent exits. Reap the owned group, + // while still draining its buffered usage/completion frames before the close event. + this.child.once('exit', () => { + void this.close(); + }); + this.child.once('close', (code, signal) => { + void this.outputDrained.then(() => fail(`process_exit:code=${code ?? 'none'}:signal=${signal ?? 'none'}`)); + }); + this.child.stdin?.on('error', error => fail(`stdin_error:code=${errorCode(error)}`)); + // EOF ends the response transport even if its process is still alive. Let close + // report the actual exit code after draining all frames, rather than racing it. + this.child.stdout?.once('end', () => { + void this.close(); + }); + this.child.stdout?.on('data', onData); + } + + private fail(error: Error): void { + if (this.failure) return; + this.failure = error; + const ids = this.requests ? this.requests.fail() : this.pending.keys(); + for (const id of ids) { + const call = this.pending.get(id)!; + clearTimeout(call.timer); + call.reject(error); + } + this.pending.clear(); + this.onFailure(error); + // A lost reply leaves the remote turn's state unknown; no writer may outlive this transport. + void this.close(); + } + + private write(message: CodexMessage): void { + if (this.failure) throw this.failure; + const json = JSON.stringify(message); + if (this.nativeInput) this.nativeInput.write(json); + else this.child!.stdin!.write(json + '\n'); + } + + request(method: string, params: CodexMessage): Promise { + if (this.failure) return Promise.reject(this.failure); + // Continue draining buffered replies and usage, but never dispatch work to a closing writer. + const id = this.requests ? this.requests.open(method) : this.closing ? null : ++this.nextId; + if (id == null) return Promise.reject(new Error('math_codex_transport_closed:closing')); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + if (this.requests && !this.requests.has(id)) return; + this.fail(new Error(`math_codex_rpc_timeout:${method}`)); + }, 120_000); + this.pending.set(id, { method: this.requests ? undefined : method, resolve, reject, timer }); + try { + this.write({ id, method, params }); + } catch (error) { + clearTimeout(timer); + this.requests?.take(id); + this.pending.delete(id); + reject(error); + } + }); + } + + async initialize(experimental = false): Promise { + await this.request( + 'initialize', + nativeProcess?.codexInitialize(experimental) ?? { + clientInfo: { name: 'deepscientist-math', version: '0.1.0' }, + capabilities: experimental ? { experimentalApi: true } : null, + }, + ); + this.write({ method: 'initialized' }); + } + + close(): Promise { + this.requests?.close(); + if (!this.closing) { + this.closing = (this.nativeChild?.stop() ?? closeMathProcess(this.child!)).then(async () => { + // A TERM handler may deliver the last usage and completion before it closes its stdio. + this.nativeInput?.close(); + const fallback = this.nativeOutput && setTimeout(() => this.nativeOutput?.close(), 3000); + try { + await this.outputDrained; + } finally { + clearTimeout(fallback); + this.nativeOutput?.close(); + } + }); + } + return this.closing; + } + async confirmStopped(): Promise { + const receipt = await (this.nativeChild?.confirm() ?? confirmMathProcessStopped(this.child!)); + if (receipt.status !== 'stopped') return receipt; + try { + // An isolated writer must have reported its identity even on a clean launcher exit. + await this.processIdentity; + return receipt; + } catch { + return { status: 'unconfirmed', reason: 'process-identity-unavailable' }; + } + } +} diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 719be852..3b7641fa 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -1,46 +1,25 @@ -import { spawn, type ChildProcessByStdio } from 'node:child_process'; -import type { Readable, Writable } from 'node:stream'; -import { getSystemErrorName } from 'node:util'; -import { constants as osConstants } from 'node:os'; import { nativeProcess } from '../math/nativeProcess'; import { createTurnEvidence } from './codexTurnEvidence'; -import { - closeMathProcess, - confirmMathProcessStopped, - trackMathProcessSession, - watchMathProcessNamespace, - type MathProcessStopReceipt, -} from '../math/mathProcess'; +import { CodexRpc, codexObject as object, type CodexMessage as Json } from './codexRpc'; import fs from 'node:fs'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; import { parse as parseToml, stringify as stringifyToml } from 'smol-toml'; import { mathProofEnvironmentWorkerEnvironment } from '../math/mathProofEnvironment'; -import { assertMathCanonicalPath, isMathPathWithin, outermostMathPaths } from '../math/paths'; +import { assertMathCanonicalPath, outermostMathPaths } from '../math/paths'; import { startChatCompletionsBridge } from './chatCompletionsBridge'; import { WESTLAKE_NATIVE_TEAM_UNSUPPORTED, WESTLAKE_PROVIDER, validateWestlakeModel } from './westlake'; import { SUB2API_PROVIDER } from './sub2api'; -import type { ModelRequestGate } from './modelRequest'; +import { createCodexTurnRequests } from './codexTurnRequests'; import { prepareFormalizationSandbox } from './formalizationSandbox'; import { startFormalizationRelay } from './formalizationRelay'; -import { mathDigest, readMathText } from '../math/mathRuntimeIo'; +import { createCodexOutputWatch } from './codexOutputWatch'; import { scheduleMathTimeout } from '../math/mathTimers'; import { assertMathAgentSkillsCurrent, assertMathAgentSkillsDiscovered } from './codexSkills'; import { planMathAgentSession } from './agentSessionPlan'; import { MathAgentToolDispatcher } from './agentTeamTools'; -import { - harnessReadRoots, - hostPrivateRoots, - prepareHarnessProcess, - type HarnessProcessIdentity, -} from './harnessProcess'; +import { harnessReadRoots, hostPrivateRoots, prepareHarnessProcess } from './harnessProcess'; import { runHarnessLeanHealthCheck } from './leanHealthCheck'; -import { - NativeAgentControl, - NativeAgentControlInputError, - NATIVE_AGENT_CONTROL_REQUEST, - nativeAgentControlModelCatalog, -} from './nativeAgentControl'; import { CODEX_FAILURE_CODES, HTTP_FAILURE_CODES, @@ -50,7 +29,6 @@ import { } from './failureDiagnostic'; export type { MathAgentFailureDiagnostic, MathAgentFailureReason } from './failureDiagnostic'; -type Json = Record; const outputToolItems = new Set([ 'commandExecution', 'fileChange', @@ -79,7 +57,7 @@ const completedAssistantText = (value: unknown): string | undefined => { return item.text; }; -function acceptedTeamHandoff(item: Json, readOnlyWorkspace: boolean | undefined): boolean { +function pendingPlanApproval(item: Json): boolean { if ( item.type !== 'dynamicToolCall' || item.tool !== 'theoremos_team' || @@ -89,33 +67,15 @@ function acceptedTeamHandoff(item: Json, readOnlyWorkspace: boolean | undefined) ) return false; const args = item.arguments; - if (!args || typeof args !== 'object' || !('operation' in args)) return false; + if (!args || typeof args !== 'object' || !('operation' in args) || args.operation !== 'publish_plan') return false; const output = item.contentItems[0]; if (output?.type !== 'inputText' || typeof output.text !== 'string') return false; - let result: Json; try { - result = object(JSON.parse(output.text)); + const result = object(JSON.parse(output.text)); + return result.ok === true && result.status === 'pending'; } catch { return false; } - if (result.ok !== true) return false; - switch (args.operation) { - case 'publish_plan': - return Boolean(readOnlyWorkspace) && result.status === 'pending'; - case 'finish': - case 'submit': - case 'submit_helpers': - case 'yield': - return result.status === 'pending-writer-stop'; - case 'adopt': { - const adoption = result.adoption; - if (!adoption || typeof adoption !== 'object') return false; - const { targetId, status } = adoption as Json; - return targetId === 'lead' && (status === 'queued' || status === 'integrating'); - } - default: - return false; - } } const RELAY_CAPABILITY_ENV = 'THEOREM_OS_MODEL_RELAY_CAPABILITY'; @@ -157,73 +117,18 @@ export function mathWorkerPermissionConfig( }; } -const object = (value: unknown): Json => { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('math_codex_invalid_message'); - return value as Json; -}; -function threadDispatch( - id: string, - metadataOnly: boolean, - settings: Json, - tools?: readonly unknown[], - bootstrap?: Json, -) { - if (nativeProcess) return nativeProcess.codexThreadDispatch(id, metadataOnly, settings, tools, bootstrap); - const params = { - ...settings, - ...(id ? { threadId: id, ...(metadataOnly ? { excludeTurns: true } : {}) } : {}), - ...(!id && tools?.length ? { dynamicTools: tools } : {}), - }; - if (!bootstrap) return { method: id ? 'thread/resume' : 'thread/start', params }; +function threadDispatch(id: string, metadataOnly: boolean, settings: Json, tools?: readonly unknown[]) { + if (nativeProcess) return nativeProcess.codexThreadDispatch(id, metadataOnly, settings, tools); return { - method: 'theoremos/agentControl/start', + method: id ? 'thread/resume' : 'thread/start', params: { - version: 1, - bootstrap: { - ...bootstrap, - hostOverrides: { - ...object(bootstrap.hostOverrides ?? {}), - developerInstructions: settings.developerInstructions, - ...(tools ? { dynamicTools: tools } : {}), - }, - }, - [id ? 'resume' : 'thread']: params, + ...settings, + ...(id ? { threadId: id, ...(metadataOnly ? { excludeTurns: true } : {}) } : {}), + ...(!id && tools?.length ? { dynamicTools: tools } : {}), }, }; } -function memberInput( - envelope: Json, - threadId: string, - message: string, - first: boolean, - skills: NonNullable, -): Json { - if (nativeProcess) return nativeProcess.codexMemberInput(envelope, threadId, message, first, skills); - if (!first) - return { - author: envelope.author, - startOptions: {}, - input: { kind: 'userInput', items: [{ type: 'text', text: message, text_elements: [] }] }, - version: 1, - threadId, - }; - const text = - message + - skills - .map( - skill => - `\nUse the frozen ${skill.name} research skill. Read ${JSON.stringify(skill.path)} before research and follow its relevant references on demand.`, - ) - .join(''); - return { - ...envelope, - version: 1, - threadId, - contextItems: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text }] }], - }; -} - const failureDiagnostic = (error: Json): MathAgentFailureDiagnostic | undefined => { const info = error.codexErrorInfo; const structured = info && typeof info === 'object' && !Array.isArray(info) ? (info as Json) : undefined; @@ -242,7 +147,7 @@ const failureDiagnostic = (error: Json): MathAgentFailureDiagnostic | undefined ...(reason ? { reason } : {}), }; }; -import type { MathAgentActivity, MathAgentOptions, MathAgentSession, MathNativeConfiguration } from './agentSession'; +import type { MathAgentActivity, MathAgentOptions, MathAgentSession } from './agentSession'; export type { MathAgentActivity, MathAgentOptions, MathAgentSession } from './agentSession'; // Isolated formalization already supplies the complete frozen role protocol. @@ -261,335 +166,6 @@ function prepareWorkerTemporaryDirectory(workspace: string): string { return temporaryDirectory; } -/** One persistent Codex app-server; all protocol traffic stays on stdio. */ -class CodexRpc { - private child?: ChildProcessByStdio; - private nativeChild?: InstanceType['CodexChild']>; - private readonly nativeInput?: InstanceType['CodexStdin']>; - private readonly requests = nativeProcess && new nativeProcess.CodexRequests(); - private nextId = 0; - private pending = new Map< - number, - { method?: string; resolve: (result: Json) => void; reject: (error: Error) => void; timer: NodeJS.Timeout } - >(); - private readonly outputDrained: Promise; - private nativeOutput?: InstanceType['CodexStdout']>; - private failure?: Error; - private closing?: Promise; - readonly processIdentity: Promise; - onNotification: (method: string, params: Json) => void = () => {}; - onRequest: (method: string, params: Json) => Promise = async () => undefined; - onFailure: (error: Error) => void = () => {}; - - constructor( - executable: string, - profile: string, - environment: NodeJS.ProcessEnv = process.env, - launch?: { command: string; args: string[]; inheritedFds?: readonly number[]; infoDescriptor?: number }, - ) { - const extras: ('pipe' | number)[] = [...(launch?.inheritedFds ?? [])]; - if (launch?.infoDescriptor !== undefined) { - if (launch.infoDescriptor !== extras.length + 3) throw new Error('math_harness_info_descriptor_invalid'); - extras.push('pipe'); - } - const fail = (reason: string) => this.fail(new Error(`math_codex_transport_closed:${reason}`)); - const errorCode = (error: NodeJS.ErrnoException) => - /^[A-Z0-9_]{1,32}$/u.test(error.code ?? '') ? error.code : 'unknown'; - const receive = (line: Buffer) => { - try { - const message = object(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(line))); - if (message.method !== undefined && typeof message.method !== 'string') throw new Error(); - if (message.method && message.id !== undefined) { - // Only explicitly registered host tools are handled. Permission requests - // and all other interactive calls still receive no grant. - void Promise.resolve() - .then(() => this.onRequest(message.method as string, object(message.params ?? {}))) - .then( - result => - this.write( - result === undefined - ? { - id: message.id, - error: { - code: -32601, - message: 'Interactive requests are unavailable in headless mathematics', - }, - } - : { id: message.id, result }, - ), - error => - this.write({ - id: message.id, - error: - message.method === NATIVE_AGENT_CONTROL_REQUEST && error instanceof NativeAgentControlInputError - ? { code: -32602, message: error.message } - : { code: -32603, message: 'Headless tool request failed' }, - }), - ) - .catch(() => {}); - } else if (message.method) { - this.onNotification(message.method as string, object(message.params ?? {})); - } else { - if (typeof message.id !== 'number') return; - const call = this.pending.get(message.id); - if (!call) return; - const error = message.error ? object(message.error) : undefined; - const result = error ? undefined : object(message.result ?? {}); - // A malformed reply above must fail this call along with the rest of the transport. - const method = this.requests ? this.requests.take(message.id) : call.method; - if (method == null) throw new Error('math_codex_untracked_request'); - this.pending.delete(message.id); - clearTimeout(call.timer); - const code = - typeof error?.code === 'number' && Number.isSafeInteger(error.code) ? error.code : 'invalid_code'; - const startup = - method === 'thread/start' || method === 'initialize' || 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}:${method}`, - method.startsWith('theoremos/agentControl/') ? { cause: error } : undefined, - ), - ); - else call.resolve(result!); - } - } catch { - fail('invalid_frame'); - } - }; - let parts: Buffer[] = [], - bytes = 0; - const onData = (chunk: Buffer) => { - if (this.failure) return; - let start = 0; - while (start < chunk.length) { - const newline = chunk.indexOf(10, start), - end = newline < 0 ? chunk.length : newline; - bytes += end - start; - if (bytes > 8 * 1024 * 1024) { - parts = []; - fail('frame_too_large'); - return; - } - parts.push(chunk.subarray(start, end)); - if (newline < 0) break; - const line = Buffer.concat(parts, bytes); - parts = []; - bytes = 0; - receive(line); - if (this.failure) return; - start = newline + 1; - } - }; - let nativeIdentity: Promise | undefined; - let finishOutput = () => {}; - this.outputDrained = nativeProcess - ? new Promise(resolve => { - finishOutput = resolve; - }) - : Promise.resolve(); - try { - this.nativeOutput = - nativeProcess && - new nativeProcess.CodexStdout((frames, eof, tooLarge, errno) => { - if (!this.child && !this.nativeChild) return; - for (const frame of frames) { - if (this.failure) break; - receive(frame); - } - if (!eof) return; - finishOutput(); - if (tooLarge) fail('frame_too_large'); - else if (errno) fail('stdout_error:code=' + getSystemErrorName(-errno)); - else void this.close(); - }); - this.nativeInput = - nativeProcess && - new nativeProcess.CodexStdin(errno => { - if (!this.closing) - this.fail(new Error('math_codex_transport_closed:stdin_error:code=' + getSystemErrorName(-errno))); - }); - const childEnvironment = { ...environment, CODEX_HOME: profile }; - if (nativeProcess && this.nativeInput && this.nativeOutput) { - try { - let onIdentity: ((result: { identity?: HarnessProcessIdentity; error?: string }) => void) | undefined; - if (launch?.infoDescriptor !== undefined) { - nativeIdentity = new Promise((resolve, reject) => { - onIdentity = result => - result.identity - ? resolve(result.identity) - : reject(new Error(result.error ?? 'math_harness_process_identity_unavailable')); - }); - void nativeIdentity.catch(() => {}); - } - this.nativeChild = new nativeProcess.CodexChild( - launch?.command ?? executable, - childEnvironment, - this.nativeInput, - this.nativeOutput, - (code, signal) => { - const signame = - signal && - Object.keys(osConstants.signals).find( - s => osConstants.signals[s as keyof typeof osConstants.signals] === signal, - ); - void this.close(); - void this.outputDrained.then(() => - fail(`process_exit:code=${code ?? 'none'}:signal=${signame ?? 'none'}`), - ); - }, - launch && { - args: launch.args, - descriptors: launch.inheritedFds ?? [], - infoDescriptor: launch.infoDescriptor, - }, - onIdentity, - ); - } catch (cause) { - const errno = /^math_codex_spawn_errno:(\d+)$/u.exec((cause as Error).message); - if (errno) - throw new Error('math_codex_transport_closed:spawn_error:code=' + getSystemErrorName(-Number(errno[1]))); - throw cause; - } - } else { - this.child = spawn(launch?.command ?? executable, launch?.args ?? ['app-server', '--listen', 'stdio://'], { - env: childEnvironment, - stdio: [this.nativeInput?.childFd() ?? 'pipe', this.nativeOutput?.childFd() ?? 'pipe', 'pipe', ...extras], - detached: process.platform !== 'win32', - }) as ChildProcessByStdio; - } - } catch (error) { - this.nativeInput?.close(); - finishOutput(); - this.nativeOutput?.close(); - throw error; - } finally { - this.nativeInput?.spawned(); - this.nativeOutput?.spawned(); - } - if (!this.child) { - this.processIdentity = nativeIdentity ?? Promise.resolve(undefined); - return; - } - trackMathProcessSession(this.child); - const infoDescriptor = launch?.infoDescriptor; - this.processIdentity = - infoDescriptor === undefined ? Promise.resolve(undefined) : watchMathProcessNamespace(this.child, infoDescriptor); - void this.processIdentity.catch(() => {}); - // Do not forward provider diagnostics, which can contain credentials or task text. - this.child.stderr.resume(); - this.child.once('error', error => fail(`spawn_error:code=${errorCode(error)}`)); - // Descendants may retain the pipes after their parent exits. Reap the owned group, - // while still draining its buffered usage/completion frames before the close event. - this.child.once('exit', () => { - void this.close(); - }); - this.child.once('close', (code, signal) => { - void this.outputDrained.then(() => fail(`process_exit:code=${code ?? 'none'}:signal=${signal ?? 'none'}`)); - }); - this.child.stdin?.on('error', error => fail(`stdin_error:code=${errorCode(error)}`)); - // EOF ends the response transport even if its process is still alive. Let close - // report the actual exit code after draining all frames, rather than racing it. - this.child.stdout?.once('end', () => { - void this.close(); - }); - this.child.stdout?.on('data', onData); - } - - private fail(error: Error): void { - if (this.failure) return; - this.failure = error; - const ids = this.requests ? this.requests.fail() : this.pending.keys(); - for (const id of ids) { - const call = this.pending.get(id)!; - clearTimeout(call.timer); - call.reject(error); - } - this.pending.clear(); - this.onFailure(error); - // A lost reply leaves the remote turn's state unknown; no writer may outlive this transport. - void this.close(); - } - - private write(message: Json): void { - if (this.failure) throw this.failure; - const json = JSON.stringify(message); - if (this.nativeInput) this.nativeInput.write(json); - else this.child!.stdin!.write(json + '\n'); - } - - request(method: string, params: Json): Promise { - if (this.failure) return Promise.reject(this.failure); - // Continue draining buffered replies and usage, but never dispatch work to a closing writer. - const id = this.requests ? this.requests.open(method) : this.closing ? null : ++this.nextId; - if (id == null) return Promise.reject(new Error('math_codex_transport_closed:closing')); - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - if (this.requests && !this.requests.has(id)) return; - this.fail(new Error(`math_codex_rpc_timeout:${method}`)); - }, 120_000); - this.pending.set(id, { method: this.requests ? undefined : method, resolve, reject, timer }); - try { - this.write({ id, method, params }); - } catch (error) { - clearTimeout(timer); - this.requests?.take(id); - this.pending.delete(id); - reject(error); - } - }); - } - - async initialize(experimental = false): Promise { - await this.request( - 'initialize', - nativeProcess?.codexInitialize(experimental) ?? { - clientInfo: { name: 'deepscientist-math', version: '0.1.0' }, - capabilities: experimental ? { experimentalApi: true } : null, - }, - ); - this.write({ method: 'initialized' }); - } - - close(): Promise { - this.requests?.close(); - if (!this.closing) { - this.closing = (this.nativeChild?.stop() ?? closeMathProcess(this.child!)).then(async () => { - // A TERM handler may deliver the last usage and completion before it closes its stdio. - this.nativeInput?.close(); - const fallback = this.nativeOutput && setTimeout(() => this.nativeOutput?.close(), 3000); - try { - await this.outputDrained; - } finally { - clearTimeout(fallback); - this.nativeOutput?.close(); - } - }); - } - return this.closing; - } - async confirmStopped(): Promise { - const receipt = await (this.nativeChild?.confirm() ?? confirmMathProcessStopped(this.child!)); - if (receipt.status !== 'stopped') return receipt; - try { - // An isolated writer must have reported its identity even on a clean launcher exit. - await this.processIdentity; - return receipt; - } catch { - return { status: 'unconfirmed', reason: 'process-identity-unavailable' }; - } - } -} - const RESUME_HISTORY_TOO_LARGE = 'math_codex_resume_history_too_large'; export async function createCodexMathSession(options: MathAgentOptions): Promise { @@ -617,20 +193,20 @@ async function openCodexMathSession( if (options.isolateProcess && options.readIsolation) throw new Error('math_codex_process_isolation_role_conflict'); if (options.readOnlyWorkspace && !options.isolateProcess) throw new Error('math_codex_read_only_workspace_requires_process_isolation'); - if (options.nativeAgentControl && options.readIsolation) throw new Error('math_native_agent_control_role_conflict'); const tools = options.tools ? new MathAgentToolDispatcher( options.tools, (calledThread, calledTurn) => - calledThread === threadId && activeTurn === calledTurn && !turnSettled && !turnStopping && !closing, + calledThread === threadId && currentTurn?.id === calledTurn && isTurnRunning() && !closing, ) : undefined; const configFile = path.join(options.profile, 'config.toml'); const frozenConfig = fs.existsSync(configFile) ? fs.readFileSync(configFile, 'utf8') : undefined; const profileConfig = frozenConfig === undefined ? {} : parseToml(frozenConfig); const providerId = typeof profileConfig.model_provider === 'string' ? profileConfig.model_provider : undefined; - if (providerId === WESTLAKE_PROVIDER.id && options.nativeAgentControl) - throw new Error(WESTLAKE_NATIVE_TEAM_UNSUPPORTED); + const sharedTeam = options.sharedProofTeam; + const useWestlakeBridge = providerId === WESTLAKE_PROVIDER.id; + if (useWestlakeBridge && sharedTeam) throw new Error(WESTLAKE_NATIVE_TEAM_UNSUPPORTED); const providers = profileConfig.model_providers; const selectedProvider = providerId && providers && typeof providers === 'object' && !Array.isArray(providers) @@ -640,103 +216,36 @@ async function openCodexMathSession( selectedProvider && typeof selectedProvider === 'object' && !Array.isArray(selectedProvider) ? (selectedProvider as Json) : undefined; - const webNativeTeam = providerId === 'web_provider' && Boolean(options.nativeAgentControl); + const enableSharedTeam = sharedTeam && !options.readOnlyWorkspace; + const webSharedTeam = providerId === 'web_provider' && Boolean(sharedTeam); const useResponsesRelay = - (providerId === SUB2API_PROVIDER.id || webNativeTeam) && !options.readIsolation && Boolean(options.requestGate); - const executionPlan = planMathAgentSession( - options.nativeAgentControl?.initialInput - ? { ...options, skills: skills.map(skill => ({ ...skill, loading: 'file' as const })) } - : options, - ); - const activeRequests = new Set(); - let requestTurn = 0, - turnSettled = true, - turnStopping = false, + (providerId === SUB2API_PROVIDER.id || webSharedTeam) && !options.readIsolation && Boolean(options.requestGate); + if (sharedTeam?.requireMetering && !useResponsesRelay) + throw new Error('math_shared_team_token_budget_requires_metered_provider'); + const executionPlan = planMathAgentSession(options); + let turnPhase: 'settled' | 'running' | 'stopping' = 'settled'; + let turnCheckpointReached = false; + const isTurnRunning = () => turnPhase === 'running'; + const isTurnSettled = () => turnPhase === 'settled'; + const startTurn = () => { + requests.beginTurn(); + turnPhase = 'running'; turnCheckpointReached = false; + }; let priorBoundaryCheckpoint = false, externallyInterrupted = false; - type NotificationFence = { promise: Promise; release(): void; steered: boolean }; - let notificationFence: NotificationFence | undefined; - let requestStateChanged = () => {}; - let cancelNotifications = () => {}; - let drainTurnRequests: (() => void) | undefined; - const drainRequests = () => - new Promise(resolve => { - drainTurnRequests = () => { - if (activeRequests.size) return; - drainTurnRequests = undefined; - resolve(); - }; - drainTurnRequests(); - }); - let checkCompletedOutput: ((reviewIncomplete?: boolean) => void) | undefined; - let completedOutputWatch: { id: string; file: string; changed(): void } | undefined; - let checkTurnCheckpoint: ((atRequestBoundary?: boolean) => boolean) | undefined; - const requestGate: ModelRequestGate = identity => { - // A tool can submit and immediately request more model work before fs/changed arrives. - // Inspect that file synchronously before admitting another paid request. - if (!turnSettled && !turnStopping) checkCompletedOutput?.(); - checkTurnCheckpoint?.(); - if (turnSettled || turnStopping) return { allowed: false, reason: 'math_model_request_stopped' }; - const admission = options.requestGate?.(identity) ?? { allowed: true as const, settle: () => {} }; - if (!admission.allowed) return admission; - const request = {}; - activeRequests.add(request); - return { - allowed: true, - settle: receipt => { - if (!activeRequests.delete(request)) return; - try { - admission.settle(receipt); - } finally { - requestStateChanged(); - } - }, - }; - }; - requestGate.beforeRequest = async signal => { - const turn = requestTurn; - if (checkTurnCheckpoint?.()) throw new Error('math_codex_turn_checkpoint'); - let deferredFence: NotificationFence | undefined; - await options.requestGate?.beforeRequest?.(signal); - // The next request can arrive before the file watcher reports a completed Lean check. - if ( - options.completedOutput?.reviewIncomplete && - turn === requestTurn && - !signal.aborted && - !turnSettled && - !turnStopping - ) - checkCompletedOutput?.(true); - if ([...notices].some(notice => notice.waitForRequest)) { - // A settled response may still be executing its submission tool. The next - // request proves those tools have finished; prefer their valid output to steer. - if (!turnSettled && !turnStopping) checkCompletedOutput?.(); - if (!turnSettled && !turnStopping) deferredFence = flushNotifications(true); - } - // A subsequent HTTP request may already be queued when steer is sent. Keep it outside - // provider admission until Codex acknowledges the notice, so steer cannot cancel paid work. - while (notificationFence) { - signal.throwIfAborted(); - const fence = notificationFence; - await new Promise((resolve, reject) => { - const abort = () => { - signal.removeEventListener('abort', abort); - reject(signal.reason ?? new Error('math_codex_request_aborted')); - }; - signal.addEventListener('abort', abort, { once: true }); - void fence.promise.then(() => { - signal.removeEventListener('abort', abort); - resolve(); - }); - }); - } - signal.throwIfAborted(); - if (turn !== requestTurn || turnSettled || turnStopping) throw new Error('math_codex_notification_turn_settled'); - // This request predates the delivered instructions. Stdio acknowledgement can - // beat its HTTP cancellation; only a new request can carry the updated context. - if (deferredFence?.steered) throw new Error('math_codex_notification_request_superseded'); - }; + let turnOutput: Awaited>> | undefined; + let checkTurnCheckpoint: ((boundary: 'request' | 'tool') => boolean) | undefined; + const requests = createCodexTurnRequests({ + upstream: options.requestGate, + running: isTurnRunning, + noticeTurn: () => (isTurnRunning() && !turnCheckpointReached && !closing ? currentTurn?.id : undefined), + toolsBusy: () => tools?.busy ?? false, + checkpoint: () => checkTurnCheckpoint?.('request'), + reviewIncomplete: Boolean(options.completedOutput?.reviewIncomplete), + checkOutput: mode => turnOutput?.check(mode), + request: (method, params) => rpc.request(method, { threadId, ...params }), + }); const envKey = provider && typeof provider === 'object' && typeof provider.env_key === 'string' ? provider.env_key : undefined; if (envKey && !/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(envKey)) @@ -764,7 +273,7 @@ async function openCodexMathSession( : filters && typeof filters === 'object' ? { 'shell_environment_policy.filters': { ...filters, [credentialEnvKey]: 'exclude' } } : { 'shell_environment_policy.exclude': [...new Set([...exclude, credentialEnvKey])] }; - if (providerId === WESTLAKE_PROVIDER.id) { + if (useWestlakeBridge) { if (envKey !== WESTLAKE_PROVIDER.apiKeyEnvironment || provider?.base_url !== WESTLAKE_PROVIDER.baseUrl) throw new Error('math_westlake_profile_invalid'); validateWestlakeModel(options.model, options.effort); @@ -783,7 +292,7 @@ async function openCodexMathSession( ...(options.outputSchema ? { outputSchema: options.outputSchema } : {}), env: options.environment, signal: options.signal, - requestGate, + requestGate: requests.gate, onUsageIncomplete: options.onUsageIncomplete, }) : undefined; @@ -791,8 +300,7 @@ async function openCodexMathSession( let environment = isolated?.env ?? (envKey ? { ...(workerEnvironment ?? process.env), [envKey]: apiKey } : workerEnvironment); if (!isolated && temporaryDirectory) environment = { ...(environment ?? process.env), TMPDIR: temporaryDirectory }; - let bridge: Awaited> | undefined; - let responsesRelay: Awaited> | undefined; + let loopback: { baseUrl?: string; apiKey: string; close(): Promise } | undefined; let nativeProfile = isolated?.profile ?? options.profile; if (!isolated && frozenConfig !== undefined) { // Codex persists project trust in config.toml; keep those writes outside the frozen profile. @@ -818,14 +326,14 @@ async function openCodexMathSession( } } if (useResponsesRelay) { - responsesRelay = await startFormalizationRelay({ + loopback = await startFormalizationRelay({ transport: 'loopback-http', profile: options.profile, model: options.model, effort: options.effort, env: options.environment, signal: options.signal, - requestGate, + requestGate: requests.gate, onUsageIncomplete: options.onUsageIncomplete, }); environment = Object.fromEntries( @@ -833,24 +341,24 @@ async function openCodexMathSession( ([name]) => name !== envKey && !name.startsWith(SUB2API_PROVIDER.apiKeyEnvironment), ), ); - environment[RELAY_CAPABILITY_ENV] = responsesRelay.apiKey; - } - if (providerId === WESTLAKE_PROVIDER.id) { - bridge = await startChatCompletionsBridge({ + environment[RELAY_CAPABILITY_ENV] = loopback.apiKey; + } else if (useWestlakeBridge) { + loopback = await startChatCompletionsBridge({ baseUrl: WESTLAKE_PROVIDER.baseUrl, apiKey: apiKey!, model: options.model, effort: options.effort, onUsageIncomplete: options.onUsageIncomplete, - requestGate, + requestGate: requests.gate, }); // Codex receives only a disposable loopback credential, including outside proof projections. environment = Object.fromEntries( Object.entries(environment ?? process.env).filter(([name]) => !name.startsWith('WESTLAKEHPC_API_KEY')), ); - environment[WESTLAKE_PROVIDER.apiKeyEnvironment] = bridge.apiKey; + environment[WESTLAKE_PROVIDER.apiKeyEnvironment] = loopback.apiKey; } - const usesRequestReceipts = Boolean((bridge || responsesRelay || isolated) && options.requestGate); + const providerTransport = isolated ?? loopback; + const usesRequestReceipts = Boolean(providerTransport && options.requestGate); const providerSettings: Json = isolated ? { model_provider: isolated.providerId, @@ -861,13 +369,12 @@ async function openCodexMathSession( : providerId ? { model_provider: providerId, - ...(responsesRelay + ...(useResponsesRelay ? { [`model_providers.${providerId}.stream_idle_timeout_ms`]: RESPONSES_STREAM_IDLE_TIMEOUT_MS } : {}), ...(provider && typeof provider.base_url === 'string' ? { - [`model_providers.${providerId}.base_url`]: - responsesRelay?.baseUrl ?? bridge?.baseUrl ?? provider.base_url, + [`model_providers.${providerId}.base_url`]: loopback?.baseUrl ?? provider.base_url, } : {}), ...(typeof profileConfig.model_catalog_json === 'string' @@ -875,18 +382,11 @@ async function openCodexMathSession( : {}), } : {}; - if (options.nativeAgentControl && typeof providerSettings.model_catalog_json === 'string') { - providerSettings.model_catalog_json = nativeAgentControlModelCatalog( - path.resolve(options.profile, providerSettings.model_catalog_json), - options.model, - path.join(nativeProfile, 'agent-control'), - ); - } let rpc: CodexRpc; environment = { ...(environment ?? process.env) }; delete environment.THEOREMOS_LIBRARY_HOST_CONFIG; + // Old executables may still be selected through a frozen profile. delete environment.THEOREMOS_HOST_AGENT_CONTROL; - if (options.nativeAgentControl) environment.THEOREMOS_HOST_AGENT_CONTROL = '1'; let processLaunch: ReturnType | undefined; try { options.signal?.throwIfAborted(); @@ -909,69 +409,39 @@ async function openCodexMathSession( processLaunch ? { ...processLaunch, infoDescriptor: 3 } : isolated, ); } catch (error) { - await responsesRelay?.close(); - await bridge?.close(); - await isolated?.close(); + await providerTransport?.close(); throw error; } - const nativeControl = options.nativeAgentControl - ? new NativeAgentControl(options.nativeAgentControl, (method, params) => rpc.request(method, params)) - : undefined; - const nativeConfiguration: MathNativeConfiguration = { - source: 'thread-start-overrides', - overrides: { - includeSkillInstructions: false, - ...(nativeControl - ? ({ - deferMailboxPreemption: true, - rootAgentUsageHintText: '', - subagentUsageHintText: '', - // Codex high effort otherwise emits ExplicitRequestOnly after the host's - // delegation instructions. Use its native per-session mode override. - multiAgentModeHintText: options.nativeAgentControl?.bootstrap - ? 'You are a member of an explicitly requested flat team. Carry out the Lead assignment. ' + - 'Do not spawn sub-agents or dispatch, redirect or interrupt other members.' - : 'You are the Lead of an explicitly requested flat team. Follow the pinned Lead charter. ' + - 'Only Lead dispatches or interrupts members. Members may message one another.', - } as const) - : {}), - }, - }; let closing: Promise | undefined; - let boundTurn: Promise = Promise.resolve(undefined); - let bindTurn: ((turnId?: string) => void) | undefined; const closeSession = () => (closing ??= (async () => { options.signal?.removeEventListener('abort', aborted); compacting?.reject(new Error('math_codex_compaction_closed')); - turnStopping = true; - cancelNotifications(); - publicItems.clear(); - bindTurn?.(); + endTurnInput('stopping'); + currentTurn?.bind(); tools?.stop(); - nativeControl?.stop(); try { await rpc.close(); } finally { try { - await responsesRelay?.close(); + await providerTransport?.close(); } finally { - try { - await bridge?.close(); - } finally { - await isolated?.close(); - } + await tools?.settled(); } - await tools?.settled(); - await nativeControl?.settled(); } })()); const aborted = () => { void closeSession().catch(() => {}); }; - let activeTurn: string | undefined; - let turnEvidence: ReturnType | undefined; - let completion: { resolve: (turn: Json) => void; reject: (error: Error) => void } | undefined; + type ActiveTurn = { + id?: string; + binding: Promise; + bind(turnId?: string): void; + evidence: ReturnType; + resolve(turn: Json): void; + reject(error: Error): void; + }; + let currentTurn: ActiveTurn | undefined; let compacting: { resolve: (turn: Json) => void; reject: (error: Error) => void; turnId?: string; installed?: boolean } | undefined; const earlyCompletions = new Map(); @@ -982,150 +452,6 @@ async function openCodexMathSession( let lastInputTokens = 0; let transportFailure: Error | undefined; let threadId = options.threadId; - type Notice = { - turnId: string; - turn: number; - message: string; - waitForRequest: boolean; - resolve(): void; - reject(error: Error): void; - }; - const notices = new Set(); - let notificationFlush: NodeJS.Immediate | undefined; - const releaseFence = (fence = notificationFence) => { - if (!fence) return; - if (notificationFence === fence) notificationFence = undefined; - fence.release(); - }; - cancelNotifications = () => { - clearImmediate(notificationFlush); - notificationFlush = undefined; - for (const notice of notices) notice.reject(new Error('math_codex_notification_turn_settled')); - notices.clear(); - releaseFence(); - }; - const flushNotifications = (atRequest = false): NotificationFence | undefined => { - if ( - !notices.size || - activeRequests.size || - tools?.busy || - notificationFence || - !activeTurn || - turnSettled || - turnStopping || - turnCheckpointReached || - closing - ) - return; - if (![...notices].some(notice => !notice.waitForRequest || atRequest)) return; - const turnId = activeTurn, - turn = requestTurn; - let release!: () => void; - const fence: NotificationFence = { - promise: new Promise(resolve => { - release = resolve; - }), - release: () => release(), - steered: false, - }; - notificationFence = fence; - // The bridge may settle accounting while writing its terminal event. Finish that write - // before sending input, while the fence already protects the next provider request. - notificationFlush = setImmediate(() => { - notificationFlush = undefined; - if (notificationFence !== fence) return; - if (activeTurn !== turnId || requestTurn !== turn || turnSettled || turnStopping || closing) { - cancelNotifications(); - return; - } - // An admission already past its async transport hook may have won this same event-loop turn. - // Let that request finish and retry the notice at its settlement boundary. - if (activeRequests.size) { - releaseFence(fence); - return; - } - const batch = [...notices].filter( - notice => notice.turn === turn && notice.turnId === turnId && (!notice.waitForRequest || atRequest), - ); - fence.steered = true; - const request = options.nativeAgentControl?.initialInput - ? rpc.request('theoremos/agentControl/input', { - version: 1, - threadId, - expectedTurnId: turnId, - author: options.nativeAgentControl.initialInput.author, - input: { - kind: 'message', - message: { kind: 'plaintext', text: batch.map(notice => notice.message).join('\n\n') }, - mode: 'triggerTurn', - }, - startOptions: {}, - }) - : rpc.request('turn/steer', { - threadId, - expectedTurnId: turnId, - input: batch.map(notice => ({ type: 'text', text: notice.message, text_elements: [] })), - }); - void request - .then( - () => { - for (const notice of batch) if (notices.delete(notice)) notice.resolve(); - }, - error => { - for (const notice of batch) if (notices.delete(notice)) notice.reject(error); - }, - ) - .finally(() => { - releaseFence(fence); - flushNotifications(); - }); - }); - return fence; - }; - const notify: NonNullable = async (message, notifyOptions) => { - if (!activeTurn || turnSettled || turnStopping || turnCheckpointReached || closing) { - if (notifyOptions?.mode === 'advisory') throw new Error('math_codex_notification_turn_settled'); - if (notifyOptions?.waitForRequest === false) throw new Error('math_codex_notification_turn_settled'); - return; - } - if (notifyOptions?.mode === 'advisory') { - if (options.nativeAgentControl?.initialInput) { - await rpc.request('theoremos/agentControl/input', { - version: 1, - threadId, - author: options.nativeAgentControl.initialInput.author, - startOptions: {}, - input: { kind: 'message', message: { kind: 'plaintext', text: message }, mode: 'queueOnly' }, - }); - return; - } - // Codex queues these behind the current response and tools. Unlike steer, - // history injection neither cancels a request nor starts work if the turn - // finishes during delivery; the durable team inbox remains authoritative. - await rpc.request('thread/inject_items', { - threadId, - items: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: message }] }], - }); - return; - } - if (notifyOptions?.waitForRequest === false && (activeRequests.size || notificationFence)) - throw new Error('math_codex_notification_request_active'); - return new Promise((resolve, reject) => { - notices.add({ - turnId: activeTurn!, - turn: requestTurn, - message, - waitForRequest: notifyOptions?.waitForRequest === true, - resolve, - reject, - }); - flushNotifications(); - }); - }; - requestStateChanged = () => { - drainTurnRequests?.(); - flushNotifications(); - }; let lastStreamActivityAt = 0; const outputTails = new Map(); const outputKey = (turnId: unknown, itemId: string) => `${typeof turnId === 'string' ? turnId : ''}\u0000${itemId}`; @@ -1139,27 +465,32 @@ async function openCodexMathSession( completed: boolean; }; const publicItems = new Map(); + const endTurnInput = (phase: 'stopping' | 'settled') => { + if (isTurnSettled() || turnPhase === phase) return; + turnPhase = phase; + tools?.cancel(); + requests.cancelNotifications(); + publicItems.clear(); + }; const publicTurn = (params: Json) => options.onItemUpdate && - completion && - !turnSettled && - !turnStopping && + currentTurn && + isTurnRunning() && !closing && !options.signal?.aborted && params.threadId === threadId && typeof params.turnId === 'string' && !earlyCompletions.has(params.turnId) && - (!activeTurn || params.turnId === activeTurn) + (!currentTurn?.id || params.turnId === currentTurn?.id) ? params.turnId : undefined; const publishPublicItem = (entry: PublicItem) => { if ( !entry.changed || entry.completed || - entry.turnId !== activeTurn || + entry.turnId !== currentTurn?.id || earlyCompletions.has(entry.turnId) || - turnSettled || - turnStopping || + !isTurnRunning() || closing || options.signal?.aborted ) @@ -1226,12 +557,22 @@ async function openCodexMathSession( entry.changed = true; publishPublicItem(entry); }; - const reportedInvalidOutputs = new Set(); - let validationFeedbackPending = false; + const watchTurnOutput = + options.completedOutput && + createCodexOutputWatch({ + output: options.completedOutput, + workspace: options.workspace, + isolatedWorkspace: isolated?.workspace, + signal: options.signal, + usesRequestReceipts, + request: (method, params) => rpc.request(method, params), + notify: requests.notify, + phase: () => turnPhase, + }); type BufferedActivity = { value: MathAgentActivity; streaming: boolean; at: number }; const earlyActivities = new Map(); const emitActivity = ({ value, streaming, at }: BufferedActivity) => { - if (!options.onActivity || !completion || turnSettled || turnStopping || closing || options.signal?.aborted) return; + if (!options.onActivity || !currentTurn || !isTurnRunning() || closing || options.signal?.aborted) return; if (streaming && at - lastStreamActivityAt < 30_000) return; lastStreamActivityAt = at; options.onActivity(value); @@ -1240,16 +581,17 @@ async function openCodexMathSession( event: MathAgentActivity['event'], itemType?: string, streaming = false, - turnId: unknown = activeTurn, + turnId: unknown = currentTurn?.id, ) => { - if (!options.onActivity || !completion || turnSettled || turnStopping || closing || options.signal?.aborted) return; - if (typeof turnId === 'string' && (activeTurn ? turnId !== activeTurn : earlyCompletions.has(turnId))) return; + if (!options.onActivity || !currentTurn || !isTurnRunning() || closing || options.signal?.aborted) return; + if (typeof turnId === 'string' && (currentTurn?.id ? turnId !== currentTurn.id : earlyCompletions.has(turnId))) + return; const entry = { value: { event, ...(itemType && /^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(itemType) ? { itemType } : {}) }, streaming, at: Date.now(), }; - if (!activeTurn && typeof turnId === 'string') { + if (!currentTurn?.id && typeof turnId === 'string') { // Bind early scheduling events only after turn/start confirms their owner. // Store metadata only, with the same bounded turn history as early completions. if (!earlyActivities.has(turnId) && earlyActivities.size >= 32) @@ -1264,44 +606,32 @@ async function openCodexMathSession( emitActivity(entry); }; const recordTurnOutput = (turnId: unknown) => { - if (completion) turnEvidence?.recordOutput(typeof turnId === 'string' ? turnId : undefined); + currentTurn?.evidence.recordOutput(typeof turnId === 'string' ? turnId : undefined); }; rpc.onFailure = error => { - cancelNotifications(); - publicItems.clear(); transportFailure = error; lastError = error.message; lastFailureDiagnostic = undefined; - completion?.reject(error); + currentTurn?.reject(error); compacting?.reject(error); - tools?.stop(); - nativeControl?.stop(); - bindTurn?.(); if (!closing) { void closeSession().catch(() => {}); } }; rpc.onRequest = async (method, params) => { - if (method === NATIVE_AGENT_CONTROL_REQUEST && nativeControl) return nativeControl.call(params); if (method !== 'item/tool/call' || !tools) return; - const turnId = await boundTurn; + const turnId = await currentTurn?.binding; if (!turnId || params.turnId !== turnId) return { contentItems: [{ type: 'inputText', text: 'math_agent_tool_turn_mismatch' }], success: false }; const result = await tools.call(params); - flushNotifications(); + requests.flushNotifications(); return result; }; rpc.onNotification = (method, params) => { if (method === 'fs/changed') { // File watches belong to this connection, not a thread or turn. Old watches // and unrelated directory changes must never submit the active role. - if ( - completedOutputWatch && - params.watchId === completedOutputWatch.id && - Array.isArray(params.changedPaths) && - params.changedPaths.includes(completedOutputWatch.file) - ) - completedOutputWatch.changed(); + if (turnOutput?.matches(params)) turnOutput.check('watch'); return; } if (threadId !== undefined && params.threadId !== undefined && params.threadId !== threadId) return; @@ -1312,16 +642,17 @@ async function openCodexMathSession( if (method === 'item/started' || method === 'item/completed') { const item = object(params.item); // Direct providers have no request relay. The completed tool item confirms - // that Codex received the accepted handoff before we check whether to stop. + // that Codex received the pending plan approval before we check whether to stop. if ( !usesRequestReceipts && method === 'item/completed' && - activeTurn && + currentTurn?.id && params.threadId === threadId && - params.turnId === activeTurn && - acceptedTeamHandoff(item, options.readOnlyWorkspace) + params.turnId === currentTurn?.id && + options.readOnlyWorkspace && + pendingPlanApproval(item) ) - checkTurnCheckpoint?.(false); + checkTurnCheckpoint?.('tool'); if ( compacting?.turnId && method === 'item/completed' && @@ -1333,9 +664,9 @@ async function openCodexMathSession( observePublicItem(method, params, item); if ( method === 'item/completed' && - completion && + currentTurn && typeof params.turnId === 'string' && - (!activeTurn || params.turnId === activeTurn) + (!currentTurn?.id || params.turnId === currentTurn?.id) ) { const text = completedAssistantText(item); if (text !== undefined) { @@ -1394,6 +725,7 @@ async function openCodexMathSession( typeof last.inputTokens === 'number' && Number.isSafeInteger(last.inputTokens) && last.inputTokens >= 0 ? last.inputTokens : 0; + if (enableSharedTeam && !usesRequestReceipts) options.onUsageIncomplete?.(); options.onUsage(object(usage.total ?? {}), { ...(typeof params.turnId === 'string' ? { turnId: params.turnId } : {}), }); @@ -1411,9 +743,9 @@ async function openCodexMathSession( else if (compacting.installed) compacting.resolve(turn); else compacting.reject(new Error('math_codex_compaction_missing_summary')); } - const owner = turnEvidence?.route(turn.id); - if (completion && owner === 'active') completion.resolve(turn); - else if (completion && owner === 'early') { + const owner = currentTurn?.evidence.route(turn.id); + if (owner === 'active') currentTurn?.resolve(turn); + else if (owner === 'early') { if (earlyCompletions.size >= 32) earlyCompletions.delete(earlyCompletions.keys().next().value!); earlyCompletions.set(turn.id, turn); } @@ -1423,11 +755,12 @@ async function openCodexMathSession( try { options.signal?.throwIfAborted(); const processIdentity = await rpc.processIdentity; - await rpc.initialize(Boolean(options.tools || nativeControl)); - await nativeControl?.initialize(); + await rpc.initialize(Boolean(options.tools)); const inherited = profileConfig.mcp_servers; const disabled = Object.fromEntries(Object.keys(inherited ?? {}).map(name => [name, { enabled: false }])); - const soloWorkspace = options.soloProofWorkspace && !isolated && !nativeControl && !options.readOnlyWorkspace; + const soloWorkspace = options.soloProofWorkspace && !isolated && !options.readOnlyWorkspace; + const managedTools = options.soloProofWorkspace || options.skills?.length || options.tools; + const limitedProviderTools = Boolean(providerTransport); const settings = { model: options.model, cwd: isolated?.workspace ?? options.workspace, @@ -1454,45 +787,19 @@ async function openCodexMathSession( 'features.plugins': false, // Only the frozen, explicitly selected mathematics skills belong in these // sessions. This suppresses the global catalog, not explicit skill loading. - 'skills.include_instructions': nativeConfiguration.overrides.includeSkillInstructions, + 'skills.include_instructions': false, // Preserve the projected proof environment; user profiles and shell snapshots // can select tools that execute outside the isolated mathematical worktree. allow_login_shell: false, 'features.shell_snapshot': false, 'shell_environment_policy.experimental_use_profile': false, - ...(bridge || responsesRelay || isolated + ...(limitedProviderTools ? { - ...(!nativeControl ? { 'features.multi_agent': false, 'features.multi_agent_v2': false } : {}), - 'features.goals': false, 'features.view_image': false, - ...(responsesRelay ? { web_search: 'disabled' } : {}), - } - : {}), - // Native role files cannot narrow inherited writer permissions; profiles cannot enable children implicitly. - ...(!nativeControl && (options.soloProofWorkspace || options.skills?.length || options.tools) - ? { - 'features.multi_agent': false, - 'features.multi_agent_v2': false, - 'agents.enabled': false, - 'features.goals': false, - } - : {}), - ...(nativeControl - ? { - 'features.multi_agent': true, - // Empty role overrides suppress generic hints that conflict with the - // host's complete workspace, capacity and delegation contract. - 'features.multi_agent_v2': { - enabled: true, - root_agent_usage_hint_text: nativeConfiguration.overrides.rootAgentUsageHintText, - subagent_usage_hint_text: nativeConfiguration.overrides.subagentUsageHintText, - multi_agent_mode_hint_text: nativeConfiguration.overrides.multiAgentModeHintText, - }, - 'agents.enabled': true, - 'features.goals': false, - 'features.defer_mailbox_preemption': nativeConfiguration.overrides.deferMailboxPreemption, + ...(useResponsesRelay ? { web_search: 'disabled' } : {}), } : {}), + ...(limitedProviderTools || managedTools ? { 'features.goals': false } : {}), model_reasoning_effort: options.effort, // The formalization sandbox is the OS boundary for isolated roles; every other shell runs the worker profile. ...(!isolated @@ -1510,15 +817,33 @@ async function openCodexMathSession( ...shellTemporaryPolicy, } : {}), + ...(enableSharedTeam + ? { + 'agents.enabled': true, + 'agents.max_depth': 1, + 'agents.max_threads': sharedTeam.capacity, + 'features.multi_agent': true, + 'features.multi_agent_v2': { + enabled: true, + max_concurrent_threads_per_session: sharedTeam.capacity, + multi_agent_mode_hint_text: + 'The user requests a flat team for this proof. Delegate independent work in the shared checkout. Assign each writable file to only one agent at a time.', + }, + } + : limitedProviderTools || managedTools + ? { + 'features.multi_agent': false, + 'features.multi_agent_v2': false, + ...(managedTools ? { 'agents.enabled': false } : {}), + } + : {}), ...providerSettings, }, }; - const bootstrap = options.nativeAgentControl?.bootstrap; // Codex restores history internally. Echoing it can exceed the stdio frame limit. // Retain historical usage replay for sessions that depend on native thread totals, unless the history // already failed to fit one frame; cumulative totals of the next turn still include the skipped replay. - const metadataOnlyResume = - forceMetadataOnlyResume || usesRequestReceipts || (nativeControl && !options.requestGate); + const metadataOnlyResume = forceMetadataOnlyResume || usesRequestReceipts; if (skills.some(skill => skill.loading === 'native')) { // Refresh discovery before the thread caches the skill list. const discovered = await rpc.request('skills/list', { cwds: [options.workspace], forceReload: true }); @@ -1526,13 +851,7 @@ async function openCodexMathSession( assertMathAgentSkillsCurrent(skills); options.signal?.throwIfAborted(); } - const request = threadDispatch( - options.threadId ?? '', - Boolean(metadataOnlyResume), - settings, - tools?.definitions, - bootstrap, - ); + const request = threadDispatch(options.threadId ?? '', metadataOnlyResume, settings, tools?.definitions); const result = await rpc.request(request.method, request.params).catch(error => { if ( options.threadId && @@ -1552,7 +871,6 @@ async function openCodexMathSession( providerId: providerId ?? null, isolated: Boolean(isolated), permissionProfile: MATH_WORKER_PERMISSION_PROFILE, - ...(bootstrap ? { member: { threadId: bootstrap.threadId, sessionId: bootstrap.sessionId } } : {}), }, result, ); @@ -1560,13 +878,6 @@ async function openCodexMathSession( const startedThreadId = object(result.thread).id; if (typeof startedThreadId !== 'string' || !startedThreadId) throw new Error('math_codex_thread_missing'); threadId = startedThreadId; - if ( - bootstrap && - (threadId !== bootstrap.threadId || - object(result.agentControl).sessionId !== bootstrap.sessionId || - object(object(result.agentControl).agent).threadId !== threadId) - ) - throw new Error('math_native_agent_control_child_binding_mismatch'); if (options.threadId && threadId !== options.threadId) throw new Error('math_codex_session_binding_mismatch'); if ( result.model !== options.model || @@ -1575,16 +886,7 @@ async function openCodexMathSession( ) throw new Error('math_codex_session_binding_mismatch'); if (providerId && result.modelProvider !== providerId) throw new Error('math_codex_session_binding_mismatch'); - // Native bootstrap intersects the captured authority with the destination math-worker profile. - // Upstream represents that intersection as a custom profile, without a named profile ID. - if (bootstrap) { - const effective = object(object(result.agentControl).configSnapshot); - if (effective.fullAccess !== false || object(effective.permissionProfile ?? {}).type !== 'managed') - throw new Error('math_codex_sandbox_profile_mismatch'); - } - // Ordinary new threads must still confirm the requested named sandbox profile. if ( - !bootstrap && !isolated && !options.threadId && object(result.activePermissionProfile ?? {}).id !== MATH_WORKER_PERMISSION_PROFILE @@ -1592,16 +894,10 @@ async function openCodexMathSession( throw new Error('math_codex_sandbox_profile_mismatch'); } options.signal?.throwIfAborted(); - if (nativeControl) - await nativeControl.bind( - result.agentControl ?? (await rpc.request('theoremos/agentControl/snapshot', { threadId })), - ); - const boundThreadId = threadId; let skillsDispatched = false; return { threadId, executionPlan, - nativeConfiguration, ...(isolated ? { isolationReceipt: isolated.receipt } : processLaunch @@ -1610,7 +906,6 @@ async function openCodexMathSession( ...(processIdentity ? { processIdentity } : {}), usageSource: usesRequestReceipts ? ('upstream-requests' as const) : ('native-thread-totals' as const), advisoryNotifications: 'native-history', - ...(nativeControl ? { nativeAgentControl: nativeControl.connection } : {}), get lastError() { return lastError; }, @@ -1626,14 +921,11 @@ async function openCodexMathSession( compact: async () => { options.signal?.throwIfAborted(); if (closing || transportFailure) throw transportFailure ?? new Error('math_codex_transport_closed:closing'); - if (completion || activeTurn || compacting) throw new Error('math_codex_turn_already_running'); + if (currentTurn || compacting) throw new Error('math_codex_turn_already_running'); const done = new Promise((resolve, reject) => { compacting = { resolve, reject }; }); - turnSettled = false; - turnStopping = false; - turnCheckpointReached = false; - requestTurn++; + startTurn(); const cancel = scheduleMathTimeout(() => { compacting?.reject(new Error('math_codex_compaction_timeout')); void closeSession(); @@ -1641,8 +933,7 @@ async function openCodexMathSession( const stop = () => compacting?.reject(new Error('math_codex_compaction_closed')); options.signal?.addEventListener('abort', stop, { once: true }); try { - const [, turn] = await Promise.all([rpc.request('thread/compact/start', { threadId }), done]); - if (nativeControl) await nativeControl.waitTurnSettled(String(turn.id), turn.status); + await Promise.all([rpc.request('thread/compact/start', { threadId }), done]); } catch (error) { await closeSession(); options.signal?.throwIfAborted(); @@ -1651,14 +942,14 @@ async function openCodexMathSession( cancel?.(); options.signal?.removeEventListener('abort', stop); compacting = undefined; - turnSettled = true; + turnPhase = 'settled'; } }, run: async (message, messageId, workspace, onStarted) => { lastCompletedResponse = undefined; options.signal?.throwIfAborted(); if (transportFailure) throw transportFailure; - if (completion || compacting) throw new Error('math_codex_turn_already_running'); + if (currentTurn || compacting) throw new Error('math_codex_turn_already_running'); if (priorBoundaryCheckpoint) message = 'Host continuation: the preceding turn ended at a settled request boundary for a checkpoint. ' + @@ -1673,7 +964,6 @@ async function openCodexMathSession( if (temporaryDirectory) prepareWorkerTemporaryDirectory(options.workspace); lastError = undefined; lastFailureDiagnostic = undefined; - turnEvidence = createTurnEvidence(); completedMessages.clear(); let resolve!: (turn: Json) => void; let reject!: (error: Error) => void; @@ -1683,287 +973,160 @@ async function openCodexMathSession( }); // Attach immediately so a transport failure during turn/start is handled. void done.catch(() => {}); - requestTurn++; - turnSettled = false; - turnStopping = false; - turnCheckpointReached = false; - boundTurn = new Promise(resolve => { - bindTurn = resolve; + startTurn(); + let bind!: (turnId?: string) => void; + const binding = new Promise(resolve => { + bind = resolve; }); - completion = { + const turn: ActiveTurn = { + binding, + bind, + evidence: createTurnEvidence(), resolve: turn => { - turnSettled = true; - tools?.cancel(); - cancelNotifications(); - publicItems.clear(); + endTurnInput('settled'); resolve(turn); }, reject: error => { - turnSettled = true; - tools?.cancel(); - cancelNotifications(); - publicItems.clear(); + endTurnInput('settled'); reject(error); }, }; + currentTurn = turn; lastStreamActivityAt = 0; outputTails.clear(); - publicItems.clear(); earlyActivities.clear(); - let checkpoint = false; - let boundaryCheckpoint = false; - let submitted = false; - let requestDrain: Promise | undefined; + let checkpoint: 'request' | 'tool' | 'timeout' | undefined; let interruptionRequested = false; let cancelTimer: (() => void) | undefined; let cancelCheckpointTimer: (() => void) | undefined; - let outputWatchId: string | undefined; - let checkOutput: ((allowFeedback?: boolean, stopped?: boolean, review?: boolean) => void) | undefined; - let submittedDigest: string | undefined; - let reviewedOutputDigest: string | undefined; let interruptDeadline: NodeJS.Timeout | undefined; try { - if (options.completedOutput) { - const file = path.resolve(options.completedOutput.file), - parent = path.dirname(file); - if (isolated && !isMathPathWithin(options.workspace, file)) - throw new Error('math_codex_output_watch_outside_workspace'); - assertMathCanonicalPath(parent); - fs.mkdirSync(parent, { recursive: true }); - assertMathCanonicalPath(parent); - const nativeFile = isolated ? path.join(isolated.workspace, path.relative(options.workspace, file)) : file; - outputWatchId = randomUUID(); - completedOutputWatch = { id: outputWatchId, file: nativeFile, changed: () => checkOutput?.() }; - // Watch the parent before starting the writer: the output may not - // exist yet, and atomic submissions replace the file's inode. - const watched = await rpc.request('fs/watch', { watchId: outputWatchId, path: path.dirname(nativeFile) }); - if (typeof watched.path !== 'string' || !path.isAbsolute(watched.path)) - throw new Error('math_codex_output_watch_path_missing'); - completedOutputWatch.file = path.join(watched.path, path.basename(nativeFile)); - if (options.completedOutput.reviewIncomplete) { - try { - reviewedOutputDigest = mathDigest(readMathText(file, 2_000_000)); - } catch { - // A prior diagnostic is optional. Only review new output from this turn. - } - } - } - const initialEnvelope = options.nativeAgentControl?.initialInput; + if (watchTurnOutput) turnOutput = await watchTurnOutput(() => checkpoint !== undefined, turn.reject); const started = await rpc.request( - initialEnvelope ? 'theoremos/agentControl/input' : 'turn/start', - initialEnvelope - ? memberInput(initialEnvelope, boundThreadId, message, !skillsDispatched, skillsDispatched ? [] : skills) - : nativeProcess - ? nativeProcess.codexTurnDispatch({ - threadId, - messageId, - cwd: isolated?.workspace ?? workspace, - model: options.model, - effort: options.effort, - message, - skills: skillsDispatched ? [] : skills, - isolated: Boolean(isolated), - ...(options.outputSchema ? { outputSchema: options.outputSchema } : {}), - }) - : { - threadId, - clientUserMessageId: messageId, - cwd: isolated?.workspace ?? workspace, - model: options.model, - effort: options.effort, - approvalPolicy: 'never', - ...(options.outputSchema ? { outputSchema: options.outputSchema } : {}), - ...(isolated ? { sandboxPolicy: { type: 'dangerFullAccess' } } : {}), - input: [ - { type: 'text', text: message, text_elements: [] }, - ...(!skillsDispatched - ? skills.map(skill => - skill.loading === 'native' - ? { type: 'skill', name: skill.name, path: skill.path } - : { - type: 'text', - text: `Use the frozen ${skill.name} research skill. Read ${JSON.stringify(skill.path)} before research and follow its relevant references on demand. This session uses explicit file loading, not native skill injection.`, - text_elements: [], - }, - ) - : []), - ], - }, + 'turn/start', + nativeProcess + ? nativeProcess.codexTurnDispatch({ + threadId, + messageId, + cwd: isolated?.workspace ?? workspace, + model: options.model, + effort: options.effort, + message, + skills: skillsDispatched ? [] : skills, + isolated: Boolean(isolated), + ...(options.outputSchema ? { outputSchema: options.outputSchema } : {}), + }) + : { + threadId, + clientUserMessageId: messageId, + cwd: isolated?.workspace ?? workspace, + model: options.model, + effort: options.effort, + approvalPolicy: 'never', + ...(options.outputSchema ? { outputSchema: options.outputSchema } : {}), + ...(isolated ? { sandboxPolicy: { type: 'dangerFullAccess' } } : {}), + input: [ + { type: 'text', text: message, text_elements: [] }, + ...(!skillsDispatched + ? skills.map(skill => + skill.loading === 'native' + ? { type: 'skill', name: skill.name, path: skill.path } + : { + type: 'text', + text: `Use the frozen ${skill.name} research skill. Read ${JSON.stringify(skill.path)} before research and follow its relevant references on demand. This session uses explicit file loading, not native skill injection.`, + text_elements: [], + }, + ) + : []), + ], + }, ); skillsDispatched = true; const turnId = object(started.turn).id; if (typeof turnId !== 'string' || !turnId) throw new Error('math_codex_turn_missing'); - activeTurn = turnId; - turnEvidence.bind(turnId); - bindTurn?.(turnId); + turn.id = turnId; + turn.evidence.bind(turnId); + turn.bind(turnId); // Replay pre-terminal activity before applying an early completion below. for (const entry of earlyActivities.get(turnId) ?? []) emitActivity(entry); earlyActivities.clear(); for (const [key, entry] of publicItems) { - if (entry.turnId !== activeTurn) publicItems.delete(key); + if (entry.turnId !== turnId) publicItems.delete(key); else publishPublicItem(entry); } const requestInterruption = () => { if (interruptionRequested) return; interruptionRequested = true; - turnStopping = true; - tools?.cancel(); - cancelNotifications(); - publicItems.clear(); + endTurnInput('stopping'); // A cleanup deadline after submission/cancellation is independent of solving budgets. interruptDeadline = setTimeout(() => { void closeSession(); }, 10_000); - void rpc.request('turn/interrupt', { threadId, turnId: activeTurn }).catch(() => { + void rpc.request('turn/interrupt', { threadId, turnId }).catch(() => { // A terminal event can precede this reply; a late rejection must not stop the next turn. - if (activeTurn === turnId && !turnSettled) void closeSession(); + if (currentTurn === turn && !isTurnSettled()) void closeSession(); }); }; const stopAfterRequests = () => { - turnStopping = true; - tools?.cancel(); - cancelNotifications(); - publicItems.clear(); - requestDrain ??= drainRequests(); - void requestDrain.then(() => { - if (activeTurn === turnId && !turnSettled && !closing) requestInterruption(); + endTurnInput('stopping'); + requests.drainThen(() => { + if (currentTurn === turn && !isTurnSettled() && !closing) requestInterruption(); }); }; - checkTurnCheckpoint = (atRequestBoundary = true) => { + checkTurnCheckpoint = boundary => { if ( checkpoint || - turnSettled || - turnStopping || + !isTurnRunning() || closing || !(turnCheckpointReached || options.requestGate?.checkpoint?.()) ) return false; // For relayed turns the unpaid request boundary confirms tools had a // chance to finish and save a valid output. - checkCompletedOutput?.(); - if (submitted || turnSettled || turnStopping || closing) return false; - checkpoint = true; - boundaryCheckpoint = atRequestBoundary; + turnOutput?.check(); + if (turnOutput?.submitted || !isTurnRunning() || closing) return false; + checkpoint = boundary; stopAfterRequests(); return true; }; - const early = earlyCompletions.get(activeTurn); - earlyCompletions.delete(activeTurn); - if (early) completion.resolve(early); + const early = earlyCompletions.get(turnId); + earlyCompletions.delete(turnId); + if (early) turn.resolve(early); // An explicit stop can arrive while turn/start still has no remote turn id. // Replay it after acknowledgement unless a terminal event already settled it. - if (turnStopping && !turnSettled && !closing) requestInterruption(); - onStarted(activeTurn); - if (options.completedOutput) { - // A file submission ends this role. Report it after the native turn - // settles; the caller still confirms process shutdown before acceptance. - checkOutput = (allowFeedback = true, stopped = false, review = allowFeedback) => { - if ((!stopped && (submitted || checkpoint)) || !activeTurn || options.signal?.aborted) return; - let outputText: string, value: unknown; - try { - const file = options.completedOutput!.file; - outputText = readMathText(file, 2_000_000); - // Validators may hand a candidate to the host exactly once. - // Recheck the accepted bytes after the writer has stopped, - // without repeating those submission side effects. - if (stopped && submitted) { - submitted = mathDigest(outputText) === submittedDigest; - return; - } - value = JSON.parse(outputText); - } catch { - if (stopped) submitted = false; - return; /* Missing, partial or unsafe files are not submissions. */ - } - try { - options.completedOutput!.validate(value); - } catch (error) { - const reviewIncomplete = options.completedOutput!.reviewIncomplete; - if (review && reviewIncomplete && !turnSettled && !turnStopping) { - const outputDigest = mathDigest(outputText); - if (outputDigest !== reviewedOutputDigest) { - reviewedOutputDigest = outputDigest; - const notice = reviewIncomplete(value, activeTurn); - if (notice) - void notify(notice, usesRequestReceipts ? { waitForRequest: true } : { mode: 'advisory' }).catch( - () => {}, - ); - } - } - const feedback = options.completedOutput!.validationFeedback; - if ( - !allowFeedback || - !feedback || - turnSettled || - turnStopping || - earlyCompletions.has(turnId) || - validationFeedbackPending - ) - return; - const outputDigest = mathDigest(outputText); - if (reportedInvalidOutputs.has(outputDigest)) return; - reportedInvalidOutputs.add(outputDigest); - let message: string; - try { - message = feedback(error, { text: outputText, turnId }); - } catch (cause) { - completion?.reject( - cause instanceof Error ? cause : new Error('math_codex_validation_feedback_failed'), - ); - return; - } - validationFeedbackPending = true; - // Repair feedback shares the paid-request settlement boundary with other - // notices. A turn may finish before delivery; don't affect a later run. - void notify(message) - .catch(() => {}) - .finally(() => { - validationFeedbackPending = false; - }); - return; - } - submitted = true; - submittedDigest = mathDigest(outputText); - // Stop new paid work first. Interrupting an in-flight request loses its final - // usage receipt, so let admitted requests settle before stopping the writer. - if (!turnSettled) stopAfterRequests(); - }; - // Admission has already passed beforeRequest's notification fence. Only - // accept valid submissions there. Review incomplete outputs before the fence. - checkCompletedOutput = (reviewIncomplete = false) => checkOutput?.(false, false, reviewIncomplete); - checkOutput(); - } + if (turnPhase === 'stopping' && !closing) requestInterruption(); + onStarted(turnId); + turnOutput?.bind(turnId, stopAfterRequests); + turnOutput?.check('watch'); if (options.turnCheckpointMs) cancelCheckpointTimer = scheduleMathTimeout(() => { // Keep the admitted response and its native tools alive. Admission // performs the handoff; natural completion or the hard deadline also // settles a turn which never asks for another request. - if (activeTurn !== turnId || turnSettled || turnStopping || closing) return; + if (currentTurn !== turn || !isTurnRunning() || closing) return; turnCheckpointReached = true; - cancelNotifications(); + requests.cancelNotifications(); }, options.turnCheckpointMs); if (options.turnTimeoutMs) cancelTimer = scheduleMathTimeout(() => { // Draining paid requests still consumes the existing turn allowance. - if (submitted && !activeRequests.size) return; - checkpoint = true; - boundaryCheckpoint = false; + if (turnOutput?.submitted && !requests.busy) return; + checkpoint = 'timeout'; // Only check sources after turn/completed confirms the writer stopped. requestInterruption(); }, options.turnTimeoutMs); const finished = await done; - await nativeControl?.waitTurnSettled(turnId, finished.status); await tools?.settled(); - await requestDrain; + await requests.drainCompletion; // Native watches are debounced and can be a noop on unsupported // hosts. Completion remains a deterministic final discovery boundary. - if (finished.status !== 'failed') checkOutput?.(false, true); + if (finished.status !== 'failed') turnOutput?.check('settled'); options.signal?.throwIfAborted(); if (typeof finished.status !== 'string') throw new Error('math_codex_turn_status_missing'); - const outcome = turnEvidence.outcome( + const outcome = turn.evidence.outcome( finished.status, - submitted, - checkpoint, + turnOutput?.submitted ?? false, + checkpoint !== undefined, Array.isArray(finished.items) && finished.items.some(isTurnOutputItem), ); if (outcome === 'empty') { @@ -1984,7 +1147,10 @@ async function openCodexMathSession( if (text !== undefined) lastCompletedResponse = { turnId, text }; } priorBoundaryCheckpoint = - boundaryCheckpoint && !externallyInterrupted && !submitted && finished.status === 'interrupted'; + checkpoint === 'request' && + !externallyInterrupted && + !turnOutput?.submitted && + finished.status === 'interrupted'; return outcome; } catch (error) { // A local evidence failure must stop the remote writer before callers can retry or inspect its files. @@ -1996,45 +1162,35 @@ async function openCodexMathSession( cancelTimer?.(); cancelCheckpointTimer?.(); clearTimeout(interruptDeadline); - completedOutputWatch = undefined; - if (outputWatchId && !closing && !transportFailure) - await rpc.request('fs/unwatch', { watchId: outputWatchId }).catch(() => closeSession().catch(() => {})); - checkCompletedOutput = undefined; + const outputWatch = turnOutput; + turnOutput = undefined; + if (outputWatch && !closing && !transportFailure) + await outputWatch.close().catch(() => closeSession().catch(() => {})); checkTurnCheckpoint = undefined; turnCheckpointReached = false; - drainTurnRequests = undefined; - turnSettled = true; - tools?.cancel(); + endTurnInput('settled'); await tools?.settled(); - cancelNotifications(); - bindTurn?.(); - bindTurn = undefined; - activeTurn = undefined; - completion = undefined; + turn.bind(); + currentTurn = undefined; earlyCompletions.clear(); - turnEvidence = undefined; outputTails.clear(); - publicItems.clear(); completedMessages.clear(); earlyActivities.clear(); } }, interrupt: async () => { externallyInterrupted = true; - turnStopping = true; - tools?.cancel(); - cancelNotifications(); - publicItems.clear(); - if (activeTurn && !turnSettled && !closing) - await rpc.request('turn/interrupt', { threadId, turnId: activeTurn }); + endTurnInput('stopping'); + const turnId = currentTurn?.id; + if (turnId && !isTurnSettled() && !closing) await rpc.request('turn/interrupt', { threadId, turnId }); }, - notify, + notify: requests.notify, close: closeSession, stopForFreeze: async () => { // An interrupt RPC acknowledgement does not settle the active turn. // Once closing, await shutdown instead: run and compact can await the // same shutdown before clearing their local turn state. - if (!closing && (completion || activeTurn || compacting || tools?.busy || nativeControl?.busy)) + if (!closing && (currentTurn || compacting || tools?.busy)) return { status: 'unconfirmed', reason: 'turn-not-settled' }; try { await closeSession(); @@ -2049,7 +1205,7 @@ async function openCodexMathSession( () => ({ ok: true }) as const, cause => ({ ok: false, cause }) as const, ); - if (nativeControl && processLaunch && (await rpc.confirmStopped().then(receipt => receipt.status !== 'stopped'))) + if (sharedTeam && processLaunch && (await rpc.confirmStopped().then(receipt => receipt.status !== 'stopped'))) throw new Error('math_codex_startup_shutdown_unconfirmed', { cause: error }); if (closeResult.ok === false) throw closeResult.cause; options.signal?.throwIfAborted(); diff --git a/src/runtime/codexTurnRequests.ts b/src/runtime/codexTurnRequests.ts new file mode 100644 index 00000000..8417dfe9 --- /dev/null +++ b/src/runtime/codexTurnRequests.ts @@ -0,0 +1,209 @@ +import type { MathAgentSession } from './agentSession'; +import type { CodexRpc } from './codexRpc'; +import type { ModelRequestGate } from './modelRequest'; + +type NotificationFence = { promise: Promise; release(): void; steered: boolean }; + +/** Coordinates request receipts and notices that need a boundary between paid requests. */ +export function createCodexTurnRequests(input: { + upstream?: ModelRequestGate; + running(): boolean; + noticeTurn(): string | undefined; + toolsBusy(): boolean; + checkpoint(): boolean | undefined; + reviewIncomplete: boolean; + checkOutput(mode?: 'review'): void; + request: CodexRpc['request']; +}) { + const activeRequests = new Set(); + let requestTurn = 0; + let notificationFence: NotificationFence | undefined; + let drain: { promise: Promise; resolve(): void } | undefined; + const requestGate: ModelRequestGate = identity => { + // A tool can submit and immediately request more model work before fs/changed arrives. + // Inspect that file synchronously before admitting another paid request. + if (input.running()) input.checkOutput(); + input.checkpoint(); + if (!input.running()) return { allowed: false, reason: 'math_model_request_stopped' }; + const admission = input.upstream?.(identity) ?? { allowed: true as const, settle: () => {} }; + if (!admission.allowed) return admission; + const request = {}; + activeRequests.add(request); + return { + allowed: true, + settle: receipt => { + if (!activeRequests.delete(request)) return; + try { + admission.settle(receipt); + } finally { + if (!activeRequests.size) drain?.resolve(); + flushNotifications(); + } + }, + }; + }; + requestGate.beforeRequest = async signal => { + const turn = requestTurn; + const assertCurrentTurn = () => { + signal.throwIfAborted(); + if (turn !== requestTurn || !input.running()) throw new Error('math_codex_notification_turn_settled'); + }; + assertCurrentTurn(); + if (input.checkpoint()) throw new Error('math_codex_turn_checkpoint'); + let deferredFence: NotificationFence | undefined; + await input.upstream?.beforeRequest?.(signal); + assertCurrentTurn(); + // The next request can arrive before the file watcher reports a completed Lean check. + if (input.reviewIncomplete) input.checkOutput('review'); + if (input.running() && [...notices].some(notice => notice.waitForRequest)) { + // A settled response may still be executing its submission tool. The next + // request proves those tools have finished; prefer their valid output to steer. + if (!input.reviewIncomplete) input.checkOutput(); + deferredFence = flushNotifications(true); + } + // A subsequent HTTP request may already be queued when steer is sent. Keep it outside + // provider admission until Codex acknowledges the notice, so steer cannot cancel paid work. + while (notificationFence) { + signal.throwIfAborted(); + const fence = notificationFence; + await new Promise((resolve, reject) => { + const abort = () => { + signal.removeEventListener('abort', abort); + reject(signal.reason ?? new Error('math_codex_request_aborted')); + }; + signal.addEventListener('abort', abort, { once: true }); + void fence.promise.then(() => { + signal.removeEventListener('abort', abort); + resolve(); + }); + }); + } + assertCurrentTurn(); + // This request predates the delivered instructions. Stdio acknowledgement can + // beat its HTTP cancellation; only a new request can carry the updated context. + if (deferredFence?.steered) throw new Error('math_codex_notification_request_superseded'); + }; + type Notice = { + message: string; + waitForRequest: boolean; + resolve(): void; + reject(error: Error): void; + }; + const notices = new Set(); + let notificationFlush: NodeJS.Immediate | undefined; + const releaseFence = (fence = notificationFence) => { + if (!fence) return; + if (notificationFence === fence) notificationFence = undefined; + fence.release(); + }; + const cancelNotifications = () => { + clearImmediate(notificationFlush); + notificationFlush = undefined; + for (const notice of notices) notice.reject(new Error('math_codex_notification_turn_settled')); + notices.clear(); + releaseFence(); + }; + const flushNotifications = (atRequest = false): NotificationFence | undefined => { + if (!notices.size || activeRequests.size || input.toolsBusy() || notificationFence) return; + const turnId = input.noticeTurn(); + if (!turnId || ![...notices].some(notice => !notice.waitForRequest || atRequest)) return; + const turn = requestTurn; + let release!: () => void; + const fence: NotificationFence = { + promise: new Promise(resolve => { + release = resolve; + }), + release: () => release(), + steered: false, + }; + notificationFence = fence; + // The bridge may settle accounting while writing its terminal event. Finish that write + // before sending input, while the fence already protects the next provider request. + notificationFlush = setImmediate(() => { + notificationFlush = undefined; + if (notificationFence !== fence) return; + if (requestTurn !== turn || input.noticeTurn() !== turnId) { + cancelNotifications(); + return; + } + // An admission already past its async transport hook may have won this same event-loop turn. + // Let that request finish and retry the notice at its settlement boundary. + if (activeRequests.size) { + releaseFence(fence); + return; + } + const batch = [...notices].filter(notice => !notice.waitForRequest || atRequest); + fence.steered = true; + const request = input.request('turn/steer', { + expectedTurnId: turnId, + input: batch.map(notice => ({ type: 'text', text: notice.message, text_elements: [] })), + }); + void request + .then( + () => { + for (const notice of batch) if (notices.delete(notice)) notice.resolve(); + }, + error => { + for (const notice of batch) if (notices.delete(notice)) notice.reject(error); + }, + ) + .finally(() => { + releaseFence(fence); + flushNotifications(); + }); + }); + return fence; + }; + const notify: NonNullable = async (message, notifyOptions) => { + if (!input.noticeTurn()) { + if (notifyOptions?.mode === 'advisory') throw new Error('math_codex_notification_turn_settled'); + if (notifyOptions?.waitForRequest === false) throw new Error('math_codex_notification_turn_settled'); + return; + } + if (notifyOptions?.mode === 'advisory') { + // History injection queues behind the current response and tools without + // starting a new turn if the current turn finishes during delivery. + await input.request('thread/inject_items', { + items: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: message }] }], + }); + return; + } + if (notifyOptions?.waitForRequest === false && (activeRequests.size || notificationFence)) + throw new Error('math_codex_notification_request_active'); + return new Promise((resolve, reject) => { + notices.add({ + message, + waitForRequest: notifyOptions?.waitForRequest === true, + resolve, + reject, + }); + flushNotifications(); + }); + }; + return { + gate: requestGate, + notify, + beginTurn() { + requestTurn++; + drain = undefined; + }, + cancelNotifications, + flushNotifications, + drainThen(afterDrain: () => void) { + if (drain) return; + let resolve!: () => void; + const promise = new Promise(done => { + resolve = done; + }); + drain = { promise, resolve }; + void promise.then(afterDrain); + if (!activeRequests.size) resolve(); + }, + get drainCompletion() { + return drain?.promise; + }, + get busy() { + return activeRequests.size > 0; + }, + }; +} diff --git a/src/runtime/nativeAgentControl.ts b/src/runtime/nativeAgentControl.ts deleted file mode 100644 index 1dfa5879..00000000 --- a/src/runtime/nativeAgentControl.ts +++ /dev/null @@ -1,270 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { createHash } from 'node:crypto'; -import { nativeProcess } from '../math/nativeProcess'; - -type Json = Record; - -export const NATIVE_AGENT_CONTROL_VERSION = 1 as const; -export const NATIVE_AGENT_CONTROL_REQUEST = 'theoremos/agentControl/request'; - -/** Actionable input feedback intended for the calling agent, unlike private host diagnostics. */ -export class NativeAgentControlInputError extends Error {} - -/** Requests originate in the native AgentControl implementation, never in a model tool. */ -export type NativeAgentControlRequest = Readonly<{ - version: 1; - sessionId: string; - threadId: string; - operationId: string; - operation: string; - payload: Json; -}>; - -export type NativeAgentControlConnection = Readonly<{ - /** Actual native identity and configuration returned by the idle child/root startup. */ - info?: Json; - request(method: string, params: Json): Promise; - update(params: Json): Promise; - input(params: Json): Promise; -}>; - -export type NativeAgentControlOptions = Readonly<{ - /** Captured by the parent Codex runtime; used only to create an idle native child. */ - bootstrap?: Json; - /** Native input envelope (author, input, startOptions), captured by Codex. */ - initialInput?: Json; - request( - request: NativeAgentControlRequest, - connection: NativeAgentControlConnection, - context: Readonly<{ signal: AbortSignal }>, - ): Promise; - connected?(connection: NativeAgentControlConnection): void | Promise; - bound?(connection: NativeAgentControlConnection): void | Promise; - disconnected?(connection: NativeAgentControlConnection): void | Promise; -}>; - -const object = (value: unknown): Json => { - if (!value || typeof value !== 'object' || Array.isArray(value)) - throw new Error('math_native_agent_control_invalid_message'); - return value as Json; -}; - -function sourceTurnCallback(params: Json): string | undefined { - if ( - params.version !== 1 || - ['sessionId', 'threadId', 'operationId', 'operation'].some(key => typeof params[key] !== 'string' || !params[key]) - ) - throw new Error('math_native_agent_control_invalid_message'); - const payload = object(params.payload); - const outcome = params.operation === 'turnFinished' ? object(payload.outcome) : undefined; - const nativeTurnId = outcome?.turnId ?? payload.turnId; - if ( - typeof nativeTurnId === 'string' && - ['admitTurn', 'turnFinished', 'releaseTurn'].includes(String(params.operation)) - ) - return nativeTurnId; -} - -function createTurnHandoff() { - if (nativeProcess) return new nativeProcess.TeamTurnHandoff(); - let admitted = false, - reported = false, - released = false; - return { - acknowledge(operation: string, reply: Json) { - if (operation === 'admitTurn') admitted = object(reply.result).admitted === true; - if (operation === 'turnFinished') reported = true; - if (operation === 'releaseTurn') released = true; - }, - ready(interrupted: boolean) { - return (interrupted || reported) && (!admitted || released); - }, - }; -} - -/** Owns the trusted stdio callbacks for one isolated writer process. */ -export class NativeAgentControl { - readonly connection: NativeAgentControlConnection; - private readonly abort = new AbortController(); - private readonly pending = new Set>(); - private disconnected = false; - private info?: Json; - private readonly turns = new Map< - string, - { handoff: ReturnType; error?: unknown; changed: Set<() => void> } - >(); - - constructor( - private readonly options: NativeAgentControlOptions, - request: (method: string, params: Json) => Promise, - ) { - const call = (method: string, params: Json) => - this.abort.signal.aborted - ? Promise.reject(new Error('math_native_agent_control_closed')) - : request(method, params); - const self = this; - this.connection = { - get info() { - return self.info; - }, - request: call, - update: params => call('theoremos/agentControl/update', { version: 1, ...params }), - input: params => call('theoremos/agentControl/input', { version: 1, ...params }), - }; - } - - get busy(): boolean { - return this.pending.size > 0; - } - - private turn(turnId: string) { - let turn = this.turns.get(turnId); - if (!turn) { - turn = { handoff: createTurnHandoff(), changed: new Set() }; - this.turns.set(turnId, turn); - } - return turn; - } - - /** Codex emits the terminal notification before reporting its outcome and dropping its guard. */ - async waitTurnSettled(turnId: string, status: unknown): Promise { - const turn = this.turn(turnId); - const ready = () => turn.handoff.ready(status === 'interrupted'); - const check = () => { - this.abort.signal.throwIfAborted(); - if (turn.error) throw turn.error; - }; - check(); - if (!ready()) - await new Promise((resolve, reject) => { - const finish = (error?: unknown) => { - clearTimeout(timer); - turn.changed.delete(changed); - this.abort.signal.removeEventListener('abort', aborted); - if (error) reject(error); - else resolve(); - }; - const changed = () => { - try { - check(); - if (ready()) finish(); - } catch (error) { - finish(error); - } - }; - const aborted = () => finish(this.abort.signal.reason); - // Transport cleanup deadline, not an inference allowance or mathematical task budget. - const timer = setTimeout(() => finish(new Error('math_native_agent_control_handoff_timeout')), 120_000); - turn.changed.add(changed); - this.abort.signal.addEventListener('abort', aborted, { once: true }); - changed(); - }); - this.turns.delete(turnId); - } - - async bind(info: unknown): Promise { - this.info = object(info); - await this.options.bound?.(this.connection); - } - - async initialize(): Promise { - let capabilities: Json; - try { - capabilities = await this.connection.request('theoremos/agentControl/capabilities', {}); - } catch (cause) { - throw new Error('math_native_agent_control_backend_required', { cause }); - } - if ( - capabilities.version !== 1 || - capabilities.backend !== 'theoremos-host' || - capabilities.nativeTools !== true || - capabilities.isolatedChildBootstrap !== true - ) - throw new Error('math_native_agent_control_backend_required'); - await this.options.connected?.(this.connection); - } - - call(params: Json): Promise { - if (this.abort.signal.aborted) return Promise.reject(new Error('math_native_agent_control_closed')); - let nativeTurnId: string | null | undefined; - try { - nativeTurnId = nativeProcess ? nativeProcess.teamTurnCallback(params) : sourceTurnCallback(params); - } catch (error) { - return Promise.reject(error); - } - const request = { ...params } as NativeAgentControlRequest; - const turn = nativeTurnId == null ? undefined : this.turn(nativeTurnId); - const result = Promise.resolve() - .then(() => { - this.abort.signal.throwIfAborted(); - return this.options.request(request, this.connection, { signal: this.abort.signal }); - }) - .then(object) - .then(value => { - turn?.handoff.acknowledge(request.operation, value); - return value; - }) - .then( - value => { - this.pending.delete(result); - if (turn) { - for (const changed of turn.changed) changed(); - } - return value; - }, - error => { - this.pending.delete(result); - if (turn) { - turn.error = error; - for (const changed of turn.changed) changed(); - } - throw error; - }, - ) - .finally(() => { - this.pending.delete(result); - }); - this.pending.add(result); - return result; - } - - stop(): void { - this.abort.abort(new Error('math_native_agent_control_closed')); - } - - async settled(): Promise { - await Promise.allSettled([...this.pending]); - if (this.disconnected) return; - this.disconnected = true; - await this.options.disconnected?.(this.connection); - } -} - -/** Enables host-backed tools in a disposable catalog without changing a frozen provider profile. */ -export function nativeAgentControlModelCatalog(catalogFile: string, model: string, directory: string): string { - const catalog = object(JSON.parse(fs.readFileSync(catalogFile, 'utf8'))); - if (!Array.isArray(catalog.models)) throw new Error('math_native_agent_control_model_catalog_invalid'); - let selected = false; - const projected = { - ...catalog, - models: catalog.models.map(value => { - const entry = object(value); - if (entry.slug !== model) return entry; - selected = true; - return { ...entry, multi_agent_version: 'v2' }; - }), - }; - if (!selected) throw new Error('math_native_agent_control_model_missing'); - const content = JSON.stringify(projected); - const digest = createHash('sha256').update(content).digest('hex'); - const file = path.join(directory, `agent-control-models-${digest}.json`); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - try { - fs.writeFileSync(file, content, { flag: 'wx', mode: 0o600 }); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; - if (fs.readFileSync(file, 'utf8') !== content) throw new Error('math_native_agent_control_model_catalog_changed'); - } - return file; -} diff --git a/src/runtime/providerProfile.ts b/src/runtime/providerProfile.ts index 9c76388e..5bd4308c 100644 --- a/src/runtime/providerProfile.ts +++ b/src/runtime/providerProfile.ts @@ -14,6 +14,24 @@ type ProviderProfile = { features?: Record; }; +function providerProfileDigest(directory: string, config = readMathText(path.join(directory, 'config.toml'))) { + return mathDigest( + canonicalMathJson({ + 'config.toml': config, + 'models.json': readMathText(path.join(directory, 'models.json')), + }), + ); +} + +export function selectedProviderProfile(directory: string, supportedProviders: readonly string[]) { + const configFile = path.join(directory, 'config.toml'); + if (!fs.existsSync(configFile)) return; + const config = readMathText(configFile); + const id = parseToml(config).model_provider; + if (typeof id !== 'string' || !supportedProviders.includes(id)) return; + return { id, profile: fs.realpathSync(directory), digest: providerProfileDigest(directory, config) }; +} + export function createProviderProfile(provider: ProviderProfile) { const files = (directory: string, model: string, effort: string) => { provider.validate(model, effort); @@ -49,21 +67,12 @@ export function createProviderProfile(provider: ProviderProfile) { }; const expectedDigest = (directory: string, model: string, effort: string) => mathDigest(canonicalMathJson(files(directory, model, effort))); - const digest = (directory: string) => - mathDigest( - canonicalMathJson( - Object.fromEntries( - ['config.toml', 'models.json'].map(name => [name, readMathText(path.join(directory, name))]), - ), - ), - ); return { expectedDigest, - digest, + digest: (directory: string) => providerProfileDigest(directory), selected(directory: string): { profile: string; digest: string } | undefined { - const configFile = path.join(directory, 'config.toml'); - if (!fs.existsSync(configFile) || parseToml(readMathText(configFile)).model_provider !== provider.id) return; - return { profile: fs.realpathSync(directory), digest: digest(directory) }; + const selected = selectedProviderProfile(directory, [provider.id]); + if (selected) return { profile: selected.profile, digest: selected.digest }; }, prepare(directory: string, model: string, effort: string): string { const contents = files(directory, model, effort); diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts deleted file mode 100644 index 9c73ff4b..00000000 --- a/src/solver/agentTeam.ts +++ /dev/null @@ -1,2510 +0,0 @@ -import { nextTeamMember } from './teamMemberSchedule'; -import fs from 'node:fs'; -import path from 'node:path'; -import crypto from 'node:crypto'; -import { z } from 'zod'; -import type { MathAgentSession, MathAgentTools } from '../runtime/agentSession'; -import { confirmHarnessProcessStopped } from '../runtime/harnessProcess'; -import { NativeAgentControlInputError } from '../runtime/nativeAgentControl'; -import { planApprovalStatus, publishNativeApprovalPlan } from './planApproval'; -import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { bindLeanPackages } from '../math/leanDiagnostics'; -import { inspectLeanSource, inspectScopedLeanDeclarations } from '../math/leanSource'; -import { leanNameWithoutRoot } from '../math/leanSyntax'; -import type { SolverRunState } from './archive'; -import type { WorkerAccess } from './research'; -import type { RuntimeSolverModules } from './modules/runtime'; -import { git, committedSource, commitSolverSources, SolverSourceError, withSolverWorktree } from './problem'; -import { solverSourceFeedback } from './feedback'; -import { prepareResearchSkill } from './researchSkill'; -import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext'; -import { - correctableDeclarationCheck, - DeclarationArtifactCheckError, - DeclarationSubmissionError, -} from './declarationArtifacts'; -import { solverSourceDigest } from './modules/evidence'; -import { writeOwnedDeclarationIndex } from './declarationIndex'; -import { recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter'; -import { prepareTacticBatteryFailureCacheRoot } from './tacticBatteryFailureCache'; -import { TACTIC_BATTERY_TIMEOUT_MS } from './tacticBattery'; -import { locateKnowledgeDeclaration } from './theoremKnowledge'; -import type { CooperativeTask } from './tasks'; -import { ResearchUsage } from './researchUsage'; -import { aggregateUsage, buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; -import { - agentTeamStateSchema, - type AgentTeamAdoptionDependency, - type AgentTeamState, - type AgentTeamWorker, - type AgentTeamTask, -} from './agentTeamState'; -import { AgentTeamOperations } from './agentTeamOperations'; -import { - checkAgentTeamProofDelivery, - integrateAgentTeamProofDelivery, - readAgentTeamProofDelivery, - MissingAdoptionDependencyError, - ReusedTeamCheckFailure, - type TeamFailureCache, -} from './agentTeamProof'; -import { ownedSourceDigest } from './cooperativeProof'; -import { saveAgentTeamResearchArtifact, inspectAgentTeamResearchArtifact } from './agentTeamResearch'; -import { agentTeamRouteSummary, agentTeamTaskHistory } from './agentTeamViews'; -import { agentTeamProfileSelection, resolveNewMemberProfiles, resolveAgentTeamProfiles } from './agentTeamProfiles'; -import { prepareWorkerProject, writeWorkerProject } from './workerProject'; -import { - agentTeamRequestSchema as request, - agentTeamToolDefinition as teamTool, - agentTeamArgumentFeedback, - agentTeamOperationAllowed, - legacyHelperSubmissionSchema, -} from './agentTeamTool'; -import type { ModelRequestGate } from '../runtime/modelRequest'; -import { LeanEnvironmentHealthCheckError } from '../runtime/leanHealthCheck'; -import { writeLibraryAccess } from './libraryAccess'; -import { prepareAgentTeamWorkspace } from './agentTeamWorkspace'; -import { - AgentTeamNativeControl, - nativeSpawnHistory, - nativeTeamAssignmentMessage, - type NativeTeamAcceptedChild, - type NativeTeamSpawn, -} from './agentTeamNative'; -import { IncrementalHelperRejection, landVerifiedHelpers } from './incrementalHelpers'; -import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; -import { portfolioRouteIdSchema, type RetiredRoute, type routeRetirementSchema } from './routeControl'; -import { researchLeanHealthCheck, researchToolRoots } from './researchToolGuide'; - -type LiveWorker = { - session?: MathAgentSession; - task: Promise; - abort: AbortController; - routeAbort: AbortController; - admittedTurnId?: string; - runSettled?: boolean; - readyNotice?: 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) { - if (state.researchDelegation?.mode !== 'team') return; - for (const record of [{ ...state, id: 'lead' }, ...(state.agentTeam?.workers ?? [])]) { - if (record.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + record.id); - if (record.writerProcess && confirmHarnessProcessStopped(record.writerProcess).status !== 'stopped') - throw new Error('math_writer_stop_unconfirmed:' + record.id + ':previous-process-active'); - } -} - -function followupObjective(task: AgentTeamTask, message: string): string { - const inherited = agentTeamProfileSelection(task.message); - return !inherited.length || agentTeamProfileSelection(message).length - ? message - : 'Profiles: ' + inherited.join(', ') + '\n' + message; -} - -function openRouteTask(task: AgentTeamTask) { - return ( - !task.cancelRequested && !task.deliveryId && ['queued', 'running', 'paused', 'interrupted'].includes(task.status) - ); -} - -function correctableSourceFailure(error: unknown) { - return ( - error instanceof SolverSourceError || (error instanceof Error && error.message === 'math_source_outside_ownership') - ); -} - -function correctableProofFailure(error: unknown) { - if (correctableSourceFailure(error)) return true; - if (error instanceof DeclarationSubmissionError) return true; - if (error instanceof DeclarationArtifactCheckError) return correctableDeclarationCheck(error); - 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 readonly operations: AgentTeamOperations; - private readonly nativeIdle = new Map(); - private readonly failedNominations: TeamFailureCache = new Map(); - private readonly nativeStarts = new Map< - string, - { - promise: Promise; - resolve: (value: NativeTeamAcceptedChild) => void; - reject: (error: unknown) => void; - accepted: boolean; - } - >(); - private readonly workspaces = new Map }>(); - private leadSession?: MathAgentSession; - private stopping = false; - private serial: Promise = Promise.resolve(); - private taskSequence = 0; - leadAdoptionCheckpoint = false; - leadCompletionCheckpoint = false; - - constructor( - private input: { - state: SolverRunState; - root: string; - taskText: string; - leadAccess: WorkerAccess; - modules: RuntimeSolverModules; - 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; - }, - ) { - if (input.state.agentTeam?.transport !== 'native-agent-control') - throw new Error('math_historical_team_requires_pinned_revision'); - this.archive = input.state.agentTeam; - this.directory = path.join(path.dirname(input.state.worktree), 'agent-team'); - fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 }); - fs.mkdirSync(path.join(path.dirname(input.state.worktree), 'team-workspaces'), { recursive: true, mode: 0o700 }); - agentTeamStateSchema.parse(this.archive); - this.operations = new AgentTeamOperations(this.archive.operations); - for (const worker of this.archive.workers) - for (const task of worker.tasks) this.taskSequence = Math.max(this.taskSequence, task.sequence ?? 0); - for (const worker of this.archive.workers) for (const task of worker.tasks) task.sequence ??= ++this.taskSequence; - this.archive.hostLimits = { - maxTurns: Number.isFinite(input.maxTurns) ? input.maxTurns : null, - maxTotalTokens: input.maxTotalTokens, - }; - this.refreshUsage(); - this.nativeControl = new AgentTeamNativeControl( - this.archive, - { - spawn: (request, signal) => this.spawnNative(request, signal), - followup: (worker, request, signal) => this.followupNative(worker, request, signal), - interrupt: worker => this.interruptNative(worker), - load: worker => this.loadNative(worker), - 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' && !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'; - this.input.save(); - }, - }, - () => this.input.save(), - this.operations, - ); - } - - get hiddenRoots() { - return [this.directory, path.join(path.dirname(this.input.state.worktree), 'team-workspaces')]; - } - get hasActiveWorkers() { - return this.live.size > 0; - } - nativeAgentControlOptions(actor = 'lead') { - return this.nativeControl.options(actor); - } - get reviewPlan() { - return Boolean(this.input.state.planApproval); - } - get mayStartProofWork() { - return !this.reviewPlan || planApprovalStatus(this.input.state) === 'approved'; - } - get leadSourceRecoveryPending() { - const { pendingResearchFreeze, pendingDeclarationCheck, pendingProofCheck } = this.input.state; - return Boolean(pendingResearchFreeze || pendingDeclarationCheck || pendingProofCheck); - } - - private assertNativePlanApproved() { - if (!this.mayStartProofWork) - throw new NativeAgentControlInputError( - 'math_team_plan_approval_required: Publish a route with theoremos_team publish_plan and wait for approval before dispatch.', - ); - } - setLeadSession(session?: MathAgentSession) { - this.leadSession = session; - if (session?.nativeConfiguration && this.archive.nativeControl) { - this.archive.nativeControl.rootRuntimeConfiguration = session.nativeConfiguration; - this.input.save(); - } - } - - leadWriterStopped() { - this.nativeControl.writerStopped('lead'); - } - - beginLeadTurn() { - this.leadAdoptionCheckpoint = false; - this.leadCompletionCheckpoint = false; - } - - /** Only proof handoffs interrupt Lead; Codex owns ordinary team orchestration. */ - leadRequestGate(base: ModelRequestGate): ModelRequestGate { - const gate: ModelRequestGate = identity => base(identity); - gate.beforeRequest = base.beforeRequest; - gate.checkpoint = () => { - if (base.checkpoint?.()) return true; - if ((this.input.state.requestUsageAccounting?.pendingRequests ?? 0) > 0) return false; - if (!this.mayStartProofWork && planApprovalStatus(this.input.state) === 'pending') return true; - if (this.archive.completionRequested) { - if (!this.leadCompletionCheckpoint) { - this.leadCompletionCheckpoint = true; - this.input.emit('team_completion_checkpoint', { requestedAt: this.archive.completionRequested.at }); - } - return true; - } - const adoptions = this.archive.adoptions.filter( - item => - item.targetId === 'lead' && - ['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; - this.input.emit('team_adoption_checkpoint', { adoptionIds: adoptions.map(item => item.id) }); - } - return true; - }; - return gate; - } - - refreshUsage() { - const { state } = this.input; - const records = [state, ...this.archive.workers]; - state.tokenBudget = buildTokenBudget(this.input.maxTotalTokens, records, state.tokenBudget?.enforcement); - state.teamUsage = aggregateUsage(records); - return state.tokenBudget; - } - - private event( - from: string | null, - to: string, - kind: AgentTeamState['events'][number]['kind'], - message: string, - extra: { - taskId?: string; - deliveryId?: string; - researchArtifactId?: string; - researchRevision?: number; - sourceTaskId?: string; - relatedTaskId?: string; - dispatchResearchRevision?: number; - objectiveRevision?: number; - progressId?: string; - } = {}, - ) { - const item = { - sequence: (this.archive.events.at(-1)?.sequence ?? 0) + 1, - from: from ?? 'host', - to, - kind, - at: Date.now(), - text: message.slice(0, 16000), - ...extra, - }; - this.archive.events.push(item); - this.input.save(); - this.input.emit('team_event', { ...item }); - // Saved events, including completion and checked deliveries, all use the - // native advisory queue. Amendments supply their effective context separately. - if (from !== to && kind !== 'completed' && kind !== 'interrupted') - void this.nativeControl - .advisory(from, to, 'Mathematical host update (advisory):\n' + canonicalMathJson(item), item.sequence) - .catch(() => {}); - return item; - } - - tools(actor = 'lead'): MathAgentTools { - const definition = teamTool(actor, this.reviewPlan); - return { - definitions: [definition], - call: async (name, args, context) => { - context.signal.throwIfAborted(); - if (name !== definition.name) throw new Error('math_team_tool_unknown'); - const parsed = - args && typeof args === 'object' && 'operation' in args && args.operation === 'submit_helpers' - ? legacyHelperSubmissionSchema.safeParse(args) - : request.safeParse(args); - if (!parsed.success) return agentTeamArgumentFeedback(actor, args, parsed.error, this.reviewPlan); - const received = parsed.data; - const operation = - received.operation === 'submit_helpers' - ? { ...received, operation: 'submit' as const, helpersOnly: true } - : received; - if (!agentTeamOperationAllowed(actor, operation.operation, this.reviewPlan)) - return { - ok: false, - error: 'math_team_native_operation_required', - hint: "Use an advertised mathematical host operation. Native collaboration tools manage this run's agent transport.", - }; - if (operation.operation === 'history') { - 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(received)); - // Serialize host operations that mutate shared evidence. - const apply = this.serial.then(async () => { - context.signal.throwIfAborted(); - const prior = this.operations.get(key); - if (prior) { - if (prior.digest !== digest) throw new Error('math_team_call_changed'); - if ( - operation.operation === 'inspect' && - operation.changeIndex !== undefined && - prior.result === 'read-fixed-delivery-page' - ) - return this.perform(actor, operation); - return prior.result; - } - let result: unknown; - try { - result = await this.perform(actor, operation); - } catch (error) { - result = { ok: false, error: error instanceof Error ? error.message : 'math_team_operation_failed' }; - } - // Successful pages can be replayed from the content-addressed delivery; avoid storing its whole source twice. - const fixedPage = - operation.operation === 'inspect' && - operation.changeIndex !== undefined && - result !== null && - typeof result === 'object' && - 'ok' in result && - result.ok === true; - this.operations.append({ key, digest, result: fixedPage ? 'read-fixed-delivery-page' : result }); - this.input.save(); - return result; - }); - this.serial = apply.catch(() => {}); - return apply; - }, - }; - } - - private worker(id: string) { - const worker = this.archive.workers.find(item => item.id === id); - if (!worker) throw new Error('math_team_agent_unknown:' + id); - 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 && (openRouteTask(task) || 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(openRouteTask)) { - 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.input.save(); - 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; - let resolve!: (value: NativeTeamAcceptedChild) => void, reject!: (error: unknown) => void; - const promise = new Promise((done, fail) => { - resolve = done; - reject = fail; - }); - // A fixture or a shutdown may observe failure before the initiating RPC starts awaiting. - void promise.catch(() => {}); - const pending = { promise, resolve, reject, accepted: false }; - this.nativeStarts.set(worker.id, pending); - return pending; - } - - private assertNativeDispatchOpen(signal: AbortSignal) { - if (this.stopping || this.input.signal.aborted) throw new Error('math_team_dispatch_stopped'); - signal.throwIfAborted(); - } - - private async waitNativeStart( - worker: AgentTeamWorker, - signal: AbortSignal, - provisional = false, - ): Promise { - const pending = this.nativeStarts.get(worker.id)!; - const abort = () => { - if (pending.accepted) return; - if (provisional) { - worker.status = 'stopped'; - for (const task of worker.tasks.filter(task => ['queued', 'running', 'paused'].includes(task.status))) { - task.cancelRequested = { at: Date.now(), reason: 'Native spawn cancelled before host acceptance.' }; - if (task.status !== 'running') { - task.status = 'cancelled'; - task.finishedAt = Date.now(); - } - } - } - this.live.get(worker.id)?.abort.abort(signal.reason); - this.input.save(); - }; - signal.addEventListener('abort', abort, { once: true }); - if (signal.aborted) abort(); - // A skipped launch has no worker finalizer to settle this promise. - if (!this.live.has(worker.id)) pending.reject(new Error('math_team_dispatch_stopped')); - try { - return await pending.promise; - } finally { - signal.removeEventListener('abort', abort); - this.nativeStarts.delete(worker.id); - } - } - - private async spawnNative(request: NativeTeamSpawn, signal: AbortSignal): Promise { - this.assertNativeDispatchOpen(signal); - this.assertNativePlanApproved(); - const { model, effort } = this.input.state; - const config = request.bootstrap.config as Record; - if (config.model !== model || config.reasoningEffort !== effort) - throw new NativeAgentControlInputError( - 'math_team_native_run_config_frozen: Retry spawn_agent with the same task_name and omit model and reasoning_effort to inherit the run configuration (' + - model + - ', ' + - effort + - ').', - ); - 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(message, undefined, routeId); - const seedCommit = git(this.input.state.worktree, ['rev-parse', 'HEAD']); - const spawnHistory = nativeSpawnHistory(request.bootstrap); - const worker: AgentTeamWorker = { - id, - role: 'researcher', - worktree: path.join(path.dirname(this.input.state.worktree), 'team-workspaces', id), - seedCommit, - status: 'preparing', - phase: 'prepared', - turns: 0, - tasks: [], - cursor: 0, - native: { - sessionId: request.sessionId, - threadId: request.threadId, - agentPath: request.agentPath, - parentThreadId: request.parentThreadId, - spawnOperationId: request.operationId, - spawnRequestDigest: request.requestDigest, - spawnHistory, - bootstrap: request.bootstrap, - initialInput: request.initialInput, - }, - }; - const parentExposures = this.archive.leadExposures ?? []; - const adopted = new Set(parentExposures.filter(item => item.kind === 'adopted').map(item => item.deliveryId)); - worker.exposures = parentExposures - .filter( - item => - item.kind === 'adopted' || - (spawnHistory === 'parent-history' && item.kind === 'inspected' && !adopted.has(item.deliveryId)), - ) - .map(item => ({ ...item, kind: item.kind === 'adopted' ? 'adopted' : 'possible-via-parent' })); - this.archive.workers.push(worker); - this.nativeStart(worker); - worker.tasks.push(task); - this.input.save(); - this.launch(worker); - return this.waitNativeStart(worker, signal, true); - } - - private async followupNative( - worker: AgentTeamWorker, - initialInput: Record, - signal: AbortSignal, - ): Promise { - this.assertNativeDispatchOpen(signal); - this.assertNativePlanApproved(); - const { message, routeId } = nativeTaskRoute( - nativeTeamAssignmentMessage(initialInput.input as Record), - ); - this.assertRouteAvailable(routeId); - if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); - if (worker.status === 'stopped') throw new Error('math_team_agent_stopped'); - const profiles = message.trimStart().startsWith('Profiles:') ? this.memberProfiles(message, worker) : undefined; - const active = this.live.get(worker.id); - if (active?.session && !active.runSettled && worker.native!.status === 'running' && worker.activity === 'running') { - 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 || 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.', - ); - if (task.pauseRequested) - throw new NativeAgentControlInputError( - 'math_team_native_member_busy: this member is handing off its draft. Give it a new assignment after the handoff settles.', - ); - const changedProfiles = - profiles && canonicalMathJson(profiles.evidence.selected) !== canonicalMathJson(task.profileEvidence?.selected); - // Preserve the attributed native message and codec. The receiver's frozen - // profile and its local reading paths accompany the very same turn input. - const result = await connection.input({ - threadId: worker.native!.threadId, - ...initialInput, - expectedTurnId: worker.native!.turnId, - ...(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.updateNativeFollowup(task, message, profiles?.evidence ?? task.profileEvidence); - const accepted = this.nativeControl.accepted(worker, active.session, worker.native!.turnId!); - return { ...accepted, submissionId: result.submissionId }; - } - // Keep the native operation queue available while the previous writer or Lean check settles. - if (active) - throw new NativeAgentControlInputError( - 'math_team_native_member_busy: ' + - worker.id + - ' is ' + - (worker.activity ?? worker.status) + - '. Continue other work or send an advisory message. Follow up after this member finishes.', - ); - await this.closeNativeIdle(worker); - this.assertNativeDispatchOpen(signal); - if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); - if ((worker.status as string) === 'stopped') throw new Error('math_team_agent_stopped'); - this.assertRouteAvailable(routeId); - // Integrating checked results can take minutes of Lean work. Do it without holding - // Lead's tool call, then tell Lead that this member is ready for the followup. - if (!worker.tasks.some(task => task.status === 'queued') && this.pendingIntegration(worker)) { - this.launch(worker); - const entry = this.live.get(worker.id); - if (entry) { - entry.readyNotice = true; - throw new NativeAgentControlInputError( - 'math_team_native_member_busy: ' + - worker.id + - ' is integrating checked results into its workspace. Continue other work. The host sends a message when this member is ready; then repeat this followup.', - ); - } - } - const saved = worker.tasks.findLast( - task => - ['paused', 'interrupted', 'queued'].includes(task.status) && - !task.cancelRequested && - !task.deliveryId && - (routeId === undefined || routeId === task.routeId), - ); - // There is one captured input per native writer. Do not replace it while - // a different queued task still needs it. - if (worker.tasks.some(task => task.status === 'queued' && task !== saved)) - throw new NativeAgentControlInputError( - 'math_team_native_assignment_queued: Continue the queued route before assigning different work to this member.', - ); - if (saved) { - this.assertRouteAvailable(saved.routeId); - const followup = followupObjective(saved, message); - if ( - saved.status === 'paused' && - saved.pauseRequested?.kind === 'handoff' && - saved.sourceCommit && - followup.trim() === saved.message.trim() && - saved.lastStartedSourceCommit === saved.sourceCommit && - git(worker.worktree, ['rev-parse', 'HEAD']) === saved.sourceCommit - ) - throw new NativeAgentControlInputError( - 'math_team_native_followup_unchanged: This member paused without a new draft. Adopt a needed result into their workspace, ' + - 'or give them a concrete next step with the new evidence or a different approach.', - ); - this.updateNativeFollowup(saved, followup, profiles?.evidence); - saved.pauseRequested = undefined; - saved.status = 'queued'; - saved.error = undefined; - } else worker.tasks.push(this.newTask(message, profiles?.evidence, routeId)); - worker.native!.initialInput = initialInput; - this.input.save(); - this.nativeStart(worker); - this.launch(worker); - return this.waitNativeStart(worker, signal); - } - - /** Host work the next writer launch must finish before the member's turn can start. */ - private pendingIntegration(worker: AgentTeamWorker) { - if (worker.pendingDelivery || worker.tasks.some(task => task.helperSubmission)) return true; - if ( - this.archive.adoptions.some( - item => item.targetId === worker.id && ['queued', 'integrating'].includes(item.status), - ) - ) - return true; - const helpers = this.helperAdoptions(worker.id, worker.worktree); - return helpers.canReadDraft() && (helpers.untried.length > 0 || helpers.readyInDraft().length > 0); - } - - /** Native input is the instruction source; retain it for isolated-workspace resume. */ - private updateNativeFollowup(task: AgentTeamTask, message: string, evidence?: AgentTeamTask['profileEvidence']) { - const nextMessage = followupObjective(task, message); - const nextEvidence = - evidence ?? - resolveAgentTeamProfiles(this.input.leadAccess.researchSkill!, nextMessage, this.expertCards).evidence; - (task.objectiveHistory ??= []).push({ - revision: task.objectiveRevision ?? 1, - message: task.message, - workKind: task.workKind, - at: Date.now(), - reason: 'Native followup.', - profileEvidence: task.profileEvidence, - }); - task.message = nextMessage; - task.objectiveRevision = (task.objectiveRevision ?? 1) + 1; - task.profileEvidence = nextEvidence; - } - - private async interruptNative(worker: AgentTeamWorker) { - const entry = this.live.get(worker.id); - if (entry) { - entry.abort.abort(new Error('math_team_native_interrupted')); - await entry.session?.interrupt().catch(() => {}); - } - await this.closeNativeIdle(worker); - } - - private async closeNativeIdle(worker: AgentTeamWorker) { - const session = this.nativeIdle.get(worker.id); - if (!session) return; - await stopProofWriter({ - session, - record: worker, - workerId: worker.id, - close: async () => { - await session.close(); - this.nativeIdle.delete(worker.id); - }, - save: () => this.input.save(), - deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }), - confirmed: reason => this.input.emit('team_writer_stop_confirmed', { workerId: worker.id, reason }), - }); - this.nativeControl.writerStopped(worker.id); - worker.writerProcess = undefined; - this.input.save(); - } - - 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'); - if (!worker.threadId) throw new Error('math_team_native_child_not_bound'); - const access = this.workspaces.get(worker.id)?.access ?? (await this.prepare(worker)); - if (this.live.has(worker.id)) throw new Error('math_team_native_member_busy'); - if ((worker.status as string) === 'stopped') throw new Error('math_team_agent_stopped'); - const { state } = this.input; - const task = worker.tasks.at(-1)!; - const sourceCommit = git(worker.worktree, ['rev-parse', 'HEAD']); - const context = buildSkillResearchContext( - state.problem, - { ...state, ...worker, check: undefined }, - { - ...access, - root: this.input.root, - tools: this.input.modules.M4.tools, - worktree: worker.worktree, - taskText: this.input.taskText, - researchSkill: access.researchSkill!, - teamRole: { id: worker.id, role: 'worker' }, - teamAssignment: { taskId: task.id, message: task.message, sourceCommit }, - sourceFeedback: this.sourceFeedback(worker), - }, - ); - access.assertHarnessCurrent?.(); - access.assertKnowledgeCurrent?.(); - const session = await this.input.modules.M1.open({ - executable: this.input.executable, - profile: this.input.profile, - workspace: worker.worktree, - proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative), - model: state.model, - effort: state.effort, - threadId: worker.threadId, - environment: { - ...access.environment, - DEEPSCIENTIST_MATH_WORKER_ID: worker.id, - DEEPSCIENTIST_MATH_WORKER_WORKTREE: worker.worktree, - }, - skills: [access.researchSkill!], - tools: this.tools(worker.id), - nativeAgentControl: this.nativeAgentControlOptions(worker.id), - hiddenRoots: [ - prepareTacticBatteryFailureCacheRoot(), - this.directory, - state.worktree, - git(state.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir']), - ], - readableRoots: researchToolRoots(this.input.root, this.input.modules.M4.tools), - isolatedWorkspaceParent: path.dirname(worker.worktree), - isolateProcess: true, - instructions: context.instructions, - signal: this.input.signal, - onUsage: () => { - throw new Error('math_team_native_idle_usage'); - }, - }).catch(error => { - recordUnconfirmedWriterStartup(worker, error, () => this.input.save()); - throw error; - }); - this.nativeIdle.set(worker.id, session); - if (worker.native && session.nativeConfiguration) worker.native.runtimeConfiguration = session.nativeConfiguration; - worker.writerProcess = session.processIdentity; - this.input.save(); - if ((worker.status as string) === 'stopped') await this.closeNativeIdle(worker); - } - - private async perform(actor: string, operation: z.infer): Promise { - if (this.stopping || this.input.signal.aborted) throw new Error('math_team_stopped'); - if (!this.mayStartProofWork && ['adopt', 'finish', 'retire_route'].includes(operation.operation)) - this.assertNativePlanApproved(); - switch (operation.operation) { - case 'publish_plan': - if (!this.reviewPlan) throw new Error('math_plan_approval_not_required'); - return publishNativeApprovalPlan(this.input.state, operation, this.input.save, this.input.emit); - case 'finish': { - this.archive.completionRequested = { at: Date.now(), summary: operation.summary }; - this.input.save(); - return { - ok: true, - status: 'pending-writer-stop', - originalProblemAcceptance: 'not-assessed', - instruction: - 'Sources and notes should already be saved. Return now. The host also checkpoints before the next model request, confirms writer shutdown, freezes sources and independently checks all original targets.', - }; - } - case 'yield': { - if (actor === 'lead') throw new Error('math_team_child_operation_required'); - const worker = this.worker(actor), - task = worker.tasks.find(task => task.status === 'running'); - if (!task || task.cancelRequested || !this.live.has(actor)) throw new Error('math_team_task_not_running'); - if (task.declarations) throw new Error('math_team_submission_pending'); - task.pauseRequested ??= { at: Date.now(), kind: 'handoff', reason: operation.reason }; - this.input.save(); - return { - ok: true, - taskId: task.id, - status: 'pending-writer-stop', - instruction: - 'Save your draft and notes, then return. Lead can adopt needed results and resume this same task after writer shutdown.', - }; - } - case 'inspect-research': { - const reference = this.archive.researchArtifacts?.find(item => item.id === operation.artifactId); - if (!reference) throw new Error('math_team_research_unknown'); - return { - ok: true, - ...inspectAgentTeamResearchArtifact({ - reference: { - id: reference.id, - agentId: reference.agentId, - taskId: reference.taskId, - commit: reference.commit, - path: reference.path, - }, - state: this.input.state, - offset: operation.offset, - limit: operation.limit, - }), - }; - } - case 'inspect': { - const reference = this.archive.deliveries.find(item => item.id === operation.deliveryId); - if (!reference) throw new Error('math_team_delivery_unknown'); - const delivery = readAgentTeamProofDelivery(reference.path, this.input.state); - if ( - delivery.id !== reference.id || - delivery.agentId !== reference.agentId || - (delivery.provenance?.taskId && delivery.provenance.taskId !== reference.taskId) - ) - throw new Error('math_team_delivery_identity_changed'); - if (operation.changeIndex === undefined && (operation.offset !== undefined || operation.limit !== undefined)) - throw new Error('math_team_inspect_change_index_required'); - const page = (index: number, offset = 0, limit = 16000) => { - const change = delivery.changes[index]; - if (!change) throw new Error('math_team_inspect_change_index_out_of_range'); - const characters = Array.from(change.after); - if (offset > characters.length) throw new Error('math_team_inspect_offset_out_of_range'); - const end = Math.min(offset + limit, characters.length); - return { - file: change.file, - name: change.name, - changeIndex: index, - offset, - totalCharacters: characters.length, - source: characters.slice(offset, end).join(''), - truncated: end < characters.length, - ...(end < characters.length ? { nextOffset: end } : {}), - }; - }; - if (operation.changeIndex !== undefined) { - const change = page(operation.changeIndex, operation.offset, operation.limit); - this.recordExposure(actor, reference, delivery.commit, 'inspected'); - return { - ok: true, - id: delivery.id, - commit: delivery.commit, - sourceDigest: delivery.sourceDigest, - change, - originalProblemAcceptance: 'not-assessed', - }; - } - this.recordExposure(actor, reference, delivery.commit, 'inspected'); - return { - ok: true, - id: delivery.id, - agentId: delivery.agentId, - taskId: reference.taskId, - commit: delivery.commit, - seedCommit: delivery.seedCommit, - sourceDigest: delivery.sourceDigest, - provenance: delivery.provenance, - declarations: delivery.declarations, - imports: delivery.imports, - changes: delivery.changes.map((_, index) => page(index)), - artifacts: delivery.artifacts.map(artifact => ({ - id: artifact.id, - declaration: artifact.declaration, - proof: artifact.proof, - })), - originalProblemAcceptance: 'not-assessed', - }; - } - case 'submit': { - 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 || task.helperSubmission) throw new Error('math_team_submission_pending'); - const outside = operation.declarations.filter( - declaration => !this.input.state.problem.ownedFiles.includes(declaration.file), - ); - if (outside.length) - return { - ok: false, - error: 'math_agent_team_proof_declaration_outside_ownership', - rejectedFiles: [...new Set(outside.map(declaration => declaration.file))], - 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.helpersOnly) { - task.helperSubmission = operation.declarations; - task.summary = operation.summary; - task.pauseRequested = { - at: Date.now(), - kind: 'handoff', - reason: 'Standalone helper handoff. The assignment remains open.', - }; - this.input.save(); - return { - ok: true, - status: 'pending-writer-stop', - taskId: task.id, - instruction: - 'Save source and notes, then return. The host verifies standalone helpers and the assignment can resume afterward.', - }; - } - task.nomination = { - objectiveRevision: task.objectiveRevision ?? 1, - objectiveDigest: mathDigest(task.message), - workKind: task.workKind, - }; - task.declarations = operation.declarations; - task.summary = operation.summary; - this.input.save(); - return { - ok: true, - status: 'pending-writer-stop', - taskId: task.id, - instruction: - 'Save source and notes, then return. The host checks declarations after confirming writer shutdown.', - }; - } - case 'adopt': { - const targetId = operation.targetId ?? 'lead'; - if (!this.archive.deliveries.some(item => item.id === operation.deliveryId)) - throw new Error('math_team_delivery_unknown'); - const previous = this.archive.adoptions.find( - item => item.deliveryId === operation.deliveryId && item.targetId === targetId && item.status !== 'failed', - ); - if (previous) { - if (targetId !== 'lead' && previous.status !== 'completed') this.launch(this.worker(targetId)); - return { ok: true, adoption: previous }; - } - if (targetId !== 'lead' && this.live.has(targetId)) throw new Error('math_team_target_writing'); - if (targetId !== 'lead') { - const target = this.worker(targetId); - if (target.status === 'stopped') throw new Error('math_team_agent_stopped'); - if (target.pendingDelivery) throw new Error('math_team_target_delivery_pending'); - } - const adoption = { - id: crypto.randomUUID(), - deliveryId: operation.deliveryId, - targetId, - status: 'queued' as const, - }; - this.archive.adoptions.push(adoption); - this.input.save(); - if (targetId !== 'lead') this.launch(this.worker(targetId)); - return { - ok: true, - adoption, - ...(targetId === 'lead' - ? { - instruction: - 'Sources and notes should already be saved. Return now; the host also releases your writer before the next model request, checks and integrates this delivery, then continues your saved thread.', - } - : {}), - }; - } - case 'retire_route': { - const { operation: _operation, ...retirement } = operation; - return this.retireRoute(retirement); - } - default: - throw new Error('math_team_operation_invalid'); - } - } - - private get expertCards() { - const delegation = this.input.state.researchDelegation; - return delegation?.mode === 'team' ? delegation.personalExperts?.cards : undefined; - } - private memberProfiles(message: string, worker?: AgentTeamWorker) { - const skill = - (worker && this.workspaces.get(worker.id)?.access?.researchSkill) ?? this.input.leadAccess.researchSkill!; - return resolveNewMemberProfiles(skill, message, this.expertCards); - } - - private newTask( - message: string, - profileEvidence = this.memberProfiles(message).evidence, - routeId?: string, - ): AgentTeamTask { - this.assertRouteAvailable(routeId); - return { - id: crypto.randomUUID(), - message, - status: 'queued', - createdAt: Date.now(), - turns: 0, - objectiveRevision: 1, - routeId, - profileEvidence, - sequence: ++this.taskSequence, - }; - } - - private recordExposure( - actor: string, - reference: AgentTeamState['deliveries'][number], - commit: string, - kind: 'inspected' | 'adopted', - ) { - if (reference.agentId === actor) return; - const exposures = actor === 'lead' ? (this.archive.leadExposures ??= []) : (this.worker(actor).exposures ??= []); - if (!exposures.some(item => item.deliveryId === reference.id && item.kind === kind)) { - exposures.push({ - deliveryId: reference.id, - agentId: reference.agentId, - taskId: reference.taskId, - commit, - kind, - at: new Date().toISOString(), - }); - } - } - - private prepareWorkspace(worker: AgentTeamWorker) { - const existing = this.workspaces.get(worker.id); - if (existing) return existing; - prepareAgentTeamWorkspace({ - sourceWorktree: this.input.state.worktree, - worktree: worker.worktree, - seedCommit: worker.seedCommit, - migrationDirectory: path.join(this.directory, 'workspace-migrations'), - }); - const workspace: { access?: WorkerAccess; preparation?: Promise } = {}; - this.workspaces.set(worker.id, workspace); - return workspace; - } - - private prepare(worker: AgentTeamWorker): Promise { - const workspace = this.prepareWorkspace(worker); - return (workspace.preparation ??= this.prepareAccess(worker).then( - access => { - workspace.access = access; - return access; - }, - error => { - workspace.preparation = undefined; - throw error; - }, - )); - } - - private async prepareAccess(worker: AgentTeamWorker): Promise { - const { state, leadAccess } = this.input; - let access: WorkerAccess; - if (this.input.prepareWorker) access = await this.input.prepareWorker(worker.id, worker.worktree); - else { - const project = prepareWorkerProject(worker.worktree, state.problem); - const packages = path.join(state.worktree, state.problem.projectRelative, '.lake/packages'); - if (fs.existsSync(packages)) bindLeanPackages(project, packages); - const skill = prepareResearchSkill(this.input.root, worker.worktree, state.researchSkill!, state.problem); - access = { ...leadAccess, researchSkill: skill, retrievalRoot: project }; - } - if (access.libraryCatalog) writeLibraryAccess(state.problem, worker.worktree, access.libraryCatalog, false); - writeWorkerProject(worker.worktree, state.problem.projectRelative); - return access; - } - - /** Invalid drafts stay editable; only stopped-writer source checks can admit them as evidence. */ - private sourceFeedback(worker: AgentTeamWorker): string | undefined { - const feedback = solverSourceFeedback(this.input.state.problem, worker.worktree); - if (!feedback) return; - return ( - feedback + - '\n' + - 'The source draft and RESEARCH.md remain in this member workspace. They were not archived as checked evidence. ' + - 'Lead can assign a correction to this same member. Preserve the draft and notes; repair the source and submit a new nomination.' - ); - } - - private rejectSubmission(worker: AgentTeamWorker, task: AgentTeamTask, error: unknown) { - const reason = correctableSourceFailure(error) - ? (this.sourceFeedback(worker) ?? (error as Error).message) - : error instanceof Error - ? error.message - : 'math_team_delivery_failed'; - const pending = worker.pendingDelivery; - if ( - error instanceof DeclarationArtifactCheckError && - pending?.taskId === task.id && - pending.commit && - pending.sourceDigest - ) { - task.failedCheck = { - declaration: error.declaration, - seedCommit: pending.seedCommit, - commit: pending.commit, - sourceDigest: pending.sourceDigest, - problemReceiptDigest: this.input.state.problem.receiptDigest, - environmentDigest: this.input.state.environmentDigest, - objectiveRevision: task.nomination?.objectiveRevision, - projectionCommit: error.verification.targetCommit, - ...(error instanceof ReusedTeamCheckFailure && { reusedFrom: error.previous }), - status: error.verification.status, - results: error.verification.results.map( - ({ checkId, receiptId, status, error, stdoutPreview, stderrPreview }) => ({ - checkId, - receiptId, - status, - error, - stdoutPreview, - stderrPreview, - }), - ), - }; - } - 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'; - worker.error = undefined; - this.input.save(); - } - - 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, routeAbort: new AbortController(), task: undefined as unknown as Promise }; - this.live.set(worker.id, entry); - entry.task = Promise.resolve() - .then(async () => { - const access = await this.prepare(worker); - await this.flushHelperSubmissions(worker); - if (worker.pendingDelivery) await this.finishDelivery(worker); - await this.flushAdoptions(worker.id); - for (;;) { - const step = nextTeamMember({ - stopped: this.stopping || abort.signal.aborted || worker.status === 'stopped', - tasks: worker.tasks.map(task => task.status), - budget: this.input.state.tokenBudget!.status, - turnsLeft: this.input.state.turns < this.input.maxTurns, - timeLeft: this.input.remainingMs() > 0, - }); - if (step.action === 'stop') break; - const task = worker.tasks[step.index]!; - if (step.action === 'pause') { - this.pauseForBudget(worker, task, step.reason); - break; - } - await this.flushAdoptions(worker.id); - await this.runTask(worker, task, entry, access); - } - }) - .catch(error => { - if (!this.stopping && !abort.signal.aborted) { - if (error instanceof LeanEnvironmentHealthCheckError) - this.input.emit('lean_environment_unavailable', { workerId: worker.id, health: error.health }); - worker.status = 'failed'; - worker.error = error instanceof Error ? error.message : 'math_team_worker_failed'; - this.event(worker.id, 'lead', 'failed', worker.error); - } - }) - .finally(() => { - const pending = this.nativeStarts.get(worker.id); - const firstTask = worker.tasks[0]; - if ( - pending && - !pending.accepted && - worker.native && - !worker.native.submissionId && - !worker.writerStopUnconfirmed && - (worker.status === 'failed' || firstTask.status === 'failed') - ) { - worker.status = 'stopped'; - worker.activity = 'idle'; - firstTask.status = 'failed'; - firstTask.error ??= worker.error ?? 'math_team_native_start_failed'; - firstTask.finishedAt ??= Date.now(); - } - pending?.reject(new Error(worker.error ?? 'math_team_native_start_failed')); - this.live.delete(worker.id); - this.input.save(); - if ( - entry.readyNotice && - !this.stopping && - !this.input.signal.aborted && - !['failed', 'stopped'].includes(worker.status) && - !worker.writerStopUnconfirmed && - !this.pendingIntegration(worker) - ) - this.event( - null, - 'lead', - 'message', - worker.id + ' finished integrating checked results and is ready. Repeat the followup to assign its work.', - ); - // Per-task interruption consumes this controller. Reuse the member only after runTask has - // confirmed shutdown and saved its draft; a global stop or quarantine must never relaunch it. - if ( - entry.routeAbort.signal.aborted && - worker.tasks.some(task => task.status === 'queued') && - modelDispatchAllowed(this.input.state.tokenBudget!) && - this.input.remainingMs() > 0 && - this.input.state.turns < this.input.maxTurns - ) - this.launch(worker); - }); - } - - private async runTask( - worker: AgentTeamWorker, - task: AgentTeamTask, - entry: Pick, - access: WorkerAccess, - ) { - entry.admittedTurnId = undefined; - entry.runSettled = false; - await this.closeNativeIdle(worker); - const { state } = this.input; - const signal = AbortSignal.any([this.input.signal, entry.abort.signal]); - if (signal.aborted || task.status !== 'queued' || task.cancelRequested) return; - this.assertRouteAvailable(task.routeId); - access.assertHarnessCurrent?.(); - access.assertKnowledgeCurrent?.(); - if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); - const sourceFeedback = this.sourceFeedback(worker); - const sourceCommit = sourceFeedback - ? git(worker.worktree, ['rev-parse', 'HEAD']) - : commitSolverSources(state.problem, worker.worktree); - // A corrected or deferred delivery still includes the draft written in earlier assignments. - worker.pendingSourceBase ??= sourceCommit; - task.seedCommit = worker.pendingSourceBase; - task.lastStartedSourceCommit = sourceCommit; - task.status = 'running'; - task.startedAt ??= Date.now(); - task.lastStartedAt = Date.now(); - task.finishedAt = undefined; - task.summary = undefined; - task.error = undefined; - task.declarations = undefined; - task.nomination = undefined; - worker.status = 'running'; - worker.activity = 'running'; - worker.phase = 'running'; - worker.error = undefined; - task.objectiveRevision ??= 1; - task.profileEvidence = resolveAgentTeamProfiles(access.researchSkill!, task.message, this.expertCards).evidence; - initializeUsageAccounting(worker); - this.refreshUsage(); - this.input.save(); - const usage = new ResearchUsage({ - state, - research: worker, - signal, - remainingMs: this.input.remainingMs, - changed: () => { - this.refreshUsage(); - this.input.save(); - }, - emit: (event, details) => this.input.emit(event, { ...details, workerId: worker.id }), - }); - const sessionId = crypto.randomUUID(); - const callbacks = usage.bindSession(sessionId, () => entry.session?.lastInputTokens); - 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 with helpersOnly:true 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 = callbacks.requestGate!(identity); - if ( - admission.allowed === false && - (admission.reason === 'math_model_usage_unavailable' || admission.reason === 'math_total_token_limit') - ) { - task.pauseRequested ??= { at: Date.now(), kind: 'budget', reason: admission.reason }; - this.input.save(); - } - return admission; - }; - requestGate.beforeRequest = callbacks.requestGate?.beforeRequest; - 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'; - }; - const teamRole = { id: worker.id, role: 'worker' as const }; - const teamAssignment = { taskId: task.id, message: task.message, sourceCommit }; - const turnTiming = teamTurnTiming(this.input.maxTurnMs); - const context = buildSkillResearchContext( - state.problem, - { ...state, ...worker, check: undefined }, - { - ...access, - root: this.input.root, - tools: this.input.modules.M4.tools, - worktree: worker.worktree, - taskText: this.input.taskText, - researchSkill: access.researchSkill!, - teamRole, - teamAssignment, - sourceFeedback, - executionLimits: { ...turnTiming, remainingRunMs: this.input.remainingMs }, - }, - ); - writeOwnedDeclarationIndex(state.problem, worker.worktree); - const tools = this.tools(worker.id); - const nativeOptions = this.nativeAgentControlOptions(worker.id); - if (nativeOptions?.bootstrap) - nativeOptions.bootstrap.hostOverrides = { - ...(nativeOptions.bootstrap.hostOverrides as Record | undefined), - cwd: worker.worktree, - developerInstructions: context.instructions, - dynamicTools: tools.definitions.map(definition => ({ type: 'function', ...definition })), - workspaceRelocation: { - from: (nativeOptions.bootstrap.config as Record).cwd, - to: worker.worktree, - }, - }; - let completed = false, - started = false, - reserved = false, - writerStopped = false; - let outcome: 'completed' | 'failed' | 'interrupted' = 'interrupted'; - try { - if ( - !modelDispatchAllowed(state.tokenBudget!) || - this.input.remainingMs() <= 0 || - state.turns >= this.input.maxTurns - ) - throw new Error('math_team_dispatch_stopped'); - state.turns++; - worker.turns++; - reserved = true; - this.refreshUsage(); - this.input.save(); - entry.session = await this.input.modules.M1.open({ - executable: this.input.executable, - profile: this.input.profile, - workspace: worker.worktree, - proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative), - leanHealthCheck: researchLeanHealthCheck( - this.input.root, - path.join(worker.worktree, state.problem.projectRelative), - this.input.modules.M4.tools, - ), - model: state.model, - effort: state.effort, - threadId: worker.threadId, - environment: { - ...access.environment, - DEEPSCIENTIST_MATH_WORKER_ID: worker.id, - DEEPSCIENTIST_MATH_WORKER_WORKTREE: worker.worktree, - }, - skills: [access.researchSkill!], - tools, - nativeAgentControl: nativeOptions, - hiddenRoots: [ - prepareTacticBatteryFailureCacheRoot(), - this.directory, - state.worktree, - git(state.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir']), - ], - readableRoots: researchToolRoots(this.input.root, this.input.modules.M4.tools), - isolatedWorkspaceParent: path.dirname(worker.worktree), - isolateProcess: true, - instructions: context.instructions, - signal, - ...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.input.save(); - }, - ...callbacks, - requestGate, - }); - usage.sessionOpened(entry.session); - if (worker.native && entry.session.nativeConfiguration) - worker.native.runtimeConfiguration = entry.session.nativeConfiguration; - if (entry.session.processIdentity) worker.writerProcess = entry.session.processIdentity; - worker.threadId = entry.session.threadId || worker.threadId; - this.input.save(); - signal.throwIfAborted(); - if (!modelDispatchAllowed(state.tokenBudget!) || this.input.remainingMs() <= 0) - throw new Error('math_team_dispatch_stopped'); - task.turns = (task.turns ?? 0) + 1; - usage.begin(task.id); - started = true; - const status = await entry.session.run(context.message, task.id, worker.worktree, activeTurnId => { - turnId = activeTurnId; - milestone.start(); - worker.threadId = entry.session!.threadId; - worker.cursor = context.inboxThrough ?? worker.cursor; - worker.previewCursor = context.inboxPreviewThrough ?? worker.previewCursor; - usage.turnStarted(turnId); - this.input.save(); - if (worker.threadId !== worker.native!.threadId) throw new Error('math_team_native_start_identity_changed'); - const accepted = this.nativeControl.accepted(worker, entry.session!, turnId); - const pending = this.nativeStarts.get(worker.id); - if (pending) { - pending.accepted = true; - pending.resolve(accepted); - } - }); - if ((status === 'checkpoint' || milestoneCheckpoint) && !task.declarations) { - task.pauseRequested ??= milestoneCheckpoint - ? { at: Date.now(), kind: 'handoff', reason: 'math_soft_slice_checkpoint' } - : { at: Date.now(), kind: 'budget', reason: 'math_team_turn_checkpoint' }; - this.input.save(); - } - completed = - ['completed', 'submitted'].includes(status) || (status === 'checkpoint' && task.declarations !== undefined); - outcome = completed ? 'completed' : status === 'failed' ? 'failed' : 'interrupted'; - const response = entry.session.lastCompletedResponse?.text; - if (response) task.summary ??= response.slice(0, 16000); - } catch (error) { - outcome = - signal.aborted || (error instanceof Error && error.message === 'math_team_dispatch_stopped') - ? 'interrupted' - : 'failed'; - task.error = error instanceof Error ? error.message : 'math_team_worker_failed'; - if (recordUnconfirmedWriterStartup(worker, error, () => this.input.save())) throw error; - 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.input.save(); - if (signal.aborted && !closingSession) await current.interrupt().catch(() => {}); - await stopProofWriter({ - session: current, - record: worker, - workerId: worker.id, - close: async () => { - await closeSession(current); - entry.session = undefined; - usage.sessionClosed(sessionId); - }, - save: () => this.input.save(), - deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }), - confirmed: reason => this.input.emit('team_writer_stop_confirmed', { workerId: worker.id, reason }), - }); - this.nativeControl.writerStopped(worker.id); - worker.writerProcess = undefined; - } - writerStopped = !worker.writerStopUnconfirmed; - } finally { - if (started) usage.finish(completed); - else if (reserved) { - state.turns--; - worker.turns--; - this.refreshUsage(); - } - 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'; - if ((worker.status as string) !== 'stopped') - worker.status = - task.status === 'paused' ? 'paused' : task.status === 'interrupted' ? 'interrupted' : 'idle'; - worker.activity = task.status === 'paused' ? 'paused' : 'idle'; - // Register submitted work in the same durable transition as the result and - // research snapshot. A crash must never strand a completed nomination. - if (task.declarations && !task.cancelRequested && task.pauseRequested?.kind !== 'handoff') { - worker.pendingDelivery = { - taskId: task.id, - seedCommit: task.seedCommit!, - declarations: this.deliveryDeclarations(worker, task), - }; - worker.activity = 'checking'; - worker.phase = 'checking'; - } - // Persist completion and its fixed source together; recovery must not mistake a - // finished task with an unsaved draft for a fully archived result. - this.saveResearch(worker, task); - } - this.input.save(); - } - } - 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) ?? teamTaskResearchSummary(task), - { taskId: task.id, researchArtifactId: task.researchArtifactId }, - ); - } - } - - private saveResearch(worker: AgentTeamWorker, task: AgentTeamTask) { - if (worker.writerStopUnconfirmed || this.live.get(worker.id)?.session || this.nativeIdle.has(worker.id)) - throw new Error('math_writer_stop_unconfirmed:' + worker.id); - if (task.status === 'queued' || task.status === 'running') throw new Error('math_team_research_task_unfinished'); - try { - task.sourceCommit = commitSolverSources(this.input.state.problem, worker.worktree); - } catch (error) { - if (!correctableSourceFailure(error)) throw error; - this.rejectSubmission(worker, task, error); - return; - } - 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: 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.input.save(); - } - - private pauseForBudget(worker: AgentTeamWorker, task: AgentTeamTask, reason: string) { - task.status = 'paused'; - task.pauseRequested = { at: Date.now(), kind: 'budget', reason }; - task.pausedAt = Date.now(); - worker.status = 'paused'; - worker.activity = 'paused'; - this.event(null, 'lead', 'paused', reason, { taskId: task.id }); - } - - private deliveryDeclarations(worker: AgentTeamWorker, task: AgentTeamTask) { - const declarations = new Map[number]>(); - const record = (declaration: NonNullable[number]) => { - declarations.set(declaration.file + '\0' + leanNameWithoutRoot(declaration.name), declaration); - }; - for (const id of worker.pendingPeerDeliveries ?? []) { - const reference = this.archive.deliveries.find(delivery => delivery.id === id); - if (!reference) throw new Error('math_team_delivery_unknown'); - const peer = readAgentTeamProofDelivery(reference.path, this.input.state); - for (const declaration of peer.declarations) record(declaration); - } - for (const declaration of task.declarations ?? []) record(declaration); - 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.input.save(); - return; - } - const access = this.workspaces.get(worker.id)?.access ?? (await this.prepare(worker)); - const nominations = task.helperSubmission!; - const local = this.live.get(worker.id)?.routeAbort.signal; - const signal = local ? AbortSignal.any([this.input.signal, local]) : this.input.signal; - 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); - access.assertHarnessCurrent?.(); - }; - const { state } = this.input; - try { - assertWriterStopped(); - await this.input.exclusiveCheck(async () => { - const closed = await this.closeSubmittedSorries( - worker, - task, - nominations, - access.environment, - signal, - assertWriterStopped, - ); - const sourceCommit = - closed || !task.sourceCommit ? commitSolverSources(state.problem, worker.worktree) : task.sourceCommit; - const expectedCommit = this.archive.canonicalCommit ?? git(state.worktree, ['rev-parse', 'HEAD']); - const result = await landVerifiedHelpers({ - state, - worktree: state.worktree, - expectedCommit, - sourceWorktree: worker.worktree, - sourceCommit, - seedCommit: task.seedCommit ?? worker.seedCommit, - 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.input.save(); - const signatures = result.helpers - .slice(0, 8) - .map(({ file, qualifiedName, type }) => ({ file, qualifiedName, type: type.slice(0, 240) })); - const notice = - 'Verified ' + - result.helpers.length + - ' standalone helpers at ' + - delivery.commit + - '.\n' + - canonicalMathJson(signatures) + - '\nUse inspect for the full signature list. The host applies these sources before your next turn. ' + - '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 }); - } - } - - /** - * Before the Lean check of a submission, try the fixed tactic battery on each nominated theorem whose body is still - * `sorry` or `admit`, against its exact submitted type. A closure is written into the stopped writer's sources and - * committed there; the ordinary check still decides acceptance. A failed or unavailable attempt changes nothing. - * Returns whether any source changed. - */ - private async closeSubmittedSorries( - worker: AgentTeamWorker, - task: AgentTeamTask, - declarations: readonly { file?: string; name?: string; type?: string; kind?: 'definition' }[], - env: NodeJS.ProcessEnv, - signal: AbortSignal, - assertWriterStopped: () => void, - ): Promise { - const closeTask = this.input.modules.M2.closeTask, - { problem } = this.input.state; - if (!closeTask) return false; - // One shared bound per submission, so several open helpers cannot multiply the host delay. - const deadline = Date.now() + Math.min(this.input.proofTimeoutMs ?? Infinity, TACTIC_BATTERY_TIMEOUT_MS); - let changed = false; - for (const declaration of declarations) { - const remaining = deadline - Date.now(); - if (remaining <= 0) break; - const { file, name, type } = declaration; - if (declaration.kind === 'definition' || !file || !name || !type || !problem.ownedFiles.includes(file)) continue; - const relative = path.join(problem.projectRelative, file); - let theoremName: string; - try { - const source = fs.readFileSync(path.join(worker.worktree, relative), 'utf8'); - const located = locateKnowledgeDeclaration(source, name); - const body = inspectLeanSource(source.slice(located.bodyOffset, located.endOffset)); - if (located.kind !== 'theorem' || (!body.sorryCount && !body.admitCount)) continue; - theoremName = located.qualifiedName; - } catch { - continue; - } - assertWriterStopped(); - let seedCommit: string; - try { - seedCommit = commitSolverSources(problem, worker.worktree); - } catch { - break; - } - const helper: CooperativeTask = { - id: 'submitted-helper', - kind: 'lemma', - objective: 'Close submitted helper ' + theoremName, - proofPath: file, - theoremName, - type, - dependsOn: [], - revision: 0, - }; - const started = Date.now(); - const battery = await closeTask({ - problem, - task: helper, - worktree: worker.worktree, - seedCommit, - context: theoremName, - env, - signal, - timeoutMs: remaining, - }); - signal.throwIfAborted(); - let applied = false; - if (battery.status === 'closed' && battery.commit) { - assertWriterStopped(); - fs.writeFileSync( - path.join(worker.worktree, relative), - committedSource(worker.worktree, battery.commit, relative), - ); - commitSolverSources(problem, worker.worktree); - applied = changed = true; - } - this.input.emit('task_tactic_battery', { - taskId: task.id, - workerId: worker.id, - declaration: theoremName, - seedCommit, - status: battery.status, - reason: battery.reason, - durationMs: Date.now() - started, - applied, - ...(battery.cacheHit - ? { cacheHit: true, cacheKey: battery.cacheKey, originDiagnosticDigest: battery.originDiagnosticDigest } - : {}), - ...(battery.commit ? { commit: battery.commit } : {}), - ...(battery.artifact ? { artifact: battery.artifact } : {}), - ...(battery.vacuous ? { vacuous: true } : {}), - }); - if (applied) { - const vacuity = battery.vacuous - ? ' Host vacuity probe: its hypotheses alone derive False, so no consumer can discharge them; ' + - 'revise the helper unless it is an intended impossible case.' - : ''; - this.event( - null, - worker.id, - 'message', - 'The host tactic battery closed the sorry in ' + - theoremName + - ' against its submitted type, and your source now contains that proof. The ordinary Lean check still decides the submission.' + - vacuity, - { taskId: task.id }, - ); - if (battery.vacuous) - this.event(null, 'lead', 'message', worker.id + ' submitted ' + theoremName + '.' + vacuity, { - taskId: task.id, - }); - } - } - return changed; - } - - private async finishDelivery(worker: AgentTeamWorker) { - await this.closeNativeIdle(worker); - const pending = worker.pendingDelivery; - if (!pending) return; - if (worker.writerStopUnconfirmed || this.live.get(worker.id)?.session) - throw new Error('math_writer_stop_unconfirmed:' + worker.id); - const access = this.workspaces.get(worker.id)?.access ?? (await this.prepare(worker)); - const task = worker.tasks.find(item => item.id === pending.taskId)!; - // Native turn interruption preserves a nomination. Retirement withdraws it. - const local = this.live.get(worker.id)?.routeAbort.signal; - const signal = local ? AbortSignal.any([this.input.signal, local]) : this.input.signal; - worker.activity = 'checking'; - worker.phase = 'checking'; - this.input.save(); - try { - const evidenceKey = ({ file, name }: { file: string; name: string }) => file + '\0' + name; - const explicit = new Set(task.declarations?.map(evidenceKey)); - const inheritedTypes = new Set( - (worker.pendingPeerDeliveries ?? []).flatMap(id => { - const reference = this.archive.deliveries.find(delivery => delivery.id === id); - return reference?.kind === 'helpers' - ? (readAgentTeamProofDelivery(reference.path, this.input.state).inferredHelperTypes ?? []) - : []; - }), - ); - // A submission can replace the inherited spelling (for example, with `_root_.`). - const inferredHelperTypes = pending.declarations - .map(evidenceKey) - .filter(key => inheritedTypes.has(key) && !explicit.has(key)); - // A recorded commit is a retry of the same sources; the battery only runs before the first check. - if (!pending.commit && task.declarations?.length) - await this.input.exclusiveCheck(() => - this.closeSubmittedSorries(worker, task, task.declarations!, access.environment, signal, () => { - signal.throwIfAborted(); - if (worker.writerStopUnconfirmed || this.live.get(worker.id)?.session) - throw new Error('math_writer_stop_unconfirmed:' + worker.id); - }), - ); - const commit = commitSolverSources(this.input.state.problem, worker.worktree); - const digest = solverSourceDigest(this.input.state.problem, worker.worktree); - if (pending.commit && (pending.commit !== commit || pending.sourceDigest !== digest)) - throw new Error('math_team_delivery_source_changed'); - pending.commit = commit; - pending.sourceDigest = digest; - this.input.save(); - const delivery = await this.input.exclusiveCheck(() => - checkAgentTeamProofDelivery({ - state: this.input.state, - failureCache: this.failedNominations, - agentId: worker.id, - worktree: worker.worktree, - seedCommit: pending.seedCommit, - declarations: pending.declarations, - inferredHelperTypes, - env: access.environment, - signal, - timeoutMs: this.input.proofTimeoutMs, - // Older checkpoints do not record when a nomination was made relative to a followup. - provenance: { - ...(task.nomination ?? - (!task.objectiveHistory?.length && (task.objectiveRevision ?? 1) === 1 - ? { objectiveRevision: 1, workKind: task.workKind } - : {})), - taskId: task.id, - ...(worker.native ? { spawnHistory: worker.native.spawnHistory ?? 'unknown' } : {}), - exposures: structuredClone(worker.exposures ?? []), - }, - 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'), - 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; - const checkedType = - delivery.declarations.length === 1 - ? delivery.artifacts[0]?.proof.verification.results[0]?.elaboratedDeclarationType - : undefined; - const signature = - checkedType && Buffer.byteLength(checkedType, 'utf8') <= 512 ? '\nLean signature: ' + checkedType : ''; - const checked = - 'Lean checked ' + - ready + - (more > 0 ? ' and ' + more + ' more' : '') + - '.' + - signature + - '\nUse this deliveryId to adopt into the workspace that needs the declarations. Inspect when you need more evidence.'; - 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.input.save(); - return; - } - // Keep infrastructure failures pending; deterministic proof feedback is correctable by another explicit assignment. - if (correctableProofFailure(error)) { - this.rejectSubmission(worker, task, error); - const location = task.failedCheck - ? 'Failed Lean check for ' + - task.failedCheck.declaration.name + - '. Read failedCheck via ' + - JSON.stringify({ operation: 'history', agentId: worker.id, offset: worker.tasks.indexOf(task), limit: 1 }) + - '.\n' - : ''; - this.event(worker.id, 'lead', 'failed', location + task.error!, { - taskId: task.id, - researchArtifactId: task.researchArtifactId, - }); - } else throw error; - } - worker.activity = worker.tasks.some(task => task.status === 'paused') ? 'paused' : 'idle'; - worker.phase = 'prepared'; - this.input.save(); - } - - private helperAdoptions(targetId: string, worktree: string) { - const { problem } = this.input.state; - const deliveries = this.archive.deliveries.filter(delivery => delivery.kind === 'helpers'); - const helperOrder = new Map(deliveries.map((delivery, index) => [delivery.id, index])); - const latest = new Map( - this.archive.adoptions.filter(item => item.targetId === targetId).map(item => [item.deliveryId, item]), - ); - const untried = deliveries.filter(delivery => !latest.has(delivery.id)); - const failedHelper = (item: AgentTeamState['adoptions'][number]) => - item.status === 'failed' && helperOrder.has(item.deliveryId) && Boolean(item.missingDependencies?.length); - const blocked = [...latest.values()].filter(failedHelper); - const sourceNames = new Map>(); - const namesAt = (file: string, commit?: string) => { - const key = (commit ?? '') + '\0' + file; - let names = sourceNames.get(key); - if (!names) { - const relative = path.join(problem.projectRelative, file); - const source = commit - ? committedSource(worktree, commit, relative) - : fs.readFileSync(path.join(worktree, relative), 'utf8'); - names = new Set(inspectScopedLeanDeclarations(source).map(item => item.qualifiedName)); - sourceNames.set(key, names); - } - return names; - }; - const newlyAvailable = - (before: string, after?: string) => - ({ file, name }: AgentTeamAdoptionDependency) => - problem.ownedFiles.includes(file) && - file.endsWith('.lean') && - namesAt(file, after).has(name) && - !namesAt(file, before).has(name); - const hasDraftCandidates = untried.length > 0 || blocked.length > 0; - const canReadDraft = () => hasDraftCandidates && !solverSourceFeedback(problem, worktree); - const readyInDraft = () => - blocked.filter( - item => item.expectedCommit && item.missingDependencies?.some(newlyAvailable(item.expectedCommit)), - ); - return { - helperOrder, - latest, - untried, - failedHelper, - newlyAvailable, - hasDraftCandidates, - canReadDraft, - readyInDraft, - }; - } - - /** Called only after the receiving writer has stopped; no running writer is overwritten. */ - async flushAdoptions(targetId = 'lead') { - const { state } = this.input; - const target = targetId === 'lead' ? undefined : this.worker(targetId); - if (target) await this.closeNativeIdle(target); - 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; - // A check already bound to Lead's source must finish before an adoption can advance it. - if (!target && (state.pendingProofCheck || state.pendingDeclarationCheck)) return; - // Multiple adoptions in one flush can leave a previous freeze and an in-flight intent. - // Recover that intent before freezing the source again. - const recoveringLead = !target && this.leadSourceRecoveryPending; - const helpers = this.helperAdoptions(targetId, worktree); - const { helperOrder, latest, untried, failedHelper, newlyAvailable, readyInDraft } = helpers; - const queued = this.archive.adoptions.filter( - item => - item.targetId === targetId && (item.status === 'integrating' || (!recoveringLead && item.status === 'queued')), - ); - const inspectDraft = !recoveringLead && target?.status !== 'stopped' && helpers.hasDraftCandidates; - if (!queued.length && !inspectDraft) return; - // A restored idle member needs its pinned project metadata before source validation. - const access = target - ? (this.workspaces.get(targetId)?.access ?? (await this.prepare(target))) - : this.input.leadAccess; - const queueHelper = (deliveryId: string) => { - const retry = { id: crypto.randomUUID(), deliveryId, targetId, status: 'queued' as const }; - this.archive.adoptions.push(retry); - latest.set(deliveryId, retry); - return retry; - }; - // A stopped writer can supply a prerequisite in its own saved draft. - if (inspectDraft && helpers.canReadDraft()) { - const queuedBefore = queued.length; - for (const failed of readyInDraft()) queued.push(queueHelper(failed.deliveryId)); - for (const delivery of untried) queued.push(queueHelper(delivery.id)); - if (queued.length > queuedBefore) this.input.save(); - } - if (!queued.length) return; - // Resume a saved transition before moving HEAD. Install shared helpers in - // publication order before processing deliveries that may depend on them. - const pending = queued.filter(item => item.status === 'queued'); - const ordered = [ - ...queued.filter(item => item.status === 'integrating'), - ...pending - .filter(item => helperOrder.has(item.deliveryId)) - .sort((a, b) => helperOrder.get(a.deliveryId)! - helperOrder.get(b.deliveryId)!), - ...pending.filter(item => !helperOrder.has(item.deliveryId)), - ]; - const deferred = new Map<(typeof ordered)[number], string>(); - const readyAfterTransfer = (before: string, after: string) => { - if (before === after || target?.status === 'stopped') return []; - return [...latest.values()].filter( - failed => - (deferred.has(failed) || failedHelper(failed)) && - failed.missingDependencies?.some(newlyAvailable(before, after)), - ); - }; - for (const [index, adoption] of ordered.entries()) { - const reference = this.archive.deliveries.find(item => item.id === adoption.deliveryId)!; - const delivery = readAgentTeamProofDelivery(reference.path, state); - adoption.expectedCommit ??= commitSolverSources(state.problem, worktree); - adoption.status = 'integrating'; - if (target) target.activity = 'integrating'; - this.input.save(); - let event: { to: string; kind: 'adopted' | 'failed'; text: string } | undefined; - try { - const result = await this.input.exclusiveCheck(() => - integrateAgentTeamProofDelivery({ - state, - delivery, - worktree, - expectedCommit: adoption.expectedCommit!, - env: access.environment, - signal: this.input.signal, - timeoutMs: this.input.proofTimeoutMs, - evidenceDirectory: path.join(this.directory, 'proofs'), - assertWriterStopped: () => { - if ( - this.live.get(targetId)?.session || - target?.writerStopUnconfirmed || - (targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed)) - ) - throw new Error('math_team_target_writing'); - }, - }), - ); - const ready = readyAfterTransfer(result.beforeCommit, result.commit); - if (!target) { - state.check = undefined; - // Save the next acceptance step with adoption completion, so restart needs no extra model turn. - if (reference.kind !== 'helpers' || result.commit !== adoption.expectedCommit || state.pendingResearchFreeze) - state.pendingResearchFreeze = { - commit: result.commit, - sourceDigest: result.sourceDigest, - problemReceiptDigest: state.problem.receiptDigest, - environmentDigest: state.environmentDigest, - }; - } else { - // An adopted peer is part of the next transfer until the member's own draft - // has been delivered. Retain the old ancestor instead of losing that draft. - if ( - target.pendingSourceBase && - ownedSourceDigest(state.problem, worktree, target.pendingSourceBase) !== - ownedSourceDigest(state.problem, worktree, adoption.expectedCommit!) - ) { - const peers = (target.pendingPeerDeliveries ??= []); - if (!peers.includes(delivery.id)) peers.push(delivery.id); - } else { - target.pendingSourceBase = undefined; - target.pendingPeerDeliveries = undefined; - } - } - adoption.status = 'completed'; - adoption.commit = result.commit; - adoption.receiptId = result.id; - adoption.error = undefined; - adoption.missingDependencies = undefined; - this.recordExposure(targetId, reference, delivery.commit, 'adopted'); - // Queue newly enabled retries in the same save as the prerequisite's completion. - for (const failed of ready) { - if (deferred.delete(failed)) { - ordered.push(failed); - } else { - const retry = queueHelper(failed.deliveryId); - if (!recoveringLead) ordered.push(retry); - } - } - event = { to: targetId, kind: 'adopted', text: 'Checked declarations integrated at ' + result.commit }; - } catch (error) { - adoption.error = error instanceof Error ? error.message : 'math_team_adoption_failed'; - if ( - !correctableProofFailure(error) && - !/^math_task_integration_(?:conflict|missing_context|missing_declaration)$/u.test(adoption.error) && - adoption.error !== 'math_agent_team_proof_source_changed' - ) { - // Leave the same expectedCommit queued for crash-safe retry; infrastructure failures are not proof feedback. - this.input.save(); - throw error; - } - adoption.missingDependencies = - error instanceof MissingAdoptionDependencyError && error.missing.length ? error.missing : undefined; - if (adoption.missingDependencies && index + 1 < ordered.length) { - // This rejection precedes the durable intent. The next successful source change - // can supply the dependency, so release the old revision and keep the adoption queued. - deferred.set(adoption, adoption.expectedCommit!); - adoption.status = 'queued'; - adoption.expectedCommit = undefined; - } else { - adoption.status = 'failed'; - event = { to: 'lead', kind: 'failed', text: adoption.error }; - } - } - if (target) target.activity = target.tasks.some(task => task.status === 'paused') ? 'paused' : 'idle'; - if (event) this.event(null, event.to, event.kind, event.text, { deliveryId: adoption.deliveryId }); - else this.input.save(); - } - for (const [adoption, expectedCommit] of deferred) { - adoption.status = 'failed'; - adoption.expectedCommit = expectedCommit; - this.event(null, 'lead', 'failed', adoption.error!, { deliveryId: adoption.deliveryId }); - } - } - - async restore() { - assertAgentTeamProcessesStopped(this.input.state); - // Reconcile lost usage receipts before saving any recovered writer or launching tasks. - for (const worker of this.archive.workers) initializeUsageAccounting(worker); - this.refreshUsage(); - this.nativeControl.writerStopped('lead', 'recovery-process-check'); - this.input.state.writerProcess = undefined; - for (const worker of this.archive.workers) { - worker.writerProcess = undefined; - if (worker.native) this.nativeControl.writerStopped(worker.id, 'recovery-process-check'); - // Isolate legacy Git worktrees before Lead can access the shared repository. - this.prepareWorkspace(worker); - const queued = worker.tasks.filter(task => task.status === 'queued'); - if (worker.native && queued.length > 1) { - // Older checkpoints could accept another queue entry after a blocked - // followup. Only its last input was saved, so require explicit reassignment. - for (const task of queued) { - task.status = 'interrupted'; - task.finishedAt = Date.now(); - this.event( - worker.id, - 'lead', - 'interrupted', - 'Assign this saved task explicitly to continue; its queued native input could not be recovered.', - { taskId: task.id }, - ); - } - } - for (const task of worker.tasks.filter(item => item.status === 'running')) { - // Restore the pinned project metadata before freezing a stopped writer's draft. - await this.prepare(worker); - task.status = task.cancelRequested ? 'cancelled' : task.pauseRequested ? 'paused' : 'interrupted'; - if (task.status === 'paused') task.pausedAt = Date.now(); - else task.finishedAt = Date.now(); - // Submit is already a durable nomination. A crash can precede the turn's - // completed response or its final snapshot; freeze and check it only after - // the previous process is confirmed stopped, without inventing completion. - if ( - !worker.pendingDelivery && - task.declarations?.length && - !task.cancelRequested && - task.pauseRequested?.kind !== 'handoff' && - (task.seedCommit || worker.pendingSourceBase) - ) { - worker.pendingDelivery = { - taskId: task.id, - seedCommit: task.seedCommit ?? worker.pendingSourceBase!, - declarations: this.deliveryDeclarations(worker, task), - }; - } - this.saveResearch(worker, task); - this.event( - worker.id, - 'lead', - task.status, - task.pauseRequested?.reason ?? - task.cancelRequested?.reason ?? - 'Previous dispatch was interrupted; source and native thread retained. Assign explicitly to continue.', - { taskId: task.id, researchArtifactId: task.researchArtifactId }, - ); - } - if (worker.status === 'running') { - worker.status = 'interrupted'; - worker.phase = 'prepared'; - } - if (worker.tasks.some(task => task.status === 'paused') && worker.status !== 'stopped') { - worker.status = 'paused'; - worker.activity = 'paused'; - } else worker.activity = 'idle'; - // Historical checkpoints could settle a completion or interruption without - // registering its nomination. Recover only the last writer at its fixed HEAD. - if (!worker.pendingDelivery && worker.pendingSourceBase) { - const task = worker.tasks.findLast(task => task.seedCommit !== undefined); - if ( - task && - ['completed', 'interrupted'].includes(task.status) && - task.declarations?.length && - !task.deliveryId && - !task.cancelRequested && - task.pauseRequested?.kind !== 'handoff' && - task.seedCommit === worker.pendingSourceBase && - task.sourceCommit && - task.sourceCommit === git(worker.worktree, ['rev-parse', 'HEAD']) && - !git(worker.worktree, [ - 'status', - '--porcelain', - '--', - ...this.input.state.problem.ownedFiles.map(file => - path.join(this.input.state.problem.projectRelative, file), - ), - ]) - ) { - worker.pendingDelivery = { - taskId: task.id, - seedCommit: task.seedCommit ?? worker.pendingSourceBase, - declarations: this.deliveryDeclarations(worker, task), - }; - this.input.save(); - } - } - await this.flushHelperSubmissions(worker); - if (worker.pendingDelivery) await this.finishDelivery(worker); - // Older hosts left interrupted assignments open even after Lead retired their route. - let closedRetiredTask = false; - for (const task of worker.tasks) { - if (task.status !== 'interrupted' || !openRouteTask(task)) continue; - const retirement = this.archive.retiredRoutes?.find(route => route.routeId === task.routeId); - if (!retirement) continue; - task.cancelRequested = { at: retirement.retiredAt, reason: retirement.reason }; - task.status = 'cancelled'; - task.finishedAt = retirement.retiredAt; - closedRetiredTask = true; - } - if (closedRetiredTask && !worker.tasks.some(openRouteTask)) worker.status = 'stopped'; - } - await this.flushAdoptions(); - for (const worker of this.archive.workers) { - await this.flushAdoptions(worker.id); - if (worker.tasks.some(task => task.status === 'queued')) this.launch(worker); - } - this.input.save(); - } - - async close() { - this.stopping = true; - this.leadSession = undefined; - for (const entry of this.live.values()) { - entry.abort.abort(); - void entry.session?.interrupt().catch(() => {}); - } - await this.serial; - await Promise.allSettled([...this.live.values()].map(entry => entry.task)); - await Promise.allSettled([...this.nativeIdle.keys()].map(id => this.closeNativeIdle(this.worker(id)))); - this.input.save(); - const unconfirmed = this.archive.workers.find(worker => worker.writerStopUnconfirmed); - if (unconfirmed) throw new Error('math_writer_stop_unconfirmed:' + unconfirmed.id); - } -} diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts deleted file mode 100644 index a9cea699..00000000 --- a/src/solver/agentTeamContext.ts +++ /dev/null @@ -1,102 +0,0 @@ -import type { SolverRunState } from './archive'; -import type { ContextSection } from './contextCompiler'; -import { agentTeamDispatchBudget, agentTeamDispatchTask, agentTeamInboxPreview } from './agentTeamViews'; - -export type AgentTeamRole = Readonly<{ id: string; role: 'lead' | 'worker' }>; -export type AgentTeamAssignment = Readonly<{ taskId: string; message: string; sourceCommit: string }>; - -/** Stable authority and identity; professional profiles live in the pinned skill and current assignment. */ -export function agentTeamInstructions(role: AgentTeamRole, maxAgents: number): string { - const shared = - 'Each member has a separate worktree. ' + - "Call collaboration tools directly in their exposed namespace, not through functions.exec. A child's final answer is automatically delivered to its parent. " + - 'Use canonical agent paths or thread IDs with native tools and the observed workspace member IDs with theoremos_team. ' + - 'Use theoremos_team for checked handoffs and evidence.'; - if (role.role === 'lead') - return ( - 'You are the Lead of a flat mathematical research team (member ID lead, native path /root). ' + - `Decide when to use native collaboration tools for independent gaps. Capacity is ${maxAgents} including you and idle members. ` + - 'Use spawn_agent with the assignment and optional Route: and Profiles: headers. Omit model and reasoning_effort to inherit the run configuration. ' + - 'Use followup_task to reuse a member and interrupt_agent to stop its turn while keeping its draft.\n' + - 'Only Lead dispatches, interrupts and adopts. Compare a checked delivery with the required Lean signature. Save before adopting by ID, then return so the host can apply it.\n' + - shared - ); - 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). ` + - 'Use native send_message to share the first usable finding or blocker with its claim, assumptions and evidence. Members may message peers. ' + - 'Call submit for checked delivery or yield to record a dependency, then return. ' + - 'Only Lead dispatches and adopts. Do not spawn subteams or interrupt peers.\n' + - shared - ); -} - -export function agentTeamWorkerDeliveryHelp(): string { - return ( - 'This proof-writing member publishes through theoremos_team, operation submit. Save source and worktree-root RESEARCH.md, ' + - 'then supply summary and declarations: [{"file":"OWNED_FILE.lean","name":"Qualified.helper","type":"COMPLETE_CLOSED_LEAN_TYPE"}]. ' + - 'For type, you can paste the full Lean #check output. Preserve line breaks and indentation, especially around let and have. ' + - "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. ' + - 'Set helpersOnly:true to submit only standalone helpers and keep the current assignment open for resumption. ' + - '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. ' + - 'For an investigation with no formal delivery, return a useful summary without fabricating declarations. ' + - 'Only independent host checks of all frozen original targets can accept the original problem.' - ); -} - -/** Refresh current work without promoting a prior task, peer message or Lead check into this member's result. */ -export function agentTeamWorkerSection( - state: Readonly, - role: AgentTeamRole, - assignment: AgentTeamAssignment, -): { section: ContextSection; inboxThrough: number; inboxPreviewThrough: number } { - const team = state.agentTeam; - const worker = team?.workers.find(item => item.id === role.id); - if (!team || !worker) throw new Error('math_team_agent_unknown:' + role.id); - const current = worker.tasks.find(item => item.id === assignment.taskId); - if (!current || current.message !== assignment.message) throw new Error('math_team_assignment_changed'); - const prior = worker.tasks.findLast( - item => - item.id !== current.id && ['completed', 'failed', 'interrupted', 'cancelled', 'paused'].includes(item.status), - ); - const inbox = agentTeamInboxPreview(team, role.id, worker.cursor, worker.previewCursor); - const { error: currentError, failedCheck } = agentTeamDispatchTask(current); - return { - inboxThrough: inbox.through, - inboxPreviewThrough: inbox.previewThrough, - section: { - id: 'agent-team-assignment', - kind: 'assignment', - text: - 'Current native task instructions (latest accepted followup; earlier instructions remain in native history; frozen problem and source constraints still apply):\n' + - JSON.stringify({ - agentId: role.id, - coordinator: 'lead', - taskId: current.id, - objective: assignment.message, - objectiveRevision: current.objectiveRevision ?? 1, - workKind: current.workKind, - ...(current.routeId ? { routeId: current.routeId } : {}), - deliveryExposures: worker.exposures ?? [], - sourceCommit: assignment.sourceCommit, - deliveryBaseCommit: current.seedCommit, - cancelRequested: current.cancelRequested, - pauseRequested: current.pauseRequested, - currentError, - failedCheck, - previousTask: prior && agentTeamDispatchTask(prior), - landedHelpers: team.landedHelpers?.slice(-8).map(({ qualifiedName, file, commit }) => ({ - qualifiedName, - file, - commit, - })), - budget: agentTeamDispatchBudget(state), - inbox, - retrieval: 'Use route_summary for current team work or history and inspect-research for saved evidence.', - }), - }, - }; -} diff --git a/src/solver/agentTeamContributions.ts b/src/solver/agentTeamContributions.ts index cdaebb70..74a4b72e 100644 --- a/src/solver/agentTeamContributions.ts +++ b/src/solver/agentTeamContributions.ts @@ -1,11 +1,13 @@ import path from 'node:path'; import { z } from 'zod'; import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import { leanDeclarationKeys } from '../math/leanSource'; import type { SolverRunState } from './archive'; -import { deliveredDeclarationChange, teamDeclarationForwarding } from './agentTeamForwarding'; -import { committedSource, git } from './problem'; -import { locateKnowledgeDeclaration } from './theoremKnowledge'; +import { + committedDeclarationVersions, + deliveredDeclarationChange, + teamDeclarationForwarding, +} from './agentTeamForwarding'; +import { git } from './problem'; import type { ProofCheck } from './modules/evidence'; const target = z.object({ @@ -117,23 +119,8 @@ export function buildAgentTeamContributions(state: SolverRunState, evaluation: R ], ), }; - const sources = new Map(), - worktree = state.problem.workspace; - function version(at: string, file: string, qualified: string) { - const key = at + '\0' + file; - const source = - sources.get(key) ?? committedSource(worktree, at, path.posix.join(state.problem.projectRelative, file)); - sources.set(key, source); - try { - const loc = locateKnowledgeDeclaration(source, qualified); - if (loc.qualifiedName !== qualified.replace(/^_root_\./u, '')) return; - const body = source.slice(source.lastIndexOf('\n', loc.startOffset - 1) + 1, loc.endOffset).trimEnd() + '\n'; - return { digest: mathDigest(body), key: leanDeclarationKeys(source).get(loc.startOffset) }; - } catch (err) { - if (err instanceof Error && err.message === 'math_knowledge_declaration_missing_or_ambiguous') return; - throw err; - } - } + const worktree = state.problem.workspace; + const version = committedDeclarationVersions(worktree, state.problem.projectRelative); const unresolved = new Map(); const transfers = teamDeclarationForwarding(state, path.join(path.dirname(state.worktree), 'agent-team/proofs')); for (const ref of team.deliveries) { diff --git a/src/solver/agentTeamForwarding.ts b/src/solver/agentTeamForwarding.ts index a17b3ea7..1db0015c 100644 --- a/src/solver/agentTeamForwarding.ts +++ b/src/solver/agentTeamForwarding.ts @@ -13,12 +13,31 @@ export function deliveredDeclarationChange(delivery: AgentTeamProofDelivery, fil return changes.length === 1 ? changes[0] : undefined; } +/** Match exact names and source bytes in one repository for the lifetime of an archive read. */ +export function committedDeclarationVersions(repository: string, projectRelative: string) { + const sources = new Map(); + return (commit: string, file: string, name: string) => { + const key = commit + '\0' + file; + const source = sources.get(key) ?? committedSource(repository, commit, path.posix.join(projectRelative, file)); + sources.set(key, source); + try { + const loc = locateKnowledgeDeclaration(source, name); + if (loc.qualifiedName !== name) return; + const body = source.slice(source.lastIndexOf('\n', loc.startOffset - 1) + 1, loc.endOffset).trimEnd() + '\n'; + return { key: leanDeclarationKeys(source).get(loc.startOffset), digest: mathDigest(body) }; + } catch (error) { + if (error instanceof Error && error.message === 'math_knowledge_declaration_missing_or_ambiguous') return; + throw error; + } + }; +} + /** Direct, recorded transfers of identical declarations. A missing source never establishes authorship. */ export function teamDeclarationForwarding(state: SolverRunState, proofsRoot: string) { const team = state.agentTeam!, archive = path.join(proofsRoot, 'sources.git'); - const deliveries = new Map(), - sources = new Map(); + const deliveries = new Map(); + const version = committedDeclarationVersions(archive, state.problem.projectRelative); function read(id: string) { if (deliveries.has(id)) return deliveries.get(id)!; const ref = team.deliveries.find(r => r.id === id); @@ -31,20 +50,6 @@ export function teamDeclarationForwarding(state: SolverRunState, proofsRoot: str deliveries.set(id, d); return d; } - function version(at: string, file: string, name: string) { - const key = at + '\0' + file, - source = sources.get(key) ?? committedSource(archive, at, path.posix.join(state.problem.projectRelative, file)); - sources.set(key, source); - try { - const loc = locateKnowledgeDeclaration(source, name); - if (loc.qualifiedName !== name) return; - const body = source.slice(source.lastIndexOf('\n', loc.startOffset - 1) + 1, loc.endOffset).trimEnd() + '\n'; - return { key: leanDeclarationKeys(source).get(loc.startOffset), digest: mathDigest(body) }; - } catch (error) { - if (error instanceof Error && error.message === 'math_knowledge_declaration_missing_or_ambiguous') return; - throw error; - } - } function origins(d: AgentTeamProofDelivery, file: string, name: string) { const result = new Map(); const change = deliveredDeclarationChange(d, file, name); diff --git a/src/solver/agentTeamNative.ts b/src/solver/agentTeamNative.ts deleted file mode 100644 index b77c4c8f..00000000 --- a/src/solver/agentTeamNative.ts +++ /dev/null @@ -1,782 +0,0 @@ -import crypto from 'node:crypto'; -import { nativeProcess } from '../math/nativeProcess'; -type Mailbox = InstanceType['TeamMailbox']>; -import type { - NativeAgentControlConnection, - NativeAgentControlOptions, - NativeAgentControlRequest, -} from '../runtime/nativeAgentControl'; -import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; -import type { AgentTeamState, AgentTeamWorker } from './agentTeamState'; -import { AgentTeamOperations } from './agentTeamOperations'; - -type Json = Record; -export type NativeTeamAcceptedChild = { agent: Json; configSnapshot: Json; submissionId: string }; -export type NativeTeamSpawn = { - sessionId: string; - threadId: string; - agentPath: string; - parentThreadId: string; - operationId: string; - requestDigest: string; - bootstrap: Json; - initialInput: Json; - message: string; -}; - -/** NativeChildBootstrap.initialHistory is the serde representation of Codex InitialHistory. */ -export function nativeSpawnHistory(bootstrap: Json): 'fresh' | 'parent-history' | 'unknown' { - const history = bootstrap.initialHistory; - if (history === 'New') return 'fresh'; - if ( - history && - typeof history === 'object' && - Object.keys(history).length === 1 && - 'Forked' in history && - Array.isArray(history.Forked) - ) - return 'parent-history'; - return 'unknown'; -} - -export type AgentTeamNativeLifecycle = { - spawn(input: NativeTeamSpawn, signal: AbortSignal): Promise; - followup(worker: AgentTeamWorker, input: Json, signal: AbortSignal): Promise; - interrupt(worker: AgentTeamWorker): Promise; - load(worker: AgentTeamWorker): Promise; - admit(worker: AgentTeamWorker, turnId: string): void; -}; - -const object = (value: unknown): Json => { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('math_team_native_object_required'); - return value as Json; -}; -const text = (value: unknown): string => { - if (typeof value !== 'string' || !value) throw new Error('math_team_native_identity_required'); - return value; -}; - -function nativeSource(source: unknown): Json { - const value = object(source); - return object(object(value.subagent).thread_spawn); -} - -/** Copy the native task payload for the business ledger without decoding or changing its codec. - * Upstream marks ordinary Direct tool messages Encrypted; only direct-plaintext/code-mode - * messages use Plaintext. The attributed native input must still be forwarded unchanged. */ -export function nativeTeamAssignmentMessage(input: Json): string { - if (input.kind === 'message') { - const message = object(input.message); - if (message.kind !== 'plaintext' && message.kind !== 'encrypted') - throw new Error('math_team_native_assignment_message_required'); - return text(message.text); - } - throw new Error('math_team_native_assignment_message_required'); -} - -/** One host-owned native tree; Rust retains the actual local mailbox/watch implementation. */ -export class AgentTeamNativeControl { - private readonly connections = new Map(); - private readonly pending = new Map; digest: string }>(); - private readonly flushing = new Map>(); - private readonly ordered = new Map>(); - private readonly updates = new Map>(); - - private readonly mailbox?: Mailbox; - - constructor( - private readonly archive: AgentTeamState, - private readonly lifecycle: AgentTeamNativeLifecycle, - private readonly save: () => void, - private readonly operations = new AgentTeamOperations(archive.operations), - ) { - // Queue ownership transferred to a lost runtime is uncertain, never a read receipt. - const state = archive.nativeControl; - if (nativeProcess) - this.mailbox = new nativeProcess.TeamMailbox( - state?.sequence ?? 0, - (state?.mailbox ?? []).map(({ threadId, status, sequence }) => ({ threadId, status, sequence })), - ); - this.recoverMail(); - } - - options(actor: string): NativeAgentControlOptions { - const worker = actor === 'lead' ? undefined : this.worker(actor); - return { - ...(worker?.native ? { bootstrap: worker.native.bootstrap, initialInput: worker.native.initialInput } : {}), - request: (request, connection, context) => this.request(actor, request, connection, context.signal), - disconnected: connection => { - for (const [threadId, active] of this.connections) - if (active.connection === connection) { - this.detach(threadId); - this.save(); - } - }, - bound: async connection => { - const threadId = - actor === 'lead' ? this.archive.nativeControl?.rootThreadId : this.worker(actor).native!.threadId; - const active = threadId && this.connections.get(threadId); - if (!threadId || !active || active.connection !== connection) - throw new Error('math_team_native_caller_changed'); - if (!connection.info) throw new Error('math_team_native_start_identity_changed'); - this.refresh(threadId, connection); - active.bound = true; - this.save(); - await this.flush(threadId); - if (this.connection(threadId) !== connection) throw new Error('math_team_native_caller_changed'); - }, - }; - } - - private detach(threadId: string) { - this.connections.delete(threadId); - this.recoverMail(threadId); - } - - private recoverMail(threadId?: string) { - const entries = this.archive.nativeControl?.mailbox ?? []; - if (this.mailbox) { - for (const i of this.mailbox.recover(threadId)) entries[i]!.status = 'uncertain'; - } else - for (const mail of entries) - if ((threadId === undefined || mail.threadId === threadId) && mail.status === 'accepted') - mail.status = 'uncertain'; - } - - private treeBinding() { - const control = this.archive.nativeControl; - return control && { sessionId: control.sessionId, rootThreadId: control.rootThreadId }; - } - - private worker(id: string) { - const worker = this.archive.workers.find(item => item.id === id); - if (!worker?.native) throw new Error('math_team_native_member_unknown'); - return worker; - } - - private workerByThread(threadId: string) { - const worker = this.archive.workers.find(item => item.native?.threadId === threadId); - if (!worker?.native) throw new Error('math_team_native_member_unknown'); - return worker; - } - - private identity(threadId: string) { - const state = this.archive.nativeControl; - if (!state) throw new Error('math_team_native_tree_unbound'); - if (threadId === state.rootThreadId) return { threadId, path: '/root' }; - const worker = this.workerByThread(threadId); - return { threadId, path: worker.native!.agentPath }; - } - - private resolve(reference: string): string { - const state = this.archive.nativeControl!; - if (reference === state.rootThreadId || reference === '/root') return state.rootThreadId; - const worker = this.archive.workers.find( - item => item.native?.threadId === reference || item.native?.agentPath === reference, - ); - if (!worker?.native) throw new Error('math_team_native_reference_unknown'); - return worker.native.threadId; - } - - private target(target: unknown): string { - const value = object(target); - return this.resolve(text(value.kind === 'id' ? value.threadId : value.reference)); - } - - private route( - request: NativeAgentControlRequest, - lead: boolean, - ): { threadId: string; mode?: 'queueOnly' | 'triggerTurn' } { - if (nativeProcess) { - return nativeProcess.teamSessionBinding({ - action: 'route', - request, - lead, - root: this.treeBinding(), - workers: this.archive.workers.flatMap(({ native }) => - native ? [{ threadId: native.threadId, agentPath: native.agentPath }] : [], - ), - }) as { threadId: string; mode?: 'queueOnly' | 'triggerTurn' }; - } - const operation = request.operation; - if (operation === 'interrupt' && !lead) throw new Error('math_team_lead_operation_required'); - const threadId = this.target(request.payload.target); - const root = this.archive.nativeControl!.rootThreadId; - if (operation === 'resolve') return { threadId }; - if (operation === 'interrupt') { - if (threadId === request.threadId || threadId === root) - throw new Error('math_team_native_interrupt_root_or_self'); - return { threadId }; - } - const input = object(request.payload.input); - if (input.kind !== 'message') throw new Error('math_team_native_message_required'); - if (threadId === request.threadId) throw new Error('math_team_message_self_addressed'); - if (input.mode === 'queueOnly') return { threadId, mode: 'queueOnly' }; - if (input.mode !== 'triggerTurn') throw new Error('math_team_native_message_mode_invalid'); - if (!lead) throw new Error('math_team_lead_operation_required'); - if (threadId === root) throw new Error('math_team_native_followup_root'); - return { threadId, mode: 'triggerTurn' }; - } - - private inOrder(threadId: string, operation: () => Promise): Promise { - const prior = this.ordered.get(threadId) ?? Promise.resolve(); - const apply = prior.catch(() => {}).then(operation); - this.ordered.set(threadId, apply); - void apply - .finally(() => { - if (this.ordered.get(threadId) === apply) this.ordered.delete(threadId); - }) - .catch(() => {}); - return apply; - } - - private refresh(threadId: string, connection: NativeAgentControlConnection) { - const info = connection.info; - if (!info) return; - const state = this.archive.nativeControl; - if (nativeProcess && state) { - const child = - threadId === state.rootThreadId - ? undefined - : this.archive.workers.find(worker => worker.native?.threadId === threadId)?.native; - const current = nativeProcess.teamSessionBinding({ - action: 'bind', - thread: threadId, - info, - root: this.treeBinding(), - child: child && { agentPath: child.agentPath }, - status: child ? child.status : state.rootAgent?.status, - }) as Json; - if (threadId === state.rootThreadId) { - state.rootAgent = current; - state.rootConfigSnapshot = object(info.configSnapshot); - } else { - const worker = this.workerByThread(threadId).native!; - worker.agent = current; - worker.configSnapshot = object(info.configSnapshot); - } - return; - } - const agent = object(info.agent), - actualId = text(agent.threadId); - if (!this.archive.nativeControl || actualId !== threadId || info.sessionId !== this.archive.nativeControl.sessionId) - throw new Error('math_team_native_start_identity_changed'); - const configSnapshot = object(info.configSnapshot); - if (threadId === this.archive.nativeControl.rootThreadId) { - this.archive.nativeControl.rootAgent = { - ...agent, - status: this.archive.nativeControl.rootAgent?.status ?? agent.status, - }; - this.archive.nativeControl.rootConfigSnapshot = configSnapshot; - } else { - const native = this.workerByThread(threadId).native!; - if (object(agent.metadata).agentPath !== native.agentPath) throw new Error('math_team_native_start_path_changed'); - native.agent = { ...agent, status: native.status ?? native.agent?.status ?? agent.status }; - native.configSnapshot = configSnapshot; - } - } - - accepted( - worker: AgentTeamWorker, - session: { nativeAgentControl?: NativeAgentControlConnection }, - turnId: string, - ): NativeTeamAcceptedChild { - const native = worker.native!, - connection = session.nativeAgentControl; - if (!connection) throw new Error('math_team_native_backend_required'); - if (this.connection(native.threadId) !== connection) throw new Error('math_team_native_child_not_bound'); - this.refresh(native.threadId, connection); - if (!native.agent || !native.configSnapshot) throw new Error('math_team_native_child_not_bound'); - native.turnId = turnId; - native.submissionId = turnId; - native.status = native.lastOutcome?.turnId === turnId ? native.lastOutcome.status : 'running'; - native.agent = { ...native.agent, status: native.status }; - this.save(); - return { agent: native.agent, configSnapshot: native.configSnapshot, submissionId: turnId }; - } - - connection(threadId: string) { - const active = this.connections.get(threadId); - return active?.bound ? active.connection : undefined; - } - - /** A confirmed stopped process is distinct from a native turn completion or a proof delivery. */ - writerStopped(actor: string, source: 'writer-stop' | 'recovery-process-check' = 'writer-stop') { - const state = this.archive.nativeControl; - if (!state) return; - if (actor === 'lead') { - state.rootWriterStop = { source, at: Date.now() }; - if (state.rootAgent && (state.rootAgent.status === 'running' || state.rootAgent.status === 'pending_init')) - state.rootAgent = { ...state.rootAgent, status: 'shutdown' }; - } else { - const native = this.worker(actor).native!; - native.writerStop = { source, at: Date.now(), ...(native.turnId ? { turnId: native.turnId } : {}) }; - if (native.status === undefined || native.status === 'running' || native.status === 'pending_init') { - native.status = 'shutdown'; - if (native.agent) native.agent = { ...native.agent, status: 'shutdown' }; - } - } - this.save(); - } - - /** A null sender denotes the host; member names, including "host", retain their identity. */ - async advisory(from: string | null, to: string, message: string, hostEventSequence?: number): Promise { - if (from === to || !this.archive.nativeControl) return; - const sender = - from === null - ? null - : from === 'lead' - ? this.archive.nativeControl.rootThreadId - : this.worker(from).native!.threadId; - const recipient = to === 'lead' ? this.archive.nativeControl.rootThreadId : this.worker(to).native!.threadId; - await this.queue(sender, recipient, { kind: 'plaintext', text: message }, 'advisory', hostEventSequence); - } - - private async queue( - sender: string | null, - recipient: string, - message: Json, - kind: 'advisory' | 'discussion' | 'completion' = 'advisory', - hostEventSequence?: number, - record?: (id: string) => void, - ): Promise { - const id = crypto.randomUUID(), - author = sender === null ? '/morpheus' : this.identity(sender).path, - target = this.identity(recipient).path; - const member = - kind === 'discussion' && sender && sender !== this.archive.nativeControl!.rootThreadId - ? this.workerByThread(sender) - : undefined; - this.archive.nativeControl!.mailbox.push({ - id, - threadId: recipient, - author, - recipient: target, - ...(kind === 'completion' ? { communication: message } : { message }), - status: 'queued', - ...(hostEventSequence === undefined ? {} : { hostEventSequence }), - ...(kind === 'discussion' - ? { sentAt: Date.now(), originTaskId: member?.tasks.find(task => task.status === 'running')?.id } - : {}), - }); - this.mailbox?.queue(recipient); - // Save the operation response with the queued message. On restart its caller can - // recover the same submission ID even if the original socket acknowledgment was lost. - record?.(id); - this.save(); - await this.flush(recipient); - return id; - } - - private async flush(threadId: string): Promise { - const prior = this.flushing.get(threadId); - if (prior) { - await prior; - return this.flush(threadId); - } - const state = this.archive.nativeControl; - if (!this.connection(threadId) || !state) return; - const indices = this.mailbox?.queued(threadId); - const queued = indices - ? indices.map(i => state.mailbox[i]!) - : state.mailbox.filter(item => item.threadId === threadId && item.status === 'queued'); - if (!queued.length) return; - const apply = (async () => { - try { - await this.update( - threadId, - { - mailbox: queued.map(({ id, author, recipient, message, communication }) => ({ - id, - author, - recipient, - ...(communication ? { communication } : { message }), - })), - }, - queued, - indices, - ); - } catch { - // update() marks mail uncertain at handoff. A disconnect before handoff leaves it queued for the next bind. - } - })(); - this.flushing.set(threadId, apply); - try { - await apply; - } finally { - this.flushing.delete(threadId); - } - } - - private async update( - threadId: string, - fields: Json, - mail: NonNullable['mailbox'] = [], - indices: number[] = [], - ): Promise { - const previous = this.updates.get(threadId) ?? Promise.resolve(); - const apply = previous - .catch(() => {}) - .then(async () => { - const state = this.archive.nativeControl!, - connection = this.connection(threadId); - if (!connection) throw new Error('math_team_native_runtime_unloaded'); - const sequence = this.mailbox ? this.mailbox.handoff(threadId, indices) : state.sequence + 1; - state.sequence = sequence; - // Persist uncertain ownership before handing off bytes: a crash cannot replay an accepted update. - for (const item of mail) { - item.sequence = sequence; - item.status = 'uncertain'; - } - this.save(); - const response = await connection.update({ sessionId: state.sessionId, threadId, sequence, ...fields }); - if (this.mailbox) - this.mailbox.confirm( - threadId, - sequence, - response.acceptedSequence ?? null, - this.connection(threadId) === connection, - indices, - ); - else { - if (response.acceptedSequence !== sequence) throw new Error('math_team_native_mailbox_ack_changed'); - if (this.connection(threadId) !== connection) throw new Error('math_team_native_runtime_unloaded'); - } - for (const item of mail) item.status = 'accepted'; - if (mail.length) this.save(); - }); - this.updates.set(threadId, apply); - try { - await apply; - } finally { - if (this.updates.get(threadId) === apply) this.updates.delete(threadId); - } - } - - private snapshot(threadId: string): Json { - const state = this.archive.nativeControl!, - connection = this.connection(threadId); - if (connection) this.refresh(threadId, connection); - const native = threadId === state.rootThreadId ? undefined : this.workerByThread(threadId).native!; - const agent = native ? native.agent : state.rootAgent; - if (connection && agent) - return { kind: 'loaded', agent, configSnapshot: native?.configSnapshot ?? state.rootConfigSnapshot }; - return { - kind: 'unloaded', - metadata: agent - ? object(agent.metadata) - : { - agentId: threadId, - agentPath: this.identity(threadId).path, - agentNickname: null, - agentRole: null, - }, - }; - } - - private async request( - actor: string, - request: NativeAgentControlRequest, - connection: NativeAgentControlConnection, - signal: AbortSignal, - ): Promise { - const payload = request.payload; - if (request.operation === 'attach') { - const threadId = text(payload.threadId), - proposedSessionId = text(payload.sessionId); - let sessionId = proposedSessionId; - if (nativeProcess) { - const child = actor === 'lead' ? undefined : this.worker(actor).native!; - sessionId = nativeProcess.teamSessionBinding({ - action: 'attach', - lead: actor === 'lead', - request, - root: this.treeBinding(), - child: child && { threadId: child.threadId, sessionId: child.sessionId }, - }) as string; - } else { - if (request.threadId !== threadId || request.sessionId !== proposedSessionId) - return Promise.reject(new Error('math_team_native_attach_identity_changed')); - if (actor === 'lead') { - if ( - threadId !== sessionId || - (this.archive.nativeControl && - (this.archive.nativeControl.sessionId !== sessionId || - this.archive.nativeControl.rootThreadId !== threadId)) - ) - return Promise.reject(new Error('math_team_native_tree_changed')); - } else { - const native = this.worker(actor).native!; - if ( - native.threadId !== threadId || - (native.sessionId !== proposedSessionId && proposedSessionId !== threadId) - ) - return Promise.reject(new Error('math_team_native_attach_identity_changed')); - sessionId = native.sessionId; - } - } - if (actor === 'lead') - this.archive.nativeControl ??= { sessionId, rootThreadId: threadId, sequence: 0, mailbox: [] }; - const active = this.connections.get(threadId); - if (active?.connection !== connection) { - if (active) this.detach(threadId); - this.connections.set(threadId, { connection, bound: false }); - } - this.save(); - return Promise.resolve({ result: { sessionId } }); - } - const expected = actor === 'lead' ? this.archive.nativeControl?.rootThreadId : this.worker(actor).native!.threadId; - const connected = Boolean(expected && this.connections.get(expected)?.connection === connection); - let readOnly: boolean; - if (nativeProcess) - readOnly = - nativeProcess.teamSessionBinding({ - action: 'request', - expected, - connected, - request, - root: this.treeBinding(), - }) === 'read'; - else { - if ( - !connected || - request.threadId !== expected || - request.sessionId !== this.archive.nativeControl?.sessionId || - (payload.caller !== undefined && payload.caller !== expected) - ) - throw new Error('math_team_native_caller_changed'); - readOnly = ['resolve', 'list', 'childPaths', 'recordUsage', 'releaseTurn'].includes(request.operation); - } - this.refresh(expected!, connection); - if (readOnly) return this.perform(actor, request, signal).then(result => ({ result })); - const key = 'native:' + request.operationId; - const digest = mathDigest(canonicalMathJson([request.sessionId, expected, request.operation, payload])); - const receipt = this.operations.get(key); - const pending = this.pending.get(key); - if (nativeProcess) { - const replay = nativeProcess.teamSessionBinding({ - action: 'replay', - recorded: receipt?.digest, - pending: pending?.digest, - digest, - }); - if (replay === 'recorded') return Promise.resolve(object(receipt!.result)); - if (replay === 'pending') return pending!.promise; - } else { - if (pending) - return pending.digest === digest ? pending.promise : Promise.reject(new Error('math_team_call_changed')); - if (receipt) - return receipt.digest !== digest - ? Promise.reject(new Error('math_team_call_changed')) - : Promise.resolve(object(receipt.result)); - } - const operation = - request.operation === 'spawn' - ? this.spawn(actor, request, digest, signal) - : this.perform(actor, request, signal, result => this.operations.append({ key, digest, result: { result } })); - const apply = operation - .then(result => { - const response = { result }; - if (!this.operations.get(key)) { - this.operations.append({ key, digest, result: response }); - this.save(); - } - return response; - }) - .finally(() => this.pending.delete(key)); - this.pending.set(key, { promise: apply, digest }); - return apply; - } - - private async spawn(actor: string, request: NativeAgentControlRequest, requestDigest: string, signal: AbortSignal) { - if (actor !== 'lead') throw new Error('math_team_lead_operation_required'); - signal.throwIfAborted(); - if (nativeProcess) { - const workers = this.archive.workers.flatMap(({ native }) => - native - ? [ - { - agentPath: native.agentPath, - spawnOperationId: native.spawnOperationId, - spawnRequestDigest: native.spawnRequestDigest, - agent: native.agent, - configSnapshot: native.configSnapshot, - submissionId: native.submissionId, - }, - ] - : [], - ); - const launch = nativeProcess.teamSessionBinding({ - action: 'spawn', - request, - workers, - digest: requestDigest, - thread: crypto.randomUUID(), - }) as { action: 'reuse'; response: NativeTeamAcceptedChild } | { action: 'start'; input: NativeTeamSpawn }; - return launch.action === 'reuse' ? launch.response : this.lifecycle.spawn(launch.input, signal); - } - const { payload, threadId: caller } = request; - const source = nativeSource(payload.source), - agentPath = text(source.agent_path); - if (!/^\/root\/[^/]+$/u.test(agentPath) || source.parent_thread_id !== caller) - throw new Error('math_team_native_flat_team_required'); - const existing = this.archive.workers.find(worker => worker.native?.agentPath === agentPath); - if (existing) { - const native = existing.native!; - if (native.spawnOperationId !== request.operationId) throw new Error('math_team_agent_exists'); - if (native.spawnRequestDigest !== requestDigest) throw new Error('math_team_call_changed'); - if (native.agent && native.configSnapshot && native.submissionId) - return { agent: native.agent, configSnapshot: native.configSnapshot, submissionId: native.submissionId }; - throw new Error('math_team_native_spawn_unconfirmed'); - } - const threadId = crypto.randomUUID(), - input = object(payload.input), - bootstrap = { ...object(payload.bootstrap), threadId }; - const initialInput = { - author: this.identity(caller).path, - input, - startOptions: object(payload.startOptions ?? {}), - }; - return this.lifecycle.spawn( - { - sessionId: request.sessionId, - threadId, - agentPath, - parentThreadId: caller, - operationId: request.operationId, - requestDigest, - bootstrap, - initialInput, - message: nativeTeamAssignmentMessage(input), - }, - signal, - ); - } - - private async perform( - actor: string, - request: NativeAgentControlRequest, - signal: AbortSignal, - record?: (result: Json) => void, - ): Promise { - const payload = request.payload, - state = this.archive.nativeControl!, - caller = request.threadId; - const leadOnly = () => { - if (actor !== 'lead') throw new Error('math_team_lead_operation_required'); - }; - switch (request.operation) { - case 'resolve': - return this.route(request, actor === 'lead'); - case 'send': { - const { threadId: target, mode } = this.route(request, actor === 'lead'); - const input = object(payload.input); - if (mode === 'queueOnly') { - return this.inOrder(target, async () => { - const snapshot = this.snapshot(target); - const metadata = object(snapshot.kind === 'loaded' ? object(snapshot.agent).metadata : snapshot.metadata); - const submissionId = await this.queue(caller, target, object(input.message), 'discussion', undefined, id => - record?.({ threadId: target, metadata, submissionId: id }), - ); - return { threadId: target, metadata, submissionId }; - }); - } - const result = await this.inOrder(target, () => - this.lifecycle.followup( - this.workerByThread(target), - { - author: this.identity(caller).path, - input, - startOptions: object(payload.startOptions ?? {}), - }, - signal, - ), - ); - return { threadId: target, metadata: object(result.agent.metadata), submissionId: result.submissionId }; - } - case 'ensureChildLoaded': { - if (payload.parent !== caller || actor !== 'lead') throw new Error('math_team_lead_operation_required'); - const child = this.workerByThread(text(payload.child)); - if (child.native!.parentThreadId !== caller) throw new Error('math_team_native_parent_changed'); - await this.inOrder(child.native!.threadId, () => this.lifecycle.load(child)); - return {}; - } - case 'interrupt': { - const { threadId: target } = this.route(request, actor === 'lead'); - return this.inOrder(target, async () => { - const before = this.snapshot(target); - await this.lifecycle.interrupt(this.workerByThread(target)); - return before; - }); - } - case 'list': { - const prefix = payload.pathPrefix == null ? undefined : text(payload.pathPrefix); - return { - agents: [...this.connections.keys()] - .filter(id => { - if (!prefix) return true; - const agentPath = this.identity(id).path; - return agentPath === prefix || agentPath.startsWith(prefix + '/'); - }) - .flatMap(id => { - const snapshot = this.snapshot(id); - return snapshot.kind === 'loaded' ? [snapshot.agent] : []; - }), - }; - } - case 'childPaths': { - if (payload.parent !== caller) throw new Error('math_team_native_parent_changed'); - return { - paths: this.archive.workers - .filter(worker => worker.native?.parentThreadId === caller) - .map(worker => worker.native!.agentPath) - .sort(), - }; - } - case 'turnFinished': { - const outcome = object(payload.outcome); - const finishedThread = outcome.threadId ?? outcome.thread_id; - if (finishedThread !== caller) throw new Error('math_team_native_turn_identity_changed'); - if (actor === 'lead') { - if (state.rootAgent) state.rootAgent = { ...state.rootAgent, status: outcome.status }; - } else { - const native = this.worker(actor).native!; - const turnId = text(outcome.turnId ?? outcome.turn_id); - if (!native.turnId || native.turnId === turnId) { - native.lastOutcome = { turnId, status: outcome.status }; - native.status = outcome.status; - if (native.agent) native.agent = { ...native.agent, status: outcome.status }; - } - // Terminal output is a native advisory result, never a mathematical nomination. - if (payload.completionMessage && typeof payload.completionMessage === 'object') { - const parent = text(payload.parentThreadId); - if (parent !== native.parentThreadId) throw new Error('math_team_native_parent_changed'); - await this.queue(caller, parent, object(payload.completionMessage), 'completion', undefined, () => - record?.({}), - ); - } - } - this.save(); - return {}; - } - case 'admitTurn': - if (payload.threadId !== caller) throw new Error('math_team_native_turn_identity_changed'); - if (actor !== 'lead') this.lifecycle.admit(this.worker(actor), text(payload.turnId)); - else if (state.rootAgent) state.rootAgent = { ...state.rootAgent, status: 'running' }; - return { admitted: true }; - case 'releaseTurn': - return {}; - case 'recordUsage': - return {}; // Provider request receipts own accounting; no second charge or quota. - case 'configUpdate': { - leadOnly(); - for (const threadId of this.connections.keys()) - if (this.connection(threadId)) await this.update(threadId, { serviceTier: payload.serviceTier ?? null }); - this.save(); - return {}; - } - default: - throw new Error('math_team_native_operation_unknown:' + request.operation); - } - } -} diff --git a/src/solver/agentTeamOperations.ts b/src/solver/agentTeamOperations.ts deleted file mode 100644 index 56a6ce2e..00000000 --- a/src/solver/agentTeamOperations.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { AgentTeamState } from './agentTeamState'; - -type OperationReceipt = AgentTeamState['operations'][number]; - -/** One index for both callers. The append-only array remains the checkpoint format. */ -export class AgentTeamOperations { - private readonly byKey = new Map(); - - constructor(private readonly receipts: OperationReceipt[]) { - for (const receipt of receipts) { - // Match the old find() behavior for checkpoints with repeated keys. - if (!this.byKey.has(receipt.key)) this.byKey.set(receipt.key, receipt); - } - } - - get(key: string): OperationReceipt | undefined { - return this.byKey.get(key); - } - - append(receipt: OperationReceipt): void { - this.receipts.push(receipt); - if (!this.byKey.has(receipt.key)) this.byKey.set(receipt.key, receipt); - } -} diff --git a/src/solver/agentTeamProfiles.ts b/src/solver/agentTeamProfiles.ts index fb62eb26..dea2d856 100644 --- a/src/solver/agentTeamProfiles.ts +++ b/src/solver/agentTeamProfiles.ts @@ -2,7 +2,6 @@ import fs from 'node:fs'; import path from 'node:path'; import { z } from 'zod'; import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills'; -import { NativeAgentControlInputError } from '../runtime/nativeAgentControl'; import { mathDigest } from '../math/mathRuntimeIo'; import type { ContextSection } from './contextCompiler'; import type { FrozenPersonalExpert } from './personalExpertSchema'; @@ -159,33 +158,6 @@ export function agentTeamProfileSelection(message: string): string[] { ]; } -/** New assignments must load every explicit selection; historical records remain readable below. */ -export function resolveNewMemberProfiles( - skill: MathAgentSkill, - message: string, - cards?: readonly FrozenPersonalExpert[], -) { - const selected = agentTeamProfileSelection(message); - if (selected.includes('lead')) - throw new NativeAgentControlInputError( - 'math_team_profile_reserved: lead belongs to the coordinator. Replace it in Profiles: with a member specialty ' + - '(e.g. prover, researcher or engineer) for the assigned gap, or omit the header.', - ); - if (selected.length) assertMathAgentSkillsCurrent([skill]); - const profiles = resolveProfiles(skill, selected, false, cards); - const emptyHeader = !selected.length && message.trimStart().startsWith('Profiles:'); - if (emptyHeader || profiles.evidence.unresolved.length) - throw new NativeAgentControlInputError( - 'math_team_profile_unresolved: ' + - (emptyHeader ? 'empty Profiles: header' : JSON.stringify(profiles.evidence.unresolved)) + - '. Use only comma-separated IDs or slugs from the pinned Skill (references/team-roles.md or references/domain-experts.md)' + - (cards?.length ? " or asset: from this run's personal expert catalogue" : '') + - '. ' + - 'Put "Profiles: prover" on its own line before the assignment, after the optional Route: line in native messages. The Profiles: line is optional. Describe custom expertise in the body.', - ); - return profiles; -} - export function resolveAgentTeamLeadProfile(skill: MathAgentSkill) { return resolveProfiles(skill, ['lead'], true); } diff --git a/src/solver/agentTeamProof.ts b/src/solver/agentTeamProof.ts index e0026910..540e5584 100644 --- a/src/solver/agentTeamProof.ts +++ b/src/solver/agentTeamProof.ts @@ -1,45 +1,20 @@ import fs from 'node:fs'; import path from 'node:path'; import { z } from 'zod'; -import { canonicalMathJson, mathDigest, readMathText, writeMathTextDurable } from '../math/mathRuntimeIo'; +import { canonicalMathJson, mathDigest, readMathText } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; -import { inspectScopedLeanDeclarations, leanDeclarationKeys } from '../math/leanSource'; -import { leanNameWithoutRoot, maskLeanCommentsAndStrings } from '../math/leanSyntax'; -import { bindLeanPackages } from '../math/leanDiagnostics'; -import { formalVerificationToolIdentity } from '../math/verifier'; -import { hasDeterministicLeanFailure, proofReuseEnvironment } from './proofReuse'; +import { teamExposureKind, teamSpawnHistory } from './agentTeamState'; +import type { DeclarationChange } from './cooperativeProof'; import { - applyTaskChanges, - ownedSourceDigest, - taskChanges, - TaskIntegrationMissingDeclarationError, - type DeclarationChange, -} from './cooperativeProof'; -import { - checkTeamDeclarationArtifacts, - DeclarationArtifactCheckError, - DeclarationSubmissionError, teamDeclarationListSchema, validateDeclarationArtifact, type DeclarationArtifact, type DeclarationArtifactIdentity, type DeclarationSubmission, } from './declarationArtifacts'; -import { - assertSolverSources, - committedSource, - commitSolverSources, - git, - solverProofImports, - withSolverWorktree, -} from './problem'; -import { locateKnowledgeDeclaration } from './theoremKnowledge'; -import { solverSourceDigest } from './modules/evidence'; -import { archiveAgentTeamCommits, importAgentTeamCommit } from './agentTeamWorkspace'; -import { teamExposureKind, teamSpawnHistory, type AgentTeamAdoptionDependency } from './agentTeamState'; type Identity = { runId: string; problemReceiptDigest: string; environmentDigest: string }; -export type AgentTeamProofProvenance = z.infer; +type AgentTeamProofProvenance = z.infer; export type AgentTeamProofDelivery = Readonly< Identity & { schema: 'theorem-os.agent-team-proof-delivery.v1'; @@ -68,42 +43,12 @@ export type AgentTeamProofAdoption = Readonly< artifacts: readonly DeclarationArtifact[]; } >; -type AgentTeamProofAdoptionIntent = Readonly< - Identity & { - schema: 'theorem-os.agent-team-proof-adoption-intent.v1'; - id: string; - worktree: string; - adoption: AgentTeamProofAdoption; - } ->; -type CheckInput = { +type AdoptionLocation = { state: DeclarationArtifactIdentity; - env: NodeJS.ProcessEnv; - signal: AbortSignal; - timeoutMs?: number; - assertWriterStopped: () => void; + worktree: string; + expectedCommit: string; evidenceDirectory: string; }; -export type TeamFailureCache = Map; -export class ReusedTeamCheckFailure extends DeclarationArtifactCheckError { - constructor( - readonly previous: { commit: string; agentId: string }, - error: DeclarationArtifactCheckError, - ) { - super(error.declaration, error.verification); - } -} -export class MissingAdoptionDependencyError extends DeclarationSubmissionError { - constructor( - message: string, - readonly missing: AgentTeamAdoptionDependency[], - cause: Error, - ) { - super(message, { cause }); - } -} -type IntegrationInput = CheckInput & { delivery: AgentTeamProofDelivery; worktree: string; expectedCommit: string }; -type AdoptionLocation = Pick; const hash = z.string().regex(/^[a-f0-9]{64}$/u), commitHash = z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u); const identitySchema = { runId: z.string().min(1), problemReceiptDigest: hash, environmentDigest: hash }; @@ -130,7 +75,7 @@ const provenanceSchema = z .optional(), }) .strict(); -export const deliverySchema = z +const deliverySchema = z .object({ schema: z.literal('theorem-os.agent-team-proof-delivery.v1'), id: hash, @@ -228,8 +173,8 @@ export function readAgentTeamProofDelivery(file: string, state: DeclarationArtif } function evidenceFile( - input: Pick, - kind: 'deliveries' | 'adoptions' | 'adoption-intents', + input: Pick, + kind: 'adoptions' | 'adoption-intents', id: string, worktree: string, ): string { @@ -241,22 +186,6 @@ function evidenceFile( return file; } -function persist( - input: CheckInput, - kind: 'deliveries' | 'adoptions' | 'adoption-intents', - record: AgentTeamProofDelivery | AgentTeamProofAdoption | AgentTeamProofAdoptionIntent, - worktree: string, -): void { - const file = evidenceFile(input, kind, record.id, worktree), - directory = path.dirname(file); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - assertMathCanonicalPath(file); - const text = canonicalMathJson(record); - if (fs.existsSync(file)) { - if (readMathText(file) !== text) return fail('evidence_changed'); - } else writeMathTextDurable(file, text, 0o400); -} - const intentId = (input: AdoptionLocation, delivery: AgentTeamProofDelivery) => mathDigest( canonicalMathJson({ @@ -327,508 +256,3 @@ export function readRecordedAgentTeamAdoption( return fail('adoption_identity_changed'); return receipt; } - -function retainEvidence( - input: CheckInput, - worktree: string, - artifacts: readonly DeclarationArtifact[], - commit: string, -): void { - const commits = [...new Set([commit, ...artifacts.map(artifact => artifact.proof.verification.targetCommit)])]; - // Validate the host evidence location before creating or moving source objects there. - evidenceFile(input, 'deliveries', 'source-archive', worktree); - archiveAgentTeamCommits(path.join(input.evidenceDirectory, 'sources.git'), worktree, commits); - for (const id of commits) { - commitHash.parse(id); - git(worktree, ['update-ref', `refs/math/agent-team/evidence/${id}`, id]); - } -} - -function importEvidenceCommit(input: IntegrationInput, commit: string): void { - try { - git(input.worktree, ['cat-file', '-e', `${commit}^{commit}`]); - return; - } catch { - /* An independent receiver may not have this checked source yet. */ - } - evidenceFile(input, 'deliveries', 'source-archive', input.worktree); - const archive = path.join(input.evidenceDirectory, 'sources.git'); - let archived = false; - if (fs.existsSync(archive)) { - try { - git(archive, ['cat-file', '-e', `${commit}^{commit}`]); - archived = true; - } catch { - /* Legacy records can predate the host-owned archive. */ - } - } - // Legacy shared-worktree evidence is retained in the frozen primary repository. - // Never read a mutable/deleted member path supplied by a delivery record. - if (!archived) archiveAgentTeamCommits(archive, input.state.problem.workspace, [commit]); - importAgentTeamCommit(archive, input.worktree, commit); -} - -/** Reuse committed bytes only within one delivery inspection. */ -function readDeliverySources(worktree: string, projectRelative: string) { - const sources = new Map(); - return (revision: string, file: string) => { - const key = revision + '\0' + file; - let source = sources.get(key); - if (source === undefined) { - source = committedSource(worktree, revision, `${projectRelative}/${file}`); - sources.set(key, source); - } - return source; - }; -} - -function missingAdoptionDependency( - error: unknown, - delivery: AgentTeamProofDelivery, - problem: DeclarationArtifactIdentity['problem'], - readProducer: ReturnType, - readRecipient: ReturnType, - commit: string, -): MissingAdoptionDependencyError | undefined { - if (!(error instanceof DeclarationArtifactCheckError) || !hasDeterministicLeanFailure(error.verification)) return; - const unknown = [ - ...error.message.matchAll(/Unknown (?:identifier|constant) `([^`\n]+)`|The identifier `([^`\n]+)` is unknown/giu), - ].map(match => match[1] ?? match[2]!); - if (!unknown.length) return; - const references = delivery.artifacts.find( - item => item.declaration.name === error.declaration.name && item.declaration.file === error.declaration.file, - )?.references; - const owned = problem.ownedFiles.filter(file => file.endsWith('.lean')); - const namesAt = (readSource: ReturnType, revision: string) => { - const namesByFile = new Map>(); - return (file: string) => { - let names = namesByFile.get(file); - if (!names) { - names = new Set(inspectScopedLeanDeclarations(readSource(revision, file)).map(item => item.qualifiedName)); - namesByFile.set(file, names); - } - return names; - }; - }; - const producerNamesIn = namesAt(readProducer, delivery.commit), - recipientNamesIn = namesAt(readRecipient, commit); - // Lean may report a name relative to the current namespace, including a qualified suffix. - const matchesName = (reported: string, name: string) => - reported.startsWith('_root_.') - ? leanNameWithoutRoot(reported) === name - : reported === name || name.endsWith('.' + reported); - const candidates = new Map(); - const unmatched: string[] = []; - const inputs = references - ? [...references.statement, ...references.proof].filter(({ file }) => owned.includes(file)) - : []; - for (const reported of new Set(unknown)) { - // Lean references include generated constants. Only declarations spelled out in - // the producer can be supplied by a checked delivery. - const named = inputs.filter( - ({ file, name }) => - matchesName(reported, name) && producerNamesIn(file).has(name) && !recipientNamesIn(file).has(name), - ); - if (!named.length) unmatched.push(reported); - for (const entry of named) candidates.set(entry.file + '\0' + entry.name, entry); - } - if (unmatched.length) { - // Tactics can use names that disappear from the elaborated proof, such as an unused - // simp argument. Require the reported token in the checked source and a unique missing match. - const source = readProducer(delivery.commit, error.declaration.file); - const { bodyOffset, endOffset } = locateKnowledgeDeclaration(source, error.declaration.name); - const words = new Set( - maskLeanCommentsAndStrings(source.slice(bodyOffset, endOffset)).match( - /[\p{L}_][\p{L}\p{M}\p{N}_'?!]*(?:\.[\p{L}_][\p{L}\p{M}\p{N}_'?!]*)*/gu, - ) ?? [], - ); - for (const reported of unmatched) { - if (!words.has(reported)) continue; - const named = owned.flatMap(file => - [...producerNamesIn(file)] - .filter(name => matchesName(reported, name) && !recipientNamesIn(file).has(name)) - .map(name => ({ file, name })), - ); - const [entry] = named; - if (entry && named.length === 1) candidates.set(entry.file + '\0' + entry.name, entry); - } - } - const missing = [...candidates.values()]; - if (missing.length) { - return new MissingAdoptionDependencyError( - `The recipient is missing ${missing.map(({ file, name }) => `${name} (${file})`).join(', ')}. ` + - 'Adopt the checked delivery for the missing declarations into this workspace, then retry.\n' + - error.message, - missing, - error, - ); - } -} - -/** Every changed declaration must be named and independently checked; metadata never widens source ownership. */ -function deliveryPatch( - problem: DeclarationArtifactIdentity['problem'], - worktree: string, - seedCommit: string, - commit: string, - declarations: DeclarationSubmission['declarations'], - readSource = readDeliverySources(worktree, problem.projectRelative), -) { - if (declarations.some(declaration => !problem.ownedFiles.includes(declaration.file))) - return fail('declaration_outside_ownership'); - git(worktree, ['merge-base', '--is-ancestor', seedCommit, commit]); - if ( - problem.ownedFiles.some( - file => !file.endsWith('.lean') && readSource(seedCommit, file) !== readSource(commit, file), - ) - ) - return fail('undeclared_source_change'); - const changes = taskChanges(problem, worktree, commit, undefined, { seedCommit }, readSource); - const changeKey = (file: string, name: string) => `${file}\0${name}`; - const firstChanges = new Map(); - // A declaration can have both a body change and a later reorder entry. - for (const change of changes) { - const key = changeKey(change.file, change.name); - if (!firstChanges.has(key)) firstChanges.set(key, change); - } - const keysByFile = new Map>(); - const declared = new Set( - declarations.map(declaration => { - const source = readSource(commit, declaration.file); - let location: ReturnType; - try { - location = locateKnowledgeDeclaration(source, declaration.name); - } catch (error) { - if (error instanceof Error && error.message === 'math_knowledge_declaration_missing_or_ambiguous') - return fail('declaration_missing'); - throw error; - } - let keys = keysByFile.get(declaration.file); - if (!keys) { - keys = leanDeclarationKeys(source); - keysByFile.set(declaration.file, keys); - } - const name = keys.get(location.startOffset); - if (!name) return fail('declaration_missing'); - const key = changeKey(declaration.file, name), - change = firstChanges.get(key); - if (declaration.kind === 'definition' && (!change || change.before !== undefined)) - throw new DeclarationSubmissionError('math_agent_team_definition_must_be_new:' + declaration.name); - if (change?.before && change.before !== change.after) { - const prior = readSource(seedCommit, declaration.file); - if (locateKnowledgeDeclaration(prior, declaration.name).kind === 'definition') - throw new DeclarationSubmissionError('math_agent_team_cannot_replace_definition:' + declaration.name); - } - return key; - }), - ); - if ( - declared.size !== declarations.length || - changes.some(change => !declared.has(changeKey(change.file, change.name))) - ) - return fail('undeclared_source_change'); - const imports = problem.ownedFiles - .filter(file => file.endsWith('.lean')) - .flatMap(file => { - const before = solverProofImports(problem, readSource(seedCommit, file)); - const after = solverProofImports(problem, readSource(commit, file)); - if (before.some(module => !after.includes(module))) return fail('import_removed'); - return after.filter(module => !before.includes(module)).map(module => ({ file, module })); - }); - return { changes, imports }; -} - -function frozenSource(input: CheckInput, worktree: string, commit: string): () => void { - const { state } = input, - { problem } = state; - const identity = canonicalMathJson(identityOf(state)); - return () => { - input.signal.throwIfAborted(); - input.assertWriterStopped(); - assertSolverSources(problem, worktree); - if (canonicalMathJson(identityOf(state)) !== identity) return fail('run_identity_changed'); - if ( - git(worktree, ['rev-parse', 'HEAD']) !== commit || - git(worktree, [ - 'status', - '--porcelain', - '--', - ...problem.ownedFiles.map(file => path.join(problem.projectRelative, file)), - ]) - ) - return fail('source_changed'); - }; -} - -/** Called only after the child writer has stopped. No mutable child files become proof evidence. */ -export async function checkAgentTeamProofDelivery( - input: CheckInput & { - agentId: string; - worktree: string; - seedCommit: string; - declarations: DeclarationSubmission['declarations']; - provenance?: AgentTeamProofProvenance; - failureCache?: TeamFailureCache; - inferredHelperTypes?: string[]; - }, -): Promise { - const declarations = teamDeclarationListSchema.parse(input.declarations); - const agentId = deliverySchema.shape.agentId.parse(input.agentId); - commitHash.parse(input.seedCommit); - assertMathCanonicalPath(input.worktree); - input.signal.throwIfAborted(); - input.assertWriterStopped(); - const { problem } = input.state; - if (input.worktree === problem.workspace) return fail('worktree_not_isolated'); - const commit = commitSolverSources(problem, input.worktree), - stable = frozenSource(input, input.worktree, commit); - stable(); - const patch = deliveryPatch(problem, input.worktree, input.seedCommit, commit, declarations); - const project = path.join(input.worktree, problem.projectRelative); - const environmentKey = () => { - const env = proofReuseEnvironment(project, input.env); - const tools = env.reusable && env.digest && formalVerificationToolIdentity(project, env.env); - return tools ? [env.digest, tools] : undefined; - }; - 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, - inferredExpectedTypes: new Set(input.inferredHelperTypes), - assertFrozenSource: stable, - }).catch(error => { - if ( - key && - input.failureCache && - error instanceof DeclarationArtifactCheckError && - hasDeterministicLeanFailure(error.verification) - ) { - stable(); - if (canonicalMathJson(environmentKey() ?? null) === canonicalMathJson(environment)) { - if (input.failureCache.size >= 32) input.failureCache.delete(input.failureCache.keys().next().value!); - input.failureCache.set(key, { commit, agentId, error }); - } - } - throw error; - }); - stable(); - 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); - retainEvidence(input, input.worktree, artifacts, commit); - persist(input, 'deliveries', delivery, input.worktree); - stable(); - return delivery; -} - -async function finishAdoption( - input: IntegrationInput, - adoption: AgentTeamProofAdoption, -): Promise { - const stable = frozenSource(input, input.worktree, adoption.commit); - stable(); - if (!sameIdentity(adoption, input.state)) return fail('adoption_identity_changed'); - if (ownedSourceDigest(input.state.problem, input.worktree, adoption.commit) !== adoption.sourceDigest) - return fail('adoption_source_changed'); - persist(input, 'adoptions', adoption, input.worktree); - stable(); - return adoption; -} - -/** A persisted intent may finish only its exact stopped-writer transition, never an unrelated or later HEAD. */ -async function resumeAdoption( - input: IntegrationInput, - delivery: AgentTeamProofDelivery, - adoption: AgentTeamProofAdoption, -): Promise { - const { problem } = input.state, - head = git(input.worktree, ['rev-parse', 'HEAD']); - if (head !== adoption.beforeCommit && head !== adoption.commit) return fail('source_changed'); - const stable = frozenSource(input, input.worktree, head); - stable(); - const parents = git(input.worktree, ['rev-list', '--parents', '-n', '1', adoption.commit]).split(' '); - if (adoption.commit !== adoption.beforeCommit && (parents.length !== 2 || parents[1] !== adoption.beforeCommit)) - return fail('adoption_source_changed'); - const owned = new Set(problem.ownedFiles.map(file => path.join(problem.projectRelative, file))); - if ( - git(input.worktree, ['diff', '--name-only', adoption.beforeCommit, adoption.commit]) - .split('\n') - .filter(Boolean) - .some(file => !owned.has(file)) - ) - return fail('adoption_source_changed'); - // Reconstruct the authorized patch as well as verifying hashes: a different committed tree cannot become a recovered success. - await withSolverWorktree(input.worktree, adoption.beforeCommit, async checkout => { - assertSolverSources(problem, checkout); - applyTaskChanges(problem, checkout, delivery.changes, [...delivery.imports]); - if (solverSourceDigest(problem, checkout) !== adoption.sourceDigest) return fail('adoption_source_changed'); - }); - await withSolverWorktree(input.worktree, adoption.commit, async checkout => { - assertSolverSources(problem, checkout); - if (ownedSourceDigest(problem, checkout, adoption.commit) !== adoption.sourceDigest) - return fail('adoption_source_changed'); - if (head !== adoption.commit) { - // A crash before FF has not adopted anything. Check the saved candidate anew before continuing that transition. - const packages = path.join(input.worktree, problem.projectRelative, '.lake', 'packages'); - 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, - inferredExpectedTypes: new Set(delivery.inferredHelperTypes), - assertFrozenSource: () => { - stable(); - checkoutStable(); - }, - }); - stable(); - checkoutStable(); - } - }); - stable(); - if (head !== adoption.commit) git(input.worktree, ['merge', '--ff-only', '--no-edit', adoption.commit]); - return finishAdoption(input, adoption); -} - -/** Stage and recheck off-line, persist the checked intent, then FF. Retrying the same expectedCommit is idempotent. */ -export async function integrateAgentTeamProofDelivery(input: IntegrationInput): Promise { - const delivery = validateDelivery(input.delivery, input.state), - { problem } = input.state; - commitHash.parse(input.expectedCommit); - assertMathCanonicalPath(input.worktree); - input.signal.throwIfAborted(); - input.assertWriterStopped(); - const pending = readIntent(input, delivery); - const stable = frozenSource(input, input.worktree, input.expectedCommit); - if (!pending) stable(); - // New deliveries are independent of the mutable member directory. Legacy evidence - // already in the target repository remains readable without a new source lookup. - importEvidenceCommit(input, delivery.commit); - if (pending) importEvidenceCommit(input, pending.commit); - return withSolverWorktree(input.worktree, delivery.commit, async frozen => { - assertSolverSources(problem, frozen); - const readSource = readDeliverySources(frozen, problem.projectRelative); - if (ownedSourceDigest(problem, frozen, delivery.commit, readSource) !== delivery.sourceDigest) - return fail('delivery_source_changed'); - const patch = deliveryPatch( - problem, - frozen, - delivery.seedCommit, - delivery.commit, - delivery.declarations, - readSource, - ); - if (canonicalMathJson(patch) !== canonicalMathJson({ changes: delivery.changes, imports: delivery.imports })) - return fail('delivery_patch_changed'); - if (pending) return resumeAdoption(input, delivery, pending); - return withSolverWorktree(input.worktree, input.expectedCommit, async checkout => { - const packages = path.join(input.worktree, problem.projectRelative, '.lake', 'packages'); - if (fs.existsSync(packages)) bindLeanPackages(path.join(checkout, problem.projectRelative), packages); - try { - applyTaskChanges(problem, checkout, patch.changes, patch.imports); - } catch (error) { - if (!(error instanceof TaskIntegrationMissingDeclarationError)) throw error; - const { name, file } = error.declaration; - const seed = readSource(delivery.seedCommit, file), - keys = leanDeclarationKeys(seed); - const declaration = inspectScopedLeanDeclarations(seed).find(item => keys.get(item.startOffset) === name); - if (error.role === 'anchor' && !declaration) throw error; - const required = error.role === 'anchor' ? `the declaration anchor ${name}` : name; - throw new MissingAdoptionDependencyError( - `${error.message}\nThis patch requires ${required} (${file}) at the delivery's seed revision ${delivery.seedCommit}. ` + - 'Adopt a checked delivery containing that previous declaration, then retry.', - declaration ? [{ file, name: declaration.qualifiedName }] : [], - error, - ); - } - const commit = commitSolverSources(problem, checkout), - checkoutStable = frozenSource(input, checkout, commit); - const assertAdoptionSources = () => { - stable(); - checkoutStable(); - }; - const artifacts = await checkTeamDeclarationArtifacts({ - ...input, - worktree: checkout, - commit, - declarations: delivery.declarations, - inferredExpectedTypes: new Set(delivery.inferredHelperTypes), - assertFrozenSource: assertAdoptionSources, - }).catch(error => { - throw ( - missingAdoptionDependency( - error, - delivery, - problem, - readSource, - readDeliverySources(checkout, problem.projectRelative), - commit, - ) ?? error - ); - }); - assertAdoptionSources(); - const record: AgentTeamProofAdoption = { - schema: 'theorem-os.agent-team-proof-adoption.v1', - id: '', - ...identityOf(input.state), - deliveryId: delivery.id, - beforeCommit: input.expectedCommit, - commit, - sourceDigest: ownedSourceDigest(problem, checkout, commit), - artifacts, - }; - const adoption = { ...record, id: recordId(record) }; - retainEvidence(input, input.worktree, artifacts, commit); - persist( - input, - 'adoption-intents', - { - schema: 'theorem-os.agent-team-proof-adoption-intent.v1', - id: intentId(input, delivery), - ...identityOf(input.state), - worktree: input.worktree, - adoption, - }, - input.worktree, - ); - // This is checked adoption evidence, not whole-problem acceptance. Journals stay with the primary. - assertAdoptionSources(); - git(input.worktree, ['merge', '--ff-only', '--no-edit', commit]); - return finishAdoption(input, adoption); - }); - }); -} diff --git a/src/solver/agentTeamState.ts b/src/solver/agentTeamState.ts index e4456e10..5c0bb42c 100644 --- a/src/solver/agentTeamState.ts +++ b/src/solver/agentTeamState.ts @@ -209,7 +209,7 @@ export const agentTeamStateSchema = z ) .optional(), /** Absent retains the historical dynamic-tool team on resume. */ - transport: z.enum(['host-tools', 'native-agent-control']).optional(), + transport: z.enum(['host-tools', 'native-agent-control', 'codex-shared']).optional(), nativeControl: z .object({ sessionId: z.string(), diff --git a/src/solver/agentTeamTool.ts b/src/solver/agentTeamTool.ts deleted file mode 100644 index 810e6923..00000000 --- a/src/solver/agentTeamTool.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { z } from 'zod'; -import type { MathAgentToolDefinition } from '../runtime/agentSession'; -import { declarationSubmissionSchema } from './declarationArtifacts'; -import { portfolioRouteIdSchema, routeRetirementSchema } from './routeControl'; -import { nativePlanApprovalSchema } from './planApproval'; - -type Json = Record; -const text = z.string().trim().min(1).max(16000); -const id = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/u); -const submission = z - .object({ - operation: z.literal('submit'), - summary: text, - objectiveRevision: z.number().int().positive().optional(), - declarations: declarationSubmissionSchema.shape.declarations, - helpersOnly: z.boolean().optional(), - }) - .strict(); -// Saved threads can still send the old operation. Keep its parsed form for the operation journal. -export const legacyHelperSubmissionSchema = submission - .omit({ helpersOnly: true }) - .extend({ operation: z.literal('submit_helpers') }); - -export const agentTeamRequestSchema = z.discriminatedUnion('operation', [ - nativePlanApprovalSchema, - z.object({ operation: z.literal('finish'), summary: text }).strict(), - z.object({ operation: z.literal('yield'), reason: text }).strict(), - z - .object({ - operation: z.literal('history'), - agentId: id.optional(), - offset: z.number().int().nonnegative().optional(), - limit: z.number().int().min(1).max(8).optional(), - }) - .strict(), - z - .object({ - operation: z.literal('inspect'), - deliveryId: z.string().regex(/^[a-f0-9]{64}$/u), - changeIndex: z.number().int().nonnegative().optional(), - offset: z.number().int().nonnegative().optional(), - limit: z.number().int().min(1).max(16000).optional(), - }) - .strict(), - 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(), - submission, - z - .object({ operation: z.literal('adopt'), deliveryId: z.string().regex(/^[a-f0-9]{64}$/u), targetId: id.optional() }) - .strict(), - routeRetirementSchema.extend({ operation: z.literal('retire_route') }), - z - .object({ - operation: z.literal('route_summary'), - routeId: portfolioRouteIdSchema.optional(), - includeRetired: z.boolean().optional(), - }) - .strict(), -]); - -const deliveryOperations = new Set(['yield', 'submit']); -const leadOperations = new Set(['publish_plan', 'finish', 'adopt', 'retire_route']); - -function operationsFor(actor: string, approval: boolean) { - return agentTeamRequestSchema.options.filter(option => { - const operation = option.shape.operation.value; - if (operation === 'publish_plan' && !approval) return false; - return actor === 'lead' ? !deliveryOperations.has(operation) : !leadOperations.has(operation); - }); -} - -export function agentTeamOperationAllowed(actor: string, operation: string, approval = false) { - return operationsFor(actor, approval).some(option => option.shape.operation.value === operation); -} - -/** Only the concrete schema kinds used by this interface; refinements still run on the host. */ -function fieldSchema(value: z.ZodTypeAny): Json { - if (value instanceof z.ZodOptional) return fieldSchema(value.unwrap()); - if (value instanceof z.ZodEffects) return fieldSchema(value.innerType()); - if (value instanceof z.ZodString) { - const schema: Json = { type: 'string' }; - for (const check of value._def.checks) { - if (check.kind === 'min') schema.minLength = check.value; - if (check.kind === 'max') schema.maxLength = check.value; - if (check.kind === 'regex') schema.pattern = check.regex.source; - } - return schema; - } - if (value instanceof z.ZodNumber) { - const schema: Json = { type: value.isInt ? 'integer' : 'number' }; - if (value.minValue !== null) schema.minimum = value.minValue; - 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), - ...(value._def.minLength ? { minItems: value._def.minLength.value } : {}), - ...(value._def.maxLength ? { maxItems: value._def.maxLength.value } : {}), - }; - if (value instanceof z.ZodObject) { - const shape = value.shape as z.ZodRawShape; - return { - type: 'object', - properties: Object.fromEntries(Object.entries(shape).map(([key, field]) => [key, fieldSchema(field)])), - required: Object.keys(shape).filter(key => !shape[key]!.isOptional()), - additionalProperties: false, - }; - } - throw new Error('math_team_tool_schema_kind_unsupported'); -} - -function operationContracts(actor: string, approval: boolean) { - return operationsFor(actor, approval).map(option => { - const schema = fieldSchema(option); - // Old native threads can still submit the previously accepted optional field. - // The advertised interface binds the current task itself. - delete schema.properties.objectiveRevision; - return { operation: option.shape.operation.value, schema }; - }); -} - -function contractText(operation: string, schema: Json): string { - const required = (schema.required as string[]).filter(key => key !== 'operation'); - const optional = Object.keys(schema.properties).filter(key => key !== 'operation' && !required.includes(key)); - return ( - `${operation}: required ${required.length ? required.join(', ') : 'none'}; optional ${optional.length ? optional.join(', ') : 'none'}; other fields forbidden.` + - (operation === 'inspect' - ? ' For more source, pass a changeIndex from the overview and its nextOffset. offset and limit require changeIndex and count Unicode code points.' - : '') - ); -} - -/** The same contracts drive advertised fields and corrective feedback. */ -export function agentTeamArgumentFeedback(actor: string, args: unknown, error: z.ZodError, approval = false) { - const operation = args && typeof args === 'object' && 'operation' in args ? (args as Json).operation : undefined; - const contracts = operationContracts(actor, approval); - const contract = contracts.find(item => item.operation === operation); - return { - ok: false, - error: 'math_team_arguments_invalid', - detail: error.message, - ...(contract - ? { contract: contract.schema, hint: contractText(contract.operation, contract.schema) } - : { - allowedOperations: contracts.map(item => item.operation), - hint: 'Choose an advertised operation for this caller.', - }), - }; -} - -/** Advertise required/allowed fields per operation, retaining the native single-entry interface. */ -export function agentTeamToolDefinition(actor: string, approval = false): MathAgentToolDefinition { - const lead = actor === 'lead', - contracts = operationContracts(actor, approval); - const properties: Json = {}; - for (const { schema } of contracts) Object.assign(properties, schema.properties); - properties.operation = { type: 'string', enum: contracts.map(item => item.operation) }; - const purpose = lead - ? 'Mathematical host interface for the Lead. Native collaboration tools manage agent identities, spawning, followups, messages and interruption. Adopt rechecks a delivery in the saved consumer draft before merging. Inspect shows details on demand. Return with saved original proofs for independent checking. Finish requests early handoff. ' - : 'Mathematical host interface for a proof-writing member. Native collaboration tools deliver messages. Submit exact saved declarations, then return for stopped-writer checking. Yield preserves this task and draft for native followup after dependencies are integrated. '; - return { - name: 'theoremos_team', - description: - purpose + - 'History pages complete business task text; inspect and inspect-research read fixed evidence. agentId/targetId refer to the workspace member IDs shown in team observations; native collaboration targets use canonical paths or thread IDs. ' + - 'Configured limits apply to the shared run. ' + - (lead && approval - ? 'While approval is required, first call publish_plan with goals [{theoremName,objective}] for all original targets and optional investigations, then return. Follow the host approval status before starting proof work. ' - : '') + - 'Only the host publishes checked proof evidence; original proof acceptance remains independent. Inspection and adoption retain peer-result provenance. ' + - (lead - ? 'Use retire_route to record a refutation and cancel all unfinished work tagged with that route. ' + - 'For native spawn_agent or followup_task, put an optional Route: ROUTE_ID line first, then an optional Profiles: line of comma-separated IDs or slugs, then the assignment. ' - : 'Set helpersOnly:true on submit to share standalone helpers and keep the assignment open. The host makes checked helpers available to peers before their next turn. ' + - 'Submit omits agentId because the caller and task are already bound; each declaration supplies file, name and complete closed type. For a new auxiliary def or abbrev, also set kind to "definition"; submit theorems about it as separate declarations. ') + - 'Use route_summary for a compact view of route assignments, checked helpers and recent deliveries. ' + - 'Supply only the fields for the selected operation:\n' + - contracts.map(item => contractText(item.operation, item.schema)).join('\n'), - inputSchema: { - type: 'object', - properties, - required: ['operation'], - additionalProperties: false, - oneOf: contracts.map(item => item.schema), - }, - }; -} diff --git a/src/solver/agentTeamViews.ts b/src/solver/agentTeamViews.ts index 96b44025..26907309 100644 --- a/src/solver/agentTeamViews.ts +++ b/src/solver/agentTeamViews.ts @@ -1,16 +1,14 @@ import type { SolverRunState } from './archive'; -import type { AgentTeamState, AgentTeamTask, AgentTeamWorker } from './agentTeamState'; +import type { AgentTeamTask, AgentTeamWorker } from './agentTeamState'; import { projectAgentTeamBudget } from './agentTeamBudget'; -import { buildTokenBudget } from './usageBudget'; +import { buildTokenBudget, type TokenBudget } from './usageBudget'; const WORKERS = 4, TASKS = 4, - REFERENCES = 8, - EVENTS = 8; + REFERENCES = 8; const TASK_TEXT = 600, EVENT_TEXT = 800, RESEARCH_TEXT = 2000; -const HISTORY_BYTES = 256 * 1024; type Activity = NonNullable; @@ -24,11 +22,11 @@ function preview(value: string, limit: number) { return { text: value, truncated: false }; } -function taskProjection(task: AgentTeamTask, historyOffset: number, full = false) { +function taskProjection(task: AgentTeamTask, historyOffset: number) { const textTruncated: string[] = []; const field = (name: string, value?: string) => { if (value === undefined) return undefined; - const result = full ? { text: value, truncated: false } : preview(value, TASK_TEXT); + const result = preview(value, TASK_TEXT); if (result.truncated) textTruncated.push(name); return result.text; }; @@ -40,23 +38,20 @@ function taskProjection(task: AgentTeamTask, historyOffset: number, full = false 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, - sourceCount: task.profileEvidence.sources.length, - }, - objectiveHistory: full ? task.objectiveHistory : undefined, + profileEvidence: task.profileEvidence && { + skillDigest: task.profileEvidence.skillDigest, + selected: task.profileEvidence.selected, + loaded: task.profileEvidence.loaded, + unresolved: task.profileEvidence.unresolved, + sourceCount: task.profileEvidence.sources.length, + }, objectiveHistoryCount: task.objectiveHistory?.length ?? 0, - progress: (full ? task.progress : task.progress?.slice(-1))?.map(item => ({ + progress: task.progress?.slice(-1).map(item => ({ ...item, summary: field('progress.summary', item.summary), nextStep: field('progress.nextStep', item.nextStep), - knowledgeUses: full ? item.knowledgeUses : undefined, - evidenceRefs: full ? item.evidenceRefs : undefined, + knowledgeUses: undefined, + evidenceRefs: undefined, })), progressCount: task.progress?.length ?? 0, objective: field('objective', task.message), @@ -73,13 +68,11 @@ function taskProjection(task: AgentTeamTask, historyOffset: number, full = false sourceCommit: task.sourceCommit, researchArtifactId: task.researchArtifactId, deliveryId: task.deliveryId, - failedCheck: full - ? task.failedCheck - : task.failedCheck && { - file: task.failedCheck.declaration.file, - name: task.failedCheck.declaration.name, - commit: task.failedCheck.commit, - }, + failedCheck: task.failedCheck && { + file: task.failedCheck.declaration.file, + name: task.failedCheck.declaration.name, + commit: task.failedCheck.commit, + }, declarationCount: task.declarations?.length, cancelRequested: task.cancelRequested && { ...task.cancelRequested, @@ -105,7 +98,12 @@ function activity(worker: AgentTeamWorker, current: AgentTeamTask | undefined, i return 'idle'; } -function taskBudget(state: Readonly, worker: AgentTeamWorker, task: AgentTeamTask) { +function taskBudget( + state: Readonly, + worker: AgentTeamWorker, + task: AgentTeamTask, + budget: TokenBudget, +) { const unavailable = Boolean( worker.requestUsageAccounting?.receipts?.some( receipt => receipt.taskId === task.id && receipt.status === 'missing', @@ -113,7 +111,7 @@ function taskBudget(state: Readonly, worker: AgentTeamWorker, ta (task.turns === undefined && task.status !== 'queued' && state.taskUsage?.[task.id] === undefined), ); const projection = projectAgentTeamBudget({ - tokenBudget: state.tokenBudget ?? buildTokenBudget(0, []), + tokenBudget: budget, maxTurns: state.agentTeam?.hostLimits?.maxTurns ?? Infinity, turns: state.turns ?? 0, task: { id: task.id, budget: task.budget, turns: task.turns }, @@ -134,7 +132,7 @@ function taskBudget(state: Readonly, worker: AgentTeamWorker, ta }; } -function workerTaskView(state: Readonly, worker: AgentTeamWorker, assignmentTaskId?: string) { +function workerTaskView(state: Readonly, worker: AgentTeamWorker, budget: TokenBudget) { const selected = new Set(); let current: AgentTeamTask | undefined, queuedTaskCount = 0; @@ -159,47 +157,14 @@ function workerTaskView(state: Readonly, worker: AgentTeamWorker const task = worker.tasks[index]!; return { ...taskProjection(task, index), - ...(task.id === assignmentTaskId ? { objective: undefined, profileEvidence: undefined } : {}), - budget: taskBudget(state, worker, task), + budget: taskBudget(state, worker, task, budget), }; }); return { current, tasks, queuedTaskCount }; } -function contextBudget(state: Readonly, focusAgentId?: string) { - const team = state.agentTeam, - limits = team?.hostLimits; - if (!state.tokenBudget) - return { - tokenBudget: undefined, - turns: state.turns, - maxTurns: limits?.maxTurns, - turnLimitKnown: Boolean(limits), - leadReserve: team?.leadReserve, - }; - const worker = team?.workers.find(item => item.id === focusAgentId); - const task = worker?.tasks.find(item => item.status === 'running'); - const budget = projectAgentTeamBudget({ - tokenBudget: state.tokenBudget, - maxTurns: limits?.maxTurns ?? Infinity, - turns: state.turns, - leadReserve: team?.leadReserve, - task: task && { id: task.id, budget: task.budget, turns: task.turns }, - taskUsage: state.taskUsage, - taskUsageUnavailable: - task && - worker?.requestUsageAccounting?.receipts?.some( - receipt => receipt.taskId === task.id && receipt.status === 'missing', - ), - }); - return { ...budget, maxTurns: limits?.maxTurns, turnLimitKnown: Boolean(limits) }; -} - -/** A bounded observation shared by poll/wait and both kinds of dispatch context. */ -export function agentTeamOverview( - state: Readonly, - options: { focusAgentId?: string; assignmentTaskId?: string; budget?: unknown; workerLimit?: number } = {}, -) { +/** A bounded view of historical team state for CLI inspection and the workbench. */ +export function agentTeamOverview(state: Readonly, tokenBudget: TokenBudget, workerLimit = WORKERS) { const team = state.agentTeam; const workers = team?.workers ?? []; const research = team?.researchState; @@ -218,27 +183,18 @@ export function agentTeamOverview( for (let index = adoptions.length - 1; index >= 0 && selectedAdoptions.size < REFERENCES; index--) selectedAdoptions.add(index); const rank = (worker: AgentTeamWorker) => - worker.id === options.focusAgentId + worker.status === 'running' || worker.status === 'preparing' || worker.pendingDelivery || integrating.has(worker.id) ? 0 - : worker.status === 'running' || - worker.status === 'preparing' || - worker.pendingDelivery || - integrating.has(worker.id) - ? 1 - : worker.status === 'stopped' - ? 3 - : 2; + : worker.status === 'stopped' + ? 2 + : 1; const visibleWorkers = workers .map((worker, index) => ({ worker, index, rank: rank(worker) })) .sort((left, right) => left.rank - right.rank || right.index - left.index) - .slice(0, options.workerLimit ?? WORKERS) + .slice(0, workerLimit) .sort((left, right) => left.index - right.index) .map(({ worker }) => { - const { current, tasks, queuedTaskCount } = workerTaskView( - state, - worker, - worker.id === options.focusAgentId ? options.assignmentTaskId : undefined, - ); + const { current, tasks, queuedTaskCount } = workerTaskView(state, worker, tokenBudget); const error = worker.error && preview(worker.error, TASK_TEXT); const stopReason = worker.writerStopUnconfirmed && preview(worker.writerStopUnconfirmed.reason, TASK_TEXT); const usage = buildTokenBudget(0, [worker]), @@ -348,7 +304,15 @@ export function agentTeamOverview( ...(error && error.truncated ? { errorTruncated: true } : {}), }; }), - budget: options.budget ?? contextBudget(state, options.focusAgentId), + budget: { + ...projectAgentTeamBudget({ + tokenBudget, + maxTurns: team?.hostLimits?.maxTurns ?? Infinity, + turns: state.turns, + leadReserve: team?.leadReserve, + }), + turnLimitKnown: Boolean(team?.hostLimits), + }, totals: { workers: workers.length, tasks: taskCount, @@ -375,275 +339,3 @@ export function agentTeamOverview( }, }; } - -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, project: (item: T) => Row) { - let used = 2; // Array brackets. - const selected: Row[] = []; - for (const item of rows) { - const row = project(item); - const size = Buffer.byteLength(JSON.stringify(row)) + Number(selected.length > 0); - if (used + size > bytes) break; - selected.push(row); - 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< - string | null, - { routeId: string | null; running: number; queued: number; paused: number; completed: number } - >(); - 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 [{ task, workerId, status }]; - }) - .sort( - (a, b) => routeTaskRank[a.status] - routeTaskRank[b.status] || (b.task.sequence ?? 0) - (a.task.sequence ?? 0), - ); - const routes = routeSummaryRows( - [...activeRoutes.values()].sort((a, b) => b.running + b.queued + b.paused - (a.running + a.queued + a.paused)), - 800, - route => route, - ); - const tasks = routeSummaryRows(taskRows, 2200, ({ task, workerId, status }) => ({ - taskId: oneLine(task.id, 64), - workerId, - routeId: task.routeId ?? null, - status, - workKind: task.workKind ?? null, - objective: oneLine(task.message, 100), - })); - const retirementRows = includeRetired - ? [...retired.values()].toReversed().filter(route => routeId === undefined || route.routeId === routeId) - : []; - const retiredRoutes = routeSummaryRows(retirementRows, 950, route => ({ - routeId: route.routeId, - source: route.source, - reason: oneLine(route.reason, 120), - evidenceRefCount: route.evidenceRefs?.length ?? 0, - })); - const helpers = team.landedHelpers ?? []; - const landedHelpers = routeSummaryRows(helpers.slice(-8).reverse(), 1200, helper => ({ - file: oneLine(helper.file, 96), - qualifiedName: oneLine(helper.qualifiedName, 120), - signature: oneLine(helper.type, 120), - landedAt: helper.landedAt ?? null, - })); - const deliveries = - routeId === undefined && includeRetired - ? team.deliveries - : team.deliveries.filter(delivery => byTask.has(delivery.taskId)); - const recentDeliveries = routeSummaryRows(deliveries.slice(-8).reverse(), 1250, delivery => { - const task = byTask.get(delivery.taskId); - return { - id: oneLine(delivery.id, 64), - producer: delivery.agentId, - kind: delivery.kind ?? 'proof', - declarationCount: - delivery.declarationCount ?? - (task?.deliveryId === delivery.id && task.declarations ? task.declarations.length : null), - summary: oneLine(delivery.summary ?? task?.summary ?? 'Independently checked delivery.', 100), - }; - }); - 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 { agentId, offset = 0, limit = 4 } = input; - if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 8) - throw new Error('math_team_history_arguments_invalid'); - let total: number; - let entries: { agentId: string; task: AgentTeamTask; index: number }[]; - if (agentId) { - const worker = team.workers.find(item => item.id === agentId); - if (!worker) throw new Error('math_team_agent_unknown:' + agentId); - total = worker.tasks.length; - entries = worker.tasks - .slice(offset, offset + limit) - .map((task, index) => ({ agentId, task, index: offset + index })); - } else { - const all = team.workers.flatMap(worker => - worker.tasks.map((task, index) => ({ agentId: worker.id, task, index })), - ); - all.sort( - (left, right) => - (left.task.sequence ?? Number.MAX_SAFE_INTEGER) - (right.task.sequence ?? Number.MAX_SAFE_INTEGER), - ); - total = all.length; - entries = all.slice(offset, offset + limit); - } - // Include the next whole task or leave it for the next page; a byte limit never skips a row. - // One legal task is always returned even when its full text exceeds the ordinary page budget. - const tasks = []; - let bytes = Buffer.byteLength(JSON.stringify(team.researchState ?? null)); - for (const entry of entries) { - const projection = taskProjection(entry.task, entry.index, true); - const size = Buffer.byteLength(JSON.stringify(projection)); - if (tasks.length && bytes + size > HISTORY_BYTES) break; - tasks.push({ agentId: entry.agentId, ...projection }); - bytes += size; - } - return { - ok: true, - agentId, - offset, - total, - coordination: team.coordination, - tasks, - nextOffset: offset + tasks.length < total ? offset + tasks.length : null, - ...(team.researchState && { researchState: { ...team.researchState, advisory: true } }), - declarations: - 'Task text is complete. Declaration arrays are omitted; inspect a checked deliveryId for exact declarations and evidence.', - pagination: - 'Pages stop at a complete task boundary. Follow nextOffset; a single large task can exceed the ordinary 256 KiB page budget.', - }; -} - -function eventPreview(event: AgentTeamState['events'][number]) { - const result = preview(event.text, EVENT_TEXT); - return { ...event, text: result.text, ...(result.truncated ? { textTruncated: true } : {}) }; -} - -/** A truncated preview never acknowledges the unreturned message body. */ -export function agentTeamInboxPreview( - team: Readonly, - actor: string, - after: number, - previewAfter = after, -) { - const events: ReturnType[] = []; - let through = after, - truncated = false, - more = false; - const start = Math.max(after, previewAfter); - for (const item of team.events) { - if (item.to !== actor || item.sequence <= start) continue; - if (events.length === EVENTS) { - more = true; - break; - } - const event = eventPreview(item); - events.push(event); - truncated ||= Boolean(event.textTruncated); - if (start === after && !truncated) through = event.sequence; - } - return { - after, - through, - previewAfter: start, - previewThrough: events.at(-1)?.sequence ?? start, - events, - more: more || truncated, - continuation: - 'Read addressed native messages for complete updates; use history and inspect-research for saved task results. Previews do not acknowledge their bodies.', - }; -} - -export function agentTeamRecentEvents(team: Readonly | undefined, actor: string) { - const events = team?.events ?? []; - const accepted = new Set( - team?.nativeControl?.mailbox - .filter(mail => mail.status === 'accepted' && mail.hostEventSequence !== undefined) - .map(mail => mail.hostEventSequence), - ); - const recent: ReturnType[] = []; - for (let index = events.length - 1; index >= 0 && recent.length < EVENTS; index--) { - const event = events[index]!; - if (event.to === actor && !accepted.has(event.sequence)) recent.push(eventPreview(event)); - } - return recent.reverse(); -} - -export function agentTeamDispatchTask(task: AgentTeamTask) { - return { - id: task.id, - status: task.status, - routeId: task.routeId, - summary: task.summary && preview(task.summary, TASK_TEXT).text, - error: task.error && preview(task.error, TASK_TEXT).text, - sourceCommit: task.sourceCommit, - researchArtifactId: task.researchArtifactId, - deliveryId: task.deliveryId, - failedCheck: task.failedCheck && { - file: task.failedCheck.declaration.file, - name: task.failedCheck.declaration.name, - commit: task.failedCheck.commit, - }, - cancelRequested: task.cancelRequested && { - ...task.cancelRequested, - reason: task.cancelRequested.reason && preview(task.cancelRequested.reason, TASK_TEXT).text, - }, - pauseRequested: task.pauseRequested && { - ...task.pauseRequested, - reason: preview(task.pauseRequested.reason, TASK_TEXT).text, - }, - }; -} - -export function agentTeamDispatchBudget(state: Readonly) { - const tokenBudget = state.tokenBudget; - const maxTurns = state.agentTeam?.hostLimits?.maxTurns; - return { - remainingTurns: maxTurns == null ? undefined : Math.max(0, maxTurns - state.turns), - tokenLimit: tokenBudget?.maxTotalTokens || undefined, - reportedTokens: tokenBudget?.maxTotalTokens ? tokenBudget.reportedTotalTokens : undefined, - tokenStatus: tokenBudget?.maxTotalTokens ? tokenBudget.status : undefined, - }; -} diff --git a/src/solver/agentTeamWorkspace.ts b/src/solver/agentTeamWorkspace.ts deleted file mode 100644 index ee18cec9..00000000 --- a/src/solver/agentTeamWorkspace.ts +++ /dev/null @@ -1,126 +0,0 @@ -import fs from 'node:fs'; -import { nativeProcess } from '../math/nativeProcess'; -import path from 'node:path'; -import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; -import { mathDigest } from '../math/mathRuntimeIo'; -import { git } from './problem'; - -const commitPattern = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u; - -function copySourceExcludes(source: string, metadata: string): void { - const excludes = git(source, ['rev-parse', '--path-format=absolute', '--git-path', 'info/exclude']); - if (fs.existsSync(excludes)) fs.copyFileSync(excludes, path.join(metadata, 'info', 'exclude')); -} - -/** Transfer only an explicitly authorized commit ancestry, without tags, remote refs, or alternates. */ -export function importAgentTeamCommit(source: string, target: string, commit: string): void { - if (nativeProcess) return nativeProcess.teamWorkspace({ action: 'import', source, target, commit }); - assertMathCanonicalPath(source); - assertMathCanonicalPath(target); - if (!commitPattern.test(commit)) throw new Error('math_agent_team_source_commit_invalid'); - git(target, [ - '-c', - 'core.hooksPath=/dev/null', - '-c', - 'protocol.file.allow=always', - 'fetch', - '--quiet', - '--no-tags', - '--no-write-fetch-head', - '--no-recurse-submodules', - source, - commit, - ]); - if (git(target, ['rev-parse', `${commit}^{commit}`]) !== commit) - throw new Error('math_agent_team_source_commit_changed'); -} - -/** Host-owned storage survives member cleanup and is hidden from every research process. */ -export function archiveAgentTeamCommits(directory: string, source: string, commits: readonly string[]): void { - if (nativeProcess) return nativeProcess.teamWorkspace({ action: 'archive', source, directory, commits }); - assertMathCanonicalPath(directory); - assertMathCanonicalPath(source); - if (!fs.existsSync(directory)) { - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - git(directory, [ - 'init', - '--quiet', - '--bare', - `--object-format=${git(source, ['rev-parse', '--show-object-format'])}`, - ]); - } - for (const commit of new Set(commits)) { - importAgentTeamCommit(source, directory, commit); - git(directory, ['update-ref', `refs/math/agent-team/evidence/${commit}`, commit]); - } -} - -/** A member keeps its files across stopped-writer migration; only its shared Git metadata is replaced. */ -export function prepareAgentTeamWorkspace(input: { - sourceWorktree: string; - worktree: string; - seedCommit: string; - migrationDirectory: string; -}): void { - if (nativeProcess) return nativeProcess.teamWorkspace({ action: 'prepare', ...input }); - const { sourceWorktree, worktree, seedCommit } = input; - for (const directory of [sourceWorktree, worktree, input.migrationDirectory]) assertMathCanonicalPath(directory); - if ( - isMathPathWithin(worktree, input.migrationDirectory) || - sourceWorktree === worktree || - !commitPattern.test(seedCommit) - ) - throw new Error('math_agent_team_source_workspace_invalid'); - fs.mkdirSync(worktree, { recursive: true, mode: 0o700 }); - const metadata = path.join(worktree, '.git'); - const stage = path.join(input.migrationDirectory, mathDigest(worktree)); - const replacement = path.join(stage, 'repository', '.git'), - previous = path.join(stage, 'linked.git'); - // A host crash between the two renames must leave the same draft recoverable. - if (!fs.existsSync(metadata) && fs.existsSync(previous) && fs.existsSync(replacement)) - fs.renameSync(replacement, metadata); - if (fs.existsSync(metadata) && fs.statSync(metadata).isDirectory()) { - if ( - git(worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir']) !== metadata || - fs.existsSync(path.join(metadata, 'objects', 'info', 'alternates')) - ) - throw new Error('math_agent_team_source_repository_not_independent'); - git(worktree, ['merge-base', '--is-ancestor', seedCommit, 'HEAD']); - return; - } - if (!fs.existsSync(metadata)) { - git(worktree, ['init', '--quiet', `--object-format=${git(sourceWorktree, ['rev-parse', '--show-object-format'])}`]); - importAgentTeamCommit(sourceWorktree, worktree, seedCommit); - git(worktree, ['checkout', '--quiet', '--detach', seedCommit]); - copySourceExcludes(sourceWorktree, metadata); - return; - } - const head = git(worktree, ['rev-parse', 'HEAD']); - git(worktree, ['merge-base', '--is-ancestor', seedCommit, head]); - const oldDirectory = git(worktree, ['rev-parse', '--path-format=absolute', '--git-dir']); - const oldCommon = git(worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir']); - const registration = path.join(oldDirectory, 'gitdir'); - if ( - !isMathPathWithin(path.join(oldCommon, 'worktrees'), oldDirectory) || - fs.readFileSync(registration, 'utf8').trim() !== metadata - ) - throw new Error('math_agent_team_source_worktree_registration_invalid'); - fs.rmSync(stage, { recursive: true, force: true }); - const repository = path.dirname(replacement); - fs.mkdirSync(repository, { recursive: true, mode: 0o700 }); - git(repository, ['init', '--quiet', `--object-format=${git(worktree, ['rev-parse', '--show-object-format'])}`]); - importAgentTeamCommit(worktree, repository, head); - git(repository, ['update-ref', '--no-deref', 'HEAD', head]); - git(repository, ['read-tree', head]); - copySourceExcludes(worktree, replacement); - fs.renameSync(metadata, previous); - try { - fs.renameSync(replacement, metadata); - } catch (error) { - fs.renameSync(previous, metadata); - throw error; - } - // Remove just this validated stopped worktree registration, without touching its files or other members. - fs.rmSync(oldDirectory, { recursive: true }); - fs.rmSync(stage, { recursive: true, force: true }); -} diff --git a/src/solver/continuationSeed.ts b/src/solver/continuationSeed.ts index 2948d5a2..3b49f070 100644 --- a/src/solver/continuationSeed.ts +++ b/src/solver/continuationSeed.ts @@ -1,7 +1,7 @@ import { nativeProcess } from '../math/nativeProcess'; import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; import type { SolverRunState } from './archive'; -import type { TaskProof } from './cooperativeProof'; +import type { ContinuationSnapshot } from './continuationInput'; import { committedSource, git, type SolverProblem } from './problem'; import { researchCheckpointOutputDigest, type ResearchCheckpoint } from './researchCheckpoints'; import { isAdvisoryTask, isFinalCandidateReview, taskVersion, type CooperativeTask, type TaskRecord } from './tasks'; @@ -16,9 +16,10 @@ export type ContinuationSeedOptions = { timeoutMs?: number; onProgress?: (event: string, details: Record) => void; lease?: import('../math/mathRuntimeIo').MathLease; + /** Set only after the caller has prepared and bound the destination Lean environment. */ preparedEnvironment?: NodeJS.ProcessEnv; deferChecks?: boolean; - onSeeded?: (state: SolverRunState, freshChecks: TaskProof[]) => void; + onSeeded?: (state: SolverRunState, snapshot: ContinuationSnapshot) => void; }; export type ContinuationSeedReport = { diff --git a/src/solver/cooperationShared.ts b/src/solver/cooperationShared.ts index bfd80112..074bc027 100644 --- a/src/solver/cooperationShared.ts +++ b/src/solver/cooperationShared.ts @@ -2,7 +2,6 @@ import { parseCooperationPlan, type CooperationPlanProblem } from './tasks'; import { assertPlanTaskTypeContracts } from './taskTypeContract'; 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'; @@ -124,7 +123,15 @@ export type CooperationState = { leadSeedCommit?: string; review?: ReviewRecord; error?: string; - landedHelpers?: (LandedHelper & { producer?: string })[]; + /** Helpers recorded by the historical host adoption workflow. */ + landedHelpers?: { + file: string; + qualifiedName: string; + commit: string; + type: string; + kind?: 'definition'; + producer?: string; + }[]; /** 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. */ diff --git a/src/solver/evaluation.ts b/src/solver/evaluation.ts index d32f51ff..a70a9b5d 100644 --- a/src/solver/evaluation.ts +++ b/src/solver/evaluation.ts @@ -88,7 +88,7 @@ export async function evaluateSolverProof( receipt: ProofCheck, env: NodeJS.ProcessEnv, signal: AbortSignal, - options: { command?: string; timeoutMs: number; teamContributions?: boolean }, + options: { command?: string; timeoutMs: number }, ): Promise> { const deadline = Date.now() + options.timeoutMs; const controller = new AbortController(); @@ -121,7 +121,6 @@ export async function evaluateSolverProof( evaluationSignal, undefined, options.timeoutMs, - options.teamContributions, ); assertActive(); const method = policy.integrated(finalCheck.passed, finalCheck.commit, finalCheck.sourceDigest); @@ -145,7 +144,6 @@ export async function evaluateSolverProof( method, official: false, result, - ...(options.teamContributions ? { verification: finalCheck } : {}), }; } if (method === 'official-comparator') { @@ -167,7 +165,6 @@ export async function evaluateSolverProof( method, official: true, comparison, - ...(options.teamContributions ? { verification: finalCheck } : {}), }; } return { status: 'passed', method, official: false, verification: finalCheck }; diff --git a/src/solver/incrementalHelpers.ts b/src/solver/incrementalHelpers.ts deleted file mode 100644 index e936589e..00000000 --- a/src/solver/incrementalHelpers.ts +++ /dev/null @@ -1,381 +0,0 @@ -import path from 'node:path'; -import { z } from 'zod'; -import { inspectScopedLeanDeclarations } from '../math/leanSource'; -import { isSimpleLeanName, maskLeanComments, MAX_LEAN_EXPECTED_TYPE_BYTES } from '../math/leanSyntax'; -import { mathDigest } from '../math/mathRuntimeIo'; -import { importAgentTeamCommit } from './agentTeamWorkspace'; -import { applyTaskChanges, createTaskSourceProjector, taskChanges, type DeclarationChange } from './cooperativeProof'; -import type { DeclarationArtifactIdentity } from './declarationArtifacts'; -import { checkProjectedDeclarations } from './modules/evidence'; -import { - assertSolverSources, - committedSource, - commitSolverSources, - git, - solverProofImports, - SolverSourceError, - withSolverWorktree, -} from './problem'; -import { hasDeterministicLeanFailure, hasLeanResourceLimitFailure, proofReuseEnvironment } from './proofReuse'; -import { solverSourceContext } from './sourceContext'; -import { allowedKnowledgeFile, locateKnowledgeDeclaration } from './theoremKnowledge'; -import type { CooperativeTask } from './tasks'; -import { VerifierFailureError } from './verifierFailure'; - -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) - .refine(value => Buffer.byteLength(value) <= MAX_LEAN_EXPECTED_TYPE_BYTES) - .optional(), - kind: z.literal('definition').optional(), - }) - .strict(), - ) - .min(1) - .max(32); -export type HelperNomination = z.infer[number]; -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; - }); - const receipt = verification.verification; - // An interrupted or unbound check must leave the frozen nomination available for recovery. - if ( - receipt.results.some(result => result.cleanupError) || - (!verification.passed && - !hasDeterministicLeanFailure(receipt) && - !(batch.length === 1 && hasLeanResourceLimitFailure(receipt))) - ) - throw new VerifierFailureError({ stage: 'incremental-helper-check', sourceCommit, verification: receipt }); - 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 => { - const type = checked.get(id(declaration.file, declaration.name))!; - if (Buffer.byteLength(type) <= MAX_LEAN_EXPECTED_TYPE_BYTES) return { ...declaration, type }; - // The printed signature adds the declaration name and layout to the checked type. - if (declaration.type !== undefined) return { ...declaration, type: declaration.type }; - return reject( - 'type_export_too_large', - `${declaration.name}: nominate an equivalent type of at most ${MAX_LEAN_EXPECTED_TYPE_BYTES} UTF-8 bytes.`, - ); - }); - const helpers = declarations.map(({ file, name, type, kind }) => - landedHelperSchema.parse({ - file, - qualifiedName: name, - type: type.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 b005897d..d5ab70bb 100644 --- a/src/solver/inspection.ts +++ b/src/solver/inspection.ts @@ -18,7 +18,6 @@ import { safeFailureDiagnostic } from '../runtime/failureDiagnostic'; 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. */ @@ -128,23 +127,13 @@ function teamDetails( tokenBudget: ReturnType, workerLimit?: number, ) { - const teamMode = state.researchDelegation?.mode === 'team'; + const delegation = state.researchDelegation; + if (delegation?.mode !== 'team') return {}; const resultMatches = matchesObservation(state, result); const evaluator = resultMatches && result?.evaluator && typeof result.evaluator === 'object' ? (result.evaluator as Record) : undefined; - const teamBudget = teamMode - ? { - ...projectAgentTeamBudget({ - tokenBudget, - maxTurns: state.agentTeam?.hostLimits?.maxTurns ?? Infinity, - turns: state.turns, - leadReserve: state.agentTeam?.leadReserve, - }), - turnLimitKnown: Boolean(state.agentTeam?.hostLimits), - } - : undefined; const savedContributions = teamContributionsSchema.safeParse(resultMatches ? result?.teamContributions : undefined); const contributions = state.agentTeam?.transport !== 'native-agent-control' @@ -155,50 +144,48 @@ function teamDetails( ? savedContributions.data : buildAgentTeamContributions(state, evaluator ?? {}); + const overview = agentTeamOverview(state, tokenBudget, workerLimit); return { - ...(teamMode - ? { - agentTeam: { - evidence: 'recorded-not-replayed', - control: 'agent-organized', - contributions, - maxAgents: state.researchDelegation!.maxAgents, - native: state.agentTeam?.nativeControl && { - status: state.agentTeam.nativeControl.rootAgent?.status, - writerStop: state.agentTeam.nativeControl.rootWriterStop, - runtimeConfiguration: state.agentTeam.nativeControl.rootRuntimeConfiguration, - }, - budget: teamBudget, - overview: agentTeamOverview({ ...state, tokenBudget }, { budget: teamBudget, workerLimit }), - workers: (state.agentTeam?.workers ?? []).map(worker => ({ - id: worker.id, - status: worker.status, - turns: worker.turns, - threadId: worker.threadId, - writerStopUnconfirmed: worker.writerStopUnconfirmed, - native: worker.native && { - status: worker.native.status, - lastOutcome: worker.native.lastOutcome, - spawnHistory: worker.native.spawnHistory ?? 'unknown', - writerStop: worker.native.writerStop, - runtimeConfiguration: worker.native.runtimeConfiguration, - }, - tasks: worker.tasks.map(task => ({ - id: task.id, - message: task.message, - status: task.status, - summary: task.summary, - error: task.error, - deliveryId: task.deliveryId, - })), - })), - events: state.agentTeam?.events ?? [], - deliveries: (state.agentTeam?.deliveries ?? []).map(({ id, agentId, taskId }) => ({ id, agentId, taskId })), - adoptions: state.agentTeam?.adoptions ?? [], - originalProblemAcceptance: 'see-final-evaluation', - }, - } - : {}), + agentTeam: { + evidence: 'recorded-not-replayed', + control: 'agent-organized', + ...(state.agentTeam?.transport === 'codex-shared' && { transport: 'codex-shared' as const }), + contributions, + maxAgents: delegation.maxAgents, + native: state.agentTeam?.nativeControl && { + status: state.agentTeam.nativeControl.rootAgent?.status, + writerStop: state.agentTeam.nativeControl.rootWriterStop, + runtimeConfiguration: state.agentTeam.nativeControl.rootRuntimeConfiguration, + }, + budget: overview.budget, + overview, + workers: (state.agentTeam?.workers ?? []).map(worker => ({ + id: worker.id, + status: worker.status, + turns: worker.turns, + threadId: worker.threadId, + writerStopUnconfirmed: worker.writerStopUnconfirmed, + native: worker.native && { + status: worker.native.status, + lastOutcome: worker.native.lastOutcome, + spawnHistory: worker.native.spawnHistory ?? 'unknown', + writerStop: worker.native.writerStop, + runtimeConfiguration: worker.native.runtimeConfiguration, + }, + tasks: worker.tasks.map(task => ({ + id: task.id, + message: task.message, + status: task.status, + summary: task.summary, + error: task.error, + deliveryId: task.deliveryId, + })), + })), + events: state.agentTeam?.events ?? [], + deliveries: (state.agentTeam?.deliveries ?? []).map(({ id, agentId, taskId }) => ({ id, agentId, taskId })), + adoptions: state.agentTeam?.adoptions ?? [], + originalProblemAcceptance: 'see-final-evaluation', + }, }; } diff --git a/src/solver/modules/context.ts b/src/solver/modules/context.ts index b3c02ac4..fdf86f26 100644 --- a/src/solver/modules/context.ts +++ b/src/solver/modules/context.ts @@ -42,14 +42,11 @@ import { prepareSkillResearchContext, skillResearchContinuationSection, } from '../skillResearchContext'; -import type { AgentTeamAssignment, AgentTeamRole } from '../agentTeamContext'; import { researchSkillIdentity } from '../researchSkill'; import { buildResearchToolGuide, longCommandGuidance, researchToolCommand } from '../researchToolGuide'; import type { ResearchToolHelp } from '../researchToolHelp'; export type ContextAccess = Readonly<{ - teamRole?: AgentTeamRole; - teamAssignment?: AgentTeamAssignment; /** Dispatch-time observations; execution and request admission remain host enforced. */ executionLimits?: Readonly<{ turnTimeoutMs?: number; turnCheckpointMs?: number; remainingRunMs(): number }>; root: string; @@ -229,7 +226,7 @@ export function buildResearchContext( throw new Error('math_research_skill_changed'); } // A native team's approval record uses the historical cooperation shape for storage only. - const nativeTeam = state.researchDelegation?.mode === 'team'; + const nativeTeam = state.agentTeam?.transport === 'codex-shared'; const cooperation = nativeTeam ? undefined : state.cooperation; if (Boolean(access.continuation) !== Boolean(state.continuationDigest)) throw new Error('math_continuation_identity_missing'); @@ -491,7 +488,6 @@ ${access.corpusFile ? `For library lookup, run ${command} search-lean --workspac environmentDigest: state.environmentDigest, mandatory: [ ...(attachments ? [attachments] : []), - ...(singleSkill?.teamObservation ? [singleSkill.teamObservation] : []), ...(skillWorkflow && !state.compactSoloResearch ? [ { diff --git a/src/solver/modules/evidence.ts b/src/solver/modules/evidence.ts index ef9dedc3..7c9eb57b 100644 --- a/src/solver/modules/evidence.ts +++ b/src/solver/modules/evidence.ts @@ -305,7 +305,6 @@ export async function checkSolverProof( signal?: AbortSignal, previous?: ProofCheck, timeoutMs = 180_000, - collectDirectProofReferences = false, ): Promise { signal?.throwIfAborted(); const commit = commitSolverSources(problem, worktree); @@ -362,7 +361,6 @@ export async function checkSolverProof( signal, prepareLocalDependencies: problem.kind === 'lean-eval', collectDeclarationReferences: true, - collectDirectProofReferences, }, ); // Advisory scratch and diagnostic logs stay in the worker. The strict verifier receives diff --git a/src/solver/planApproval.ts b/src/solver/planApproval.ts index c7982c04..cc36ddf8 100644 --- a/src/solver/planApproval.ts +++ b/src/solver/planApproval.ts @@ -1,6 +1,8 @@ import path from 'node:path'; import crypto from 'node:crypto'; +import { setTimeout as delay } from 'node:timers/promises'; import { z } from 'zod'; +import type { MathAgentToolDefinition } from '../runtime/agentSession'; import type { SolverRunState } from './archive'; import { pendingDeliveryLines } from './deliveries'; import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo'; @@ -65,14 +67,13 @@ export function planApprovalInspection(state: SolverRunState) { }; } -/** Both kinds of Lead consume the same approval log and persist the result before advancing its cursor. */ -export function drainPlanApprovals( +/** Persist each approval before advancing the log cursor. */ +function drainPlanApprovals( state: SolverRunState, stateFile: string, signal: AbortSignal, save: () => void, emit: (event: string, details: Record) => void, - changed = save, ) { const archive = state.cooperation; if (!archive) return; @@ -116,16 +117,56 @@ export function drainPlanApprovals( ...(approval ? { planVersion: approval.planVersion } : {}), }; record.rejections = [...(record.rejections ?? []), rejection].slice(-MAX_PLAN_APPROVAL_REJECTIONS); - changed(); + save(); emit('plan_approval_rejected', rejection); } else { Object.assign(record, { approvedId: approval.id, approvedVersion: approval.planVersion, approvedAt: Date.now() }); - changed(); + save(); emit('plan_approved', { id: approval.id, planVersion: approval.planVersion }); } } } +/** Wait outside the writer session and pause the execution clock only while awaiting input. */ +export async function waitForPlanApproval(input: { + state: SolverRunState; + signal: AbortSignal; + save: () => void; + emit: (event: string, details: Record) => void; + unanswered: () => void; + canContinue: () => boolean; + setWaiting?: (waiting: boolean) => void; +}): Promise { + const { state, signal, save, emit } = input; + if (planApprovalStatus(state) !== 'pending') return true; + if (!input.canContinue()) { + input.unanswered(); + return false; + } + // On resume the approval may already be logged, before reserving another turn. + if (state.phase !== 'running') { + state.phase = 'running'; + save(); + } + const stateFile = path.join(path.dirname(state.worktree), 'state.json'); + const read = () => drainPlanApprovals(state, stateFile, signal, save, emit); + read(); + if (planApprovalStatus(state) !== 'pending') return true; + + input.setWaiting?.(true); + save(); + try { + do { + await delay(200, undefined, { signal }); + read(); + } while (planApprovalStatus(state) === 'pending'); + return true; + } finally { + input.setWaiting?.(false); + save(); + } +} + export const nativePlanApprovalSchema = z .object({ operation: z.literal('publish_plan'), @@ -140,6 +181,33 @@ export const nativePlanApprovalSchema = z }) .strict(); +export const sharedTeamPlanTool: MathAgentToolDefinition = { + name: 'theoremos_team', + description: 'Publish the initial route with one objective for each original theorem, then return for approval.', + inputSchema: { + type: 'object', + properties: { + operation: { const: 'publish_plan', type: 'string' }, + goals: { + type: 'array', + minItems: 1, + items: { + type: 'object', + properties: { + theoremName: { type: 'string', minLength: 1, maxLength: 512 }, + objective: { type: 'string', minLength: 1, maxLength: 2000 }, + }, + required: ['theoremName', 'objective'], + additionalProperties: false, + }, + }, + investigations: { type: 'array', items: { type: 'string', minLength: 1, maxLength: 2000 }, maxItems: 32 }, + }, + required: ['operation', 'goals'], + additionalProperties: false, + }, +}; + export function nativeApprovalPlanBrief(tasks: readonly TaskRecord[]) { return canonicalMathJson( tasks.map(({ task }) => ({ diff --git a/src/solver/prepareSolverLean.ts b/src/solver/prepareSolverLean.ts new file mode 100644 index 00000000..d48e8fd8 --- /dev/null +++ b/src/solver/prepareSolverLean.ts @@ -0,0 +1,131 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { DEFAULT_LEAN_LIBRARY_CACHE_ROOT } from '../math/leanCompilationCache'; +import { prepareLeanDiagnosticOverrides, runLeanDiagnostics } from '../math/leanDiagnostics'; +import { checkResolvedLeanToolchainReadiness } from '../math/leanToolchainReadiness'; +import { prepareMathProofEnvironment, MATH_PROOF_ENVIRONMENT_ENV } from '../math/mathProofEnvironment'; +import { DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT } from '../math/mathProofEnvironmentCache'; +import { writeMathJsonDurable } from '../math/mathRuntimeIo'; +import { assertMathCanonicalPath } from '../math/paths'; +import type { RuntimeSolverModules } from './modules/runtime'; +import type { SolverProblem } from './problem'; + +/** Check the runnable project before admitting a model turn. The caller owns the prepared environment on success. */ +export async function prepareSolverLean(input: { + problem: SolverProblem; + project: string; + sourcePackages?: string; + env: NodeJS.ProcessEnv; + signal: AbortSignal; + deadlineAt: number; + directory: string; + cacheRoot?: string; + checkStatement?: boolean; + checkPreparedSources?: RuntimeSolverModules['M2']['checkPreparedSources']; + emit: (event: string, details: Record) => void; +}) { + const { problem, project, sourcePackages, signal, deadlineAt, directory, emit } = input; + let { env } = input; + const readiness = checkResolvedLeanToolchainReadiness({ projectRoot: project, env, timeoutMs: 180_000 }); + writeMathJsonDurable(path.join(directory, 'toolchain-readiness.json'), readiness); + if (readiness.status !== 'ready') { + emit('preparation_failed', { workerId: 'solver', diagnostics: readiness.diagnostics }); + throw new Error('math_lean_toolchain_unavailable'); + } + + let proofEnvironment: Awaited> | undefined; + try { + if (sourcePackages) { + // Model-side paths must not change the proof environment cache identity on resume. + const overrides = path.join(project, '.lake', 'package-overrides.json'); + assertMathCanonicalPath(overrides); + fs.rmSync(overrides, { force: true }); + proofEnvironment = await prepareMathProofEnvironment(project, sourcePackages, { + env, + signal, + deadlineAt, + cacheRoot: input.cacheRoot || DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT, + onProgress: phase => emit('proof_environment', { phase }), + }); + env = { ...env, [MATH_PROOF_ENVIRONMENT_ENV]: proofEnvironment.environmentValue }; + prepareLeanDiagnosticOverrides(project); + } + + const diagnosticInput = (files: readonly string[]) => ({ + projectRoot: project, + files, + env, + signal, + timeoutMs: deadlineAt - Date.now(), + }); + const persistDiagnostic = ( + name: string, + result: { exitCode: number | null; timedOut: boolean; stdout: string; stderr: string }, + code: string, + fallback: string, + rejection?: string, + ) => { + writeMathJsonDurable(path.join(directory, name + '-diagnostics.json'), result); + if (result.exitCode === 0 && !result.timedOut && !rejection) return; + emit('preparation_failed', { + workerId: 'solver', + timedOut: result.timedOut, + diagnostics: (rejection || result.stderr || result.stdout || fallback).slice(0, 2000), + }); + throw new Error(code); + }; + + const targets = [...new Set(problem.targets.map(target => target.proofPath))]; + const dependencies = await runLeanDiagnostics({ + ...diagnosticInput(targets), + dependenciesOnly: true, + excludedFiles: problem.ownedFiles, + onProgress: file => emit('dependency_check', { workerId: 'solver', file }), + }); + persistDiagnostic( + 'preparation', + dependencies, + 'math_lean_dependencies_failed', + 'Lean dependency check did not finish.', + ); + + const checkSources = input.checkPreparedSources?.bind(undefined, problem.baseCommit) ?? runLeanDiagnostics; + // Frozen library sources only become usable after Lean checks them without sorry. + const frozenFiles = problem.frozenFiles; + const files = Object.keys(frozenFiles ?? {}); + if (frozenFiles && files.length) { + emit('library_pack_check', { files }); + const library = await checkSources({ + ...diagnosticInput(files), + onProgress: file => emit('library_pack_check', { file }), + sharedLibraryCache: { root: DEFAULT_LEAN_LIBRARY_CACHE_ROOT, files: frozenFiles }, + onSharedCache: (phase, file) => emit('library_pack_cache', { phase, ...(file ? { file } : {}) }), + }); + const sorry = + 'messages' in library && library.messages?.find(message => /declaration uses '?sorry'?/u.test(message.message)); + persistDiagnostic( + 'library-pack', + library, + 'math_library_pack_failed', + 'Library-pack check did not finish.', + sorry ? `${sorry.file ?? ''} ${sorry.message}` : undefined, + ); + } + if (input.checkStatement) { + const statement = await checkSources({ + ...diagnosticInput(targets), + onProgress: file => emit('statement_check', { file }), + }); + persistDiagnostic('statement', statement, 'math_statement_check_failed', 'Statement check did not finish.'); + } + return { env, proofEnvironment, dependencies: dependencies.phases }; + } catch (error) { + // A failed preparation still owns any mount it opened. + try { + await proofEnvironment?.dispose(); + } catch { + // Keep the preparation failure as the reported cause. + } + throw error; + } +} diff --git a/src/solver/proofWriter.ts b/src/solver/proofWriter.ts index c23e0380..d45a9ad9 100644 --- a/src/solver/proofWriter.ts +++ b/src/solver/proofWriter.ts @@ -1,5 +1,13 @@ import type { MathAgentSession } from '../runtime/agentSession'; import type { SolverRunState } from './archive'; +import { confirmHarnessProcessStopped } from '../runtime/harnessProcess'; + +/** Refuse to reuse a proof workspace while its previous writer may still be running. */ +export function assertProofWriterStopped(state: Pick) { + if (state.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:lead'); + if (state.writerProcess && confirmHarnessProcessStopped(state.writerProcess).status !== 'stopped') + throw new Error('math_writer_stop_unconfirmed:lead:previous-process-active'); +} /** Opening can fail before the caller has a session to stop. */ export function recordUnconfirmedWriterStartup( diff --git a/src/solver/research.ts b/src/solver/research.ts index 914427ac..6365b166 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import crypto from 'node:crypto'; import { setTimeout as delay } from 'node:timers/promises'; import { VerificationCheckpointError } from './verificationCheckpoint'; -import type { MathAgentActivity, MathAgentFailureDiagnostic, MathAgentSession } from '../runtime/agentSession'; +import type { MathAgentFailureDiagnostic, MathAgentSession } from '../runtime/agentSession'; import { safeFailureDiagnostic } from '../runtime/failureDiagnostic'; import { confirmHarnessProcessStopped } from '../runtime/harnessProcess'; import { VerifierFailureError, verifierFailureDiagnostic } from './verifierFailure'; @@ -11,11 +11,17 @@ import { readMathBuildManifest } from '../math/mathBuildManifest'; import { MathGitError } from '../math/mathGit'; import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo'; import type { SolverRunState } from './archive'; -import { commitSolverSources, git, pinSolverResearchSkill } from './problem'; +import { commitSolverSources, committedSource, git, pinSolverResearchSkill } from './problem'; import { tryOriginalProofByTactics } from './originalProofTactics'; -import { createSavedEditCheck } from './savedEditCheck'; -import { AgentResearchTeam, assertAgentTeamProcessesStopped } from './agentTeam'; -import { drainPlanApprovals, nativeApprovalPlanBrief, planApprovalStatus } from './planApproval'; +import { createResearchTurnCheckpoint, type ResearchTurnCheckpointReason } from './researchTurnCheckpoint'; +import { + waitForPlanApproval, + sharedTeamPlanTool, + nativeApprovalPlanBrief, + nativePlanApprovalSchema, + planApprovalStatus, + publishNativeApprovalPlan, +} from './planApproval'; import { LeanEnvironmentHealthCheckError } from '../runtime/leanHealthCheck'; import { rememberSolverFailure, solverSourceFeedback } from './feedback'; import type { RuntimeSolverModules } from './modules/runtime'; @@ -34,11 +40,10 @@ import { import { buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; import { driveResearch, type ResearchDriver, type DispatchOutcome, type SettlementOutcome } from './researchLoop'; import { ResearchUsage } from './researchUsage'; -import { inspectKnowledgeUses } from './knowledgeUsage'; +import { inspectKnowledgeUses, type KnowledgeUse } from './knowledgeUsage'; import { checkKnowledgeApplications } from './knowledgeApplications'; import { parseMathResponse } from './deliveries'; import { readCheckpointNotesDigest, savedContextCheckpoint } from './contextCheckpoint'; -import { committedSource } from './problem'; import type { ContinuationSnapshot } from './continuationInput'; import type { MathTools } from '../math/mathTools'; import { checkTaskProof } from './cooperativeProof'; @@ -51,20 +56,17 @@ import { type LibraryAccess, } from './libraryAccess'; import { prepareTacticBatteryFailureCacheRoot } from './tacticBatteryFailureCache'; -import { SingleSolverProofHandoff } from './singleSolverProofHandoff'; +import { SingleSolverProofHandoff, type SingleSolverProofSubmission } from './singleSolverProofHandoff'; import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills'; import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext'; -import { recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter'; +import { assertProofWriterStopped, recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter'; import { createSkillProofLifecycle, originalProofHasHoles, savedProofCanResume } from './skillProofLifecycle'; import { DECLARATION_SUBMISSION_FILE } from './declarationArtifacts'; -import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; +import { softSliceSettings, type SoftSliceSettings } from './softSlice'; import { materializeResearchToolHelp } from './researchToolHelp'; import { assertActiveResearchState } from './researchRetirement'; import { researchLeanHealthCheck, researchToolRoots } from './researchToolGuide'; -const interruptGraceMs = 10_000; -const nonToolItems = new Set(['reasoning', 'agentMessage', 'userMessage', 'contextCompaction']); - export type WorkerAccess = { environment: NodeJS.ProcessEnv; corpusFile?: string; @@ -100,7 +102,6 @@ export async function runResearchLead(input: { maxTotalTokens: number; proofTimeoutMs?: number; executionBudget?: { remainingMs(): number; setWaiting(waiting: boolean): void }; - prepareTeamWorker?: (id: string, worktree: string) => Promise; softSlice?: SoftSliceSettings; drive?: ResearchDriver; save: () => void; @@ -108,22 +109,25 @@ export async function runResearchLead(input: { }): Promise<{ worktree: string; check: ProofCheck } | undefined> { const { state, access, modules, save } = input; const milestoneSettings = softSliceSettings(input.softSlice ?? {}); - const research = state; - const worker = { - id: 'solver', - role: 'lead' as const, - worktree: state.worktree, - ownedFiles: state.problem.ownedFiles, - }; + const { worktree, problem } = state; + const workerId = 'solver'; + const worker = { id: workerId, role: 'lead' as const, worktree, ownedFiles: problem.ownedFiles }; assertActiveResearchState(state); - assertAgentTeamProcessesStopped(state); + assertProofWriterStopped(state); const skillMode = state.researchMode === 'skill'; const fullSkillWorkflow = skillMode && state.researchSkillWorkflow === 'full'; const sessionSkill = state.compactSoloResearch ? undefined : access.researchSkill; - const nativePlanReview = - state.planApproval && - state.researchDelegation?.mode === 'team' && - state.agentTeam?.transport === 'native-agent-control'; + const sharedTeam = state.agentTeam?.transport === 'codex-shared'; + const nativePlanReview = state.planApproval && state.researchDelegation?.mode === 'team'; + const mayStartProofWork = () => !nativePlanReview || planApprovalStatus(state) === 'approved'; + const sharedPlanningTools = + sharedTeam && nativePlanReview + ? { + definitions: [sharedTeamPlanTool], + call: async (_name: string, args: unknown) => + publishNativeApprovalPlan(state, nativePlanApprovalSchema.parse(args), save, input.emit), + } + : undefined; if ( nativePlanReview && planApprovalStatus(state) === 'approved' && @@ -135,14 +139,14 @@ export async function runResearchLead(input: { state.pendingProofCheck && (!skillMode || state.pendingProofCheck.environmentDigest !== state.environmentDigest || - state.pendingProofCheck.problemReceiptDigest !== state.problem.receiptDigest) + state.pendingProofCheck.problemReceiptDigest !== problem.receiptDigest) ) throw new Error('math_proof_checkpoint_identity_changed'); if ( state.pendingResearchFreeze && (!skillMode || state.pendingResearchFreeze.environmentDigest !== state.environmentDigest || - state.pendingResearchFreeze.problemReceiptDigest !== state.problem.receiptDigest) + state.pendingResearchFreeze.problemReceiptDigest !== problem.receiptDigest) ) throw new Error('math_research_freeze_identity_changed'); if (state.researchDelegation && !skillMode) throw new Error('math_native_delegation_requires_skill'); @@ -151,27 +155,17 @@ export async function runResearchLead(input: { const identity = state.researchSkill; if (!skill || !identity || skill.digest !== identity.digest || skill.loading !== identity.loading) throw new Error('math_research_skill_changed'); - pinSolverResearchSkill(state.problem, worker.worktree, skill); + pinSolverResearchSkill(problem, worktree, skill); } - if (research.writerStopUnconfirmed) - throw new Error( - 'math_writer_stop_unconfirmed:' + - worker.id + - ': recover into a new isolated workspace before starting another writer.', - ); - initializeUsageAccounting(research); + initializeUsageAccounting(state); const enforcement = state.tokenBudget?.enforcement; - state.tokenBudget = buildTokenBudget( - input.maxTotalTokens, - [research, ...(state.agentTeam?.workers ?? [])], - enforcement, - ); + state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [state], enforcement); const dispatchAllowed = () => modelDispatchAllowed(state.tokenBudget!); if ( savedProofCanResume(state, !nativePlanReview || planApprovalStatus(state) === 'approved') && state.check && - !solverSourceFeedback(state.problem, worker.worktree) && - solverProofIsCurrent(state.problem, worker.worktree, state.check) + !solverSourceFeedback(problem, worktree) && + solverProofIsCurrent(problem, worktree, state.check) ) { if (state.pendingProofCheck) { if ( @@ -182,7 +176,7 @@ export async function runResearchLead(input: { state.pendingProofCheck = undefined; save(); } - return { worktree: worker.worktree, check: state.check }; + return { worktree, check: state.check }; } if (state.check?.passed) { state.check = undefined; @@ -200,30 +194,29 @@ export async function runResearchLead(input: { const started = Date.now(); const remaining = input.executionBudget?.remainingMs() ?? input.deadline - started; const timeoutMs = Math.min(5_000, input.proofTimeoutMs ?? Infinity, Math.floor(remaining / 10)); - const sourcePaths = state.problem.ownedFiles.map(file => path.join(state.problem.projectRelative, file)); - const sourcesClean = () => !git(worker.worktree, ['status', '--porcelain', '--', ...sourcePaths]); + const sourcePaths = problem.ownedFiles.map(file => path.join(problem.projectRelative, file)); + const sourcesClean = () => !git(worktree, ['status', '--porcelain', '--', ...sourcePaths]); if (timeoutMs > 0 && sourcesClean()) { - const head = git(worker.worktree, ['rev-parse', 'HEAD']); + const head = git(worktree, ['rev-parse', 'HEAD']); input.emit('original_tactics_started', { timeoutMs }); const check = await tryOriginalProofByTactics({ - problem: state.problem, - worktree: worker.worktree, + problem, + worktree, env: access.environment, signal: input.signal, timeoutMs, }); input.signal.throwIfAborted(); - if (check?.passed && sourcesClean() && git(worker.worktree, ['rev-parse', 'HEAD']) === head) { - git(worker.worktree, ['merge', '--ff-only', '--no-edit', check.commit]); - if (!solverProofIsCurrent(state.problem, worker.worktree, check)) - throw new Error('math_original_tactics_source_changed'); + if (check?.passed && sourcesClean() && git(worktree, ['rev-parse', 'HEAD']) === head) { + git(worktree, ['merge', '--ff-only', '--no-edit', check.commit]); + if (!solverProofIsCurrent(problem, worktree, check)) throw new Error('math_original_tactics_source_changed'); state.phase = 'checking'; state.check = check; state.originalTacticAttempt = { durationMs: Date.now() - started, commit: check.commit }; save(); input.emit('original_tactics_finished', { ...state.originalTacticAttempt, passed: true }); - input.emit('candidate_selected', { workerId: worker.id, commit: check.commit, method: 'original_tactics' }); - return { worktree: worker.worktree, check }; + input.emit('candidate_selected', { workerId, commit: check.commit, method: 'original_tactics' }); + return { worktree, check }; } state.originalTacticAttempt = { durationMs: Date.now() - started }; save(); @@ -241,80 +234,35 @@ export async function runResearchLead(input: { aborted: signal.aborted, }); let winner: { worktree: string; check: ProofCheck } | undefined; - let verificationQueue = Promise.resolve(); - const exclusiveCheck = async (check: () => Promise): Promise => { - const previous = verificationQueue; - let release!: () => void; - verificationQueue = new Promise(resolve => { - release = resolve; - }); - await previous; - try { - signal.throwIfAborted(); - return await check(); - } finally { - release(); - } - }; - const team = - state.researchDelegation?.mode === 'team' - ? new AgentResearchTeam({ - state, - root: input.root, - taskText: input.taskText, - leadAccess: access, - modules, - executable: input.executable, - profile: input.profile, - signal, - maxAgents: state.researchDelegation.maxAgents, - maxTurns: input.maxTurns, - maxTurnMs: input.maxTurnMs, - maxTotalTokens: input.maxTotalTokens, - proofTimeoutMs: input.proofTimeoutMs, - remainingMs: () => budget().remainingMs, - prepareWorker: input.prepareTeamWorker, - softSlice: input.softSlice, - save, - emit: input.emit, - exclusiveCheck, - }) - : undefined; - const turnTiming = team + const turnTiming = sharedTeam ? teamTurnTiming(input.maxTurnMs) : { turnTimeoutMs: Number.isFinite(input.maxTurnMs) ? input.maxTurnMs : undefined }; const updateUsage = () => { const previous = state.tokenBudget!.status; - const next = team - ? team.refreshUsage() - : (state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [research], enforcement)); + const next = (state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [state], enforcement)); if (next.status !== previous && !modelDispatchAllowed(next)) input.emit('model_budget_stopped', { ...next }); }; - const errors: unknown[] = []; - const cleanupErrors: unknown[] = []; + let failure: { error: unknown } | undefined; + let cleanupFailure: { error: unknown } | undefined; state.error = undefined; - let deferredLeadAdoptions = team?.leadSourceRecoveryPending; try { - await team?.restore(); let session: MathAgentSession | undefined; let sessionInstructions: string | undefined; let closing: Promise | undefined; let retries = 0; - let nativeContextRecovery: 'pending' | 'attempted' | undefined; let lastCheck: ProofCheck | undefined; - research.error = undefined; - const emit = (event: string, details = {}) => input.emit(event, { workerId: worker.id, ...details }); - // The host has one Lead writer in team mode too. This watches the full-proof Lean diagnostic, - // while the stopped-writer Skill lifecycle handles optional declaration nominations. - const singleHandoff = new SingleSolverProofHandoff( - state.problem, - worker.worktree, - submission => emit('proof_ready_checkpoint_requested', { ...submission, reason: 'current-lean-diagnostics' }), - !team && skillMode ? details => emit('lean_stall_detected', details) : undefined, - ); - const sourceFeedback = () => solverSourceFeedback(state.problem, worker.worktree); + const emit = (event: string, details = {}) => input.emit(event, { workerId, ...details }); + const singleHandoff = sharedTeam + ? undefined + : new SingleSolverProofHandoff( + problem, + worktree, + submission => emit('proof_ready_checkpoint_requested', { ...submission, reason: 'current-lean-diagnostics' }), + skillMode ? details => emit('lean_stall_detected', details) : undefined, + ); + const sourceFeedback = () => solverSourceFeedback(problem, worktree); const recovered = () => { - const recovery = research.recovery; + const recovery = state.recovery; if (!recovery || recovery.phase === 'recovered') return; recovery.phase = 'recovered'; recovery.recoveredAt = Date.now(); @@ -322,7 +270,7 @@ export async function runResearchLead(input: { save(); }; const waitForRecovery = async (resumed = false) => { - const recovery = research.recovery; + const recovery = state.recovery; if (recovery?.phase !== 'cooling-down') return; const started = Date.now(); const delayMs = researchCooldownWait( @@ -351,51 +299,41 @@ export async function runResearchLead(input: { save(); } }; - const context = (feedback?: string, previousCheck?: ProofCheck, previousFailures = research.failures) => { + const context = (feedback?: string, previousCheck?: ProofCheck, previousFailures = state.failures) => { access.assertKnowledgeCurrent?.(); - if (access.libraryCatalog) writeLibraryAccess(state.problem, worker.worktree, access.libraryCatalog); + if (access.libraryCatalog) writeLibraryAccess(problem, worktree, access.libraryCatalog); const contextAccess = { root: input.root, - worktree: worker.worktree, + worktree, taskText: input.taskText, ...access, ...(modules.M4.tools ? { tools: modules.M4.tools } : {}), sourceFeedback: feedback, previousCheck, previousFailures, - maxOptionalContextBytes: research.contextOverflow?.maxOptionalContextBytes, + maxOptionalContextBytes: state.contextOverflow?.maxOptionalContextBytes, ...(skillMode ? { executionLimits: { ...turnTiming, remainingRunMs: () => budget().remainingMs } } : {}), - ...(team ? { teamRole: { id: 'lead', role: 'lead' as const } } : {}), }; const currentContext = skillMode && !fullSkillWorkflow - ? buildSkillResearchContext(state.problem, state, { ...contextAccess, researchSkill: access.researchSkill! }) - : modules.M4.build(state.problem, state, contextAccess); - materializeResearchToolHelp(currentContext, worker.worktree); + ? buildSkillResearchContext(problem, state, { ...contextAccess, researchSkill: access.researchSkill! }) + : modules.M4.build(problem, state, contextAccess); + materializeResearchToolHelp(currentContext, worktree); return { ...currentContext }; }; let feedbackCheck: ProofCheck | undefined; - let feedbackFailures = research.failures; + let feedbackFailures = state.failures; let reservedTurn = false; - let softSliceAtModelBoundary: (() => boolean) | undefined; - let softSliceCheckpoint = false; - let savedEditCheckpoint = false; - let contextSchedulingCheckpoint = false; + let activeCheckpoint: ReturnType | undefined; let explicitCompaction = false, contextUsageVersion = 0, compactedUsageVersion = -1; let sessionHasHistory = false; - let turnActivity: ((activity: MathAgentActivity) => void) | undefined; let turnContext: { digest: string; fresh: boolean } | undefined; - let dispatched: { responsibility: string; threadId: string; compaction?: 'pending' | 'completed' } | undefined; - const markCompaction = (threadId: string, compaction: 'pending' | 'completed') => { - if (dispatched?.threadId === threadId) dispatched = { ...dispatched, compaction }; - else dispatched = undefined; - }; - let rebuildContext = false; + let dispatched: { responsibility: string; threadId: string } | undefined; const usage = new ResearchUsage({ state, - research, + research: state, signal, remainingMs: () => budget().remainingMs, changed: () => { @@ -407,16 +345,16 @@ export async function runResearchLead(input: { const failureDetail = (error: unknown, sessionError?: string, diagnostic?: MathAgentFailureDiagnostic) => researchFailureDetail(error, sessionError, diagnostic, usage.stopReason); const locallyStopped = (detail?: string) => usage.stopReason !== undefined && detail === usage.stopReason; - const checkpointNotesDigest = () => readCheckpointNotesDigest(worker.worktree); - const currentCheckpointNotesDigest = () => savedContextCheckpoint(research, worker.worktree); + const checkpointNotesDigest = () => readCheckpointNotesDigest(worktree); + const currentCheckpointNotesDigest = () => savedContextCheckpoint(state, worktree); const contextCheckpointInstruction = 'Before further searches or experiments, save the exact current argument, ' + 'attempted methods, useful declaration and file references, and the unresolved inference in RESEARCH.md.'; const requestContextCheckpoint = (lastInputTokens: number) => { - const threadId = research.threadId; - if (!threadId || (research.contextCheckpoint?.threadId === threadId && research.contextCheckpoint.requestId)) + const threadId = state.threadId; + if (!threadId || (state.contextCheckpoint?.threadId === threadId && state.contextCheckpoint.requestId)) return false; - research.contextCheckpoint = { + state.contextCheckpoint = { threadId, requestId: crypto.randomUUID(), requestedAt: Date.now(), @@ -426,172 +364,13 @@ export async function runResearchLead(input: { save(); return true; }; - const modelTurn = async ( - run: (started: (turnId: string) => void) => Promise, - onStarted: (turnId: string) => void, - ): Promise => { - if (!dispatchAllowed() || budget().remainingMs <= 0 || signal.aborted) return undefined; - const kind = team && !team.mayStartProofWork ? 'planning' : 'proof'; - state.dispatchCounts ??= {}; - state.dispatchCounts[kind] = (state.dispatchCounts[kind] ?? 0) + 1; - reservedTurn = false; - contextSchedulingCheckpoint = false; - softSliceCheckpoint = false; - savedEditCheckpoint = false; - usage.begin(); - team?.beginLeadTurn(); - const activeSession = session!; - let finished = false; - let toolsRunning = 0; - let interruptTimer: ReturnType | undefined; - let checkpointClosing = false; - const live = () => !finished && !signal.aborted && session === activeSession; - // Only runs that already pinned edit probes need their speculative verifier. - const editController = state.savedEditChecks && !team && skillMode ? new AbortController() : undefined; - const checkEdit = editController - ? createSavedEditCheck({ - problem: state.problem, - worktree: worker.worktree, - env: access.environment, - signal: AbortSignal.any([signal, editController.signal]), - timeoutMs: Math.min(5_000, input.proofTimeoutMs ?? Infinity), - }) - : undefined; - let editProbe: Promise | undefined; - let editFailure: Error | undefined; - const closeStalledTurn = () => { - if (!live() || checkpointClosing) return; - checkpointClosing = true; - void close().catch(() => {}); - }; - const interruptForCheckpoint = (event: string, details: Record) => { - if (!live() || interruptTimer) return false; - emit(event, details); - interruptTimer = setTimeout(closeStalledTurn, interruptGraceMs); - interruptTimer.unref(); - void activeSession.interrupt().catch(closeStalledTurn); - return true; - }; - let milestoneTurnId: string | undefined; - const milestoneCurrent = () => live() && !interruptTimer && !softSliceCheckpoint; - const milestone = - kind === 'proof' - ? createSoftSlice(milestoneSettings, { - current: milestoneCurrent, - notice: (reason, completedCompactions) => { - emit(reason === 'time' ? 'soft_slice_milestone_requested' : 'compaction_circuit_breaker_triggered', { - turnId: milestoneTurnId, - completedCompactions, - graceMs: milestoneSettings.graceMs, - }); - const submission = team - ? 'Use theoremos_team route_summary to review the team. Collect useful checked results and coordinate active teammates. ' + - 'If slots are free, delegate focused independent obligations using the team tools. ' - : skillMode - ? 'Write .scratch/declaration-submission.json only if you have at least one locally compiled standalone helper to nominate. Never write an empty declarations array. ' - : 'Save standalone helpers in the owned Lean files for host checking. '; - void activeSession - .notify?.( - submission + - 'Write fewer than 20 lines in worktree-root RESEARCH.md covering what is established, the exact obstruction, ' + - 'and the next route or smaller obligation. Save your files and return after the current request and tools settle.', - activeSession.advisoryNotifications === 'native-history' - ? { mode: 'advisory' } - : { waitForRequest: true }, - ) - .catch(error => { - if (milestoneCurrent()) emit('soft_slice_notice_failed', { reason: failureDetail(error) }); - }); - }, - interrupt: () => { - softSliceCheckpoint = interruptForCheckpoint('soft_slice_checkpoint_requested', { - turnId: milestoneTurnId, - boundary: 'wait-limit', - }); - }, - }) - : undefined; - if (milestone) - softSliceAtModelBoundary = () => { - if (toolsRunning || !milestone.useBoundary()) return false; - softSliceCheckpoint = true; - emit('soft_slice_checkpoint_requested', { turnId: milestoneTurnId, boundary: 'request' }); - return true; - }; - turnActivity = activity => { - if (checkEdit && activity.event === 'item_completed' && activity.itemType === 'fileChange' && live()) { - editProbe = checkEdit() - .then(sourceDigest => { - if (sourceDigest && live() && !savedEditCheckpoint) - savedEditCheckpoint = interruptForCheckpoint('saved_edit_checkpoint_requested', { sourceDigest }); - }) - .catch(error => { - editFailure = error instanceof Error ? error : new Error('math_saved_edit_check_failed'); - interruptForCheckpoint('saved_edit_check_failed', { reason: editFailure.message }); - }); - } - if (activity.itemType && !nonToolItems.has(activity.itemType)) { - if (activity.event === 'item_started') toolsRunning++; - else if (activity.event === 'item_completed') { - toolsRunning = Math.max(0, toolsRunning - 1); - if (!toolsRunning && activeSession.usageSource !== 'upstream-requests' && milestone?.useBoundary()) - softSliceCheckpoint = interruptForCheckpoint('soft_slice_checkpoint_requested', { - turnId: milestoneTurnId, - boundary: 'tool', - }); - } - } - if (live() && activity.itemType === 'contextCompaction') { - if (activity.event === 'item_started') markCompaction(activeSession.threadId, 'pending'); - if (activity.event === 'item_completed') { - markCompaction(activeSession.threadId, 'completed'); - milestone?.compacted(); - } - } - }; - const started = (turnId: string) => { - onStarted(turnId); - milestoneTurnId = turnId; - milestone?.start(); - }; - let completed = false; - try { - const result = await run(started); - const detail = failureDetail(undefined, activeSession.lastError, activeSession.lastFailureDiagnostic); - if (usage.stopReason && detail !== usage.stopReason) throw new Error(detail); - const resultStatus = - typeof result === 'string' - ? result - : result && typeof result === 'object' && 'status' in result - ? result.status - : undefined; - completed = resultStatus === 'completed'; - if (milestone?.requested && completed) softSliceCheckpoint = true; - if (completed) recovered(); - return result; - } finally { - finished = true; - editController?.abort(); - milestone?.stop(); - softSliceAtModelBoundary = undefined; - clearTimeout(interruptTimer); - turnActivity = undefined; - try { - await editProbe; - if (checkpointClosing) await close(); - if (editFailure) throw editFailure; - } finally { - usage.finish(completed); - } - } - }; const reserveTurn = () => { if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0 || signal.aborted) return false; - // Reserve synchronously before opening a session so peers cannot overspend the shared budget. + // Reserve before session startup. Return the slot if the turn never starts. reservedTurn = true; state.turns++; - research.phase = 'running'; + state.phase = 'running'; save(); return true; }; @@ -610,59 +389,166 @@ export async function runResearchLead(input: { const current = session, closingSessionId = usage.sessionId; session = undefined; - team?.setLeadSession(undefined); try { closing = current.close(); await closing; if ( - team && + sharedTeam && current.processIdentity && confirmHarnessProcessStopped(current.processIdentity).status === 'stopped' ) { - team.leadWriterStopped(); state.writerProcess = undefined; save(); } } catch (error) { - cleanupErrors.push(error); + cleanupFailure ??= { error }; throw error; } finally { usage.sessionClosed(closingSessionId); } }; + const stopWriter = (current: MathAgentSession, submission?: SingleSolverProofSubmission) => + stopProofWriter({ + session: current, + record: state, + workerId, + close, + save, + deferred: reason => emit('proof_ready_freeze_deferred', { ...submission, reason }), + confirmed: reason => emit('proof_ready_freeze_confirmed', { ...submission, reason }), + }); const cancel = () => { void close().catch(() => {}); }; signal.addEventListener('abort', cancel, { once: true }); - const beginTurn = async (currentContext: ContextBundle, operation: ResearchOperation) => { + const rememberSessionThread = (threadId: string) => { + if (state.threadId === threadId) return false; + state.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() }; + state.threadId = threadId; + return true; + }; + const openResearchSession = async (instructions: string): Promise<'ready' | DispatchOutcome> => { + const project = path.join(worktree, problem.projectRelative); + while (!session) { + signal.throwIfAborted(); + if (!dispatchAllowed() || budget().remainingMs <= 0) return 'stopped'; + try { + const sessionId = crypto.randomUUID(); + const resumingThread = state.threadId; + const usageCallbacks = usage.bindSession(sessionId, () => session?.lastInputTokens); + if (usageCallbacks.requestGate) + usageCallbacks.requestGate.checkpoint = () => + Boolean(sharedTeam && nativePlanReview && planApprovalStatus(state) === 'pending') || + (activeCheckpoint?.atRequestBoundary() ?? false); + access.assertHarnessCurrent?.(); + session = await modules.M1.open({ + executable: input.executable, + profile: input.profile, + ...(sessionSkill ? { skills: [sessionSkill] } : {}), + ...(sharedTeam + ? { + sharedProofTeam: { + capacity: state.researchDelegation!.mode === 'team' ? state.researchDelegation!.maxAgents : 1, + requireMetering: input.maxTotalTokens > 0, + }, + isolateProcess: true, + leanHealthCheck: researchLeanHealthCheck(input.root, project, modules.M4.tools), + ...(!mayStartProofWork() ? { readOnlyWorkspace: true, tools: sharedPlanningTools } : {}), + } + : {}), + hiddenRoots: [prepareTacticBatteryFailureCacheRoot()], + soloProofWorkspace: !sharedTeam, + readableRoots: researchToolRoots(input.root, modules.M4.tools), + proofProjectRoot: project, + ...(singleHandoff ? { completedOutput: singleHandoff.output } : {}), + workspace: worktree, + environment: { + ...access.environment, + DEEPSCIENTIST_MATH_WORKER_ID: workerId, + DEEPSCIENTIST_MATH_WORKER_WORKTREE: worktree, + }, + model: state.model, + effort: state.effort, + threadId: state.threadId, + ...turnTiming, + instructions, + onActivity: activity => { + state.lastActivity = { ...activity, at: Date.now() }; + emit('worker_activity', { activity: activity.event, itemType: activity.itemType }); + if (activity.event === 'lean_environment_ready') + emit('lean_environment_ready', { workerId, health: activity.health }); + activeCheckpoint?.onActivity(activity); + }, + ...usageCallbacks, + onUsage: (value, context) => { + usageCallbacks.onUsage(value, context); + if (!explicitCompaction) contextUsageVersion++; + }, + }); + if ( + state.agentSessionPlan && + session.executionPlan && + canonicalMathJson(state.agentSessionPlan) !== canonicalMathJson(session.executionPlan) + ) + throw new Error('math_agent_session_plan_changed'); + usage.sessionOpened(session); + sessionHasHistory = Boolean(resumingThread && resumingThread === session.threadId); + if (sharedTeam && session.processIdentity) { + state.writerProcess = session.processIdentity; + save(); + } + } catch (error) { + if (recordUnconfirmedWriterStartup(state, error, save)) throw error; + signal.throwIfAborted(); + if (error instanceof LeanEnvironmentHealthCheckError) + emit('lean_environment_unavailable', { workerId, health: error.health }); + const detail = failureDetail(error); + if (!recoverableResearchFailure(detail)) throw error; + await retryFailedTurn(detail); + if (researchFailureReason(detail) === 'math_model_context_window_exceeded') return 'rebuild'; + } + } + if (signal.aborted) { + await close(); + signal.throwIfAborted(); + } + sessionInstructions = instructions; + if (session.threadId) { + rememberSessionThread(session.threadId); + save(); + } + return 'ready'; + }; + const beginTurn = async ( + currentContext: ContextBundle, + operation: ResearchOperation, + ): Promise<'ready' | DispatchOutcome> => { // A new session validates its launch inputs immediately before opening, including retries. if (session) access.assertHarnessCurrent?.(); usage.resetTurn(); - rebuildContext = false; turnContext = { digest: mathDigest( canonicalMathJson({ instructions: currentContext.instructions, operation, - problem: state.problem.receiptDigest, + problem: problem.receiptDigest, environment: state.environmentDigest, model: state.model, - optionalBytes: - research.contextOverflow?.maxOptionalContextBytes ?? currentContext.manifest?.maxOptionalBytes, - sources: state.problem.ownedFiles.map(file => [ + optionalBytes: state.contextOverflow?.maxOptionalContextBytes ?? currentContext.manifest?.maxOptionalBytes, + sources: problem.ownedFiles.map(file => [ file, - mathDigest(fs.readFileSync(path.join(worker.worktree, state.problem.projectRelative, file))), + mathDigest(fs.readFileSync(path.join(worktree, problem.projectRelative, file))), ]), }), ), - fresh: !research.threadId, + fresh: !state.threadId, }; - if (turnContext.fresh && research.contextOverflow?.failedFreshContextDigests.includes(turnContext.digest)) + if (turnContext.fresh && state.contextOverflow?.failedFreshContextDigests.includes(turnContext.digest)) throw new Error('math_model_context_capacity_blocked'); - writeOwnedDeclarationIndex(state.problem, worker.worktree); + writeOwnedDeclarationIndex(problem, worktree); if (currentContext.manifest) { - research.lastContextManifest = currentContext.manifest; - writeMathJsonDurable(path.join(worker.worktree, 'CONTEXT-MANIFEST.json'), currentContext.manifest); + state.lastContextManifest = currentContext.manifest; + writeMathJsonDurable(path.join(worktree, 'CONTEXT-MANIFEST.json'), currentContext.manifest); emit('context_compiled', { contentDigest: currentContext.manifest.contentDigest, requiredTaskIds: currentContext.manifest.requiredTaskIds, @@ -675,14 +561,14 @@ export async function runResearchLead(input: { maxBytes: currentContext.manifest.maxBytes, }); } - if (!reserveTurn()) return false; + if (!reserveTurn()) return 'stopped'; if (currentContext.knowledgeRetrievals?.length && currentContext.manifest) { const ledger = (state.knowledgeRetrievals ??= { dropped: 0, observations: [] }); for (const retrieval of currentContext.knowledgeRetrievals) { const observation = { ...retrieval, - workerId: worker.id, - workerTurn: research.turns, + workerId, + workerTurn: state.turns, runTurn: state.turns, contextDigest: currentContext.manifest.contentDigest, at: Date.now(), @@ -695,123 +581,17 @@ export async function runResearchLead(input: { ledger.dropped += excess; save(); } - if (!session) { - const workspace = worker.worktree; - while (!session) { - signal.throwIfAborted(); - if (!dispatchAllowed() || budget().remainingMs <= 0) return false; - try { - const sessionId = crypto.randomUUID(); - const resumingThread = research.threadId; - const usageCallbacks = usage.bindSession(sessionId, () => session?.lastInputTokens); - if (usageCallbacks.requestGate) - usageCallbacks.requestGate.checkpoint = () => softSliceAtModelBoundary?.() ?? false; - if (team && usageCallbacks.requestGate) - usageCallbacks.requestGate = team.leadRequestGate(usageCallbacks.requestGate); - access.assertHarnessCurrent?.(); - session = await modules.M1.open({ - executable: input.executable, - profile: input.profile, - ...(sessionSkill ? { skills: [sessionSkill] } : {}), - ...(team - ? { - tools: team.tools(), - isolateProcess: true, - ...(!team.mayStartProofWork ? { readOnlyWorkspace: true } : {}), - nativeAgentControl: team.nativeAgentControlOptions(), - } - : {}), - ...(team - ? { - leanHealthCheck: researchLeanHealthCheck( - input.root, - path.join(worker.worktree, state.problem.projectRelative), - modules.M4.tools, - ), - } - : {}), - hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), ...(team?.hiddenRoots ?? [])], - soloProofWorkspace: !team, - readableRoots: researchToolRoots(input.root, modules.M4.tools), - proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative), - completedOutput: singleHandoff.output, - workspace, - environment: { - ...access.environment, - DEEPSCIENTIST_MATH_WORKER_ID: worker.id, - DEEPSCIENTIST_MATH_WORKER_WORKTREE: workspace, - }, - model: state.model, - effort: state.effort, - threadId: research.threadId, - ...turnTiming, - instructions: currentContext.instructions, - onActivity: activity => { - research.lastActivity = { ...activity, at: Date.now() }; - emit('worker_activity', { activity: activity.event, itemType: activity.itemType }); - // Solo activity is telemetry. Requests and proof transitions save their own checkpoints. - if (team) save(); - if (activity.event === 'lean_environment_ready') - emit('lean_environment_ready', { workerId: worker.id, health: activity.health }); - turnActivity?.(activity); - }, - ...usageCallbacks, - onUsage: (value, context) => { - usageCallbacks.onUsage(value, context); - if (!explicitCompaction) contextUsageVersion++; - }, - }); - if ( - state.agentSessionPlan && - session.executionPlan && - canonicalMathJson(state.agentSessionPlan) !== canonicalMathJson(session.executionPlan) - ) - throw new Error('math_agent_session_plan_changed'); - usage.sessionOpened(session); - sessionHasHistory = Boolean(resumingThread && resumingThread === session.threadId); - team?.setLeadSession(session); - if (team && session.processIdentity) { - state.writerProcess = session.processIdentity; - save(); - } - } catch (error) { - if (recordUnconfirmedWriterStartup(research, error, save)) throw error; - signal.throwIfAborted(); - if (error instanceof LeanEnvironmentHealthCheckError) - emit('lean_environment_unavailable', { workerId: worker.id, health: error.health }); - const detail = failureDetail(error); - if (!recoverableResearchFailure(detail)) throw error; - await retryFailedTurn(detail); - if (researchFailureReason(detail) === 'math_model_context_window_exceeded') { - rebuildContext = true; - if (unreserveTurn()) save(); - return false; - } - } - } - if (signal.aborted) { - await close(); - signal.throwIfAborted(); - } - sessionInstructions = currentContext.instructions; - if (session.threadId) { - if (!research.threadId || research.threadId !== session.threadId) - research.contextCheckpointBaseline = { threadId: session.threadId, notesDigest: checkpointNotesDigest() }; - research.threadId = session.threadId; - save(); - } - } - if ((await maintainContext()) !== 'unchanged') { - // Select the dispatch again if maintenance changed what this thread retains. - rebuildContext = true; + const opened = session ? 'ready' : await openResearchSession(currentContext.instructions); + if (opened === 'stopped') return opened; + if (opened === 'rebuild' || (await maintainContext())) { + // Recompile the turn after recovering from an overflow or changing thread history. if (unreserveTurn()) save(); - return false; + return 'rebuild'; } - // Opening a session can await while another worker exhausts the shared allowance. - return dispatchAllowed(); + return dispatchAllowed() ? 'ready' : 'stopped'; }; const retryFailedTurn = async (error?: string, diagnostic?: MathAgentFailureDiagnostic): Promise => { - research.lastFailure = { + state.lastFailure = { at: Date.now(), reason: researchFailureReason(error, diagnostic), ...(diagnostic ? { diagnostic: safeFailureDiagnostic(diagnostic) } : {}), @@ -819,18 +599,14 @@ export async function runResearchLead(input: { save(); if (!dispatchAllowed()) return; if (researchFailureReason(error) === 'math_model_context_window_exceeded') { - const overflow = (research.contextOverflow ??= { maxOptionalContextBytes: 0, failedFreshContextDigests: [] }); + const overflow = (state.contextOverflow ??= { maxOptionalContextBytes: 0, failedFreshContextDigests: [] }); overflow.maxOptionalContextBytes = 0; if (turnContext?.fresh && !overflow.failedFreshContextDigests.includes(turnContext.digest)) overflow.failedFreshContextDigests.push(turnContext.digest); - if (team && research.threadId && team.archive.nativeControl?.rootThreadId === research.threadId) { - if (nativeContextRecovery === 'attempted') throw new Error('math_model_context_capacity_blocked'); - nativeContextRecovery = 'pending'; - } await rotateSession('context'); retries = 0; emit('worker_context_recovering', { - reason: research.lastFailure.reason, + reason: state.lastFailure.reason, contextDigest: turnContext?.digest, maxOptionalContextBytes: 0, }); @@ -839,12 +615,12 @@ export async function runResearchLead(input: { } const retry = modules.M3.retry(error, retries, { ...state, turns: state.turns - Number(reservedTurn) }, budget()); if (!retry) { - const previous = research.recovery?.phase !== 'recovered' ? research.recovery : undefined; + const previous = state.recovery?.phase !== 'recovered' ? state.recovery : undefined; const cooldown = retries >= 3 ? planResearchCooldown(error, previous?.cycles ?? 0, budget()) : undefined; if (!cooldown) throw new Error(researchFailureReason(error)); await rotateSession('request'); const now = Date.now(); - research.recovery = { + state.recovery = { phase: 'cooling-down', reason: cooldown.reason, cycles: cooldown.cycle, @@ -856,7 +632,7 @@ export async function runResearchLead(input: { reason: cooldown.reason, cycle: cooldown.cycle, delayMs: cooldown.delayMs, - nextRetryAt: research.recovery.nextRetryAt, + nextRetryAt: state.recovery.nextRetryAt, }); save(); await waitForRecovery(); @@ -864,9 +640,9 @@ export async function runResearchLead(input: { return; } retries = retry.attempt; - // Close failed writers before retrying. A bound native team must reopen its existing root. + // Close failed writers before rotating the thread. if ( - research.threadId && + state.threadId && (retry.reason === 'math_model_tool_failed' || (retry.reason === 'math_model_request_failed' && retries === 2) || (retries === 1 && ['math_model_request_timeout', 'math_codex_transport_closed'].includes(retry.reason))) @@ -884,93 +660,83 @@ export async function runResearchLead(input: { const rotateSession = async (reason: 'context' | 'request') => { dispatched = undefined; sessionInstructions = undefined; - const previous = research.threadId; + const previous = state.threadId; await close(); - if (previous && team && team.archive.nativeControl?.rootThreadId === previous) { - // Child lineage, mailbox ownership and the host's usage baseline all bind this thread ID. - sessionHasHistory = false; - compactedUsageVersion = -1; - save(); - emit('context_reconnecting', { threadId: previous, turns: research.turns, reason }); - return; - } - if (previous) research.previousThreadIds = [...(research.previousThreadIds ?? []), previous]; - research.threadId = undefined; - research.lastInputTokens = undefined; - research.contextCheckpoint = undefined; - research.contextCheckpointBaseline = undefined; + if (previous) state.previousThreadIds = [...(state.previousThreadIds ?? []), previous]; + state.threadId = undefined; + state.lastInputTokens = undefined; + state.contextCheckpoint = undefined; + state.contextCheckpointBaseline = undefined; sessionHasHistory = false; compactedUsageVersion = -1; - research.usageBeforeThread = research.usage; + state.usageBeforeThread = state.usage; save(); - emit('context_restarted', { previousThreadId: previous, turns: research.turns, reason }); + emit('context_restarted', { previousThreadId: previous, turns: state.turns, reason }); }; - const maintainContext = async (): Promise<'unchanged' | 'compacted' | 'rotated'> => { - const recoverNative = nativeContextRecovery === 'pending'; - if ((skillMode && !recoverNative) || !research.threadId) return 'unchanged'; - const threadId = research.threadId; + const maintainContext = async (): Promise => { + if (skillMode || !state.threadId) return false; + const threadId = state.threadId; const notesDigest = currentCheckpointNotesDigest(); - if (!session) { - if (!notesDigest) return 'unchanged'; - emit('context_checkpoint_ready', { threadId, notesDigest }); - await rotateSession('context'); - return 'rotated'; - } - if (!sessionHasHistory) return 'unchanged'; - const lastInputTokens = Math.max(session.lastInputTokens ?? 0, research.lastInputTokens ?? 0); - if (!recoverNative && lastInputTokens < 96_000 && !notesDigest) return 'unchanged'; - if (recoverNative) nativeContextRecovery = 'attempted'; - if (session.compact && (recoverNative || compactedUsageVersion !== contextUsageVersion || notesDigest)) { + if (session && !sessionHasHistory) return false; + const lastInputTokens = Math.max(session?.lastInputTokens ?? 0, state.lastInputTokens ?? 0); + if (!notesDigest && (!session || lastInputTokens < 96_000)) return false; + // Wait for new usage or saved notes before asking for native compaction again. + if (session?.compact && compactedUsageVersion === contextUsageVersion && !notesDigest) return false; + if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); + if (session?.compact) { const startedAt = Date.now(); - if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); emit('context_compaction_requested', { threadId, lastInputTokens }); usage.beginMaintenance(); explicitCompaction = true; try { await session.compact(); signal.throwIfAborted(); - markCompaction(threadId, 'completed'); + dispatched = undefined; compactedUsageVersion = contextUsageVersion; - research.contextCheckpoint = undefined; - research.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() }; - research.lastInputTokens = session.lastInputTokens; + state.contextCheckpoint = undefined; + state.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() }; + state.lastInputTokens = session.lastInputTokens; emit('context_compaction_completed', { threadId, maintenanceMs: Date.now() - startedAt }); save(); - return 'compacted'; + return true; } catch (error) { signal.throwIfAborted(); emit('context_compaction_failed', { threadId, reason: failureDetail(error) }); - if (recoverNative) throw new Error('math_model_context_capacity_blocked', { cause: error }); } finally { explicitCompaction = false; usage.finishMaintenance(); } - await rotateSession('context'); - return 'rotated'; } - if (recoverNative) throw new Error('math_model_context_capacity_blocked'); - if (session.compact) return 'unchanged'; // Wait for a new usage observation before another native maintenance request. - if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); await rotateSession('context'); - return 'rotated'; + return true; + }; + const recordKnowledgeUses = (uses: readonly KnowledgeUse[], commit: string) => { + const records = (state.knowledgeUses ??= []); + for (const use of uses) { + const record = { ...use, workerId, commit }; + const key = canonicalMathJson(record); + if (records.some(previous => canonicalMathJson(previous) === key)) continue; + records.push(record); + emit('knowledge_use_observed', { ...record }); + } }; - const checkWhole = async (candidate = research.candidate) => { - const previousFailures = research.failures; + const checkWhole = async (candidate = state.candidate) => { + const previousFailures = state.failures; const checkStarted = Date.now(); - emit('proof_check_started', { turn: research.turns }); - research.check = await modules.M2.check( - state.problem, - worker.worktree, + emit('proof_check_started', { turn: state.turns }); + const check = (state.check = await modules.M2.check( + problem, + worktree, access.environment, signal, lastCheck, input.proofTimeoutMs, - ); - research.failures = rememberSolverFailure(research.check, previousFailures); - const reused = research.check === lastCheck || research.check.verification === lastCheck?.verification; + )); + state.failures = rememberSolverFailure(check, previousFailures); + const reused = check === lastCheck || check.verification === lastCheck?.verification; emit('proof_checked', { - passed: research.check.passed, - commit: research.check.commit, + passed: check.passed, + commit: check.commit, reused, durationMs: Date.now() - checkStarted, }); @@ -978,7 +744,7 @@ export async function runResearchLead(input: { let claims: unknown; try { claims = parseMathResponse( - committedSource(worker.worktree, research.check.commit, 'RESEARCH.md'), + committedSource(worktree, check.commit, 'RESEARCH.md'), 'math-result', {}, 'summary', @@ -986,125 +752,71 @@ export async function runResearchLead(input: { } catch { /* Ordinary notes need no usage response. */ } - { - const records = (state.knowledgeUses ??= []); - for (const [index, target] of state.problem.targets.entries()) { - const task = { - id: `original_goal_${index + 1}`, - kind: 'goal' as const, - objective: `Prove ${target.theoremName}`, - revision: 0, - dependsOn: [], - ...target, - }; - const observed = inspectKnowledgeUses( - claims, - access.knowledgeSnapshot, - task, - research.check, - access.installedLibrary, - ); - const checked = await checkKnowledgeApplications(observed.uses, { - task, - projectRoot: path.join(worker.worktree, state.problem.projectRelative), - env: access.environment, - environmentDigest: state.environmentDigest, - commit: research.check.commit, - signal, - timeoutMs: input.proofTimeoutMs ?? Infinity, - originalContexts: state.problem.targets, - previous: records, - sourceAtCommit: file => - committedSource( - worker.worktree, - research.check!.commit, - path.posix.join(state.problem.projectRelative, file), - ), - }); - for (const use of checked) { - const record = { ...use, workerId: worker.id, commit: research.check!.commit }; - const key = canonicalMathJson(record); - if (!records.some(previous => canonicalMathJson(previous) === key)) { - records.push(record); - emit('knowledge_use_observed', { ...record }); - } - } - if (observed.rejected) - emit('knowledge_use_rejected', { commit: research.check!.commit, rejected: observed.rejected }); - } - if (records.length > 256) records.splice(0, records.length - 256); + const records = (state.knowledgeUses ??= []); + for (const [index, target] of problem.targets.entries()) { + const task = { + id: `original_goal_${index + 1}`, + kind: 'goal' as const, + objective: `Prove ${target.theoremName}`, + revision: 0, + dependsOn: [], + ...target, + }; + const observed = inspectKnowledgeUses(claims, access.knowledgeSnapshot, task, check, access.installedLibrary); + const checked = await checkKnowledgeApplications(observed.uses, { + task, + projectRoot: path.join(worktree, problem.projectRelative), + env: access.environment, + environmentDigest: state.environmentDigest, + commit: check.commit, + signal, + timeoutMs: input.proofTimeoutMs ?? Infinity, + originalContexts: problem.targets, + previous: records, + sourceAtCommit: file => + committedSource(worktree, check.commit, path.posix.join(problem.projectRelative, file)), + }); + recordKnowledgeUses(checked, check.commit); + if (observed.rejected) emit('knowledge_use_rejected', { commit: check.commit, rejected: observed.rejected }); } + if (records.length > 256) records.splice(0, records.length - 256); } - lastCheck = research.check; + lastCheck = check; save(); - if (research.check.passed) { - state.check = research.check; + if (check.passed) { state.candidate = candidate; - winner = { worktree: worker.worktree, check: research.check }; + winner = { worktree, check }; save(); - emit('candidate_selected', { commit: research.check.commit }); + emit('candidate_selected', { commit: check.commit }); abort(); return; } - if (['unavailable', 'blocked'].includes(research.check.verification.status)) + if (['unavailable', 'blocked'].includes(check.verification.status)) throw new VerifierFailureError({ stage: 'solver-proof-check', - sourceCommit: research.check.commit, - verification: research.check.verification, + sourceCommit: check.commit, + verification: check.verification, }); }; const skillProofLifecycle = skillMode ? createSkillProofLifecycle({ state, - worktree: worker.worktree, + worktree, environment: access.environment, skill: access.researchSkill!, signal, proofTimeoutMs: input.proofTimeoutMs, - writerStopped: () => !session && !research.writerStopUnconfirmed, + writerStopped: () => !session && !state.writerStopUnconfirmed, + checkHelpers: !sharedTeam, sourceFeedback, - exclusiveCheck, checkWhole, save, emit, }) : undefined; const resumeSkillProofWork = async () => { - if (team && !team.mayStartProofWork) return; + if (!mayStartProofWork()) return; await skillProofLifecycle?.resumePending(); - if (!winner && !signal.aborted && deferredLeadAdoptions && team) { - deferredLeadAdoptions = false; - await team.flushAdoptions(); - await skillProofLifecycle!.resumePending(); - } - }; - const awaitNativePlanApproval = async () => { - if (planApprovalStatus(state) !== 'pending') return true; - if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0) { - emit('plan_approval_unanswered', { planVersion: state.cooperation?.planVersion }); - return false; - } - // A resumed run can be waiting on a saved plan before it reserves a new turn. - if (state.phase !== 'running') { - research.phase = 'running'; - save(); - } - const stateFile = path.join(path.dirname(state.worktree), 'state.json'); - const read = () => drainPlanApprovals(state, stateFile, signal, save, input.emit); - read(); - if (planApprovalStatus(state) !== 'pending') return true; - input.executionBudget?.setWaiting(true); - save(); - try { - do { - await delay(200, undefined, { signal }); - read(); - } while (planApprovalStatus(state) === 'pending'); - } finally { - input.executionBudget?.setWaiting(false); - save(); - } - return true; }; let deliveredApprovedPlan = false; let liveDraft = false; @@ -1113,16 +825,17 @@ export async function runResearchLead(input: { operation: ResearchOperation; turnSession: MathAgentSession; executionError?: string; + checkpointReason?: ResearchTurnCheckpointReason; }; type ProofTurn = { candidate: ResearchCandidate; turnError?: string; diagnostic?: MathAgentFailureDiagnostic }; const dispatchTurn = async (): Promise => { if ( !skillMode && - research.threadId && - research.contextCheckpoint?.threadId === research.threadId && - !research.contextCheckpoint.requestId + state.threadId && + state.contextCheckpoint?.threadId === state.threadId && + !state.contextCheckpoint.requestId ) - requestContextCheckpoint(Math.max(session?.lastInputTokens ?? 0, research.lastInputTokens ?? 0)); + requestContextCheckpoint(Math.max(session?.lastInputTokens ?? 0, state.lastInputTokens ?? 0)); await maintainContext(); const options: readonly ResearchOperation[] = ['direct']; const action = @@ -1137,36 +850,30 @@ export async function runResearchLead(input: { const onStarted = (turnId: string) => { // Some headless CLIs report a native ID only after starting. Persist that exact // identity before publishing a turn; an empty ID cannot stand for a saved thread. - if (!session?.threadId) throw new Error('math_agent_session_binding_missing'); - if (research.threadId !== session.threadId) { - research.contextCheckpointBaseline = { threadId: session.threadId, notesDigest: checkpointNotesDigest() }; - research.threadId = session.threadId; - save(); - } - emit('turn_started', { turnId, threadId: session.threadId, turn: research.turns, totalTurns: state.turns }); + const threadId = session?.threadId; + if (!threadId) throw new Error('math_agent_session_binding_missing'); + if (rememberSessionThread(threadId)) save(); + emit('turn_started', { turnId, threadId, turn: state.turns, totalTurns: state.turns }); }; const repair = sourceFeedback(); - if (repair) research.check = undefined; + if (repair) state.check = undefined; const currentContext = context(repair, feedbackCheck, feedbackFailures); const responsibility = skillMode ? mathDigest(currentContext.instructions) : undefined; - const sameResponsibility = + const continuation = responsibility !== undefined && dispatched?.responsibility === responsibility && - Boolean(research.threadId) && - dispatched.threadId === research.threadId && + Boolean(state.threadId) && + dispatched.threadId === state.threadId && currentContext.continuationMessage !== undefined; - const continuation = sameResponsibility && !dispatched?.compaction; const checkpointInstruction = - research.threadId && - research.contextCheckpoint?.threadId === research.threadId && - !currentCheckpointNotesDigest() + state.threadId && state.contextCheckpoint?.threadId === state.threadId && !currentCheckpointNotesDigest() ? contextCheckpointInstruction : undefined; Object.assign(currentContext, finalizeResearchDispatch(currentContext, { continuation, checkpointInstruction })); - if (team?.reviewPlan && !deliveredApprovedPlan) { + if (nativePlanReview && !deliveredApprovedPlan) { const approval = state.cooperation?.planApproval; currentContext.message = - (team.mayStartProofWork + (mayStartProofWork() ? `The human approved plan version ${approval!.approvedVersion}. Begin proof research and coordinate the native team. Approved route:\n` + nativeApprovalPlanBrief(state.cooperation!.tasks) : 'This turn is for planning only. Read the frozen statement and publish one concrete route objective for each original theorem ' + @@ -1176,17 +883,56 @@ export async function runResearchLead(input: { currentContext.message; } if (session && sessionInstructions !== currentContext.instructions) await close(); - if (!(await beginTurn(currentContext, operation))) { - return rebuildContext ? 'rebuild' : 'stopped'; - } - let candidate: ResearchCandidate | undefined; - let executionError: string | undefined; + const admission = await beginTurn(currentContext, operation); + if (admission !== 'ready') return admission; const turnSession = session!; + let candidate: ResearchCandidate; + let executionError: string | undefined; + let checkpoint: ReturnType | undefined; try { - candidate = await modelTurn( - started => - modules.M1.execute(state.problem, currentContext, operation, worker, turnSession, signal, turnId => { - if (team?.reviewPlan && team.mayStartProofWork) deliveredApprovedPlan = true; + if (!dispatchAllowed() || budget().remainingMs <= 0 || signal.aborted) return 'stopped'; + const kind = mayStartProofWork() ? 'proof' : 'planning'; + const counts = (state.dispatchCounts ??= {}); + counts[kind] = (counts[kind] ?? 0) + 1; + reservedTurn = false; + usage.begin(); + let completed = false; + try { + const turnCheckpoint = createResearchTurnCheckpoint({ + session: turnSession, + signal, + milestone: + kind === 'proof' + ? { settings: milestoneSettings, mode: sharedTeam ? 'team' : skillMode ? 'skill' : 'legacy' } + : undefined, + // Only existing runs with pinned edit probes use a speculative checker. + savedEdit: + state.savedEditChecks && !sharedTeam && skillMode + ? { + problem, + worktree, + env: access.environment, + timeoutMs: Math.min(5_000, input.proofTimeoutMs ?? Infinity), + } + : undefined, + isCurrent: () => session === turnSession, + close, + onCompaction: () => { + dispatched = undefined; + }, + failureDetail, + emit, + }); + checkpoint = activeCheckpoint = turnCheckpoint; + candidate = await modules.M1.execute( + problem, + currentContext, + operation, + worker, + turnSession, + signal, + turnId => { + if (nativePlanReview && mayStartProofWork()) deliveredApprovedPlan = true; dispatched = responsibility === undefined ? undefined : { responsibility, threadId: turnSession.threadId }; emit('context_dispatched', { @@ -1196,94 +942,86 @@ export async function runResearchLead(input: { messageDigest: mathDigest(currentContext.message), compiledContentDigest: currentContext.manifest?.contentDigest, }); - started(turnId); - }), - onStarted, - ); + onStarted(turnId); + turnCheckpoint.start(turnId); + }, + ); + const detail = failureDetail(undefined, turnSession.lastError, turnSession.lastFailureDiagnostic); + if (usage.stopReason && detail !== usage.stopReason) throw new Error(detail); + completed = candidate.status === 'completed'; + if (completed) recovered(); + } finally { + activeCheckpoint = undefined; + try { + await checkpoint?.finish(completed); + } finally { + usage.finish(completed); + } + } } catch (error) { signal.throwIfAborted(); executionError = failureDetail(error, turnSession.lastError, turnSession.lastFailureDiagnostic); if ( - !savedEditCheckpoint && - !softSliceCheckpoint && - !(team?.reviewPlan && planApprovalStatus(state) === 'pending') && + !checkpoint?.reason && + !(nativePlanReview && planApprovalStatus(state) === 'pending') && !recoverableResearchFailure(executionError) && !locallyStopped(executionError) ) throw error; candidate = { status: 'failed', - worktree: worker.worktree, - problemReceiptDigest: state.problem.receiptDigest, + worktree, + problemReceiptDigest: problem.receiptDigest, operation, - provenance: { workerId: worker.id, threadId: turnSession.threadId }, + provenance: { workerId, threadId: turnSession.threadId }, }; } - if (!candidate) return 'stopped'; - return { candidate, operation, turnSession, executionError }; + return { candidate, operation, turnSession, executionError, checkpointReason: checkpoint?.reason }; }; const settleTurn = async ({ candidate, operation, turnSession, executionError, + checkpointReason, }: DispatchedTurn): Promise => { - if (candidate.status !== 'failed' && currentCheckpointNotesDigest()) contextSchedulingCheckpoint = true; - if (savedEditCheckpoint || softSliceCheckpoint || contextSchedulingCheckpoint) - candidate = { ...candidate, status: 'checkpoint' }; + const reason = + checkpointReason ?? + (candidate.status !== 'failed' && currentCheckpointNotesDigest() + ? 'math_context_scheduling_checkpoint' + : undefined); + if (reason) candidate = { ...candidate, status: 'checkpoint' }; const lastInputTokens = session?.lastInputTokens; sessionHasHistory = true; const diagnostic = safeFailureDiagnostic(session?.lastFailureDiagnostic); const turnError = executionError ?? failureDetail(session?.lastError, undefined, diagnostic); - if (team && !team.mayStartProofWork) { + if (!mayStartProofWork()) { // The planner's response never becomes a proof candidate. Stop its process before // pausing the execution clock and wait in the host, outside any model turn. - await stopProofWriter({ - session: turnSession, - record: research, - workerId: worker.id, - close, - save, - deferred: reason => emit('proof_ready_freeze_deferred', { reason }), - confirmed: reason => emit('proof_ready_freeze_confirmed', { reason }), - }); - team.leadWriterStopped(); + await stopWriter(turnSession); state.writerProcess = undefined; save(); if (planApprovalStatus(state) === 'pending') { retries = 0; - emit('turn_checkpoint', { turn: research.turns, reason: 'math_team_plan_approval' }); + emit('turn_checkpoint', { turn: state.turns, reason: 'math_team_plan_approval' }); } else if (candidate.status === 'failed') await retryFailedTurn(turnError, diagnostic); return 'planning'; } if (access.libraryCatalog && candidate.status !== 'failed') { let request: LibraryInstallationRequested | undefined; try { - request = takeLibraryRequest(state.problem, worker.worktree, access.libraryCatalog); + request = takeLibraryRequest(problem, worktree, access.libraryCatalog); } catch (error) { emit('library_request_rejected', { reason: error instanceof Error ? error.message : String(error) }); - fs.rmSync(path.join(worker.worktree, 'LIBRARY_REQUEST.json'), { force: true }); + fs.rmSync(path.join(worktree, 'LIBRARY_REQUEST.json'), { force: true }); } if (request) { if (skillMode) { - await stopProofWriter({ - session: turnSession, - record: research, - workerId: worker.id, - close, - save, - deferred: reason => emit('proof_ready_freeze_deferred', { reason }), - confirmed: reason => emit('proof_ready_freeze_confirmed', { reason }), - }); - if (team) { - team.leadWriterStopped(); - state.writerProcess = undefined; - save(); - } + await stopWriter(turnSession); } else await close(); access.assertHarnessCurrent?.(); if (access.researchSkill) assertMathAgentSkillsCurrent([access.researchSkill]); - if (!sourceFeedback()) commitSolverSources(state.problem, worker.worktree); + if (!sourceFeedback()) commitSolverSources(problem, worktree); emit('library_installation_requested', { names: request.request.names, catalogDigest: request.request.catalogDigest, @@ -1292,13 +1030,13 @@ export async function runResearchLead(input: { } } if ( - candidate.worktree !== worker.worktree || - candidate.problemReceiptDigest !== state.problem.receiptDigest || + candidate.worktree !== worktree || + candidate.problemReceiptDigest !== problem.receiptDigest || candidate.operation !== operation || - candidate.provenance.workerId !== worker.id + candidate.provenance.workerId !== workerId ) throw new Error('math_candidate_identity_changed'); - const singleSubmission = singleHandoff.takeSubmission(); + const singleSubmission = singleHandoff?.takeSubmission(); // Keep a settled solo draft in its existing session while it has open goals. // The writer still stops before the host freezes or checks its source. if ( @@ -1311,15 +1049,14 @@ export async function runResearchLead(input: { state.turns < input.maxTurns && budget().remainingMs > 0 && !signal.aborted && - !fs.existsSync(path.join(worker.worktree, '.scratch', DECLARATION_SUBMISSION_FILE)) && + !fs.existsSync(path.join(worktree, '.scratch', DECLARATION_SUBMISSION_FILE)) && !sourceFeedback() && - originalProofHasHoles(state.problem, worker.worktree) + originalProofHasHoles(problem, worktree) ) { - research.lastInputTokens = lastInputTokens ?? research.lastInputTokens; - research.candidate = candidate; - research.check = undefined; + state.lastInputTokens = lastInputTokens ?? state.lastInputTokens; + state.candidate = candidate; + state.check = undefined; retries = 0; - nativeContextRecovery = undefined; liveDraft = true; save(); emit('research_draft_saved', { originalProblemAcceptance: 'not-assessed' }); @@ -1329,58 +1066,30 @@ export async function runResearchLead(input: { if (singleSubmission || skillMode) { // The runtime has settled the turn and stopped new requests. Reap all remaining // writer processes before the ordinary source freeze and independent host check. - await stopProofWriter({ - session: turnSession, - record: research, - workerId: worker.id, - close, - save, - deferred: reason => emit('proof_ready_freeze_deferred', { ...singleSubmission, reason }), - confirmed: reason => emit('proof_ready_freeze_confirmed', { ...singleSubmission, reason }), - }); - if (team) { - team.leadWriterStopped(); - state.writerProcess = undefined; - save(); - } + await stopWriter(turnSession, singleSubmission); access.assertHarnessCurrent?.(); // submitted is a delivery status, never proof acceptance. The usual M2 check below // fingerprints the stopped writer's actual sources and verifies every original target. if (singleSubmission) candidate = { ...candidate, status: 'completed' }; } if (candidate.status === 'failed') await close(); - research.lastInputTokens = lastInputTokens ?? research.lastInputTokens; - research.candidate = candidate; + state.lastInputTokens = lastInputTokens ?? state.lastInputTokens; + state.candidate = candidate; const turn = candidate.status; if (!['completed', 'failed', 'checkpoint'].includes(turn)) return 'unsupported'; if (turn !== 'failed') { retries = 0; - nativeContextRecovery = undefined; } if (turn === 'checkpoint') emit('turn_checkpoint', { - turn: research.turns, - ...(team?.leadCompletionCheckpoint - ? { reason: 'math_team_completion_checkpoint' } - : team?.leadAdoptionCheckpoint - ? { reason: 'math_team_adoption_checkpoint' } - : savedEditCheckpoint - ? { reason: 'math_saved_edit_checkpoint' } - : softSliceCheckpoint - ? { reason: 'math_soft_slice_checkpoint' } - : contextSchedulingCheckpoint - ? { reason: 'math_context_scheduling_checkpoint' } - : {}), + turn: state.turns, + ...(reason ? { reason } : {}), }); if (turn === 'failed') emit('turn_failed', { reason: researchFailureReason(turnError), ...(diagnostic ? { diagnostic } : {}) }); const sourceError = sourceFeedback(); if (sourceError) { - if (team?.archive.completionRequested) { - emit('team_completion_rejected', { reason: sourceError, requestedAt: team.archive.completionRequested.at }); - team.archive.completionRequested = undefined; - } - research.check = undefined; + state.check = undefined; save(); emit('source_rejected', { reason: sourceError }); if (turn === 'failed' && turnError && !locallyStopped(turnError)) { @@ -1394,18 +1103,11 @@ export async function runResearchLead(input: { return 'rejected'; } if (skillMode) { - await team?.flushAdoptions(); const { commit, wholeProofReady } = await skillProofLifecycle!.freezeSources(); - if (team?.archive.completionRequested) { - const requested = team.archive.completionRequested; - team.archive.completionRequested = undefined; - emit('team_completion_frozen', { commit, wholeProofReady, requestedAt: requested.at }); - save(); - } // An unfinished research turn can publish useful helpers without repeatedly // compiling every original hole. Ordinary diagnostics remain advisory. if (!wholeProofReady) { - research.check = undefined; + state.check = undefined; save(); emit('research_saved', { commit, originalProblemAcceptance: 'not-assessed' }); if (turn === 'failed') await retryFailedTurn(turnError, diagnostic); @@ -1415,16 +1117,16 @@ export async function runResearchLead(input: { return { candidate, turnError, diagnostic }; }; const verifyTurn = async ({ candidate, turnError, diagnostic }: ProofTurn) => { - const previousCheck = research.check; - const previousFailures = research.failures; + const previousCheck = state.check; + const previousFailures = state.failures; if (skillProofLifecycle) await skillProofLifecycle.checkFrozenWholeProof(candidate); else { - research.phase = 'checking'; + state.phase = 'checking'; save(); try { - await exclusiveCheck(() => checkWhole(candidate)); + await checkWhole(candidate); } finally { - research.phase = 'running'; + state.phase = 'running'; save(); } } @@ -1439,19 +1141,19 @@ export async function runResearchLead(input: { access.assertKnowledgeCurrent?.(); if ( (!skillMode || fullSkillWorkflow) && - !team && - !research.turns && + !sharedTeam && + !state.turns && access.installedLibrary && modules.M2.applyLibrary && budget().remainingMs > 0 ) { const closed = await applyOriginalLibraryTasks({ - problem: state.problem, + problem, library: access.installedLibrary, taskText: input.taskText, environmentDigest: state.environmentDigest, - worktree: worker.worktree, - workerId: worker.id, + worktree, + workerId, env: access.environment, signal, timeoutMs: Math.min(input.proofTimeoutMs ?? Infinity, budget().remainingMs), @@ -1460,40 +1162,41 @@ export async function runResearchLead(input: { emit, onProof: (task, proof) => { // A saved host proof still needs whole-problem acceptance after a restart. - research.phase = 'checking'; - const records = (state.knowledgeUses ??= []); - for (const use of inspectKnowledgeUses( - undefined, - access.knowledgeSnapshot, - task, - proof, - access.installedLibrary, - ).uses) { - const record = { ...use, workerId: worker.id, commit: proof.commit }; - if (!records.some(previous => canonicalMathJson(previous) === canonicalMathJson(record))) { - records.push(record); - emit('knowledge_use_observed', { ...record }); - } - } + state.phase = 'checking'; + recordKnowledgeUses( + inspectKnowledgeUses(undefined, access.knowledgeSnapshot, task, proof, access.installedLibrary).uses, + proof.commit, + ); save(); }, }); - if ((closed || research.phase === 'checking') && !signal.aborted) await exclusiveCheck(() => checkWhole()); + if ((closed || state.phase === 'checking') && !signal.aborted) await checkWhole(); } let dispatchedTurn!: DispatchedTurn; let proofTurn!: ProofTurn; await (input.drive ?? driveResearch)(async step => { switch (step) { case 'poll': - return { after: 'poll', aborted: signal.aborted, review: Boolean(team?.reviewPlan) }; + return { after: 'poll', aborted: signal.aborted, review: Boolean(nativePlanReview) }; case 'approve': - return { after: 'approve', released: await awaitNativePlanApproval() }; + return { + after: 'approve', + released: await waitForPlanApproval({ + state, + signal, + save, + emit: input.emit, + unanswered: () => emit('plan_approval_unanswered', { planVersion: state.cooperation?.planVersion }), + canContinue: () => dispatchAllowed() && state.turns < input.maxTurns && budget().remainingMs > 0, + setWaiting: waiting => input.executionBudget?.setWaiting(waiting), + }), + }; case 'recover': await resumeSkillProofWork(); return { after: 'recover', winner: Boolean(winner) }; case 'admit': - if (research.phase === 'checking') { - research.phase = 'running'; + if (state.phase === 'checking') { + state.phase = 'running'; save(); } return { @@ -1519,23 +1222,20 @@ export async function runResearchLead(input: { }); } catch (error) { if (!signal.aborted) { - errors.push(error); + failure = { error }; if (error instanceof VerificationCheckpointError) emit('worker_checkpoint', { reason: error.message, key: error.checkpoint.key }); else if (error instanceof LibraryInstallationRequested) emit('worker_checkpoint', { reason: error.message }); else { - research.error = error instanceof Error ? error.message : 'math_worker_failed'; + state.error = error instanceof Error ? error.message : 'math_worker_failed'; const verification = verifierFailureDiagnostic(error) ?? - (research.error === 'math_verifier_unavailable' + (state.error === 'math_verifier_unavailable' ? new VerifierFailureError({ stage: 'worker-boundary' }, error).diagnostic : undefined); - if (verification) { - research.verifierFailure = verification; - state.verifierFailure = verification; - } + if (verification) state.verifierFailure = verification; emit('worker_failed', { - reason: research.error, + reason: state.error, ...(verification ? { verification } : {}), ...(error instanceof MathGitError ? { git: error.diagnostic } : {}), }); @@ -1546,47 +1246,27 @@ export async function runResearchLead(input: { signal.removeEventListener('abort', cancel); try { if (liveDraft && session && !signal.aborted) { - await stopProofWriter({ - session, - record: research, - workerId: worker.id, - close, - save, - deferred: reason => emit('proof_ready_freeze_deferred', { reason }), - }); + await stopWriter(session); if (!sourceFeedback()) { const { commit } = await skillProofLifecycle!.freezeSources(); emit('research_saved', { commit, originalProblemAcceptance: 'not-assessed' }); } } else await close(); } catch (error) { - if (!cleanupErrors.includes(error)) cleanupErrors.push(error); - } - if (reservedTurn) { - state.turns--; + cleanupFailure ??= { error }; } + unreserveTurn(); updateUsage(); save(); } input.signal.throwIfAborted(); // Quarantine is the actionable failure even if ordinary session cleanup also failed. - const unconfirmedStop = errors.find( - error => error instanceof Error && error.message.startsWith('math_writer_stop_unconfirmed:'), - ); - if (unconfirmedStop) throw unconfirmedStop; - if (cleanupErrors.length) throw cleanupErrors[0]; - if (!winner && errors.length) - throw ( - errors.find(error => error instanceof LibraryInstallationRequested) ?? - errors.find(error => error instanceof VerificationCheckpointError) ?? - errors[0] - ); + const error = failure?.error; + if (error instanceof Error && error.message.startsWith('math_writer_stop_unconfirmed:')) throw error; + if (cleanupFailure) throw cleanupFailure.error; + if (!winner && failure) throw failure.error; return winner; } finally { - try { - await team?.close(); - } finally { - input.signal.removeEventListener('abort', abort); - } + input.signal.removeEventListener('abort', abort); } } diff --git a/src/solver/researchRetirement.ts b/src/solver/researchRetirement.ts index c706271c..e3d0879e 100644 --- a/src/solver/researchRetirement.ts +++ b/src/solver/researchRetirement.ts @@ -1,7 +1,7 @@ import type { SolverRunState } from './archive'; export const legacyCollaborationRetired = - 'math_legacy_collaboration_retired: resume with the historical TheoremOS revision that created this run.'; + 'math_legacy_collaboration_retired: resume with the historical TheoremOS revision that created this run (see archive/isolated-codex-teams for AgentControl teams).'; /** Archive readers accept historical research state. A writer only accepts solo or native team state. */ export function assertActiveResearchState( @@ -17,12 +17,13 @@ export function assertActiveResearchState( | 'commonResearchSkill' >, ) { - const nativeTeam = state.agentTeam?.transport === 'native-agent-control'; + const nativeTeam = state.agentTeam?.transport === 'codex-shared'; if ( state.portfolioExploration || state.commonResearchSkill || (state.workerCount ?? 1) > 1 || state.workers?.length || + state.agentTeam?.workers.length || state.researchDelegation?.mode === 'read-only' || ((state.researchDelegation?.mode === 'team' || state.agentTeam || state.cooperation || state.planApproval) && !nativeTeam) diff --git a/src/solver/researchToolGuide.ts b/src/solver/researchToolGuide.ts index 5759d121..aaa5c724 100644 --- a/src/solver/researchToolGuide.ts +++ b/src/solver/researchToolGuide.ts @@ -51,11 +51,9 @@ export function buildResearchToolGuide( | 'knowledgeFile' | 'knowledgeDigest' | 'libraryCatalog' - | 'teamRole' | 'assignment' >, environmentDigest: string, - team = false, soloWorkspace = false, ) { const command = researchToolCommand(access.root, access.tools); @@ -89,18 +87,13 @@ export function buildResearchToolGuide( 'lean', (file && leanCheckCommand ? `${leanCheckCommand}\n` + - `Edit ${quote(path.join(problem.projectRelative, file))} from the worktree root; pass ${quote(file)} to --file. ` + - (team - ? 'To test a peer result, append --candidate followed by its actual message:, research: or delivery: reference to this single-file check. ' - : '') + `Edit ${quote(path.join(problem.projectRelative, file))} from the worktree root; pass ${quote(file)} to --file. ` : '') + 'Pass project-relative paths. Repeat --file to check multiple sources. Preserve the Lean exit status. ' + 'Use --brief for positions and goals, or the default JSON output for firstBlocking and diagnosticArtifacts. ' + `On an infrastructure error, save your work and run ${command} check-lean --worktree ${quote(access.worktree)} --health.\n` + `Look up local declarations with rg -F -- 'NAME' ${quote(path.join(access.worktree, DECLARATION_INDEX_FILE))}. Read the declaration in its source before using it.\n` + - (team - ? 'Share a useful probe result or blocker through native send_message, with its saved source path and exact diagnostic.' - : 'Save useful probe results and exact diagnostics with source references in RESEARCH.md for continuation.'), + 'Save useful probe results and exact diagnostics with source references in RESEARCH.md for continuation.', '', ); if (access.corpusFile) @@ -132,10 +125,8 @@ export function buildResearchToolGuide( `${command} library search --worktree ${quote(access.worktree)} --query 'NAME_OR_DESCRIPTION' --goal 'EXACT_LEAN_CONTEXT'\n` + `${command} library get --worktree ${quote(access.worktree)} --name 'QUALIFIED_NAME' --max-bytes 16000\n` + 'Follow nextOffset until the source is complete. Import installed-frozen names; do not copy library sources. ' + - (access.teamRole?.role === 'worker' - ? 'If a needed declaration is not installed, send Lead its qualified name, intended application and required premises with native send_message. Lead requests installation for the team.' - : `${command} library request --worktree ${quote(access.worktree)} --name 'QUALIFIED_NAME' --reason 'EXACT_USE_AND_PREMISES'\n` + - 'A request saves the current run for host-controlled continuation; it does not mutate frozen dependencies or accept a proof.'), + `${command} library request --worktree ${quote(access.worktree)} --name 'QUALIFIED_NAME' --reason 'EXACT_USE_AND_PREMISES'\n` + + 'A request saves the current run for host-controlled continuation; it does not mutate frozen dependencies or accept a proof.', '', ); help.section( diff --git a/src/solver/researchTurnCheckpoint.ts b/src/solver/researchTurnCheckpoint.ts new file mode 100644 index 00000000..e8df5c9f --- /dev/null +++ b/src/solver/researchTurnCheckpoint.ts @@ -0,0 +1,136 @@ +import type { MathAgentActivity, MathAgentSession } from '../runtime/agentSession'; +import { createSavedEditCheck } from './savedEditCheck'; +import { createSoftSlice, type softSliceSettings } from './softSlice'; + +const nonToolItems = new Set(['reasoning', 'agentMessage', 'userMessage', 'contextCompaction']); +const interruptGraceMs = 10_000; + +export type ResearchTurnCheckpointReason = 'math_saved_edit_checkpoint' | 'math_soft_slice_checkpoint'; + +const milestoneGuidance = { + team: 'Ask teammates to save their files and report their results. ', + skill: + 'Write .scratch/declaration-submission.json only if you have at least one locally compiled standalone helper to nominate. Never write an empty declarations array. ', + legacy: 'Save standalone helpers in the owned Lean files for host checking. ', +}; + +/** Track a single model turn's opportunities to yield with its current work saved. */ +export function createResearchTurnCheckpoint(input: { + session: MathAgentSession; + signal: AbortSignal; + milestone?: { settings: ReturnType; mode: keyof typeof milestoneGuidance }; + savedEdit?: Omit[0], 'signal'>; + isCurrent(): boolean; + close(): Promise; + onCompaction(): void; + failureDetail(error: unknown): string | undefined; + emit(event: string, details: Record): void; +}) { + const { session, signal, emit } = input; + let reason: ResearchTurnCheckpointReason | undefined; + let turnId: string | undefined; + let finished = false; + let runningTools = 0; + let interruptTimer: ReturnType | undefined; + let closing: Promise | undefined; + const live = () => !finished && !signal.aborted && input.isCurrent(); + const closeStalledTurn = () => { + if (!live() || closing) return; + closing = input.close(); + void closing.catch(() => {}); + }; + const interrupt = (event: string, details: Record, checkpoint?: ResearchTurnCheckpointReason) => { + if (!live() || interruptTimer) return; + emit(event, details); + reason = checkpoint ?? reason; + interruptTimer = setTimeout(closeStalledTurn, interruptGraceMs); + interruptTimer.unref(); + void session.interrupt().catch(closeStalledTurn); + }; + const interruptAtMilestone = (boundary: 'tool' | 'wait-limit') => + interrupt('soft_slice_checkpoint_requested', { turnId, boundary }, 'math_soft_slice_checkpoint'); + + const milestoneCurrent = () => live() && !interruptTimer && !reason; + const milestone = input.milestone; + const slice = + milestone && + createSoftSlice(milestone.settings, { + current: milestoneCurrent, + notice: (trigger, completedCompactions) => { + emit(trigger === 'time' ? 'soft_slice_milestone_requested' : 'compaction_circuit_breaker_triggered', { + turnId, + completedCompactions, + graceMs: milestone.settings.graceMs, + }); + void session + .notify?.( + milestoneGuidance[milestone.mode] + + '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.', + session.advisoryNotifications === 'native-history' ? { mode: 'advisory' } : { waitForRequest: true }, + ) + .catch(error => { + if (milestoneCurrent()) emit('soft_slice_notice_failed', { reason: input.failureDetail(error) }); + }); + }, + interrupt: () => interruptAtMilestone('wait-limit'), + }); + + const editController = input.savedEdit && new AbortController(); + const checkEdit = + input.savedEdit && editController + ? createSavedEditCheck({ ...input.savedEdit, signal: AbortSignal.any([signal, editController.signal]) }) + : undefined; + let editProbe: Promise | undefined; + let editFailure: Error | undefined; + + return { + get reason() { + return reason; + }, + start(id: string) { + turnId = id; + slice?.start(); + }, + onActivity({ event, itemType }: MathAgentActivity) { + if (checkEdit && event === 'item_completed' && itemType === 'fileChange' && live()) { + editProbe = checkEdit() + .then(sourceDigest => { + if (sourceDigest) + interrupt('saved_edit_checkpoint_requested', { sourceDigest }, 'math_saved_edit_checkpoint'); + }) + .catch(error => { + editFailure = error instanceof Error ? error : new Error('math_saved_edit_check_failed'); + interrupt('saved_edit_check_failed', { reason: editFailure.message }); + }); + } + if (itemType === 'contextCompaction' && live()) { + if (event === 'item_started' || event === 'item_completed') input.onCompaction(); + if (event === 'item_completed') slice?.compacted(); + } else if (itemType && !nonToolItems.has(itemType)) { + if (event === 'item_started') runningTools++; + if (event === 'item_completed') { + runningTools = Math.max(0, runningTools - 1); + if (!runningTools && session.usageSource !== 'upstream-requests' && slice?.useBoundary()) + interruptAtMilestone('tool'); + } + } + }, + atRequestBoundary() { + if (runningTools || !slice?.useBoundary()) return false; + reason = 'math_soft_slice_checkpoint'; + emit('soft_slice_checkpoint_requested', { turnId, boundary: 'request' }); + return true; + }, + async finish(completed: boolean) { + if (slice?.requested && completed) reason ??= 'math_soft_slice_checkpoint'; + finished = true; + editController?.abort(); + slice?.stop(); + clearTimeout(interruptTimer); + await editProbe; + await closing; + if (editFailure) throw editFailure; + }, + }; +} diff --git a/src/solver/run.ts b/src/solver/run.ts index 570eb531..18a097c9 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -4,7 +4,7 @@ import path from 'node:path'; import crypto from 'node:crypto'; import { VerificationCheckpointError, withVerificationCheckpoints } from './verificationCheckpoint'; import { parseRunOptions, resolveRunStrategy, resolveRunLimits, frozenRunConfiguration } from './runOptions'; -import { readMathBuildManifest, readMathBuildManifestDigest } from '../math/mathBuildManifest'; +import { readMathBuildManifestDigest } from '../math/mathBuildManifest'; import { MathGitError } from '../math/mathGit'; import { scheduleMathTimeout } from '../math/mathTimers'; import { @@ -19,12 +19,9 @@ import { projectMathematicsRuntimeEnvironment, resolveMathematicsRuntimeEnvironment, } from '../math/mathRuntimeEnvironment'; -import { checkResolvedLeanToolchainReadiness } from '../math/leanToolchainReadiness'; -import { prepareMathProofEnvironment, MATH_PROOF_ENVIRONMENT_ENV } from '../math/mathProofEnvironment'; -import { DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT } from '../math/mathProofEnvironmentCache'; -import { DEFAULT_LEAN_LIBRARY_CACHE_ROOT } from '../math/leanCompilationCache'; +import type { prepareMathProofEnvironment } from '../math/mathProofEnvironment'; import { resolveMathematicsLakePackagesCache } from '../math/verifier'; -import { bindLeanPackages, prepareLeanDiagnosticOverrides, runLeanDiagnostics } from '../math/leanDiagnostics'; +import { bindLeanPackages } from '../math/leanDiagnostics'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; import { git, readSolverProblem, assertSolverSources } from './problem'; import { solverSourceFeedback } from './feedback'; @@ -52,9 +49,10 @@ import { evaluateSolverProof } from './evaluation'; import { solverProofIsCurrent } from './modules/evidence'; import { checkCodexProviderConnectivity } from '../runtime/codexConnectivity'; import { buildTokenBudget } from './usageBudget'; -import { selectedDeepSeekProfile } from '../runtime/deepseek'; -import { WESTLAKE_NATIVE_TEAM_UNSUPPORTED, selectedWestlakeProfile } from '../runtime/westlake'; -import { selectedSub2apiProfile } from '../runtime/sub2api'; +import { DEEPSEEK_PROVIDER } from '../runtime/deepseek'; +import { WESTLAKE_NATIVE_TEAM_UNSUPPORTED, WESTLAKE_PROVIDER } from '../runtime/westlake'; +import { SUB2API_PROVIDER } from '../runtime/sub2api'; +import { selectedProviderProfile } from '../runtime/providerProfile'; import { copyKnowledgeSnapshot } from './theoremKnowledgeStore'; import { readAuthorizedKnowledgeCatalog } from './theoremKnowledgeAuthorization'; import { ExecutionDeadline } from '../runtime/executionDeadline'; @@ -77,37 +75,43 @@ import type { SolverExplanations } from './automaticExplanations'; import { readMathAgentSkill } from '../runtime/agentSkills'; import { prepareResearchSkill, researchSkillIdentity } from './researchSkill'; import { prepareWorkerProject } from './workerProject'; +import { prepareSolverLean } from './prepareSolverLean'; import { prepareSolverRuntimeEnvironment } from './environment'; import { assertResearchHarnessCurrent, bindResearchHarness, requireCodexHarness } from '../runtime/researchHarness'; import { planMathAgentSession } from '../runtime/agentSessionPlan'; -import { SingleSolverProofHandoff } from './singleSolverProofHandoff'; -import { assertAgentTeamProcessesStopped } from './agentTeam'; -import { buildAgentTeamContributions } from './agentTeamContributions'; +import { assertProofWriterStopped } from './proofWriter'; -const runSummary = (state: SolverRunState | undefined) => { - const workers = state?.agentTeam - ? [ - { ...state, id: 'lead', role: 'lead', turns: state.usageAccounting?.startedTurns ?? 0 }, - ...state.agentTeam.workers, - ] - : undefined; +function runResultFields(stateFile: string, state: SolverRunState | undefined, clock?: ExecutionDeadline) { return { + schema: 'deepscientist.math.run.v2', + stateFile, + runId: state?.runId, + problemId: state?.problem.contract.problemId, + ...(state?.solveStartedAt && state.solveFinishedAt + ? { solveWallMs: state.solveFinishedAt - state.solveStartedAt } + : {}), + ...(clock ? { solveExecutionMs: clock.executionMs(), solveWaitingMs: clock.waitingMs() } : {}), turns: state?.turns, dispatchCounts: state?.dispatchCounts, ...(state?.originalTacticAttempt ? { originalTacticAttempt: state.originalTacticAttempt } : {}), ...(state?.verifierFailure ? { verifierFailure: state.verifierFailure } : {}), - usage: state?.teamUsage ?? state?.usage, + usage: 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, - })), + workers: + state?.agentTeam?.transport === 'codex-shared' + ? [ + { + id: 'lead', + role: 'lead', + turns: state.usageAccounting?.startedTurns ?? 0, + dispatchCounts: state.dispatchCounts, + usage: state.usage, + error: state.error, + }, + ] + : undefined, }; -}; +} export async function runSolver( args: string[], @@ -133,7 +137,7 @@ export async function runSolver( '--knowledge-base FILE attaches an immutable saved-theorem catalog. Resume requires the same catalog digest. Historical knowledge never grants proof acceptance.', ); console.log( - `New Codex runs start one Lead who can delegate up to ${DEFAULT_TEAM_AGENTS - 1} members as needed. Use --agent-team N to set the total capacity (2..8 including Lead), or --workers 1 to disable delegation. Native collaboration requires the pinned Codex team backend and a compatible provider profile.`, + `New Codex runs start one Lead who can delegate up to ${DEFAULT_TEAM_AGENTS - 1} members as needed. Use --agent-team N to set the total capacity (2..8 including Lead), or --workers 1 to disable delegation. Team members use native Codex delegation in one shared proof worktree.`, ); 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.', @@ -161,13 +165,13 @@ export async function runSolver( 'Use --codex FILE or --harness-executable FILE to select a Codex binary. Resume retains the frozen launch settings.', ); console.log( - 'Codex Lead delegates and communicates with native tools. theoremos_team handles route approval, saved-result lookup and checked proof handoffs. Configured limits are shared. Reproduce host scheduling experiments with their pinned historical revision.', + 'Codex Lead delegates and communicates with native tools. Lead assigns files to members. The host checks all original targets after the entire team stops. Reproduce host scheduling experiments with their pinned historical revision.', ); console.log( '--skill-preferred-profiles engineer,D011 optionally suggests member work roles and domain specialties from the pinned Skill to the team Lead. The Lead chooses actual assignments and may use other profiles. Omit for no preference on a new run; resume retains the saved selection.', ); console.log( - '--skill-expert-cards-file FILE freezes user-selected expert cards for a team run. Lead sees their catalogue and can select asset: in a member assignment. Resume reuses the saved cards.', + '--skill-expert-cards-file FILE freezes user-selected expert cards for a team run. Lead can use the local tool help to select relevant cards for a member assignment. Resume reuses the saved cards.', ); console.log( 'Team mode makes an early collaboration decision and exposes remaining run time and turn deadlines to every member. A finite --max-turn-seconds remains a hard ceiling; at 80% the host requests a checkpoint at the next model-request boundary, allowing the current response and tools to finish first. The overall deadline and cancellation remain hard stops; missing usage still blocks finite-budget continuation.', @@ -181,39 +185,36 @@ export async function runSolver( requireCurrentScheduler(values.scheduler!); const specified = (key: string) => args.some(arg => arg === '--' + key || arg.startsWith('--' + key + '=')); const publicRun = entryPoint !== 'internal'; - let savedConfiguration: SolverRunState | undefined; - if (values.resume && values.output) { - try { - savedConfiguration = readSolverRunState(`${path.resolve(values.output)}.runtime/state.json`); - } catch { - /* The authoritative read under the run lease reports invalid resume state. */ + const resolveConfiguration = (saved?: SolverRunState) => { + if (saved) { + assertActiveResearchState(saved); + requireCodexHarness(saved.agentHarness?.id ?? 'codex'); } - } - if (savedConfiguration) assertActiveResearchState(savedConfiguration); - const strategyValues = - publicRun && !values.resume && values['research-mode'] === undefined - ? { ...values, 'research-mode': 'skill' } - : values; - const options = resolveRunStrategy(strategyValues, savedConfiguration, specified('model'), Boolean(customModules)); - values.model = options.model; - const { coordination, researchMode, skillLoading, delegationMode, maxAgents } = options; - if (publicRun && values.workers === '1' && delegationMode === 'team') - throw new Error('--workers 1 requires a solo run. Use --agent-team N for a new team or omit --workers on resume.'); - const skillMode = researchMode === 'skill'; - const configured = configuredRuntimeModules(values.method!, values.scheduler!); - const modulePlan = - values['module-plan'] && - (researchModulePlanSchema.parse(readMathJson(values['module-plan'])) as ResearchModulePlan); - if (modulePlan) requireCurrentScheduler(modulePlan.scheduler); - const modules = modulePlan ? configurableRuntimeModules(modulePlan, coordination, 1) : (customModules ?? configured); + const strategyValues = + publicRun && !values.resume && values['research-mode'] === undefined + ? { ...values, 'research-mode': 'skill' } + : values; + const strategy = resolveRunStrategy(strategyValues, saved, specified('model'), Boolean(customModules)); + if (publicRun && values.workers === '1' && strategy.delegationMode === 'team') + throw new Error( + '--workers 1 requires a solo run. Use --agent-team N for a new team or omit --workers on resume.', + ); + const configured = configuredRuntimeModules(values.method!, values.scheduler!); + const modulePlan = + values['module-plan'] && + (researchModulePlanSchema.parse(readMathJson(values['module-plan'])) as ResearchModulePlan); + if (modulePlan) requireCurrentScheduler(modulePlan.scheduler); + const modules = modulePlan + ? configurableRuntimeModules(modulePlan, strategy.coordination, 1) + : (customModules ?? configured); + return { strategy, modules, limits: resolveRunLimits(values, strategy, Boolean(saved?.planApproval)) }; + }; + const newRunConfiguration = values.resume ? undefined : resolveConfiguration(); const required = (key: keyof typeof values): string => { const value = values[key]; if (typeof value !== 'string' || !value.trim()) throw new Error(`--${key} is required`); return value; }; - const { maxRunMs, proofTimeoutMs, preparationMs, maxTurnMs, maxTurns, evaluatorMs, tokenLimit, planApproval } = - resolveRunLimits(values, options, Boolean(savedConfiguration?.planApproval)); - let maxTotalTokens = tokenLimit; const tokenLimitSpecified = specified('max-total-tokens'); const effortSpecified = specified('effort'); const workspace = fs.realpathSync(required('workspace')); @@ -228,6 +229,9 @@ export async function runSolver( if (stat.mode & 0o077 || (process.getuid && stat.uid !== process.getuid())) throw new Error('math_state_directory_not_private'); const stateFile = path.join(directory, 'state.json'); + const requestedContinuationSource = + values['continuation-source-run'] && continuationSourceStateFile(values['continuation-source-run']); + let continuationSourceRun = requestedContinuationSource; const controller = new AbortController(); const abort = () => controller.abort(); const hostAbort = () => controller.abort(hostSignal?.reason); @@ -236,16 +240,12 @@ export async function runSolver( process.once('SIGINT', abort); process.once('SIGTERM', abort); const preparationStarted = Date.now(); + let preparationTimer = newRunConfiguration && scheduleMathTimeout(abort, newRunConfiguration.limits.preparationMs); + const cancelPreparation = () => preparationTimer?.(); let preparing = true; - let deadline = Infinity; let executionClock: ExecutionDeadline | undefined; - const cancelPreparation = scheduleMathTimeout(abort, preparationMs); let ownedState: SolverRunState | undefined; let proofEnvironment: Awaited> | undefined; - let continuationSeeding = false; - const requestedContinuationSource = - values['continuation-source-run'] && continuationSourceStateFile(values['continuation-source-run']); - let continuationSourceRun = requestedContinuationSource; let ownsRun = false; let publishedExit: number | undefined; const emit = (event: string, details = {}) => @@ -273,24 +273,42 @@ export async function runSolver( proofEnvironment = undefined; await environment?.dispose(); }; - const runWithLease = async (lease: MathLease): Promise => { + const runWithLease = async (lease: MathLease): Promise => { + let resumedState: SolverRunState | undefined; + if (values.resume) { + try { + resumedState = readSolverRunState(stateFile); + } catch (error) { + reportRejection(error); + return 1; + } + } + let configuration: ReturnType; + try { + configuration = newRunConfiguration ?? resolveConfiguration(resumedState); + } catch (configurationError) { + // Preserve thrown configuration errors after releasing the lock. + return { configurationError }; + } + const { strategy, limits, modules } = configuration; + const { coordination, researchMode, skillLoading, delegationMode, maxAgents, model } = strategy; + const { maxRunMs, proofTimeoutMs, preparationMs, maxTurnMs, maxTurns, evaluatorMs, tokenLimit, planApproval } = + limits; + const skillMode = researchMode === 'skill'; + let maxTotalTokens = tokenLimit; + const preparationDeadline = preparationStarted + preparationMs; + const timeToPrepare = preparationDeadline - Date.now(); + if (timeToPrepare <= 0) abort(); + lease.signal.throwIfAborted(); + preparationTimer ??= scheduleMathTimeout(abort, timeToPrepare); const execute = async (): Promise => { const signal = lease.signal; - const resumedState = values.resume ? readSolverRunState(stateFile) : undefined; - if (resumedState) { - assertActiveResearchState(resumedState); - requireCodexHarness(resumedState.agentHarness?.id ?? 'codex'); - } const buildFile = fs.realpathSync(required('build-manifest')); const bundleRoot = path.join(root, 'out', 'main'); - const readBuildDigest = () => { - if (autoLibrary) - return readMathBuildManifestDigest(buildFile, root, bundleRoot, undefined, 'runtime', { - expectedTextDigest: autoLibrary.expectedBuild, - }); - readMathBuildManifest(buildFile, root, bundleRoot, 'runtime'); - return mathDigest(fs.readFileSync(buildFile)); - }; + const readBuildDigest = (expectedDigest?: string) => + readMathBuildManifestDigest(buildFile, root, bundleRoot, expectedDigest, 'runtime', { + expectedTextDigest: autoLibrary?.expectedBuild, + }); const buildDigest = readBuildDigest(); const task = fs.readFileSync(required('task-file'), 'utf8'); const receiptFile = values['receipt-file'] || path.join(workspace, 'active-problem.json'); @@ -329,13 +347,18 @@ export async function runSolver( const profile = profileArgument ? fs.realpathSync(profileArgument) : process.env.CODEX_HOME || path.join(os.homedir(), '.config/deepscientist/math-sol-codex'); - const codexWestlake = selectedWestlakeProfile(profile); - // Historical runs keep the transport frozen by their existing checkpoint. - const nativeTeamRun = - delegationMode === 'team' && (!values.resume || resumedState?.agentTeam?.transport === 'native-agent-control'); + const usesBuiltInCodex = modules.M1.open === directRuntimeModules.M1.open; + const selectedProfile = selectedProviderProfile( + profile, + usesBuiltInCodex ? [DEEPSEEK_PROVIDER.id, SUB2API_PROVIDER.id, WESTLAKE_PROVIDER.id] : [WESTLAKE_PROVIDER.id], + ); + const codexWestlake = selectedProfile?.id === WESTLAKE_PROVIDER.id; + const providerProfile = usesBuiltInCodex ? selectedProfile : undefined; + const sharedTeamRun = + delegationMode === 'team' && (!values.resume || resumedState?.agentTeam?.transport === 'codex-shared'); const westlakeTeamError = WESTLAKE_NATIVE_TEAM_UNSUPPORTED + ': select a native-compatible Codex profile such as the Responses gateway.'; - if (!values.resume && codexWestlake && nativeTeamRun) throw new Error(westlakeTeamError); + if (!values.resume && codexWestlake && sharedTeamRun) throw new Error(westlakeTeamError); const preparedEnvironment = prepareSolverRuntimeEnvironment(process.env); let { environment: env, corpusFile, corpusBytes, corpus } = preparedEnvironment; const { mathTools } = preparedEnvironment; @@ -343,24 +366,15 @@ export async function runSolver( values['harness-executable'] ?? values.codex ?? resumedState?.agentHarness?.executable ?? - (nativeTeamRun - ? process.env.THEOREMOS_CODEX_BACKEND_EXECUTABLE || path.join(root, 'out/codex-backend/codex') - : process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE || 'codex'); + (process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE || 'codex'); const pinHarness = (publicRun && !values.resume && specified('codex')) || specified('harness-executable') || specified('harness-profile') || Boolean(resumedState?.agentHarness) || - nativeTeamRun; + sharedTeamRun; const agentHarness = pinHarness ? bindResearchHarness('codex', executable, profile) : undefined; const assertHarnessCurrent = agentHarness ? () => assertResearchHarnessCurrent(agentHarness) : undefined; - const sub2apiProfile = - modules.M1.open === directRuntimeModules.M1.open ? selectedSub2apiProfile(profile) : undefined; - const westlakeProfile = modules.M1.open === directRuntimeModules.M1.open ? codexWestlake : undefined; - const providerProfile = - modules.M1.open === directRuntimeModules.M1.open - ? (selectedDeepSeekProfile(profile) ?? sub2apiProfile ?? westlakeProfile) - : undefined; const knowledge = values['knowledge-base'] ? readAuthorizedKnowledgeCatalog( values['knowledge-base'], @@ -399,17 +413,17 @@ export async function runSolver( : publicRun && skillMode && !delegationMode && !specified('skill-loading'); const sessionSkill = compactSoloResearch ? undefined : loadedSkill; const plannedSession = planMathAgentSession({ - ...(sessionSkill ? { skills: [sessionSkill] } : {}), - completedOutput: new SingleSolverProofHandoff(problem, worktree, () => {}).output, + skills: sessionSkill ? [sessionSkill] : undefined, + completedOutput: !sharedTeamRun, }); const identity = { - taskDigest: mathDigest(task), + taskDigest: continuationIdentity.taskDigest, buildDigest, providerProfile: providerProfile?.profile, providerProfileDigest: providerProfile?.digest, environmentDigest: preparedEnvironment.environmentDigest, evaluatorDigest: mathDigest(values['evaluator-command'] || 'host-default'), - model: values.model!, + model, effort: resumedState && !effortSpecified ? resumedState.effort : values.effort!, methodDigest: solverMethodDigest(modules, coordination), knowledgeDigest: knowledge?.digest, @@ -421,25 +435,18 @@ export async function runSolver( const previous = result.explanations as SolverExplanations | undefined; const language = (values['explanation-language'] as 'zh' | 'en' | undefined) ?? (previous?.language === 'en' ? 'en' : 'zh'); - if (values['no-explanations']) { - if (!previous) { - result.explanations = { - status: 'disabled', - language, - directory: path.join(directory, 'explanations', language), - targets: [], - }; - try { - lease.assertOwned(); - writeMathJsonDurable(output, result); - } catch { - emit('explanation_failed', { reason: 'automatic_explanation_failed', output }); - } - } - return; - } - cancelPreparation(); + const explanationDirectory = path.join(directory, 'explanations', language); + const publish = (summary: SolverExplanations) => { + lease.assertOwned(); + result.explanations = summary; + writeMathJsonDurable(output, result); + }; try { + if (values['no-explanations']) { + if (!previous) publish({ status: 'disabled', language, directory: explanationDirectory, targets: [] }); + return; + } + cancelPreparation(); await disposeProofEnvironment(); const { generateSolverExplanations } = await import('./automaticExplanations'); await generateSolverExplanations({ @@ -459,34 +466,28 @@ export async function runSolver( env: explanationEnv, signal, onEvent: emit, - onUpdate: summary => { - lease.assertOwned(); - result.explanations = summary; - writeMathJsonDurable(output, result); - }, + onUpdate: publish, }); } catch { // The accepted result was saved first. A generation or persistence error never invalidates that proof. const failed = result.explanations as SolverExplanations | undefined; - if (!failed || failed.status === 'running') { - result.explanations = { - status: signal.aborted ? 'stopped' : 'error', - language, - directory: path.join(directory, 'explanations', language), - targets: (failed?.targets ?? []).map(target => - target.status === 'pending' || target.status === 'running' - ? { ...target, status: signal.aborted ? 'stopped' : 'error', reason: 'automatic_explanation_failed' } - : target, - ), - }; + const reason = 'automatic_explanation_failed'; + if (!values['no-explanations'] && (!failed || failed.status === 'running')) { + const status = signal.aborted ? 'stopped' : 'error'; try { - lease.assertOwned(); - writeMathJsonDurable(output, result); + publish({ + status, + language, + directory: explanationDirectory, + targets: (failed?.targets ?? []).map(target => + target.status === 'pending' || target.status === 'running' ? { ...target, status, reason } : target, + ), + }); } catch { /* Keep the already-persisted accepted proof result. */ } } - emit('explanation_failed', { reason: 'automatic_explanation_failed', output }); + emit('explanation_failed', { reason, output }); } }; const moduleConfiguration = solverModuleConfiguration(modules); @@ -510,7 +511,7 @@ export async function runSolver( canContinueSeed && state.pendingContinuationSource ? continuationSourceStateFile(state.pendingContinuationSource) : undefined; - assertAgentTeamProcessesStopped(state); + assertProofWriterStopped(state); const frozen = frozenRunConfiguration(state, { agentHarness, researchMode, @@ -569,7 +570,7 @@ export async function runSolver( return result.status === 'evaluated_passed' ? 0 : 2; } } - if (codexWestlake && nativeTeamRun) throw new Error(westlakeTeamError); + if (codexWestlake && sharedTeamRun) throw new Error(westlakeTeamError); // Older runtimes could record a new seed request on a run that was already underway. if (state.pendingContinuationSource && !continuationSourceRun) { delete state.pendingContinuationSource; @@ -601,11 +602,11 @@ export async function runSolver( ? { originalTacticsEnabled: true as const } : {}), ...(researchDelegation ? { researchDelegation } : {}), - ...(nativeTeamRun + ...(sharedTeamRun ? { agentTeam: { schema: 'theorem-os.agent-team.v1' as const, - transport: 'native-agent-control' as const, + transport: 'codex-shared' as const, workers: [], events: [], deliveries: [], @@ -627,7 +628,7 @@ export async function runSolver( tokenBudget: buildTokenBudget( maxTotalTokens, [], - westlakeProfile ? 'provider-observed-upstream-request-limit' : undefined, + usesBuiltInCodex && codexWestlake ? 'provider-observed-upstream-request-limit' : undefined, ), }; git(workspace, ['worktree', 'add', '--detach', state.worktree, problem.baseCommit]); @@ -636,20 +637,13 @@ export async function runSolver( } ownsRun = true; ownedState = state; - state.tokenBudget = buildTokenBudget( - maxTotalTokens, - [state, ...(state.agentTeam?.workers ?? [])], - state.tokenBudget?.enforcement, - ); + if (state.agentTeam?.transport === 'codex-shared') + state.agentTeam.hostLimits = { maxTurns: Number.isFinite(maxTurns) ? maxTurns : null, maxTotalTokens }; + state.tokenBudget = buildTokenBudget(maxTotalTokens, [state], state.tokenBudget?.enforcement); const save = () => { lease.assertOwned(); writeSolverRunState(stateFile, state); }; - const prepareProject = (worktree: string) => { - const project = prepareWorkerProject(worktree, state.problem); - if (sourcePackages) bindLeanPackages(project, sourcePackages); - return project; - }; const sourceProject = path.join(workspace, problem.projectRelative); const sourcePackages = resolveMathematicsLakePackagesCache(sourceProject, env); if (!sourcePackages) { @@ -666,131 +660,41 @@ export async function runSolver( throw new Error('math_lake_packages_unavailable'); } } - const project = prepareProject(state.worktree); + const project = prepareWorkerProject(state.worktree, state.problem); + if (sourcePackages) bindLeanPackages(project, sourcePackages); if (!values.resume) sourceFeedback = solverSourceFeedback(state.problem, state.worktree); if (sourceFeedback) { state.check = undefined; save(); } if (values['startup-only'] && !autoLibrary?.leanOnly) { - const connectivity = - modules.M1.open === directRuntimeModules.M1.open - ? await checkCodexProviderConnectivity({ env, signal, profile }) - : { - status: 'not-required', - diagnostics: 'The custom execution component does not use the built-in Codex provider.', - }; + const connectivity = usesBuiltInCodex + ? await checkCodexProviderConnectivity({ env, signal, profile }) + : { + status: 'not-required', + diagnostics: 'The custom execution component does not use the built-in Codex provider.', + }; writeMathJsonDurable(path.join(directory, 'provider-connectivity.json'), connectivity); if (connectivity.status === 'unavailable') { emit('preparation_failed', { workerId: 'solver', diagnostics: connectivity.diagnostics }); throw new Error('math_codex_provider_unreachable'); } } - const readiness = checkResolvedLeanToolchainReadiness({ projectRoot: project, env, timeoutMs: 180_000 }); - writeMathJsonDurable(path.join(directory, 'toolchain-readiness.json'), readiness); - if (readiness.status !== 'ready') { - emit('preparation_failed', { workerId: 'solver', diagnostics: readiness.diagnostics }); - throw new Error('math_lean_toolchain_unavailable'); - } - if (sourcePackages) { - // Model-side path overrides are regenerated after binding the frozen packages. - // Their worktree-specific paths must not invalidate the preparation cache on resume. - const overrides = path.join(project, '.lake', 'package-overrides.json'); - assertMathCanonicalPath(overrides); - fs.rmSync(overrides, { force: true }); - proofEnvironment = await prepareMathProofEnvironment(project, sourcePackages, { - env, - signal, - deadlineAt: preparationStarted + preparationMs, - cacheRoot: values['proof-environment-cache-dir'] || DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT, - onProgress: phase => emit('proof_environment', { phase }), - }); - env = { ...env, [MATH_PROOF_ENVIRONMENT_ENV]: proofEnvironment.environmentValue }; - } - const checkDependencies = async ( - workerId: string, - projectRoot: string, - timeoutMs = preparationMs - (Date.now() - preparationStarted), - ) => { - if (sourcePackages) prepareLeanDiagnosticOverrides(projectRoot); - const diagnostics = await runLeanDiagnostics({ - projectRoot, - files: [...new Set(problem.targets.map(target => target.proofPath))], - dependenciesOnly: true, - excludedFiles: problem.ownedFiles, - env, - signal, - timeoutMs, - onProgress: file => emit('dependency_check', { workerId, file }), - }); - writeMathJsonDurable( - path.join(directory, workerId === 'solver' ? 'preparation-diagnostics.json' : `preparation-${workerId}.json`), - diagnostics, - ); - if (diagnostics.exitCode !== 0 || diagnostics.timedOut) { - emit('preparation_failed', { - workerId, - timedOut: diagnostics.timedOut, - diagnostics: (diagnostics.stderr || diagnostics.stdout || 'Lean dependency check did not finish.').slice( - 0, - 2000, - ), - }); - throw new Error('math_lean_dependencies_failed'); - } - return diagnostics; - }; - const diagnostics = await checkDependencies('solver', project); - const checkSources = modules.M2.checkPreparedSources?.bind(undefined, problem.baseCommit) ?? runLeanDiagnostics; - // Library-pack modules are only advisory until Lean accepts them in this environment, without sorry. - if (problem.frozenFiles && Object.keys(problem.frozenFiles).length) { - emit('library_pack_check', { files: Object.keys(problem.frozenFiles).length }); - const library = await checkSources({ - projectRoot: project, - files: Object.keys(problem.frozenFiles), - env, - signal, - timeoutMs: preparationMs - (Date.now() - preparationStarted), - onProgress: file => emit('library_pack_check', { file }), - sharedLibraryCache: { root: DEFAULT_LEAN_LIBRARY_CACHE_ROOT, files: problem.frozenFiles }, - onSharedCache: (phase, file) => emit('library_pack_cache', { phase, ...(file ? { file } : {}) }), - }); - writeMathJsonDurable(path.join(directory, 'library-pack-diagnostics.json'), library); - const sorry = - 'messages' in library && - library.messages?.find(message => /declaration uses '?sorry'?/u.test(message.message)); - if (library.exitCode !== 0 || library.timedOut || sorry) { - emit('preparation_failed', { - workerId: 'solver', - timedOut: library.timedOut, - diagnostics: (sorry - ? `${sorry.file ?? ''} ${sorry.message}` - : library.stderr || library.stdout || 'Library-pack check did not finish.' - ).slice(0, 2000), - }); - throw new Error('math_library_pack_failed'); - } - } - // A generated statement (auto-library spec) must elaborate before any model turn tries to prove it. - if (values['check-statement']) { - const statement = await checkSources({ - projectRoot: project, - files: [...new Set(problem.targets.map(target => target.proofPath))], - env, - signal, - timeoutMs: preparationMs - (Date.now() - preparationStarted), - onProgress: file => emit('statement_check', { file }), - }); - writeMathJsonDurable(path.join(directory, 'statement-diagnostics.json'), statement); - if (statement.exitCode !== 0 || statement.timedOut) { - emit('preparation_failed', { - workerId: 'solver', - timedOut: statement.timedOut, - diagnostics: (statement.stderr || statement.stdout || 'Statement check did not finish.').slice(0, 2000), - }); - throw new Error('math_statement_check_failed'); - } - } + const preparedLean = await prepareSolverLean({ + problem, + project, + sourcePackages, + env, + signal, + deadlineAt: preparationDeadline, + directory, + cacheRoot: values['proof-environment-cache-dir'], + checkStatement: values['check-statement'], + checkPreparedSources: modules.M2.checkPreparedSources, + emit, + }); + env = preparedLean.env; + proofEnvironment = preparedLean.proofEnvironment; let corpusCreated = false; if (!corpusFile && sourcePackages && fs.existsSync(path.join(sourcePackages, 'mathlib', 'Mathlib'))) { corpusFile = path.join(project, '.lake', 'retrieval-corpus.json'); @@ -838,114 +742,82 @@ export async function runSolver( routeFindings: knowledge.base.routeFindings, }, }); - const prepareAccess = ( - workerId: string, - workerRoot: string, - workerProject: string, - workerCorpus: string | undefined, - pinnedSkill: WorkerAccess['researchSkill'], - ): WorkerAccess => { - const workerContinuation = continuation && copyContinuationSnapshot(continuation, workerProject); - assertHostProblemCurrent(); - let knowledgeFile: string | undefined; - if (knowledge) { - if (knowledge.base.libraryAuthorization) - readAuthorizedKnowledgeCatalog( - values['knowledge-base']!, - workspace, - values['receipt-file'] || path.join(workspace, 'active-problem.json'), - knowledge.digest, - ); - knowledgeFile = path.join(workerProject, '.lake', 'theorem-knowledge.json'); - copyKnowledgeSnapshot(knowledge, values['knowledge-base']!, knowledgeFile); - } - const environmentFile = path.join(directory, `environment-${workerId}.json`); - const environment = { - ...env, - DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, - DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS: workerCorpus, - }; - writeMathJsonDurable(environmentFile, projectMathematicsRuntimeEnvironment(environment), 0o400); - return { - environment: resolveMathematicsRuntimeEnvironment(environment), - corpusFile: workerCorpus, - ...(assertHarnessCurrent ? { assertHarnessCurrent } : {}), - ...(pinnedSkill ? { researchSkill: pinnedSkill } : {}), - retrievalRoot: corpus?.projectSubdirectory ? workerRoot : workerProject, - ...(mathTools ? { mathTools } : {}), - ...(installedLibrary ? { installedLibrary } : {}), - ...(libraryCatalog - ? { - libraryCatalog: { - file: path.resolve(values['library-catalog']!), - digest: libraryCatalog.identity.catalogDigest, - }, - } - : {}), - ...(workerContinuation ? { continuation: workerContinuation } : {}), - ...(problem.libraryBinding?.hostConfiguration - ? { - assertKnowledgeCurrent: () => { - if (knowledge) - readAuthorizedKnowledgeCatalog(knowledgeFile!, workspace, receiptFile, knowledge.digest); - else assertHostProblemCurrent(); - }, - } - : {}), - ...(knowledge ? { knowledgeFile, knowledgeDigest: knowledge.digest, knowledgeSnapshot } : {}), - }; - }; - let leadAccess = prepareAccess('solver', state.worktree, project, corpusFile, leadSkill); - const prepareTeamWorker = async (workerId: string, workerWorktree: string): Promise => { - signal.throwIfAborted(); - const accessId = 'team-' + workerId; - const workerProject = prepareProject(workerWorktree); - const lake = path.join(workerProject, '.lake'); - await checkDependencies(accessId, workerProject, Math.min(preparationMs, executionClock!.remainingMs())); - let workerCorpusFile: string | undefined; - if (corpusFile) { - workerCorpusFile = path.join(lake, 'retrieval-corpus.json'); - assertMathCanonicalPath(workerCorpusFile); - if (fs.existsSync(workerCorpusFile)) { - if (mathDigest(readMathText(workerCorpusFile)) !== env.DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS_SHA256) - throw new Error('math_corpus_identity_changed'); - } else fs.writeFileSync(workerCorpusFile, corpusBytes!, { mode: 0o400, flag: 'wx' }); - } - return prepareAccess(accessId, workerWorktree, workerProject, workerCorpusFile, prepareSkill(workerWorktree)); + const knowledgeFile = knowledge && path.join(project, '.lake', 'theorem-knowledge.json'); + if (knowledge && knowledgeFile) { + if (knowledge.base.libraryAuthorization) + readAuthorizedKnowledgeCatalog(values['knowledge-base']!, workspace, receiptFile, knowledge.digest); + copyKnowledgeSnapshot(knowledge, values['knowledge-base']!, knowledgeFile); + } + // Continuation seeding checks the frozen solver environment before replaying saved helpers. + const environmentFile = path.join(directory, 'environment-solver.json'); + const environment = { + ...env, + DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, + DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS: corpusFile, }; + writeMathJsonDurable(environmentFile, projectMathematicsRuntimeEnvironment(environment), 0o400); if (continuationSourceRun) { - continuationSeeding = true; - await seedSingleSolverContinuation({ - sourceRun: continuationSourceRun, - run: stateFile, - root, - buildManifest: buildFile, - buildScope: 'runtime', - signal, - lease, - preparedEnvironment: env, - timeoutMs: maxRunMs === Infinity ? Infinity : Math.max(1, preparationMs - (Date.now() - preparationStarted)), - deferChecks: values['startup-only'], - onProgress: emit, - onSeeded: seeded => { - state = ownedState = seeded; - }, - }); - continuationSeeding = false; - if (!state.continuationDigest) throw new Error('math_continuation_identity_missing'); - continuation = readContinuationSnapshot( - path.join(directory, 'continuation.json'), - state.continuationDigest, - continuationIdentity, - ); - leadAccess = prepareAccess('solver', state.worktree, project, corpusFile, leadSkill); + try { + await seedSingleSolverContinuation({ + sourceRun: continuationSourceRun, + run: stateFile, + root, + buildManifest: buildFile, + buildScope: 'runtime', + signal, + lease, + preparedEnvironment: env, + timeoutMs: maxRunMs === Infinity ? Infinity : Math.max(1, preparationDeadline - Date.now()), + deferChecks: values['startup-only'], + onProgress: emit, + onSeeded: (seeded, snapshot) => { + state = ownedState = seeded; + continuation = snapshot; + }, + }); + } catch (error) { + // The seed can save resumable progress before handing over the new state. + ownedState = readSolverRunState(stateFile); + throw error; + } } + const worktreeContinuation = continuation && copyContinuationSnapshot(continuation, project); + const leadAccess: WorkerAccess = { + environment: resolveMathematicsRuntimeEnvironment(environment), + corpusFile, + ...(assertHarnessCurrent ? { assertHarnessCurrent } : {}), + ...(leadSkill ? { researchSkill: leadSkill } : {}), + retrievalRoot, + ...(mathTools ? { mathTools } : {}), + ...(installedLibrary ? { installedLibrary } : {}), + ...(libraryCatalog + ? { + libraryCatalog: { + file: path.resolve(values['library-catalog']!), + digest: libraryCatalog.identity.catalogDigest, + }, + } + : {}), + ...(worktreeContinuation ? { continuation: worktreeContinuation } : {}), + ...(problem.libraryBinding?.hostConfiguration + ? { + assertKnowledgeCurrent: () => { + if (knowledge) readAuthorizedKnowledgeCatalog(knowledgeFile!, workspace, receiptFile, knowledge.digest); + else assertHostProblemCurrent(); + }, + } + : {}), + ...(knowledge ? { knowledgeFile, knowledgeDigest: knowledge.digest, knowledgeSnapshot } : {}), + }; emit('ready', { runId: state.runId, worktree: state.worktree, workers: [{ id: 'solver', role: 'lead', worktree: state.worktree, ownedFiles: state.problem.ownedFiles }], }); - emit('preparation_finished', { durationMs: Date.now() - preparationStarted, dependencies: diagnostics.phases }); + emit('preparation_finished', { + durationMs: Date.now() - preparationStarted, + dependencies: preparedLean.dependencies, + }); if (values['startup-only']) { writeMathJsonDurable(output, { schema: 'deepscientist.math.run.v2', @@ -964,16 +836,16 @@ export async function runSolver( state.solveStartedAt = Date.now(); state.solveFinishedAt = undefined; state.solveWaitingMs = 0; - deadline = state.solveStartedAt + maxRunMs; - executionClock = new ExecutionDeadline(maxRunMs, abort); + const deadline = state.solveStartedAt + maxRunMs; + const clock = (executionClock = new ExecutionDeadline(maxRunMs, abort)); const executionBudget = { - remainingMs: () => executionClock!.remainingMs(), + remainingMs: () => clock.remainingMs(), setWaiting: (waiting: boolean) => { - const previous = executionClock!.waiting; - executionClock!.setWaiting(waiting); - state.solveWaitingMs = executionClock!.waitingMs(); - if (previous !== executionClock!.waiting) - emit(executionClock!.waiting ? 'plan_approval_wait_started' : 'plan_approval_wait_ended'); + const previous = clock.waiting; + clock.setWaiting(waiting); + state.solveWaitingMs = clock.waitingMs(); + if (previous !== clock.waiting) + emit(clock.waiting ? 'plan_approval_wait_started' : 'plan_approval_wait_ended'); }, }; emit('solve_started', { budgetMs: maxRunMs, maxTurnMs }); @@ -1003,26 +875,23 @@ export async function runSolver( maxTurnMs, maxTotalTokens, proofTimeoutMs, - prepareTeamWorker, save, emit, }), ); - executionClock.stop(); - state.solveWaitingMs = executionClock.waitingMs(); + clock.stop(); + state.solveWaitingMs = clock.waitingMs(); state.solveFinishedAt = Date.now(); let evaluation: Record = { status: 'skipped', reason: 'proof_incomplete' }; if (winner?.check.passed) { state.phase = 'evaluating'; save(); - if (readBuildDigest() !== buildDigest) throw new Error('math_build_manifest_changed'); + readBuildDigest(buildDigest); const evaluationStarted = Date.now(); emit('evaluation_started', { workerId: state.winningWorker ?? 'solver' }); evaluation = await evaluateSolverProof(state.problem, winner.check, env, signal, { command: values['evaluator-command'], timeoutMs: evaluatorMs, - teamContributions: - state.agentTeam?.transport === 'native-agent-control' && state.agentTeam.deliveries.length > 0, }); emit('evaluation_finished', { status: evaluation.status, durationMs: Date.now() - evaluationStarted }); } @@ -1034,25 +903,15 @@ export async function runSolver( limited: Boolean(state.tokenBudget?.reason), }); const result = { - schema: 'deepscientist.math.run.v2', - runId: state.runId, - problemId: state.problem.contract.problemId, + ...runResultFields(stateFile, state, clock), status, run_outcome: status, solution_commit: state.check?.passed ? state.check.commit : null, solver_ready_receipt_valid: state.check?.passed === true, completion_signal_valid: evaluation.status === 'passed', evaluator: evaluation, - ...runSummary(state), - ...(state.agentTeam?.transport === 'native-agent-control' - ? { teamContributions: buildAgentTeamContributions(state, evaluation) } - : {}), ...(status === 'runtime_error' && typeof evaluation.reason === 'string' ? { reason: evaluation.reason } : {}), ...(status === 'limit_reached' && state.tokenBudget?.reason ? { reason: state.tokenBudget.reason } : {}), - solveWallMs: state.solveFinishedAt - state.solveStartedAt, - solveExecutionMs: executionClock.executionMs(), - solveWaitingMs: state.solveWaitingMs, - stateFile, winningWorker: state.winningWorker, }; writeMathJsonDurable(output, result); @@ -1080,63 +939,39 @@ export async function runSolver( const checkpoint = error instanceof VerificationCheckpointError; const libraryRequest = error instanceof LibraryInstallationRequested ? error : undefined; executionClock?.stop(); - const status = - controller.signal.aborted || checkpoint - ? 'limit_reached' - : libraryRequest - ? 'library_requested' - : 'runtime_error'; - // Initialization owns durable progress before its final in-memory handoff. - if (continuationSeeding) ownedState = readSolverRunState(stateFile); + const stopped = controller.signal.aborted; + const limited = stopped || checkpoint; + const status = limited ? 'limit_reached' : libraryRequest ? 'library_requested' : 'runtime_error'; + const errorReason = error instanceof Error ? error.message : 'math_runtime_error'; if (ownedState) { // A zero-turn continuation can retry any preparation step, including // snapshot distribution and startup-only output after the seed handoff. if (!(preparing && continuationSourceRun && ownedState.phase === 'prepared')) ownedState.phase = 'finished'; if (ownedState.solveStartedAt && !ownedState.solveFinishedAt) ownedState.solveFinishedAt = Date.now(); if (executionClock) ownedState.solveWaitingMs = executionClock.waitingMs(); - ownedState.error = - controller.signal.aborted || checkpoint || libraryRequest - ? undefined - : error instanceof Error - ? error.message - : 'math_runtime_error'; + ownedState.error = status === 'runtime_error' ? errorReason : undefined; const verification = verifierFailureDiagnostic(error); if (verification) ownedState.verifierFailure = verification; writeSolverRunState(stateFile, ownedState); } writeMathJsonDurable(output, { - schema: 'deepscientist.math.run.v2', + ...runResultFields(stateFile, ownedState, executionClock), status, run_outcome: status, - reason: controller.signal.aborted - ? preparing - ? 'math_preparation_stopped' - : 'math_run_stopped' - : error instanceof Error - ? error.message - : 'math_runtime_error', - runId: ownedState?.runId, - problemId: ownedState?.problem.contract.problemId, - ...runSummary(ownedState), - ...(ownedState?.solveStartedAt && ownedState.solveFinishedAt - ? { solveWallMs: ownedState.solveFinishedAt - ownedState.solveStartedAt } - : {}), - ...(executionClock - ? { solveExecutionMs: executionClock.executionMs(), solveWaitingMs: executionClock.waitingMs() } - : {}), + reason: stopped ? (preparing ? 'math_preparation_stopped' : 'math_run_stopped') : errorReason, ...(libraryRequest ? { libraryRequest: { request: libraryRequest.request, worktree: libraryRequest.worktree } } : {}), evaluator: { status: 'skipped' }, - stateFile, }); - publishedExit = controller.signal.aborted || checkpoint ? 4 : 1; + publishedExit = limited ? 4 : 1; emit('finished', { status, output, ...(error instanceof MathGitError ? { git: error.diagnostic } : {}) }); return publishedExit; } }; + let outcome: Awaited>; try { - return await withMathRuntimeLease( + outcome = await withMathRuntimeLease( { lockPath: path.join(directory, 'run.lock'), flockExecutable: '/usr/bin/flock', @@ -1157,4 +992,6 @@ export async function runSolver( process.removeListener('SIGINT', abort); process.removeListener('SIGTERM', abort); } + if (typeof outcome === 'number') return outcome; + throw outcome.configurationError; } diff --git a/src/solver/singleContinuationSeed.ts b/src/solver/singleContinuationSeed.ts index ace38d89..95092bf1 100644 --- a/src/solver/singleContinuationSeed.ts +++ b/src/solver/singleContinuationSeed.ts @@ -749,7 +749,7 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti if (options.deferChecks && source.declarations.length) { report.stage = 'awaiting-checks'; saveReport(); - options.onSeeded?.(state, []); + options.onSeeded?.(state, snapshot); return report; } if (source.declarations.length) { @@ -757,37 +757,34 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti assertMathCanonicalPath(environmentFile); if ((fs.lstatSync(environmentFile).mode & 0o777) !== 0o400) throw new Error('math_continuation_seed_environment_not_frozen'); - const staticEnv = { - ...(options.preparedEnvironment ?? - resolveMathematicsRuntimeEnvironment({ DEEPSCIENTIST_MATH_ENV_FILE: environmentFile })), - }; - if (!options.preparedEnvironment) { - delete staticEnv[MATH_PROOF_ENVIRONMENT_ENV]; - delete staticEnv[MATH_PROOF_ENVIRONMENT_SANDBOX_ENV]; - } - const project = path.join(state.worktree, state.problem.projectRelative), - packages = resolveMathematicsLakePackagesCache(project, staticEnv); - if (packages) bindLeanPackages(project, packages); - else { - const manifestFile = path.join(project, 'lake-manifest.json'); - const manifest = fs.existsSync(manifestFile) - ? (readMathJson(manifestFile) as { packages?: unknown }) - : undefined; - if (Array.isArray(manifest?.packages) && manifest.packages.length) - throw new Error('math_lake_packages_unavailable'); - } const timeoutMs = options.timeoutMs ?? Infinity; - if (packages && !options.preparedEnvironment) - proofEnvironment = await prepareMathProofEnvironment(project, packages, { - env: staticEnv, - signal: lease.signal, - deadlineAt: Number.isFinite(timeoutMs) ? Date.now() + timeoutMs : undefined, - cacheRoot: DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT, - onProgress: phase => emit('continuation_seed_proof_environment', { phase }), - }); - const env = proofEnvironment - ? { ...staticEnv, [MATH_PROOF_ENVIRONMENT_ENV]: proofEnvironment.environmentValue } - : staticEnv; + let env = options.preparedEnvironment; + if (!env) { + // The standalone seed command opens its own environment from the frozen run. + env = resolveMathematicsRuntimeEnvironment({ DEEPSCIENTIST_MATH_ENV_FILE: environmentFile }); + delete env[MATH_PROOF_ENVIRONMENT_ENV]; + delete env[MATH_PROOF_ENVIRONMENT_SANDBOX_ENV]; + const project = path.join(state.worktree, state.problem.projectRelative); + const packages = resolveMathematicsLakePackagesCache(project, env); + if (packages) { + bindLeanPackages(project, packages); + proofEnvironment = await prepareMathProofEnvironment(project, packages, { + env, + signal: lease.signal, + deadlineAt: Number.isFinite(timeoutMs) ? Date.now() + timeoutMs : undefined, + cacheRoot: DEFAULT_MATH_PROOF_ENVIRONMENT_CACHE_ROOT, + onProgress: phase => emit('continuation_seed_proof_environment', { phase }), + }); + env = { ...env, [MATH_PROOF_ENVIRONMENT_ENV]: proofEnvironment.environmentValue }; + } else { + const manifestFile = path.join(project, 'lake-manifest.json'); + const manifest = fs.existsSync(manifestFile) + ? (readMathJson(manifestFile) as { packages?: unknown }) + : undefined; + if (Array.isArray(manifest?.packages) && manifest.packages.length) + throw new Error('math_lake_packages_unavailable'); + } + } report.stage = 'checking'; saveReport(); const assertWriterStopped = () => { @@ -864,7 +861,7 @@ export async function seedSingleSolverContinuation(options: ContinuationSeedOpti saveReport(); delete state.pendingContinuationSource; writeSolverRunState(stateFile, state); - options.onSeeded?.(state, []); + options.onSeeded?.(state, snapshot); return report; } catch (error) { report.stage = 'interrupted'; diff --git a/src/solver/skillProofLifecycle.ts b/src/solver/skillProofLifecycle.ts index c703efab..d4989947 100644 --- a/src/solver/skillProofLifecycle.ts +++ b/src/solver/skillProofLifecycle.ts @@ -51,8 +51,8 @@ export function createSkillProofLifecycle(input: { signal: AbortSignal; proofTimeoutMs?: number; writerStopped: () => boolean; + checkHelpers?: boolean; sourceFeedback: () => string | undefined; - exclusiveCheck: (check: () => Promise) => Promise; checkWhole: (candidate?: ResearchCandidate) => Promise; save: () => void; emit: (event: string, details?: Record) => void; @@ -100,7 +100,7 @@ export function createSkillProofLifecycle(input: { assertMathAgentSkillsCurrent([skill]); setPhase('checking'); try { - await input.exclusiveCheck(() => input.checkWhole(candidate)); + await input.checkWhole(candidate); // Acceptance deliberately aborts the research loop; its pending cleanup must still finish. state.pendingProofCheck = undefined; } finally { @@ -147,28 +147,23 @@ export function createSkillProofLifecycle(input: { try { let artifacts: Awaited>; try { - // A Lead may have nothing of its own to publish while teammates work. - const submission = readDeclarationSubmission(worktree, { - allowEmpty: state.researchDelegation?.mode === 'team', - }); + const submission = readDeclarationSubmission(worktree); if (!submission) { consumed = true; return; } - artifacts = await input.exclusiveCheck(() => - checkDeclarationArtifacts({ - state, - worktree, - commit, - declarations: submission.declarations, - env: environment, - signal, - timeoutMs: input.proofTimeoutMs, - assertWriterStopped: () => { - if (!input.writerStopped()) throw new Error('math_writer_stop_unconfirmed'); - }, - }), - ); + artifacts = await checkDeclarationArtifacts({ + state, + worktree, + commit, + declarations: submission.declarations, + env: environment, + signal, + timeoutMs: input.proofTimeoutMs, + assertWriterStopped: () => { + if (!input.writerStopped()) throw new Error('math_writer_stop_unconfirmed'); + }, + }); } catch (error) { signal.throwIfAborted(); if (error instanceof VerificationCheckpointError) throw error; @@ -243,7 +238,7 @@ export function createSkillProofLifecycle(input: { if (wholeProofReady) rememberWholeProof(commit); // With no declaration submission, journal the proof check and clear the freeze in one write. // Declaration processing journals both checkpoints before it starts its own check. - await checkDeclarations(commit); + if (input.checkHelpers !== false) await checkDeclarations(commit); state.pendingResearchFreeze = undefined; save(); return { commit, wholeProofReady }; diff --git a/src/solver/skillResearchContext.ts b/src/solver/skillResearchContext.ts index d73154c5..0a53c413 100644 --- a/src/solver/skillResearchContext.ts +++ b/src/solver/skillResearchContext.ts @@ -12,9 +12,7 @@ import type { ContextAccess, ContextBundle, ResearchDispatchOptions } from './mo import type { SolverProblem } from './problem'; import { materializeResearchToolHelp } from './researchToolHelp'; import { buildResearchToolGuide, researchToolCommand } from './researchToolGuide'; -import { agentTeamInstructions, agentTeamWorkerDeliveryHelp, agentTeamWorkerSection } from './agentTeamContext'; -import { agentTeamDispatchBudget, agentTeamDispatchTask, agentTeamRecentEvents } from './agentTeamViews'; -import { agentTeamProfileSection, eligibleAgentTeamProfiles, resolveAgentTeamLeadProfile } from './agentTeamProfiles'; +import { eligibleAgentTeamProfiles } from './agentTeamProfiles'; /** Leave the last fifth of a bounded team turn for request settlement and handoff. */ export function teamTurnTiming(maxTurnMs: number): Pick { @@ -57,37 +55,6 @@ export function skillResearchContinuationSection( }; } -export function agentTeamContextSection(state: Readonly): ContextSection { - const team = state.agentTeam; - return { - id: 'agent-team', - kind: 'feedback', - text: - 'Team observations (advisory; receive updates through native messages):\n' + - JSON.stringify({ - workers: team?.workers - .filter(worker => worker.status !== 'stopped') - .map(worker => { - const current = - worker.tasks.find(task => task.status === 'running') ?? - worker.tasks.find(task => task.status === 'queued') ?? - worker.tasks.findLast(task => task.status === 'paused'); - return { - id: worker.id, - nativePath: worker.native?.agentPath, - status: worker.status, - activity: worker.activity, - task: current && agentTeamDispatchTask(current), - }; - }), - budget: agentTeamDispatchBudget(state), - recentEvents: agentTeamRecentEvents(team, 'lead'), - inbox: - 'Native messages carry addressed updates. Use route_summary for routes and deliveries, history for prior tasks, and inspect or inspect-research for saved evidence.', - }), - }; -} - /** Stable host contracts and current facts; research methods live in the pinned skill. */ export function prepareSkillResearchContext( problem: SolverProblem, @@ -108,18 +75,9 @@ export function prepareSkillResearchContext( throw new Error('math_knowledge_identity_changed'); } else if (state.knowledgeDigest) throw new Error('math_knowledge_identity_missing'); const delegation = state.researchDelegation; - const team = delegation?.mode === 'team'; - const soloWorkspace = state.researchSkillWorkflow === 'full' && !team; - const { help, leanCheckCommand } = buildResearchToolGuide( - problem, - access, - state.environmentDigest, - team, - soloWorkspace, - ); + const sharedTeam = state.agentTeam?.transport === 'codex-shared'; + const { help, leanCheckCommand } = buildResearchToolGuide(problem, access, state.environmentDigest, !sharedTeam); const project = path.join(access.worktree, problem.projectRelative); - const teamWorker = team && access.teamRole?.role === 'worker'; - if (teamWorker && !access.teamAssignment) throw new Error('math_team_assignment_missing'); const mathGuide = access.mathTools && mathToolGuide(access.mathTools, access.worktree); const toolSummary = mathGuide ? help.section('math-tools', mathGuide.detail, mathGuide.summary) : ''; const ownDelivery = @@ -140,50 +98,46 @@ export function prepareSkillResearchContext( help.section('research-methods', 'Optional research references: ' + path.relative(access.worktree, skill.path), ''); 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, + sharedTeam + ? 'Work in the shared checkout. Save changes in your assigned files, run Lean on them, and tell Lead what is ready. Lead waits for members to finish and returns with the complete proof for the host to check.' + : ownDelivery, '', ); + const cards = delegation?.mode === 'team' ? delegation.personalExperts?.cards : undefined; + if (sharedTeam && cards?.length) + help.section( + 'User expert cards', + cards + .map(card => `### asset:${card.assetId} — ${card.name}\n\n${card.summary}\n\n${card.knowledge}`) + .join('\n\n'), + '', + ); materializeResearchToolHelp({ toolHelp: help.build() }, access.worktree); const editable = problem.ownedFiles.filter(file => !Object.hasOwn(problem.frozenFiles ?? {}, file)); // Stable instructions survive both the full M4 wrapper and same-thread continuations. - // Coordinator identity comes from the host, never from an assignment's Profiles line. - const leadProfile = team && !teamWorker ? resolveAgentTeamLeadProfile(skill).section : undefined; - const cards = team ? delegation.personalExperts?.cards : undefined; - const cardCatalogue = - !teamWorker && cards?.length - ? 'User expert cards: select a relevant ID with Profiles:. Only its assigned member receives the card text. ' + - JSON.stringify( - cards.map(({ assetId, name, version, summary }) => ({ id: 'asset:' + assetId, name, version, summary })), - ) + - '\n\n' - : ''; - const preferred = team && !teamWorker ? delegation.preferredProfiles : undefined; + const cardCatalogue = cards?.length + ? 'Read the User expert cards section of .scratch/theoremos-help.md when selecting expertise. Include the relevant card reference and guidance in the assignment.\n\n' + : ''; + const preferred = delegation?.mode === 'team' ? delegation.preferredProfiles : undefined; const preferenceInstruction = preferred?.length ? 'User-preferred member profiles: ' + eligibleAgentTeamProfiles(path.dirname(skill.path)) .filter(profile => preferred.includes(profile.id)) .map(profile => profile.id + ' (' + profile.name + ')') .join(', ') + - '. ' + - 'Select these or other relevant catalogue IDs with Profiles:.\n\n' + '. Include the selected expertise and relevant Skill reference in member assignments.\n\n' : ''; const instructions = [ - teamWorker - ? 'Research the current Lead assignment. The frozen original problem supplies background and source constraints; the assignment defines the result you own.' - : 'Prove the frozen original Lean targets.', - team && agentTeamInstructions(access.teamRole ?? { id: 'lead', role: 'lead' }, delegation.maxAgents), - leadProfile?.text, + 'Prove the frozen original Lean targets.', + sharedTeam && + 'The team shares this Lean checkout. Lead assigns an exclusive writer for each editable file, including RESEARCH.md, and uses native Codex tools to assign work and collect results. ' + + 'Members may read all sources and edit only their assigned files. Use a unique scratch file for each probe. If only one proof file is available, assign it to one writer and have other members investigate or review. ' + + 'Check your changes locally with Lean, then message Lead with the files, findings and remaining gaps. Leave changes in the shared checkout. Do not commit, reset or merge. ' + + 'Lead waits for all members to finish or interrupts them before returning. Only the host independently accepts the original targets after the team has stopped. ' + + 'These instructions replace the pinned Skill’s isolated-workspace, submit and adopt workflow. Use that Skill for mathematical research and Lean guidance.', preferenceInstruction, cardCatalogue, - soloWorkspace + !sharedTeam ? 'Your shell starts in the worktree root. Edit these paths: ' + JSON.stringify(editable.map(file => path.join(problem.projectRelative, file))) + '.' @@ -196,9 +150,12 @@ export function prepareSkillResearchContext( 'Proofs must be free of sorry, admit, native_decide, unsafe and new axioms. Work independently of external candidate solutions. Leave configuration, the Skill, host help and receipts intact.', leanCheckCommand && 'Check a first attempt early and use Lean’s goals and errors to revise it:\n' + leanCheckCommand, - `For a probe, save ${JSON.stringify(path.join(project, '.scratch/tmp/Probe.lean'))} and check it with only --file '.scratch/tmp/Probe.lean'.`, - 'Save progress in worktree-root RESEARCH.md before returning. The host confirms writer shutdown before checking saved sources. Only independent checks of all original targets can accept the proof.', - !teamWorker && 'When all original targets compile without proof holes, return for independent verification.', + sharedTeam + ? 'For a probe, choose a unique .scratch/tmp/*.lean path in the Lean project and pass that project-relative path to --file.' + : `For a probe, save ${JSON.stringify(path.join(project, '.scratch/tmp/Probe.lean'))} and check it with only --file '.scratch/tmp/Probe.lean'.`, + !sharedTeam && + 'Save progress in worktree-root RESEARCH.md before returning. The host confirms writer shutdown before checking saved sources. Only independent checks of all original targets can accept the proof.', + 'When all original targets compile without proof holes, return for independent verification.', state.compactSoloResearch ? 'Find other tools, delivery formats and optional research guidance in .scratch/theoremos-help.md.' : 'Use the pinned theoremos-research Skill for research methods. Find tools and delivery formats in .scratch/theoremos-help.md.', @@ -210,17 +167,15 @@ export function prepareSkillResearchContext( const mandatory: ContextSection[] = []; const feedback = [ access.sourceFeedback, - !teamWorker && state.check && !state.check.passed + 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 }); - const teamObservation = team && !teamWorker ? agentTeamContextSection(state) : undefined; - if (teamObservation) mandatory.push(teamObservation); const declarationFeedback = path.join(access.worktree, '.scratch/declaration-feedback.json'); - const hasDeclarationFeedback = !teamWorker && fs.existsSync(declarationFeedback); + const hasDeclarationFeedback = !sharedTeam && fs.existsSync(declarationFeedback); if (hasDeclarationFeedback) mandatory.push({ id: 'declaration-feedback', @@ -240,20 +195,11 @@ export function prepareSkillResearchContext( kind: 'sources', text: 'Read current Lean sources and worktree-root RESEARCH.md as needed to continue saved work.', }); - const workerContext = teamWorker - ? agentTeamWorkerSection(state, access.teamRole!, access.teamAssignment!) - : undefined; - const workerSections = workerContext - ? [workerContext.section, agentTeamProfileSection(skill, access.teamAssignment!.message, cards)] - : []; return { instructions, mandatory, - teamObservation, hasDeclarationFeedback, continuation, - workerContext, - workerSections, }; } @@ -261,12 +207,8 @@ export function buildSkillResearchContext( problem: SolverProblem, state: Readonly, access: ContextAccess & { researchSkill: MathAgentSkill }, -): ContextBundle & { inboxThrough?: number; inboxPreviewThrough?: number } { - const { instructions, mandatory, continuation, workerContext, workerSections } = prepareSkillResearchContext( - problem, - state, - access, - ); +): ContextBundle { + const { instructions, mandatory, continuation } = prepareSkillResearchContext(problem, state, access); const attachments = continuation && continuationContextSection(continuation, researchToolCommand(access.root, access.tools), problem.projectRelative); @@ -274,7 +216,6 @@ export function buildSkillResearchContext( id: 'original-problem', kind: 'problem', text: - (workerContext ? 'Frozen original problem (background for your current Lead assignment):\n' : '') + access.taskText + '\n\n' + JSON.stringify({ @@ -295,7 +236,6 @@ export function buildSkillResearchContext( compileContextSections({ instructions, mandatory: [ - ...workerSections, ...executionLimitsSections(access.executionLimits), options.continuation ? skillResearchContinuationSection(problem, state) : originalProblem, ...mandatory, @@ -321,8 +261,6 @@ export function buildSkillResearchContext( : options.continuation ? continued : full, - inboxThrough: workerContext?.inboxThrough, - inboxPreviewThrough: workerContext?.inboxPreviewThrough, scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest }, }; diff --git a/src/solver/teamMemberSchedule.ts b/src/solver/teamMemberSchedule.ts deleted file mode 100644 index 285c8220..00000000 --- a/src/solver/teamMemberSchedule.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { nativeProcess } from '../math/nativeProcess'; -import type { TokenBudget } from './usageBudget'; - -export type TeamMemberInputs = { - stopped: boolean; - tasks: string[]; - budget: TokenBudget['status']; - turnsLeft: boolean; - timeLeft: boolean; -}; -export type TeamMemberStep = - { action: 'stop' } | { action: 'dispatch'; index: number } | { action: 'pause'; index: number; reason: string }; - -export function nextTeamMember(input: TeamMemberInputs): TeamMemberStep { - if (nativeProcess) return nativeProcess.nextTeamMember(input); - const index = input.tasks.indexOf('queued'); - if (input.stopped || index < 0) return { action: 'stop' }; - if (input.budget !== 'available' && input.budget !== 'unlimited') - return { - action: 'pause', - index, - reason: input.budget === 'usage-unavailable' ? 'math_model_usage_unavailable' : 'math_total_token_limit', - }; - if (!input.turnsLeft) return { action: 'pause', index, reason: 'math_team_total_turn_limit' }; - return input.timeLeft ? { action: 'dispatch', index } : { action: 'stop' }; -} diff --git a/tests/agentTeamContext.test.ts b/tests/agentTeamContext.test.ts deleted file mode 100644 index a08a80f7..00000000 --- a/tests/agentTeamContext.test.ts +++ /dev/null @@ -1,196 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import type { SolverRunState } from '../src/solver/archive'; -import { agentTeamWorkerSection } from '../src/solver/agentTeamContext'; -import { agentTeamStateSchema, type AgentTeamState } from '../src/solver/agentTeamState'; -import type { ContextSection } from '../src/solver/contextCompiler'; -import { agentTeamContextSection } from '../src/solver/skillResearchContext'; - -const sourceCommit = 'a'.repeat(40), - savedCommit = 'b'.repeat(40); -const artifactId = 'c'.repeat(64), - hostPath = '/host-private/agent-team/research/artifact.json'; -const assignment = { taskId: 'current', message: 'Check the remaining hypothesis.', sourceCommit }; - -function fixture(overrides: Partial = {}): SolverRunState { - const agentTeam = agentTeamStateSchema.parse({ - schema: 'theorem-os.agent-team.v1', - workers: [ - { - id: 'child', - role: 'researcher', - worktree: '/isolated/child', - seedCommit: sourceCommit, - status: 'running', - phase: 'running', - turns: 2, - cursor: 0, - tasks: [ - { - id: 'prior', - message: 'Inspect the exceptional case.', - status: 'completed', - summary: 'A conditional reduction.', - }, - { id: assignment.taskId, message: assignment.message, status: 'running', seedCommit: sourceCommit }, - ], - }, - ], - events: [], - deliveries: [], - adoptions: [], - operations: [], - ...overrides, - }); - return { agentTeam } as SolverRunState; -} - -function data(section: ContextSection) { - return JSON.parse(section.text.slice(section.text.indexOf('\n') + 1)); -} - -function childData(state: SolverRunState) { - return data(agentTeamWorkerSection(state, { id: 'child', role: 'worker' }, assignment).section); -} - -describe('current team research context', () => { - it('leaves historical research and unrelated artifacts out of dispatch while preserving addressed notices', () => { - const researchState = { - revision: 3, - summary: 'Use the reduction only under its compactness hypothesis.', - publishedAt: 1234, - }; - const state = fixture({ - researchState, - researchArtifacts: [{ id: artifactId, agentId: 'peer', taskId: 'survey', commit: savedCommit, path: hostPath }], - events: [ - { - sequence: 1, - from: 'lead', - to: 'child', - kind: 'research-updated', - at: 1234, - text: researchState.summary, - researchRevision: 3, - }, - ], - }); - const archived = structuredClone(state.agentTeam); - const lead = data(agentTeamContextSection(state)), - child = childData(state); - for (const context of [lead, child]) { - expect(context).not.toHaveProperty('researchState'); - expect(context).not.toHaveProperty('researchArtifacts'); - expect(JSON.stringify(context).includes(hostPath)).toBe(false); - } - expect(child.inbox.events).toEqual(state.agentTeam!.events); - expect(child.inbox.through).toBe(1); - expect(state.agentTeam).toEqual(archived); - expect(Object.hasOwn(state.agentTeam!.researchState!, 'advisory')).toBe(false); - }); - - it('carries the most recent cancelled task and its saved research into the replacement assignment', () => { - const state = fixture(), - worker = state.agentTeam!.workers[0]!; - const cancelRequested = { - at: 2000, - reason: 'The previous interface needs a different hypothesis.', - replacementTaskId: 'current', - }; - worker.tasks.splice(1, 0, { - id: 'cancelled-task', - message: 'Prove the old interface.', - status: 'cancelled', - summary: 'The boundary case remains unresolved.', - sourceCommit: savedCommit, - researchArtifactId: artifactId, - cancelRequested, - }); - const child = childData(state), - lead = data(agentTeamContextSection(state)); - - expect(child.previousTask).toMatchObject({ - id: 'cancelled-task', - status: 'cancelled', - summary: 'The boundary case remains unresolved.', - sourceCommit: savedCommit, - researchArtifactId: artifactId, - cancelRequested, - }); - expect(child.taskId).toBe('current'); - expect(child.sourceCommit).toBe(sourceCommit); - expect(child.deliveryBaseCommit).toBe(sourceCommit); - expect(lead.workers[0].task).toMatchObject({ id: 'current', status: 'running' }); - expect(JSON.stringify(lead)).not.toContain('cancelled-task'); - }); - - it('makes an in-flight cancellation visible without treating the current task as stopped', () => { - const state = fixture(), - current = state.agentTeam!.workers[0]!.tasks.at(-1)!; - current.cancelRequested = { at: 2500, reason: 'A decisive counterexample changed the route.' }; - const child = childData(state), - lead = data(agentTeamContextSection(state)); - - expect(child.cancelRequested).toEqual(current.cancelRequested); - expect(child.taskId).toBe(current.id); - expect(lead.workers[0].task).toMatchObject({ - id: current.id, - status: 'running', - cancelRequested: current.cancelRequested, - }); - expect(current.status).toBe('running'); - }); - - it('shows the live route when an older task is still paused', () => { - const state = fixture(), - worker = state.agentTeam!.workers[0]!; - worker.tasks[0]!.status = 'paused'; - const lead = data(agentTeamContextSection(state)); - expect(lead.workers[0].task).toMatchObject({ id: 'current', status: 'running' }); - }); - - it('reads historical team records without inventing a shared revision, artifact or completed-source reference', () => { - const original = fixture(); - const state = { - agentTeam: agentTeamStateSchema.parse(JSON.parse(JSON.stringify(original.agentTeam))), - } as SolverRunState; - const lead = data(agentTeamContextSection(state)), - child = childData(state); - - for (const context of [lead, child]) { - expect(Object.hasOwn(context, 'researchState')).toBe(false); - expect(context).not.toHaveProperty('researchArtifacts'); - } - expect(child.previousTask).toMatchObject({ id: 'prior', status: 'completed', summary: 'A conditional reduction.' }); - expect(Object.hasOwn(child.previousTask, 'sourceCommit')).toBe(false); - expect(Object.hasOwn(child.previousTask, 'researchArtifactId')).toBe(false); - expect(child.inbox).toMatchObject({ after: 0, through: 0, events: [] }); - }); - - it('echoes only Lead notices without a current native queue owner', () => { - const events = ['accepted', 'uncertain', 'queued'].map((text, index) => ({ - sequence: index + 1, - from: 'child', - to: 'lead', - kind: 'message' as const, - at: index, - text, - })); - const state = fixture({ - events, - nativeControl: { - sessionId: 'session', - rootThreadId: 'root', - sequence: events.length, - mailbox: events.map(({ sequence, text }) => ({ - id: String(sequence), - threadId: 'root', - author: '/root/child', - recipient: '/root', - status: text as 'accepted' | 'uncertain' | 'queued', - hostEventSequence: sequence, - })), - }, - }); - expect(data(agentTeamContextSection(state)).recentEvents).toEqual(events.slice(1)); - }); -}); diff --git a/tests/agentTeamContextContract.test.ts b/tests/agentTeamContextContract.test.ts deleted file mode 100644 index d8e40191..00000000 --- a/tests/agentTeamContextContract.test.ts +++ /dev/null @@ -1,353 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { agentTeamOperationAllowed, agentTeamRequestSchema } from '../src/solver/agentTeamTool'; -import { agentTeamTaskHistory } from '../src/solver/agentTeamViews'; -import { agentTeamStateSchema } from '../src/solver/agentTeamState'; -import { agentTeamContextSection, buildSkillResearchContext } from '../src/solver/skillResearchContext'; -import { buildResearchContext, finalizeResearchDispatch } from '../src/solver/modules/context'; -import { resolveAgentTeamLeadProfile, resolveAgentTeamProfiles } from '../src/solver/agentTeamProfiles'; -import { researchSkillIdentity } from '../src/solver/researchSkill'; -import { readPersonalExperts } from '../src/solver/personalExperts'; -import { publishNativeApprovalPlan } from '../src/solver/planApproval'; -import { localExample, solverState } from './helpers/solver'; - -const roots: string[] = []; -afterEach(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -function fixture() { - const base = localExample('team-context-contract-'); - roots.push(base.directory); - const skill = readMathAgentSkill(path.resolve('skills/theoremos-research/SKILL.md')); - const objective = 'Profiles: D002, prover\nInvestigate the consumer hypothesis and report one useful result.'; - const state = solverState(base.problem, base.workspace, { - runId: 'context-contract', - phase: 'prepared', - researchMode: 'skill', - researchSkill: researchSkillIdentity(skill), - researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - events: [], - deliveries: [], - adoptions: [], - operations: [], - workers: [ - { - id: 'member', - role: 'researcher', - worktree: base.workspace, - phase: 'running', - status: 'running', - seedCommit: base.problem.baseCommit, - turns: 1, - cursor: 0, - tasks: [ - { - id: 'current', - message: objective, - status: 'running', - seedCommit: base.problem.baseCommit, - profileEvidence: resolveAgentTeamProfiles(skill, objective).evidence, - }, - ], - }, - ], - }, - }); - const access = { - root: path.resolve('.'), - worktree: base.workspace, - retrievalRoot: base.workspace, - environment: {}, - taskText: 'Solve the frozen original statement.', - researchSkill: skill, - }; - return { ...base, state, access, objective }; -} - -describe('native team context contract', () => { - it('keeps the native Lead charter and continuation when a plan is saved for approval', () => { - const f = fixture(); - f.state.researchSkillWorkflow = 'full'; - f.state.planApproval = true; - publishNativeApprovalPlan( - f.state, - { - operation: 'publish_plan', - goals: f.problem.targets.map(target => ({ - theoremName: target.theoremName, - objective: 'Check the local lemma first.', - })), - }, - () => {}, - () => {}, - ); - const context = buildResearchContext(f.problem, f.state, f.access); - const dispatch = finalizeResearchDispatch(context, { continuation: true }); - expect(dispatch.instructions).toContain(resolveAgentTeamLeadProfile(f.access.researchSkill).section.text); - expect(dispatch.manifest?.included).toContainEqual( - expect.objectContaining({ id: 'same-thread-skill-research', required: true }), - ); - expect(dispatch.message).not.toContain('Check the local lemma first.'); - }); - - it.each(['direct', 'full'] as const)( - 'injects the pinned Lead charter once through the %s workflow, including continuation', - workflow => { - const f = fixture(); - if (workflow === 'full') f.state.researchSkillWorkflow = 'full'; - f.state.researchDelegation = { mode: 'team', maxAgents: 3, preferredProfiles: ['D011', 'engineer'] }; - const profile = resolveAgentTeamLeadProfile(f.access.researchSkill); - expect(profile.evidence).toMatchObject({ selected: ['lead'], loaded: ['lead'], unresolved: [] }); - // Root dispatch normally omits teamRole; explicit coordinator dispatch has the same charter. - for (const teamRole of [undefined, { id: 'lead', role: 'lead' } as const]) { - const access = { ...f.access, ...(teamRole ? { teamRole } : {}) }; - const context = - workflow === 'full' - ? buildResearchContext(f.problem, f.state, access) - : buildSkillResearchContext(f.problem, f.state, access); - for (const continuation of [false, true]) { - const dispatched = finalizeResearchDispatch(context, { - continuation, - checkpointInstruction: 'Assess the current team update and continue saved work.', - }); - expect(dispatched.instructions).toContain(profile.section.text); - expect(dispatched.instructions).toContain('User-preferred member profiles:'); - expect(dispatched.instructions).toContain('D011 (Elementary Number Theory)'); - expect((dispatched.instructions + dispatched.message).split(profile.section.text)).toHaveLength(2); - expect(dispatched.instructions).toContain(JSON.stringify(profile.evidence)); - expect(dispatched.manifest?.usedBytes).toBe( - Buffer.byteLength(dispatched.instructions) + Buffer.byteLength(dispatched.message), - ); - } - } - }, - ); - - it('gives Lead the actual member delivery interface while keeping its own standalone request separate', () => { - const f = fixture(); - f.state.researchDelegation = { mode: 'team', maxAgents: 3, preferredProfiles: ['D011', 'engineer'] }; - const lead = buildSkillResearchContext(f.problem, f.state, { ...f.access, teamRole: { id: 'lead', role: 'lead' } }); - const leadHelp = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); - const member = buildSkillResearchContext(f.problem, f.state, { - ...f.access, - teamRole: { id: 'member', role: 'worker' }, - teamAssignment: { taskId: 'current', message: f.objective, sourceCommit: f.problem.baseCommit }, - }); - const memberHelp = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); - const leadProfile = resolveAgentTeamLeadProfile(f.access.researchSkill).section.text; - const memberProfile = resolveAgentTeamProfiles(f.access.researchSkill, f.objective).section.text; - const request = agentTeamRequestSchema.parse({ - operation: 'submit', - summary: 'One independent result.', - declarations: [{ file: f.problem.ownedFiles[0], name: 'Fixture.helper', type: 'True' }], - }); - expect(agentTeamOperationAllowed('member', request.operation)).toBe(true); - expect(agentTeamOperationAllowed('lead', request.operation)).toBe(false); - expect(leadHelp).toContain('operation submit'); - expect(leadHelp).toContain('only for your own Lead worktree'); - expect(leadHelp).toContain('## long-commands'); - expect(memberHelp).toContain('operation submit'); - expect(memberHelp).not.toContain('declaration-submission.json'); - for (const context of [lead, member]) { - for (const continuation of [false, true]) { - const full = finalizeResearchDispatch(context, { continuation }); - if (context === member) { - expect(full.instructions + full.message).not.toContain(leadProfile); - expect(full.message).toContain(memberProfile); - expect(full.instructions + full.message).not.toContain('User-preferred member profiles:'); - expect(full.message).not.toContain('Profile D011 ('); - expect(full.instructions).toContain('the assignment defines the result you own'); - expect(full.instructions).not.toContain('Research the fixed original mathematics problem'); - expect(full.message).toContain(JSON.stringify(f.objective)); - if (!continuation) { - expect(full.message).toContain('Frozen original problem (background for your current Lead assignment)'); - expect(full.message).toContain(JSON.stringify(f.problem.contract.formalStatement)); - } - } - const editable = JSON.parse( - /Editable Lean paths relative to it: (\[[^\n]*?\])\./u.exec(full.instructions)![1]!, - ); - expect(editable).toEqual( - f.problem.ownedFiles.filter(file => !Object.hasOwn(f.problem.frozenFiles ?? {}, file)), - ); - expect(full.instructions).toContain('separate worktree'); - expect(full.instructions + full.message).not.toContain('theoremos_team poll'); - expect(full.instructions + full.message).not.toContain('Poll after'); - expect(full.instructions + full.message).not.toContain('After ordinary tools resume'); - expect(full.instructions + full.message).not.toContain('Built-in spawn/fork is disabled'); - if (context === member) { - expect(full.instructions).toContain('Only Lead dispatches and adopts.'); - expect(full.instructions).toContain('Do not spawn subteams or interrupt peers.'); - expect(full.message).not.toContain('"currentStage"'); - } else { - expect(full.instructions).toContain('Lead of a flat mathematical research team'); - expect(full.instructions).toContain( - 'Call collaboration tools directly in their exposed namespace, not through functions.exec.', - ); - expect(full.instructions).toContain("A child's final answer is automatically delivered to its parent."); - expect(full.instructions).toContain('.scratch/theoremos-help.md'); - expect(full.instructions).not.toContain('Read local tool-help section "long-commands"'); - } - expect(agentTeamOperationAllowed('member', 'poll')).toBe(false); - } - } - }); - - it('shows personal card descriptions to Lead and only assigned card knowledge to members', () => { - const f = fixture(); - const file = path.join(f.directory, 'expert-cards.json'); - const card = { - name: 'Chosen expert', - assetId: 'chosen', - version: 'v1', - digest: 'a'.repeat(64), - summary: 'Short catalogue entry', - knowledge: 'Private chosen expert knowledge', - }; - fs.writeFileSync( - file, - JSON.stringify([ - card, - { - ...card, - assetId: 'other', - name: 'Other expert', - digest: 'b'.repeat(64), - knowledge: 'Private unrelated knowledge', - }, - ]), - ); - f.state.researchDelegation = { mode: 'team', maxAgents: 3, personalExperts: readPersonalExperts(file)! }; - const lead = buildSkillResearchContext(f.problem, f.state, f.access); - expect(lead.instructions).toContain(card.summary); - expect(lead.instructions + lead.message).not.toContain(card.knowledge); - const msg = 'Profiles: asset:chosen, prover\nInvestigate the consumer.'; - f.state.agentTeam!.workers[0]!.tasks[0]!.message = msg; - const member = buildSkillResearchContext(f.problem, f.state, { - ...f.access, - teamRole: { id: 'member', role: 'worker' }, - teamAssignment: { taskId: 'current', message: msg, sourceCommit: f.problem.baseCommit }, - }); - expect(member.message).toContain(card.knowledge); - expect(member.message).toContain('"releaseDigest":"' + card.digest + '"'); - expect(member.message + member.instructions).not.toContain('Private unrelated knowledge'); - expect(member.continuationMessage).toContain(card.knowledge); - }); - - it('keeps one full current assignment and one evidence record, with complete history still readable', () => { - const f = fixture(); - f.state.agentTeam!.events.push( - { sequence: 1, from: 'lead', to: 'member', kind: 'message', at: 1, text: 'Check the consumer hypothesis.' }, - { sequence: 2, from: 'lead', to: 'member', kind: 'message', at: 2, text: 'Long advisory. '.repeat(400) }, - ); - const context = buildSkillResearchContext(f.problem, f.state, { - ...f.access, - teamRole: { id: 'member', role: 'worker' }, - teamAssignment: { taskId: 'current', message: f.objective, sourceCommit: f.problem.baseCommit }, - }); - const envelope = JSON.parse(context.message.split('\n')[1]!); - expect(envelope.inbox).toMatchObject({ through: 1, previewThrough: 2, more: true }); - expect(context.inboxThrough).toBe(1); - expect(envelope.objective).toBe(f.objective); - expect(envelope).not.toHaveProperty('profileEvidence'); - expect(envelope).not.toHaveProperty('workers'); - expect(context.message.match(/theorem-os\.agent-team-profile-evidence\.v1/gu)).toHaveLength(1); - const history = agentTeamTaskHistory(f.state.agentTeam!, { agentId: 'member' }); - expect(history.tasks[0]?.objective).toBe(f.objective); - expect(history.tasks[0]?.profileEvidence).toEqual(f.state.agentTeam!.workers[0]!.tasks[0]!.profileEvidence); - }); -}); - -it.each(['opening', 'saved presentation', 'failed probe', 'uncertain mail'] as const)( - 'keeps native %s evidence advisory after state recovery', - scenario => { - const f = fixture(), - team = f.state.agentTeam!; - team.workers = []; - if (scenario !== 'opening') - team.coordinationPresentation = { - at: 1, - reason: 'opening', - decisionRevision: 0, - eventSequence: 0, - startedRequests: 0, - }; - if (scenario === 'failed probe' || scenario === 'uncertain mail') - team.coordination = { - revision: 1, - at: 2, - decision: 'continue', - reason: 'A concrete question is ready to inspect.', - nextStep: 'Read current sources and check the next inference.', - startedRequests: 0, - eventSequence: 0, - nativeMessageSequence: 0, - observationRevision: 0, - }; - if (scenario === 'failed probe') - team.coordinationObservation = { - revision: 1, - at: 3, - key: 'failed-probe', - kind: 'tool-result', - failed: true, - description: 'The local probe failed; inspect the current diagnostic.', - }; - if (scenario === 'uncertain mail') - team.nativeControl = { - sessionId: 'session', - rootThreadId: 'root-thread', - sequence: 1, - mailbox: [ - { - id: 'mail-1', - threadId: 'root-thread', - author: '/root/member', - recipient: '/root', - status: 'uncertain', - sequence: 1, - }, - ], - }; - f.state.agentTeam = agentTeamStateSchema.parse(JSON.parse(JSON.stringify(team))); - const archived = structuredClone(f.state.agentTeam); - const observation = JSON.parse(agentTeamContextSection(f.state).text.split('\n')[1]!); - expect(observation).not.toHaveProperty('currentStage'); - expect(observation).not.toHaveProperty('coordination'); - expect(observation).not.toHaveProperty('coordinationObservation'); - const context = buildSkillResearchContext(f.problem, f.state, { - ...f.access, - teamRole: { id: 'lead', role: 'lead' }, - }); - for (const continuation of [false, true]) { - const dispatch = finalizeResearchDispatch(context, { continuation }); - expect(dispatch.message).toContain('Read current Lean sources and worktree-root RESEARCH.md'); - expect(dispatch.message).not.toContain('Address the pending collaboration decision'); - expect(dispatch.message).not.toContain('After ordinary tools resume'); - expect(dispatch.message).not.toContain('before extended proof work'); - expect(dispatch.manifest!.included.find(item => item.id === 'saved-work')).toMatchObject({ - kind: 'sources', - required: true, - }); - } - expect(f.state.agentTeam).toEqual(archived); - }, -); - -it('retains standalone declaration delivery without exposing a team contract', () => { - const f = fixture(); - delete f.state.researchDelegation; - delete f.state.agentTeam; - const context = buildSkillResearchContext(f.problem, f.state, f.access); - const help = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); - expect(help).toContain('.scratch/declaration-submission.json'); - expect(help).not.toContain('Member delivery contract'); - expect(context.instructions).not.toContain('operation submit'); - expect(context.message).not.toContain('agent-team-profile-evidence'); -}); diff --git a/tests/agentTeamHandoffs.test.ts b/tests/agentTeamHandoffs.test.ts deleted file mode 100644 index e72edc60..00000000 --- a/tests/agentTeamHandoffs.test.ts +++ /dev/null @@ -1,196 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import type { ModelRequestGate } from '../src/runtime/modelRequest'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { agentTeamStateSchema } from '../src/solver/agentTeamState'; -import { agentTeamOverview } from '../src/solver/agentTeamViews'; -import { directSolverModules } from '../src/solver/modules'; -import { git, readSolverProblem } from '../src/solver/problem'; -import { beginRequestUsage, initializeRequestUsageAccounting } from '../src/solver/usageBudget'; -import { temporaryDirectory } from './helpers/files'; -import { solverState } from './helpers/solver'; - -const fixtures: ReturnType[] = []; -afterEach(async () => { - for (const f of fixtures.splice(0)) { - await f.team.close(); - fs.rmSync(f.directory, { recursive: true, force: true }); - } -}); - -function fixture() { - const directory = temporaryDirectory('agent-team-handoffs-'); - const receipt = bootstrapLeanTask(path.join(directory, 'lead'), { - task: 'Disposable proof handoff fixture.', - source: 'theorem original : True := by sorry\n', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const state = solverState(problem, receipt.workspaceRoot, { - runId: 'proof-handoffs', - phase: 'running', - threadId: 'saved-lead-thread', - researchMode: 'skill', - researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - coordination: { - revision: 1, - at: 1, - decision: 'defer', - reason: 'Historical optional note.', - nextStep: 'Inspect one definition.', - startedRequests: 0, - eventSequence: 0, - }, - coordinationPresentation: { at: 2, reason: 'opening', decisionRevision: 1, eventSequence: 0 }, - coordinationObservation: { - revision: 1, - at: 3, - key: 'old-probe', - kind: 'tool-result', - failed: true, - description: 'Old tool diagnostic.', - }, - }, - }); - state.agentTeam = agentTeamStateSchema.parse(JSON.parse(JSON.stringify(state.agentTeam))); - initializeRequestUsageAccounting(state); - const events: string[] = [], - open = vi.fn(async () => { - throw new Error('No model is used by the handoff fixture.'); - }); - const team = new AgentResearchTeam({ - state, - root: process.cwd(), - taskText: 'Disposable proof handoff fixture.', - leadAccess: { environment: {}, retrievalRoot: receipt.workspaceRoot }, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, - executable: 'unused-offline-fixture', - profile: 'unused-offline-fixture', - signal: new AbortController().signal, - maxAgents: 3, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save: () => {}, - emit: event => { - events.push(event); - }, - exclusiveCheck: operation => operation(), - }); - const f = { directory, state, team, events, open, sourceFile: path.join(receipt.projectRoot, 'Submission.lean') }; - fixtures.push(f); - return f; -} - -describe('native proof handoff adapter', () => { - it('reads historical coordination fields without turning them or incoming messages into a research gate', () => { - const f = fixture(), - notes = structuredClone(f.state.agentTeam); - const source = fs.readFileSync(f.sourceFile, 'utf8'), - head = git(f.state.worktree, ['rev-parse', 'HEAD']); - const base: ModelRequestGate = identity => ({ allowed: true, settle: beginRequestUsage(f.state, identity) }); - const gate = f.team.leadRequestGate(base); - f.team.beginLeadTurn(); - for (let i = 1; i <= 3; i++) { - f.team.archive.events.push({ - sequence: i, - from: 'expert', - to: 'lead', - kind: 'message', - at: i, - text: 'A native finding.', - }); - const request = gate({ requestId: `ordinary-research-${i}`, threadId: f.state.threadId }); - if (!request.allowed) throw new Error(request.reason); - expect(gate.checkpoint!()).toBe(false); - request.settle({ - complete: true, - outcome: 'completed', - usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 }, - }); - expect(gate.checkpoint!()).toBe(false); - } - expect(agentTeamOverview(f.state)).not.toHaveProperty('coordination'); - expect(f.team.archive.coordination).toEqual(notes!.coordination); - expect(f.team.archive.coordinationPresentation).toEqual(notes!.coordinationPresentation); - expect(f.team.archive.coordinationObservation).toEqual(notes!.coordinationObservation); - expect(f.events).toEqual([]); - expect(f.open).not.toHaveBeenCalled(); - expect(git(f.state.worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(fs.readFileSync(f.sourceFile, 'utf8')).toBe(source); - }); - - it.each(['adopt', 'finish', 'base'] as const)( - 'retains the %s checkpoint and waits for paid response settlement', - async kind => { - const f = fixture(); - let baseCheckpoint = false; - const beforeRequest = vi.fn(async () => {}); - const base: ModelRequestGate = identity => ({ allowed: true, settle: beginRequestUsage(f.state, identity) }); - base.checkpoint = () => baseCheckpoint; - base.beforeRequest = beforeRequest; - const gate = f.team.leadRequestGate(base); - f.team.beginLeadTurn(); - await gate.beforeRequest!(new AbortController().signal); - expect(beforeRequest).toHaveBeenCalledOnce(); - const request = gate({ requestId: 'last-paid-response', threadId: f.state.threadId }); - if (!request.allowed) throw new Error(request.reason); - if (kind === 'adopt') - f.team.archive.adoptions.push({ - id: 'adoption', - deliveryId: 'b'.repeat(64), - targetId: 'lead', - status: 'queued', - }); - if (kind === 'finish') - await f.team.tools().call( - 'theoremos_team', - { operation: 'finish', summary: 'Saved sources ready for independent checking.' }, - { - callId: 'finish', - turnId: 'current', - threadId: f.state.threadId!, - signal: new AbortController().signal, - }, - ); - expect(gate.checkpoint!()).toBe(false); - request.settle({ - complete: true, - outcome: 'completed', - usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 }, - }); - if (kind === 'base') baseCheckpoint = true; - expect(gate.checkpoint!()).toBe(true); - expect(gate.checkpoint!()).toBe(true); - expect(f.team.leadAdoptionCheckpoint).toBe(kind === 'adopt'); - expect(f.team.leadCompletionCheckpoint).toBe(kind === 'finish'); - expect(f.events).toEqual( - kind === 'base' ? [] : [kind === 'adopt' ? 'team_adoption_checkpoint' : 'team_completion_checkpoint'], - ); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(f.state.check).toBeUndefined(); - expect(f.open).not.toHaveBeenCalled(); - }, - ); - - it('honors a recovered adoption before admitting another paid response', () => { - const f = fixture(), - base = vi.fn(() => ({ allowed: true as const, settle: () => {} })); - f.team.archive.adoptions.push({ id: 'recovered', deliveryId: 'b'.repeat(64), targetId: 'lead', status: 'queued' }); - const gate = f.team.leadRequestGate(base); - f.team.beginLeadTurn(); - expect(gate.checkpoint!()).toBe(true); - expect(base).not.toHaveBeenCalled(); - expect(f.open).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/agentTeamNativeControl.test.ts b/tests/agentTeamNativeControl.test.ts deleted file mode 100644 index 3395de77..00000000 --- a/tests/agentTeamNativeControl.test.ts +++ /dev/null @@ -1,693 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; - -vi.mock('../src/math/nativeProcess', async importOriginal => { - const addon = process.env.THEOREMOS_TEST_PROCESS_ADDON; - if (!addon) return importOriginal(); - const handle = { exports: {} }; - process.dlopen(handle, addon); - return { nativeProcess: handle.exports }; -}); -import { AgentTeamNativeControl, type AgentTeamNativeLifecycle } from '../src/solver/agentTeamNative'; -import type { AgentTeamState, AgentTeamWorker } from '../src/solver/agentTeamState'; -import type { NativeAgentControlConnection } from '../src/runtime/nativeAgentControl'; -import { agentTeamInstructions } from '../src/solver/agentTeamContext'; -import { agentTeamOperationAllowed, agentTeamToolDefinition } from '../src/solver/agentTeamTool'; -import { deferred } from './helpers/async'; - -type Json = Record; -const ROOT = '00000000-0000-4000-8000-000000000001'; -const CHILD = '00000000-0000-4000-8000-000000000002'; - -function member(id = 'analyst', threadId = CHILD): AgentTeamWorker { - return { - id, - role: 'researcher', - worktree: '/isolated/' + id, - phase: 'prepared', - status: 'idle', - turns: 0, - seedCommit: 'a'.repeat(40), - tasks: [], - cursor: 0, - native: { - sessionId: ROOT, - threadId, - parentThreadId: ROOT, - agentPath: '/root/' + id, - bootstrap: { threadId, sessionId: ROOT }, - initialInput: { author: '/root', input: {} }, - agent: { - threadId, - metadata: { agentId: threadId, agentPath: '/root/' + id }, - status: { completed: 'Saved advisory research.' }, - }, - configSnapshot: { cwd: '/isolated/' + id }, - }, - }; -} - -function connection(threadId = ROOT, path = '/root') { - const current: NativeAgentControlConnection = { - info: { - sessionId: ROOT, - agent: { threadId, metadata: { agentId: threadId, agentPath: path }, status: 'running' }, - configSnapshot: { cwd: '/isolated' + path }, - }, - request: vi.fn(async () => ({})), - input: vi.fn(async () => ({ accepted: true, threadId, submissionId: 'submission' })), - update: vi.fn(async request => ({ acceptedSequence: request.sequence })), - }; - return current; -} - -async function fixture() { - const archive: AgentTeamState = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [member()], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }; - const accepted = { - agent: archive.workers[0].native!.agent!, - configSnapshot: { cwd: '/isolated/analyst' }, - submissionId: 'turn-a', - }; - const lifecycle: AgentTeamNativeLifecycle = { - spawn: vi.fn(async () => accepted), - followup: vi.fn(async () => accepted), - interrupt: vi.fn(async () => {}), - load: vi.fn(async () => {}), - admit: vi.fn(), - }; - const save = vi.fn(), - control = new AgentTeamNativeControl(archive, lifecycle, save), - root = connection(); - let index = 0; - const call = (operation: string, payload: Json, actor = 'lead', channel = root, operationId = 'op-' + ++index) => { - const threadId = actor === 'lead' ? ROOT : archive.workers.find(worker => worker.id === actor)!.native!.threadId; - return control - .options(actor) - .request({ version: 1, sessionId: ROOT, threadId, operation, operationId, payload }, channel, { - signal: new AbortController().signal, - }); - }; - await call('attach', { threadId: ROOT, sessionId: ROOT }); - await control.options('lead').bound!(root); - return { archive, lifecycle, save, control, root, call, accepted }; -} - -describe('native AgentControl mathematical-team host routing', () => { - it('uses real canonical identities and returns only loaded native agents', async () => { - const f = await fixture(); - expect( - await f.call('resolve', { caller: ROOT, target: { kind: 'reference', reference: '/root/analyst' } }), - ).toEqual({ result: { threadId: CHILD } }); - await expect( - f.call('resolve', { caller: ROOT, target: { kind: 'reference', reference: 'analyst' } }), - ).rejects.toThrow('reference_unknown'); - await expect( - f.call('resolve', { caller: ROOT, target: { kind: 'id', threadId: '00000000-0000-4000-8000-000000000099' } }), - ).rejects.toThrow('reference_unknown'); - expect((await f.call('list', { caller: ROOT })).result).toMatchObject({ agents: [{ threadId: ROOT }] }); - const child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - expect(child.update).not.toHaveBeenCalled(); - await f.control.options('analyst').bound!(child); - expect((await f.call('list', { caller: ROOT, pathPrefix: '/root/analyst' })).result).toMatchObject({ - agents: [{ threadId: CHILD }], - }); - await expect(f.call('list', { caller: CHILD })).rejects.toThrow('caller_changed'); - await f.control.options('analyst').disconnected!(child); - const result = await f.call('interrupt', { caller: ROOT, target: { kind: 'id', threadId: CHILD } }); - expect(result.result).toMatchObject({ kind: 'unloaded', metadata: { agentPath: '/root/analyst' } }); - expect(f.lifecycle.interrupt).toHaveBeenCalledWith(f.archive.workers[0]); - expect(f.archive.workers[0].status).toBe('idle'); - }); - - it('keeps repeated native reads and usage acknowledgments out of the durable mutation journal', async () => { - const f = await fixture(); - f.save.mockClear(); - for (let index = 0; index < 3; index++) { - expect( - await f.call('resolve', { caller: ROOT, target: { kind: 'reference', reference: '/root/analyst' } }), - ).toEqual({ result: { threadId: CHILD } }); - expect((await f.call('list', { caller: ROOT })).result).toMatchObject({ agents: [{ threadId: ROOT }] }); - expect(await f.call('childPaths', { parent: ROOT })).toEqual({ result: { paths: ['/root/analyst'] } }); - expect( - await f.call('recordUsage', { - caller: ROOT, - threadId: ROOT, - turnId: 'turn-' + index, - usage: { total_tokens: index }, - }), - ).toEqual({ result: {} }); - expect(await f.call('releaseTurn', { caller: ROOT, threadId: ROOT, turnId: 'turn-' + index })).toEqual({ - result: {}, - }); - } - await expect(f.call('recordUsage', { caller: CHILD })).rejects.toThrow('caller_changed'); - await expect(f.call('releaseTurn', { caller: CHILD })).rejects.toThrow('caller_changed'); - expect(f.archive.operations).toEqual([]); - expect(f.save).not.toHaveBeenCalled(); - expect(f.root.update).not.toHaveBeenCalled(); - expect(f.lifecycle.followup).not.toHaveBeenCalled(); - }); - - it('reads current loaded membership instead of replaying a saved list snapshot', async () => { - const f = await fixture(); - const payload = { caller: ROOT }; - expect((await f.call('list', payload, 'lead', f.root, 'same-read')).result).toMatchObject({ - agents: [{ threadId: ROOT }], - }); - const child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - await f.control.options('analyst').bound!(child); - f.save.mockClear(); - expect((await f.call('list', payload, 'lead', f.root, 'same-read')).result).toMatchObject({ - agents: [{ threadId: ROOT }, { threadId: CHILD }], - }); - expect(f.archive.operations).toEqual([]); - expect(f.save).not.toHaveBeenCalled(); - }); - - it('keeps queue-only mail durable without starting an idle model turn', async () => { - const f = await fixture(); - const result = await f.call('send', { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'A dependency is ready.' } }, - }); - expect(result.result).toMatchObject({ threadId: CHILD, metadata: { agentPath: '/root/analyst' } }); - expect(f.lifecycle.followup).not.toHaveBeenCalled(); - expect(f.lifecycle.load).not.toHaveBeenCalled(); - expect(f.archive.nativeControl!.mailbox).toMatchObject([ - { status: 'queued', author: '/root', recipient: '/root/analyst' }, - ]); - const child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - expect(child.update).not.toHaveBeenCalled(); - await f.control.options('analyst').bound!(child); - expect(child.update).toHaveBeenCalledTimes(1); - expect(f.archive.nativeControl!.mailbox[0].status).toBe('accepted'); - await f.control.options('analyst').disconnected!(child); - expect(f.archive.nativeControl!.mailbox[0].status).toBe('uncertain'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - expect(child.update).toHaveBeenCalledTimes(1); - }); - - it('keeps a reconnecting child unloaded and retains mail if its startup fails before binding', async () => { - const f = await fixture(), - provisional = { ...connection(CHILD, '/root/analyst'), info: undefined }; - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', provisional); - expect(await f.call('list', { caller: ROOT, pathPrefix: '/root/analyst' })).toEqual({ result: { agents: [] } }); - const target = { kind: 'reference', reference: '/root/analyst' }; - expect(await f.call('resolve', { caller: ROOT, target })).toEqual({ result: { threadId: CHILD } }); - const sent = await f.call('send', { - caller: ROOT, - target, - input: { - kind: 'message', - mode: 'queueOnly', - message: { kind: 'plaintext', text: 'Use the checked dependency.' }, - }, - }); - expect(sent.result).toMatchObject({ threadId: CHILD, submissionId: expect.any(String) }); - expect(provisional.update).not.toHaveBeenCalled(); - expect(f.archive.nativeControl!.mailbox[0].status).toBe('queued'); - await f.control.options('analyst').disconnected!(provisional); - const child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - expect(child.update).not.toHaveBeenCalled(); - await f.control.options('analyst').bound!(child); - expect(child.update).toHaveBeenCalledTimes(1); - expect(f.archive.nativeControl!.mailbox[0].status).toBe('accepted'); - expect((await f.call('list', { caller: ROOT, pathPrefix: '/root/analyst' })).result).toMatchObject({ - agents: [{ threadId: CHILD }], - }); - }); - - it('leaves delivery uncertain when an in-flight update is acknowledged by the replaced connection', async () => { - const f = await fixture(), - child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - await f.control.options('analyst').bound!(child); - await f.control.advisory(null, 'analyst', 'Already forwarded to the old connection.'); - expect(f.archive.nativeControl!.mailbox[0].status).toBe('accepted'); - const updating = deferred(), - release = deferred(); - vi.mocked(child.update).mockImplementationOnce(async request => { - updating.resolve(); - await release.promise; - return { acceptedSequence: request.sequence }; - }); - const sent = f.call('send', { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input: { - kind: 'message', - mode: 'queueOnly', - message: { kind: 'plaintext', text: 'Do not replay an unconfirmed delivery.' }, - }, - }); - await updating.promise; - const replacement = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', replacement); - await f.control.options('analyst').disconnected!(child); - release.resolve(); - await f.control.options('analyst').bound!(replacement); - await sent; - expect(child.update).toHaveBeenCalledTimes(2); - expect(replacement.update).not.toHaveBeenCalled(); - expect(f.archive.nativeControl!.mailbox.map(mail => mail.status)).toEqual(['uncertain', 'uncertain']); - }); - - it('preserves native sender identity and enforces the flat Lead dispatch authority', async () => { - const f = await fixture(), - child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - await f.call( - 'send', - { - caller: CHILD, - target: { kind: 'reference', reference: '/root' }, - input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'An advisory finding.' } }, - }, - 'analyst', - child, - ); - expect(f.archive.nativeControl!.mailbox[0]).toMatchObject({ - author: '/root/analyst', - recipient: '/root', - status: 'accepted', - }); - expect(f.archive.nativeControl!.mailbox[0].hostEventSequence).toBeUndefined(); - await f.control.advisory('analyst', 'lead', 'Checked declarations are ready.'); - expect(f.archive.nativeControl!.mailbox[1]).toMatchObject({ status: 'accepted' }); - expect(f.archive.nativeControl!.mailbox[1]).not.toHaveProperty('hostEventSequence'); - const notification = vi.mocked(f.root.update).mock.calls.at(-1)![0].mailbox![0]; - expect(notification).not.toHaveProperty('hostEventSequence'); - await expect(f.call('spawn', { caller: CHILD }, 'analyst', child)).rejects.toThrow('lead_operation_required'); - await expect( - f.call('interrupt', { caller: CHILD, target: { kind: 'id', threadId: ROOT } }, 'analyst', child), - ).rejects.toThrow('lead_operation_required'); - await expect( - f.call( - 'send', - { - caller: CHILD, - target: { kind: 'id', threadId: CHILD }, - input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'Self.' } }, - }, - 'analyst', - child, - ), - ).rejects.toThrow('self_addressed'); - await expect( - f.call('send', { - caller: ROOT, - target: { kind: 'id', threadId: ROOT }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Root followup.' } }, - }), - ).rejects.toThrow(); - }); - - it('delivers host adoption and failure observations without looking up a nonexistent host worker', async () => { - const f = await fixture(), - child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - await f.control.options('analyst').bound!(child); - await f.control.advisory(null, 'lead', 'Checked declarations were integrated.'); - await f.control.advisory(null, 'analyst', 'The dependency is ready.'); - expect(f.archive.nativeControl!.mailbox).toMatchObject([ - { author: '/morpheus', recipient: '/root', status: 'accepted' }, - { author: '/morpheus', recipient: '/root/analyst', status: 'accepted' }, - ]); - expect(f.archive.nativeControl!.mailbox.every(item => item.hostEventSequence === undefined)).toBe(true); - expect(f.lifecycle.followup).not.toHaveBeenCalled(); - }); - - it('keeps a member named host distinct from the native host author', async () => { - const f = await fixture(); - f.archive.workers[0] = member('host'); - await f.control.advisory('host', 'lead', 'Member checked delivery.'); - await f.control.advisory(null, 'host', 'Checked dependency ready.'); - expect(f.archive.nativeControl!.mailbox).toMatchObject([ - { author: '/root/host', recipient: '/root', status: 'accepted' }, - { author: '/morpheus', recipient: '/root/host', status: 'queued' }, - ]); - }); - - it('passes attributed followup to the current member lifecycle without amending its objective', async () => { - const f = await fixture(), - worker = f.archive.workers[0]; - worker.tasks.push({ - id: 'same-task', - message: 'Profiles: D006\nInvestigate this gap.', - status: 'running', - objectiveRevision: 2, - }); - const input = { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Continue with the new evidence.' }, - }; - await f.call('send', { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input, - startOptions: { parentTurnId: 'parent-turn' }, - }); - expect(f.lifecycle.followup).toHaveBeenCalledWith( - worker, - { - author: '/root', - input, - startOptions: { parentTurnId: 'parent-turn' }, - }, - expect.any(AbortSignal), - ); - expect(worker.tasks).toMatchObject([{ id: 'same-task', objectiveRevision: 2, status: 'running' }]); - }); - - it('deduplicates one native operation and rejects changed completed or pending payloads', async () => { - const f = await fixture(), - gate = deferred extends Promise ? F['accepted'] : never>(); - vi.mocked(f.lifecycle.followup).mockReturnValue(gate.promise); - const payload = { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue.' } }, - }; - const first = f.call('send', payload, 'lead', f.root, 'stable-op'); - const repeated = f.call('send', payload, 'lead', f.root, 'stable-op'); - await expect( - f.call('send', { ...payload, startOptions: { parentTurnId: 'different' } }, 'lead', f.root, 'stable-op'), - ).rejects.toThrow('call_changed'); - gate.resolve(f.accepted); - expect(await first).toEqual(await repeated); - expect(f.lifecycle.followup).toHaveBeenCalledTimes(1); - await expect( - f.call('send', { ...payload, startOptions: { parentTurnId: 'changed' } }, 'lead', f.root, 'stable-op'), - ).rejects.toThrow('call_changed'); - }); - - it('recovers the same submission after a process dies between handoff and acknowledgment', async () => { - const f = await fixture(); - const child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - await f.control.options('analyst').bound!(child); - const gate = deferred(); - const submitted = deferred(); - vi.mocked(child.update).mockImplementationOnce(async request => { - submitted.resolve(); - await gate.promise; - return { acceptedSequence: request.sequence }; - }); - const payload = { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'Saved once.' } }, - }; - const first = f.call('send', payload, 'lead', f.root, 'same-message'); - try { - await submitted.promise; - const archived = structuredClone(f.archive); - expect(archived.nativeControl!.mailbox[0].status).toBe('uncertain'); - const restored = new AgentTeamNativeControl(archived, f.lifecycle, vi.fn()); - const root = connection(); - const request = (operation: string, p: Json) => - restored - .options('lead') - .request( - { version: 1, sessionId: ROOT, threadId: ROOT, operation, operationId: 'same-message', payload: p }, - root, - { signal: new AbortController().signal }, - ); - await request('attach', { threadId: ROOT, sessionId: ROOT }); - await restored.options('lead').bound!(root); - const reply = await request('send', payload); - expect(reply.result).toMatchObject({ submissionId: archived.nativeControl!.mailbox[0].id }); - expect(archived.nativeControl!.mailbox).toHaveLength(1); - await expect( - request('send', { ...payload, input: { ...payload.input, message: { text: 'Changed' } } }), - ).rejects.toThrow('call_changed'); - } finally { - gate.resolve(); - await first; - } - }); - - it('replays a saved native dispatch receipt after recovery without dispatching the member twice', async () => { - const f = await fixture(); - const payload = { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue the assignment.' } }, - }; - const accepted = await f.call('send', payload, 'lead', f.root, 'saved-dispatch'); - expect(f.lifecycle.followup).toHaveBeenCalledTimes(1); - const archive = structuredClone(f.archive), - save = vi.fn(); - const lifecycle = { ...f.lifecycle, followup: vi.fn(async () => f.accepted) }; - const recovered = new AgentTeamNativeControl(archive, lifecycle, save), - root = connection(); - const request = (operation: string, operationId: string, payload: Json) => - recovered.options('lead').request( - { - version: 1, - sessionId: ROOT, - threadId: ROOT, - operation, - operationId, - payload, - }, - root, - { signal: new AbortController().signal }, - ); - await request('attach', 'recovered-attach', { threadId: ROOT, sessionId: ROOT }); - save.mockClear(); - expect(await request('send', 'saved-dispatch', payload)).toEqual(accepted); - await expect( - request('send', 'saved-dispatch', { ...payload, startOptions: { parentTurnId: 'changed' } }), - ).rejects.toThrow('call_changed'); - expect(lifecycle.followup).not.toHaveBeenCalled(); - expect(save).not.toHaveBeenCalled(); - expect(archive.operations).toEqual(f.archive.operations); - }); - - it('records native completion as advisory without manufacturing a proof delivery', async () => { - const f = await fixture(), - child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - await f.call( - 'turnFinished', - { outcome: { threadId: CHILD, turnId: 'native-turn', status: { completed: 'A useful result.' } } }, - 'analyst', - child, - ); - expect(f.archive.workers[0].native!.status).toEqual({ completed: 'A useful result.' }); - expect(f.archive.workers[0].tasks).toEqual([]); - expect(f.archive.deliveries).toEqual([]); - expect(f.archive.adoptions).toEqual([]); - expect(f.archive.workers[0].pendingDelivery).toBeUndefined(); - }); - - it('preserves the native completion communication without adding another plaintext wrapper', async () => { - const f = await fixture(), - child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - const communication = { - author: '/root/analyst', - recipient: '/root', - citations: [], - content: 'Useful advisory result.', - trigger_turn: false, - }; - await f.call( - 'turnFinished', - { - outcome: { threadId: CHILD, turnId: 'terminal-turn', status: { completed: 'Useful result.' } }, - parentThreadId: ROOT, - completionMessage: communication, - }, - 'analyst', - child, - ); - expect(f.archive.nativeControl!.mailbox[0]).toMatchObject({ communication, status: 'accepted' }); - expect(f.archive.nativeControl!.mailbox[0].message).toBeUndefined(); - const sent = vi.mocked(f.root.update).mock.calls[0][0] as Json; - expect(sent.mailbox[0].communication).toEqual(communication); - expect(sent.mailbox[0].message).toBeUndefined(); - }); - - it('resolves cold child attachment to the persisted tree and leaves uncertain delivery unreplayed', async () => { - const f = await fixture(), - child = connection(CHILD, '/root/analyst'); - const response = await f.control.options('analyst').request( - { - version: 1, - sessionId: CHILD, - threadId: CHILD, - operationId: 'cold-attach', - operation: 'attach', - payload: { threadId: CHILD, sessionId: CHILD }, - }, - child, - { signal: new AbortController().signal }, - ); - expect(response).toEqual({ result: { sessionId: ROOT } }); - await f.control.options('analyst').bound!(child); - vi.mocked(child.update).mockRejectedValueOnce(new Error('response-lost-after-native-acceptance')); - await f.call('send', { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'No false read receipt.' } }, - }); - expect(f.archive.nativeControl!.mailbox[0]).toMatchObject({ status: 'uncertain', sequence: 1 }); - await f.control.options('analyst').bound!(child); - expect(child.update).toHaveBeenCalledTimes(1); - expect(f.lifecycle.followup).not.toHaveBeenCalled(); - }); - - it('retries queued mail on reattach if the recipient disconnected before the update could send it', async () => { - const f = await fixture(), - child = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); - await f.control.options('analyst').bound!(child); - const updating = deferred(), - release = deferred(); - vi.mocked(child.update).mockImplementationOnce(async request => { - updating.resolve(); - await release.promise; - return { acceptedSequence: request.sequence }; - }); - const configUpdate = f.call('configUpdate', { serviceTier: 'priority' }).catch(error => (error as Error).message); - await updating.promise; - const send = f.call('send', { - caller: ROOT, - target: { kind: 'id', threadId: CHILD }, - input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'A dependency is ready.' } }, - }); - await expect.poll(() => f.archive.nativeControl!.mailbox.length).toBe(1); - await f.control.options('analyst').disconnected!(child); - release.resolve(); - await configUpdate; - await send; - const [mail] = f.archive.nativeControl!.mailbox; - expect(mail).toMatchObject({ status: 'queued' }); - expect(mail.sequence).toBeUndefined(); - expect(child.update).toHaveBeenCalledTimes(1); - - const resumed = connection(CHILD, '/root/analyst'); - await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', resumed); - await f.control.options('analyst').bound!(resumed); - expect(resumed.update).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - mailbox: [ - expect.objectContaining({ id: mail.id, message: { kind: 'plaintext', text: 'A dependency is ready.' } }), - ], - }), - ); - expect(mail.status).toBe('accepted'); - }); - - it('returns one spawn receipt for the same operation and rejects a reused path for another assignment', async () => { - const f = await fixture(); - const payload = { - caller: ROOT, - source: { subagent: { thread_spawn: { parent_thread_id: ROOT, agent_path: '/root/prover' } } }, - bootstrap: { sessionId: ROOT, threadId: null, config: { cwd: '/lead' } }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Profiles: prover\nProve the helper.' }, - }, - startOptions: {}, - }; - vi.mocked(f.lifecycle.spawn).mockImplementationOnce(async request => { - const worker = member('prover', request.threadId); - worker.native!.spawnOperationId = request.operationId; - worker.native!.spawnRequestDigest = request.requestDigest; - worker.native!.submissionId = 'actual-submission'; - f.archive.workers.push(worker); - return { - agent: worker.native!.agent!, - configSnapshot: worker.native!.configSnapshot!, - submissionId: 'actual-submission', - }; - }); - const accepted = await f.call('spawn', payload, 'lead', f.root, 'spawn-accepted'); - expect(await f.call('spawn', payload, 'lead', f.root, 'spawn-accepted')).toEqual(accepted); - // Recover the acceptance-before-parent-receipt save window from the fixed child binding. - const archive = structuredClone(f.archive); - archive.operations = []; - const recovered = new AgentTeamNativeControl(archive, f.lifecycle, f.save), - root = connection(); - const call = (operation: string, operationId: string, payload: Json) => - recovered.options('lead').request( - { - version: 1, - sessionId: ROOT, - threadId: ROOT, - operation, - operationId, - payload, - }, - root, - { signal: new AbortController().signal }, - ); - await call('attach', 'recovered-attach', { threadId: ROOT, sessionId: ROOT }); - await expect( - call('spawn', 'spawn-accepted', { ...payload, startOptions: { parentTurnId: 'different-task-lineage' } }), - ).rejects.toThrow('call_changed'); - expect(await call('spawn', 'spawn-accepted', payload)).toEqual(accepted); - await expect(call('spawn', 'another-spawn', payload)).rejects.toThrow('agent_exists'); - expect(f.lifecycle.spawn).toHaveBeenCalledTimes(1); - }); - - it('makes native transport operations unavailable through the mathematical dynamic tool', () => { - const tool = agentTeamToolDefinition('lead'); - const operations = (tool.inputSchema.properties as Json).operation.enum; - for (const operation of [ - 'spawn', - 'assign', - 'message', - 'poll', - 'wait', - 'stop', - 'resume', - 'amend', - 'cancel', - 'coordinate', - 'publish', - 'budget', - 'progress', - ]) { - expect(operations).not.toContain(operation); - expect(agentTeamOperationAllowed('lead', operation)).toBe(false); - } - expect(operations).toEqual([ - 'finish', - 'history', - 'inspect', - 'inspect-research', - 'adopt', - 'retire_route', - 'route_summary', - ]); - const memberTool = agentTeamToolDefinition('analyst'); - expect((memberTool.inputSchema.properties as Json).operation.enum).toEqual([ - 'yield', - 'history', - 'inspect', - 'inspect-research', - 'submit', - 'route_summary', - ]); - expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4)).toContain('native collaboration tools'); - expect(agentTeamInstructions({ id: 'lead', role: 'lead' }, 4)).not.toContain('Built-in spawn/fork is disabled'); - }); -}); diff --git a/tests/agentTeamNativeLifecycle.test.ts b/tests/agentTeamNativeLifecycle.test.ts deleted file mode 100644 index 7cfe8629..00000000 --- a/tests/agentTeamNativeLifecycle.test.ts +++ /dev/null @@ -1,1587 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import crypto from 'node:crypto'; -import { afterEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('../src/math/nativeProcess', async importOriginal => { - const addon = process.env.THEOREMOS_TEST_PROCESS_ADDON; - if (!addon) return importOriginal(); - const handle = { exports: {} }; - process.dlopen(handle, addon); - return { nativeProcess: handle.exports }; -}); -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 { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; -import { agentTeamOverview } from '../src/solver/agentTeamViews'; -import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; -import { directSolverModules } from '../src/solver/modules'; -import { readSolverProblem } from '../src/solver/problem'; -import { personalExpertCardsDigest } from '../src/solver/personalExperts'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { deferred } from './helpers/async'; -import { temporaryDirectory } from './helpers/files'; -import { solverState } from './helpers/solver'; -import { createWebWorkerBridge } from '../apps/web/workerBridge'; - -vi.mock('../src/math/mathBuildManifest', async importOriginal => ({ - ...(await importOriginal()), - readMathBuildManifest: vi.fn(), -})); - -type Json = Record; -const fixtures: ReturnType[] = []; -const ROOT = '00000000-0000-4000-8000-000000000001'; - -/** Only model execution is controlled; task state, worktree isolation, source freezing and Lean checks are real. */ -function fixture({ - earlyCompletion = false, - beforeOpen, - beforeVerification, - emit = () => {}, -}: { - earlyCompletion?: boolean; - beforeOpen?: () => Promise; - beforeVerification?: () => Promise; - emit?: (name: string, payload: Json) => void; -} = {}) { - const directory = temporaryDirectory('native-team-lifecycle-'), - root = path.resolve('.'); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { - task: 'Prove the frozen statement.', - source: 'namespace NativeTeam\ntheorem original : True := by sorry\nend NativeTeam\n', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, receipt.workspaceRoot, { - runId: 'native-team-lifecycle', - phase: 'running', - environmentDigest: mathDigest('Lean standard environment'), - model: 'unused', - effort: 'high', - researchMode: 'skill', - researchSkillWorkflow: 'full', - researchSkill: identity, - researchDelegation: { mode: 'team', maxAgents: 3 }, - workerCount: 1, - coordination: 'independent', - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - requestUsageAccounting: { startedRequests: 0, reportedRequests: 0, pendingRequests: 0, incomplete: false }, - }); - const skill = prepareResearchSkill(root, state.worktree, identity, problem); - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - const environment = { - PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - ELAN_HOME: path.join(os.homedir(), '.elan'), - LEAN_PATH: '', - LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env'), - }; - const controller = new AbortController(); - const sessions: { - session: MathAgentSession; - options: MathAgentOptions; - started: ReturnType; - outcome: ReturnType>; - stopGate: ReturnType; - native: (operation: string, payload: Json) => Promise; - complete: (stop?: boolean) => Promise; - inputs: Json[]; - turnId: string; - message?: string; - id: string; - }[] = []; - const modules = { - ...directSolverModules, - M1: { - ...directSolverModules.M1, - open: async (options: MathAgentOptions) => { - await beforeOpen?.(); - const config = options.nativeAgentControl!; - const threadId = options.threadId ?? String(config.bootstrap!.threadId); - const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!, - turnId = crypto.randomUUID(); - const agentPath = '/root/' + id; - const info = { - sessionId: ROOT, - agent: { threadId, metadata: { agentId: threadId, agentPath }, status: 'pending_init' }, - configSnapshot: { cwd: options.workspace }, - }; - const inputs: Json[] = []; - const connection: NativeAgentControlConnection = { - info, - request: vi.fn(async () => ({})), - update: vi.fn(async value => ({ acceptedSequence: value.sequence })), - input: vi.fn(async value => { - inputs.push(value); - return { accepted: true, threadId, submissionId: turnId, turn: { id: turnId } }; - }), - }; - const native = async (operation: string, payload: Json) => - config.request( - { version: 1, sessionId: ROOT, threadId, operationId: crypto.randomUUID(), operation, payload }, - connection, - { signal: new AbortController().signal }, - ); - await native('attach', { threadId, sessionId: ROOT }); - await config.bound?.(connection); - const started = deferred(), - outcome = deferred(), - stopGate = deferred(); - let settled = false, - didRun = false; - const abort = () => { - outcome.resolve('interrupted'); - stopGate.resolve(); - }; - options.signal?.addEventListener('abort', abort, { once: true }); - const session: MathAgentSession = { - threadId, - nativeAgentControl: connection, - usageSource: 'upstream-requests', - nativeConfiguration: { - source: 'thread-start-overrides', - overrides: { - includeSkillInstructions: false, - deferMailboxPreemption: true, - rootAgentUsageHintText: '', - subagentUsageHintText: '', - }, - }, - get lastCompletedResponse() { - return settled ? { turnId, text: 'Saved an advisory research result.' } : undefined; - }, - run: async (message, _messageId, _workspace, onStarted) => { - didRun = true; - current.message = message; - await native('admitTurn', { threadId, turnId }); - if (earlyCompletion) { - await native('turnFinished', { - outcome: { threadId, turnId, status: { completed: 'Finished before input receipt.' } }, - }); - outcome.resolve('completed'); - stopGate.resolve(); - } - onStarted(turnId); - started.resolve(); - try { - return await outcome.promise; - } finally { - settled = true; - } - }, - interrupt: async () => { - abort(); - }, - stopForFreeze: async () => { - if (!didRun) return { status: 'stopped' }; - await stopGate.promise; - return settled ? { status: 'stopped' } : { status: 'unconfirmed', reason: 'turn-not-settled' }; - }, - close: async () => { - options.signal?.removeEventListener('abort', abort); - await config.disconnected?.(connection); - }, - }; - const current = { - session, - options, - started, - outcome, - stopGate, - inputs, - turnId, - native, - id, - message: undefined as string | undefined, - complete: async (stop = true) => { - await native('turnFinished', { outcome: { threadId, turnId, status: { completed: 'Advisory result.' } } }); - outcome.resolve('completed'); - if (stop) stopGate.resolve(); - }, - }; - sessions.push(current); - return session; - }, - }, - }; - const team = new AgentResearchTeam({ - state, - root, - taskText: 'Prove the frozen statement.', - leadAccess: { - environment, - retrievalRoot: path.join(state.worktree, problem.projectRelative), - researchSkill: skill, - }, - modules, - executable: 'offline-fixture', - profile: 'offline-fixture', - signal: controller.signal, - maxAgents: 3, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save: () => writeSolverRunState(path.join(directory, 'state.json'), state), - emit, - exclusiveCheck: async operation => { - await beforeVerification?.(); - return operation(); - }, - }); - const rootOptions = team.nativeAgentControlOptions()!; - const rootConnection: NativeAgentControlConnection = { - info: { - sessionId: ROOT, - agent: { threadId: ROOT, metadata: { agentId: ROOT, agentPath: '/root' }, status: 'running' }, - configSnapshot: { cwd: state.worktree }, - }, - request: vi.fn(async () => ({})), - update: vi.fn(async value => ({ acceptedSequence: value.sequence })), - input: vi.fn(async () => ({})), - }; - const native = ( - operation: string, - payload: Json, - operationId = crypto.randomUUID(), - signal = new AbortController().signal, - ) => - rootOptions.request( - { version: 1, sessionId: ROOT, threadId: ROOT, operation, operationId, payload }, - rootConnection, - { signal }, - ); - let toolCalls = 0; - const tool = (operation: Json, actor = 'lead', channel = team) => - channel.tools(actor).call('theoremos_team', operation, { - threadId: - actor === 'lead' ? ROOT : state.agentTeam!.workers.find(worker => worker.id === actor)!.native!.threadId, - turnId: actor === 'lead' ? 'root-turn' : sessions.findLast(item => item.id === actor)!.turnId, - callId: 'tool-' + ++toolCalls, - signal: controller.signal, - }) as Promise; - const spawn = async ( - name: string, - message = 'Profiles: D006, prover\nInvestigate a complementary helper.', - signal?: AbortSignal, - messageKind: 'plaintext' | 'encrypted' = 'plaintext', - initialHistory?: unknown, - ) => { - await native('attach', { threadId: ROOT, sessionId: ROOT }); - await rootOptions.bound?.(rootConnection); - const source = { subagent: { thread_spawn: { parent_thread_id: ROOT, agent_path: '/root/' + name, depth: 1 } } }; - return native( - 'spawn', - { - caller: ROOT, - source, - bootstrap: { - version: 1, - sessionId: ROOT, - threadId: null, - source, - config: { cwd: state.worktree, model: state.model, reasoningEffort: state.effort }, - ...(initialHistory === undefined ? {} : { initialHistory }), - }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: messageKind, text: message } }, - startOptions: { parentTurnId: 'root-turn' }, - }, - crypto.randomUUID(), - signal, - ); - }; - const f = { - directory, - state, - team, - sessions, - controller, - native, - tool, - spawn, - source: (worktree: string) => path.join(worktree, problem.projectRelative, 'Submission.lean'), - }; - fixtures.push(f); - return f; -} - -afterEach(async () => { - for (const f of fixtures.splice(0)) { - f.controller.abort(); - for (const session of f.sessions) { - session.outcome.resolve('interrupted'); - session.stopGate.resolve(); - } - await f.team.close().catch(error => { - if (!f.state.agentTeam!.workers.some(worker => worker.writerStopUnconfirmed)) throw error; - }); - fs.rmSync(f.directory, { recursive: true, force: true }); - } -}); - -describe('native AgentControl preserves the mathematical team lifecycle', () => { - it('projects native activity, finding-based dispatch, and stable checked delivery and adoption evidence', async () => { - const f = fixture(), - output = path.join(f.directory, 'view.json'); - const stateFile = output + '.runtime/state.json'; - fs.mkdirSync(path.dirname(stateFile)); - const bridge = createWebWorkerBridge({ webRunId: 'web-native-team', output, directory: f.directory }); - const capture = async () => { - writeSolverRunState(stateFile, f.state); - return (await bridge.capture()).observation; - }; - expect((await capture()).inspection.nativeTeam).toMatchObject({ memberCount: 0, tasks: [], findings: [] }); - await f.spawn('producer', 'Prove the helper.'); - const [producer] = f.state.agentTeam!.workers; - const producerTask = producer!.tasks[0]!, - session = f.sessions[0]!; - expect((await capture()).inspection.nativeTeam?.tasks).toMatchObject([{ id: producerTask.id, status: 'running' }]); - const sent = await session.native('send', { - caller: producer!.native!.threadId, - target: { kind: 'id', threadId: ROOT }, - input: { - kind: 'message', - mode: 'queueOnly', - message: { kind: 'plaintext', text: 'Use the candidate hypothesis True.' }, - }, - }); - const ref = 'message:' + sent.result.submissionId; - const received = (await capture()).inspection.nativeTeam!; - expect(received.findings).toContainEqual( - expect.objectContaining({ ref, from: 'producer', to: 'lead', status: 'accepted' }), - ); - expect(received.tasks[0]!.reassignment).toBeUndefined(); - await f.spawn('consumer', 'Profiles: engineer\nBased on: ' + ref + '\nTest the consumer with the proposed input.'); - const [, consumer] = f.state.agentTeam!.workers; - const consumerTask = consumer!.tasks[0]!, - originalThread = consumer!.native!.threadId; - expect( - (await capture()).inspection.nativeTeam?.tasks.find(task => task.id === consumerTask.id)?.reassignment, - ).toEqual({ ref, revision: 1 }); - const source = fs - .readFileSync(f.source(producer!.worktree), 'utf8') - .replace('theorem original', 'theorem helper : True := by trivial\ntheorem original'); - fs.writeFileSync(f.source(producer!.worktree), source); - await f.tool( - { - operation: 'submit', - summary: 'The helper is ready.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.helper', type: 'True' }], - }, - 'producer', - ); - expect((await capture()).inspection.nativeTeam?.tasks.find(task => task.id === producerTask.id)?.status).toBe( - 'stopping', - ); - await session.complete(); - await expect.poll(() => f.state.agentTeam!.deliveries.length, { timeout: 30_000 }).toBe(1); - const first = await capture(), - delivered = first.inspection.nativeTeam!.deliveries[0]!; - expect(delivered).toMatchObject({ - taskId: producerTask.id, - proof: { - sources: [{ file: 'Submission.lean', source }], - declarations: [{ name: 'NativeTeam.helper', receipts: [{ status: 'kernel_verified' }] }], - }, - }); - const draft = 'theorem downstream : True := by exact helper\n'; - fs.writeFileSync( - f.source(consumer!.worktree), - fs.readFileSync(f.source(consumer!.worktree), 'utf8').replace('end NativeTeam', draft + 'end NativeTeam'), - ); - expect(await f.tool({ operation: 'yield', reason: 'Waiting for helper.' }, 'consumer')).toMatchObject({ ok: true }); - await f.sessions.find(item => item.id === 'consumer')!.complete(); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); - expect(consumerTask.status).toBe('paused'); - expect(await f.tool({ operation: 'adopt', deliveryId: delivered.id, targetId: 'consumer' })).toMatchObject({ - ok: true, - }); - const adoption = f.state.agentTeam!.adoptions.at(-1)!; - await expect.poll(() => ['completed', 'failed'].includes(adoption.status), { timeout: 30_000 }).toBe(true); - expect(adoption.status, adoption.error).toBe('completed'); - const latest = await capture(); - expect(latest.sequence).toBeGreaterThan(first.sequence); - expect(latest.inspection.nativeTeam!.deliveries[0]).toEqual(delivered); - expect(latest.inspection.nativeTeam!.adoptions[0]).toMatchObject({ - targetId: 'consumer', - deliveryId: delivered.id, - status: 'completed', - receiptId: expect.any(String), - proof: { sources: [{ source: expect.stringContaining(draft) }] }, - }); - // The same delivery and commit do not prove adoption in another member's worktree. - adoption.targetId = 'producer'; - const otherMember = (await capture()).inspection.nativeTeam!.adoptions[0]!; - expect(otherMember.proof).toBeUndefined(); - expect(otherMember.receiptId).toBeUndefined(); - adoption.targetId = 'consumer'; - // Older completed records use the same finalized receipt, found via the persisted checked intent. - f.state.agentTeam!.adoptions[0]!.receiptId = undefined; - expect((await capture()).inspection.nativeTeam!.adoptions[0]).toEqual(latest.inspection.nativeTeam!.adoptions[0]); - - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: originalThread }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: consumerTask.message } }, - startOptions: {}, - }); - expect(consumer!.native!.threadId).toBe(originalThread); - expect(consumer!.tasks.map(task => task.id)).toEqual([consumerTask.id]); - const resumed = fs.readFileSync(f.source(consumer!.worktree), 'utf8'); - expect(resumed).toContain(draft); - expect(resumed).toContain('theorem helper : True := by trivial'); - }, 90_000); - - it.each([ - ['fresh', 'New'], - ['unknown', undefined], - ['unknown', { Resumed: {} }], - ])('does not infer parent inspection for %s child history (%j)', async (expected, initialHistory) => { - const f = fixture(), - parent = (f.team.archive.leadExposures = [ - { - deliveryId: 'a'.repeat(64), - taskId: 'draft', - agentId: 'author', - commit: f.state.problem.baseCommit, - kind: 'inspected', - at: '2026-01-01', - }, - { - deliveryId: 'b'.repeat(64), - taskId: 'merged', - agentId: 'author', - commit: f.state.problem.baseCommit, - kind: 'adopted', - at: '2026-01-02', - }, - ]); - await f.spawn('reviewer', 'Review this claim.', undefined, 'plaintext', initialHistory); - const worker = f.team.archive.workers[0]!; - expect(worker.exposures).toEqual([parent[1]]); - expect(worker.native!.spawnHistory).toBe(expected); - const saved = readSolverRunState(path.join(f.directory, 'state.json')); - // Old records have no frozen exposure snapshot; never reconstruct it from later Lead activity. - delete saved.agentTeam!.workers[0]!.native!.spawnHistory; - expect(agentTeamOverview(saved).workers[0]?.nativeIdentity?.spawnHistory).toBe('unknown'); - }); - it.each([ - ['Profiles: lead', /math_team_profile_reserved/], - ['Profiles: , ', /math_team_profile_unresolved: empty Profiles: header/], - ['Profiles: asset:unselected', /math_team_profile_unresolved: .*asset:unselected/], - [ - 'Profiles: prover (Lean prover, Mathlib).', - /math_team_profile_unresolved: .*Lean prover.*Mathlib.*Profiles: prover.*body/, - ], - ])('rejects %s before reserving a place or steering a member', async (header, feedback) => { - const f = fixture(), - bad = header + '\nInvestigate the interface.'; - await expect(f.spawn('analyst', bad)).rejects.toThrow(feedback); - expect(f.state.agentTeam!.workers).toHaveLength(0); - expect(f.sessions).toHaveLength(0); - await f.spawn('analyst', 'Profiles: prover\nUse your Mathlib expertise to check the interface.'); - const worker = f.state.agentTeam!.workers[0], - task = worker.tasks[0]; - await expect( - f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: bad } }, - startOptions: {}, - }), - ).rejects.toThrow(feedback); - expect(task.objectiveRevision).toBe(1); - expect(task.profileEvidence?.loaded).toEqual(['prover']); - expect(f.sessions[0].inputs).toHaveLength(0); - }); - - it('accepts the upstream Direct encrypted message shape for spawn and new-task followup without changing codec or attribution', async () => { - const f = fixture(), - message = 'Profiles: D006, prover\nNATIVE_WORKER_TEST Read the fixed skill and inspect the fixture.'; - await f.spawn('analyst', message, undefined, 'encrypted'); - const worker = f.state.agentTeam!.workers[0]; - expect(worker.tasks[0].message).toBe(message); - expect(worker.tasks[0].profileEvidence?.loaded).toEqual(expect.arrayContaining(['D006', 'prover'])); - expect(f.sessions[0].options.nativeAgentControl!.initialInput).toMatchObject({ - author: '/root', - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'encrypted', text: message } }, - startOptions: { parentTurnId: 'root-turn' }, - }); - await f.sessions[0].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const followup = 'Profiles: engineer\nNATIVE_FOLLOWUP_TEST Inspect the next interface.'; - const input = { kind: 'message', mode: 'triggerTurn', message: { kind: 'encrypted', text: followup } }; - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input, - startOptions: { parentTurnId: 'root-followup-turn', initiatingAgentPath: '/root' }, - }); - expect(worker.tasks).toHaveLength(2); - expect(worker.tasks[1].message).toBe(followup); - expect(f.sessions[1].options.nativeAgentControl!.initialInput).toEqual({ - author: '/root', - input, - startOptions: { parentTurnId: 'root-followup-turn', initiatingAgentPath: '/root' }, - }); - }); - - it('reaps an unaccepted spawn and does not relaunch it from a queued task after cancellation', async () => { - const opening = deferred(), - f = fixture({ beforeOpen: () => opening.promise }), - caller = new AbortController(); - const spawn = f.spawn('analyst', undefined, caller.signal); - void spawn.catch(() => {}); - await expect.poll(() => f.state.agentTeam!.workers.length).toBe(1); - caller.abort(new Error('parent-cancelled-before-acceptance')); - opening.resolve(); - await expect(spawn).rejects.toThrow(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const worker = f.state.agentTeam!.workers[0]; - expect(worker.status).toBe('stopped'); - expect(worker.native!.submissionId).toBeUndefined(); - expect(worker.tasks[0].status).toBe('cancelled'); - expect(worker.writerStopUnconfirmed).toBeUndefined(); - }); - - it('rejects a late spawn when the run has stopped before a worker is scheduled', async () => { - const f = fixture(); - f.controller.abort(new Error('run-stopped')); - const spawn = f.spawn('analyst').then( - () => 'accepted', - error => (error as Error).message, - ); - const nextTick = new Promise(resolve => setImmediate(() => resolve('still pending'))); - expect(await Promise.race([spawn, nextTick])).toBe('math_team_dispatch_stopped'); - expect(f.state.agentTeam!.workers).toEqual([]); - expect(f.sessions).toEqual([]); - }); - - it('releases the failed startup seat for other native assignments', async () => { - let opens = 0; - const f = fixture({ - beforeOpen: async () => { - if (++opens === 1) throw new Error('worker-start-failed'); - }, - }); - await expect(f.spawn('broken')).rejects.toThrow(); - await f.spawn('analyst'); - await expect(f.spawn('prover')).resolves.toMatchObject({ - result: { agent: { metadata: { agentPath: '/root/prover' } } }, - }); - expect(f.state.agentTeam!.workers[0]).toMatchObject({ - status: 'stopped', - tasks: [{ status: 'failed', error: 'worker-start-failed' }], - }); - }); - - it('holds the seat and the workspace when a failed startup could not confirm writer shutdown', async () => { - let opens = 0; - const f = fixture({ - beforeOpen: async () => { - if (++opens === 1) throw new Error('math_codex_startup_shutdown_unconfirmed'); - }, - }); - await expect(f.spawn('broken')).rejects.toThrow(); - const worker = f.state.agentTeam!.workers[0]; - expect(worker.writerStopUnconfirmed).toMatchObject({ reason: 'math_codex_startup_shutdown_unconfirmed' }); - expect(worker.tasks[0].researchArtifactId).toBeUndefined(); - expect( - readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0].writerStopUnconfirmed, - ).toEqual(worker.writerStopUnconfirmed); - await f.spawn('analyst'); - await expect(f.spawn('prover')).rejects.toThrow('math_team_capacity_exceeded'); - await expect(f.team.restore()).rejects.toThrow('math_writer_stop_unconfirmed:broken'); - }); - - it('rejects a followup promptly while the previous writer is still stopping', async () => { - const f = fixture(); - await f.spawn('analyst'); - const worker = f.state.agentTeam!.workers[0]!, - session = f.sessions[0]!; - await session.complete(false); - await expect.poll(() => worker.activity).toBe('stopping'); - await expect( - f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue the work.' } }, - }), - ).rejects.toThrow('math_team_native_member_busy'); - expect(worker.tasks).toHaveLength(1); - expect(f.sessions).toHaveLength(1); - session.stopGate.resolve(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - }); - - it('keeps the member mailbox available while a Lean delivery check runs', async () => { - const checking = deferred(), - finishCheck = deferred(); - const f = fixture({ - beforeVerification: () => { - checking.resolve(); - return finishCheck.promise; - }, - }); - try { - await f.spawn('analyst'); - const worker = f.state.agentTeam!.workers[0]!, - prior = f.sessions[0]!; - fs.writeFileSync( - f.source(worker.worktree), - fs - .readFileSync(f.source(worker.worktree), 'utf8') - .replace('end NativeTeam', 'theorem reusable (n : Nat) : n = n := by rfl\nend NativeTeam'), - ); - expect( - await f.tool( - { - operation: 'submit', - summary: 'A useful helper.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.reusable', type: '∀ n : Nat, n = n' }], - }, - worker.id, - ), - ).toMatchObject({ status: 'pending-writer-stop' }); - await prior.complete(); - await checking.promise; - expect(worker.activity).toBe('checking'); - const target = { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId } }; - const send = (mode: 'queueOnly' | 'triggerTurn', text: string) => - f.native('send', { - ...target, - input: { kind: 'message', mode, message: { kind: 'plaintext', text } }, - }); - const followup = send('triggerTurn', 'Investigate a new gap.'); - const message = send('queueOnly', 'Save this advisory update for later.'); - await expect(followup).rejects.toThrow('math_team_native_member_busy'); - const response = await message; - expect(f.team.archive.nativeControl!.mailbox).toContainEqual( - expect.objectContaining({ - id: response.result.submissionId, - status: 'queued', - }), - ); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(worker.tasks).toHaveLength(1); - finishCheck.resolve(); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); - expect(f.team.archive.deliveries).toHaveLength(1); - await send('triggerTurn', 'Investigate a new gap.'); - expect(worker.tasks).toHaveLength(2); - } finally { - finishCheck.resolve(); - } - }, 40_000); - - it('answers a followup at once while an idle member integrates checked helpers, then reports readiness to Lead', async () => { - let gate: ReturnType | undefined; - const waiting = deferred(); - const f = fixture({ - beforeVerification: async () => { - if (gate) { - waiting.resolve(); - await gate.promise; - } - }, - }); - try { - await f.spawn('analyst'); - const analyst = f.state.agentTeam!.workers[0]!; - await f.sessions[0]!.complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - await f.spawn('prover'); - const prover = f.state.agentTeam!.workers[1]!; - fs.writeFileSync( - f.source(prover.worktree), - fs - .readFileSync(f.source(prover.worktree), 'utf8') - .replace('end NativeTeam', 'theorem reusable (n : Nat) : n = n := by rfl\nend NativeTeam'), - ); - expect( - await f.tool( - { - operation: 'submit', - helpersOnly: true, - summary: 'A useful helper.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.reusable', type: '∀ n : Nat, n = n' }], - }, - prover.id, - ), - ).toMatchObject({ status: 'pending-writer-stop' }); - await f.sessions[1]!.complete(); - await expect - .poll(() => f.team.archive.deliveries.some(item => item.kind === 'helpers'), { timeout: 30_000 }) - .toBe(true); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); - gate = deferred(); - const followup = () => - f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: analyst.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Use the helper for the next step.' }, - }, - }); - // Lead's tool call does not wait for the member's Lean integration. - await expect(followup()).rejects.toThrow('math_team_native_member_busy'); - await waiting.promise; - expect(analyst.activity).toBe('integrating'); - expect(analyst.tasks).toHaveLength(1); - expect(f.sessions).toHaveLength(2); - await expect(followup()).rejects.toThrow('math_team_native_member_busy'); - gate.resolve(); - await expect - .poll( - () => - f.team.archive.events.some( - event => - event.to === 'lead' && - event.kind === 'message' && - event.text.startsWith('analyst finished integrating'), - ), - { timeout: 30_000 }, - ) - .toBe(true); - expect(f.team.archive.adoptions).toContainEqual( - expect.objectContaining({ targetId: 'analyst', status: 'completed' }), - ); - await followup(); - expect(analyst.tasks).toHaveLength(2); - expect(f.sessions).toHaveLength(3); - } finally { - gate?.resolve(); - } - }, 60_000); - - it.each([ - ['standalone helper', true], - ['proof delivery', false], - ] as const)( - 'installs a standalone prerequisite before an explicitly queued dependent %s on the first flush', - async (_kind, helpersOnly) => { - const f = fixture(), - leadSource = f.source(f.state.worktree); - const initialSource = fs.readFileSync(leadSource, 'utf8'); - const prerequisite = 'theorem prerequisite : True := by trivial\n'; - const downstream = 'theorem downstream : True := by exact prerequisite\n'; - const submit = async (agentId: string, name: string, source: string, standalone: boolean) => { - await f.spawn(agentId, 'Prove and share NativeTeam.' + name + '.'); - const worker = f.team.archive.workers.find(item => item.id === agentId)!; - const file = f.source(worker.worktree); - fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace('theorem original', source + 'theorem original')); - expect( - await f.tool( - { - operation: 'submit', - helpersOnly: standalone, - summary: 'Checked declaration ' + name, - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.' + name, type: 'True' }], - }, - agentId, - ), - ).toMatchObject({ status: 'pending-writer-stop' }); - await f.sessions.at(-1)!.complete(); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); - const reference = f.team.archive.deliveries.find(item => item.agentId === agentId); - expect(reference).toBeDefined(); - expect(reference!.kind).toBe(standalone ? 'helpers' : undefined); - return { reference: reference!, evidence: readAgentTeamProofDelivery(reference!.path, f.state) }; - }; - - const first = await submit('producer', 'prerequisite', prerequisite, true); - const second = await submit('consumer', 'downstream', downstream, helpersOnly); - expect(second.evidence.declarations.map(item => item.name)).toEqual(['NativeTeam.downstream']); - expect(second.evidence.artifacts[0]!.references?.proof).toContainEqual({ - file: 'Submission.lean', - name: 'NativeTeam.prerequisite', - }); - expect(fs.readFileSync(leadSource, 'utf8')).toBe(initialSource); - expect(await f.tool({ operation: 'adopt', deliveryId: second.reference.id })).toMatchObject({ - ok: true, - adoption: { targetId: 'lead', status: 'queued' }, - }); - - const priorEvents = f.team.archive.events.length; - await f.team.flushAdoptions(); - const leadEvents = f.team.archive.events.slice(priorEvents).filter(event => event.to === 'lead'); - expect(leadEvents.map(({ kind, deliveryId }) => [kind, deliveryId])).toEqual([ - ['adopted', first.reference.id], - ['adopted', second.reference.id], - ]); - expect(fs.readFileSync(leadSource, 'utf8')).toBe( - initialSource.replace('theorem original', prerequisite + downstream + 'theorem original'), - ); - }, - 60_000, - ); - - it.each([ - ['standalone helper', true], - ['proof delivery', false], - ] as const)( - 'closes a submitted sorry helper with the host tactic battery before the ordinary %s check', - async (_kind, helpersOnly) => { - const emitted: Json[] = []; - const f = fixture({ - emit: (name, payload) => { - if (name === 'task_tactic_battery') emitted.push(payload); - }, - }); - await f.spawn('prover', 'Prove and share NativeTeam.shifted.'); - const worker = f.team.archive.workers[0]!, - file = f.source(worker.worktree); - fs.writeFileSync( - file, - fs - .readFileSync(file, 'utf8') - .replace('theorem original', 'theorem shifted (n : Nat) : n + 0 = n := by sorry\ntheorem original'), - ); - expect( - await f.tool( - { - operation: 'submit', - helpersOnly, - summary: 'Helper with an open body.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.shifted', type: '∀ n : Nat, n + 0 = n' }], - }, - 'prover', - ), - ).toMatchObject({ status: 'pending-writer-stop' }); - await f.sessions[0]!.complete(); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); - expect(emitted).toEqual([ - expect.objectContaining({ - workerId: 'prover', - declaration: 'NativeTeam.shifted', - status: 'closed', - applied: true, - }), - ]); - const source = fs.readFileSync(file, 'utf8'); - expect(source).toContain('theorem shifted (n : Nat) : n + 0 = n := by first |'); - expect(source.match(/sorry/gu)).toHaveLength(1); // only the untouched original statement - expect(f.team.archive.events).toContainEqual( - expect.objectContaining({ - to: 'prover', - kind: 'message', - text: expect.stringContaining('host tactic battery closed the sorry in NativeTeam.shifted'), - }), - ); - const delivery = f.team.archive.deliveries.find(item => item.agentId === 'prover'); - expect(delivery?.kind).toBe(helpersOnly ? 'helpers' : undefined); - expect(readAgentTeamProofDelivery(delivery!.path, f.state).declarations.map(item => item.name)).toContain( - 'NativeTeam.shifted', - ); - }, - 90_000, - ); - - it('leaves a submitted sorry helper unchanged when the host tactic battery cannot close it', async () => { - const emitted: Json[] = []; - const f = fixture({ - emit: (name, payload) => { - if (name === 'task_tactic_battery') emitted.push(payload); - }, - }); - await f.spawn('prover', 'Prove and share NativeTeam.wrong.'); - const worker = f.team.archive.workers[0]!, - file = f.source(worker.worktree); - fs.writeFileSync( - file, - fs - .readFileSync(file, 'utf8') - .replace('theorem original', 'theorem wrong (n : Nat) : n = n + 1 := by sorry\ntheorem original'), - ); - const before = fs.readFileSync(file, 'utf8'); - expect( - await f.tool( - { - operation: 'submit', - helpersOnly: true, - summary: 'Helper with an open body.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.wrong', type: '∀ n : Nat, n = n + 1' }], - }, - 'prover', - ), - ).toMatchObject({ status: 'pending-writer-stop' }); - await f.sessions[0]!.complete(); - await expect.poll(() => emitted.length, { timeout: 90_000 }).toBe(1); - expect(emitted[0]).toMatchObject({ declaration: 'NativeTeam.wrong', status: 'failed', applied: false }); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); - expect(fs.readFileSync(file, 'utf8')).toBe(before); - expect(f.team.archive.deliveries.filter(item => item.agentId === 'prover')).toEqual([]); - }, 150_000); - - it('installs an ordinary prerequisite in an older member before retrying its dependent helper', async () => { - const f = fixture(); - await f.spawn('consumer'); - await f.sessions[0]!.complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const consumerSource = f.source(f.team.archive.workers[0]!.worktree); - const initialSource = fs.readFileSync(consumerSource, 'utf8'); - - await f.spawn('producer'); - const producer = f.team.archive.workers[1]!; - const producerSource = f.source(producer.worktree); - const prerequisite = 'theorem prerequisite : True := by trivial\n'; - const downstream = 'theorem downstream : True := by exact prerequisite\n'; - const submit = async (name: string, source: string, helpersOnly: boolean) => { - fs.writeFileSync( - producerSource, - fs.readFileSync(producerSource, 'utf8').replace('theorem original', source + 'theorem original'), - ); - expect( - await f.tool( - { - operation: 'submit', - helpersOnly, - summary: 'Publish ' + name, - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.' + name, type: 'True' }], - }, - producer.id, - ), - ).toMatchObject({ status: 'pending-writer-stop' }); - await f.sessions.at(-1)!.complete(); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); - return f.team.archive.deliveries.at(-1)!; - }; - const first = await submit('prerequisite', prerequisite, false); - expect(first.kind).toBeUndefined(); - await f.tool({ operation: 'adopt', deliveryId: first.id }); - await f.team.flushAdoptions(); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain(prerequisite); - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: producer.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Share the consequence as a standalone helper.' }, - }, - }); - const second = await submit('downstream', downstream, true); - expect(second.kind).toBe('helpers'); - expect(fs.readFileSync(consumerSource, 'utf8')).toBe(initialSource); - - const priorEvents = f.team.archive.events.length; - expect(await f.tool({ operation: 'adopt', deliveryId: first.id, targetId: 'consumer' })).toMatchObject({ - ok: true, - }); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); - const events = f.team.archive.events.slice(priorEvents).filter(event => event.deliveryId); - expect(events.map(({ to, kind, deliveryId }) => [to, kind, deliveryId])).toEqual([ - ['consumer', 'adopted', first.id], - ['consumer', 'adopted', second.id], - ]); - expect(fs.readFileSync(consumerSource, 'utf8')).toBe( - initialSource.replace('theorem original', prerequisite + downstream + 'theorem original'), - ); - }, 60_000); - - it('keeps a child accepted by the host when its initiating request is subsequently cancelled', async () => { - const f = fixture(), - caller = new AbortController(); - await f.spawn('analyst', undefined, caller.signal); - caller.abort(new Error('parent-cancelled-after-acceptance')); - const worker = f.state.agentTeam!.workers[0]; - expect(worker.status).toBe('running'); - expect(worker.tasks[0].cancelRequested).toBeUndefined(); - expect(worker.native!.submissionId).toBe(f.sessions[0].turnId); - expect(f.team.hasActiveWorkers).toBe(true); - }); - - it('preserves an exact terminal result arriving before the spawn/input acceptance callback', async () => { - const f = fixture({ earlyCompletion: true }); - const receipt = await f.spawn('analyst'); - expect((receipt.result as Json).agent.status).toEqual({ completed: 'Finished before input receipt.' }); - const native = f.state.agentTeam!.workers[0].native!; - expect(native.lastOutcome).toEqual({ - turnId: f.sessions[0].turnId, - status: { completed: 'Finished before input receipt.' }, - }); - expect(native.status).toEqual({ completed: 'Finished before input receipt.' }); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(f.state.agentTeam!.deliveries).toEqual([]); - }); - - it('starts distinct isolated native writers, loads expertise and steers a busy member without a new task', async () => { - const f = fixture(); - const first = await f.spawn('analyst'), - second = await f.spawn('engineer', 'Profiles: engineer\nCheck the local source interface.'); - const workers = f.state.agentTeam!.workers; - expect((first.result as Json).agent.threadId).not.toBe((second.result as Json).agent.threadId); - expect(workers[0].worktree).not.toBe(workers[1].worktree); - expect(f.sessions[0].options).toMatchObject({ - isolateProcess: true, - workspace: workers[0].worktree, - nativeAgentControl: { - bootstrap: { - threadId: workers[0].native!.threadId, - hostOverrides: { - cwd: workers[0].worktree, - workspaceRelocation: { from: f.state.worktree, to: workers[0].worktree }, - }, - }, - }, - }); - expect(f.sessions[0].message).toContain('Investigate a complementary helper.'); - expect(workers[0].native!.runtimeConfiguration).toEqual(f.sessions[0].session.nativeConfiguration); - expect(workers[0].tasks[0].profileEvidence?.loaded).toEqual(expect.arrayContaining(['D006', 'prover'])); - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: workers[0].native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Consider this advisory observation.' }, - }, - startOptions: {}, - }); - expect(f.sessions).toHaveLength(2); - expect(workers[0].tasks).toHaveLength(1); - expect(workers[0].tasks[0].objectiveRevision).toBe(2); - expect(workers[0].tasks[0].message).toContain('Consider this advisory observation.'); - expect(workers[0].tasks[0].profileEvidence?.loaded).toEqual(expect.arrayContaining(['D006', 'prover'])); - expect(workers[0].tasks[0].objectiveHistory?.[0]?.revision).toBe(1); - expect(f.sessions[0].inputs).toMatchObject([{ author: '/root', threadId: workers[0].native!.threadId }]); - expect(f.sessions[0].inputs[0]).not.toHaveProperty('contextItems'); - expect( - await f.tool({ operation: 'spawn', agentId: 'shadow', message: 'Attempt an obsolete transport.' }), - ).toMatchObject({ ok: false }); - }); - - it('delivers the new specialty in the attributed busy input and records it only after acceptance', async () => { - const f = fixture(); - await f.spawn('analyst'); - const worker = f.state.agentTeam!.workers[0], - task = worker.tasks[0], - session = f.sessions[0]; - const cards = [ - { - assetId: 'ideal', - name: 'User expert on ideals', - version: '1', - digest: 'b'.repeat(64), - summary: 'Fractional ideals', - knowledge: 'Observe the hypotheses of the chosen factorization law.', - }, - ]; - f.state.researchDelegation = { - mode: 'team', - maxAgents: 3, - personalExperts: { cards, digest: personalExpertCardsDigest(cards) }, - }; - const text = 'Profiles: D012, engineer, asset:ideal\nCheck the ideal factorization interface.'; - const input = { kind: 'message', mode: 'triggerTurn', message: { kind: 'encrypted', text } }; - const startOptions = { initiatingAgentPath: '/root', parentTurnId: 'root-followup' }; - const send = () => - f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input, - startOptions, - }); - vi.mocked(session.session.nativeAgentControl!.input).mockResolvedValueOnce({ accepted: false }); - await expect(send()).rejects.toThrow('math_team_native_input_not_accepted'); - expect(task.objectiveRevision).toBe(1); - expect(task.profileEvidence?.loaded).toEqual(['D006', 'prover']); - await send(); - expect(f.sessions).toHaveLength(1); - expect(session.inputs[0]).toMatchObject({ author: '/root', input, startOptions, expectedTurnId: session.turnId }); - const passage = session.inputs[0].contextItems[0].content[0].text; - expect(passage).toContain('The ideal class group measures the obstruction to principality'); - expect(passage).toContain( - path.join(path.dirname(session.options.skills![0].path), 'references/domain-materials/number-theory.md'), - ); - expect(passage).toContain('Profile engineer'); - expect(passage).toContain(cards[0].knowledge); - expect(task.message).toBe(text); - expect(task.profileEvidence?.loaded).toEqual(['D012', 'engineer', 'asset:ideal']); - expect(task.profileEvidence?.sources.find(source => source.kind === 'collected-reading')?.loading).toBe( - 'available-on-demand', - ); - await send(); - expect(session.inputs[1]).not.toHaveProperty('contextItems'); - }); - - it('resumes a yielded draft in the same task with the latest native instruction', async () => { - const f = fixture(); - await f.spawn('analyst'); - const worker = f.state.agentTeam!.workers[0], - task = worker.tasks[0], - first = f.sessions[0]; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'A saved dependency question.\n'); - expect(await f.tool({ operation: 'yield', reason: 'Need a checked dependency.' }, worker.id)).toMatchObject({ - status: 'pending-writer-stop', - }); - await first.complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(task.status).toBe('paused'); - const oldInput = worker.native!.initialInput; - await expect( - f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Profiles: unknown-profile\nContinue the draft.' }, - }, - startOptions: {}, - }), - ).rejects.toThrow('math_team_profile_unresolved'); - expect(worker.native!.initialInput).toEqual(oldInput); - expect(task.status).toBe('paused'); - expect(task.objectiveRevision).toBe(1); - expect(f.sessions).toHaveLength(1); - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'The dependency is now available; continue.' }, - }, - startOptions: { parentTurnId: 'root-turn-2' }, - }); - expect(worker.tasks).toHaveLength(1); - expect(worker.tasks[0]).toBe(task); - expect(task.objectiveRevision).toBe(2); - expect(task.message).toContain('The dependency is now available; continue.'); - expect(task.profileEvidence?.loaded).toEqual(expect.arrayContaining(['D006', 'prover'])); - expect(task.objectiveHistory?.[0]?.message).toContain('Investigate a complementary helper.'); - expect(f.sessions).toHaveLength(2); - expect(f.sessions[1].session.threadId).toBe(first.session.threadId); - expect(f.sessions[1].options.nativeAgentControl!.initialInput).toMatchObject({ - author: '/root', - input: { message: { text: 'The dependency is now available; continue.' } }, - }); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toContain('saved dependency'); - }); - - it('keeps an unchanged handoff paused and accepts new instructions on the same draft', async () => { - const f = fixture(); - const objective = 'Prove the same helper.'; - await f.spawn('analyst', 'Profiles: prover\n' + objective); - const worker = f.state.agentTeam!.workers[0], - task = worker.tasks[0], - first = f.sessions[0]; - expect(await f.tool({ operation: 'yield', reason: 'Waiting for a checked premise.' }, worker.id)).toMatchObject({ - status: 'pending-writer-stop', - }); - await first.complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(task.status).toBe('paused'); - const saved = readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0]!.tasks[0]!; - expect(saved.sourceCommit).toBe(saved.lastStartedSourceCommit); - const followup = (text: string) => - f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } }, - }); - await expect(followup(objective)).rejects.toThrow('math_team_native_followup_unchanged'); - expect(f.sessions).toHaveLength(1); - expect(task).toMatchObject({ status: 'paused', objectiveRevision: 1 }); - await followup('First derive the premise by induction.'); - expect(worker.tasks).toEqual([task]); - expect(task).toMatchObject({ status: 'running', objectiveRevision: 2 }); - }); - - it('can reuse a yielded worker for a different route and return to its original task', async () => { - const f = fixture(); - await f.spawn('analyst', 'Route: initial\nProfiles: prover, D006\nInvestigate the first approach.'); - const worker = f.state.agentTeam!.workers[0], - original = worker.tasks[0]; - expect(original).toMatchObject({ routeId: 'initial', profileEvidence: { selected: ['prover', 'D006'] } }); - expect(await f.tool({ operation: 'yield', reason: 'Awaiting a dependency.' }, worker.id)).toMatchObject({ - status: 'pending-writer-stop', - }); - await f.sessions[0].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const followup = (text: string) => - f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } }, - }); - await followup('Route: other\nProfiles: engineer\nCheck an independent approach while the first waits.'); - expect(worker.tasks).toHaveLength(2); - expect(original.status).toBe('paused'); - expect(worker.tasks[1]).toMatchObject({ - routeId: 'other', - status: 'running', - profileEvidence: { selected: ['engineer'] }, - }); - expect(f.sessions[1].message).toContain('Check an independent approach'); - await f.sessions[1].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - await followup('Route: initial\nThe dependency is ready. Continue the original approach.'); - expect(worker.tasks).toHaveLength(2); - expect(original).toMatchObject({ status: 'running', objectiveRevision: 2 }); - expect(f.sessions[2].message).toContain('Continue the original approach'); - }); - - it('releases an interrupted route for a replacement, retaining the stopped draft', async () => { - const f = fixture(); - await f.spawn('analyst', 'Route: obsolete\nInvestigate the initial route.'); - const worker = f.team.archive.workers[0], - task = worker.tasks[0]; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Partial result.\n'); - await f.native('interrupt', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - version: 'v2', - }); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(task.status).toBe('interrupted'); - const commit = task.sourceCommit; - await f.spawn('peer'); - await expect( - f.tool({ operation: 'retire_route', routeId: 'obsolete', reason: 'Refuted by the saved probe.' }), - ).resolves.toMatchObject({ cancelledTaskIds: [task.id], releasedAgentIds: [worker.id] }); - await f.spawn('replacement'); - expect(task).toMatchObject({ status: 'cancelled', sourceCommit: commit }); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe('Partial result.\n'); - }); - - it('keeps another interrupted route resumable when retiring a paused route', async () => { - const f = fixture(); - await f.spawn('analyst', 'Route: keep\nInvestigate this route.'); - const worker = f.team.archive.workers[0], - target = { kind: 'id', threadId: worker.native!.threadId }; - await f.native('interrupt', { caller: ROOT, target, version: 'v2' }); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const followup = (text: string) => - f.native('send', { - caller: ROOT, - target, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text }, - }, - }); - await followup('Route: obsolete\nExplore another approach.'); - await f.tool({ operation: 'yield', reason: 'Awaiting evidence.' }, worker.id); - await f.sessions[1].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(await f.tool({ operation: 'retire_route', routeId: 'obsolete', reason: 'No longer needed.' })).toMatchObject( - { releasedAgentIds: [] }, - ); - await followup('Continue the remaining approach.'); - expect(worker.tasks.map(task => [task.routeId, task.status])).toEqual([ - ['keep', 'running'], - ['obsolete', 'cancelled'], - ]); - }); - - it('releases a slot left on a retired interrupted assignment by an older checkpoint', async () => { - const f = fixture(); - await f.spawn('analyst', 'Route: obsolete\nInvestigate this route.'); - const worker = f.team.archive.workers[0]; - await f.native('interrupt', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - version: 'v2', - }); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - f.team.archive.retiredRoutes = [{ routeId: 'obsolete', retiredAt: Date.now(), reason: 'Refuted.', source: 'lead' }]; - await f.team.restore(); - expect(worker.status).toBe('stopped'); - expect(worker.tasks[0]).toMatchObject({ status: 'cancelled', cancelRequested: { reason: 'Refuted.' } }); - await f.spawn('peer'); - await f.spawn('replacement'); - }); - - it('dispatches the next preview page without acknowledging a truncated body', async () => { - const f = fixture(); - await f.spawn('analyst'); - await f.sessions[0].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const team = f.team.archive, - worker = team.workers[0], - seq = team.events.at(-1)?.sequence ?? 0; - for (let i = 1; i <= 9; i++) - team.events.push({ - sequence: seq + i, - at: Date.now(), - from: 'lead', - to: worker.id, - kind: 'message', - text: i === 1 ? 'A'.repeat(801) : 'fixed-notice-' + i, - }); - for (let turn = 1; turn <= 2; turn++) { - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Check step ' + turn }, - }, - }); - const message = f.sessions[turn].message; - expect(message).toContain(turn === 1 ? 'fixed-notice-8' : 'fixed-notice-9'); - expect(message).not.toContain(turn === 1 ? 'fixed-notice-9' : 'fixed-notice-8'); - const saved = readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0]; - expect(saved.previewCursor).toBeGreaterThanOrEqual(seq + (turn === 1 ? 8 : 9)); - expect(saved.cursor).toBeLessThan(seq + 1); - await f.sessions[turn].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - } - }); - - it('holds legacy queued routes for reassignment when the checkpoint has only one native input', async () => { - const f = fixture(); - await f.spawn('analyst', 'Route: initial\nInvestigate the first approach.'); - const worker = f.state.agentTeam!.workers[0]; - await f.sessions[0].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - const earlier = { - id: 'queued-earlier', - message: 'First queued approach.', - status: 'queued' as const, - routeId: 'earlier', - }; - const latest = { - id: 'queued-latest', - message: 'Last queued approach.', - status: 'queued' as const, - routeId: 'latest', - }; - worker.tasks.push(earlier, latest); - worker.native!.initialInput = { - author: '/root', - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Route: latest\nLast queued approach.' }, - }, - }; - await f.team.restore(); - expect(worker.tasks.slice(-2).map(task => task.status)).toEqual(['interrupted', 'interrupted']); - expect(f.team.hasActiveWorkers).toBe(false); - expect(f.sessions).toHaveLength(1); - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Route: earlier\nContinue the saved earlier approach.' }, - }, - }); - expect(worker.tasks.find(task => task.id === earlier.id)?.status).toBe('running'); - expect(f.sessions[1].message).toContain('Continue the saved earlier approach'); - }); - - it('returns the pre-interruption observation and retains the member, task and draft for continuation', async () => { - const f = fixture(); - await f.spawn('analyst'); - const worker = f.state.agentTeam!.workers[0], - task = worker.tasks[0]; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Retain this partial argument.\n'); - const snapshot = await f.native('interrupt', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - version: 'v2', - }); - expect(snapshot.result).toMatchObject({ kind: 'loaded', agent: { status: 'running' } }); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(worker.status).toBe('interrupted'); - expect(task.status).toBe('interrupted'); - expect(worker.native!.status).toBe('shutdown'); - expect(worker.native!.agent!.status).toBe('shutdown'); - expect(worker.native!.writerStop).toMatchObject({ source: 'writer-stop', turnId: f.sessions[0].turnId }); - expect(worker.native!.lastOutcome).toBeUndefined(); - const saved = readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0].native!; - expect(saved.status).toBe('shutdown'); - expect(saved.lastOutcome).toBeUndefined(); - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue the saved task.' } }, - startOptions: {}, - }); - expect(worker.tasks).toHaveLength(1); - expect(worker.tasks[0]).toBe(task); - expect(f.sessions[1].session.threadId).toBe(f.sessions[0].session.threadId); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toContain('partial argument'); - // Native admission cannot create a second model turn beside the dispatched writer. - await expect( - f.sessions[1].native('admitTurn', { threadId: worker.native!.threadId, turnId: 'unexpected-second-turn' }), - ).rejects.toThrow('native_turn_not_dispatched'); - }); - - it('does not publish completed native research as proof and waits for writer shutdown before checking a nomination', async () => { - const f = fixture(); - await f.spawn('analyst'); - const worker = f.state.agentTeam!.workers[0]; - await f.sessions[0].complete(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(f.state.agentTeam!.deliveries).toHaveLength(0); - expect(worker.tasks[0].researchArtifactId).toBeTruthy(); - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Profiles: prover\nSave and submit the helper.' }, - }, - startOptions: {}, - }); - expect(worker.tasks).toHaveLength(2); - await f.native('send', { - caller: ROOT, - target: { kind: 'id', threadId: worker.native!.threadId }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { - kind: 'plaintext', - text: 'Profiles: engineer, prover\nCheck this helper against the owned source interface.', - }, - }, - startOptions: {}, - }); - expect(worker.tasks).toHaveLength(2); - expect(worker.tasks[1].objectiveRevision).toBe(2); - expect(worker.tasks[1].profileEvidence?.loaded).toEqual(['engineer', 'prover']); - const draft = fs - .readFileSync(f.source(worker.worktree), 'utf8') - .replace('end NativeTeam', 'theorem reusable (n : Nat) : n = n := by rfl\nend NativeTeam'); - fs.writeFileSync(f.source(worker.worktree), draft); - expect( - await f.tool( - { - operation: 'submit', - summary: 'A useful helper.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.reusable', type: '∀ n : Nat, n = n' }], - }, - worker.id, - ), - ).toMatchObject({ status: 'pending-writer-stop' }); - const second = f.sessions[1]; - await second.complete(false); - expect(f.state.agentTeam!.deliveries).toHaveLength(0); - second.stopGate.resolve(); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); - expect(worker.writerStopUnconfirmed).toBeUndefined(); - expect(f.state.agentTeam!.deliveries).toHaveLength(1); - expect(worker.tasks[1].deliveryId).toBe(f.state.agentTeam!.deliveries[0].id); - expect(f.state.agentTeam!.events.find(event => event.kind === 'delivery')).toMatchObject({ - deliveryId: worker.tasks[1].deliveryId, - text: expect.stringContaining('Lean signature: NativeTeam.reusable (n : Nat) : n = n'), - }); - expect(f.state.phase).toBe('running'); - }, 70_000); - - it('pins a submitted declaration across an in-flight reassignment and an interruption before completion', async () => { - const f = fixture(), - inspected = { - deliveryId: 'a'.repeat(64), - taskId: 'draft', - agentId: 'producer', - commit: f.state.problem.baseCommit, - kind: 'inspected' as const, - at: '2026-01-01', - }; - const alsoInspected = { ...inspected, deliveryId: 'b'.repeat(64) }, - adopted = { ...alsoInspected, kind: 'adopted' as const }; - f.team.archive.leadExposures = [inspected, alsoInspected, adopted]; - await f.spawn('analyst', 'Prove helper A.', undefined, 'plaintext', { Forked: [] }); - f.team.archive.leadExposures.push({ ...inspected, deliveryId: 'c'.repeat(64) }); - const worker = f.state.agentTeam!.workers[0]!, - task = worker.tasks[0]!, - session = f.sessions[0]!; - const address = { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId } }; - const followup = () => - f.native('send', { - ...address, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Investigate a new question B.' }, - }, - startOptions: {}, - }); - const steering = deferred(); - const acknowledge = deferred(); - vi.mocked(session.session.nativeAgentControl!.input).mockImplementationOnce(async () => { - steering.resolve(); - await acknowledge.promise; - return { accepted: true, threadId: worker.native!.threadId, submissionId: session.turnId }; - }); - const inFlight = followup(); - await steering.promise; - fs.writeFileSync( - f.source(worker.worktree), - fs - .readFileSync(f.source(worker.worktree), 'utf8') - .replace('end NativeTeam', 'theorem helperA : True := by trivial\nend NativeTeam'), - ); - const nomination = { - operation: 'submit', - summary: 'A is ready.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.helperA', type: 'True' }], - }; - expect(await f.tool(nomination, worker.id)).toMatchObject({ status: 'pending-writer-stop' }); - acknowledge.resolve(); - await inFlight; - expect(task.objectiveRevision).toBe(2); - expect( - readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0]!.tasks[0]!.nomination, - ).toMatchObject({ objectiveRevision: 1, objectiveDigest: mathDigest('Prove helper A.') }); - await expect(followup()).rejects.toThrow('math_team_submission_pending'); - expect( - await f.tool( - { - ...nomination, - summary: 'Replace A.', - declarations: [{ file: 'Submission.lean', name: 'NativeTeam.other', type: 'False' }], - }, - worker.id, - ), - ).toMatchObject({ ok: false }); - expect(f.team.archive.deliveries).toHaveLength(0); - await f.native('interrupt', { ...address, version: 'v2' }); - await expect.poll(() => f.team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); - expect(task.status).toBe('interrupted'); - expect(f.team.archive.deliveries).toHaveLength(1); - const delivery = readAgentTeamProofDelivery(f.team.archive.deliveries[0]!.path, f.state); - expect(delivery.provenance).toMatchObject({ - taskId: task.id, - objectiveRevision: 1, - objectiveDigest: mathDigest('Prove helper A.'), - }); - expect(delivery.provenance?.spawnHistory).toBe('parent-history'); - expect(delivery.provenance?.exposures).toEqual([{ ...inspected, kind: 'possible-via-parent' }, adopted]); - const durable = readSolverRunState(path.join(f.directory, 'state.json')); - expect(agentTeamOverview(durable).workers[0]?.deliveryExposures).toEqual(delivery.provenance!.exposures); - expect(delivery.declarations).toEqual(nomination.declarations); - await followup(); - expect(worker.tasks).toHaveLength(2); - expect(task.deliveryId).toBe(delivery.id); - expect(task.objectiveRevision).toBe(2); - }, 70_000); -}); diff --git a/tests/agentTeamNativeTools.test.ts b/tests/agentTeamNativeTools.test.ts deleted file mode 100644 index bbbe83dc..00000000 --- a/tests/agentTeamNativeTools.test.ts +++ /dev/null @@ -1,1602 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { createServer, type Server, type ServerResponse } from 'node:http'; -import type { AddressInfo } from 'node:net'; -import { parse as parseToml, stringify as stringifyToml } from 'smol-toml'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { createCodexMathSession, type MathAgentSession } from '../src/runtime/codexSession'; -import type { ModelRequestGate, ModelRequestReceipt } from '../src/runtime/modelRequest'; -import { prepareSub2apiProfile, SUB2API_PROVIDER } from '../src/runtime/sub2api'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { directSolverModules } from '../src/solver/modules'; -import { readSolverProblem } from '../src/solver/problem'; -import { beginRequestUsage, initializeRequestUsageAccounting } from '../src/solver/usageBudget'; -import { solverState } from './helpers/solver'; - -type Json = Record; -const executable = process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? 'codex'; -const nativeAvailable = - spawnSync(executable, ['--version'], { - env: { PATH: process.env.PATH }, - timeout: 5000, - stdio: 'ignore', - }).status === 0; -const nativeLeadOperations = [ - 'finish', - 'history', - 'inspect', - 'inspect-research', - 'adopt', - 'retire_route', - 'route_summary', -]; -const nativeMemberOperations = ['yield', 'history', 'inspect', 'inspect-research', 'submit', '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 () => { - await session?.close(); - session = undefined; - if (server) { - const current = server; - server = undefined; - current.closeAllConnections(); - await new Promise((resolve, reject) => current.close(error => (error ? reject(error) : resolve()))); - } - vi.restoreAllMocks(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - directory = undefined; -}); - -function declaredTools(request: Json): Json[] { - const declarations = [ - ...(request.tools ?? []), - ...(Array.isArray(request.input) - ? request.input.filter((item: Json) => item.type === 'additional_tools').flatMap((item: Json) => item.tools) - : []), - ]; - return declarations.flatMap((tool: Json) => (tool.type === 'namespace' ? tool.tools : [tool])); -} - -/** Full forks retain earlier role hints; only the latest privileged mode applies. */ -function effectiveMultiAgentMode(request: Json): string | undefined { - const messages = [ - request.instructions, - ...(Array.isArray(request.input) - ? request.input - .filter((item: Json) => ['system', 'developer'].includes(item.role)) - .map((item: Json) => - typeof item.content === 'string' - ? item.content - : (item.content ?? []).map((part: Json) => part.text ?? '').join('\n'), - ) - : []), - ]; - return messages - .filter((text): text is string => typeof text === 'string') - .flatMap(text => - [...text.matchAll(/([\s\S]*?)<\/multi_agent_mode>/gu)].map(match => match[1]!.trim()), - ) - .at(-1); -} - -function fixtureResponse(response: ServerResponse, id: string, items: Json[]) { - const base = { id, object: 'response', created_at: 1, model: 'deepseek-flash', status: 'in_progress', output: [] }; - const stream: Json[] = [{ type: 'response.created', response: base }]; - for (const [output_index, item] of items.entries()) { - const isCall = item.type === 'function_call'; - stream.push({ - type: 'response.output_item.added', - output_index, - item: isCall - ? { ...item, status: 'in_progress', arguments: '' } - : { ...item, status: 'in_progress', content: [] }, - }); - if (isCall) - stream.push( - { type: 'response.function_call_arguments.delta', item_id: item.id, output_index, delta: item.arguments }, - { type: 'response.function_call_arguments.done', item_id: item.id, output_index, arguments: item.arguments }, - ); - else - stream.push( - { - type: 'response.output_text.delta', - item_id: item.id, - output_index, - content_index: 0, - delta: item.content[0].text, - }, - { - type: 'response.output_text.done', - item_id: item.id, - output_index, - content_index: 0, - text: item.content[0].text, - }, - ); - stream.push({ type: 'response.output_item.done', output_index, item }); - } - stream.push({ - type: 'response.completed', - response: { - ...base, - status: 'completed', - output: items, - usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, - }, - }); - response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); - response.end(stream.map(event => 'event: ' + event.type + '\ndata: ' + JSON.stringify(event) + '\n\n').join('')); -} - -// This checks the real native client's wire protocol. The upstream is local and -// scripted, so passing this test says nothing about a model choosing to delegate. -describe.skipIf(!nativeAvailable || !process.env.THEOREMOS_TEST_CODEX_EXECUTABLE)( - 'real Codex dynamic team tool transport without a model', - () => { - it.each(['lead', 'member'])( - 'round trips the %s mathematical tool contract', - async actor => { - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-native-tools-'))); - const requests: Json[] = [], - routes: string[] = [], - errors: unknown[] = []; - const summary = 'Transport fixture: save Lead finish intent.'; - const args = actor === 'lead' ? { operation: 'finish', summary } : { operation: 'route_summary' }; - const call = { - type: 'function_call', - id: 'fc_team_probe', - call_id: 'call_team_probe', - name: 'theoremos_team', - arguments: JSON.stringify(args), - status: 'completed', - }; - server = createServer(async (request, response) => { - try { - routes.push(request.url ?? ''); - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))); - const index = requests.length; - const final = { - type: 'message', - id: 'msg_team_probe', - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text: 'The host result was received.', annotations: [] }], - }; - const item = index === 1 ? call : final; - const isCall = item.type === 'function_call'; - const base = { - id: 'resp_team_probe_' + index, - object: 'response', - created_at: 1, - model: 'deepseek-flash', - status: 'in_progress', - output: [], - }; - const events: Json[] = [ - { type: 'response.created', response: base }, - { - type: 'response.output_item.added', - output_index: 0, - item: isCall - ? { ...item, status: 'in_progress', arguments: '' } - : { ...final, status: 'in_progress', content: [] }, - }, - ]; - if (isCall) - events.push( - { - type: 'response.function_call_arguments.delta', - item_id: item.id, - output_index: 0, - delta: item.arguments, - }, - { - type: 'response.function_call_arguments.done', - item_id: item.id, - output_index: 0, - arguments: item.arguments, - }, - ); - else - events.push( - { - type: 'response.output_text.delta', - item_id: final.id, - output_index: 0, - content_index: 0, - delta: final.content[0].text, - }, - { - type: 'response.output_text.done', - item_id: final.id, - output_index: 0, - content_index: 0, - text: final.content[0].text, - }, - ); - events.push( - { type: 'response.output_item.done', output_index: 0, item }, - { - type: 'response.completed', - response: { - ...base, - status: 'completed', - output: [item], - usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, - }, - }, - ); - response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); - response.end( - events.map(event => 'event: ' + event.type + '\ndata: ' + JSON.stringify(event) + '\n\n').join(''), - ); - } catch (error) { - errors.push(error); - response.writeHead(500); - response.end(); - } - }); - await new Promise((resolve, reject) => { - server!.once('error', reject); - server!.listen(0, '127.0.0.1', resolve); - }); - const endpoint = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/v1'; - const profile = path.join(directory, 'profile'); - prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); - const configFile = path.join(profile, 'config.toml'), - config = parseToml(fs.readFileSync(configFile, 'utf8')) as Json; - // A disposable provider ID bypasses production endpoint selection entirely. - config.model_provider = 'offline_team_fixture'; - config.model_providers = { - offline_team_fixture: { - ...config.model_providers.sub2api, - base_url: endpoint, - env_key: 'THEOREMOS_TEST_KEY', - }, - }; - fs.chmodSync(configFile, 0o600); - fs.writeFileSync(configFile, stringifyToml(config)); - const receipt = bootstrapLeanTask(path.join(directory, 'work'), { - task: 'Offline transport fixture only.', - source: 'theorem original : True := by sorry\n', - }); - const state = solverState( - readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), - receipt.workspaceRoot, - { - runId: 'offline-native-tools', - phase: 'running', - researchMode: 'skill', - researchDelegation: { mode: 'team', maxAgents: 3 }, - }, - ); - state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - events: [], - deliveries: [], - adoptions: [], - operations: [], - workers: [], - }; - const team = new AgentResearchTeam({ - state, - root: process.cwd(), - taskText: 'Offline transport fixture only.', - leadAccess: { environment: {}, retrievalRoot: receipt.workspaceRoot }, - modules: directSolverModules, - executable, - profile, - signal: new AbortController().signal, - maxAgents: 3, - maxTurns: 4, - maxTurnMs: 10_000, - maxTotalTokens: 0, - remainingMs: () => 10_000, - save: () => {}, - emit: () => {}, - exclusiveCheck: operation => operation(), - }); - const tools = team.tools(actor), - hostCalls: { name: string; arguments: unknown; threadId: string; turnId: string }[] = []; - session = await createCodexMathSession({ - executable, - profile, - workspace: receipt.workspaceRoot, - model: 'deepseek-flash', - effort: 'high', - instructions: 'Offline team transport fixture.', - turnTimeoutMs: 10_000, - environment: { - PATH: process.env.PATH, - THEOREMOS_TEST_KEY: 'offline-synthetic-key', - [SUB2API_PROVIDER.apiKeyEnvironment]: 'offline-synthetic-key', - NO_PROXY: '127.0.0.1,localhost', - }, - onUsage: () => {}, - tools: { - definitions: tools.definitions, - call: async (name, args, context) => { - hostCalls.push({ name, arguments: args, threadId: context.threadId, turnId: context.turnId }); - return tools.call(name, args, context); - }, - }, - }); - expect( - await session.run( - 'Exercise the local team interface.', - 'offline-native-tools', - receipt.workspaceRoot, - () => {}, - ), - ).toBe('completed'); - expect(errors).toEqual([]); - expect(routes).toEqual(Array(2).fill('/v1/responses')); - expect(requests).toHaveLength(2); - const advertised = declaredTools(requests[0]).find(tool => tool.name === 'theoremos_team'); - expectAdvertisedOperations( - advertised!, - actor === 'member' ? nativeMemberOperations : nativeLeadOperations, - tools.definitions[0]!.inputSchema, - ); - expect(advertised!.parameters.properties).not.toHaveProperty('budget'); - expect(advertised!.parameters.properties).not.toHaveProperty('leadReserve'); - expect(hostCalls).toEqual([ - { name: 'theoremos_team', arguments: args, threadId: session.threadId, turnId: expect.any(String) }, - ]); - if (actor === 'lead') expect(state.agentTeam!.completionRequested).toMatchObject({ summary }); - const returned = requests - .at(-1)! - .input.find((item: Json) => item.type === 'function_call_output' && item.call_id === call.call_id); - expect(JSON.stringify(returned?.output)).toContain(actor === 'lead' ? 'pending-writer-stop' : 'routes'); - expect(session.lastCompletedResponse?.text).toBe('The host result was received.'); - expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - }, - 20_000, - ); - - it.skipIf(!process.env.THEOREMOS_TEST_CODEX_EXECUTABLE).each(['opening', 'defer', 'continue'] as const)( - 'ignores archived %s coordination state while native research and collaboration remain available', - async savedDecision => { - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-native-autonomy-'))); - const requests: Json[] = [], - errors: unknown[] = [], - events: string[] = [], - hostCalls: Json[] = []; - const functionCall = (id: string, name: string, args: Json, namespace?: string) => ({ - type: 'function_call', - id, - call_id: id, - name, - ...(namespace ? { namespace } : {}), - arguments: JSON.stringify(args), - status: 'completed', - }); - // Archived decisions, a failed probe and native recipient feedback cannot - // introduce a host coordination prerequisite for ordinary research. - const calls = [ - functionCall('probe_before_decision', 'ordinary_research_probe', { stage: 'before-decision' }), - functionCall('saved_history', 'theoremos_team', { operation: 'history' }), - functionCall('native_list', 'list_agents', {}, 'collaboration'), - functionCall( - 'native_recipient_probe', - 'send_message', - { - target: '/root', - message: 'Offline self-addressed recipient probe; no team task is dispatched.', - }, - 'collaboration', - ), - functionCall('probe_after_updates', 'ordinary_research_probe', { stage: 'after-updates' }), - ]; - const finalText = 'Native research continued without a host coordination gate.'; - server = createServer(async (request, response) => { - try { - if (request.url !== '/v1/responses') throw new Error('unexpected_native_autonomy_route'); - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))); - const index = requests.length; - const item = calls[index - 1] ?? { - type: 'message', - id: 'msg_native_autonomy', - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text: finalText, annotations: [] }], - }; - fixtureResponse(response, 'resp_native_autonomy_' + index, [item]); - } catch (error) { - errors.push(error); - response.writeHead(500); - response.end(); - } - }); - await new Promise((resolve, reject) => { - server!.once('error', reject); - server!.listen(0, '127.0.0.1', resolve); - }); - const endpoint = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/v1/responses'; - const realFetch = globalThis.fetch.bind(globalThis); - vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { - const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; - if (url !== SUB2API_PROVIDER.baseUrl + '/responses') throw new Error('unexpected_native_autonomy_upstream'); - return realFetch(endpoint, init); - }); - const profile = path.join(directory, 'profile'); - prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); - const receipt = bootstrapLeanTask(path.join(directory, 'work'), { - task: 'Offline native autonomy fixture.', - source: 'theorem original : True := by sorry\n', - }); - const state = solverState( - readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), - receipt.workspaceRoot, - { - runId: 'offline-native-autonomy', - phase: 'running', - researchMode: 'skill', - researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }, - ); - if (savedDecision !== 'opening') { - state.agentTeam!.coordination = { - decision: savedDecision, - reason: 'Saved archived decision.', - nextStep: 'Inspect a local probe.', - revision: 1, - at: 1, - startedRequests: 0, - observationRevision: 0, - activeAssignments: false, - eventSequence: 0, - nativeMessageSequence: 0, - }; - state.agentTeam!.coordinationObservation = { - key: 'saved-failed-probe', - kind: 'tool-result', - failed: true, - description: 'A previous local probe failed.', - revision: 1, - at: 1, - }; - } - // A persisted presentation from the old scheduler must remain harmless on resume. - state.agentTeam!.coordinationPresentation = { - at: 1, - reason: savedDecision === 'opening' ? 'opening' : 'research-update', - decisionRevision: state.agentTeam!.coordination?.revision ?? 0, - eventSequence: 0, - nativeMessageSequence: 0, - observationRevision: state.agentTeam!.coordinationObservation?.revision ?? 0, - startedRequests: 0, - }; - const savedJournal = structuredClone({ - coordination: state.agentTeam!.coordination, - observation: state.agentTeam!.coordinationObservation, - presentation: state.agentTeam!.coordinationPresentation, - }); - const receipts: ModelRequestReceipt[] = []; - const team = new AgentResearchTeam({ - state, - root: process.cwd(), - taskText: 'Offline native autonomy fixture.', - leadAccess: { environment: {}, retrievalRoot: receipt.workspaceRoot }, - modules: directSolverModules, - executable, - profile, - signal: new AbortController().signal, - maxAgents: 3, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save: () => {}, - emit: event => { - events.push(event); - }, - exclusiveCheck: operation => operation(), - }); - const tools = team.tools(), - onUsageIncomplete = vi.fn(); - const gate = team.leadRequestGate(() => ({ - allowed: true, - settle: value => { - receipts.push(value); - }, - })); - try { - team.beginLeadTurn(); - session = await createCodexMathSession({ - executable, - profile, - workspace: receipt.workspaceRoot, - model: 'deepseek-flash', - effort: 'high', - instructions: 'Offline native autonomy fixture.', - turnTimeoutMs: 10_000, - nativeAgentControl: team.nativeAgentControlOptions(), - requestGate: gate, - environment: { - PATH: process.env.PATH, - [SUB2API_PROVIDER.apiKeyEnvironment]: 'offline-synthetic-key', - NO_PROXY: '127.0.0.1,localhost', - }, - onUsage: () => {}, - onUsageIncomplete, - tools: { - definitions: [ - ...tools.definitions, - { - name: 'ordinary_research_probe', - description: 'Disposable local research observation.', - inputSchema: { - type: 'object', - properties: { stage: { type: 'string' } }, - required: ['stage'], - additionalProperties: false, - }, - }, - ], - call: async (name, args, context) => { - hostCalls.push({ name, arguments: args }); - if (name === 'ordinary_research_probe') { - const stage = (args as Json).stage; - return { ok: false, diagnostic: stage }; - } - return tools.call(name, args, context); - }, - }, - }); - team.setLeadSession(session); - expect( - await session.run( - 'Exercise native research with archived coordination state.', - 'offline-native-autonomy', - receipt.workspaceRoot, - () => {}, - ), - ).toBe('completed'); - expect(errors).toEqual([]); - expect(requests).toHaveLength(calls.length + 1); - for (const request of requests) { - expect(request.tool_choice).toBe('auto'); - const advertised = declaredTools(request); - expect(advertised.map(tool => tool.name)).toEqual( - expect.arrayContaining([ - 'spawn_agent', - 'followup_task', - 'send_message', - 'list_agents', - 'wait_agent', - 'interrupt_agent', - 'theoremos_team', - 'ordinary_research_probe', - 'exec_command', - ]), - ); - const host = advertised.find(tool => tool.name === 'theoremos_team'); - expectAdvertisedOperations(host!, nativeLeadOperations, tools.definitions[0]!.inputSchema); - for (const property of ['decision', 'nextStep', 'budget', 'leadReserve', 'objectiveRevision']) - expect(host!.parameters.properties).not.toHaveProperty(property); - } - expect(hostCalls).toEqual( - calls - .filter(call => !('namespace' in call)) - .map(call => ({ - name: call.name, - arguments: JSON.parse(call.arguments), - })), - ); - const listOutput = requests - .at(-1)! - .input.find((item: Json) => item.type === 'function_call_output' && item.call_id === 'native_list'); - expect(JSON.stringify(listOutput?.output)).toContain('/root'); - expect(requests.at(-1)!.input).toContainEqual( - expect.objectContaining({ - type: 'function_call_output', - call_id: 'native_recipient_probe', - }), - ); - expect(state.agentTeam!.workers).toHaveLength(0); - expect(state.agentTeam!.deliveries).toHaveLength(0); - expect({ - coordination: state.agentTeam!.coordination, - observation: state.agentTeam!.coordinationObservation, - presentation: state.agentTeam!.coordinationPresentation, - }).toEqual(savedJournal); - expect(state.agentTeam!.researchState).toBeUndefined(); - expect( - events.filter(event => event.startsWith('team_coordination') || event === 'team_research_observed'), - ).toEqual([]); - expect(receipts).toHaveLength(requests.length); - expect(receipts.every(value => value.complete)).toBe(true); - expect(onUsageIncomplete).not.toHaveBeenCalled(); - expect(session.lastCompletedResponse?.text).toBe(finalText); - expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - } finally { - await team.close(); - } - }, - 20_000, - ); - - it.skipIf(!process.env.THEOREMOS_TEST_CODEX_EXECUTABLE)( - 'runs official native spawn, isolated child tools, mailbox wakeup and native completion with minimal host operations', - async () => { - const [{ readMathAgentSkill }, { prepareResearchSkill, researchSkillIdentity }, { agentTeamInstructions }] = - await Promise.all([ - import('../src/runtime/agentSkills'), - import('../src/solver/researchSkill'), - import('../src/solver/agentTeamContext'), - ]); - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-native-dispatch-'))); - const root = process.cwd(), - requests: Json[] = [], - errors: unknown[] = [], - events: string[] = []; - const controller = new AbortController(); - const receipt = bootstrapLeanTask(path.join(directory, 'work'), { - task: 'Offline native dispatch fixture.', - source: 'theorem original : True := by sorry\n', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const identity = researchSkillIdentity( - readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md')), - ); - const state = solverState(problem, receipt.workspaceRoot, { - runId: 'offline-native-dispatch', - phase: 'running', - environmentDigest: 'e'.repeat(64), - model: 'deepseek-flash', - effort: 'high', - researchMode: 'skill', - researchSkill: identity, - researchDelegation: { mode: 'team', maxAgents: 2 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }); - const researchSkill = prepareResearchSkill(root, state.worktree, identity, problem); - const privateFile = path.join(state.worktree, 'lead-private'); - fs.writeFileSync(privateFile, 'fixture-private'); - const profile = path.join(directory, 'profile'); - prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); - const toolchain = path.join(process.env.HOME!, '.elan/toolchains/leanprover--lean4---v4.33.0'); - const environment = { - PATH: `${toolchain}/bin:${process.env.PATH}`, - ELAN_HOME: path.join(process.env.HOME!, '.elan'), - LEAN_PATH: '', - LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env'), - [SUB2API_PROVIDER.apiKeyEnvironment]: 'offline-synthetic-key', - NO_PROXY: '127.0.0.1,localhost', - }; - const opened: Parameters[0][] = []; - const modules = { - ...directSolverModules, - M1: { - ...directSolverModules.M1, - open: async (options: Parameters[0]) => { - opened.push(options); - return createCodexMathSession(options); - }, - }, - }; - const team = new AgentResearchTeam({ - state, - root, - taskText: 'Offline native dispatch fixture.', - modules, - executable, - profile, - leadAccess: { environment, researchSkill, retrievalRoot: receipt.workspaceRoot }, - signal: controller.signal, - maxAgents: 2, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save: () => {}, - emit: event => { - events.push(event); - }, - exclusiveCheck: check => check(), - }); - const functionCall = (id: string, name: string, args: Json, namespace?: string) => ({ - type: 'function_call', - id, - call_id: id, - name, - ...(namespace ? { namespace } : {}), - arguments: JSON.stringify(args), - status: 'completed', - }); - const finalMessage = (id: string, text: string) => ({ - type: 'message', - id, - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text, annotations: [] }], - }); - const quote = (value: string) => "'" + value.replace(/'/gu, "'\\''") + "'"; - const finding = 'The native child verified its isolated fixture workspace.'; - const childFinal = 'The native child completed its independent fixture assignment.'; - const rootFinal = 'The Lead received the child message and native completion.'; - let rootStep = 0, - childStep = 0, - waitStarted = false; - const modes = { lead: new Set(), member: new Set() }; - server = createServer(async (request, response) => { - try { - if (request.url !== '/v1/responses') throw new Error('unexpected_native_dispatch_route'); - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - const body = JSON.parse(Buffer.concat(chunks).toString('utf8')); - requests.push(body); - const requestIndex = requests.length; - const text = body.input - .filter((item: Json) => ['message', 'agent_message'].includes(item.type)) - .flatMap((item: Json) => item.content ?? []) - .map((part: Json) => part.text ?? part.encrypted_content ?? '') - .join('\n'); - const host = declaredTools(body).find(tool => tool.name === 'theoremos_team'); - const child = text.includes('NATIVE_ACTUAL_CHILD_FIXTURE'); - const allowed = child ? nativeMemberOperations : nativeLeadOperations; - 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', - ); - expect(mode).not.toContain('Do not spawn sub-agents unless'); - expect(body.tool_choice).toBe('auto'); - if (child) { - expect(mode).toContain('You are a member of an explicitly requested flat team.'); - expect(mode).toContain('Do not spawn sub-agents or dispatch, redirect or interrupt other members.'); - expect(mode).not.toContain('Follow the pinned Lead charter.'); - modes.member.add(mode!); - } else { - expect(mode).toContain('You are the Lead of an explicitly requested flat team.'); - expect(mode).toContain('Only Lead dispatches or interrupts members.'); - modes.lead.add(mode!); - } - let item: Json; - if (text.includes('NATIVE_ACTUAL_CHILD_FIXTURE')) { - const worker = team.archive.workers[0]!; - if (childStep++ === 0) - item = functionCall('child_isolation', 'exec_command', { - login: false, - cmd: - 'test "$PWD" = ' + - quote(worker.worktree) + - ' && test ! -r ' + - quote(privateFile) + - ' && mkdir -p .scratch && printf native-isolation-ok > .scratch/native-receipt.txt && cat .scratch/native-receipt.txt', - }); - else if (childStep === 2) { - await expect.poll(() => waitStarted, { timeout: 10_000 }).toBe(true); - item = functionCall( - 'child_message', - 'send_message', - { target: '/root', message: finding }, - 'collaboration', - ); - } else item = finalMessage('child_final', childFinal); - } else if (rootStep++ === 0) - item = functionCall( - 'native_spawn', - 'spawn_agent', - { - task_name: 'expert', - fork_turns: 'none', - message: - 'Profiles: researcher\nNATIVE_ACTUAL_CHILD_FIXTURE Inspect the disposable fixture and report the observed isolation result.', - }, - 'collaboration', - ); - else if (rootStep === 2) - item = functionCall('native_wait', 'wait_agent', { timeout_ms: 10000 }, 'collaboration'); - else if (rootStep === 3) { - await expect.poll(() => team.hasActiveWorkers, { timeout: 20_000 }).toBe(false); - // Completion can arrive after this model request started. Finish one - // native tool boundary before expecting it in the next request's history. - item = functionCall('native_list', 'list_agents', {}, 'collaboration'); - } else item = finalMessage('root_final', rootFinal); - fixtureResponse(response, 'resp_native_dispatch_' + requestIndex, [item]); - } catch (error) { - errors.push(error); - controller.abort(error); - response.writeHead(500); - response.end(); - } - }); - await new Promise((resolve, reject) => { - server!.once('error', reject); - server!.listen(0, '127.0.0.1', resolve); - }); - const endpoint = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/v1/responses'; - const realFetch = globalThis.fetch.bind(globalThis); - vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { - const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; - if (url !== SUB2API_PROVIDER.baseUrl + '/responses') throw new Error('unexpected_native_dispatch_upstream'); - return realFetch(endpoint, init); - }); - try { - team.beginLeadTurn(); - session = await createCodexMathSession({ - executable, - profile, - workspace: state.worktree, - environment, - model: state.model, - effort: state.effort, - signal: controller.signal, - skills: [researchSkill], - instructions: agentTeamInstructions({ id: 'lead', role: 'lead' }, 2), - nativeAgentControl: team.nativeAgentControlOptions(), - requestGate: team.leadRequestGate(() => ({ allowed: true, settle: () => {} })), - onUsage: () => {}, - onItem: (phase, item) => { - if (phase === 'started' && item.id === 'native_wait') waitStarted = true; - }, - tools: team.tools(), - }); - team.setLeadSession(session); - expect( - await session.run( - 'Run the offline native team fixture.', - 'offline-native-dispatch', - state.worktree, - () => {}, - ), - ).toBe('completed'); - expect(errors).toEqual([]); - expect(rootStep).toBe(4); - expect( - childStep, - JSON.stringify({ - events, - workerErrors: team.archive.workers.map(worker => worker.error), - taskErrors: team.archive.workers.flatMap(worker => worker.tasks.map(task => task.error)), - }), - ).toBe(3); - expect(opened).toHaveLength(1); - expect(opened[0]!.nativeAgentControl).toBeDefined(); - expect(opened[0]!.isolateProcess).toBe(true); - const worker = team.archive.workers[0]!; - expect(worker.worktree).not.toBe(state.worktree); - expect(worker.native?.agentPath).toBe('/root/expert'); - expect(worker.native?.parentThreadId).toBe(session.threadId); - expect(worker.tasks[0]!.status).toBe('completed'); - expect(worker.native?.lastOutcome).toMatchObject({ status: { completed: childFinal } }); - expect([...modes.lead]).toEqual([session.nativeConfiguration!.overrides.multiAgentModeHintText]); - expect([...modes.member]).toEqual([worker.native!.runtimeConfiguration!.overrides.multiAgentModeHintText]); - expect(fs.readFileSync(path.join(worker.worktree, '.scratch/native-receipt.txt'), 'utf8')).toBe( - 'native-isolation-ok', - ); - const history = JSON.stringify(requests.at(-1)!.input); - expect(history).toContain(finding); - expect(history).toContain(childFinal); - const waitOutput = requests - .at(-1)! - .input.find((item: Json) => item.type === 'function_call_output' && item.call_id === 'native_wait'); - expect(JSON.stringify(waitOutput?.output)).toContain('Wait completed.'); - expect(requests.every(request => request.tool_choice === 'auto')).toBe(true); - expect( - events.filter(event => event.startsWith('team_coordination') || event === 'team_research_observed'), - ).toEqual([]); - expect(team.archive.coordination).toBeUndefined(); - expect( - requests.flatMap(request => - request.input.filter((item: Json) => item.type === 'function_call' && item.name === 'theoremos_team'), - ), - ).toEqual([]); - expect(team.archive.deliveries).toHaveLength(0); - expect(state.check).toBeUndefined(); - expect(worker.writerStopUnconfirmed).toBeUndefined(); - expect(team.hasActiveWorkers).toBe(false); - expect(session.lastCompletedResponse?.text).toBe(rootFinal); - expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - } finally { - controller.abort(); - await team.close(); - } - }, - 60_000, - ); - - it('checkpoints native continuation after a Lead adoption and resumes the saved thread after writer shutdown', async () => { - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-native-adopt-'))); - const traceFile = path.join(directory, 'trace.jsonl'), - launcher = path.join(directory, 'codex-traced'); - const trace = (event: Json) => fs.appendFileSync(traceFile, JSON.stringify(event) + '\n'); - const readTrace = (): Json[] => - fs - .readFileSync(traceFile, 'utf8') - .trim() - .split('\n') - .map(line => JSON.parse(line)); - // Transparent stdin tracing observes real RPC methods without replacing Codex. - fs.writeFileSync( - launcher, - '#!' + - process.execPath + - '\n' + - String.raw` -const fs = require('node:fs'); -const { spawn } = require('node:child_process'); -const child = spawn(process.env.THEOREMOS_NATIVE_TEST_EXECUTABLE, process.argv.slice(2), { stdio: ['pipe', 'inherit', 'inherit'] }); -let pending = ''; -process.stdin.on('data', chunk => { - pending += chunk; - const lines = pending.split('\n'); pending = lines.pop(); - for (const line of lines) { - const frame = JSON.parse(line); - if (frame.method) fs.appendFileSync(process.env.THEOREMOS_NATIVE_TEST_TRACE, JSON.stringify({ event: 'rpc', method: frame.method, - threadId: frame.params?.threadId }) + '\n'); - } -}); -process.stdin.pipe(child.stdin); -for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => child.kill(signal)); -child.on('error', () => process.exit(1)); -child.on('close', code => process.exit(code ?? 0)); -`, - { mode: 0o700 }, - ); - const requests: Json[] = [], - routes: string[] = [], - errors: unknown[] = [], - prematureCloses: number[] = []; - const deliveryId = 'a'.repeat(64), - finalText = 'The saved Lead thread continued after the adoption checkpoint.'; - const args = { operation: 'adopt', deliveryId }; - const call = { - type: 'function_call', - id: 'fc_native_adopt', - call_id: 'call_native_adopt', - name: 'theoremos_team', - arguments: JSON.stringify(args), - status: 'completed', - }; - server = createServer(async (request, response) => { - try { - routes.push(request.url ?? ''); - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8'))); - const index = requests.length; - response.once('close', () => { - if (!response.writableEnded) prematureCloses.push(index); - }); - const final = { - type: 'message', - id: 'msg_native_adopt', - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text: finalText, annotations: [] }], - }; - const item = index === 1 ? call : final; - const base = { - id: 'resp_native_adopt_' + index, - object: 'response', - created_at: 1, - model: 'deepseek-flash', - status: 'in_progress', - output: [], - }; - const events: Json[] = [ - { type: 'response.created', response: base }, - { - type: 'response.output_item.added', - output_index: 0, - item: - index === 1 - ? { ...call, status: 'in_progress', arguments: '' } - : { ...final, status: 'in_progress', content: [] }, - }, - ]; - if (index === 1) - events.push( - { - type: 'response.function_call_arguments.delta', - item_id: call.id, - output_index: 0, - delta: call.arguments, - }, - { - type: 'response.function_call_arguments.done', - item_id: call.id, - output_index: 0, - arguments: call.arguments, - }, - ); - else - events.push( - { - type: 'response.output_text.delta', - item_id: final.id, - output_index: 0, - content_index: 0, - delta: finalText, - }, - { - type: 'response.output_text.done', - item_id: final.id, - output_index: 0, - content_index: 0, - text: finalText, - }, - ); - events.push( - { type: 'response.output_item.done', output_index: 0, item }, - { - type: 'response.completed', - response: { - ...base, - status: 'completed', - output: [item], - usage: { - input_tokens: 10, - output_tokens: 2, - total_tokens: 12, - input_tokens_details: { cached_tokens: 4 }, - output_tokens_details: { reasoning_tokens: 1 }, - }, - }, - }, - ); - trace({ event: 'upstream-terminal', index }); - response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); - response.end( - events.map(event => 'event: ' + event.type + '\ndata: ' + JSON.stringify(event) + '\n\n').join(''), - ); - } catch (error) { - errors.push(error); - response.writeHead(500); - response.end(); - } - }); - await new Promise((resolve, reject) => { - server!.once('error', reject); - server!.listen(0, '127.0.0.1', resolve); - }); - const endpoint = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/v1/responses'; - const realFetch = globalThis.fetch.bind(globalThis); - vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { - const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; - // Keep the production relay/profile path, but never contact its configured upstream. - if (url !== SUB2API_PROVIDER.baseUrl + '/responses') throw new Error('unexpected_native_test_upstream'); - return realFetch(endpoint, init); - }); - const profile = path.join(directory, 'profile'); - prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); - const receipt = bootstrapLeanTask(path.join(directory, 'work'), { - task: 'Offline adoption scheduling fixture.', - source: 'theorem original : True := by sorry\n', - }); - const state = solverState( - readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), - receipt.workspaceRoot, - { - runId: 'offline-native-adopt', - phase: 'running', - researchMode: 'skill', - researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - adoptions: [], - operations: [], - deliveries: [ - { - id: deliveryId, - agentId: 'producer', - taskId: 'offline-delivery', - path: path.join(directory, 'unused-delivery.json'), - }, - ], - }, - }, - ); - initializeRequestUsageAccounting(state); - const receipts: ModelRequestReceipt[] = [], - hostCalls: Json[] = [], - events: Json[] = []; - const baseGate: ModelRequestGate = identity => { - const settle = beginRequestUsage(state, identity); - trace({ event: 'admitted', requestId: identity?.requestId }); - return { - allowed: true, - settle: value => { - settle(value); - receipts.push(value); - trace({ event: 'settled', complete: value.complete, outcome: value.outcome }); - }, - }; - }; - const team = new AgentResearchTeam({ - state, - root: process.cwd(), - taskText: 'Offline adoption scheduling fixture.', - leadAccess: { environment: {}, retrievalRoot: receipt.workspaceRoot }, - modules: directSolverModules, - executable: launcher, - profile, - signal: new AbortController().signal, - maxAgents: 3, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save: () => {}, - emit: (event, details) => events.push({ event, details }), - exclusiveCheck: operation => operation(), - }); - const tools = team.tools(), - onUsageIncomplete = vi.fn(); - const open = (threadId?: string) => - createCodexMathSession({ - executable: launcher, - profile, - workspace: receipt.workspaceRoot, - model: 'deepseek-flash', - effort: 'high', - instructions: 'Offline adoption scheduling fixture.', - threadId, - environment: { - PATH: process.env.PATH, - [SUB2API_PROVIDER.apiKeyEnvironment]: 'offline-synthetic-key', - THEOREMOS_NATIVE_TEST_EXECUTABLE: executable, - THEOREMOS_NATIVE_TEST_TRACE: traceFile, - NO_PROXY: '127.0.0.1,localhost', - }, - onUsage: () => {}, - onUsageIncomplete, - requestGate: team.leadRequestGate(baseGate), - tools: { - definitions: tools.definitions, - call: async (name, value, context) => { - hostCalls.push({ name, arguments: value, threadId: context.threadId }); - return tools.call(name, value, context); - }, - }, - }); - try { - team.beginLeadTurn(); - session = await open(); - team.setLeadSession(session); - const threadId = session.threadId; - expect(session.usageSource).toBe('upstream-requests'); - expect( - await session.run( - 'Adopt the supplied fixture delivery.', - 'native-adopt-first', - receipt.workspaceRoot, - () => {}, - ), - ).toBe('checkpoint'); - expect(requests).toHaveLength(1); - expect(hostCalls).toEqual([{ name: 'theoremos_team', arguments: args, threadId }]); - expect(team.archive.adoptions).toEqual([ - expect.objectContaining({ deliveryId, targetId: 'lead', status: 'queued' }), - ]); - expect(events.filter(item => item.event === 'team_adoption_checkpoint')).toHaveLength(1); - expect(receipts).toEqual([ - { - complete: true, - outcome: 'completed', - providerRequestId: 'resp_native_adopt_1', - usage: { - inputTokens: 10, - outputTokens: 2, - totalTokens: 12, - cachedInputTokens: 4, - reasoningOutputTokens: 1, - }, - }, - ]); - expect(state.requestUsageAccounting).toMatchObject({ - startedRequests: 1, - reportedRequests: 1, - pendingRequests: 0, - incomplete: false, - }); - expect(onUsageIncomplete).not.toHaveBeenCalled(); - expect(prematureCloses).toEqual([]); - expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - const firstTrace = readTrace(), - interrupt = firstTrace.findIndex(item => item.event === 'rpc' && item.method === 'turn/interrupt'); - expect(firstTrace.filter(item => item.event === 'rpc' && item.method === 'turn/steer')).toEqual([]); - expect(interrupt).toBeGreaterThan(firstTrace.findIndex(item => item.event === 'settled')); - expect(requests).toHaveLength(1); - - // This fixture covers scheduling only; Git/Lean integration has its own test. - team.archive.adoptions[0]!.status = 'completed'; - team.beginLeadTurn(); - session = await open(threadId); - team.setLeadSession(session); - expect(session.threadId).toBe(threadId); - expect( - await session.run( - 'Continue after the fixture adoption checkpoint.', - 'native-adopt-resumed', - receipt.workspaceRoot, - () => {}, - ), - ).toBe('completed'); - expect(session.lastCompletedResponse?.text).toBe(finalText); - expect(requests).toHaveLength(2); - expect(routes).toEqual(['/v1/responses', '/v1/responses']); - expect(hostCalls).toHaveLength(1); - expect(receipts).toHaveLength(2); - expect(receipts.every(item => item.complete && item.outcome === 'completed')).toBe(true); - expect(state.requestUsageAccounting).toMatchObject({ - startedRequests: 2, - reportedRequests: 2, - pendingRequests: 0, - incomplete: false, - }); - expect(errors).toEqual([]); - expect(prematureCloses).toEqual([]); - expect(onUsageIncomplete).not.toHaveBeenCalled(); - expect(readTrace()).toContainEqual({ event: 'rpc', method: 'thread/resume', threadId }); - expect(readTrace().filter(item => item.event === 'rpc' && item.method === 'turn/steer')).toEqual([]); - expect(await session.stopForFreeze!()).toEqual({ status: 'stopped' }); - } finally { - await team.close(); - } - }, 20_000); - }, -); - -describe.skipIf(!nativeAvailable || !process.env.THEOREMOS_TEST_CODEX_EXECUTABLE)( - 'native child decision checkpoints without a model', - () => { - it.each(['submit', 'yield'] as const)( - 'finishes the paid tool group before %s releases the writer', - async operation => { - const [{ readMathAgentSkill }, { prepareResearchSkill, researchSkillIdentity }, { deferred }] = - await Promise.all([ - import('../src/runtime/agentSkills'), - import('../src/solver/researchSkill'), - import('./helpers/async'), - ]); - const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'agent-team-native-child-'))); - const root = process.cwd(), - requests: Json[] = [], - errors: unknown[] = [], - prematureCloses: number[] = []; - const releaseTail = deferred(); - let tailRunning = false, - tailFinished = false; - const declarations = [{ file: 'Submission.lean', name: 'Team.reusable', type: '∀ n : Nat, n = n' }]; - const decision = - operation === 'submit' - ? { operation, summary: 'The fixture equality helper is ready.', declarations } - : { operation, reason: 'The saved fixture draft needs a peer interface.' }; - const toolCalls = [decision, { operation: 'history' }].map((arguments_, index) => ({ - type: 'function_call', - id: `fc_native_${operation}_${index}`, - call_id: `call_native_${operation}_${index}`, - name: 'theoremos_team', - arguments: JSON.stringify(arguments_), - status: 'completed', - })); - let leadRequests = 0; - server = createServer(async (request, response) => { - try { - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - const body = JSON.parse(Buffer.concat(chunks).toString('utf8')); - const text = body.input - .filter((item: Json) => ['message', 'agent_message'].includes(item.type)) - .flatMap((item: Json) => item.content ?? []) - .map((part: Json) => part.text ?? part.encrypted_content ?? '') - .join('\n'); - const final = (text: string) => ({ - type: 'message', - id: 'msg_fixture', - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text, annotations: [] }], - }); - if (!text.includes('NATIVE_CHILD_PAID_TOOLS')) { - const index = ++leadRequests; - const spawn = { - type: 'function_call', - id: 'spawn_child', - call_id: 'spawn_child', - name: 'spawn_agent', - namespace: 'collaboration', - status: 'completed', - arguments: JSON.stringify({ - task_name: 'child', - fork_turns: 'none', - message: 'NATIVE_CHILD_PAID_TOOLS Save the fixture handoff.', - }), - }; - fixtureResponse(response, 'resp_child_fixture_lead_' + index, [ - index === 1 ? spawn : final('Child dispatched.'), - ]); - return; - } - const index = requests.push(body); - response.once('close', () => { - if (!response.writableEnded) prematureCloses.push(index); - }); - fixtureResponse( - response, - `resp_native_${operation}_${index}`, - index === 1 ? toolCalls : [final('Unexpected extra paid continuation.')], - ); - } catch (error) { - errors.push(error); - response.writeHead(500); - response.end(); - } - }); - await new Promise((resolve, reject) => { - server!.once('error', reject); - server!.listen(0, '127.0.0.1', resolve); - }); - const endpoint = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/v1/responses'; - const realFetch = globalThis.fetch.bind(globalThis); - vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { - const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; - if (url !== SUB2API_PROVIDER.baseUrl + '/responses') throw new Error('unexpected_native_child_upstream'); - return realFetch(endpoint, init); - }); - const profile = path.join(directory, 'profile'); - prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); - const original = 'namespace Team\ntheorem original : True := by sorry\nend Team\n'; - const helper = 'theorem reusable (n : Nat) : n = n := by rfl\n'; - const receipt = bootstrapLeanTask(path.join(directory, 'work'), { - task: 'Offline native child fixture.', - source: original, - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const identity = researchSkillIdentity( - readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md')), - ); - const state = solverState(problem, receipt.workspaceRoot, { - runId: `offline-native-${operation}`, - phase: 'running', - environmentDigest: 'e'.repeat(64), - model: 'deepseek-flash', - effort: 'high', - researchMode: 'skill', - researchSkill: identity, - researchDelegation: { mode: 'team', maxAgents: 2 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }); - const researchSkill = prepareResearchSkill(root, state.worktree, identity, problem); - const toolchain = path.join(process.env.HOME!, '.elan/toolchains/leanprover--lean4---v4.33.0'); - const environment = { - PATH: `${toolchain}/bin:${process.env.PATH}`, - ELAN_HOME: path.join(process.env.HOME!, '.elan'), - LEAN_PATH: '', - LEAN_SYSROOT: '', - DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', - DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env'), - [SUB2API_PROVIDER.apiKeyEnvironment]: 'offline-synthetic-key', - NO_PROXY: '127.0.0.1,localhost', - }; - const opened: Parameters[0][] = [], - hostCalls: string[] = []; - const modules = { - ...directSolverModules, - M1: { - ...directSolverModules.M1, - open: async (options: Parameters[0]) => { - opened.push(options); - fs.writeFileSync( - path.join(options.workspace, problem.projectRelative, 'Submission.lean'), - original.replace('end Team', helper + 'end Team'), - ); - session = await createCodexMathSession({ - ...options, - tools: { - definitions: options.tools!.definitions, - call: async (name, value, context) => { - const args = value as Json; - hostCalls.push(args.operation); - if (args.operation === 'history') { - tailRunning = true; - await releaseTail.promise; - fs.writeFileSync( - path.join(options.workspace, 'RESEARCH.md'), - 'The final paid tool output was preserved.', - ); - tailFinished = true; - } - return options.tools!.call(name, value, context); - }, - }, - }); - return session; - }, - }, - }; - const controller = new AbortController(); - const team = new AgentResearchTeam({ - state, - root, - taskText: 'Offline native child fixture.', - modules, - executable, - profile, - leadAccess: { environment, researchSkill, retrievalRoot: receipt.workspaceRoot }, - signal: controller.signal, - maxAgents: 2, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save: () => {}, - emit: () => {}, - exclusiveCheck: check => check(), - }); - const lead = await createCodexMathSession({ - executable, - profile, - workspace: state.worktree, - environment, - model: state.model, - effort: state.effort, - signal: controller.signal, - skills: [researchSkill], - instructions: 'Dispatch the disposable child fixture.', - nativeAgentControl: team.nativeAgentControlOptions(), - tools: team.tools(), - requestGate: team.leadRequestGate(() => ({ allowed: true, settle: () => {} })), - onUsage: () => {}, - }); - try { - team.setLeadSession(lead); - expect( - await lead.run( - 'Run the isolated child checkpoint fixture.', - 'native-child-fixture', - state.worktree, - () => {}, - ), - ).toBe('completed'); - expect(leadRequests).toBe(2); - const worker = team.archive.workers[0]!; - await expect - .poll( - () => ({ - tailRunning, - error: worker.error ?? worker.tasks[0]?.error, - requests: requests.length, - opened: opened.length, - activity: worker.activity, - status: worker.tasks[0]?.status, - }), - { timeout: 10_000 }, - ) - .toEqual({ - tailRunning: true, - error: undefined, - requests: 1, - opened: 1, - activity: 'running', - status: 'running', - }); - expect(requests).toHaveLength(1); - expect(opened).toHaveLength(1); - expect(worker.tasks[0]!.status).toBe('running'); - expect(worker.tasks[0]!.researchArtifactId).toBeUndefined(); - expect(team.archive.deliveries).toHaveLength(0); - expect(tailFinished).toBe(false); - expect(opened[0]!.signal?.aborted).toBe(false); - releaseTail.resolve(); - await expect.poll(() => team.hasActiveWorkers, { timeout: 60_000 }).toBe(false); - expect(tailFinished).toBe(true); - expect(requests).toHaveLength(1); - expect(hostCalls).toEqual([operation, 'history']); - expect(worker.error).toBeUndefined(); - expect(worker.writerStopUnconfirmed).toBeUndefined(); - expect(worker.requestUsageAccounting).toMatchObject({ - startedRequests: 1, - reportedRequests: 1, - pendingRequests: 0, - incomplete: false, - }); - expect(worker.usageAccounting).toMatchObject({ reportedTurns: 1, pending: false, incomplete: false }); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe( - 'The final paid tool output was preserved.', - ); - if (operation === 'submit') { - expect(worker.tasks[0]).toMatchObject({ status: 'completed', deliveryId: expect.any(String) }); - expect(worker.tasks[0]!.pauseRequested).toBeUndefined(); - expect(team.archive.deliveries).toHaveLength(1); - } else { - expect(worker.tasks[0]).toMatchObject({ status: 'paused', pauseRequested: { kind: 'handoff' } }); - expect(team.archive.deliveries).toHaveLength(0); - } - expect(errors).toEqual([]); - expect(prematureCloses).toEqual([]); - expect(state.tokenBudget?.status).toBe('unlimited'); - expect(state.check).toBeUndefined(); - } finally { - releaseTail.resolve(); - controller.abort(); - await lead.close(); - await team.close(); - } - }, - 90_000, - ); - }, -); diff --git a/tests/agentTeamProof.test.ts b/tests/agentTeamProof.test.ts deleted file mode 100644 index b6cd1a55..00000000 --- a/tests/agentTeamProof.test.ts +++ /dev/null @@ -1,1327 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { execFileSync } from 'node:child_process'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import { - checkAgentTeamProofDelivery, - integrateAgentTeamProofDelivery, - readAgentTeamProofDelivery, - ReusedTeamCheckFailure, - type TeamFailureCache, -} from '../src/solver/agentTeamProof'; -import { commitSolverSources, git, readSolverProblem } from '../src/solver/problem'; -import { solverState } from './helpers/solver'; -import { temporaryDirectory } from './helpers/files'; -import { declarationSubmissionSchema } from '../src/solver/declarationArtifacts'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { directSolverModules } from '../src/solver/modules'; -import { prepareAgentTeamWorkspace } from '../src/solver/agentTeamWorkspace'; -import { buildAgentTeamContributions } from '../src/solver/agentTeamContributions'; -import { teamDeclarationForwarding } from '../src/solver/agentTeamForwarding'; -import { checkSolverProof } from '../src/solver/modules/evidence'; -import * as evidence from '../src/solver/modules/evidence'; -import { evaluateSolverProof } from '../src/solver/evaluation'; -import { checkedInspection } from './helpers/inspectionMarkdownNative'; -import { buildRunInspection as sourceInspection, renderRunInspection } from '../src/solver/inspection'; -import { writeSolverRunState } from '../src/solver/archive'; -import { readKnowledgeCatalog } from '../src/solver/theoremKnowledgeStore'; -import { importTeamKnowledgeDeliveries } from './helpers/nativeKnowledgeImport'; - -const buildRunInspection = checkedInspection(sourceInspection); -const roots: string[] = []; -afterEach(() => { - vi.restoreAllMocks(); - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); -const original = - 'namespace Team\ntheorem original : True := by sorry\n' + 'theorem other : True := by sorry\nend Team\n'; -const peerHelper = 'theorem reusable (n : Nat) : n = n := by rfl\n'; - -function fixture(proof = peerHelper) { - const directory = temporaryDirectory('agent-team-proof-'); - roots.push(directory); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { - source: original, - task: 'Prove both frozen statements.', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), - worktree = path.join(directory, 'child'); - git(receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, problem.baseCommit]); - const state = solverState(problem, receipt.workspaceRoot, { - runId: 'agent-team-proof-fixture', - phase: 'running', - environmentDigest: mathDigest('real lean standard environment'), - }); - const source = (root: string) => path.join(root, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync(source(worktree), original.replace('end Team', proof + 'end Team')); - 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 common = { - state, - env, - signal: new AbortController().signal, - timeoutMs: 30_000, - assertWriterStopped: () => {}, - evidenceDirectory: path.join(directory, 'runtime/agent-team/proofs'), - }; - const declarations = [{ file: 'Submission.lean', name: 'Team.reusable', type: '∀ n : Nat, n = n' }]; - const check = { ...common, agentId: 'child-1', worktree, seedCommit: problem.baseCommit, declarations }; - return { directory, receipt, problem, state, worktree, source, common, check }; -} - -function consumerWithDraft(f: ReturnType, draft: string) { - const worktree = path.join(f.directory, 'consumer'); - git(f.receipt.workspaceRoot, ['worktree', 'add', '--quiet', '--detach', worktree, f.problem.baseCommit]); - const source = original.replace('end Team', draft + 'end Team'); - const notes = 'Consumer draft: waiting for the checked Team.reusable dependency.\n'; - fs.writeFileSync(f.source(worktree), source); - fs.writeFileSync(path.join(worktree, 'RESEARCH.md'), notes); - return { worktree, source, notes, commit: commitSolverSources(f.problem, worktree) }; -} - -describe('agent-owned declaration deliveries with real Lean', () => { - it('imports a chosen unadopted delivery from its archive and checks reuse in a different problem', async () => { - const f = fixture( - 'def shift (n : Nat) : Nat := n + 1\nabbrev first := shift 0\n' + 'theorem first_eq_one : first = 1 := by rfl\n', - ); - prepareAgentTeamWorkspace({ - sourceWorktree: f.problem.workspace, - worktree: f.worktree, - seedCommit: f.problem.baseCommit, - migrationDirectory: path.join(f.directory, 'migration'), - }); - const declarations = [ - { file: 'Submission.lean', name: 'Team.shift', type: 'Nat → Nat', kind: 'definition' as const }, - { file: 'Submission.lean', name: 'Team.first', type: 'Nat', kind: 'definition' as const }, - { file: 'Submission.lean', name: 'Team.first_eq_one', type: 'Team.first = 1' }, - ]; - const delivery = await checkAgentTeamProofDelivery({ - ...f.check, - declarations, - provenance: { taskId: 'gap', objectiveRevision: 2, exposures: [] }, - }); - const file = path.join(f.common.evidenceDirectory, 'deliveries', delivery.id + '.json'); - f.state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - operations: [], - adoptions: [], - deliveries: [{ id: delivery.id, taskId: 'gap', agentId: delivery.agentId, path: file }], - }; - const stateFile = path.join(f.directory, 'runtime/state.json'), - catalog = path.join(f.directory, 'catalog.json'); - writeSolverRunState(stateFile, f.state); - fs.rmSync(f.worktree, { recursive: true }); - expect(() => git(f.problem.workspace, ['cat-file', '-e', delivery.commit + '^{commit}'])).toThrow(); - expect(() => importTeamKnowledgeDeliveries(stateFile, ['1'.repeat(64)])).toThrow('team_delivery_not_found'); - execFileSync('bun', [ - 'scripts/mathematics/theoremKnowledge.ts', - 'build', - '--state', - stateFile, - '--team-delivery', - delivery.id, - '--output', - catalog, - ]); - const base = readKnowledgeCatalog(catalog).base; - expect(base).toMatchObject({ evidence: 'recorded-not-replayed', requiresFreshCheck: true }); - expect(base.entries).toHaveLength(3); - const entries = declarations.map(d => base.entries.find(e => e.name === d.name)!); - expect(entries.map(e => e.kind)).toEqual(['definition', 'definition', 'lemma']); - expect(entries[2]!.dependencies.statement).toContainEqual({ file: 'Submission.lean', name: 'Team.first' }); - expect(entries[2]!.provenance[0]).toMatchObject({ - taskId: 'gap', - sourceCommit: delivery.commit, - teamDelivery: { id: delivery.id, producerId: delivery.agentId, objectiveRevision: 2 }, - }); - const dst = bootstrapLeanTask(path.join(f.directory, 'destination'), { - source: 'namespace Team\ntheorem cross_problem : 1 = (1 : Nat) := by sorry\nend Team\n', - task: 'Prove cross_problem', - }); - const problem = readSolverProblem(dst.workspaceRoot, dst.activeProblemPath); - expect((await checkSolverProof(problem, dst.workspaceRoot, f.common.env, f.common.signal)).passed).toBe(false); - const dstFile = path.join(dst.workspaceRoot, problem.projectRelative, 'Submission.lean'); - fs.writeFileSync( - dstFile, - fs - .readFileSync(dstFile, 'utf8') - .replace( - 'theorem cross_problem', - entries.map(e => e.declaration.trimEnd()).join('\n') + '\ntheorem cross_problem', - ) - .replace('by sorry', 'by exact first_eq_one'), - ); - expect((await checkSolverProof(problem, dst.workspaceRoot, f.common.env, f.common.signal)).passed).toBe(true); - }, 90_000); - it('checks the exact failed inputs once per live team, but retries operational errors and changed inputs', async () => { - const f = fixture(), - failureCache: TeamFailureCache = new Map(); - const declarations = [{ ...f.check.declarations[0]!, type: 'False' }]; - const check = { ...f.check, declarations, failureCache }; - const verify = vi.spyOn(evidence, 'checkProjectedDeclarations'); - verify.mockRejectedValueOnce(new Error('test verifier transport unavailable')); - await expect(checkAgentTeamProofDelivery(check)).rejects.toThrow('test verifier transport unavailable'); - expect(failureCache.size).toBe(0); - await expect(checkAgentTeamProofDelivery(check)).rejects.toThrow('math_declaration_artifact_check_failed'); - expect(failureCache.size).toBe(1); - const firstCommit = git(f.worktree, ['rev-parse', 'HEAD']); - fs.writeFileSync(path.join(f.worktree, 'RESEARCH.md'), 'Re-examine the same interface.\n'); - await expect(checkAgentTeamProofDelivery(check)).rejects.toMatchObject({ - previous: { commit: firstCommit, agentId: 'child-1' }, - }); - expect(verify).toHaveBeenCalledTimes(2); - const changedEnv = { ...check.env, LANG: 'C' }; - await expect(checkAgentTeamProofDelivery({ ...check, env: changedEnv })).rejects.toThrow( - 'math_declaration_artifact_check_failed', - ); - expect(verify).toHaveBeenCalledTimes(3); - fs.writeFileSync( - f.source(f.worktree), - fs.readFileSync(f.source(f.worktree), 'utf8').replace(':= by rfl', ':= by exact rfl'), - ); - const changed = await checkAgentTeamProofDelivery(check).catch(error => error); - expect(changed).not.toBeInstanceOf(ReusedTeamCheckFailure); - expect(verify).toHaveBeenCalledTimes(4); - const fixed = await checkAgentTeamProofDelivery({ ...check, declarations: f.check.declarations }); - expect(fixed.artifacts[0]?.proof.passed).toBe(true); - expect(verify).toHaveBeenCalledTimes(5); - }, 90_000); - - it('rechecks explicitly nominated auxiliary definitions in the consumer without proving original goals', async () => { - const def = 'def successor (n : Nat) : Nat := n + 1\nabbrev base : Nat := successor 0\n'; - const f = fixture(); - fs.writeFileSync(f.source(f.worktree), original.replace('theorem original', def + 'theorem original')); - const declarations = ['successor', 'base'].map((name, i) => ({ - file: 'Submission.lean', - name: 'Team.' + name, - type: i === 0 ? 'Nat → Nat' : 'Nat', - kind: 'definition' as const, - })); - const delivery = await checkAgentTeamProofDelivery({ ...f.check, declarations }); - const restored = readAgentTeamProofDelivery( - path.join(f.common.evidenceDirectory, 'deliveries', delivery.id + '.json'), - f.state, - ); - const consumer = consumerWithDraft(f, 'theorem base_eq_one : base = 1 := by rfl\n'); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery: restored, - worktree: consumer.worktree, - expectedCommit: consumer.commit, - }); - expect(adoption.artifacts.map(a => [a.declaration.kind, a.proof.commit, a.proof.verification.status])).toEqual( - declarations.map(() => ['definition', adoption.commit, 'kernel_verified']), - ); - const delivered = delivery.artifacts.map(a => a.proof.verification); - const adopted = adoption.artifacts.map(a => a.proof.verification); - for (const batch of [delivered, adopted]) { - expect(new Set(batch.map(v => v.sessionId)).size).toBe(1); - expect(batch.map(v => v.results.map(r => r.theoremName))).toEqual(declarations.map(d => [d.name])); - expect(new Set(batch.map(v => v.results[0]!.receiptId)).size).toBe(2); - } - expect(delivered[0]!.sessionId).not.toBe(adopted[0]!.sessionId); - const merged = fs.readFileSync(f.source(consumer.worktree), 'utf8'); - expect(merged).toContain(def); - expect(merged.match(/by sorry/gu)).toHaveLength(2); - expect(f.state.check).toBeUndefined(); - const later = await checkAgentTeamProofDelivery({ - ...f.check, - worktree: consumer.worktree, - seedCommit: f.problem.baseCommit, - declarations: [...declarations, { file: 'Submission.lean', name: 'Team.base_eq_one', type: 'Team.base = 1' }], - }); - expect(later.artifacts.at(-1)!.proof.verification.status).toBe('kernel_verified'); - }, 90_000); - - it('adopts two checked helpers even when an unrelated consumer draft fails to elaborate', async () => { - const f = fixture(peerHelper + 'theorem second : True := by trivial\n'); - const declarations = [...f.check.declarations, { file: 'Submission.lean', name: 'Team.second', type: 'True' }]; - const delivery = await checkAgentTeamProofDelivery({ ...f.check, declarations }); - const draft = 'theorem unresolved : True := by exact missing_proof\n'; - const consumer = consumerWithDraft(f, 'theorem established : True := by trivial\n' + draft); - const verify = vi.spyOn(evidence, 'checkProjectedDeclarations'); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: consumer.worktree, - expectedCommit: consumer.commit, - }); - expect(verify.mock.calls.map(([, , , , targets]) => targets.map(target => target.theoremName))).toEqual([ - ['Team.reusable', 'Team.second'], - ['Team.reusable'], - ['Team.second'], - ]); - expect(adoption.artifacts.map(a => a.proof.verification.status)).toEqual(['kernel_verified', 'kernel_verified']); - expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toContain(draft); - }, 90_000); - - it('refuses incorrect types, incomplete bodies and replacement of an existing definition', async () => { - const body = 'def encode (n : Nat) : Nat := n + 1\n', - f = fixture(body); - const decl = { file: 'Submission.lean', name: 'Team.encode', type: 'Nat → Nat', kind: 'definition' as const }; - const submit = (type = decl.type, seedCommit = f.problem.baseCommit) => - checkAgentTeamProofDelivery({ ...f.check, seedCommit, declarations: [{ ...decl, type }] }); - await expect(submit('Nat → Bool')).rejects.toThrow(/check_failed/); - const seedCommit = git(f.worktree, ['rev-parse', 'HEAD']); - fs.writeFileSync(f.source(f.worktree), original.replace('end Team', body.replace('n + 1', 'n + 2') + 'end Team')); - await expect(submit(decl.type, seedCommit)).rejects.toThrow(/definition_must_be_new/); - fs.writeFileSync( - f.source(f.worktree), - original.replace('end Team', body.replace('n + 1', 'by sorry') + 'end Team'), - ); - await expect(submit()).rejects.toThrow(); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it('evaluates the checked commit even if the worker keeps editing afterward', async () => { - const f = fixture(); - const verifiedSource = original.replaceAll('by sorry', 'by trivial'); - fs.writeFileSync(f.source(f.worktree), verifiedSource); - const checked = await checkSolverProof(f.problem, f.worktree, f.common.env, f.common.signal); - expect(checked.passed).toBe(true); - const laterSource = verifiedSource.replaceAll('by trivial', 'by exact True.intro'); - fs.writeFileSync(f.source(f.worktree), laterSource); - - const evaluation = await evaluateSolverProof(f.problem, checked, f.common.env, f.common.signal, { - command: "grep -qFx 'theorem original : True := by trivial' Submission.lean", - timeoutMs: 30_000, - }); - - expect(evaluation).toMatchObject({ status: 'passed', method: 'external-command', result: { exitCode: 0 } }); - expect(git(f.problem.workspace, ['rev-parse', 'HEAD'])).toBe(checked.commit); - expect(fs.readFileSync(f.source(f.worktree), 'utf8')).toBe(laterSource); - }, 30_000); - - it('matches versions and separates final direct, transitive, absent and unknown references', async () => { - const f = fixture(), - problem = f.problem, - lead = path.join(f.directory, 'runtime/worktree'); - git(problem.workspace, ['worktree', 'add', '--quiet', '--detach', lead, problem.baseCommit]); - const names = ['deep', 'helper', 'side', 'changed']; - fs.writeFileSync( - f.source(f.worktree), - original.replace( - 'theorem original', - names.map(n => 'theorem ' + n + ' : True := by ' + (n === 'helper' ? 'exact deep' : 'trivial')).join('\n') + - '\ntheorem original', - ), - ); - const declarations = names.map(n => ({ file: 'Submission.lean', name: 'Team.' + n, type: 'True' })); - const delivery = await checkAgentTeamProofDelivery({ ...f.check, declarations }); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: lead, - expectedCommit: problem.baseCommit, - }); - const state = f.state; - state.worktree = lead; - state.researchMode = 'skill'; - state.workerCount = 1; - state.researchDelegation = { mode: 'team', maxAgents: 2 }; - const reference = { - id: delivery.id, - agentId: f.check.agentId, - taskId: 'task', - path: path.join(f.common.evidenceDirectory, 'deliveries', delivery.id + '.json'), - }; - state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - operations: [], - deliveries: [reference], - adoptions: [ - { - id: 'selected', - targetId: 'lead', - deliveryId: delivery.id, - expectedCommit: problem.baseCommit, - commit: adoption.commit, - status: 'completed', - }, - ], - }; - const edited = fs - .readFileSync(f.source(lead), 'utf8') - .replace('changed : True := by trivial', 'changed : True := True.intro') - .replace('original : True := by sorry', 'original : True := by exact helper') - .replace('other : True := by sorry', 'other : True := by exact changed'); - fs.writeFileSync(f.source(lead), edited); - state.check = await checkSolverProof(problem, lead, f.common.env, f.common.signal); - expect(state.check.passed).toBe(true); - const evaluation = await evaluateSolverProof(problem, state.check, f.common.env, f.common.signal, { - timeoutMs: 30_000, - teamContributions: true, - }); - expect(evaluation.status).toBe('passed'); - const report = buildAgentTeamContributions(state, evaluation), - relations = (r: typeof report) => - Object.fromEntries(r.declarations.map(d => [d.name, d.targets.map(t => t.relation)])); - expect(relations(report)).toEqual({ - 'Team.deep': ['indirect', 'not-referenced'], - 'Team.helper': ['direct', 'not-referenced'], - 'Team.side': ['not-referenced', 'not-referenced'], - 'Team.changed': ['unknown', 'unknown'], - }); - const old = structuredClone(evaluation); - delete (old.verification as typeof state.check).verification.results[0]!.directProofReferences; - delete (old.verification as typeof state.check).verification.results[1]!.declarationReferences; - expect(relations(buildAgentTeamContributions(state, old))['Team.helper']).toEqual(['referenced', 'unknown']); - state.phase = 'finished'; - if (process.env.THEOREMOS_TEST_PROCESS_ADDON) { - for (const e of [evaluation, old]) { - // Rebuild from the frozen delivery, Git commits and the evaluator's original receipts. - const rebuilt = buildRunInspection(state, { - runId: state.runId, - solution_commit: state.check.commit, - status: 'evaluated_passed', - evaluator: e, - }); - expect(rebuilt.agentTeam?.contributions).toEqual(buildAgentTeamContributions(state, e)); - } - } - const inspection = buildRunInspection(state, { - runId: state.runId, - solution_commit: state.check.commit, - status: 'evaluated_passed', - evaluator: evaluation, - teamContributions: report, - }); - expect(renderRunInspection(inspection)).toContain('Team.deep | Team.original | indirect'); - state.agentTeam.adoptions = []; - expect(relations(buildAgentTeamContributions(state, evaluation))['Team.helper']).toEqual(['unknown', 'unknown']); - }, 90_000); - it('checks independent member evidence, survives source cleanup, and imports only during authorized adoption', async () => { - const f = fixture(), - migrationDirectory = path.join(f.directory, 'runtime/agent-team/migrations'); - const prepare = (worktree: string) => - prepareAgentTeamWorkspace({ - sourceWorktree: f.receipt.workspaceRoot, - worktree, - seedCommit: f.problem.baseCommit, - migrationDirectory, - }); - prepare(f.worktree); - const consumer = consumerWithDraft(f, 'theorem ownDraft : True := by sorry\n'); - prepare(consumer.worktree); - const provenance = { - objectiveRevision: 3, - exposures: [ - { - deliveryId: mathDigest('prior research'), - agentId: 'peer', - taskId: 'research-1', - commit: f.problem.baseCommit, - kind: 'inspected' as const, - at: '2026-11-17T00:00:00.000Z', - }, - ], - }; - const delivery = await checkAgentTeamProofDelivery({ ...f.check, provenance }); - expect(delivery.provenance).toEqual(provenance); - expect(() => - git(f.receipt.workspaceRoot, ['show', `${delivery.commit}:${f.problem.projectRelative}/Submission.lean`]), - ).toThrow(); - expect(() => - git(consumer.worktree, ['show', `${delivery.commit}:${f.problem.projectRelative}/Submission.lean`]), - ).toThrow(); - const archive = path.join(f.common.evidenceDirectory, 'sources.git'); - expect(git(archive, ['show', `${delivery.commit}:${f.problem.projectRelative}/Submission.lean`])).toContain( - 'theorem reusable', - ); - for (const artifact of delivery.artifacts) - expect(git(archive, ['rev-parse', `${artifact.proof.verification.targetCommit}^{commit}`])).toBe( - artifact.proof.verification.targetCommit, - ); - fs.rmSync(f.worktree, { recursive: true }); - const restored = readAgentTeamProofDelivery( - path.join(f.common.evidenceDirectory, 'deliveries', `${delivery.id}.json`), - f.state, - ); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery: restored, - worktree: consumer.worktree, - expectedCommit: consumer.commit, - }); - expect(git(consumer.worktree, ['rev-parse', 'HEAD'])).toBe(adoption.commit); - expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toContain('theorem ownDraft : True := by sorry'); - expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toContain(peerHelper); - expect(fs.readFileSync(path.join(consumer.worktree, 'RESEARCH.md'), 'utf8')).toBe(consumer.notes); - expect( - await integrateAgentTeamProofDelivery({ - ...f.common, - delivery: restored, - worktree: consumer.worktree, - expectedCommit: consumer.commit, - }), - ).toEqual(adoption); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it('freezes a helper in a separate worktree, restores its record, and adopts only after a fresh check', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - expect(delivery.artifacts[0]!.proof.verification.results[0]).toMatchObject({ - status: 'kernel_verified', - theoremName: 'Team.reusable', - sorryCount: 0, - admitCount: 0, - }); - const file = path.join(f.common.evidenceDirectory, 'deliveries', `${delivery.id}.json`); - expect(fs.statSync(file).mode & 0o777).toBe(0o400); - const restored = readAgentTeamProofDelivery(file, f.state); - expect(restored).toEqual(delivery); - // Frozen commits, not the mutable child directory, survive thread/worktree cleanup. - git(f.worktree, ['worktree', 'remove', '--force', f.worktree]); - fs.writeFileSync( - f.source(f.receipt.workspaceRoot), - original.replace('end Team', 'theorem peer : True := by trivial\nend Team'), - ); - const beforeCommit = commitSolverSources(f.problem, f.receipt.workspaceRoot); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery: restored, - worktree: f.receipt.workspaceRoot, - expectedCommit: beforeCommit, - }); - const merged = fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8'); - expect(merged).toContain('theorem reusable'); - expect(merged).toContain('theorem peer'); - expect(merged.match(/by sorry/gu)).toHaveLength(2); - expect(adoption).toMatchObject({ deliveryId: delivery.id, beforeCommit }); - expect(adoption.artifacts[0]!.proof.commit).toBe(adoption.commit); - expect(adoption.artifacts[0]!.proof.verification.results[0]!.status).toBe('kernel_verified'); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(adoption.commit); - expect(fs.statSync(path.join(f.common.evidenceDirectory, 'adoptions', `${adoption.id}.json`)).mode & 0o777).toBe( - 0o400, - ); - expect(f.state.phase).toBe('running'); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it('imports legacy shared-repository evidence into a migrated independent receiver', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - // Older runs retained these objects only in the primary common repository. - fs.rmSync(path.join(f.common.evidenceDirectory, 'sources.git'), { recursive: true }); - git(f.receipt.workspaceRoot, ['worktree', 'remove', '--force', f.worktree]); - const consumer = consumerWithDraft(f, 'theorem ownDraft : True := by sorry\n'); - prepareAgentTeamWorkspace({ - sourceWorktree: f.receipt.workspaceRoot, - worktree: consumer.worktree, - seedCommit: f.problem.baseCommit, - migrationDirectory: path.join(f.directory, 'runtime/agent-team/migrations'), - }); - expect(() => git(consumer.worktree, ['cat-file', '-e', `${delivery.commit}^{commit}`])).toThrow(); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: consumer.worktree, - expectedCommit: consumer.commit, - }); - expect(git(consumer.worktree, ['rev-parse', 'HEAD'])).toBe(adoption.commit); - expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toContain(peerHelper); - expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toContain('theorem ownDraft'); - }, 90_000); - - it('adopts an explicitly delivered original theorem without accepting unfinished original targets', async () => { - const f = fixture(); - fs.writeFileSync( - f.source(f.worktree), - original.replace('original : True := by sorry', 'original : True := by trivial'), - ); - const delivery = await checkAgentTeamProofDelivery({ - ...f.check, - declarations: [{ file: 'Submission.lean', name: 'Team.original', type: 'True' }], - }); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: f.receipt.workspaceRoot, - expectedCommit: f.problem.baseCommit, - }); - expect(fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8')).toBe( - original.replace('original : True := by sorry', 'original : True := by trivial'), - ); - expect(adoption.artifacts).toHaveLength(1); - expect(adoption.artifacts[0]!.declaration.name).toBe('Team.original'); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it.each(['lead', 'member'] as const)( - 'persists recipient bookkeeping together with completed %s adoption', - async targetId => { - const f = fixture(), - member = targetId === 'member' ? consumerWithDraft(f, 'theorem ownDraft : True := by trivial\n') : undefined; - const evidenceDirectory = path.join(f.directory, 'agent-team/proofs'); - const delivery = await checkAgentTeamProofDelivery({ ...f.check, evidenceDirectory }); - f.state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - events: [], - operations: [], - workers: member - ? [ - { - id: targetId, - role: 'researcher', - worktree: member.worktree, - seedCommit: f.problem.baseCommit, - pendingSourceBase: f.problem.baseCommit, - status: 'idle', - activity: 'idle', - phase: 'prepared', - cursor: 0, - turns: 0, - tasks: [], - }, - ] - : [], - deliveries: [ - { - id: delivery.id, - agentId: delivery.agentId, - taskId: 'task', - path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json'), - }, - ], - adoptions: [{ id: 'adoption', deliveryId: delivery.id, targetId, status: 'queued' }], - }; - const snapshots: (typeof f.state)[] = []; - const access = { environment: f.common.env, retrievalRoot: f.state.worktree }; - const team = new AgentResearchTeam({ - state: f.state, - root: process.cwd(), - taskText: 'Check a local handoff.', - leadAccess: access, - prepareWorker: async () => access, - modules: directSolverModules, - executable: 'unused', - profile: 'unused', - signal: f.common.signal, - maxAgents: 3, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - proofTimeoutMs: f.common.timeoutMs, - remainingMs: () => Infinity, - save: () => { - snapshots.push(JSON.parse(JSON.stringify(f.state))); - }, - emit: () => {}, - exclusiveCheck: fn => fn(), - }); - try { - await team.flushAdoptions(targetId); - const completed = snapshots.find(s => s.agentTeam?.adoptions[0]?.status === 'completed')!; - const commit = completed.agentTeam!.adoptions[0]!.commit; - expect(commit).toBe(git(member?.worktree ?? f.state.worktree, ['rev-parse', 'HEAD'])); - expect(completed.agentTeam!.events.at(-1)).toMatchObject({ - kind: 'adopted', - to: targetId, - deliveryId: delivery.id, - }); - if (member) - expect(completed.agentTeam!.workers[0]).toMatchObject({ - activity: 'idle', - pendingSourceBase: f.problem.baseCommit, - pendingPeerDeliveries: [delivery.id], - }); - else - expect(completed.pendingResearchFreeze).toMatchObject({ - commit, - problemReceiptDigest: f.problem.receiptDigest, - }); - } finally { - await team.close(); - } - }, - 90_000, - ); - - it('names the missing previous declaration revision before running Lean on a patch', async () => { - const f = fixture(), - prior = await checkAgentTeamProofDelivery(f.check); - const revised = peerHelper.replace('by rfl', 'by exact Eq.refl n'); - fs.writeFileSync(f.source(f.worktree), original.replace('end Team', revised + 'end Team')); - const delivery = await checkAgentTeamProofDelivery({ ...f.check, seedCommit: prior.commit }); - const target = { ...f.common, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; - const verify = vi.spyOn(evidence, 'checkProjectedDeclarations'); - await expect(integrateAgentTeamProofDelivery({ ...target, delivery })).rejects.toMatchObject({ - name: 'DeclarationSubmissionError', - message: expect.stringContaining(`reusable (Submission.lean) at the delivery's seed revision ${prior.commit}`), - }); - expect(verify).not.toHaveBeenCalled(); - expect(git(target.worktree, ['rev-parse', 'HEAD'])).toBe(target.expectedCommit); - const adopted = await integrateAgentTeamProofDelivery({ ...target, delivery: prior }); - const result = await integrateAgentTeamProofDelivery({ ...target, delivery, expectedCommit: adopted.commit }); - expect(result.artifacts[0]!.proof.verification.status).toBe('kernel_verified'); - expect(fs.readFileSync(f.source(target.worktree), 'utf8')).toContain(revised); - }, 90_000); - - it.each([ - { - prerequisite: 'theorem reusable (n : Nat) : n = n := by rfl\n', - declaration: { name: 'Team.reusable', type: '∀ n : Nat, n = n' }, - dependent: 'theorem downstream (n : Nat) : n = n := by exact reusable n\n', - dependentType: '∀ n : Nat, n = n', - }, - { - prerequisite: 'def shift (n : Nat) : Nat := n + 1\n', - declaration: { name: 'Team.shift', type: 'Nat → Nat', kind: 'definition' as const }, - dependent: 'theorem downstream (n : Nat) : shift n = n + 1 := by rfl\n', - dependentType: '∀ n : Nat, Team.shift n = n + 1', - }, - ])( - 'identifies missing $declaration.name and checks the delivery again after it is adopted', - async example => { - const f = fixture(example.prerequisite); - const prerequisite = await checkAgentTeamProofDelivery({ - ...f.check, - declarations: [{ file: 'Submission.lean', ...example.declaration }], - }); - fs.writeFileSync( - f.source(f.worktree), - original.replace('end Team', example.prerequisite + example.dependent + 'end Team'), - ); - const delivery = await checkAgentTeamProofDelivery({ - ...f.check, - seedCommit: prerequisite.commit, - declarations: [{ file: 'Submission.lean', name: 'Team.downstream', type: example.dependentType }], - }); - const target = { ...f.common, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; - await expect(integrateAgentTeamProofDelivery({ ...target, delivery })).rejects.toThrow( - `The recipient is missing ${example.declaration.name} (Submission.lean).`, - ); - expect(git(target.worktree, ['rev-parse', 'HEAD'])).toBe(target.expectedCommit); - expect(fs.readFileSync(f.source(target.worktree), 'utf8')).toBe(original); - const adopted = await integrateAgentTeamProofDelivery({ ...target, delivery: prerequisite }); - const result = await integrateAgentTeamProofDelivery({ ...target, delivery, expectedCommit: adopted.commit }); - expect(result.artifacts[0]!.proof.verification.results[0]).toMatchObject({ - status: 'kernel_verified', - theoremName: 'Team.downstream', - }); - expect(fs.readFileSync(f.source(target.worktree), 'utf8')).toContain(example.dependent); - }, - 90_000, - ); - - it('preserves a fixed unfinished consumer draft while adopting its missing peer dependency and recovering the same transition', async () => { - const f = fixture(); - fs.writeFileSync(f.source(f.worktree), original.replace('theorem original', peerHelper + 'theorem original')); - const draft = 'theorem downstream (n : Nat) : n = n := by\n have h := reusable n\n sorry\n'; - const consumer = consumerWithDraft(f, draft); - const downstream = { file: 'Submission.lean', name: 'Team.downstream', type: '∀ n : Nat, n = n' }; - await expect( - checkAgentTeamProofDelivery({ - ...f.check, - agentId: 'consumer', - worktree: consumer.worktree, - declarations: [downstream], - }), - ).rejects.toThrow('math_declaration_artifact_check_failed'); - const delivery = await checkAgentTeamProofDelivery(f.check); - const input = { ...f.common, delivery, worktree: consumer.worktree, expectedCommit: consumer.commit }; - const adoption = await integrateAgentTeamProofDelivery(input); - const expected = consumer.source.replace('theorem original', peerHelper + 'theorem original'); - expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toBe(expected); - expect(fs.readFileSync(path.join(consumer.worktree, 'RESEARCH.md'), 'utf8')).toBe(consumer.notes); - expect(git(consumer.worktree, ['show', `${consumer.commit}:${f.problem.projectRelative}/Submission.lean`])).toBe( - consumer.source.trim(), - ); - expect(adoption.beforeCommit).toBe(consumer.commit); - expect(adoption.artifacts.map(artifact => artifact.declaration.name)).toEqual(['Team.reusable']); - expect(adoption.artifacts[0]!.proof.verification.results[0]).toMatchObject({ - status: 'kernel_verified', - sorryCount: 0, - }); - expect(f.state.check).toBeUndefined(); - const recovered = { - ...input, - state: structuredClone(f.state), - delivery: readAgentTeamProofDelivery( - path.join(f.common.evidenceDirectory, 'deliveries', `${delivery.id}.json`), - f.state, - ), - }; - expect(await integrateAgentTeamProofDelivery(recovered)).toEqual(adoption); - expect(git(consumer.worktree, ['rev-parse', 'HEAD'])).toBe(adoption.commit); - expect(fs.readFileSync(f.source(consumer.worktree), 'utf8')).toBe(expected); - fs.writeFileSync( - f.source(consumer.worktree), - expected.replace(draft, 'theorem downstream (n : Nat) : n = n := by exact reusable n\n'), - ); - const completed = await checkAgentTeamProofDelivery({ - ...f.check, - agentId: 'consumer', - worktree: consumer.worktree, - declarations: [...delivery.declarations, downstream], - }); - expect(completed.seedCommit).toBe(f.problem.baseCommit); - expect(completed.artifacts.map(artifact => artifact.declaration.name)).toEqual([ - 'Team.reusable', - 'Team.downstream', - ]); - expect(completed.artifacts.every(artifact => artifact.proof.verification.status === 'kernel_verified')).toBe(true); - }, 90_000); - - it('re-delivers an adopted peer and a new consumer declaration into a Lead already owning the identical peer', async () => { - const f = fixture(); - fs.writeFileSync(f.source(f.worktree), original.replace('theorem original', peerHelper + 'theorem original')); - const draft = 'theorem downstream (n : Nat) : n = n := by exact reusable n\n'; - const consumer = consumerWithDraft(f, draft), - delivery = await checkAgentTeamProofDelivery(f.check); - const peerAdoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: consumer.worktree, - expectedCommit: consumer.commit, - }); - const lead = f.receipt.workspaceRoot; - const leadAdoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: lead, - expectedCommit: f.problem.baseCommit, - }); - const downstream = { file: 'Submission.lean', name: 'Team.downstream', type: '∀ n : Nat, n = n' }; - // Keeping the consumer's original delivery baseline requires accounting for the adopted delta too. - await expect( - checkAgentTeamProofDelivery({ - ...f.check, - agentId: 'consumer', - worktree: consumer.worktree, - declarations: [downstream], - }), - ).rejects.toThrow('math_agent_team_proof_undeclared_source_change'); - const combined = await checkAgentTeamProofDelivery({ - ...f.check, - agentId: 'consumer', - worktree: consumer.worktree, - declarations: [...delivery.declarations, downstream], - provenance: { - exposures: [ - { - kind: 'adopted', - agentId: delivery.agentId, - taskId: 'first', - deliveryId: delivery.id, - commit: delivery.commit, - at: new Date().toISOString(), - }, - ], - }, - }); - expect(combined.changes.map(change => change.name)).toEqual(['reusable', 'downstream']); - const adoption = await integrateAgentTeamProofDelivery({ - ...f.common, - delivery: combined, - worktree: lead, - expectedCommit: leadAdoption.commit, - }); - const source = fs.readFileSync(f.source(lead), 'utf8'); - expect(source.match(/theorem reusable/gu)).toHaveLength(1); - expect(source).toContain(draft); - expect(source.match(/by sorry/gu)).toHaveLength(2); - expect(adoption.artifacts.map(artifact => artifact.declaration.name)).toEqual(['Team.reusable', 'Team.downstream']); - expect( - adoption.artifacts.every( - artifact => - artifact.proof.commit === adoption.commit && artifact.proof.verification.status === 'kernel_verified', - ), - ).toBe(true); - expect(f.state.check).toBeUndefined(); - f.state.worktree = path.join(f.directory, 'runtime/worktree'); - f.state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - operations: [], - adoptions: [ - { - id: 'to-consumer', - deliveryId: delivery.id, - targetId: 'consumer', - status: 'completed', - commit: peerAdoption.commit, - expectedCommit: peerAdoption.beforeCommit, - }, - ], - deliveries: [delivery, combined].map(d => ({ - id: d.id, - agentId: d.agentId, - taskId: d.id === delivery.id ? 'first' : 'second', - path: path.join(f.common.evidenceDirectory, 'deliveries', d.id + '.json'), - })), - }; - const report = buildAgentTeamContributions(f.state, {}); - expect( - report.declarations.find(d => d.agentId === 'consumer' && d.name === 'Team.reusable')?.forwardedFrom, - ).toEqual([delivery.id]); - expect( - report.declarations.find(d => d.agentId === 'consumer' && d.name === 'Team.downstream')?.forwardedFrom, - ).toEqual([]); - const stateFile = path.join(f.directory, 'runtime/state.json'); - const imported = () => { - writeSolverRunState(stateFile, f.state); - const rows = importTeamKnowledgeDeliveries(stateFile, [combined.id]).candidates; - expect(rows.map(r => r.name)).toEqual(['Team.reusable', 'Team.downstream']); - return rows.map(r => r.provenance.teamDelivery!); - }; - const [peer, own] = imported(); - expect(peer).toMatchObject({ - id: combined.id, - producerId: 'consumer', - forwardedFrom: [{ deliveryId: delivery.id, producerId: delivery.agentId, taskId: 'first' }], - }); - expect(own).not.toHaveProperty('forwardedFrom'); - const transfers = teamDeclarationForwarding(f.state, f.common.evidenceDirectory); - expect( - transfers.origins( - { - ...combined, - provenance: { exposures: combined.provenance!.exposures!.map(e => ({ ...e, kind: 'inspected' as const })) }, - }, - 'Submission.lean', - 'Team.reusable', - ), - ).toEqual([]); - expect( - transfers.origins( - { - ...combined, - changes: combined.changes.map(c => - c.name === 'reusable' ? { ...c, after: c.after.replace('by rfl', 'by simp') } : c, - ), - }, - 'Submission.lean', - 'Team.reusable', - ), - ).toEqual([]); - // Adoption without a source change cannot establish that the declaration came from the peer. - const transfer = f.state.agentTeam.adoptions[0]!; - transfer.expectedCommit = transfer.commit; - expect(imported()[0]).not.toHaveProperty('forwardedFrom'); - transfer.expectedCommit = peerAdoption.beforeCommit; - // Leave the selected delivery intact while its optional upstream record becomes unavailable. - fs.unlinkSync(path.join(f.common.evidenceDirectory, 'deliveries', delivery.id + '.json')); - expect(imported()[0]).not.toHaveProperty('forwardedFrom'); - }, 90_000); - - it('freshly checks and restores a host combination of one adopted peer plus a full 32-declaration member submission', async () => { - const f = fixture(); - fs.writeFileSync(f.source(f.worktree), original.replace('theorem original', peerHelper + 'theorem original')); - const names = Array.from({ length: 32 }, (_, index) => `own${index}`); - const draft = names.map(name => `theorem ${name} (n : Nat) : n = n := by exact reusable n\n`).join(''); - const consumer = consumerWithDraft(f, draft), - peer = await checkAgentTeamProofDelivery(f.check); - await integrateAgentTeamProofDelivery({ - ...f.common, - delivery: peer, - worktree: consumer.worktree, - expectedCommit: consumer.commit, - }); - const own = names.map(name => ({ file: 'Submission.lean', name: `Team.${name}`, type: '∀ n : Nat, n = n' })); - const declarations = [...peer.declarations, ...own]; - expect(declarationSubmissionSchema.safeParse({ declarations: own }).success).toBe(true); - expect(declarationSubmissionSchema.safeParse({ declarations }).success).toBe(false); - // The last entry repeats the first and leaves a change unnamed. - await expect( - checkAgentTeamProofDelivery({ - ...f.check, - agentId: 'consumer', - worktree: consumer.worktree, - declarations: [...declarations.slice(0, 32), peer.declarations[0]], - }), - ).rejects.toThrow('math_agent_team_proof_undeclared_source_change'); - const combined = await checkAgentTeamProofDelivery({ - ...f.check, - agentId: 'consumer', - worktree: consumer.worktree, - declarations, - }); - expect(combined.artifacts).toHaveLength(33); - expect(combined.artifacts.map(artifact => artifact.declaration.name)).toEqual([ - 'Team.reusable', - ...own.map(item => item.name), - ]); - expect( - combined.artifacts.every( - artifact => - artifact.proof.commit === combined.commit && artifact.proof.verification.status === 'kernel_verified', - ), - ).toBe(true); - const restored = readAgentTeamProofDelivery( - path.join(f.common.evidenceDirectory, 'deliveries', `${combined.id}.json`), - f.state, - ); - expect(restored).toEqual(combined); - const input = { - ...f.common, - delivery: restored, - worktree: f.receipt.workspaceRoot, - expectedCommit: f.problem.baseCommit, - }; - const adoption = await integrateAgentTeamProofDelivery(input); - expect(adoption.artifacts).toHaveLength(33); - expect( - adoption.artifacts.every( - artifact => - artifact.proof.commit === adoption.commit && artifact.proof.verification.status === 'kernel_verified', - ), - ).toBe(true); - expect(adoption.artifacts[32].declaration.name).toBe('Team.own31'); - expect(await integrateAgentTeamProofDelivery(input)).toEqual(adoption); - const source = fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8'); - expect(source).toContain(draft); - expect(source.match(/theorem reusable/gu)).toHaveLength(1); - expect(source.match(/by sorry/gu)).toHaveLength(2); - expect(f.state.check).toBeUndefined(); - }, 180_000); - - it('rejects an incorrect proof and a false claimed type without publishing evidence', async () => { - const f = fixture('theorem reusable (n : Nat) : n = n := by exact False.elim (by trivial)\n'); - await expect(checkAgentTeamProofDelivery(f.check)).rejects.toThrow('math_declaration_artifact_check_failed'); - expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - fs.writeFileSync( - f.source(f.worktree), - original.replace('end Team', peerHelper + 'theorem second : True := by trivial\nend Team'), - ); - await expect( - checkAgentTeamProofDelivery({ - ...f.check, - declarations: [...f.check.declarations, { file: 'Submission.lean', name: 'Team.second', type: 'False' }], - }), - ).rejects.toThrow('math_declaration_artifact_check_failed:Team.second'); - expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - expect(fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8')).toBe(original); - }, 90_000); - - it.each(['helper', 'definition', 'original-proof'] as const)('rejects an undeclared %s change', async kind => { - const f = fixture(), - file = f.source(f.worktree); - const addition = kind === 'helper' ? 'theorem hidden : True := by trivial\n' : 'def hidden : Nat := 3\n'; - fs.writeFileSync( - file, - kind === 'original-proof' - ? fs.readFileSync(file, 'utf8').replace('original : True := by sorry', 'original : True := by trivial') - : fs.readFileSync(file, 'utf8').replace('end Team', addition + 'end Team'), - ); - await expect(checkAgentTeamProofDelivery(f.check)).rejects.toThrow( - 'math_agent_team_proof_undeclared_source_change', - ); - expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - }); - - it.each(['name', 'file'] as const)('reports an invalid declaration %s as correctable delivery input', async field => { - const f = fixture(); - const declaration = { - ...f.check.declarations[0]!, - ...(field === 'name' ? { name: 'Team.missing' } : { file: 'Unowned.lean' }), - }; - await expect(checkAgentTeamProofDelivery({ ...f.check, declarations: [declaration] })).rejects.toThrow( - field === 'name' - ? 'math_agent_team_proof_declaration_missing' - : 'math_agent_team_proof_declaration_outside_ownership', - ); - expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - expect(fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8')).toBe(original); - }); - - it('preserves actual Git and filesystem failures as infrastructure errors', async () => { - const f = fixture(); - await expect(checkAgentTeamProofDelivery({ ...f.check, seedCommit: 'f'.repeat(40) })).rejects.toThrow( - 'math_git_failed:merge-base', - ); - fs.unlinkSync(f.source(f.worktree)); - await expect(checkAgentTeamProofDelivery(f.check)).rejects.toMatchObject({ code: 'ENOENT' }); - expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - }); - - it('preserves the Git diagnostic when an existing seed commit is missing the owned source', async () => { - const f = fixture(), - file = f.source(f.worktree), - source = fs.readFileSync(file); - const relative = path.relative(f.worktree, file); - git(f.worktree, ['rm', '--force', '--quiet', '--', relative]); - git(f.worktree, [ - '-c', - 'user.name=Fixture', - '-c', - 'user.email=fixture@localhost', - 'commit', - '--no-gpg-sign', - '--quiet', - '-m', - 'Fixture without the owned source', - ]); - const seedCommit = git(f.worktree, ['rev-parse', 'HEAD']); - fs.writeFileSync(file, source); - commitSolverSources(f.problem, f.worktree); - await expect(checkAgentTeamProofDelivery({ ...f.check, seedCommit })).rejects.toMatchObject({ - message: 'math_task_source_unavailable', - diagnostic: { command: 'show', commit: seedCommit, file: relative }, - }); - expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - }); - - it("rechecks changed dependencies instead of accepting the child's historical receipt", async () => { - const f = fixture(); - const established = original.replace('end Team', 'theorem established : True := by trivial\nend Team'); - fs.writeFileSync(f.source(f.receipt.workspaceRoot), established); - const seedCommit = commitSolverSources(f.problem, f.receipt.workspaceRoot); - git(f.worktree, ['reset', '--hard', seedCommit]); - fs.writeFileSync( - f.source(f.worktree), - established.replace('end Team', 'theorem reusable : True := by exact established\nend Team'), - ); - const delivery = await checkAgentTeamProofDelivery({ - ...f.check, - seedCommit, - declarations: [{ file: 'Submission.lean', name: 'Team.reusable', type: 'True' }], - }); - const invalidated = established.replace('established : True := by trivial', 'established : True := by sorry'); - fs.writeFileSync(f.source(f.receipt.workspaceRoot), invalidated); - const before = commitSolverSources(f.problem, f.receipt.workspaceRoot); - await expect( - integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: f.receipt.workspaceRoot, - expectedCommit: before, - }), - ).rejects.toThrow('math_declaration_artifact_check_failed'); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(before); - expect(fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8')).toBe(invalidated); - expect(fs.existsSync(path.join(f.common.evidenceDirectory, 'adoptions'))).toBe(false); - }, 90_000); - - it('requires confirmed writer shutdown and preserves the frozen original statement', async () => { - const f = fixture(); - await expect( - checkAgentTeamProofDelivery({ - ...f.check, - assertWriterStopped: () => { - throw new Error('writer_stop_unconfirmed'); - }, - }), - ).rejects.toThrow('writer_stop_unconfirmed'); - expect(git(f.worktree, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit); - fs.writeFileSync(f.source(f.worktree), original.replace('original : True', 'original : False')); - await expect(checkAgentTeamProofDelivery(f.check)).rejects.toThrow('math_original_declaration_changed'); - expect(fs.existsSync(f.common.evidenceDirectory)).toBe(false); - }); - - it('rejects changed identity, dirty primary source, stale expected commit, and forged patch metadata', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - const adopt = { ...f.common, delivery, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; - await expect( - integrateAgentTeamProofDelivery({ ...adopt, state: { ...f.state, environmentDigest: mathDigest('other') } }), - ).rejects.toThrow('math_agent_team_proof_delivery_identity_changed'); - const forged = { ...delivery, changes: [] }, - { id: _id, ...body } = forged; - forged.id = mathDigest(canonicalMathJson(body)); - await expect(integrateAgentTeamProofDelivery({ ...adopt, delivery: forged })).rejects.toThrow( - 'math_agent_team_proof_delivery_patch_changed', - ); - fs.appendFileSync(f.source(f.receipt.workspaceRoot), '-- primary is still writing\n'); - await expect(integrateAgentTeamProofDelivery(adopt)).rejects.toThrow('math_agent_team_proof_source_changed'); - commitSolverSources(f.problem, f.receipt.workspaceRoot); - await expect(integrateAgentTeamProofDelivery(adopt)).rejects.toThrow('math_agent_team_proof_source_changed'); - expect(fs.existsSync(path.join(f.common.evidenceDirectory, 'adoptions'))).toBe(false); - }, 90_000); - - it('does not overwrite a conflicting declaration or accept a source changed during the fresh check', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - fs.writeFileSync( - f.source(f.receipt.workspaceRoot), - original.replace('end Team', 'theorem reusable (n : Nat) : n = n := by exact Eq.refl n\nend Team'), - ); - const conflict = commitSolverSources(f.problem, f.receipt.workspaceRoot); - await expect( - integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: f.receipt.workspaceRoot, - expectedCommit: conflict, - }), - ).rejects.toThrow('math_task_integration_conflict'); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(conflict); - fs.writeFileSync(f.source(f.receipt.workspaceRoot), original); - const before = commitSolverSources(f.problem, f.receipt.workspaceRoot); - const checking = integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: f.receipt.workspaceRoot, - expectedCommit: before, - }); - fs.appendFileSync(f.source(f.receipt.workspaceRoot), '-- changed while checking\n'); - await expect(checking).rejects.toThrow('math_agent_team_proof_source_changed'); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(before); - expect(fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8')).toContain('-- changed while checking'); - expect(fs.existsSync(path.join(f.common.evidenceDirectory, 'adoptions'))).toBe(false); - }, 90_000); - - it('rejects an edit to the staged adoption while Lean is checking', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - const verify = evidence.checkProjectedDeclarations; - vi.spyOn(evidence, 'checkProjectedDeclarations').mockImplementationOnce(async (...args) => { - const result = await verify(...args); - expect(result.passed).toBe(true); - fs.appendFileSync(f.source(args[2]), '\n-- staged source changed after Lean read it\n'); - return result; - }); - await expect( - integrateAgentTeamProofDelivery({ - ...f.common, - delivery, - worktree: f.receipt.workspaceRoot, - expectedCommit: f.problem.baseCommit, - }), - ).rejects.toThrow('math_agent_team_proof_source_changed'); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit); - expect(fs.existsSync(path.join(f.common.evidenceDirectory, 'adoption-intents'))).toBe(false); - }, 90_000); - - it('recovers the exact FF after publication failed and makes the same call idempotent', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - const input = { ...f.common, delivery, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; - const adoptions = path.join(f.common.evidenceDirectory, 'adoptions'), - rename = fs.renameSync; - const failure = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { - if (String(to).startsWith(adoptions + path.sep)) throw new Error('host_disconnected_after_ff'); - rename(from, to); - }); - await expect(integrateAgentTeamProofDelivery(input)).rejects.toThrow('host_disconnected_after_ff'); - failure.mockRestore(); - const head = git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD']); - expect(head).not.toBe(f.problem.baseCommit); - const directory = path.join(f.common.evidenceDirectory, 'adoption-intents'), - files = fs.readdirSync(directory); - expect(files).toHaveLength(1); - const file = path.join(directory, files[0]!), - intent = JSON.parse(fs.readFileSync(file, 'utf8')); - expect(intent.adoption).toMatchObject({ - commit: head, - beforeCommit: input.expectedCommit, - deliveryId: delivery.id, - }); - expect(fs.existsSync(path.join(adoptions, `${intent.adoption.id}.json`))).toBe(false); - const restoredDelivery = readAgentTeamProofDelivery( - path.join(f.common.evidenceDirectory, 'deliveries', `${delivery.id}.json`), - f.state, - ); - const restoredInput = { ...input, delivery: restoredDelivery, state: structuredClone(f.state) }; - const recovered = await integrateAgentTeamProofDelivery(restoredInput); - expect(recovered).toEqual(intent.adoption); - const publication = path.join(adoptions, `${recovered.id}.json`), - stamp = fs.statSync(publication).mtimeMs; - expect(await integrateAgentTeamProofDelivery(restoredInput)).toEqual(recovered); - expect(fs.statSync(publication).mtimeMs).toBe(stamp); - expect(fs.readdirSync(adoptions).filter(name => /^[a-f0-9]{64}\.json$/u.test(name))).toEqual([ - `${recovered.id}.json`, - ]); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(head); - expect(f.state.check).toBeUndefined(); - }, 90_000); - - it('finishes a persisted intent interrupted before FF while preserving the originally checked transition', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - const input = { ...f.common, delivery, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; - const directory = path.join(f.common.evidenceDirectory, 'adoption-intents'); - await expect( - integrateAgentTeamProofDelivery({ - ...input, - assertWriterStopped: () => { - if (fs.existsSync(directory) && fs.readdirSync(directory).length) - throw new Error('host_disconnected_before_ff'); - }, - }), - ).rejects.toThrow('host_disconnected_before_ff'); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(input.expectedCommit); - const file = path.join(directory, fs.readdirSync(directory)[0]!), - stamp = fs.statSync(file).mtimeMs; - const intent = JSON.parse(fs.readFileSync(file, 'utf8')); - const adoption = await integrateAgentTeamProofDelivery(input); - expect(adoption).toEqual(intent.adoption); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(intent.adoption.commit); - expect(fs.statSync(file).mtimeMs).toBe(stamp); - expect(fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8')).toContain('theorem reusable'); - }, 90_000); - - it('refuses dirty or unrelated HEADs and mismatched identity when recovering a completed transition', async () => { - const f = fixture(), - delivery = await checkAgentTeamProofDelivery(f.check); - const input = { ...f.common, delivery, worktree: f.receipt.workspaceRoot, expectedCommit: f.problem.baseCommit }; - const adoption = await integrateAgentTeamProofDelivery(input); - await expect( - integrateAgentTeamProofDelivery({ ...input, state: { ...f.state, runId: 'different-run' } }), - ).rejects.toThrow('delivery_identity_changed'); - const anotherDelivery = { ...delivery, agentId: 'different-delivery' }, - { id: _id, ...body } = anotherDelivery; - anotherDelivery.id = mathDigest(canonicalMathJson(body)); - await expect(integrateAgentTeamProofDelivery({ ...input, delivery: anotherDelivery })).rejects.toThrow( - 'source_changed', - ); - const source = fs.readFileSync(f.source(f.receipt.workspaceRoot), 'utf8'); - fs.appendFileSync(f.source(f.receipt.workspaceRoot), '-- dirty after FF\n'); - await expect(integrateAgentTeamProofDelivery(input)).rejects.toThrow('source_changed'); - fs.writeFileSync(f.source(f.receipt.workspaceRoot), source); - const directory = path.join(f.common.evidenceDirectory, 'adoption-intents'), - file = path.join(directory, fs.readdirSync(directory)[0]!); - const text = fs.readFileSync(file, 'utf8'), - intent = JSON.parse(text); - intent.runId = 'another-intent-run'; - fs.chmodSync(file, 0o600); - fs.writeFileSync(file, JSON.stringify(intent)); - await expect(integrateAgentTeamProofDelivery(input)).rejects.toThrow('adoption_intent_changed'); - fs.writeFileSync(file, text); - fs.chmodSync(file, 0o400); - // Identical owned bytes at a later, unrelated HEAD do not prove the recorded FF happened at this HEAD. - git(f.receipt.workspaceRoot, [ - '-c', - 'user.name=Fixture', - '-c', - 'user.email=fixture@localhost', - 'commit', - '--allow-empty', - '--no-gpg-sign', - '--quiet', - '-m', - 'Unrelated later commit', - ]); - expect(git(f.receipt.workspaceRoot, ['rev-parse', 'HEAD'])).not.toBe(adoption.commit); - await expect(integrateAgentTeamProofDelivery(input)).rejects.toThrow('source_changed'); - }, 90_000); -}); - -vi.mock('../src/math/nativeProcess', async importOriginal => { - const addon = process.env.THEOREMOS_TEST_PROCESS_ADDON; - if (!addon) return importOriginal(); - const handle = { exports: {} }; - process.dlopen(handle, addon); - return { nativeProcess: handle.exports }; -}); diff --git a/tests/agentTeamRouteSummary.test.ts b/tests/agentTeamRouteSummary.test.ts deleted file mode 100644 index 38d687e3..00000000 --- a/tests/agentTeamRouteSummary.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -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 } 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() { - 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: 'native-agent-control', - canonicalCommit: commit, - workers: [ - { - id: 'member', - role: 'researcher', - worktree: path.join(directory, 'member'), - phase: 'running', - turns: 1, - status: 'running', - seedCommit: commit, - tasks, - cursor: 0, - }, - ], - retiredRoutes: [ - { - routeId: 'dead', - source: 'lead', - reason: 'A boundary counterexample.\nSee probe.', - evidenceRefs: ['probe'], - retiredAt: 1, - }, - ], - 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('serves Lead and member', async () => { - const { team, save, call, commit, deliveryId } = fixture(); - const full = await call('lead'); - expect(await call('member')).toEqual(full); - expect(full).toMatchObject({ - ok: true, - canonicalCommit: commit, - 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(); - 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([ - ['lead', false, 7], - ['member', true, 6], - ['lead', true, 8], - ] as const)('preserves exact branches for %s with approval = %s', (actor, approval, count) => { - const schema = agentTeamToolDefinition(actor, approval).inputSchema as Record; - expect( - agentTeamRequestSchema.safeParse({ operation: 'route_summary', routeId: 'a', reason: 'stray' }).success, - ).toBe(false); - expect(schema.oneOf).toHaveLength(count); - expect(schema.oneOf.map((branch: Record) => branch.properties.operation.enum[0])).toEqual( - schema.properties.operation.enum, - ); - expect(schema.properties.operation.enum.includes('publish_plan')).toBe(actor === 'lead' && approval); - expect(schema.oneOf.at(-1)).toMatchObject({ - type: 'object', - required: ['operation'], - additionalProperties: false, - properties: { - operation: { enum: ['route_summary'] }, - includeRetired: { type: 'boolean' }, - routeId: { type: 'string' }, - }, - }); - }); -}); diff --git a/tests/agentTeamSolver.test.ts b/tests/agentTeamSolver.test.ts index 3f6c04e5..fbf6447d 100644 --- a/tests/agentTeamSolver.test.ts +++ b/tests/agentTeamSolver.test.ts @@ -4,6 +4,8 @@ import path from 'node:path'; import crypto from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { createServer } from 'node:http'; +import { spawnSync } from 'node:child_process'; +import { setTimeout as delay } from 'node:timers/promises'; import { buildSync } from 'esbuild'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { bootstrapLeanTask } from '../src/math/leanTask'; @@ -11,9 +13,12 @@ import { mathBuildFile, mathBuildSource, MATH_BUILD_INPUTS, MATH_RUNTIME_BUNDLES import { mathDigest, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; import { projectMathematicsRuntimeEnvironment } from '../src/math/mathRuntimeEnvironment'; import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; +import { directRuntimeModules } from '../src/solver/modules/runtime'; import { runSolver } from '../src/solver/run'; import { tacticBatteryCacheTestDefines } from './helpers/tacticBatteryCache'; +const stockCodex = process.env.THEOREMOS_TEST_STOCK_CODEX ?? 'codex'; + const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const task = 'Prove the frozen original target using independently checked team helpers.'; let directory: string | undefined; @@ -170,7 +175,7 @@ describe.skipIf(process.platform !== 'linux')('CLI native team startup and histo 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'); + expect(historical.agentTeam?.transport).toBe('codex-shared'); delete historical.agentTeam!.transport; writeSolverRunState(historicalFile, historical); const beforeResume = fs.readFileSync(historicalFile); @@ -180,4 +185,238 @@ describe.skipIf(process.platform !== 'linux')('CLI native team startup and histo expect(fs.readFileSync(historicalFile)).toEqual(beforeResume); expect(httpRequests).toEqual([{ method: 'HEAD', url: '/v1/models' }]); }, 150_000); + + it.skipIf(spawnSync(stockCodex, ['--version'], { timeout: 5000, stdio: 'ignore' }).status !== 0)( + 'uses native delegation to write in one checkout and shuts the team down before Lean accepts the proof', + async () => { + directory = fs.realpathSync( + fs.mkdtempSync(path.join(process.env.TMPDIR ?? '/data/lzh/default-storage/tmp', 'shared-team-cli-')), + ); + const root = path.join(directory, 'runtime'); + const buildFile = freezeRuntime(root); + const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { + task, + source: 'namespace Team\ntheorem original (n : Nat) : n + 0 = 0 + n := by sorry\nend Team\n', + }); + const output = path.join(directory, 'result.json'); + const taskFile = path.join(directory, 'task.md'); + fs.writeFileSync(taskFile, task); + const worktree = path.join(output + '.runtime', 'worktree'); + const proofFile = path.join( + worktree, + path.relative(receipt.workspaceRoot, receipt.projectRoot), + 'Submission.lean', + ); + const profile = path.join(directory, 'profile'); + const environmentFile = path.join(directory, 'math-environment.json'); + const elanHome = path.join(os.homedir(), '.elan'); + writeMathJsonDurable( + environmentFile, + projectMathematicsRuntimeEnvironment({ + PATH: path.join(elanHome, 'toolchains/leanprover--lean4---v4.33.0/bin') + ':' + process.env.PATH, + ELAN_HOME: elanHome, + LEAN_PATH: '', + LEAN_SYSROOT: '', + DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', + DEEPSCIENTIST_MATH_ENV_FILE: environmentFile, + NO_PROXY: '127.0.0.1,localhost', + }), + 0o400, + ); + vi.stubEnv('DEEPSCIENTIST_MATH_ENV_FILE', environmentFile); + vi.stubEnv('THEOREMOS_CODEX_BACKEND_EXECUTABLE', path.join(directory, 'missing-custom-codex')); + const assignment = 'FIXTURE_SHARED_MEMBER'; + const errors: unknown[] = []; + const events: Record[] = []; + let leadRequests = 0, + memberRequests = 0, + sequence = 0; + connectivityServer = createServer(async (request, response) => { + try { + expect(request.url).toBe('/v1/responses'); + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(Buffer.from(chunk)); + const body = JSON.parse(Buffer.concat(chunks).toString()); + const member = body.input.some( + (item: { type: string; content?: unknown }) => + item.type === 'agent_message' && JSON.stringify(item.content).includes(assignment), + ); + const id = ++sequence; + const modelMessage = (value: string) => ({ + id: 'msg_' + id, + type: 'message', + role: 'assistant', + status: 'completed', + content: [{ type: 'output_text', text: value, annotations: [] }], + }); + const call = (name: string, args: object) => { + const namespace = body.tools.find( + (tool: { type: string; tools?: { name: string }[] }) => + tool.type === 'namespace' && tool.tools?.some(definition => definition.name === name), + ); + expect( + namespace || body.tools.some((definition: { name?: string }) => definition.name === name), + name, + ).toBeTruthy(); + return { + type: 'function_call', + id: 'fc_' + id, + call_id: 'call_' + id, + name, + arguments: JSON.stringify(args), + status: 'completed', + ...(namespace && { namespace: namespace.name }), + }; + }; + let item; + if (member) { + item = + ++memberRequests === 1 + ? call('exec_command', { + cmd: "sed -i 's/by sorry/by simp/' " + JSON.stringify(path.relative(worktree, proofFile)), + login: false, + }) + : modelMessage('Member saved its proof.'); + } else if (++leadRequests === 1) { + item = call('spawn_agent', { task_name: 'fixture', fork_turns: 'none', message: assignment }); + } else { + for (let i = 0; i < 250 && memberRequests < 2; i++) await delay(20); + expect(memberRequests).toBe(2); + expect(fs.readFileSync(proofFile, 'utf8')).toContain('by simp'); + item = modelMessage('Team proof is ready.'); + } + const base = { id: 'resp_' + id, object: 'response', created_at: 1, model: body.model, output: [] }; + const emit = (value: { type: string; [key: string]: unknown }) => + response.write('event: ' + value.type + '\ndata: ' + JSON.stringify(value) + '\n\n'); + response.writeHead(200, { 'Content-Type': 'text/event-stream' }); + emit({ type: 'response.created', response: { ...base, status: 'in_progress' } }); + emit({ + type: 'response.output_item.added', + output_index: 0, + item: + item.type === 'function_call' + ? { ...item, status: 'in_progress', arguments: '' } + : { ...item, status: 'in_progress', content: [] }, + }); + if (item.type === 'function_call') { + emit({ + type: 'response.function_call_arguments.delta', + item_id: item.id, + output_index: 0, + delta: item.arguments, + }); + emit({ + type: 'response.function_call_arguments.done', + item_id: item.id, + output_index: 0, + arguments: item.arguments, + }); + } else { + emit({ + type: 'response.output_text.delta', + item_id: item.id, + output_index: 0, + content_index: 0, + delta: item.content![0].text, + }); + emit({ + type: 'response.output_text.done', + item_id: item.id, + output_index: 0, + content_index: 0, + text: item.content![0].text, + }); + } + emit({ type: 'response.output_item.done', output_index: 0, item }); + emit({ + type: 'response.completed', + response: { + ...base, + status: 'completed', + output: [item], + usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, + }, + }); + response.end(); + } catch (error) { + errors.push(error); + response.writeHead(400).end(); + } + }); + const server = connectivityServer; + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Missing local fixture endpoint'); + const fetchUpstream = globalThis.fetch.bind(globalThis); + vi.spyOn(globalThis, 'fetch').mockImplementation((request, init) => { + expect(request).toBe('https://fixture.invalid/v1/responses'); + return fetchUpstream('http://127.0.0.1:' + address.port + '/v1/responses', init); + }); + fs.mkdirSync(profile); + fs.writeFileSync( + path.join(profile, 'config.toml'), + 'model = "gpt-5.4"\nmodel_provider = "web_provider"\n' + + '[model_providers.web_provider]\nname = "Fixture"\nwire_api = "responses"\n' + + 'env_key = "THEOREMOS_PROVIDER_API_KEY"\nbase_url = "https://fixture.invalid/v1"\n' + + 'request_max_retries = 0\nstream_max_retries = 0\n', + ); + vi.spyOn(console, 'log').mockImplementation(line => events.push(JSON.parse(String(line)))); + const code = await runSolver( + [ + '--workspace', + receipt.workspaceRoot, + '--task-file', + taskFile, + '--output', + output, + '--build-manifest', + buildFile, + '--agent-team', + '2', + '--harness-profile', + profile, + '--codex', + stockCodex, + '--model', + 'gpt-5.4', + '--no-explanations', + '--max-run-seconds', + '90', + '--max-turns', + '1', + '--max-total-tokens', + '5000', + ], + root, + { + ...directRuntimeModules, + M1: { + ...directRuntimeModules.M1, + open: options => + directRuntimeModules.M1.open({ + ...options, + environment: { ...options.environment, THEOREMOS_PROVIDER_API_KEY: 'fixture-credential' }, + }), + }, + }, + undefined, + 'cli', + ); + expect(errors).toEqual([]); + expect(code, JSON.stringify(events)).toBe(0); + expect(memberRequests).toBe(2); + const state = readSolverRunState(path.join(output + '.runtime', 'state.json')); + expect(state.agentTeam).toMatchObject({ transport: 'codex-shared', workers: [], deliveries: [], adoptions: [] }); + expect(state.tokenBudget).toMatchObject({ reportedTotalTokens: sequence * 12, usageComplete: true }); + expect(state.writerProcess).toBeUndefined(); + expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ + status: 'evaluated_passed', + completion_signal_valid: true, + }); + }, + 120_000, + ); }); diff --git a/tests/agentTeamSourceRecovery.test.ts b/tests/agentTeamSourceRecovery.test.ts deleted file mode 100644 index fb441bad..00000000 --- a/tests/agentTeamSourceRecovery.test.ts +++ /dev/null @@ -1,1527 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('../src/math/nativeProcess', async importOriginal => { - const addon = process.env.THEOREMOS_TEST_PROCESS_ADDON; - if (!addon) return importOriginal(); - const handle = { exports: {} }; - process.dlopen(handle, addon); - return { nativeProcess: handle.exports }; -}); -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { LIBRARY_PACK_SCHEMA } from '../src/math/libraryPacks'; -import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; -import type { NativeAgentControlConnection } from '../src/runtime/nativeAgentControl'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { checkAgentTeamProofDelivery, readAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; -import { LEAN_MEMORY_LIMIT_ERROR } from '../src/math/verifier'; -import { DECLARATION_SUBMISSION_FILE, DeclarationArtifactCheckError } from '../src/solver/declarationArtifacts'; -import { directSolverModules } from '../src/solver/modules'; -import * as evidence from '../src/solver/modules/evidence'; -import { - agentLibrary, - LIBRARY_ACCESS_FILE, - LIBRARY_REQUEST_FILE, - type LibraryAccess, - writeLibraryAccess, -} from '../src/solver/libraryAccess'; -import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; -import { - commitSolverSources, - git, - pinSolverResearchSkill, - readSolverProblem, - withSolverWorktree, -} from '../src/solver/problem'; -import { RESEARCH_TOOL_HELP_FILE } from '../src/solver/researchToolHelp'; -import { runResearchLead } from '../src/solver/research'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { createSkillProofLifecycle } from '../src/solver/skillProofLifecycle'; -import type { SoftSliceSettings } from '../src/solver/softSlice'; -import { deferred } from './helpers/async'; -import { temporaryDirectory } from './helpers/files'; -import { solverState } from './helpers/solver'; - -vi.mock('../src/math/mathBuildManifest', async importOriginal => ({ - ...(await importOriginal()), - readMathBuildManifest: vi.fn(), -})); -// The sandbox memory cap cannot be reached cheaply; tests replace one host check with Lean's recorded outcome. -const proofChecks = vi.hoisted(() => ({ check: undefined as unknown, integrate: undefined as unknown })); -vi.mock('../src/solver/agentTeamProof', async importOriginal => { - const actual = await importOriginal(); - return { - ...actual, - checkAgentTeamProofDelivery: async (input: Parameters[0]) => { - if (proofChecks.check) throw (proofChecks.check as (value: typeof input) => Error)(input); - return actual.checkAgentTeamProofDelivery(input); - }, - integrateAgentTeamProofDelivery: async (input: Parameters[0]) => { - if (proofChecks.integrate) throw (proofChecks.integrate as (value: typeof input) => Error)(input); - return actual.integrateAgentTeamProofDelivery(input); - }, - }; -}); -function memoryLimit(declaration: (typeof declarations)[number], commit: string) { - return new DeclarationArtifactCheckError(declaration, { - schema: 'deepscientist.mathematics.verification-batch/v1', - status: 'failed', - targetCommit: commit, - sessionId: 'memory-limit-verifier', - events: [], - startedAt: 1, - checkedAt: 2, - durationMs: 1, - results: [ - { - status: 'failed', - targetCommit: commit, - proofPath: declaration.file, - theoremName: declaration.name, - receiptId: 'memory-limit', - error: LEAN_MEMORY_LIMIT_ERROR, - stdoutPreview: 'INTERNAL PANIC: out of memory', - }, - ], - }); -} - -const original = 'namespace Recovery\ntheorem goal : True := by sorry\nend Recovery\n'; -const helper = 'theorem helper : True := by trivial\n'; -const declarations = [{ file: 'Submission.lean', name: 'Recovery.helper', type: 'True' }]; -const shadowFile = 'Submission/Library/Shadow.lean'; -const shadowPack = { - schema: LIBRARY_PACK_SCHEMA, - modules: [ - { - file: shadowFile, - source: 'namespace Shadow\ntheorem helper : True := by trivial\nend Shadow\n', - origin: { - kind: 'upstream' as const, - repository: 'offline-native-fixture', - commit: 'a'.repeat(40), - file: shadowFile, - }, - }, - ], -}; -const fixtures: ReturnType[] = []; -const rootThreadId = '00000000-0000-4000-8000-000000000001'; - -function nativeConnection( - threadId: string, - agentPath: string, - cwd: string, - notices: string[] = [], -): NativeAgentControlConnection { - return { - info: { - sessionId: rootThreadId, - agent: { threadId, metadata: { agentPath, agentId: threadId }, status: 'running' }, - configSnapshot: { cwd }, - }, - request: vi.fn(async () => ({})), - input: vi.fn(async () => ({ accepted: true, threadId, submissionId: crypto.randomUUID() })), - update: vi.fn(async value => { - notices.push( - ...((value as { mailbox?: { message?: { text?: string } }[] }).mailbox ?? []).flatMap( - item => item.message?.text ?? [], - ), - ); - return { acceptedSequence: value.sequence }; - }), - }; -} - -function fixture({ - maxAgents = 2, - softSlice, - stallInterrupt = false, - librarySource, - maxTotalTokens = 0, - problemSource = original, - libraryPack, -}: { - maxAgents?: number; - softSlice?: SoftSliceSettings; - stallInterrupt?: boolean; - librarySource?: string; - maxTotalTokens?: number; - problemSource?: string; - libraryPack?: Parameters[1]['libraryPack']; -} = {}) { - const directory = temporaryDirectory('agent-team-source-recovery-'); - const receipt = bootstrapLeanTask(path.join(directory, 'primary'), { - source: problemSource, - task: 'Prove True.', - libraryPack, - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath), - root = path.resolve('.'); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, receipt.workspaceRoot, { - runId: 'agent-team-source-recovery', - phase: 'running', - environmentDigest: mathDigest('real Lean True recovery fixture'), - researchMode: 'skill', - researchSkillWorkflow: 'full', - researchSkill: identity, - researchDelegation: { mode: 'team', maxAgents }, - workerCount: 1, - coordination: 'independent', - requestUsageAccounting: { startedRequests: 0, reportedRequests: 0, pendingRequests: 0, incomplete: false }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }); - const skill = prepareResearchSkill(root, state.worktree, identity, problem); - let libraryCatalog: LibraryAccess | undefined; - if (librarySource) { - const file = 'Submission/Library/TeamFixture.lean'; - const release = writeLibraryCatalog(path.join(directory, 'release'), { - id: 'fixture/native-team-library', - revision: 'v1', - environment: 'standard', - packs: [ - { - schema: LIBRARY_PACK_SCHEMA, - modules: [ - { - file, - source: librarySource, - origin: { kind: 'upstream', repository: 'offline-native-fixture', commit: 'a'.repeat(40), file }, - }, - ], - }, - ], - }); - libraryCatalog = { file: release.file, digest: release.digest }; - writeLibraryAccess(problem, state.worktree, libraryCatalog); - } - const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); - if (!fs.existsSync(path.join(toolchain, 'bin/lean'))) throw new Error('Real Lean 4.33.0 is required.'); - const environment = { - PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, - 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; notices: string[]; complete: () => void }[] = []; - const events: { event: string; details?: Record }[] = []; - const stateFile = path.join(directory, 'run-state.json'); - const makeTeam = (current: SolverRunState, afterSave?: (state: SolverRunState) => void) => { - const team = new AgentResearchTeam({ - state: current, - root, - taskText: 'Prove True.', - leadAccess: { - environment, - retrievalRoot: path.join(current.worktree, problem.projectRelative), - researchSkill: skill, - libraryCatalog, - }, - modules: { - ...directSolverModules, - M1: { - ...directSolverModules.M1, - open: async options => { - const outcome = deferred(), - record = { options, message: '', notices: [] as string[], complete: () => outcome.resolve('completed') }; - sessions.push(record); - const config = options.nativeAgentControl!; - const threadId = options.threadId ?? String(config.bootstrap!.threadId); - const connection = nativeConnection( - threadId, - '/root/' + options.environment!.DEEPSCIENTIST_MATH_WORKER_ID, - options.workspace, - record.notices, - ); - await config.request( - { - version: 1, - sessionId: rootThreadId, - threadId, - operation: 'attach', - operationId: crypto.randomUUID(), - payload: { threadId, sessionId: rootThreadId }, - }, - connection, - { signal: controller.signal }, - ); - await config.bound?.(connection); - const session: MathAgentSession = { - threadId, - nativeAgentControl: connection, - usageSource: 'upstream-requests', - run: async (message, _id, _workspace, started) => { - record.message = message; - started('source-recovery-turn-' + sessions.length); - return outcome.promise; - }, - 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'); - await config.disconnected?.(connection); - }, - }; - return session; - }, - }, - }, - executable: 'offline-no-model', - profile: 'offline-no-credentials', - signal: controller.signal, - maxAgents, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens, - remainingMs: () => Infinity, - softSlice, - save: () => { - writeSolverRunState(stateFile, current); - afterSave?.(current); - }, - emit: (event, details) => { - events.push({ event, details }); - }, - exclusiveCheck: operation => operation(), - }); - teams.push(team); - return team; - }; - const team = makeTeam(state); - let calls = 0; - const call = (operation: Record, actor = 'lead', target = team) => - target.tools(actor).call('theoremos_team', operation, { - callId: 'source-recovery-call-' + ++calls, - turnId: 'source-recovery-turn', - threadId: 'source-recovery-thread', - signal: controller.signal, - }) as Promise; - const native = async (operation: string, payload: Record, target = team) => { - const options = target.nativeAgentControlOptions(); - const connection = nativeConnection(rootThreadId, '/root', state.worktree); - const request = (method: string, args: Record) => - options.request( - { - version: 1, - threadId: rootThreadId, - sessionId: rootThreadId, - operation: method, - operationId: crypto.randomUUID(), - payload: args, - }, - connection, - { signal: controller.signal }, - ); - await request('attach', { threadId: rootThreadId, sessionId: rootThreadId }); - await options.bound?.(connection); - return request(operation, { caller: rootThreadId, ...payload }); - }; - const input = (text: string) => ({ kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } }); - const spawn = (name: string, message: string) => { - const source = { - subagent: { thread_spawn: { parent_thread_id: rootThreadId, agent_path: '/root/' + name, depth: 1 } }, - }; - return native('spawn', { - source, - bootstrap: { source, config: { cwd: state.worktree, model: state.model, reasoningEffort: state.effort } }, - input: input(message), - startOptions: { parentTurnId: 'root-turn' }, - }); - }; - const followup = (agentId: string, message: string, target = team) => - native( - 'send', - { - target: { kind: 'path', reference: '/root/' + agentId }, - input: input(message), - }, - target, - ); - const current = { - directory, - state, - stateFile, - controller, - sessions, - teams, - team, - makeTeam, - call, - spawn, - followup, - events, - problem, - environment, - skill, - source: (worktree: string) => path.join(worktree, problem.projectRelative, 'Submission.lean'), - session: async (index: number) => { - await expect.poll(() => sessions[index]?.message, { timeout: 10_000 }).toBeTruthy(); - return sessions[index]!; - }, - }; - fixtures.push(current); - return current; -} - -afterEach(async () => { - vi.restoreAllMocks(); - proofChecks.check = proofChecks.integrate = undefined; - for (const f of fixtures.splice(0)) { - f.controller.abort(); - for (const session of f.sessions) session.complete(); - await Promise.allSettled(f.teams.map(team => team.close())); - fs.rmSync(f.directory, { recursive: true, force: true }); - } -}); -async function idle(team: AgentResearchTeam) { - await expect.poll(() => team.hasActiveWorkers, { timeout: 30_000 }).toBe(false); -} - -const downstream = 'theorem downstream : True := by exact helper\n'; - -async function registerDependentHelper(f: ReturnType) { - const { worktree } = f.state; - const evidenceDirectory = path.join(f.team.directory, 'proofs'); - const delivery = await withSolverWorktree(worktree, f.problem.baseCommit, async producer => { - const file = f.source(producer); - fs.writeFileSync(file, original.replace('theorem goal', helper + 'theorem goal')); - const seedCommit = commitSolverSources(f.problem, producer); - fs.writeFileSync(file, original.replace('theorem goal', helper + downstream + 'theorem goal')); - return checkAgentTeamProofDelivery({ - state: f.state, - worktree: producer, - agentId: 'producer', - seedCommit, - declarations: [{ file: 'Submission.lean', name: 'Recovery.downstream', type: 'True' }], - env: f.environment, - signal: f.controller.signal, - evidenceDirectory, - assertWriterStopped: () => {}, - }); - }); - f.team.archive.deliveries.push({ - id: delivery.id, - agentId: 'producer', - taskId: 'fixture', - kind: 'helpers', - path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json'), - }); - return delivery.id; -} - -describe('native team source handling', () => { - it('exposes the pinned math library to a member and reserves installation requests for Lead', async () => { - const source = 'namespace TeamFixture\ntheorem library_helper : True := by trivial\nend TeamFixture\n'; - const f = fixture({ librarySource: source }); - await f.spawn('member', 'Find the exact declaration in the published library.'); - const child = await f.session(0), - worktree = child.options.workspace; - const name = 'TeamFixture.library_helper', - library = agentLibrary(worktree); - expect(library.search(name).hits[0]).toMatchObject({ name, installation: 'not-installed' }); - expect(library.get(name).source).toMatchObject({ complete: true, text: source }); - expect(fs.readFileSync(path.join(worktree, RESEARCH_TOOL_HELP_FILE), 'utf8')).toContain( - 'Lead requests installation for the team', - ); - expect(() => library.request([name], 'Apply the checked helper.')).toThrow('math_library_request_lead_required'); - expect(fs.existsSync(path.join(worktree, LIBRARY_REQUEST_FILE))).toBe(false); - expect(agentLibrary(f.state.worktree).request([name], 'Apply the checked helper.')).toMatchObject({ - status: 'queued', - }); - expect(fs.existsSync(path.join(f.state.worktree, LIBRARY_REQUEST_FILE))).toBe(true); - }); - - it('prepares the math library on demand when an idle member resumes its saved thread', async () => { - const name = 'TeamFixture.library_helper'; - const f = fixture({ librarySource: `theorem ${name} : True := by trivial\n` }); - await f.spawn('member', 'Check the local identity.'); - const first = await f.session(0), - worktree = first.options.workspace; - const threadId = f.team.archive.workers[0]!.native!.threadId; - first.complete(); - await idle(f.team); - await f.team.close(); - const catalog = path.join(worktree, LIBRARY_ACCESS_FILE); - fs.unlinkSync(catalog); - - const restored = f.makeTeam(readSolverRunState(f.stateFile)); - await restored.restore(); - expect(fs.existsSync(catalog)).toBe(false); - expect(f.sessions).toHaveLength(1); - - await f.followup('member', 'Look up the exact lemma for the next step.', restored); - const next = await f.session(1); - expect(next.options.threadId).toBe(threadId); - expect(next.options.workspace).toBe(worktree); - expect(agentLibrary(worktree).get(name).source.complete).toBe(true); - next.complete(); - await idle(restored); - }); - - it('charges member receipts to the same run budget and blocks a subsequent request when exhausted', async () => { - const f = fixture({ maxAgents: 3, maxTotalTokens: 50 }); - await f.spawn('first', 'Check the local identity.'); - await f.spawn('second', 'Read the hypotheses.'); - const first = await f.session(0), - second = await f.session(1); - for (const [index, session] of [first, second].entries()) { - const admission = session.options.requestGate!({ requestId: 'budget-' + index }); - if (admission.allowed === false) throw new Error(admission.reason); - const totalTokens = index === 0 ? 20 : 30; - const receipt = { - usage: { inputTokens: totalTokens - 2, outputTokens: 2, totalTokens }, - complete: true, - outcome: 'completed' as const, - }; - admission.settle(receipt); - admission.settle(receipt); - } - expect(f.state.teamUsage).toMatchObject({ totalTokens: 50, inputTokens: 46, outputTokens: 4 }); - expect(f.state.tokenBudget).toMatchObject({ status: 'exhausted', usageComplete: true }); - expect(first.options.requestGate!({ requestId: 'blocked' })).toEqual({ - allowed: false, - reason: 'math_total_token_limit', - }); - first.complete(); - second.complete(); - await idle(f.team); - expect(f.team.archive.workers.map(worker => worker.requestUsageAccounting!.reportedRequests)).toEqual([1, 1]); - }); - - it('restores lost member receipts before admitting more work under a finite shared budget', async () => { - const f = fixture({ maxTotalTokens: 50 }); - await f.spawn('member', 'Check the local identity.'); - const child = await f.session(0); - const reported = child.options.requestGate!({ requestId: 'reported' }); - if (!reported.allowed) throw new Error(reported.reason); - reported.settle({ complete: true, usage: { inputTokens: 18, outputTokens: 2, totalTokens: 20 } }); - expect(child.options.requestGate!({ requestId: 'lost' }).allowed).toBe(true); - const saved = readSolverRunState(f.stateFile); - expect(saved.tokenBudget).toMatchObject({ status: 'available', reportedTotalTokens: 20, usageComplete: false }); - child.complete(); - await idle(f.team); - await f.team.close(); - - const restored = f.makeTeam(saved); - await restored.restore(); - const recovered = readSolverRunState(f.stateFile); - expect(recovered.tokenBudget).toMatchObject({ - status: 'usage-unavailable', - reportedTotalTokens: 20, - usageComplete: false, - }); - expect(recovered.teamUsage).toMatchObject({ totalTokens: 20 }); - expect(recovered.agentTeam!.workers[0]!.requestUsageAccounting).toMatchObject({ - pendingRequests: 0, - incomplete: true, - receipts: [ - expect.objectContaining({ status: 'reported' }), - expect.objectContaining({ requestId: 'lost', status: 'missing', missingReason: 'resumed-without-receipt' }), - ], - }); - await expect(f.followup('member', 'Continue the investigation.', restored)).rejects.toThrow(); - expect(f.sessions).toHaveLength(1); - }); - - it('preserves an unfinished child assignment that returns after a two-compaction milestone notice', async () => { - const f = fixture({ softSlice: { softSliceMs: 0, maxCompactionsPerSlice: 2 } }); - await f.spawn('member', 'Investigate a partial proof.'); - const session = await f.session(0), - worker = f.team.archive.workers[0]!; - const activity = session.options.onActivity!; - activity({ event: 'item_started', itemType: 'contextCompaction' }); - activity({ event: 'item_completed', itemType: 'contextCompaction' }); - expect(session.notices).toEqual([]); - activity({ event: 'item_completed', itemType: 'contextCompaction' }); - expect(session.notices).toEqual([expect.stringContaining('submit with helpersOnly:true')]); - 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({ - softSlice: { softSliceMs: 0, maxCompactionsPerSlice: 1, softSliceGraceMs: 1 }, - stallInterrupt: true, - }); - await f.spawn('member', 'Investigate a partial proof.'); - const session = await f.session(0), - worker = f.team.archive.workers[0]!; - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'This draft belongs to the same task.\n'); - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); - 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({ maxAgents: 3, libraryPack: shadowPack }); - await f.spawn('retired', 'Route: discarded\nExplore this route.'); - const retired = f.team.archive.workers[0]!; - expect( - await f.call({ - operation: 'retire_route', - routeId: 'discarded', - reason: 'Close this independent route.', - evidenceRefs: ['RESEARCH.md'], - }), - ).toMatchObject({ releasedAgentIds: ['retired'] }); - await idle(f.team); - const retiredHead = git(retired.worktree, ['rev-parse', 'HEAD']); - await f.spawn('member', 'Prove the goal and its helper lemmas.'); - const a = await f.session(1), - producer = f.team.archive.workers[1]!; - await f.spawn('peer', 'Draft another proof step.'); - const b = await f.session(2), - consumer = f.team.archive.workers[2]!; - 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', helpersOnly: true, 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); - expect(f.team.archive.adoptions.some(item => item.targetId === consumer.id)).toBe(false); - - await f.team.close(); - const saved = readSolverRunState(f.stateFile), - restored = f.makeTeam(saved); - await restored.restore(); - expect(restored.archive.adoptions.some(item => item.targetId === retired.id)).toBe(false); - expect(restored.archive.adoptions.filter(item => item.targetId === consumer.id)).toEqual([ - expect.objectContaining({ status: 'completed', receiptId: expect.any(String) }), - ]); - expect(git(retired.worktree, ['rev-parse', 'HEAD'])).toBe(retiredHead); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain('theorem goal : True := by sorry'); - const seeded = fs.readFileSync(f.source(consumer.worktree), 'utf8'); - expect(seeded).toContain(helperProofs); - expect(seeded).toContain(draft); - await f.followup('peer', 'Use the landed helpers to finish both proofs.', restored); - const next = await f.session(3); - expect(next.message).toContain('landedHelpers'); - expect(next.message).toContain('Recovery.second'); - fs.writeFileSync(f.source(consumer.worktree), seeded.replaceAll('by sorry', 'by exact second')); - expect( - await f.call( - { - operation: 'submit', - summary: 'Reused the verified helpers.', - declarations: [ - { ...declarations[0]!, name: 'Recovery.goal' }, - { ...declarations[0]!, name: 'Recovery.draft' }, - { ...declarations[0]!, name: '_root_.Recovery.helper' }, - ], - }, - 'peer', - restored, - ), - ).toMatchObject({ ok: true }); - next.complete(); - await idle(restored); - const peer = restored.archive.workers.find(item => item.id === 'peer')!; - expect(peer.error).toBeUndefined(); - const delivery = restored.archive.deliveries.find(item => item.agentId === 'peer'); - expect(delivery, peer.tasks.at(-1)?.error).toBeDefined(); - const checked = readAgentTeamProofDelivery(delivery!.path, saved); - expect(checked.artifacts.map(item => item.declaration.name)).toEqual([ - '_root_.Recovery.helper', - 'Recovery.second', - 'Recovery.goal', - 'Recovery.draft', - ]); - expect(checked.inferredHelperTypes).toEqual(['Submission.lean\0Recovery.second']); - expect(saved.check).toBeUndefined(); - }, 60_000); - - it.each([ - { - reason: 'unqualified name', - prerequisiteName: 'helper', - problemSource: original, - insertion: 'theorem goal', - diagnostic: 'Unknown identifier `helper`', - }, - { - reason: 'a tactic argument absent from the elaborated proof', - prerequisiteName: 'helper', - problemSource: 'import Submission.Library.Shadow\n' + original, - insertion: 'theorem goal', - diagnostic: 'Unknown identifier `helper`', - tacticOnly: true, - }, - { - reason: 'partially qualified name', - prerequisiteName: 'Nested.helper', - problemSource: original, - insertion: 'theorem goal', - diagnostic: 'Unknown identifier `Nested.helper`', - }, - { - reason: 'missing patch anchor', - prerequisiteName: 'helper', - insertion: 'end Recovery', - problemSource: original + 'namespace Neighbor\ntheorem other : True := by sorry\nend Neighbor\n', - diagnostic: 'math_task_integration_missing_context', - }, - ])( - 'retries a blocked helper with $reason after its delayed prerequisite is adopted across a restored checkpoint', - async ({ prerequisiteName, problemSource, insertion, diagnostic, tacticOnly = false }) => { - const f = fixture({ maxAgents: 3, problemSource, libraryPack: tacticOnly ? shadowPack : undefined }); - await f.spawn('consumer', 'Keep this earlier workspace for later use.'); - const consumer = await f.session(0); - consumer.complete(); - await idle(f.team); - const consumerFile = f.source(consumer.options.workspace); - - await f.spawn('producer', 'Prove the prerequisite.'); - const first = await f.session(1), - producerFile = f.source(first.options.workspace); - const prerequisiteSource = `theorem ${prerequisiteName} : True := by trivial\n`; - const unrelated = 'theorem unrelated : True := by trivial\n'; - const proof = tacticOnly - ? `\n have h : True := by simp [${prerequisiteName}]\n exact Shadow.helper` - : 'exact ' + prerequisiteName; - const downstream = `theorem downstream : True := by ${proof}\n`; - const submit = async (session: typeof first, name: string, source: string, helpersOnly = false) => { - const anchor = name === 'unrelated' ? 'theorem goal' : insertion; - fs.writeFileSync(producerFile, fs.readFileSync(producerFile, 'utf8').replace(anchor, source + anchor)); - expect( - await f.call( - { - operation: 'submit', - helpersOnly, - summary: 'Share ' + name, - declarations: [{ file: 'Submission.lean', name: 'Recovery.' + name, type: 'True' }], - }, - 'producer', - ), - ).toMatchObject({ ok: true }); - session.complete(); - await idle(f.team); - return f.team.archive.deliveries.at(-1)!; - }; - const prerequisite = await submit(first, prerequisiteName, prerequisiteSource); - await f.call({ operation: 'adopt', deliveryId: prerequisite.id }); - await f.team.flushAdoptions(); - expect(fs.readFileSync(f.source(f.state.worktree), 'utf8')).toContain(prerequisiteSource); - await f.followup('producer', 'Prove an independent fact.'); - const irrelevant = await submit(await f.session(2), 'unrelated', unrelated); - await f.followup('producer', 'Share the consequence of the prerequisite.'); - const dependent = await submit(await f.session(3), 'downstream', downstream, true); - expect(dependent.kind).toBe('helpers'); - if (tacticOnly) { - const references = readAgentTeamProofDelivery(dependent.path, f.state).artifacts[0]!.references!; - expect( - [...references.statement, ...references.proof].some(({ name }) => name === 'Recovery.' + prerequisiteName), - ).toBe(false); - expect(references.proof).toContainEqual({ file: shadowFile, name: 'Shadow.helper' }); - } - - const attempts = (team: AgentResearchTeam) => - team.archive.adoptions.filter(item => item.targetId === 'consumer' && item.deliveryId === dependent.id); - await f.team.flushAdoptions('consumer'); - const [failed] = attempts(f.team); - expect(failed).toMatchObject({ - status: 'failed', - expectedCommit: f.problem.baseCommit, - error: expect.stringContaining(diagnostic), - missingDependencies: [{ file: 'Submission.lean', name: 'Recovery.' + prerequisiteName }], - }); - expect(fs.readFileSync(consumerFile, 'utf8')).toBe(problemSource); - - await f.team.close(); - const saved = readSolverRunState(f.stateFile); - pinSolverResearchSkill(saved.problem, saved.worktree, f.skill); - let prerequisiteCheckpoint: SolverRunState | undefined; - const restored = f.makeTeam(saved, current => { - if ( - prerequisiteCheckpoint || - !current.agentTeam!.adoptions.some( - item => item.targetId === 'consumer' && item.deliveryId === prerequisite.id && item.status === 'completed', - ) - ) - return; - prerequisiteCheckpoint = readSolverRunState(f.stateFile); - throw new Error('fixture interruption after the prerequisite was saved'); - }); - await restored.restore(); - expect(attempts(restored)).toEqual([failed]); - - const adopt = async (deliveryId: string) => { - expect(await f.call({ operation: 'adopt', deliveryId, targetId: 'consumer' }, 'lead', restored)).toMatchObject({ - ok: true, - }); - await idle(restored); - }; - await adopt(irrelevant.id); - expect(fs.readFileSync(consumerFile, 'utf8')).toContain(unrelated); - expect(attempts(restored)).toEqual([failed]); - const priorEvents = restored.archive.events.length; - await adopt(prerequisite.id); - expect(fs.readFileSync(consumerFile, 'utf8')).not.toContain(downstream); - expect(prerequisiteCheckpoint).toBeDefined(); - const interrupted = prerequisiteCheckpoint!; - expect( - interrupted.agentTeam!.adoptions.filter( - item => item.targetId === 'consumer' && item.deliveryId === dependent.id, - ), - ).toEqual([failed, expect.objectContaining({ status: 'queued' })]); - await restored.close(); - pinSolverResearchSkill(interrupted.problem, interrupted.worktree, f.skill); - const resumed = f.makeTeam(interrupted); - await resumed.restore(); - expect(attempts(resumed)).toEqual([failed, expect.objectContaining({ status: 'completed' })]); - expect( - resumed.archive.events - .slice(priorEvents) - .filter(event => event.to === 'consumer' && event.kind === 'adopted') - .map(event => event.deliveryId), - ).toEqual([prerequisite.id, dependent.id]); - const source = fs.readFileSync(consumerFile, 'utf8'); - expect(source).toContain(unrelated); - expect(source).toContain(prerequisiteSource); - expect(source).toContain(downstream); - expect(source).toContain('theorem goal : True := by sorry'); - }, - 60_000, - ); - - it.each(['committed', 'saved draft'] as const)( - 'retries a blocked helper when Lead supplies its prerequisite in a %s', - async sourceState => { - const f = fixture(), - { worktree } = f.state, - { baseCommit } = f.problem; - const leadFile = f.source(worktree); - const deliveryId = await registerDependentHelper(f); - await f.team.flushAdoptions(); - const [failed] = f.team.archive.adoptions; - expect(failed).toMatchObject({ - status: 'failed', - expectedCommit: baseCommit, - missingDependencies: [{ file: 'Submission.lean', name: 'Recovery.helper' }], - }); - await f.team.close(); - - const saved = readSolverRunState(f.stateFile); - pinSolverResearchSkill(saved.problem, saved.worktree, f.skill); - const restored = f.makeTeam(saved); - const unrelated = original.replace('theorem goal', 'theorem unrelated : True := by trivial\ntheorem goal'); - fs.writeFileSync(leadFile, unrelated); - commitSolverSources(saved.problem, worktree); - await restored.restore(); - expect(restored.archive.adoptions).toEqual([failed]); - - fs.writeFileSync(leadFile, unrelated.replace('theorem goal', helper + 'theorem goal')); - if (sourceState === 'committed') commitSolverSources(saved.problem, worktree); - await restored.flushAdoptions(); - expect(readSolverRunState(f.stateFile).agentTeam!.adoptions).toEqual([ - failed, - expect.objectContaining({ - deliveryId, - targetId: 'lead', - status: 'completed', - receiptId: expect.any(String), - }), - ]); - expect(fs.readFileSync(leadFile, 'utf8')).toBe( - unrelated.replace('theorem goal', helper + downstream + 'theorem goal'), - ); - }, - 60_000, - ); - - it.each(['followup', 'restore'] as const)( - 'retries a blocked helper after the member supplies its prerequisite and yields, via %s', - async entry => { - const f = fixture(); - await f.spawn('consumer', 'Work in the original workspace.'); - const first = await f.session(0), - file = f.source(first.options.workspace); - const deliveryId = await registerDependentHelper(f); - first.complete(); - await idle(f.team); - const repair = 'Supply the prerequisite in your own draft.'; - await expect(f.followup('consumer', repair)).rejects.toThrow('math_team_native_member_busy'); - await idle(f.team); - const attempts = (team: AgentResearchTeam) => - team.archive.adoptions.filter(item => item.targetId === 'consumer' && item.deliveryId === deliveryId); - const [failed] = attempts(f.team); - expect(failed).toMatchObject({ - status: 'failed', - expectedCommit: f.problem.baseCommit, - missingDependencies: [{ file: 'Submission.lean', name: 'Recovery.helper' }], - }); - - await f.followup('consumer', repair); - const second = await f.session(1); - const localDraft = 'theorem localDraft : True := by exact helper\n'; - const draft = original.replace('theorem goal', helper + localDraft + 'theorem goal'); - fs.writeFileSync(file, draft); - expect(await f.call({ operation: 'yield', reason: 'The prerequisite is available.' }, 'consumer')).toMatchObject({ - status: 'pending-writer-stop', - }); - second.complete(); - await idle(f.team); - const draftCommit = git(second.options.workspace, ['rev-parse', 'HEAD']); - expect(f.team.archive.workers[0]!.tasks.at(-1)).toMatchObject({ status: 'paused', sourceCommit: draftCommit }); - expect(draftCommit).not.toBe(f.problem.baseCommit); - expect(attempts(f.team)).toEqual([failed]); - - const continueProof = 'Use the adopted downstream fact.'; - let team = f.team; - if (entry === 'restore') { - await team.close(); - const saved = readSolverRunState(f.stateFile); - pinSolverResearchSkill(saved.problem, saved.worktree, f.skill); - team = f.makeTeam(saved); - await team.restore(); - } else { - await expect(f.followup('consumer', continueProof)).rejects.toThrow('math_team_native_member_busy'); - await idle(team); - } - expect(f.sessions).toHaveLength(2); - expect(attempts(team)).toEqual([ - failed, - expect.objectContaining({ - status: 'completed', - expectedCommit: draftCommit, - receiptId: expect.any(String), - }), - ]); - expect(fs.readFileSync(file, 'utf8')).toContain(localDraft); - expect(fs.readFileSync(file, 'utf8')).toContain(downstream); - - await f.followup('consumer', continueProof, team); - await f.session(2); - expect(fs.readFileSync(file, 'utf8')).toContain('theorem goal : True := by sorry'); - }, - 60_000, - ); - - it.each(['proof', 'declaration'] as const)( - 'recovers the frozen Lead %s check before installing a later child helper', - async pending => { - const f = fixture(), - { state, environment, skill } = f; - await f.spawn('member', 'Prove the standalone helper.'); - const child = await f.session(0), - worker = f.team.archive.workers[0]!; - const leadSource = f.source(state.worktree); - const leadFact = 'theorem leadFact : True := by trivial\n'; - const requestFile = path.join(state.worktree, '.scratch', DECLARATION_SUBMISSION_FILE); - const save = () => writeSolverRunState(f.stateFile, state); - const stopBeforeCheck = new Error('fixture interruption before declaration checking'); - const lifecycle = createSkillProofLifecycle({ - state, - worktree: state.worktree, - environment, - skill, - signal: f.controller.signal, - writerStopped: () => true, - sourceFeedback: () => undefined, - exclusiveCheck: async () => { - throw stopBeforeCheck; - }, - checkWhole: async () => { - throw new Error('Whole-proof check belongs to the recovery.'); - }, - save, - emit: () => {}, - }); - if (pending === 'proof') { - fs.writeFileSync(leadSource, original.replace('by sorry', 'by trivial')); - expect((await lifecycle.freezeSources()).wholeProofReady).toBe(true); - } else { - fs.writeFileSync(leadSource, original.replace('theorem goal', leadFact + 'theorem goal')); - fs.mkdirSync(path.dirname(requestFile), { recursive: true }); - fs.writeFileSync( - requestFile, - JSON.stringify({ - declarations: [{ file: 'Submission.lean', name: 'Recovery.leadFact', type: 'True' }], - }), - ); - await expect(lifecycle.freezeSources()).rejects.toBe(stopBeforeCheck); - } - const frozenCommit = git(state.worktree, ['rev-parse', 'HEAD']); - expect(state.pendingProofCheck?.commit ?? state.pendingDeclarationCheck?.commit).toBe(frozenCommit); - - fs.writeFileSync(f.source(worker.worktree), original.replace('theorem goal', helper + 'theorem goal')); - expect( - await f.call({ operation: 'submit', helpersOnly: true, declarations, summary: 'Reusable fact.' }, worker.id), - ).toMatchObject({ ok: true }); - child.complete(); - await idle(f.team); - await f.team.close(); - const restored = readSolverRunState(f.stateFile), - delivery = restored.agentTeam!.deliveries[0]!; - expect(delivery.kind).toBe('helpers'); - expect(restored.agentTeam!.adoptions.some(item => item.targetId === 'lead')).toBe(false); - - const open = vi.fn(async () => { - throw new Error('Recovery must not use a model.'); - }); - const winner = await runResearchLead({ - state: restored, - access: { environment, retrievalRoot: state.worktree, researchSkill: skill }, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, - root: process.cwd(), - buildFile: path.join(f.directory, 'unused-build.json'), - taskText: 'Prove True.', - executable: 'unused', - profile: 'unused', - signal: f.controller.signal, - deadline: Infinity, - maxTurns: 0, - maxTurnMs: Infinity, - maxTotalTokens: 0, - proofTimeoutMs: 30_000, - save: () => writeSolverRunState(f.stateFile, restored), - emit: (event, details) => { - f.events.push({ event, details }); - }, - }); - expect(open).not.toHaveBeenCalled(); - expect(restored.pendingProofCheck).toBeUndefined(); - expect(restored.pendingDeclarationCheck).toBeUndefined(); - if (pending === 'proof') { - expect(winner?.check).toMatchObject({ passed: true, commit: frozenCommit }); - expect(git(restored.worktree, ['rev-parse', 'HEAD'])).toBe(frozenCommit); - expect(fs.readFileSync(leadSource, 'utf8')).not.toContain(helper); - } else { - expect(winner).toBeUndefined(); - const checked = f.events.findIndex( - event => - event.event === 'declarations_checked' && - event.details?.passed === true && - event.details.commit === frozenCommit, - ); - const adopted = f.events.findIndex( - event => - event.event === 'team_event' && - event.details?.kind === 'adopted' && - event.details.to === 'lead' && - event.details.deliveryId === delivery.id, - ); - expect(checked).toBeGreaterThanOrEqual(0); - expect(adopted).toBeGreaterThan(checked); - expect(fs.readFileSync(leadSource, 'utf8')).toContain(helper); - expect(fs.readFileSync(leadSource, 'utf8')).toContain(leadFact); - } - }, - 60_000, - ); - - it('rechecks the frozen standalone helper on restore after the verifier was unavailable', async () => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('theorem goal', helper + 'theorem goal')); - const check = evidence.checkProjectedDeclarations; - vi.spyOn(evidence, 'checkProjectedDeclarations').mockImplementationOnce( - (problem, checkout, worktree, commit, targets, options) => - check(problem, checkout, worktree, commit, targets, { - ...options, - verifierCommandPath: path.join(f.directory, 'missing-lean'), - }), - ); - expect( - await f.call({ operation: 'submit', helpersOnly: true, declarations, summary: 'Reusable fact.' }, worker.id), - ).toMatchObject({ ok: true }); - first.complete(); - await idle(f.team); - await f.team.close(); - - const saved = readSolverRunState(f.stateFile), - task = saved.agentTeam!.workers[0]!.tasks[0]!; - expect(saved.agentTeam!.deliveries).toHaveLength(0); - expect(saved.agentTeam!.workers[0]!.error).toBe('math_verifier_unavailable'); - expect(task.helperSubmission).toEqual(declarations); - expect(task.sourceCommit).toBe(git(worker.worktree, ['rev-parse', 'HEAD'])); - // The research entry point binds the pinned Lead skill to the reloaded problem before team recovery. - pinSolverResearchSkill( - saved.problem, - saved.worktree, - readMathAgentSkill(path.join(saved.worktree, '.agents/skills/theoremos-research/SKILL.md')), - ); - const restored = f.makeTeam(saved); - await restored.restore(); - expect(restored.archive.deliveries).toEqual([expect.objectContaining({ kind: 'helpers', taskId: task.id })]); - expect(task.helperSubmission).toBeUndefined(); - expect(restored.archive.adoptions.filter(item => item.targetId === 'lead')).toEqual([ - expect.objectContaining({ status: 'completed' }), - ]); - expect(fs.readFileSync(f.source(saved.worktree), 'utf8')).toContain(helper); - expect(f.sessions).toHaveLength(1); - }, 60_000); - - it('returns a standalone helper containing sorry to its author for correction', async () => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!; - // The host tactic battery cannot close False, so the sorry remains for the author. - fs.writeFileSync( - f.source(worker.worktree), - original.replace('theorem goal', 'theorem helper : False := by sorry\ntheorem goal'), - ); - expect( - await f.call( - { - operation: 'submit', - helpersOnly: true, - summary: 'Check this draft.', - declarations: [{ file: 'Submission.lean', name: 'Recovery.helper', type: 'False' }], - }, - worker.id, - ), - ).toMatchObject({ ok: true }); - first.complete(); - await idle(f.team); - expect(worker.tasks[0]!.error).toContain('Helper source contains sorry or admit.'); - expect(worker.tasks[0]!.helperSubmission).toBeUndefined(); - expect(f.team.archive.deliveries).toHaveLength(0); - }, 60_000); - - it('replays a recorded submit_helpers call from an older member thread', async () => { - const f = fixture(); - const originalCall = { operation: 'submit_helpers', summary: 'Verified standalone facts.', declarations }; - const context = { - threadId: 'old-member-thread', - turnId: 'old-turn', - callId: 'old-submit', - signal: f.controller.signal, - }; - const result = { ok: true, status: 'pending-writer-stop', taskId: 'old-task' }; - const saved = structuredClone(f.state); - const key = canonicalMathJson(['member', context.threadId, context.turnId, context.callId]); - const changedCall = { ...originalCall, summary: 'Changed replay.' }; - saved.agentTeam!.operations.push( - { key, digest: mathDigest(canonicalMathJson(originalCall)), result }, - { key, digest: mathDigest(canonicalMathJson(changedCall)), result: { ok: false } }, - ); - writeSolverRunState(f.stateFile, saved); - const restored = f.makeTeam(readSolverRunState(f.stateFile)); - const tools = restored.tools('member'); - await expect(tools.call('theoremos_team', originalCall, context)).resolves.toEqual(result); - await expect(tools.call('theoremos_team', changedCall, context)).rejects.toThrow('math_team_call_changed'); - expect(restored.archive.operations).toEqual(saved.agentTeam!.operations); - }); - - it('preserves the rejected Lean interface and check receipt for the producer, a repair peer and restored history', async () => { - const f = fixture({ maxAgents: 3 }); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery')); - const wrong = [{ ...declarations[0]!, type: 'False' }]; - await f.call({ operation: 'submit', summary: 'Check this interface.', declarations: wrong }, 'member'); - first.complete(); - await idle(f.team); - const task = worker.tasks[0]!, - locator = { operation: 'history', agentId: worker.id, offset: 0, limit: 1 }; - const failure = task.failedCheck!; - expect(task.status).toBe('failed'); - expect(failure).toMatchObject({ - declaration: wrong[0], - commit: git(worker.worktree, ['rev-parse', 'HEAD']), - seedCommit: f.problem.baseCommit, - objectiveRevision: 1, - environmentDigest: f.state.environmentDigest, - problemReceiptDigest: f.problem.receiptDigest, - sourceDigest: expect.stringMatching(/^[a-f0-9]{64}$/), - projectionCommit: expect.stringMatching(/^[a-f0-9]{40,64}$/), - results: [expect.objectContaining({ receiptId: expect.any(String), checkId: expect.any(String) })], - }); - expect(f.team.archive.events.find(event => event.kind === 'failed')?.text).toContain(JSON.stringify(locator)); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(readSolverRunState(f.stateFile).agentTeam!.workers[0]!.tasks[0]!.failedCheck).toEqual(failure); - await f.followup('member', 'Repair the rejected declaration.'); - const next = await f.session(1); - expect(next.message).toContain('failedCheck'); - expect((await f.call(locator, 'member')).tasks[0]?.failedCheck).toEqual(failure); - await f.spawn('repair', 'Read the earlier failed interface: ' + JSON.stringify(locator)); - await f.session(2); - expect((await f.call(locator, 'repair')).tasks[0]?.failedCheck).toEqual(failure); - expect(f.state.check).toBeUndefined(); - }, 60_000); - - it('rejects a non-owned declaration file before nomination, and accepts a corrected submission on the same turn', async () => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const session = await f.session(0), - worker = f.team.archive.workers[0]!; - expect( - await f.call( - { - operation: 'submit', - summary: 'Helper ready.', - declarations: [{ ...declarations[0], file: `${f.problem.projectRelative}/Submission.lean` }], - }, - 'member', - ), - ).toMatchObject({ - ok: false, - error: 'math_agent_team_proof_declaration_outside_ownership', - rejectedFiles: [`${f.problem.projectRelative}/Submission.lean`], - ownedFiles: ['Submission.lean'], - hint: expect.stringContaining('relative to the Lean project'), - }); - expect(worker.tasks[0]!.declarations).toBeUndefined(); - expect(worker.pendingDelivery).toBeUndefined(); - expect(session.options.requestGate!.checkpoint!()).toBe(false); - fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery')); - expect( - await f.call({ operation: 'submit', summary: 'Corrected relative path.', declarations }, 'member'), - ).toMatchObject({ ok: true, status: 'pending-writer-stop' }); - session.complete(); - await idle(f.team); - expect(f.team.archive.deliveries).toHaveLength(1); - expect(worker.pendingDelivery).toBeUndefined(); - expect(f.state.check).toBeUndefined(); - }, 60_000); - - it.each(['outside-ownership', 'original-declaration'] as const)( - 'preserves a %s draft and notes, then permits an explicit same-member correction', - async kind => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!, - file = f.source(worker.worktree); - const valid = original.replace('end Recovery', helper + 'end Recovery'); - const invalid = kind === 'original-declaration' ? valid.replace('goal : True', 'goal : False') : valid; - fs.writeFileSync(file, invalid); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Keep this unfinished investigation.\n'); - if (kind === 'outside-ownership') { - fs.writeFileSync(path.join(worker.worktree, 'Sketch.lean'), 'theorem exploratory : True := by trivial\n'); - git(worker.worktree, ['add', 'Sketch.lean']); - } - expect(await f.call({ operation: 'submit', summary: 'Nominate helper.', declarations }, 'member')).toMatchObject({ - ok: true, - }); - first.complete(); - await idle(f.team); - const rejected = worker.tasks[0]!; - expect(worker).toMatchObject({ status: 'idle', activity: 'idle', phase: 'prepared' }); - expect(worker.pendingDelivery).toBeUndefined(); - expect(rejected.status).toBe('failed'); - expect(rejected.error).toContain( - kind === 'outside-ownership' ? 'Sketch.lean' : 'math_original_declaration_changed', - ); - expect(rejected.sourceCommit).toBeUndefined(); - expect(rejected.researchArtifactId).toBeUndefined(); - expect(f.team.archive.researchArtifacts ?? []).toHaveLength(0); - expect(f.team.archive.deliveries).toHaveLength(0); - expect(fs.readFileSync(file, 'utf8')).toBe(invalid); - expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe( - 'Keep this unfinished investigation.\n', - ); - expect(git(worker.worktree, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit); - if (kind === 'outside-ownership') - expect(git(worker.worktree, ['diff', '--cached', '--name-only'])).toBe('Sketch.lean'); - expect( - f.team.archive.events.some( - event => event.kind === 'failed' && event.text.includes('Lead can assign a correction'), - ), - ).toBe(true); - await f.followup('member', 'Correct the rejected source and resubmit the helper.'); - const correction = await f.session(1); - expect(correction.options.threadId).toBe(worker.native!.threadId); - expect(correction.message).toContain('Host rejected the edited source'); - expect(correction.message).toContain( - kind === 'outside-ownership' ? 'Sketch.lean' : 'math_original_declaration_changed', - ); - expect(fs.readFileSync(file, 'utf8')).toBe(invalid); - if (kind === 'outside-ownership') { - git(worker.worktree, ['reset', 'HEAD', '--', 'Sketch.lean']); - fs.renameSync(path.join(worker.worktree, 'Sketch.lean'), path.join(worker.worktree, '.scratch', 'Sketch.lean')); - } - fs.writeFileSync(file, valid); - expect( - await f.call({ operation: 'submit', summary: 'Source corrected; helper ready.', declarations }, 'member'), - ).toMatchObject({ ok: true }); - correction.complete(); - await idle(f.team); - expect(f.team.archive.deliveries).toHaveLength(1); - expect(worker.tasks[1]!.deliveryId).toBeDefined(); - expect(worker.tasks[1]!.researchArtifactId).toBeDefined(); - expect(worker.pendingDelivery).toBeUndefined(); - expect(rejected.status).toBe('failed'); - expect(f.state.check).toBeUndefined(); - }, - 60_000, - ); - - it('clears a restored stopped-writer nomination without rewriting its invalid source or fabricating an artifact', async () => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!; - first.complete(); - await idle(f.team); - await f.team.close(); - fs.writeFileSync(f.source(worker.worktree), original.replace('goal : True', 'goal : False')); - fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Notes saved before the previous process stopped.\n'); - const saved = readSolverRunState(f.stateFile), - recoveredWorker = saved.agentTeam!.workers[0]!, - task = recoveredWorker.tasks[0]!; - recoveredWorker.status = 'failed'; - recoveredWorker.activity = 'checking'; - recoveredWorker.phase = 'checking'; - recoveredWorker.pendingSourceBase = f.problem.baseCommit; - recoveredWorker.pendingDelivery = { taskId: task.id, seedCommit: f.problem.baseCommit, declarations }; - task.declarations = declarations; - const artifactCount = saved.agentTeam!.researchArtifacts?.length ?? 0; - const restored = f.makeTeam(saved); - await restored.restore(); - expect(recoveredWorker).toMatchObject({ status: 'idle', activity: 'idle', phase: 'prepared' }); - expect(recoveredWorker.pendingDelivery).toBeUndefined(); - expect(task.status).toBe('failed'); - expect(saved.agentTeam!.researchArtifacts ?? []).toHaveLength(artifactCount); - expect(saved.agentTeam!.deliveries).toHaveLength(0); - expect(fs.readFileSync(f.source(recoveredWorker.worktree), 'utf8')).toContain('goal : False'); - expect(fs.readFileSync(path.join(recoveredWorker.worktree, 'RESEARCH.md'), 'utf8')).toContain( - 'previous process stopped', - ); - await f.followup('member', 'Repair the statement and prove the helper.', restored); - const correction = await f.session(1); - expect(correction.message).toContain('math_original_declaration_changed'); - fs.writeFileSync(f.source(recoveredWorker.worktree), original.replace('end Recovery', helper + 'end Recovery')); - expect( - await f.call({ operation: 'submit', summary: 'Recovered and repaired.', declarations }, 'member', restored), - ).toMatchObject({ ok: true }); - correction.complete(); - await idle(restored); - expect(saved.agentTeam!.deliveries).toHaveLength(1); - expect(saved.check).toBeUndefined(); - }, 60_000); - - it('retains a nomination on an unrelated infrastructure failure', async () => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery')); - expect(await f.call({ operation: 'submit', summary: 'Helper ready.', declarations }, 'member')).toMatchObject({ - ok: true, - }); - const read = fs.readFileSync.bind(fs); - const spy = vi.spyOn(fs, 'readFileSync').mockImplementation((...args: Parameters) => { - if (args[0] === f.source(worker.worktree)) throw Object.assign(new Error('fixture-source-EIO'), { code: 'EIO' }); - return read(...args); - }); - first.complete(); - await idle(f.team); - spy.mockRestore(); - expect(worker.status).toBe('failed'); - expect(worker.error).toBe('fixture-source-EIO'); - expect(worker.pendingDelivery).toBeDefined(); - expect(f.team.archive.deliveries).toHaveLength(0); - }); - - it('returns a member nomination that exhausts the Lean memory limit to Lead as correctable feedback', async () => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery')); - expect(await f.call({ operation: 'submit', summary: 'Helper ready.', declarations }, 'member')).toMatchObject({ - ok: true, - }); - proofChecks.check = (input: { declarations: typeof declarations; worktree: string }) => - memoryLimit(input.declarations[0]!, git(input.worktree, ['rev-parse', 'HEAD'])); - first.complete(); - await idle(f.team); - const task = worker.tasks[0]!; - expect(worker).toMatchObject({ status: 'idle', activity: 'idle', phase: 'prepared' }); - expect(task.status).toBe('failed'); - expect(task.error).toContain(LEAN_MEMORY_LIMIT_ERROR); - expect(task.failedCheck).toMatchObject({ - declaration: declarations[0], - results: [expect.objectContaining({ error: LEAN_MEMORY_LIMIT_ERROR })], - }); - expect( - f.team.archive.events.some( - event => event.kind === 'failed' && event.to === 'lead' && event.text.includes(LEAN_MEMORY_LIMIT_ERROR), - ), - ).toBe(true); - expect(worker.pendingDelivery).toBeUndefined(); - expect(f.team.archive.deliveries).toHaveLength(0); - }, 60_000); - - it('fails a Lead adoption that exhausts the Lean memory limit without stopping the team', async () => { - const f = fixture(); - await f.spawn('member', 'Prove the helper.'); - const first = await f.session(0), - worker = f.team.archive.workers[0]!; - fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery')); - expect(await f.call({ operation: 'submit', summary: 'Helper ready.', declarations }, 'member')).toMatchObject({ - ok: true, - }); - first.complete(); - await idle(f.team); - const delivery = f.team.archive.deliveries[0]!; - expect(await f.call({ operation: 'adopt', deliveryId: delivery.id })).toMatchObject({ ok: true }); - proofChecks.integrate = (input: { expectedCommit: string }) => memoryLimit(declarations[0]!, input.expectedCommit); - await expect(f.team.flushAdoptions()).resolves.toBeUndefined(); - expect(f.team.archive.adoptions).toEqual([ - expect.objectContaining({ - deliveryId: delivery.id, - targetId: 'lead', - status: 'failed', - error: expect.stringContaining(LEAN_MEMORY_LIMIT_ERROR), - }), - ]); - expect( - f.team.archive.events.some( - event => event.kind === 'failed' && event.to === 'lead' && event.text.includes(LEAN_MEMORY_LIMIT_ERROR), - ), - ).toBe(true); - expect(git(f.state.worktree, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit); - }, 60_000); - - it('resumes the exact acknowledged nomination after writer loss but honors an explicit cancellation', async () => { - const f = fixture(); - await f.spawn('member', 'Route: test-route\nInvestigate.'); - await f.session(0); - const worker = f.team.archive.workers[0]!, - task = worker.tasks[0]!; - const message = 'Prove the helper.'; - await f.followup(worker.id, message); - fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery')); - const reply = await f.call( - { operation: 'submit', summary: 'Ready to check.', objectiveRevision: 2, declarations }, - 'member', - ); - expect(reply).toMatchObject({ status: 'pending-writer-stop' }); - const beforeCancel = readSolverRunState(f.stateFile); - expect( - await f.call({ - operation: 'retire_route', - routeId: 'test-route', - reason: 'This route is ruled out.', - evidenceRefs: ['RESEARCH.md'], - }), - ).toMatchObject({ ok: true, cancelledTaskIds: [task.id] }); - await idle(f.team); - expect(f.team.archive.deliveries).toHaveLength(0); - const cancelled = f.makeTeam(readSolverRunState(f.stateFile)); - await cancelled.restore(); - expect(cancelled.archive.deliveries).toHaveLength(0); - // Legacy shutdown saved source and status but did not register the acknowledged submission. - const legacy = readSolverRunState(f.stateFile); - const old = legacy.agentTeam!.workers[0]!.tasks[0]!; - old.status = 'interrupted'; - delete old.cancelRequested; - delete old.nomination; - const sourceFile = f.source(worker.worktree), - fixed = fs.readFileSync(sourceFile, 'utf8'); - fs.writeFileSync(sourceFile, fixed + '\n-- newer draft\n'); - const dirty = f.makeTeam(structuredClone(legacy)); - await dirty.restore(); - expect(dirty.archive.deliveries).toHaveLength(0); - fs.writeFileSync(sourceFile, fixed); - const exact = f.makeTeam(legacy); - await exact.restore(); - expect(exact.archive.deliveries).toHaveLength(1); - // It has amended history, but no evidence of which revision nominated it. - expect(readAgentTeamProofDelivery(exact.archive.deliveries[0]!.path, legacy).provenance).not.toHaveProperty( - 'objectiveRevision', - ); - const recovered = f.makeTeam(beforeCancel); - await recovered.restore(); - const recoveredTask = recovered.archive.workers[0]!.tasks[0]!; - expect(recoveredTask.status, recoveredTask.error).toBe('interrupted'); - expect(recovered.archive.deliveries).toHaveLength(1); - expect(readAgentTeamProofDelivery(recovered.archive.deliveries[0]!.path, beforeCancel).provenance).toMatchObject({ - taskId: task.id, - objectiveRevision: 2, - objectiveDigest: mathDigest(message), - }); - expect(f.sessions).toHaveLength(1); - }, 60_000); -}); diff --git a/tests/agentTeamTool.test.ts b/tests/agentTeamTool.test.ts deleted file mode 100644 index 0f4e54dd..00000000 --- a/tests/agentTeamTool.test.ts +++ /dev/null @@ -1,184 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { MathAgentToolDispatcher } from '../src/runtime/agentTeamTools'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { - agentTeamArgumentFeedback, - agentTeamRequestSchema, - agentTeamToolDefinition, -} from '../src/solver/agentTeamTool'; -import { directSolverModules } from '../src/solver/modules'; -import { readSolverProblem } from '../src/solver/problem'; -import { temporaryDirectory } from './helpers/files'; -import { solverState } from './helpers/solver'; - -type Json = Record; -const fixtures: { directory: string; team: AgentResearchTeam }[] = []; -afterEach(async () => { - for (const fixture of fixtures.splice(0)) { - await fixture.team.close(); - fs.rmSync(fixture.directory, { recursive: true, force: true }); - } -}); - -function fixture(actor = 'member') { - const directory = temporaryDirectory('agent-team-tool-contract-'); - const receipt = bootstrapLeanTask(path.join(directory, 'work'), { - source: 'theorem original : True := by sorry\n', - task: 'Offline tool contract fixture.', - }); - const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath); - const state = solverState(problem, receipt.workspaceRoot, { - runId: 'tool-contract', - phase: 'running', - researchMode: 'skill', - researchDelegation: { mode: 'team', maxAgents: 3 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }); - const team = new AgentResearchTeam({ - state, - root: process.cwd(), - taskText: 'Offline tool contract fixture.', - leadAccess: { environment: {}, retrievalRoot: receipt.workspaceRoot }, - modules: directSolverModules, - executable: 'offline-no-model', - profile: 'offline-no-credentials', - signal: new AbortController().signal, - maxAgents: 3, - maxTurns: Infinity, - maxTurnMs: Infinity, - maxTotalTokens: 0, - remainingMs: () => Infinity, - save: () => {}, - emit: () => {}, - exclusiveCheck: operation => operation(), - }); - fixtures.push({ directory, team }); - const client = (caller: string) => { - const dispatcher = new MathAgentToolDispatcher( - team.tools(caller), - (threadId, turnId) => threadId === 'thread' && turnId === 'turn', - ); - dispatcher.beginTurn(); - const call = async (args: unknown, callId: string) => { - const response = await dispatcher.call({ - threadId: 'thread', - turnId: 'turn', - callId, - tool: 'theoremos_team', - arguments: args, - }); - return { response, value: JSON.parse((response.contentItems as Json[])[0]!.text) as Json }; - }; - return { dispatcher, call }; - }; - return { team, ...client(actor), client, state }; -} - -function branch(actor: string, operation: string): Json { - const definition = agentTeamToolDefinition(actor); - const schema = (definition.inputSchema.oneOf as Json[]).find(item => item.properties.operation.enum[0] === operation); - if (!schema) throw new Error('Missing advertised operation: ' + operation); - return schema; -} - -describe('mathematical team tool contracts', () => { - it('advertises role-specific math operations and the optional Lead plan gate', () => { - const child = agentTeamToolDefinition('member'); - const lead = agentTeamToolDefinition('lead'); - const approval = agentTeamToolDefinition('lead', true); - expect((child.inputSchema.properties.operation as Json).enum).toEqual([ - 'yield', - 'history', - 'inspect', - 'inspect-research', - 'submit', - 'route_summary', - ]); - expect((lead.inputSchema.properties.operation as Json).enum).toEqual([ - 'finish', - 'history', - 'inspect', - 'inspect-research', - 'adopt', - 'retire_route', - 'route_summary', - ]); - expect((approval.inputSchema.properties.operation as Json).enum).toContain('publish_plan'); - expect((agentTeamToolDefinition('member', true).inputSchema.properties.operation as Json).enum).not.toContain( - 'publish_plan', - ); - expect(branch('member', 'submit')).toMatchObject({ - required: ['operation', 'summary', 'declarations'], - additionalProperties: false, - properties: { declarations: { items: { required: ['file', 'name', 'type'], additionalProperties: false } } }, - }); - expect(branch('member', 'submit').properties).not.toHaveProperty('agentId'); - expect(branch('member', 'submit').properties).not.toHaveProperty('objectiveRevision'); - expect(branch('member', 'history').properties.limit.maximum).toBe(8); - }); - - it('returns the selected operation contract when a caller supplies another member identity', () => { - const args = { - operation: 'submit', - agentId: 'peer', - summary: 'Saved helper.', - declarations: [{ file: 'Submission.lean', name: 'helper', type: 'True' }], - }; - const parsed = agentTeamRequestSchema.safeParse(args); - if (parsed.success) throw new Error('The malformed request must be rejected.'); - expect(agentTeamArgumentFeedback('member', args, parsed.error)).toMatchObject({ - ok: false, - error: 'math_team_arguments_invalid', - contract: branch('member', 'submit'), - hint: expect.stringContaining('other fields forbidden'), - }); - }); - - it('rejects removed collaboration commands and unauthorized math commands without mutating the journal', async () => { - const f = fixture(); - for (const operation of ['spawn', 'assign', 'amend', 'cancel', 'coordinate', 'message', 'poll', 'wait', 'budget']) { - const result = await f.client('lead').call({ operation }, 'removed-' + operation); - expect(result.value).toMatchObject({ ok: false, error: 'math_team_arguments_invalid' }); - expect(result.value.allowedOperations).not.toContain(operation); - } - const adopt = await f.call({ operation: 'adopt', deliveryId: '0'.repeat(64) }, 'child-adopt'); - expect(adopt.value).toMatchObject({ ok: false, error: 'math_team_native_operation_required' }); - expect(f.team.archive.events).toHaveLength(0); - expect(f.team.archive.operations).toHaveLength(0); - }); - - it('makes Lead finish replay-safe through the host dispatcher', async () => { - const f = fixture('lead'), - args = { operation: 'finish', summary: 'The candidate is ready for checking.' }; - const first = await f.call(args, 'finish'), - duplicate = await f.client('lead').call(args, 'finish'); - expect(first.value).toMatchObject({ - ok: true, - status: 'pending-writer-stop', - originalProblemAcceptance: 'not-assessed', - }); - expect(duplicate.response).toEqual(first.response); - expect(f.team.archive.completionRequested?.summary).toBe(args.summary); - expect(f.team.archive.operations).toHaveLength(1); - const changed = await f.client('lead').dispatcher.call({ - threadId: 'thread', - turnId: 'turn', - callId: 'finish', - tool: 'theoremos_team', - arguments: { ...args, summary: 'Changed replay.' }, - }); - expect(changed).toMatchObject({ success: false }); - expect(f.team.archive.completionRequested?.summary).toBe(args.summary); - }); -}); diff --git a/tests/agentTeamTransportFallback.test.ts b/tests/agentTeamTransportFallback.test.ts index 069c91ff..a93061d8 100644 --- a/tests/agentTeamTransportFallback.test.ts +++ b/tests/agentTeamTransportFallback.test.ts @@ -49,7 +49,7 @@ function fixture( researchDelegation: { mode: 'team', maxAgents: 3 }, agentTeam: { schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', + transport: 'codex-shared', workers: [], events: [], deliveries: [], @@ -122,78 +122,69 @@ function fixture( const startupError = 'math_codex_rpc_failed:-32603:thread/start'; -describe('AgentResearchTeam startup transport', () => { +describe('shared Codex team startup', () => { it('surfaces a native startup failure without creating a host-tools team', async () => { const f = fixture(async options => { - expect(options.nativeAgentControl).toBeDefined(); + expect(options.sharedProofTeam).toBeDefined(); throw new Error(startupError); }); await expect(f.run()).rejects.toThrow(startupError); expect(f.start).toHaveBeenCalledOnce(); expect(readSolverRunState(f.stateFile)).toMatchObject({ turns: 0, - agentTeam: { transport: 'native-agent-control' }, + agentTeam: { transport: 'codex-shared' }, }); expect(f.emit.mock.calls.map(([event]) => event)).not.toContain('team_transport_fallback'); }); - it('leaves saved host-tools teams readable without starting their writers', async () => { - const f = fixture(async () => { - throw new Error('Historical teams must use their pinned revision.'); - }); - f.state.agentTeam!.transport = 'host-tools'; - writeSolverRunState(f.stateFile, f.state); - await expect(f.run()).rejects.toThrow('math_legacy_collaboration_retired'); - expect(f.start).not.toHaveBeenCalled(); - expect(readSolverRunState(f.stateFile)).toMatchObject({ turns: 0, agentTeam: { transport: 'host-tools' } }); - }); - - it.each(['abort', 'auth', 'auth-wrapped', 'prior-turn', 'shutdown-unconfirmed'] as const)( - 'preserves transport on %s', - async mode => { - 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'); + it.each(['host-tools', 'native-agent-control'] as const)( + 'keeps saved %s teams readable without starting their writers', + async transport => { + const f = fixture(async () => { + throw new Error('Historical teams must use their pinned revision.'); + }); + f.state.agentTeam!.transport = transport; + writeSolverRunState(f.stateFile, f.state); + await expect(f.run()).rejects.toThrow('math_legacy_collaboration_retired'); + expect(f.start).not.toHaveBeenCalled(); + expect(readSolverRunState(f.stateFile)).toMatchObject({ turns: 0, agentTeam: { transport } }); }, ); + + it.each(['abort', 'auth', 'prior-turn', 'shutdown-unconfirmed'] as const)('preserves transport on %s', async mode => { + const error = + mode === 'auth' + ? 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('codex-shared'); + expect(f.emit.mock.calls.map(([event]) => event)).not.toContain('team_transport_fallback'); + }); }); -describe('native Lead recovery', () => { - it.each(['transport exit', 'context overflow'] as const)('reopens the same team root after %s', async failure => { +describe('shared team recovery', () => { + it.each(['transport exit', 'context overflow'] as const)('continues in the same checkout after %s', async failure => { const threadId = 'native-lead'; const sequence: string[] = []; - const compact = vi.fn(async () => { - sequence.push('compact'); - }); const f = fixture( async options => { const reopening = f.start.mock.calls.length > 1; - expect(options.nativeAgentControl).toBeDefined(); - expect(options.threadId).toBe(reopening ? threadId : undefined); - if (!reopening) - f.state.agentTeam!.nativeControl = { sessionId: threadId, rootThreadId: threadId, sequence: 0, mailbox: [] }; + expect(options.sharedProofTeam).toBeDefined(); + expect(options.threadId).toBeUndefined(); + expect(options.workspace).toBe(f.state.worktree); let lastError: string | undefined; return { - threadId, - compact, + threadId: reopening ? 'replacement-lead' : threadId, get lastError() { return lastError; }, @@ -218,15 +209,12 @@ describe('native Lead recovery', () => { 2, ); await f.run(); - expect(sequence).toEqual( - failure === 'transport exit' - ? ['first', 'close', 'retry', 'close'] - : ['first', 'close', 'compact', 'retry', 'close'], - ); + expect(sequence).toEqual(['first', 'close', 'retry', 'close']); expect(readSolverRunState(f.stateFile)).toMatchObject({ - threadId, + threadId: 'replacement-lead', + previousThreadIds: [threadId], turns: 2, - agentTeam: { nativeControl: { sessionId: threadId, rootThreadId: threadId } }, + agentTeam: { transport: 'codex-shared' }, }); }); }); @@ -234,12 +222,6 @@ describe('native Lead recovery', () => { describe('native Lead plan approval', () => { it('stops the planning writer, waits for the exact version, then resumes the same thread', async () => { const setWaiting = vi.fn(); - const retiredRoute = { - routeId: 'structural-symmetry', - retiredAt: 1, - source: 'lead' as const, - reason: 'Counterexample in the member report.', - }; const close = vi.fn(async () => {}); const stopForFreeze = vi.fn(async () => ({ status: 'stopped' as const })); const f = fixture( @@ -247,7 +229,10 @@ describe('native Lead plan approval', () => { const planning = f.start.mock.calls.length === 1; expect(options.threadId).toBe(planning ? undefined : 'native-plan-lead'); expect(Boolean(options.readOnlyWorkspace)).toBe(planning); - expect(JSON.stringify(options.tools!.definitions)).toContain('publish_plan'); + expect(options.sharedProofTeam).toBeDefined(); + if (planning) expect(options.tools!.definitions).toHaveLength(1); + else expect(options.tools).toBeUndefined(); + if (planning) expect(JSON.stringify(options.tools!.definitions)).toContain('publish_plan'); return { threadId: 'native-plan-lead', close, @@ -260,32 +245,6 @@ describe('native Lead plan approval', () => { expect(message).toContain('The human approved plan version'); expect(message).toContain('Verify the available identity lemma.'); expect(message).toContain('Check the identity.'); - const control = options.nativeAgentControl!; - const threadId = 'native-plan-lead'; - const connection = { request: vi.fn(), update: vi.fn(), input: vi.fn() }; - const callNative = (operation: string, payload: Record) => - control.request( - { version: 1, sessionId: threadId, threadId, operation, operationId: operation, payload }, - connection, - { signal: f.controller.signal }, - ); - await callNative('attach', { threadId, sessionId: threadId }); - await expect( - callNative('spawn', { - caller: threadId, - source: { subagent: { thread_spawn: { parent_thread_id: threadId, agent_path: '/root/prover' } } }, - bootstrap: { config: { model: f.state.model, reasoningEffort: f.state.effort } }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Route: structural-symmetry\nCheck the remaining lemma.' }, - }, - }), - ).rejects.toThrow('math_team_route_retired:structural-symmetry'); - expect(readSolverRunState(f.stateFile).agentTeam).toMatchObject({ - retiredRoutes: [retiredRoute], - workers: [], - }); fs.writeFileSync( path.join(workspace, f.state.problem.projectRelative, f.state.problem.ownedFiles[0]!), LOCAL_EXAMPLE_PROOF, @@ -296,11 +255,13 @@ describe('native Lead plan approval', () => { const context = { threadId: 'native-plan-lead', turnId, signal: f.controller.signal }; const call = (callId: string, args: unknown) => options.tools!.call('theoremos_team', args, { ...context, callId }); - const goal = { theoremName: f.state.problem.targets[0]!.theoremName, objective: 'Use the left identity.' }; - expect(await call('incomplete', { operation: 'publish_plan', goals: [goal] })).toMatchObject({ - ok: false, - error: expect.stringContaining('math_team_plan_targets_mismatch'), - }); + const goal = { + theoremName: f.state.problem.targets[0]!.theoremName, + objective: 'Use the left identity.', + }; + await expect(call('incomplete', { operation: 'publish_plan', goals: [goal] })).rejects.toThrow( + 'math_team_plan_targets_mismatch', + ); const goals = f.state.problem.targets.map(target => ({ theoremName: target.theoremName, objective: 'Check the identity.', @@ -313,10 +274,6 @@ describe('native Lead plan approval', () => { }), ).toMatchObject({ ok: true, status: 'pending', planVersion: expect.any(String) }); expect(options.requestGate?.checkpoint?.()).toBe(true); - expect(await call('finish-blocked', { operation: 'finish', summary: 'done' })).toMatchObject({ - ok: false, - error: expect.stringContaining('math_team_plan_approval_required'), - }); return 'checkpoint'; }, }; @@ -325,7 +282,6 @@ describe('native Lead plan approval', () => { 2, { review: true, setWaiting }, ); - f.state.agentTeam!.retiredRoutes = [retiredRoute]; const running = f.run(); await vi.waitFor(() => expect(setWaiting).toHaveBeenCalledWith(true)); expect(stopForFreeze).toHaveBeenCalledOnce(); @@ -336,9 +292,9 @@ describe('native Lead plan approval', () => { const pending = readSolverRunState(f.stateFile); const plan = exportRunPlan(pending); expect(plan.tasks.map(task => task.kind)).toEqual(['goal', 'goal', 'research']); - expect(buildRunInspection(pending).planApproval).toMatchObject({ - status: 'pending', - planVersion: plan.baseVersion, + expect(buildRunInspection(pending)).toMatchObject({ + agentTeam: { transport: 'codex-shared' }, + planApproval: { status: 'pending', planVersion: plan.baseVersion }, }); await expect(queuePlanApproval(f.stateFile, { id: 'stale', planVersion: 'other-version' })).rejects.toThrow( 'math_plan_approval_version_conflict', diff --git a/tests/agentTeamViews.test.ts b/tests/agentTeamViews.test.ts index 21275c95..d2c330b7 100644 --- a/tests/agentTeamViews.test.ts +++ b/tests/agentTeamViews.test.ts @@ -1,10 +1,8 @@ import { describe, expect, it } from 'vitest'; import type { SolverRunState } from '../src/solver/archive'; import { agentTeamStateSchema, type AgentTeamState } from '../src/solver/agentTeamState'; -import { agentTeamInboxPreview, agentTeamOverview, agentTeamTaskHistory } from '../src/solver/agentTeamViews'; -import { agentTeamWorkerSection } from '../src/solver/agentTeamContext'; -import { agentTeamContextSection } from '../src/solver/skillResearchContext'; -import { compileContextSections } from '../src/solver/contextCompiler'; +import { agentTeamOverview } from '../src/solver/agentTeamViews'; +import { buildTokenBudget } from '../src/solver/usageBudget'; const commit = 'a'.repeat(40), artifactId = 'b'.repeat(64); @@ -34,60 +32,9 @@ function fixture(): SolverRunState { } as SolverRunState; } -describe('bounded team observations and complete history', () => { - it('keeps both dispatch contexts within budget after thousands of long tasks and reference records', () => { - const state = fixture(), - team = state.agentTeam!, - worker = team.workers[0]!; - const longText = '数学🧠'.repeat(3000), - current = worker.tasks[0]!; - worker.tasks = Array.from({ length: 2000 }, (_, index) => ({ - id: `past-${index}`, - message: longText, - summary: longText, - error: longText, - status: 'completed', - sourceCommit: commit, - researchArtifactId: artifactId, - deliveryId: artifactId, - })); - worker.tasks.push(current); - team.researchArtifacts = Array.from({ length: 2000 }, (_, index) => ({ - id: String(index).padStart(64, '0'), - agentId: 'child', - taskId: `past-${index}`, - commit, - path: '/host/private/not-exposed.json', - })); - team.deliveries = team.researchArtifacts.map(({ id, agentId, taskId, path }) => ({ id, agentId, taskId, path })); - team.events = Array.from({ length: 80 }, (_, index) => ({ - sequence: index + 1, - from: 'child', - to: index % 2 ? 'lead' : 'child', - kind: 'message', - text: longText, - at: index, - })); - const task = { taskId: current.id, message: current.message, sourceCommit: commit }; - const child = agentTeamWorkerSection(state, { id: 'child', role: 'worker' }, task); - for (const section of [child.section, agentTeamContextSection(state)]) { - const compiled = compileContextSections({ instructions: 'Team instructions.', mandatory: [section] }); - expect(compiled.manifest.usedBytes).toBeLessThan(96 * 1024); - expect(section.text).not.toContain('/host/private'); - expect(section.text).toContain('history'); - expect(section.text).toContain('textTruncated'); - } - const overview = agentTeamOverview(state); - expect(overview.workers[0].tasks).toHaveLength(4); - expect(overview.workers[0].tasks.some(task => task.id === 'current')).toBe(true); - expect(overview.researchArtifacts).toHaveLength(8); - expect(overview.deliveries).toHaveLength(8); - expect(overview.omissions.tasks).toBe(1997); - expect(overview.totals.tasks).toBe(2001); - expect(child.inboxThrough).toBe(0); - expect(team.workers[0].tasks[0].summary).toBe(longText); - }); +const viewTeam = (state: SolverRunState) => agentTeamOverview(state, state.tokenBudget ?? buildTokenBudget(0, [])); +describe('bounded historical team observations', () => { it('retains the current task, the next queued task and recent results instead of all queued objectives', () => { const state = fixture(), worker = state.agentTeam!.workers[0]!; @@ -104,12 +51,12 @@ describe('bounded team observations and complete history', () => { status: 'queued' as const, })), ); - const overview = agentTeamOverview(state); + const overview = viewTeam(state); expect(overview.workers[0].tasks.map(task => task.id)).toEqual(['finished', 'current', 'queued-0', 'queued-19']); expect(overview.workers[0].queuedTaskCount).toBe(20); }); - it('bounds retired-member observations while preserving the focused member and all active peers', () => { + it('prioritizes active members and keeps the most recent retired members within the display limit', () => { const state = fixture(), team = state.agentTeam!, worker = team.workers[0]!; @@ -122,88 +69,11 @@ describe('bounded team observations and complete history', () => { })), ); team.workers.push({ ...worker, id: 'active-peer', tasks: [] }); - const overview = agentTeamOverview(state, { focusAgentId: 'retired-0' }); - expect(overview.workers).toHaveLength(4); - expect(overview.workers.map(item => item.id)).toEqual( - expect.arrayContaining(['child', 'active-peer', 'retired-0']), - ); + const overview = viewTeam(state); + expect(overview.workers.map(item => item.id)).toEqual(['child', 'retired-18', 'retired-19', 'active-peer']); expect(overview.omissions.workers).toBe(18); }); - it('paginates full UTF-8 task text at whole task boundaries without skipping on byte limits or appended tasks', () => { - const state = fixture(), - team = state.agentTeam!, - worker = team.workers[0]!; - const completeText = '论'.repeat(16000); - worker.tasks = Array.from({ length: 7 }, (_, index) => ({ - id: `task-${index}`, - sequence: index + 1, - message: completeText, - summary: completeText, - error: completeText, - status: 'completed', - })); - team.researchState = { revision: 3, summary: completeText, publishedAt: 123 }; - const first = agentTeamTaskHistory(team, { limit: 8 }); - expect(first.tasks).toHaveLength(1); - expect(first.nextOffset).toBe(1); - expect(first.tasks[0].objective).toBe(completeText); - expect(first.tasks[0].summary).toBe(completeText); - expect(first.researchState?.summary).toBe(completeText); - const read = first.tasks.map(task => task.id); - team.workers.push({ - ...worker, - id: 'later', - tasks: [{ id: 'appended', sequence: 8, message: 'An assignment appended during pagination.', status: 'queued' }], - }); - let offset = first.nextOffset; - while (offset !== null) { - const page = agentTeamTaskHistory(team, { offset, limit: 8 }); - read.push(...page.tasks.map(task => task.id)); - offset = page.nextOffset; - } - expect(read).toEqual([...Array.from({ length: 7 }, (_, index) => `task-${index}`), 'appended']); - expect(new Set(read).size).toBe(read.length); - const overview = agentTeamOverview(state); - const selected = overview.workers[0].tasks[0]; - expect(agentTeamTaskHistory(team, { agentId: 'child', offset: selected.historyOffset, limit: 1 }).tasks[0].id).toBe( - selected.id, - ); - expect(overview.researchState).toMatchObject({ revision: 3, summaryTruncated: true, advisory: true }); - }); - - it('does not copy unbounded submitted declarations into a context or a history page', () => { - const state = fixture(), - task = state.agentTeam!.workers[0].tasks[0]; - task.declarations = Array.from({ length: 32 }, (_, index) => ({ - file: 'Main.lean', - name: `helper${index}`, - type: 'Nat → '.repeat(3000) + 'True', - premises: Array.from({ length: 128 }, () => 'P'.repeat(8000)), - })); - const overview = agentTeamOverview(state), - history = agentTeamTaskHistory(state.agentTeam!); - expect(overview.workers[0].tasks[0].declarationCount).toBe(32); - expect(history.tasks[0].declarationCount).toBe(32); - expect('declarations' in history.tasks[0]).toBe(false); - expect(Buffer.byteLength(JSON.stringify(overview))).toBeLessThan(8 * 1024); - }); - - it('does not acknowledge a truncated message or any message after it', () => { - const state = fixture(), - team = state.agentTeam!; - team.events = [ - { sequence: 1, from: 'lead', to: 'child', kind: 'message', text: 'A full short message.', at: 1 }, - { sequence: 2, from: 'lead', to: 'child', kind: 'message', text: '🧠'.repeat(1000), at: 2 }, - { sequence: 3, from: 'peer', to: 'child', kind: 'message', text: 'Another complete message.', at: 3 }, - ]; - const inbox = agentTeamInboxPreview(team, 'child', 0); - expect(inbox).toMatchObject({ through: 1, previewThrough: 3, more: true }); - expect(inbox.events[1]).toMatchObject({ sequence: 2, textTruncated: true, text: '🧠'.repeat(800) }); - expect(agentTeamInboxPreview(team, 'child', inbox.through).events[0].sequence).toBe(2); - expect(team.events[1].text).toHaveLength(2000); - }); - it('retains an in-progress integration among many old results and exposes writer shutdown separately', () => { const state = fixture(), team = state.agentTeam!, @@ -217,14 +87,14 @@ describe('bounded team observations and complete history', () => { targetId: 'child', status: index ? 'completed' : 'integrating', })); - expect(agentTeamOverview(state).adoptions.some(item => item.id === 'adoption-0')).toBe(true); - expect(agentTeamOverview(state).workers[0].activity).toBe('integrating'); + expect(viewTeam(state).adoptions.some(item => item.id === 'adoption-0')).toBe(true); + expect(viewTeam(state).workers[0].activity).toBe('integrating'); worker.writerStopUnconfirmed = { at: 123, reason: 'The writer has not stopped.' }; - expect(agentTeamOverview(state).workers[0].activity).toBe('stopping'); - expect(agentTeamOverview(state).workers[0].status).toBe('idle'); + expect(viewTeam(state).workers[0].activity).toBe('stopping'); + expect(viewTeam(state).workers[0].status).toBe('idle'); }); - it('projects shared and focused task budgets with explicit unknown historical turn limits', () => { + it('projects shared and recorded task budgets with explicit unknown historical turn limits', () => { const state = fixture(), team = state.agentTeam!; state.tokenBudget = { @@ -241,15 +111,16 @@ describe('bounded team observations and complete history', () => { }); Object.assign(team.workers[0].tasks[0], { budget: { tokens: 3000, turns: 4 }, turns: 2 }); state.taskUsage = { current: { totalTokens: 500 } }; - expect(agentTeamOverview(state, { focusAgentId: 'child' }).budget).toMatchObject({ + const overview = viewTeam(state); + expect(overview.budget).toMatchObject({ maxTurns: 20, turnLimitKnown: true, remaining: { tokens: 8000, turns: 15 }, childRemaining: { tokens: 7000, turns: 13 }, - task: { id: 'current', remaining: { tokens: 2500, turns: 2 } }, }); + expect(overview.workers[0].tasks[0].budget.remaining).toEqual({ tokens: 2500, turns: 2 }); delete (team as AgentTeamState & { hostLimits?: unknown }).hostLimits; - expect(agentTeamOverview(state).budget).toMatchObject({ turnLimitKnown: false, remaining: { turns: null } }); + expect(viewTeam(state).budget).toMatchObject({ turnLimitKnown: false, remaining: { turns: null } }); }); it('projects activity, cumulative task use and pending proof work from the saved records without copying receipts', () => { @@ -277,7 +148,7 @@ describe('bounded team observations and complete history', () => { task.turns = 2; task.budget = { tokens: 2000, turns: 4 }; state.taskUsage = { [task.id]: { totalTokens: 500 } }; - const view = agentTeamOverview(state).workers[0]; + const view = viewTeam(state).workers[0]; expect(view.lastActivity).toEqual(worker.lastActivity); expect(view.activity).toBe('checking'); expect(view.usage).toEqual({ @@ -301,7 +172,7 @@ describe('bounded team observations and complete history', () => { expect(JSON.stringify(view)).not.toContain('private-receipt'); worker.requestUsageAccounting.pendingRequests = 0; worker.requestUsageAccounting.incomplete = true; - expect(agentTeamOverview(state).workers[0].usage).toMatchObject({ + expect(viewTeam(state).workers[0].usage).toMatchObject({ usageComplete: false, pendingRequests: 0, pending: false, diff --git a/tests/agentTeamWorkspace.test.ts b/tests/agentTeamWorkspace.test.ts deleted file mode 100644 index ee691987..00000000 --- a/tests/agentTeamWorkspace.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import fs from 'node:fs'; -import { createHash } from 'node:crypto'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('../src/math/nativeProcess', async importOriginal => { - const addon = process.env.THEOREMOS_TEST_PROCESS_ADDON; - if (!addon) return importOriginal(); - const handle = { exports: {} }; - process.dlopen(handle, addon); - return { nativeProcess: handle.exports }; -}); -import { temporaryDirectory } from './helpers/files'; -import { git } from '../src/solver/problem'; -import { - archiveAgentTeamCommits, - importAgentTeamCommit, - prepareAgentTeamWorkspace, -} from '../src/solver/agentTeamWorkspace'; - -const roots: string[] = []; -afterEach(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); -function fixture() { - const root = temporaryDirectory('team-source-isolation-'); - roots.push(root); - const source = path.join(root, 'lead'); - fs.mkdirSync(source); - git(source, ['init', '--quiet']); - const commit = (directory: string, text: string) => { - fs.writeFileSync(path.join(directory, 'proof.lean'), text); - git(directory, ['add', 'proof.lean']); - git(directory, [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@localhost', - 'commit', - '--no-gpg-sign', - '--quiet', - '-m', - text, - ]); - return git(directory, ['rev-parse', 'HEAD']); - }; - const seed = commit(source, 'seed'); - const input = (name: string) => ({ - sourceWorktree: source, - worktree: path.join(root, 'members', name), - seedCommit: seed, - migrationDirectory: path.join(root, 'archive', 'migrations'), - }); - return { root, source, seed, commit, input }; -} - -describe('independent team source repositories', () => { - it('shares only authorized seed ancestry and explicitly transfers a checked archived commit', () => { - const f = fixture(), - siblingOnly = f.commit(f.source, 'unpublished source'); - fs.appendFileSync(path.join(f.source, '.git/info/exclude'), '\n**/.lake/\n'); - const first = f.input('first'), - second = f.input('second'); - prepareAgentTeamWorkspace(first); - prepareAgentTeamWorkspace(second); - for (const input of [first, second]) { - expect(git(input.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir'])).toBe( - path.join(input.worktree, '.git'), - ); - expect(() => git(input.worktree, ['show', `${siblingOnly}:proof.lean`])).toThrow(); - expect(fs.existsSync(path.join(input.worktree, '.git/objects/info/alternates'))).toBe(false); - expect(git(input.worktree, ['remote'])).toBe(''); - fs.mkdirSync(path.join(input.worktree, 'project/.lake'), { recursive: true }); - fs.writeFileSync(path.join(input.worktree, 'project/.lake/source-constraints.json'), '{}'); - expect(git(input.worktree, ['status', '--porcelain'])).toBe(''); - } - const delivery = f.commit(first.worktree, 'checked peer result'); - expect(() => git(second.worktree, ['show', `${delivery}:proof.lean`])).toThrow(); - expect(() => git(f.source, ['show', `${delivery}:proof.lean`])).toThrow(); - const archive = path.join(f.root, 'archive', 'sources.git'); - archiveAgentTeamCommits(archive, first.worktree, [delivery]); - fs.rmSync(first.worktree, { recursive: true }); - importAgentTeamCommit(archive, second.worktree, delivery); - expect(git(second.worktree, ['show', `${delivery}:proof.lean`])).toBe('checked peer result'); - expect(git(second.worktree, ['rev-parse', 'HEAD'])).toBe(f.seed); - expect(() => git(second.worktree, ['show', `${siblingOnly}:proof.lean`])).toThrow(); - }); - - it('finishes a stopped migration after the linked metadata moved but before replacement', () => { - const f = fixture(); - const member = f.input('recover'); - fs.mkdirSync(path.dirname(member.worktree)); - git(f.source, ['worktree', 'add', '--quiet', '--detach', member.worktree, f.seed]); - const head = f.commit(member.worktree, 'member checkpoint'); - const draft = path.join(member.worktree, 'proof.lean'); - fs.writeFileSync(draft, 'saved uncommitted draft'); - const stage = path.join(member.migrationDirectory, createHash('sha256').update(member.worktree).digest('hex')); - const repository = path.join(stage, 'repository'); - fs.mkdirSync(repository, { recursive: true }); - git(repository, ['init', '--quiet']); - importAgentTeamCommit(member.worktree, repository, head); - git(repository, ['update-ref', '--no-deref', 'HEAD', head]); - git(repository, ['read-tree', head]); - fs.renameSync(path.join(member.worktree, '.git'), path.join(stage, 'linked.git')); - prepareAgentTeamWorkspace(member); - expect(git(member.worktree, ['rev-parse', 'HEAD'])).toBe(head); - expect(git(member.worktree, ['diff', '--name-only'])).toBe('proof.lean'); - expect(fs.readFileSync(draft, 'utf8')).toBe('saved uncommitted draft'); - expect(git(member.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir'])).toBe( - path.join(member.worktree, '.git'), - ); - }); - - it('migrates a stopped linked worktree while preserving uncommitted drafts and task files', () => { - const f = fixture(), - input = f.input('legacy'); - fs.mkdirSync(path.dirname(input.worktree)); - git(f.source, ['worktree', 'add', '--quiet', '--detach', input.worktree, f.seed]); - const own = f.commit(input.worktree, 'own checkpoint'); - const peer = f.commit(f.source, 'unrelated peer objects'); - fs.writeFileSync(path.join(input.worktree, 'proof.lean'), 'uncommitted proof draft'); - fs.mkdirSync(path.join(input.worktree, '.agents')); - fs.mkdirSync(path.join(input.worktree, '.scratch')); - fs.writeFileSync(path.join(input.worktree, '.agents/SKILL.md'), 'pinned skill'); - fs.writeFileSync(path.join(input.worktree, '.scratch/research'), 'unfinished research'); - fs.writeFileSync(path.join(input.worktree, 'RESEARCH.md'), 'ongoing assignment'); - prepareAgentTeamWorkspace(input); - prepareAgentTeamWorkspace(input); - expect(git(input.worktree, ['rev-parse', 'HEAD'])).toBe(own); - expect(fs.readFileSync(path.join(input.worktree, 'proof.lean'), 'utf8')).toBe('uncommitted proof draft'); - expect(fs.readFileSync(path.join(input.worktree, '.agents/SKILL.md'), 'utf8')).toBe('pinned skill'); - expect(fs.readFileSync(path.join(input.worktree, '.scratch/research'), 'utf8')).toBe('unfinished research'); - expect(fs.readFileSync(path.join(input.worktree, 'RESEARCH.md'), 'utf8')).toBe('ongoing assignment'); - expect(() => git(input.worktree, ['show', `${peer}:proof.lean`])).toThrow(); - expect(git(f.source, ['worktree', 'list', '--porcelain'])).not.toContain(input.worktree); - expect(git(input.worktree, ['diff', '--name-only'])).toBe('proof.lean'); - }); -}); diff --git a/tests/campaignLibraryNative.test.ts b/tests/campaignLibraryNative.test.ts index b539104c..13f551c0 100644 --- a/tests/campaignLibraryNative.test.ts +++ b/tests/campaignLibraryNative.test.ts @@ -19,6 +19,7 @@ import { solverState } from './helpers/solver'; vi.mock(import('../src/math/mathBuildManifest'), async original => ({ ...(await original()), readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: (await import('./helpers/buildManifest')).fixtureBuildDigest, })); const lean = newestLeanBinary(), roots: string[] = []; diff --git a/tests/codexSession.test.ts b/tests/codexSession.test.ts index 083edb0d..1b97fb47 100644 --- a/tests/codexSession.test.ts +++ b/tests/codexSession.test.ts @@ -35,6 +35,9 @@ fs.writeFileSync(process.env.CODEX_HOME + '/provider-environment.json', JSON.str fs.writeFileSync(process.env.CODEX_HOME + '/library-host-environment.json', JSON.stringify({ hostConfigPresent: process.env.THEOREMOS_LIBRARY_HOST_CONFIG !== undefined, })); +fs.writeFileSync(process.env.CODEX_HOME + '/backend-environment.json', JSON.stringify({ + hostAgentControlPresent: process.env.THEOREMOS_HOST_AGENT_CONTROL !== undefined, +})); if (process.env.WESTLAKEHPC_API_KEY) fs.writeFileSync(process.env.CODEX_HOME + '/westlake-environment.json', JSON.stringify({ receivedLocalCredential: process.env.WESTLAKEHPC_API_KEY !== 'upstream-westlake-fixture-secret', receivedSecondaryCredential: Boolean(process.env.WESTLAKEHPC_API_KEY_2), @@ -54,6 +57,8 @@ readline.createInterface({ input: process.stdin }).on('line', line => { settings = call.params; const fixtureInstruction = settings.developerInstructions.split(String.fromCharCode(10))[0]; if (fixtureInstruction === 'startup-crash') return process.exit(27); + if (call.method === 'thread/resume' && fixtureInstruction === 'long-resume-history' && !settings.excludeTurns) + return process.stdout.write('x'.repeat(9 * 1024 * 1024)); if (fixtureInstruction === 'mutate-profile') { const config = process.env.CODEX_HOME + '/config.toml'; const update = config + '.' + process.pid + '.updated'; @@ -233,7 +238,7 @@ readline.createInterface({ input: process.stdin }).on('line', line => { fs.rmSync(root, { recursive: true, force: true }); }); - it('protects the pinned Web provider config across concurrent sessions without native agent control', async () => { + it('protects the pinned Web provider config across concurrent sessions', async () => { const profile = path.join(root, 'web-profile'), workspaces = ['scout-one', 'scout-two'].map(name => path.join(root, name)); for (const directory of [profile, ...workspaces]) fs.mkdirSync(directory); @@ -520,7 +525,10 @@ readline.createInterface({ input: process.stdin }).on('line', line => { }); it('disables inherited MCP tools and handles completion before the start response', async () => { - session = await createCodexMathSession(options); + session = await createCodexMathSession({ + ...options, + environment: { ...process.env, THEOREMOS_HOST_AGENT_CONTROL: '1' }, + }); const started = vi.fn(); expect(await session.run('proof', 'message-1', root, started)).toBe('completed'); expect(started).toHaveBeenCalledWith('message-1'); @@ -541,6 +549,9 @@ readline.createInterface({ input: process.stdin }).on('line', line => { expect(start.config).not.toHaveProperty('include_environment_context'); expect(start).not.toHaveProperty('dynamicTools'); expect(calls.some(call => call.method.startsWith('theoremos/agentControl/'))).toBe(false); + expect(JSON.parse(fs.readFileSync(path.join(root, 'runtime', 'backend-environment.json'), 'utf8'))).toEqual({ + hostAgentControlPresent: false, + }); expect(start.developerInstructions).toContain(options.instructions); expect(start.developerInstructions).toContain('"login": false'); expect(start.config.mcp_servers.unrelated).toEqual({ enabled: false }); @@ -658,6 +669,26 @@ readline.createInterface({ input: process.stdin }).on('line', line => { }, ); + it('resumes from thread metadata if the saved history exceeds the stdio frame limit', async () => { + session = await createCodexMathSession({ + ...options, + threadId: 'retained-thread', + instructions: 'long-resume-history', + requestGate: () => ({ allowed: true, settle: () => {} }), + }); + const calls = fs + .readFileSync(path.join(root, 'runtime', 'calls.jsonl'), 'utf8') + .trim() + .split('\n') + .map(line => JSON.parse(line)); + expect(calls.filter(call => call.method === 'thread/resume').map(call => call.params.excludeTurns)).toEqual([ + undefined, + true, + ]); + expect(session.threadId).toBe('retained-thread'); + expect(await session.run('Resume proof work.', 'resumed-turn', root, () => {})).toBe('completed'); + }); + it('reports bounded activity and split lock markers without exposing content or unrelated threads', async () => { const activities: unknown[] = []; session = await createCodexMathSession({ ...options, onActivity: value => activities.push(value) }); diff --git a/tests/codexSessionAgentControl.test.ts b/tests/codexSessionAgentControl.test.ts deleted file mode 100644 index 503462ee..00000000 --- a/tests/codexSessionAgentControl.test.ts +++ /dev/null @@ -1,656 +0,0 @@ -import './helpers/nativeReferenceAddon'; -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createCodexMathSession } from '../src/runtime/codexSession'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; -import type { NativeAgentControlOptions } from '../src/runtime/nativeAgentControl'; -import { nativeAgentControlModelCatalog } from '../src/runtime/nativeAgentControl'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { deferred } from './helpers/async'; -import { stopProofWriter } from '../src/solver/proofWriter'; - -const fixture = String.raw` -const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'); -const directory = process.env.CODEX_HOME; -const send = value => process.stdout.write(JSON.stringify(value) + '\n'); -let start, settings, threadId, counter = 0, handoffTurn; -const handoffOperation = process.env.TEAM_HANDOFF_FIXTURE; -const handoffCall = id => send({id,method:'item/tool/call',params:{threadId,turnId:handoffTurn.id, - tool:'theoremos_team',callId:id,arguments:{operation:handoffOperation}}}); -const handoffComplete = (id, result, turnId = handoffTurn.id) => - send({method:'item/completed',params:{threadId,turnId,item:{id,type:'dynamicToolCall', - tool:'theoremos_team',arguments:{operation:handoffOperation},success:result.success,contentItems:result.contentItems}}}); -const host = (operation, id, extra = {}) => send({id,method:'theoremos/agentControl/request',params:{version:1, - sessionId:'root-id',threadId,operationId:'operation-'+id,operation,payload:{threadId,sessionId:'root-id',...extra}}}); -readline.createInterface({input:process.stdin}).on('line', line => { - const call = JSON.parse(line); - fs.appendFileSync(path.join(directory,'calls.jsonl'), JSON.stringify(call)+'\n'); - const reply = result => send({id:call.id,result}); - if (call.id === 'invalid-team-tool') { - handoffComplete(call.id, call.result); - return handoffCall('team-tool'); - } - if (call.id === 'team-tool') { - handoffComplete('stale-tool', call.result, 'previous-turn'); - handoffComplete(call.id, call.result); - return; - } - if (call.id === 'attach') { - fs.writeFileSync(path.join(directory,'attach.json'), JSON.stringify(call)); - const turns = process.env.LONG_RESUME_HISTORY && !settings.excludeTurns - ? [{id:'old-turn', items:[{type:'agentMessage', text:'x'.repeat(8 * 1024 * 1024)}]}] : []; - return send({id:start.id,result:{thread:{id:threadId,turns},model:settings.model,approvalPolicy:'never', - reasoningEffort:settings.config.model_reasoning_effort, - activePermissionProfile:start.params.bootstrap ? null : {id:'math-worker'}, - agentControl:{sessionId:'root-id',agent:{threadId},configSnapshot:{model:settings.model, - fullAccess:Boolean(process.env.BAD_CHILD_PERMISSIONS),permissionProfile:{type:'managed'}}}}}); - } - if (call.method === 'initialize') return reply({}); - if (call.method === 'theoremos/agentControl/capabilities') return reply({version:process.env.BAD_BACKEND ? 2 : 1, - backend:'theoremos-host',nativeTools:true,isolatedChildBootstrap:true}); - if (call.method === 'skills/list') return reply({data:[{cwd:call.params.cwds[0],errors:[],skills:[{ - name:'pinned-fixture',path:process.env.FIXTURE_SKILL_PATH,enabled:true}]}]}); - if (['thread/start','thread/resume','theoremos/agentControl/start'].includes(call.method)) { - start = call; settings = call.params.thread || call.params.resume || call.params; - threadId = settings.threadId || call.params.bootstrap?.threadId || 'root-id'; - fs.writeFileSync(path.join(directory,'backend-env.json'),JSON.stringify({enabled:process.env.THEOREMOS_HOST_AGENT_CONTROL})); - if (process.env.THEOREMOS_HOST_AGENT_CONTROL === '1') return host('attach','attach'); - return reply({thread:{id:threadId},model:settings.model,approvalPolicy:'never', - reasoningEffort:settings.config.model_reasoning_effort,activePermissionProfile:{id:'math-worker'}}); - } - if (call.method === 'thread/compact/start') { - const turn = { id:'compact-turn',status:'inProgress' }; - host('admitTurn','compact-admit',{turnId:turn.id}); - send({method:'turn/started',params:{threadId,turn}}); - send({method:'item/completed',params:{threadId,turnId:turn.id,item:{id:'summary',type:'contextCompaction'}}}); - send({method:'turn/completed',params:{threadId,turn:{...turn,status:'completed'}}}); - host('turnFinished','compact-finished',{outcome:{threadId,turnId:turn.id,status:{completed:null}}}); - host('releaseTurn','compact-release',{turnId:turn.id}); - return reply({}); - } - if (['turn/start','theoremos/agentControl/input'].includes(call.method)) { - const turn = {id:'native-turn-'+ ++counter,status:'inProgress'}; - const native = process.env.THEOREMOS_HOST_AGENT_CONTROL === '1'; - if (native) host('admitTurn','admit-'+counter,{turnId:turn.id}); - if (handoffOperation) { - handoffTurn = turn; - reply({threadId,submissionId:turn.id,turn,accepted:true}); - return handoffCall('invalid-team-tool'); - } - if (process.env.HOLD_HOST_CALLBACK) host('recordUsage','usage'); - send({method:'item/completed',params:{threadId,turnId:turn.id,item:{id:'answer',type:'agentMessage',text:'Research saved.'}}}); - send({method:'turn/completed',params:{threadId,turn:{...turn,status:'completed'}}}); - if (native) setImmediate(() => { - host('turnFinished','finished-'+counter,{outcome:{threadId,turnId:turn.id,status:{completed:'Research saved.'}}}); - host('releaseTurn','released-'+counter,{turnId:turn.id}); - }); - return reply({threadId,submissionId:turn.id,turn,accepted:true}); - } - if (call.method === 'turn/interrupt' && handoffTurn) { - reply({}); - send({method:'turn/completed',params:{threadId,turn:{...handoffTurn,status:'interrupted'}}}); - return host('releaseTurn','release-handoff',{turnId:handoffTurn.id}); - } - if (call.method === 'theoremos/agentControl/update') return reply({acceptedSequence:call.params.sequence}); -}); -`; - -describe('native AgentControl stdio integration without model calls', () => { - let directory: string, options: MathAgentOptions, session: MathAgentSession | undefined; - let host: NativeAgentControlOptions; - const calls = () => - fs - .readFileSync(path.join(directory, 'calls.jsonl'), 'utf8') - .trim() - .split('\n') - .map(line => JSON.parse(line)); - - beforeEach(() => { - directory = fs.mkdtempSync(path.join(os.tmpdir(), 'native-agent-control-')); - const home = path.join(directory, 'home'); - fs.mkdirSync(home); - // The harness checks both HOME and the operating system account's home when building its masks. - const account = os.userInfo(); - vi.spyOn(os, 'homedir').mockReturnValue(home); - vi.spyOn(os, 'userInfo').mockReturnValue({ ...account, homedir: home }); - const executable = path.join(directory, 'codex-fixture'); - fs.writeFileSync(executable, `#!${process.execPath}\n${fixture}`, { mode: 0o700 }); - host = { - request: vi.fn(async request => ({ - result: { sessionId: request.sessionId, ...(request.operation === 'admitTurn' ? { admitted: true } : {}) }, - })), - }; - options = { - executable, - profile: directory, - workspace: directory, - model: 'fixture-model', - effort: 'high', - instructions: 'Frozen proof role.', - environment: { HOME: home, PATH: '/usr/bin:/bin' }, - onUsage: vi.fn(), - }; - }); - - afterEach(async () => { - await session?.close(); - session = undefined; - vi.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - }); - - it.each([ - ['publish_plan', { status: 'pending' }], - ['submit', { status: 'pending-writer-stop' }], - ['submit_helpers', { status: 'pending-writer-stop' }], - ['yield', { status: 'pending-writer-stop' }], - ['finish', { status: 'pending-writer-stop' }], - ['adopt', { adoption: { targetId: 'lead', status: 'queued' } }], - ])('stops a direct provider after the current %s is accepted and acknowledged', async (operation, accepted) => { - const workspace = path.join(directory, 'workspace'), - profile = path.join(directory, 'profile'); - fs.mkdirSync(workspace); - fs.mkdirSync(profile); - let latestCompletedItem: unknown; - const checkpointedAfter: unknown[] = []; - const requestGate: NonNullable = () => ({ allowed: true, settle: () => {} }); - requestGate.checkpoint = () => { - checkpointedAfter.push(latestCompletedItem); - return true; - }; - session = await createCodexMathSession({ - ...options, - workspace, - profile, - isolateProcess: true, - readOnlyWorkspace: operation === 'publish_plan', - nativeAgentControl: host, - requestGate, - turnTimeoutMs: 1000, - onItem: (event, item) => { - if (event === 'completed') latestCompletedItem = item.id; - }, - tools: { - definitions: [{ name: 'theoremos_team', description: 'Schedule a handoff', inputSchema: { type: 'object' } }], - call: async (_tool, _args, { callId }) => - callId === 'invalid-team-tool' - ? { ok: false, error: 'Reject the invalid handoff.' } - : { ok: true, ...accepted }, - }, - environment: { ...options.environment, TEAM_HANDOFF_FIXTURE: operation }, - }); - expect(session.usageSource).toBe('native-thread-totals'); - expect(await session.run('Schedule a handoff.', 'task', workspace, () => {})).toBe('checkpoint'); - expect(checkpointedAfter).toEqual(['stale-tool']); - expect(await session.stopForFreeze!()).toMatchObject({ status: 'stopped' }); - const rpc = fs - .readFileSync(path.join(profile, 'calls.jsonl'), 'utf8') - .trim() - .split('\n') - .map(line => JSON.parse(line)); - expect(rpc.find(call => call.id === 'invalid-team-tool')?.result.success).toBe(true); - expect(rpc.findIndex(call => call.id === 'team-tool')).toBeLessThan( - rpc.findIndex(call => call.method === 'turn/interrupt'), - ); - }); - - it('dispatches factory attach before thread startup returns and enables actual native tools explicitly', async () => { - session = await createCodexMathSession({ ...options, nativeAgentControl: host }); - expect(host.request).toHaveBeenCalledWith( - expect.objectContaining({ operation: 'attach', threadId: 'root-id', operationId: 'operation-attach' }), - expect.any(Object), - expect.objectContaining({ signal: expect.any(AbortSignal) }), - ); - expect(session.nativeAgentControl?.info).toEqual(expect.objectContaining({ sessionId: 'root-id' })); - const start = calls().find(call => call.method === 'thread/start').params; - expect(start.config).toMatchObject({ - 'features.multi_agent': true, - 'features.multi_agent_v2': { - enabled: true, - root_agent_usage_hint_text: '', - subagent_usage_hint_text: '', - multi_agent_mode_hint_text: expect.stringContaining('You are the Lead of an explicitly requested flat team.'), - }, - 'features.defer_mailbox_preemption': true, - 'skills.include_instructions': false, - 'agents.enabled': true, - }); - expect(session.nativeConfiguration).toEqual({ - source: 'thread-start-overrides', - overrides: { - includeSkillInstructions: false, - deferMailboxPreemption: true, - rootAgentUsageHintText: '', - subagentUsageHintText: '', - multiAgentModeHintText: start.config['features.multi_agent_v2'].multi_agent_mode_hint_text, - }, - }); - expect(start.dynamicTools).toBeUndefined(); - expect( - await session.nativeAgentControl!.update({ sessionId: 'root-id', threadId: session.threadId, sequence: 4 }), - ).toEqual({ acceptedSequence: 4 }); - expect(await session.run('Work from the fixed source.', 'task', directory, () => {})).toBe('completed'); - expect((await session.stopForFreeze!()).status).toBe('stopped'); - }); - - it('creates an idle child then starts its attributed input only with run observers installed', async () => { - const bootstrap = { - version: 1, - sessionId: 'root-id', - threadId: 'child-id', - source: { subagent: {} }, - hostOverrides: { developerInstructions: 'Parent role.', inheritedOption: 'preserve' }, - }; - const initialInput = { - author: '/root', - input: { kind: 'message', message: { kind: 'plaintext', text: 'Investigate this gap.' }, mode: 'triggerTurn' }, - startOptions: { parentTurnId: 'parent-turn' }, - }; - const definition = { name: 'child_tool', description: 'Child tool', inputSchema: { type: 'object' } }; - session = await createCodexMathSession({ - ...options, - tools: { definitions: [definition], call: vi.fn() }, - nativeAgentControl: { ...host, bootstrap, initialInput }, - }); - expect(calls().some(call => call.method === 'theoremos/agentControl/input')).toBe(false); - const start = calls().find(call => call.method === 'theoremos/agentControl/start').params; - expect(start.bootstrap).toMatchObject({ - ...bootstrap, - hostOverrides: { inheritedOption: 'preserve', developerInstructions: start.thread.developerInstructions }, - }); - expect(start.thread.developerInstructions).toContain(options.instructions); - expect(start.thread.dynamicTools).toEqual([{ type: 'function', ...definition }]); - expect(start.bootstrap.hostOverrides.dynamicTools).toEqual(start.thread.dynamicTools); - expect(start.thread).toMatchObject({ cwd: directory, model: 'fixture-model' }); - const onStarted = vi.fn(); - expect(await session.run('Host proof context.', 'task', directory, onStarted)).toBe('completed'); - expect(onStarted).toHaveBeenCalledWith('native-turn-1'); - expect(session.lastCompletedResponse).toEqual({ turnId: 'native-turn-1', text: 'Research saved.' }); - const input = calls().find(call => call.method === 'theoremos/agentControl/input').params; - expect(input).toMatchObject({ - ...initialInput, - version: 1, - threadId: 'child-id', - contextItems: [{ role: 'user', content: [{ type: 'input_text', text: 'Host proof context.' }] }], - }); - expect(calls().some(call => call.method === 'turn/start')).toBe(false); - expect(await session.run('Continue from saved work.', 'next', directory, () => {})).toBe('completed'); - const next = calls() - .filter(call => call.method === 'theoremos/agentControl/input') - .at(-1).params; - expect(next).toEqual({ - version: 1, - threadId: 'child-id', - author: '/root', - startOptions: {}, - input: { kind: 'userInput', items: [{ type: 'text', text: 'Continue from saved work.', text_elements: [] }] }, - }); - }); - - it.each(['root', 'resumed-root', 'child', 'resumed-child'] as const)( - 'preserves explicit pinned skill dispatch with the global catalog suppressed (%s)', - async mode => { - const isLead = mode === 'root' || mode === 'resumed-root'; - const skillDirectory = path.join(directory, '.agents', 'skills', 'pinned-fixture'); - fs.mkdirSync(skillDirectory, { recursive: true }); - const skillPath = path.join(skillDirectory, 'SKILL.md'); - fs.writeFileSync( - skillPath, - '---\nname: pinned-fixture\ndescription: Fixed mathematical fixture instructions.\n---\nUse the pinned fixture contract.\n', - ); - const bootstrap = { version: 1, sessionId: 'root-id', threadId: 'child-id', source: { subagent: {} } }; - const initialInput = { - author: '/root', - input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Assigned fixture.' } }, - startOptions: {}, - }; - session = await createCodexMathSession({ - ...options, - environment: { ...options.environment, FIXTURE_SKILL_PATH: skillPath }, - skills: [readMathAgentSkill(skillPath)], - ...(mode.startsWith('resumed-') ? { threadId: isLead ? 'root-id' : 'child-id' } : {}), - nativeAgentControl: { ...host, ...(isLead ? {} : { bootstrap, initialInput }) }, - }); - expect(await session.run('Read the fixed proof context.', 'task', directory, () => {})).toBe('completed'); - const starts = ['thread/start', 'thread/resume', 'theoremos/agentControl/start']; - const dispatch = calls().filter(call => call.method === 'skills/list' || starts.includes(call.method)); - const startMethod = !isLead ? 'theoremos/agentControl/start' : mode === 'root' ? 'thread/start' : 'thread/resume'; - expect(dispatch.map(call => call.method)).toEqual(['skills/list', startMethod]); - const started = dispatch[1].params; - const settings = started.thread ?? started.resume ?? started; - expect(settings.config['skills.include_instructions']).toBe(false); - const delegation = settings.config['features.multi_agent_v2'].multi_agent_mode_hint_text; - expect(delegation).toContain( - isLead - ? 'You are the Lead of an explicitly requested flat team.' - : 'You are a member of an explicitly requested flat team.', - ); - if (!isLead) { - expect(delegation).toContain('Do not spawn sub-agents'); - expect(delegation).not.toContain('Proactively delegate'); - } else { - expect(delegation).toContain('Follow the pinned Lead charter'); - expect(delegation).toContain('Only Lead dispatches or interrupts members'); - } - const input = calls().find(call => ['turn/start', 'theoremos/agentControl/input'].includes(call.method)).params; - if (isLead) expect(input.input).toContainEqual({ type: 'skill', name: 'pinned-fixture', path: skillPath }); - else expect(input.contextItems[0].content[0].text).toContain(JSON.stringify(skillPath)); - }, - ); - - it('rejects an incompatible executable before dispatching a thread', async () => { - await expect( - createCodexMathSession({ - ...options, - environment: { ...options.environment, BAD_BACKEND: '1' }, - nativeAgentControl: host, - }), - ).rejects.toThrow('math_native_agent_control_backend_required'); - expect(calls().some(call => call.method === 'thread/start')).toBe(false); - expect(host.request).not.toHaveBeenCalled(); - }); - - it('requires the native child to report its actual restricted permission intersection', async () => { - const bound = vi.fn(); - await expect( - createCodexMathSession({ - ...options, - environment: { ...options.environment, BAD_CHILD_PERMISSIONS: '1' }, - nativeAgentControl: { ...host, bound, bootstrap: { version: 1, sessionId: 'root-id', threadId: 'child-id' } }, - }), - ).rejects.toThrow('math_codex_sandbox_profile_mismatch'); - expect(bound).not.toHaveBeenCalled(); - expect(calls().some(call => call.method === 'theoremos/agentControl/input')).toBe(false); - }); - - it('rejects a child bound to a different parent session before dispatching an input', async () => { - await expect( - createCodexMathSession({ - ...options, - nativeAgentControl: { ...host, bootstrap: { version: 1, sessionId: 'other-parent', threadId: 'child-id' } }, - }), - ).rejects.toThrow('math_native_agent_control_child_binding_mismatch'); - expect(calls().some(call => call.method === 'theoremos/agentControl/input')).toBe(false); - }); - - it('registers the captured child identity before cold resume without replaying fork history', async () => { - const bootstrap = { version: 1, sessionId: 'root-id', threadId: 'saved-child', initialHistory: 'parent-fork' }; - session = await createCodexMathSession({ - ...options, - threadId: 'saved-child', - tools: { definitions: [], call: vi.fn() }, - environment: { ...options.environment, LONG_RESUME_HISTORY: '1' }, - nativeAgentControl: { - ...host, - bootstrap, - initialInput: { - author: '/root', - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Continue the saved child.' }, - }, - startOptions: {}, - }, - }, - }); - const start = calls().find(call => call.method === 'theoremos/agentControl/start').params; - expect(start.bootstrap).toMatchObject(bootstrap); - expect(start.resume).toMatchObject({ threadId: 'saved-child', excludeTurns: true }); - expect(start.resume.dynamicTools).toBeUndefined(); - expect(start.bootstrap.hostOverrides.dynamicTools).toEqual([]); - expect(start.thread).toBeUndefined(); - expect(calls().some(call => call.method === 'thread/resume')).toBe(false); - expect(await session.run('Current source and feedback.', 'task', directory, () => {})).toBe('completed'); - }); - - it('resumes the Lead when the stored history exceeds the stdio frame limit', async () => { - session = await createCodexMathSession({ - ...options, - threadId: 'root-id', - nativeAgentControl: host, - environment: { ...options.environment, LONG_RESUME_HISTORY: '1' }, - }); - expect(session.threadId).toBe('root-id'); - expect(await session.run('Continue the saved proof.', 'task', directory, () => {})).toBe('completed'); - }); - - it('keeps resume usage replay for a direct provider with a budget gate', async () => { - session = await createCodexMathSession({ - ...options, - threadId: 'root-id', - nativeAgentControl: host, - requestGate: () => ({ allowed: true, settle: () => {} }), - }); - const resume = calls().find(call => call.method === 'thread/resume').params; - expect(resume.excludeTurns).toBeUndefined(); - expect(session.usageSource).toBe('native-thread-totals'); - }); - - it('resumes a budget-gated Lead from metadata once its replayed history exceeds the stdio frame limit', async () => { - session = await createCodexMathSession({ - ...options, - threadId: 'root-id', - nativeAgentControl: host, - requestGate: () => ({ allowed: true, settle: () => {} }), - environment: { ...options.environment, LONG_RESUME_HISTORY: '1' }, - }); - const resumes = calls() - .filter(call => call.method === 'thread/resume') - .map(call => call.params.excludeTurns); - expect(resumes).toEqual([undefined, true]); - expect(session.threadId).toBe('root-id'); - expect(session.usageSource).toBe('native-thread-totals'); - expect(await session.run('Continue the saved proof.', 'task', directory, () => {})).toBe('completed'); - }); - - it('keeps native compaction open until the completed maintenance turn releases the writer', async () => { - const release = deferred(), - reachedRelease = deferred(); - session = await createCodexMathSession({ - ...options, - nativeAgentControl: { - request: async request => { - if (request.operation === 'releaseTurn' && request.payload.turnId === 'compact-turn') { - reachedRelease.resolve(); - await release.promise; - } - return { result: { admitted: request.operation === 'admitTurn' } }; - }, - }, - }); - let settled = false; - const compact = session.compact!().then(() => { - settled = true; - }); - try { - await reachedRelease.promise; - expect(settled).toBe(false); - await expect(session.run('Too early.', 'task', directory, () => {})).rejects.toThrow( - 'math_codex_turn_already_running', - ); - } finally { - release.resolve(); - await compact; - } - expect(await session.run('Use the compacted context.', 'task', directory, () => {})).toBe('completed'); - }); - - it('does not activate a backend through inherited process environment', async () => { - session = await createCodexMathSession({ - ...options, - environment: { ...options.environment, THEOREMOS_HOST_AGENT_CONTROL: '1' }, - }); - expect(session.nativeAgentControl).toBeUndefined(); - expect(calls().some(call => call.method === 'theoremos/agentControl/capabilities')).toBe(false); - const start = calls().find(call => call.method === 'thread/start').params; - expect(start.config).not.toHaveProperty('features.multi_agent_v2'); - expect(session.nativeConfiguration?.overrides).not.toHaveProperty('multiAgentModeHintText'); - expect(JSON.parse(fs.readFileSync(path.join(directory, 'backend-env.json'), 'utf8'))).toEqual({}); - }); - - it('withholds freeze confirmation until host callbacks settle, and cancels them on writer shutdown', async () => { - const cancelled = vi.fn(); - host = { - request: async (request, _connection, { signal }) => { - if (request.operation === 'recordUsage') - await new Promise(resolve => - signal.addEventListener( - 'abort', - () => { - cancelled(); - resolve(); - }, - { once: true }, - ), - ); - return { result: { sessionId: request.sessionId } }; - }, - }; - session = await createCodexMathSession({ - ...options, - nativeAgentControl: host, - environment: { ...options.environment, HOLD_HOST_CALLBACK: '1' }, - }); - expect(await session.run('Finish with a pending lifecycle report.', 'task', directory, () => {})).toBe('completed'); - expect(await session.stopForFreeze!()).toEqual({ status: 'unconfirmed', reason: 'turn-not-settled' }); - await session.close(); - expect(cancelled).toHaveBeenCalledOnce(); - expect((await session.stopForFreeze!()).status).toBe('stopped'); - }); - - it('lets the proof writer freeze once shutdown cancels a host callback left by the turn', async () => { - host = { - request: async (request, _connection, { signal }) => { - if (request.operation === 'recordUsage') - await new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true })); - return { result: { sessionId: request.sessionId } }; - }, - }; - session = await createCodexMathSession({ - ...options, - nativeAgentControl: host, - environment: { ...options.environment, HOLD_HOST_CALLBACK: '1' }, - }); - expect(await session.run('Finish with a pending lifecycle report.', 'task', directory, () => {})).toBe('completed'); - const record: { writerStopUnconfirmed?: { at: number; reason: string } } = {}; - const events: string[] = [], - current = session; - await stopProofWriter({ - session: current, - record, - workerId: 'lead', - close: () => current.close(), - save: () => {}, - deferred: reason => events.push('deferred:' + reason), - confirmed: reason => events.push('confirmed:' + reason), - }); - expect(events).toEqual(['deferred:turn-not-settled', 'confirmed:turn-not-settled']); - expect(record.writerStopUnconfirmed).toBeUndefined(); - }); - - it('confirms a closed writer while cancelled compaction is still unwinding', async () => { - const reachedRelease = deferred(), - shutdownStarted = deferred(), - release = deferred(); - session = await createCodexMathSession({ - ...options, - nativeAgentControl: { - request: async (request, _connection, { signal }) => { - if (request.operation === 'releaseTurn' && request.payload.turnId === 'compact-turn') { - signal.addEventListener('abort', () => shutdownStarted.resolve(), { once: true }); - reachedRelease.resolve(); - await release.promise; - } - return { result: { admitted: request.operation === 'admitTurn' } }; - }, - }, - }); - const current = session, - compact = current.compact!().catch((error: unknown) => error); - await reachedRelease.promise; - const record: { writerStopUnconfirmed?: { at: number; reason: string } } = {}; - const confirmed = vi.fn(); - const freezing = stopProofWriter({ - session: current, - record, - workerId: 'lead', - close: () => current.close(), - save: () => {}, - deferred: () => {}, - confirmed, - }); - try { - await shutdownStarted.promise; - expect(record.writerStopUnconfirmed?.reason).toBe('turn-not-settled'); - expect(confirmed).not.toHaveBeenCalled(); - } finally { - release.resolve(); - await freezing; - } - expect(confirmed).toHaveBeenCalledWith('turn-not-settled'); - expect(record.writerStopUnconfirmed).toBeUndefined(); - expect(await compact).toBeInstanceOf(Error); - }); - - it('waits for the native terminal handoff and guard release before reporting a completed writer', async () => { - let release!: () => void, entered!: () => void; - const blocked = new Promise(resolve => { - release = resolve; - }); - const releasing = new Promise(resolve => { - entered = resolve; - }); - const request = host.request; - host = { - request: async (...args) => { - if (args[0].operation === 'releaseTurn') { - entered(); - await blocked; - } - return request(...args); - }, - }; - session = await createCodexMathSession({ ...options, nativeAgentControl: host }); - let completed = false; - const run = session - .run('Save the final research result.', 'task', directory, () => {}) - .then(result => { - completed = true; - return result; - }); - await releasing; - await new Promise(resolve => setImmediate(resolve)); - try { - expect(completed).toBe(false); - } finally { - release(); - } - expect(await run).toBe('completed'); - expect((await session.stopForFreeze!()).status).toBe('stopped'); - }); - - it('projects only the selected model capability without changing provider catalog bytes', () => { - const file = path.join(directory, 'models.json'); - const source = JSON.stringify({ - models: [ - { slug: 'fixture-model', multi_agent_version: null, custom: 'retained' }, - { slug: 'other', multi_agent_version: null }, - ], - }); - fs.writeFileSync(file, source); - const projected = nativeAgentControlModelCatalog(file, 'fixture-model', path.join(directory, 'runtime')); - expect(fs.readFileSync(file, 'utf8')).toBe(source); - expect(JSON.parse(fs.readFileSync(projected, 'utf8'))).toEqual({ - models: [ - { slug: 'fixture-model', multi_agent_version: 'v2', custom: 'retained' }, - { slug: 'other', multi_agent_version: null }, - ], - }); - expect(() => nativeAgentControlModelCatalog(file, 'missing', path.join(directory, 'runtime'))).toThrow( - 'math_native_agent_control_model_missing', - ); - }); -}); diff --git a/tests/codexSessionCheckpoint.test.ts b/tests/codexSessionCheckpoint.test.ts index 8885526e..96389e33 100644 --- a/tests/codexSessionCheckpoint.test.ts +++ b/tests/codexSessionCheckpoint.test.ts @@ -15,6 +15,12 @@ const record = value => fs.appendFileSync(path.join(root, 'calls.jsonl'), JSON.s let turn, startReply, interruptError, lastControl; const complete = status => send({ method: 'turn/completed', params: { threadId: 'checkpoint-thread', turn: { ...turn, status, ...(status === 'completed' ? { items: [{ id: 'final-' + turn.id, type: 'agentMessage', text: 'Proof draft saved.' }] } : {}) } } }); +const publishPlan = id => send({ id, method: 'item/tool/call', params: { threadId: 'checkpoint-thread', turnId: turn.id, + tool: 'theoremos_team', callId: id, arguments: { operation: 'publish_plan' } } }); +const planAcknowledged = (call, turnId = turn.id) => send({ method: 'item/completed', params: { + threadId: 'checkpoint-thread', turnId, item: { id: call.id, type: 'dynamicToolCall', tool: 'theoremos_team', + arguments: { operation: 'publish_plan' }, success: call.result.success, contentItems: call.result.contentItems }, +} }); setInterval(() => { if (!fs.existsSync(path.join(root, 'control'))) return; const control = fs.readFileSync(path.join(root, 'control'), 'utf8'); @@ -41,12 +47,24 @@ setInterval(() => { readline.createInterface({ input: process.stdin }).on('line', line => { const call = JSON.parse(line); record(call); const reply = result => send({ id: call.id, result }); + if (call.id === 'invalid-plan') { + planAcknowledged(call); + return publishPlan('pending-plan'); + } + if (call.id === 'pending-plan') { + planAcknowledged({ ...call, id: 'stale-plan' }, 'previous-turn'); + return planAcknowledged(call); + } if (call.method === 'initialize') return reply({}); if (call.method === 'thread/start') return reply({ thread: { id: 'checkpoint-thread' }, model: call.params.model, reasoningEffort: call.params.config.model_reasoning_effort, approvalPolicy: 'never', activePermissionProfile: { id: 'math-worker' } }); if (call.method === 'turn/start') { turn = { id: 'remote-' + call.params.clientUserMessageId, status: 'inProgress' }; if (process.env.HOLD_START === '1') { startReply = () => reply({ turn }); return; } + if (call.params.clientUserMessageId === 'publish-plan') { + reply({ turn }); + return publishPlan('invalid-plan'); + } return reply({ turn }); } if (call.method === 'turn/steer') { @@ -107,6 +125,45 @@ describe('Codex checkpoint turn settlement', () => { fs.rmSync(root, { recursive: true, force: true }); }); + it('stops a direct planning turn after Codex acknowledges the current plan pending approval', async () => { + const workspace = path.join(root, 'workspace'); + const profile = path.join(root, 'profile'); + const home = path.join(root, 'home'); + for (const directory of [workspace, profile, home]) fs.mkdirSync(directory); + const account = os.userInfo(); + vi.spyOn(os, 'homedir').mockReturnValue(home); + vi.spyOn(os, 'userInfo').mockReturnValue({ ...account, homedir: home }); + let lastCompletedItem: unknown; + const checkpointedAfter: unknown[] = []; + const requestGate: NonNullable = () => ({ allowed: true, settle: () => {} }); + requestGate.checkpoint = () => { + checkpointedAfter.push(lastCompletedItem); + return true; + }; + session = await createCodexMathSession({ + ...options, + workspace, + profile, + environment: { HOME: home, PATH: '/usr/bin:/bin' }, + isolateProcess: true, + readOnlyWorkspace: true, + requestGate, + onItem: (event, item) => { + if (event === 'completed') lastCompletedItem = item.id; + }, + tools: { + definitions: [ + { name: 'theoremos_team', description: 'Publish a plan for approval', inputSchema: { type: 'object' } }, + ], + call: async (_tool, _args, { callId }) => + callId === 'invalid-plan' ? { ok: false, error: 'Invalid plan.' } : { ok: true, status: 'pending' }, + }, + }); + expect(await session.run('Publish the plan.', 'publish-plan', workspace, () => {})).toBe('checkpoint'); + expect(checkpointedAfter).toEqual(['stale-plan']); + expect(await session.stopForFreeze!()).toMatchObject({ status: 'stopped' }); + }); + it('delivers an explicit stop requested before turn/start acknowledgement to the confirmed remote turn', async () => { session = await createCodexMathSession({ ...options, environment: { ...options.environment, HOLD_START: '1' } }); const started = vi.fn(); diff --git a/tests/codexSessionNativeMailbox.test.ts b/tests/codexSessionNativeMailbox.test.ts deleted file mode 100644 index 62457537..00000000 --- a/tests/codexSessionNativeMailbox.test.ts +++ /dev/null @@ -1,315 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { createServer, type Server, type ServerResponse } from 'node:http'; -import type { AddressInfo } from 'node:net'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { prepareWebProviderProfile, webSolverModules } from '../apps/web/worker'; -import type { WorkerInput } from '../apps/web/shared'; -import { createCodexMathSession } from '../src/runtime/codexSession'; -import type { MathAgentSession } from '../src/runtime/agentSession'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import { SUB2API_PROVIDER, prepareSub2apiProfile } from '../src/runtime/sub2api'; -import type { ModelRequestReceipt } from '../src/runtime/modelRequest'; -import { deferred } from './helpers/async'; - -type Json = Record; -const executable = process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? path.resolve('out/codex-backend/codex'); -const nativeAvailable = - spawnSync(executable, ['--version'], { env: { PATH: process.env.PATH }, timeout: 5000, stdio: 'ignore' }).status === - 0; -const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; - -function event(response: ServerResponse, value: Json) { - response.write('event: ' + value.type + '\ndata: ' + JSON.stringify(value) + '\n\n'); -} - -describe.skipIf(!nativeAvailable)('native AgentControl mailbox through the production Responses relay', () => { - let directory: string | undefined, server: Server | undefined, session: MathAgentSession | undefined; - const activeResponses = new Set(); - afterEach(async () => { - await session?.close(); - session = undefined; - for (const response of activeResponses) response.destroy(); - activeResponses.clear(); - if (server) await new Promise(resolve => server!.close(() => resolve())); - server = undefined; - vi.unstubAllGlobals(); - if (directory) fs.rmSync(directory, { recursive: true, force: true }); - directory = undefined; - }); - - it.each(['CLI', 'Web'])( - 'retains a tool and final usage after mail in a %s research session', - async client => { - fs.mkdirSync(temporaryRoot, { recursive: true }); - directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'native-mailbox-relay-'))); - const workspace = path.join(directory, 'work'), - profile = path.join(directory, 'profile'); - fs.mkdirSync(workspace); - const apiKey = 'synthetic-fixture-key'; - const webRequest: WorkerInput = { - id: 'fixture', - provider: { id: 'sub2api', name: 'Fixture gateway', baseUrl: 'http://host.docker.internal:8080/v1' }, - input: { - apiKey, - providerId: 'sub2api', - model: 'deepseek-flash', - effort: 'high', - task: 'Offline fixture.', - source: '', - workers: 1, - coordination: 'independent', - maxTurns: 0, - maxRunSeconds: 0, - researchMode: 'skill', - nativeTeamCapacity: 2, - }, - }; - const web = client === 'Web'; - if (web) prepareWebProviderProfile(profile, webRequest); - else prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); - const pinnedDirectory = path.join(workspace, '.agents', 'skills', 'pinned-mailbox-fixture'); - fs.mkdirSync(pinnedDirectory, { recursive: true }); - const pinnedFile = path.join(pinnedDirectory, 'SKILL.md'); - const pinnedMarker = 'PINNED_MATH_SKILL_BODY_74fd'; - fs.writeFileSync( - pinnedFile, - '---\nname: pinned-mailbox-fixture\ndescription: Disposable mathematics transport fixture.\n---\n' + - pinnedMarker + - '\n', - ); - const unrelated = path.join(profile, 'runtime', 'skills', 'unrelated-catalog-fixture'); - fs.mkdirSync(unrelated, { recursive: true }); - fs.writeFileSync( - path.join(unrelated, 'SKILL.md'), - '---\nname: unrelated-catalog-fixture\ndescription: Unrelated disposable catalog entry.\n---\nUNRELATED_BODY\n', - ); - - const requests: Json[] = [], - receipts: ModelRequestReceipt[] = [], - premature: number[] = []; - const firstResponse = deferred<{ reasoningDone(): void; finish(): void }>(); - const observedItems: { phase: string; type: unknown; id: unknown }[] = []; - const errors: unknown[] = []; - server = createServer(async (request, response) => { - activeResponses.add(response); - response.once('close', () => activeResponses.delete(response)); - try { - expect(request.headers.authorization).toBe(`Bearer ${apiKey}`); - const bytes: Buffer[] = []; - for await (const chunk of request) bytes.push(Buffer.from(chunk)); - const body = JSON.parse(Buffer.concat(bytes).toString('utf8')); - requests.push(body); - const index = requests.length; - response.once('close', () => { - if (!response.writableEnded) premature.push(index); - }); - response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); - const base = { - id: 'resp_mailbox_' + index, - object: 'response', - created_at: 1, - model: 'deepseek-flash', - status: 'in_progress', - output: [], - }; - event(response, { type: 'response.created', response: base }); - const finish = (items: Json[]) => { - for (const [output_index, item] of items.entries()) { - if (item.type === 'reasoning') continue; - event(response, { - type: 'response.output_item.added', - output_index, - item: { - ...item, - status: 'in_progress', - ...(item.type === 'function_call' ? { arguments: '' } : { content: [] }), - }, - }); - if (item.type === 'function_call') { - event(response, { - type: 'response.function_call_arguments.delta', - item_id: item.id, - output_index, - delta: item.arguments, - }); - event(response, { - type: 'response.function_call_arguments.done', - item_id: item.id, - output_index, - arguments: item.arguments, - }); - } else { - event(response, { - type: 'response.output_text.delta', - item_id: item.id, - output_index, - content_index: 0, - delta: item.content[0].text, - }); - event(response, { - type: 'response.output_text.done', - item_id: item.id, - output_index, - content_index: 0, - text: item.content[0].text, - }); - } - event(response, { type: 'response.output_item.done', output_index, item }); - } - event(response, { - type: 'response.completed', - response: { - ...base, - status: 'completed', - output: items, - usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 }, - }, - }); - response.end(); - }; - if (index === 1) { - const reasoning = { - type: 'reasoning', - id: 'mailbox_reasoning', - summary: [{ type: 'summary_text', text: 'Fixture reasoning.' }], - }; - event(response, { - type: 'response.output_item.added', - output_index: 0, - item: { ...reasoning, summary: [] }, - }); - firstResponse.resolve({ - reasoningDone: () => - event(response, { type: 'response.output_item.done', output_index: 0, item: reasoning }), - finish: () => - finish([ - reasoning, - { - type: 'function_call', - id: 'write_once', - call_id: 'write_once', - name: 'exec_command', - arguments: JSON.stringify({ cmd: 'printf x >> executed-once', login: false, workdir: workspace }), - status: 'completed', - }, - ]), - }); - } else - finish([ - { - type: 'message', - id: 'mailbox_done', - role: 'assistant', - status: 'completed', - content: [{ type: 'output_text', text: 'Mailbox fixture complete.', annotations: [] }], - }, - ]); - } catch (error) { - errors.push(error); - response.destroy(); - } - }); - await new Promise(resolve => server!.listen(0, '127.0.0.1', resolve)); - const originalFetch = globalThis.fetch; - const upstream = (web ? webRequest.provider.baseUrl : SUB2API_PROVIDER.baseUrl) + '/responses'; - // The production relay still parses, admits, streams and accounts for the - // request. Only its fixed upstream endpoint is redirected to this fixture. - vi.stubGlobal('fetch', ((input: string | URL | Request, init?: RequestInit) => { - if (String(input) !== upstream) throw new Error('unexpected_fixture_upstream:' + String(input)); - return originalFetch(`http://127.0.0.1:${(server!.address() as AddressInfo).port}/v1/responses`, init); - }) as typeof fetch); - - const open = web ? webSolverModules(webRequest).M1.open : createCodexMathSession; - session = await open({ - executable, - profile, - workspace, - model: 'deepseek-flash', - effort: 'high', - instructions: 'Execute the disposable transport fixture. Follow the pinned skill.', - skills: [readMathAgentSkill(pinnedFile)], - environment: { - PATH: process.env.PATH, - ...(!web && { SUB2API_WESTLAKE_API_KEY: apiKey }), - NO_PROXY: '127.0.0.1,localhost', - }, - requestGate: () => ({ allowed: true, settle: receipt => receipts.push(receipt) }), - onUsage: () => {}, - onItem: (phase, item) => { - observedItems.push({ phase, type: item.type, id: item.id }); - }, - nativeAgentControl: { - request: async request => ({ - result: - request.operation === 'attach' - ? { sessionId: request.sessionId } - : request.operation === 'admitTurn' - ? { admitted: true } - : {}, - }), - }, - }); - expect(session.usageSource).toBe('upstream-requests'); - const running = session.run('Exercise the mailbox fixture.', 'fixture-turn', workspace, () => {}); - const response = await Promise.race([ - firstResponse.promise, - running.then(status => { - throw new Error( - `fixture ended before its first upstream request (${status}): ${session!.lastError ?? 'no error'}`, - ); - }), - ]); - const info = session.nativeAgentControl!.info!; - await session.nativeAgentControl!.update({ - sessionId: info.sessionId, - threadId: session.threadId, - sequence: 1, - mailbox: [ - { - id: 'fixture-mail', - author: '/root/peer', - recipient: '/root', - message: { kind: 'plaintext', text: 'ORDINARY_MAILBOX_UPDATE_63b8' }, - }, - ], - }); - response.reasoningDone(); - await expect - .poll(() => observedItems, { timeout: 5000 }) - .toEqual(expect.arrayContaining([expect.objectContaining({ phase: 'started', type: 'reasoning' })])); - // Keep the tool/usage frames separate from the reasoning boundary so native - // mailbox preemption has an opportunity to cancel this exact HTTP response. - await new Promise(resolve => setTimeout(resolve, 100)); - expect(premature).toEqual([]); - response.finish(); - expect(await running).toBe('completed'); - expect(errors).toEqual([]); - expect(premature).toEqual([]); - expect(requests).toHaveLength(2); - expect(fs.readFileSync(path.join(workspace, 'executed-once'), 'utf8')).toBe('x'); - expect(JSON.stringify(requests[1].input)).toContain('ORDINARY_MAILBOX_UPDATE_63b8'); - expect( - requests[1].input.some((item: Json) => item.type === 'function_call_output' && item.call_id === 'write_once'), - ).toBe(true); - expect(receipts).toHaveLength(2); - expect(receipts.every(receipt => receipt.complete && receipt.usage?.totalTokens === 12)).toBe(true); - expect(JSON.stringify(requests[0].input)).toContain(pinnedMarker); - expect(JSON.stringify(requests[0].input)).not.toContain('unrelated-catalog-fixture'); - - if (web) { - const threadId = session.threadId; - await session.compact!(); - expect(session.threadId).toBe(threadId); - expect(requests).toHaveLength(3); - expect(receipts).toHaveLength(3); - expect(await session.run('Continue after compaction.', 'after-compaction', workspace, () => {})).toBe( - 'completed', - ); - expect(requests).toHaveLength(4); - } - }, - 45_000, - ); -}); diff --git a/tests/codexSessionNotifications.test.ts b/tests/codexSessionNotifications.test.ts index e34927df..53bf44d3 100644 --- a/tests/codexSessionNotifications.test.ts +++ b/tests/codexSessionNotifications.test.ts @@ -9,6 +9,7 @@ import type { ModelRequestGate, ModelRequestReceipt } from '../src/runtime/model import { prepareSub2apiProfile, SUB2API_PROVIDER } from '../src/runtime/sub2api'; import { prepareWestlakeProfile, WESTLAKE_PROVIDER } from '../src/runtime/westlake'; import { nativeFileWatchFixture } from './helpers/nativeFileWatchFixture'; +import { deferred } from './helpers/async'; // The child may call only the disposable loopback transport. All upstream fetches are mocked below. // Like Codex, this fixture cancels an unfinished request when turn/steer arrives. @@ -119,7 +120,7 @@ async function fixture( reviewIncomplete?: (value: unknown, turnId: string) => string | undefined; submitTool?: boolean; holdSteerAbort?: boolean; - beforeRequest?: (requestNumber: number) => void; + beforeRequest?: (requestNumber: number) => void | Promise; checkpoint?: () => boolean; } = {}, ) { @@ -206,7 +207,7 @@ async function fixture( }; }; requestGate.beforeRequest = async () => { - extra.beforeRequest?.(++requestNumber); + await extra.beforeRequest?.(++requestNumber); }; requestGate.checkpoint = extra.checkpoint; session = await createCodexMathSession({ @@ -387,6 +388,44 @@ describe('soft notifications at real provider request boundaries', () => { expect(checkpoint).toHaveBeenCalledTimes(checked); }); + it('does not use a previous turn request to deliver a reminder in the next turn', async () => { + const priorRequest = deferred(); + const currentRequest = deferred(); + const beforeRequest = vi.fn((number: number) => { + if (number === 2) return priorRequest.promise; + if (number === 3) return currentRequest.promise; + }); + const { running } = await fixture('sub2api', { beforeRequest }); + streams[0].finish(); + await expect.poll(() => trace().filter(item => item.event === 'request-returned').length).toBe(1); + try { + control('request:prior-turn'); + await expect.poll(() => beforeRequest.mock.calls.length).toBe(2); + control('complete:prior-turn'); + expect(await running).toBe('completed'); + + const continued = session!.run('Continue.', 'next-turn', directory, () => {}); + void continued.catch(() => {}); + await expect.poll(() => beforeRequest.mock.calls.length).toBe(3); + const reminder = session!.notify!('Reminder for this turn.', { waitForRequest: true }); + void reminder.catch(() => {}); + + priorRequest.resolve(); + await expect.poll(() => trace().filter(item => item.event === 'request-returned').length).toBe(2); + expect(trace().filter(item => item.event === 'steer')).toEqual([]); + + currentRequest.resolve(); + await reminder; + expect(trace().filter(item => item.event === 'steer')).toMatchObject([{ expectedTurnId: 'next-turn' }]); + control('complete:next-turn'); + expect(await continued).toBe('completed'); + expect(receipts).toHaveLength(1); + } finally { + priorRequest.resolve(); + currentRequest.resolve(); + } + }); + it.each(['sub2api', 'westlake'] as const)( 'keeps the paid %s response and its tools alive before checkpointing the next admission, then continues the same thread', async provider => { diff --git a/tests/comparisonSkillBaseline.test.ts b/tests/comparisonSkillBaseline.test.ts index 3ef5f5e8..523b0db1 100644 --- a/tests/comparisonSkillBaseline.test.ts +++ b/tests/comparisonSkillBaseline.test.ts @@ -4,8 +4,7 @@ import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { comparisonReport } from '../scripts/mathematics/compareMathRuns'; import * as inspection from '../src/solver/inspection'; -import * as deepseek from '../src/runtime/deepseek'; -import * as sub2api from '../src/runtime/sub2api'; +import { prepareSub2apiProfile } from '../src/runtime/sub2api'; import { mathDigest } from '../src/math/mathRuntimeIo'; import type { SolverRunState } from '../src/solver/archive'; import { comparisonPlan, historicalSkillBaseline } from './helpers/comparisonPlan'; @@ -22,16 +21,13 @@ function archivedSkillPlan(loading: 'native' | 'file' = 'native', common = false roots.push(directory); const plan = historicalSkillBaseline(comparisonPlan(directory, 2), loading); if (common) { + const profile = path.join(fs.realpathSync(directory), 'profile'); + const digest = prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); Object.assign(plan, { commonResearchSkill: plan.skillBaseline, - commonProviderProfile: { profile: '/frozen-existing-profile', digest: mathDigest('same-provider') }, + commonProviderProfile: { profile, digest }, }); for (const job of plan.jobs) Object.assign(job, { commonResearchSkill: plan.skillBaseline }); - vi.spyOn(deepseek, 'selectedDeepSeekProfile').mockReturnValue(undefined); - vi.spyOn(sub2api, 'selectedSub2apiProfile').mockReturnValue({ - profile: '/frozen-existing-profile', - digest: mathDigest('same-provider'), - }); } fs.writeFileSync(path.join(directory, 'comparison.json'), JSON.stringify(plan)); return { directory, plan }; diff --git a/tests/declarationArtifacts.test.ts b/tests/declarationArtifacts.test.ts index 70921844..5bce177d 100644 --- a/tests/declarationArtifacts.test.ts +++ b/tests/declarationArtifacts.test.ts @@ -7,7 +7,6 @@ import { bootstrapLeanTask } from '../src/math/leanTask'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { MAX_LEAN_EXPECTED_TYPE_BYTES } from '../src/math/leanSyntax'; import type { MathematicsVerifierBatchRequest } from '../src/math/verifier'; -import { checkAgentTeamProofDelivery, integrateAgentTeamProofDelivery } from '../src/solver/agentTeamProof'; import { writeSolverRunState } from '../src/solver/archive'; import { checkDeclarationArtifacts, @@ -20,12 +19,11 @@ import { writeDeclarationArtifacts, type DeclarationArtifact, } from '../src/solver/declarationArtifacts'; -import { landVerifiedHelpers } from '../src/solver/incrementalHelpers'; import { buildTheoremKnowledge, getKnowledgeConsumers } from '../src/solver/theoremKnowledge'; import { createKnowledgeRelationIndex } from '../src/solver/theoremKnowledgeRelations'; import { importKnowledgeRuns, importTeamKnowledgeDeliveries } from './helpers/nativeKnowledgeImport'; import { knowledgeTypeExpression } from '../src/solver/theoremKnowledgeSearch'; -import { commitSolverSources, git, readSolverProblem, withSolverWorktree } from '../src/solver/problem'; +import { commitSolverSources, git, readSolverProblem } from '../src/solver/problem'; import { inspectStoredRun } from '../src/solver/storedRunInspection'; import { solverState } from './helpers/solver'; import { temporaryDirectory } from './helpers/files'; @@ -535,35 +533,36 @@ describe('independent declaration checks with the real verifier and Lean', () => async function archiveStandaloneHelper(f: Awaited>, type: string) { const { file, name } = f.declaration; - const { worktree, env, signal } = f.options, - seedCommit = f.state.problem.baseCommit; - const landed = await landVerifiedHelpers({ - state: f.state, - worktree, - sourceWorktree: worktree, - sourceCommit: f.commit, - seedCommit, - expectedCommit: seedCommit, - declarations: [{ file, name, type }], - env, - signal, - }); + const { worktree } = f.options; + const seedCommit = f.state.problem.baseCommit; + const declarations = [{ file, name, type }]; const runtime = path.join(f.directory, 'runtime'), evidenceDirectory = path.join(runtime, 'agent-team', 'proofs'); - const delivery = await withSolverWorktree(worktree, landed.commit, checkout => - checkAgentTeamProofDelivery({ - state: f.state, - worktree: checkout, - agentId: 'producer', - seedCommit, - env, - signal, - declarations: landed.declarations, - inferredHelperTypes: ['Submission.lean\0Artifact.reusable'], - evidenceDirectory, - assertWriterStopped: () => {}, - }), - ); + const artifacts = await checkDeclarationArtifacts({ + ...f.options, + declarations, + }); + const record = { + schema: 'theorem-os.agent-team-proof-delivery.v1', + runId: f.state.runId, + environmentDigest: f.state.environmentDigest, + problemReceiptDigest: f.state.problem.receiptDigest, + agentId: 'producer', + sourceWorktree: worktree, + commit: f.commit, + seedCommit, + sourceDigest: artifacts[0]!.proof.sourceDigest, + declarations, + artifacts, + changes: [], + imports: [], + }; + const delivery = { ...record, id: mathDigest(canonicalMathJson(record)) }; + const deliveryDirectory = path.join(evidenceDirectory, 'deliveries'); + const deliveryPath = path.join(deliveryDirectory, delivery.id + '.json'); + fs.mkdirSync(deliveryDirectory, { recursive: true }); + git(worktree, ['clone', '--quiet', '--bare', worktree, path.join(evidenceDirectory, 'sources.git')]); + fs.writeFileSync(deliveryPath, canonicalMathJson(delivery)); f.state.agentTeam = { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', @@ -577,7 +576,7 @@ describe('independent declaration checks with the real verifier and Lean', () => taskId: 'helper', agentId: 'producer', kind: 'helpers', - path: path.join(evidenceDirectory, 'deliveries', delivery.id + '.json'), + path: deliveryPath, }, ], }; @@ -618,46 +617,20 @@ describe('independent declaration checks with the real verifier and Lean', () => ).resolves.toHaveLength(1); }, 60_000); - it('checks and adopts root-qualified declaration names while preserving their receipt identity', async () => { + it('checks root-qualified declaration names while preserving their receipt identity', async () => { const f = await realFixture('theorem reusable (n : Nat) : n = n := by rfl\n'); fs.writeFileSync(f.file, f.source.replace('by sorry', 'by trivial')); - const { state, worktree, env, signal } = f.options, - seedCommit = state.problem.baseCommit; + const { state, worktree } = f.options; const commit = commitSolverSources(state.problem, worktree); const declarations = [ { file: 'Submission.lean', name: '_root_.Artifact.original', type: 'True' }, { file: 'Submission.lean', name: '_root_.Artifact.reusable', type: '_root_.Artifact.reusable (n : Nat) : n = n' }, ]; - const common = { - state, - env, - signal, - evidenceDirectory: path.join(f.directory, 'proofs'), - assertWriterStopped: () => {}, - }; - const delivery = await withSolverWorktree(worktree, commit, checkout => - checkAgentTeamProofDelivery({ - ...common, - worktree: checkout, - agentId: 'producer', - seedCommit, - declarations, - }), - ); - const adoption = await withSolverWorktree(worktree, seedCommit, checkout => - integrateAgentTeamProofDelivery({ - ...common, - worktree: checkout, - expectedCommit: seedCommit, - delivery, - }), + const artifacts = await checkDeclarationArtifacts({ ...f.options, commit, declarations }); + expect(artifacts.map(artifact => artifact.proof.verification.results[0])).toEqual( + declarations.map(({ name }) => expect.objectContaining({ theoremName: name, status: 'kernel_verified' })), ); - for (const artifacts of [delivery.artifacts, adoption.artifacts]) { - expect(artifacts.map(artifact => artifact.proof.verification.results[0])).toEqual( - declarations.map(({ name }) => expect.objectContaining({ theoremName: name, status: 'kernel_verified' })), - ); - expect(artifacts.map(artifact => artifact.references?.root.name)).toEqual(declarations.map(({ name }) => name)); - } + expect(artifacts.map(artifact => artifact.references?.root.name)).toEqual(declarations.map(({ name }) => name)); }, 60_000); it('joins archived proof references to a root-qualified entry in both directions', async () => { diff --git a/tests/evaluatorExecution.test.ts b/tests/evaluatorExecution.test.ts index eff7a2db..bc23f8d2 100644 --- a/tests/evaluatorExecution.test.ts +++ b/tests/evaluatorExecution.test.ts @@ -159,7 +159,7 @@ describe('external evaluator execution failures', () => { receipt, {}, new AbortController().signal, - { timeoutMs: Infinity, teamContributions: true }, + { timeoutMs: Infinity }, ); expect(value).toEqual({ status: verdict, @@ -167,7 +167,6 @@ describe('external evaluator execution failures', () => { method: 'official-comparator', official: true, comparison, - verification: receipt, }); }); diff --git a/tests/evaluatorRun.test.ts b/tests/evaluatorRun.test.ts index 22147682..e85a41b8 100644 --- a/tests/evaluatorRun.test.ts +++ b/tests/evaluatorRun.test.ts @@ -8,7 +8,10 @@ import { runSolver } from '../src/solver/run'; import { VerificationCheckpointError } from '../src/solver/verificationCheckpoint'; const host = vi.hoisted(() => ({ evaluate: vi.fn(), research: vi.fn(), prepare: vi.fn() })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); +vi.mock('../src/math/mathBuildManifest', async () => ({ + readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: (await import('./helpers/buildManifest')).fixtureBuildDigest, +})); vi.mock('../src/math/leanDiagnostics', async original => ({ ...(await original()), runLeanDiagnostics: host.prepare, diff --git a/tests/helpers/buildManifest.ts b/tests/helpers/buildManifest.ts new file mode 100644 index 00000000..7d552043 --- /dev/null +++ b/tests/helpers/buildManifest.ts @@ -0,0 +1,9 @@ +import fs from 'node:fs'; +import { mathDigest } from '../../src/math/mathRuntimeIo'; + +/** Hashes a disposable manifest fixture without requiring a built release. */ +export function fixtureBuildDigest(file: string, _root: string, _bundles: string, expectedDigest?: string) { + const digest = mathDigest(fs.readFileSync(file)); + if (expectedDigest !== undefined && expectedDigest !== digest) throw new Error('math_build_manifest_changed'); + return digest; +} diff --git a/tests/helpers/nativeDirectContext.ts b/tests/helpers/nativeDirectContext.ts deleted file mode 100644 index d374448e..00000000 --- a/tests/helpers/nativeDirectContext.ts +++ /dev/null @@ -1,86 +0,0 @@ -// A disposable real tutorial and its hosted reference context for the Rust integration test. -import fs from 'node:fs'; -import { execFileSync } from 'node:child_process'; -import path from 'node:path'; -import { bootstrapLocalExample } from '../../src/math/localExample'; -import { readSolverProblem } from '../../src/solver/problem'; -import { buildResearchContext } from '../../src/solver/modules/context'; -import type { SolverRunState } from '../../src/solver/archive'; -import { harnessReadRoots, hostPrivateRoots } from '../../src/runtime/harnessProcess'; -import { mathWorkerPermissionConfig } from '../../src/runtime/codexSession'; - -const dir = process.argv[2]!, - home = process.env.HOME!; -const worktree = path.join(home, "worker '甲' {{editable}}"); -const tools = path.join(home, 'bin-tools', 'worker.native'); -const profile = path.join(home, '.config', 'run', 'runtime'); -const envFile = path.join(dir, 'environment-solver.json'); -const executable = path.join(home, 'bin-tools', 'codex'); -fs.mkdirSync(path.dirname(tools), { recursive: true }); -fs.writeFileSync(executable, '#!/usr/bin/env fake-interpreter\n'); -fs.mkdirSync(path.join(profile, 'tmp'), { recursive: true }); -fs.writeFileSync(path.join(home, '.config', 'key.json'), 'private'); -fs.mkdirSync(path.join(home, '.ssh'), { recursive: true }); -fs.mkdirSync(path.join(dir, 'shared', 'tools'), { recursive: true }); -fs.mkdirSync(path.join(home, 'extra')); -fs.symlinkSync(path.join(dir, 'shared', 'tools'), path.join(home, 'extra', 'dependency')); -fs.symlinkSync(path.join(dir, 'shared'), path.join(home, 'private-link')); -const receipt = bootstrapLocalExample(worktree); -const problem = readSolverProblem(worktree, receipt.activeProblemPath); -const state = { - problem, - workerCount: 1, - coordination: 'independent', - failures: [], - environmentDigest: 'a'.repeat(64), -} as unknown as SolverRunState; -const taskText = 'Compare a disposable tutorial.\n任务 🧮'; -const env = { PATH: '/usr/bin', DEEPSCIENTIST_MATH_ENV_FILE: envFile, ELAN_HOME: path.join(home, '.elan') }; -const hidden = [path.join(home, 'fixture-cache'), dir]; -const readable = [path.dirname(tools), path.join(home, 'extra')]; -// Bun derives userInfo().homedir from HOME in a fixture with a synthetic home. -// Supply the POSIX account home that the standalone worker also masks. -const homes = [ - home, - execFileSync('getent', ['passwd', String(process.getuid!())], { encoding: 'utf8' }).split(':')[5]!, -]; -const expectedPermissions = mathWorkerPermissionConfig( - worktree, - hidden, - hostPrivateRoots( - [worktree, path.join(profile, 'tmp')], - harnessReadRoots(env, [worktree], executable, readable, homes), - homes, - ), -); -const expected = (feedback?: string) => { - const { instructions, message, manifest } = buildResearchContext(problem, state, { - root: dir, - worktree, - tools, - environment: env, - taskText, - sourceFeedback: feedback, - retrievalRoot: worktree, - }); - return { instructions, message, manifest }; -}; -const feedback = 'An offline fixture diagnostic.\nA second line.'; -console.log( - JSON.stringify({ - state, - worktree, - tools, - envFile, - executable, - profile, - hidden, - readable, - env, - taskText, - feedback, - expected: expected(), - withFeedback: expected(feedback), - expectedPermissions, - }), -); diff --git a/tests/researchToolGuide.test.ts b/tests/researchToolGuide.test.ts index 7dfa29e2..6b989509 100644 --- a/tests/researchToolGuide.test.ts +++ b/tests/researchToolGuide.test.ts @@ -21,15 +21,10 @@ const argv = (line: string) => .split('\0') .slice(0, -1); -it('points a copied single-file check at the editable original target within a nested member project', () => { +it('points a copied single-file check at the editable original target within a nested project', () => { const file = base.ownedFiles[3]!; const targets = [base.ownedFiles[1]!, file].map(proofPath => ({ proofPath, theoremName: 'T', declarationHash: 'h' })); - const { help, leanCheckCommand } = buildResearchToolGuide( - { ...base, targets }, - access, - 'environment', - 'native-agent-control', - ); + const { help, leanCheckCommand } = buildResearchToolGuide({ ...base, targets }, access, 'environment'); const example = help .build()! .text.split('\n') diff --git a/tests/runLeaseSafety.test.ts b/tests/runLeaseSafety.test.ts index e4848820..47c873fe 100644 --- a/tests/runLeaseSafety.test.ts +++ b/tests/runLeaseSafety.test.ts @@ -2,14 +2,17 @@ import fs from 'node:fs'; import path from 'node:path'; import { spawnSync } from 'node:child_process'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { readSolverRunState } from '../src/solver/archive'; +import { readSolverRunState, writeSolverRunState } from '../src/solver/archive'; import { directSolverModules } from '../src/solver/modules'; import { runSolver } from '../src/solver/run'; import { localExample } from './helpers/solver'; const host = vi.hoisted(() => ({ run: vi.fn() })); let beforePublish: ((file: string) => void) | undefined; -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); +vi.mock('../src/math/mathBuildManifest', async () => ({ + readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: (await import('./helpers/buildManifest')).fixtureBuildDigest, +})); vi.mock('../src/math/leanDiagnostics', async original => ({ ...(await original()), runLeanDiagnostics: async () => ({ exitCode: 0, timedOut: false, phases: [] }), @@ -94,6 +97,33 @@ afterEach(() => { }); describe('run failure checkpoint ownership', () => { + it('leaves resume configuration to the lease holder', async () => { + const current = fixture(); + expect(await runSolver([...current.args, '--startup-only'], current.directory, modules)).toBe(0); + const retired = readSolverRunState(current.stateFile); + retired.workerCount = 2; + writeSolverRunState(current.stateFile, retired); + const saved = fs.readFileSync(current.stateFile); + const output = fs.readFileSync(current.output); + const resume = [...current.args, '--resume']; + const onRejected = vi.fn(); + const lock = fs.openSync(current.lockPath, 'r+'); + try { + // flock transfers ownership to the inherited descriptor, which this fixture keeps open. + expect( + spawnSync('/usr/bin/flock', ['--nonblock', '3'], { stdio: ['ignore', 'ignore', 'ignore', lock] }).status, + ).toBe(0); + expect(await runSolver(resume, current.directory, modules, undefined, { onRejected })).toBe(1); + expect(onRejected).toHaveBeenCalledWith('math_runtime_lease_busy'); + } finally { + fs.closeSync(lock); + } + await expect(runSolver(resume, current.directory, modules)).rejects.toThrow('math_legacy_collaboration_retired'); + expect(fs.readFileSync(current.stateFile)).toEqual(saved); + expect(fs.readFileSync(current.output)).toEqual(output); + expect(host.run).not.toHaveBeenCalled(); + }); + it('retains the real run lock while publishing failure state and output', async () => { const current = fixture(), writes: string[] = []; diff --git a/tests/singleContinuationSeed.test.ts b/tests/singleContinuationSeed.test.ts index fe6cfeb0..6d75bf32 100644 --- a/tests/singleContinuationSeed.test.ts +++ b/tests/singleContinuationSeed.test.ts @@ -397,7 +397,7 @@ describe('single researcher continuation', () => { 'Alternate revision', ]); if (packageLayout === 'packed') git(pkg, ['pack-refs', '--all', '--prune']); - expect(() => execFileSync(cli, args, { env, stdio: 'pipe' })).toThrow(/package entry/u); + expect(() => execFileSync(cli, args, { env, stdio: 'pipe' })).toThrow(/math_lake_packages_unavailable/u); expect(fs.existsSync(path.join(f.directory, 'continuation-single-source.json'))).toBe(false); git(pkg, ['update-ref', 'HEAD', pinned]); if (packageLayout === 'packed') { @@ -409,7 +409,7 @@ describe('single researcher continuation', () => { const trustedCache = path.join(f.directory, 'trusted-cache'); if (packageLayout === 'trusted') { fs.renameSync(localCache, trustedCache); - expect(() => execFileSync(cli, args, { env, stdio: 'pipe' })).toThrow(/package entry/u); + expect(() => execFileSync(cli, args, { env, stdio: 'pipe' })).toThrow(/math_lake_packages_unavailable/u); expect(fs.existsSync(path.join(f.directory, 'continuation-single-source.json'))).toBe(false); } fs.chmodSync(envFile, 0o600); diff --git a/tests/skillContextContinuation.test.ts b/tests/skillContextContinuation.test.ts index 9b196055..e79c9d9c 100644 --- a/tests/skillContextContinuation.test.ts +++ b/tests/skillContextContinuation.test.ts @@ -2,12 +2,11 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; import { mathDigest } from '../src/math/mathRuntimeIo'; -import type { MathTools } from '../src/math/mathTools'; import { readMathAgentSkill } from '../src/runtime/codexSkills'; import { buildResearchContext, finalizeResearchDispatch, type ContextBundle } from '../src/solver/modules/context'; import { researchSkillIdentity } from '../src/solver/researchSkill'; import { buildSkillResearchContext, teamTurnTiming } from '../src/solver/skillResearchContext'; -import { localExample, peerWorker, solverState } from './helpers/solver'; +import { localExample, solverState } from './helpers/solver'; const roots: string[] = []; afterEach(() => { @@ -83,244 +82,20 @@ it('shows standard-library tactic availability only for a solo solver with a sta ); }); -it('gives both native roles their own Lean command and keeps the complete tool catalog in worktree help', () => { - const f = fixture(), - peer = peerWorker(f, 'analyst'), - message = 'Find a concrete input for the inference.'; - const sourceCommit = f.problem.baseCommit; - f.state.researchDelegation = { mode: 'team', maxAgents: 2 }; - f.state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [ - { - id: peer.id, - role: 'researcher', - worktree: peer.worktree, - phase: 'running', - status: 'running', - turns: 1, - cursor: 0, - seedCommit: sourceCommit, - tasks: [{ id: 'witness', status: 'running', message }], - }, - ], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }; - const tools: MathTools = { - root: '/tools', - digest: mathDigest('test manifest'), - tools: [ - { name: 'math-python', version: '1', purpose: 'SymPy for exact arithmetic.', commands: ['math-python'] }, - { name: 'custom', version: '1', purpose: 'Custom geometry fixture.', commands: ['rare-geometry-tool'] }, - ], - }; - for (const member of [false, true]) { - const worktree = member ? peer.worktree : f.workspace; - const access = { - ...f.access, - worktree, - ...(member - ? { - teamRole: { id: peer.id, role: 'worker' as const }, - teamAssignment: { taskId: 'witness', message, sourceCommit }, - } - : {}), - }; - const help = () => fs.readFileSync(path.join(worktree, '.scratch/theoremos-help.md'), 'utf8'); - const plain = buildSkillResearchContext(f.problem, f.state, access); - expect(plain.instructions).not.toContain('math-python'); - expect(help()).not.toContain('## math-tools'); - const withTools = buildSkillResearchContext(f.problem, f.state, { ...access, mathTools: tools }); - const check = help() - .split('\n') - .find(line => line.startsWith('bun ') && line.includes(' check-lean ')); - expect(check).toContain(`--worktree '${worktree}' --file '${f.problem.targets[0]!.proofPath}'`); - expect(help()).toContain('rare-geometry-tool'); - for (const continuation of [false, true]) { - const { instructions } = finalizeResearchDispatch(withTools, { continuation }); - expect(instructions).toContain(check!); - expect(instructions).toContain('math-python'); - expect(instructions).not.toContain('rare-geometry-tool'); - } - } -}); - -it('retains source research and failure feedback on native continuation with a saved coordination presentation', () => { - const f = fixture(); - f.state.researchDelegation = { mode: 'team', maxAgents: 3 }; - f.state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - coordination: { - decision: 'continue', - reason: 'Inspect a direct proof.', - nextStep: 'Check the saved candidate.', - revision: 1, - at: 1, - startedRequests: 0, - eventSequence: 0, - observationRevision: 0, - }, - coordinationObservation: { - revision: 1, - at: 2, - key: 'failed-check', - kind: 'proof-feedback', - failed: true, - description: 'The saved candidate still has an unresolved proof obligation.', - }, - coordinationPresentation: { - at: 3, - reason: 'research-update', - decisionRevision: 1, - eventSequence: 0, - observationRevision: 1, - startedRequests: 1, - }, - }; - const feedback = f.state.agentTeam.coordinationObservation!.description; - const context = buildSkillResearchContext(f.problem, f.state, { - ...f.access, - sourceFeedback: feedback, - teamRole: { id: 'lead', role: 'lead' }, - }); - const dispatch = finalizeResearchDispatch(context, { continuation: true }); - expect(dispatch.message).toContain(feedback); - expect(dispatch.message).toContain('Read current Lean sources and worktree-root RESEARCH.md'); - expect(dispatch.message.match(/RESEARCH\.md/gu)).toHaveLength(1); - expect(dispatch.manifest!.included).toEqual( - expect.arrayContaining([ - expect.objectContaining({ id: 'saved-work', kind: 'sources', required: true }), - expect.objectContaining({ id: 'same-thread-skill-research', kind: 'continuation', required: true }), - expect.objectContaining({ id: 'host-feedback', kind: 'feedback', required: true }), - ]), - ); - expect(dispatch.message).not.toContain('Address the pending collaboration decision'); - expect(dispatch.message).not.toContain('After ordinary tools resume'); - expect(dispatch.message).not.toContain('Resume original research after addressing'); - expect(dispatch.message).not.toContain('before extended proof work'); - expect(dispatch.message).not.toContain(f.taskText); -}); - -it('compiles the current child assignment and inbox inside both full and continuation context budgets', () => { - const f = fixture(), - sourceCommit = 'a'.repeat(40), - deliveryBaseCommit = 'b'.repeat(40); - const objective = 'Profiles: D041, prover\n研究当前不等式并独立验证假设;明确报告反例或可复用的 Lean 声明。'; - f.state.researchDelegation = { mode: 'team', maxAgents: 3 }; - f.state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - deliveries: [], - adoptions: [], - operations: [], - coordinationPresentation: { at: 1, reason: 'opening', decisionRevision: 0, eventSequence: 0 }, - events: [ - { - sequence: 1, - from: 'lead', - to: 'child', - kind: 'message', - at: 1, - text: 'An additional boundary case to inspect.', - }, - ], - workers: [ - { - id: 'child', - role: 'researcher', - worktree: f.workspace, - phase: 'running', - status: 'running', - turns: 1, - cursor: 0, - seedCommit: sourceCommit, - tasks: [{ id: 'current-task', message: objective, status: 'running', seedCommit: deliveryBaseCommit }], - }, - ], - }; - const context = buildSkillResearchContext(f.problem, f.state, { - ...f.access, - teamRole: { id: 'child', role: 'worker' }, - teamAssignment: { taskId: 'current-task', message: objective, sourceCommit }, - executionLimits: { ...teamTurnTiming(300_000), remainingRunMs: () => 1_200_000 }, - }); - for (const continuation of [false, true]) { - const dispatch = finalizeResearchDispatch(context, { continuation }); - expect(dispatch.message).not.toContain('Address the pending collaboration decision'); - expect(dispatch.message).not.toContain('After ordinary tools resume'); - expect(dispatch.message).not.toContain('"currentStage"'); - expect(dispatch.instructions).toContain('Only Lead dispatches and adopts.'); - expect(dispatch.instructions).toContain('Do not spawn subteams or interrupt peers.'); - expect(dispatch.manifest!.included.find(item => item.id === 'agent-team-assignment')).toMatchObject({ - kind: 'assignment', - required: true, - }); - expect(dispatch.manifest!.included.find(item => item.id === 'agent-team-profiles')).toMatchObject({ - kind: 'assignment', - required: true, - }); - expect( - JSON.parse( - dispatch.message - .split('\n') - .find(line => line.startsWith('{"schema":"theorem-os.agent-team-profile-evidence.v1"'))!, - ), - ).toMatchObject({ skillDigest: f.access.researchSkill.digest, loaded: ['D041', 'prover'], unresolved: [] }); - expect(dispatch.message).toContain('references/domain-materials/analysis.md#real-analysis'); - expect(dispatch.manifest!.usedBytes).toBe( - Buffer.byteLength(dispatch.instructions) + Buffer.byteLength(dispatch.message), - ); - const envelope = JSON.parse(dispatch.message.split('\n')[1]!); - expect(envelope).toMatchObject({ - agentId: 'child', - coordinator: 'lead', - taskId: 'current-task', - objective, - sourceCommit, - deliveryBaseCommit, - inbox: { through: 1, events: [{ text: 'An additional boundary case to inspect.' }] }, - }); - expect(JSON.parse(dispatch.message.split('\n').find(line => line.startsWith('{"remainingRunMs"'))!)).toEqual({ - remainingRunMs: 1_200_000, - turnCheckpointMs: 240_000, - turnTimeoutMs: 300_000, - }); - } - expect(() => - buildSkillResearchContext(f.problem, f.state, { - ...f.access, - teamRole: { id: 'child', role: 'worker' }, - teamAssignment: { taskId: 'other-task', message: objective, sourceCommit }, - }), - ).toThrow('math_team_assignment_changed'); - const help = fs.readFileSync(path.join(f.workspace, '.scratch/theoremos-help.md'), 'utf8'); - expect(help).not.toContain('research-observe'); - expect(help).toContain('check-lean --worktree'); - expect(() => - buildSkillResearchContext(f.problem, f.state, { - ...f.access, - teamRole: { id: 'child', role: 'worker' }, - teamAssignment: { taskId: 'current-task', message: objective, sourceCommit }, - maxContextBytes: 2000, - }), - ).toThrow('math_context_mandatory_overflow'); -}); - describe('same-thread Skill context', () => { it('refreshes execution time on continuation and retains it as required context', () => { const f = fixture(); f.state.researchSkillWorkflow = 'full'; f.state.researchDelegation = { mode: 'team', maxAgents: 3 }; + f.state.agentTeam = { + schema: 'theorem-os.agent-team.v1', + transport: 'codex-shared', + workers: [], + events: [], + deliveries: [], + adoptions: [], + operations: [], + }; let remainingRunMs = 1_200_000; const context = buildResearchContext(f.problem, f.state, { ...f.access, @@ -435,36 +210,4 @@ describe('same-thread Skill context', () => { expect(continued.manifest?.maxBytes).toBe(full.manifest?.maxBytes); expect(finalizeResearchDispatch(context, { continuation: false }).message).toBe(full.message); }); - - it('delivers team state and messages in both restart and continuation contexts', () => { - const f = fixture(); - f.state.researchSkillWorkflow = 'full'; - f.state.researchDelegation = { mode: 'team', maxAgents: 3 }; - f.state.agentTeam = { - schema: 'theorem-os.agent-team.v1', - workers: [], - deliveries: [], - adoptions: [], - operations: [], - events: [ - { - sequence: 1, - from: 'child', - to: 'lead', - kind: 'message', - at: 1, - text: 'A durable question sent between native turns.', - }, - ], - }; - const context = buildResearchContext(f.problem, f.state, { ...f.access, teamRole: { id: 'lead', role: 'lead' } }); - for (const continuation of [false, true]) { - const dispatch = finalizeResearchDispatch(context, { continuation }); - expect(dispatch.instructions).toContain('the Lead of a flat mathematical research team'); - expect(dispatch.instructions).toContain('theoremos_team'); - expect(dispatch.instructions).not.toContain('native child agents are not enabled'); - expect(dispatch.message).toContain('A durable question sent between native turns.'); - if (!continuation) expect(dispatch.manifest?.included.map(item => item.id)).toContain('agent-team'); - } - }); }); diff --git a/tests/skillResearchRuntime.test.ts b/tests/skillResearchRuntime.test.ts index faeed7b8..16710447 100644 --- a/tests/skillResearchRuntime.test.ts +++ b/tests/skillResearchRuntime.test.ts @@ -102,7 +102,7 @@ describe('skill research runtime', () => { researchDelegation: { mode: 'team', maxAgents: 2 }, agentTeam: { schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', + transport: 'codex-shared', workers: [], events: [], deliveries: [], @@ -550,7 +550,7 @@ describe('skill research runtime', () => { expect(host.verify).not.toHaveBeenCalled(); }); - it('checks a Lead declaration submission after native completion without a coordination checkpoint', async () => { + it('saves shared team sources without processing a solo declaration request', async () => { const current = fixture( [ f => { @@ -567,16 +567,15 @@ describe('skill research runtime', () => { true, ); expect(await current.completion).toBeUndefined(); - expect(current.events.some(item => item.event === 'team_coordination_checkpoint')).toBe(false); - expect(current.events.some(item => item.event === 'team_coordination_continued')).toBe(false); expect(current.stops).toHaveBeenCalledOnce(); - expect(host.declarations).toHaveBeenCalledOnce(); - expect(current.stops.mock.invocationCallOrder[0]).toBeLessThan(host.declarations.mock.invocationCallOrder[0]); - expect(fs.existsSync(current.requestFile)).toBe(false); + expect(current.events.some(item => item.event === 'research_saved')).toBe(true); + expect(host.declarations).not.toHaveBeenCalled(); + expect(host.verify).not.toHaveBeenCalled(); + expect(fs.existsSync(current.requestFile)).toBe(true); expect(current.state.check).toBeUndefined(); }); - it('accepts a completed native original proof only after writer shutdown', async () => { + it('accepts a completed shared team proof only after writer shutdown', async () => { const current = fixture( [ f => { @@ -589,13 +588,11 @@ describe('skill research runtime', () => { true, ); expect((await current.completion)?.check.passed).toBe(true); - expect(current.events.some(item => item.event === 'team_coordination_checkpoint')).toBe(false); - expect(current.events.some(item => item.event === 'team_coordination_continued')).toBe(false); expect(current.stops).toHaveBeenCalledOnce(); expect(current.stops.mock.invocationCallOrder[0]).toBeLessThan(host.verify.mock.invocationCallOrder[0]); }); - it('returns invalid-source feedback after native completion without accepting the source', async () => { + it('rejects invalid shared team source after writer shutdown', async () => { const current = fixture( [ f => { @@ -608,8 +605,6 @@ describe('skill research runtime', () => { true, ); expect(await current.completion).toBeUndefined(); - expect(current.events.some(item => item.event === 'team_coordination_checkpoint')).toBe(false); - expect(current.events.some(item => item.event === 'team_coordination_continued')).toBe(false); expect(current.events.some(item => item.event === 'source_rejected')).toBe(true); expect(current.stops).toHaveBeenCalledOnce(); expect(host.verify).not.toHaveBeenCalled(); diff --git a/tests/skillSolver.test.ts b/tests/skillSolver.test.ts index 0e4054cb..bf0f1017 100644 --- a/tests/skillSolver.test.ts +++ b/tests/skillSolver.test.ts @@ -13,12 +13,11 @@ import { localExample } from './helpers/solver'; import { bindResearchHarness } from '../src/runtime/researchHarness'; import { prepareWestlakeProfile } from '../src/runtime/westlake'; import * as connectivity from '../src/runtime/codexConnectivity'; -import * as buildManifest from '../src/math/mathBuildManifest'; -import { mathDigest } from '../src/math/mathRuntimeIo'; vi.mock('../src/math/mathBuildManifest', async original => ({ ...(await original()), readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: (await import('./helpers/buildManifest')).fixtureBuildDigest, })); vi.mock('../src/math/leanToolchainReadiness', () => ({ checkResolvedLeanToolchainReadiness: () => ({ status: 'ready' }), @@ -66,7 +65,7 @@ describe('opt-in skill research CLI and pinned identity', () => { vi.stubEnv('DEEPSCIENTIST_MATH_ENV_FILE', path.join(example.directory, 'empty.env')); vi.stubEnv('DEEPSCIENTIST_MATH_PANTOGRAPH_MANIFEST', undefined); vi.stubEnv('DEEPSCIENTIST_MATH_PANTOGRAPH_SHA256', undefined); - vi.stubEnv('THEOREMOS_CODEX_BACKEND_EXECUTABLE', process.execPath); + vi.stubEnv('DEEPSCIENTIST_MATH_CODEX_EXECUTABLE', process.execPath); vi.spyOn(console, 'log').mockImplementation(() => {}); open.mockClear(); }); @@ -165,9 +164,6 @@ describe('opt-in skill research CLI and pinned identity', () => { }); it('resumes a native team seed from the same path both before and after the seed completes', async () => { - vi.spyOn(buildManifest, 'readMathBuildManifestDigest').mockImplementation(file => - mathDigest(fs.readFileSync(file)), - ); const profile = path.join(example.directory, 'offline-profile'); fs.mkdirSync(profile); vi.stubEnv('CODEX_HOME', profile); @@ -184,7 +180,7 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(await runSolver([...resume, sourceStateFile], root, modules, undefined, 'cli')).toBe(0); const seeded = state(); expect(seeded).toMatchObject({ - agentTeam: { transport: 'native-agent-control' }, + agentTeam: { transport: 'codex-shared' }, continuationDigest: expect.any(String), phase: 'prepared', turns: 0, @@ -297,7 +293,7 @@ describe('opt-in skill research CLI and pinned identity', () => { }, ); - it('rejects a new direct Westlake Chat team before saving a run', async () => { + it('rejects the Westlake Chat bridge before saving a shared team run', async () => { const profile = path.join(example.directory, 'westlake-profile'); prepareWestlakeProfile(profile, 'deepseek-flash', 'high'); vi.stubEnv('THEOREMOS_CODEX_BACKEND_EXECUTABLE', path.join(example.directory, 'missing-native-backend')); @@ -318,24 +314,42 @@ describe('opt-in skill research CLI and pinned identity', () => { const saved = state(); saved.agentHarness = bindResearchHarness('codex', process.execPath, profile); saved.agentTeam!.transport = transport; + saved.agentSessionPlan = { ...saved.agentSessionPlan!, structuredOutput: 'validated-output-file' }; const stateFile = output + '.runtime/state.json'; writeSolverRunState(stateFile, saved); const original = fs.readFileSync(stateFile); - if (transport === 'host-tools') { - await expect(runSolver([...args, '--resume'], root, modules, undefined, 'cli')).rejects.toThrow( - 'math_legacy_collaboration_retired', - ); - } else { - expect(await runSolver([...args, '--resume'], root, modules, undefined, 'cli')).toBe(1); - rejected( - 'math_westlake_native_team_unsupported: select a native-compatible Codex profile such as the Responses gateway.', - ); - } + await expect(runSolver([...args, '--resume'], root, modules, undefined, 'cli')).rejects.toThrow( + 'archive/isolated-codex-teams', + ); expect(fs.readFileSync(stateFile)).toEqual(original); expect(open).not.toHaveBeenCalled(); }, ); + it('does not resume a shared team record with host-managed workers', async () => { + expect(await runSolver(args, root, modules, undefined, 'cli')).toBe(0); + const saved = state(); + saved.agentTeam!.workers.push({ + id: 'historical-member', + role: 'researcher', + worktree: path.join(example.directory, 'member'), + phase: 'prepared', + status: 'idle', + turns: 0, + cursor: 0, + seedCommit: saved.problem.baseCommit, + tasks: [], + }); + const stateFile = output + '.runtime/state.json'; + writeSolverRunState(stateFile, saved); + const original = fs.readFileSync(stateFile); + await expect(runSolver([...args, '--resume'], root, modules, undefined, 'cli')).rejects.toThrow( + 'math_legacy_collaboration_retired', + ); + expect(fs.readFileSync(stateFile)).toEqual(original); + expect(open).not.toHaveBeenCalled(); + }); + it('freezes optional profiles without filling seats and preserves them on resume', async () => { const team = [...args, '--research-mode', 'skill', '--skill-delegation', 'team', '--skill-max-agents', '8']; expect( @@ -477,7 +491,7 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(await runSolver(flags, root, modules, undefined, 'cli')).toBe(0); const saved = state(); expect(saved).toMatchObject({ - agentTeam: { transport: 'native-agent-control' }, + agentTeam: { transport: 'codex-shared' }, researchDelegation: { mode: 'team', maxAgents: 4 }, workerCount: 1, turns: 0, diff --git a/tests/solver.test.ts b/tests/solver.test.ts index 8de9d99e..92ad8644 100644 --- a/tests/solver.test.ts +++ b/tests/solver.test.ts @@ -87,7 +87,6 @@ const host = vi.hoisted(() => ({ verify: vi.fn(), createSession: vi.fn(), officialGate: vi.fn(), - build: vi.fn(), delay: vi.fn(), prepare: vi.fn(), freeze: vi.fn(), @@ -110,7 +109,10 @@ vi.mock('node:timers/promises', async importOriginal => ({ ...(await importOriginal()), setTimeout: host.delay, })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: host.build })); +vi.mock('../src/math/mathBuildManifest', async () => ({ + readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: (await import('./helpers/buildManifest')).fixtureBuildDigest, +})); vi.mock('../src/math/leanToolchainReadiness', () => ({ checkResolvedLeanToolchainReadiness: host.readiness })); vi.mock('../src/runtime/codexConnectivity', () => ({ checkCodexProviderConnectivity: host.connectivity })); vi.mock('../src/math/verifier', async importOriginal => ({ diff --git a/tests/solverRouteRetirement.test.ts b/tests/solverRouteRetirement.test.ts deleted file mode 100644 index 23fef21a..00000000 --- a/tests/solverRouteRetirement.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { bootstrapLeanTask } from '../src/math/leanTask'; -import { mathDigest } from '../src/math/mathRuntimeIo'; -import { readMathAgentSkill } from '../src/runtime/agentSkills'; -import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; -import type { NativeAgentControlConnection } from '../src/runtime/nativeAgentControl'; -import { AgentResearchTeam } from '../src/solver/agentTeam'; -import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive'; -import { directSolverModules } from '../src/solver/modules'; -import { readSolverProblem } from '../src/solver/problem'; -import { prepareResearchSkill, researchSkillIdentity } from '../src/solver/researchSkill'; -import { deferred } from './helpers/async'; -import { temporaryDirectory } from './helpers/files'; -import { solverState } from './helpers/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() { - const directory = temporaryDirectory('team-route-retirement-'); - const task = bootstrapLeanTask(path.join(directory, 'lead'), { - source: 'theorem target : True := by sorry\n', - task: goal, - }); - const problem = readSolverProblem(task.workspaceRoot, task.activeProblemPath); - const root = process.cwd(); - const identity = researchSkillIdentity(readMathAgentSkill(path.join(root, 'skills/theoremos-research/SKILL.md'))); - const state = solverState(problem, task.workspaceRoot, { - runId: 'team-route-retirement', - phase: 'running', - environmentDigest: mathDigest('offline route retirement fixture'), - researchMode: 'skill', - researchSkillWorkflow: 'full', - researchSkill: identity, - workerCount: 1, - researchDelegation: { mode: 'team', maxAgents: 2 }, - agentTeam: { - schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [], - events: [], - deliveries: [], - adoptions: [], - operations: [], - }, - }); - const skill = prepareResearchSkill(root, state.worktree, identity, problem); - const controller = new AbortController(), - stateFile = path.join(directory, 'state.json'); - const current = new Map< - string, - { - started: ReturnType; - stopped: ReturnType; - interrupt: () => Promise; - finish: () => void; - context?: string; - } - >(); - const teams: AgentResearchTeam[] = []; - const open = async (options: MathAgentOptions): Promise => { - const id = options.environment!.DEEPSCIENTIST_MATH_WORKER_ID!; - const config = options.nativeAgentControl!; - const threadId = options.threadId ?? String(config.bootstrap!.threadId); - const connection = nativeConnection(threadId, '/root/' + id, options.workspace); - await config.request( - { - version: 1, - threadId, - sessionId: rootThreadId, - operation: 'attach', - operationId: 'attach-' + id, - payload: { threadId, sessionId: rootThreadId }, - }, - connection, - { signal: controller.signal }, - ); - await config.bound?.(connection); - const started = deferred(), - stopped = deferred(), - outcome = deferred(); - const record = { - started, - stopped, - interrupt: vi.fn(async () => { - outcome.resolve('interrupted'); - }), - finish: () => { - stopped.resolve(); - outcome.resolve('completed'); - }, - context: undefined as string | undefined, - }; - current.set(id, record); - return { - threadId, - usageSource: 'upstream-requests', - nativeAgentControl: connection, - run: async (message, _id, _workspace, onStarted) => { - record.context = message; - onStarted('turn-' + id); - started.resolve(); - return outcome.promise; - }, - interrupt: record.interrupt, - stopForFreeze: async () => { - await stopped.promise; - return { status: 'stopped' }; - }, - close: async () => { - await config.disconnected?.(connection); - }, - }; - }; - const create = (saved: SolverRunState) => { - const team = new AgentResearchTeam({ - state: saved, - root, - taskText: goal, - leadAccess: { researchSkill: skill, environment: {}, retrievalRoot: saved.worktree }, - executable: 'offline', - profile: 'offline', - signal: controller.signal, - modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open } }, - maxAgents: 2, - maxTurns: Infinity, - maxTotalTokens: 0, - maxTurnMs: Infinity, - remainingMs: () => Infinity, - save: () => writeSolverRunState(stateFile, saved), - emit: () => {}, - exclusiveCheck: operation => operation(), - }); - teams.push(team); - return team; - }; - const team = create(state); - let sequence = 0; - const call = (args: Record, actor = 'lead', instance = team) => - instance.tools(actor).call('theoremos_team', args, { - threadId: 'fixture', - turnId: 'fixture', - callId: 'tool-' + ++sequence, - signal: controller.signal, - }); - 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('tags native spawn work, exposes the Lead operation, and blocks retired native requests', async () => { - const f = fixture(); - const options = f.team.nativeAgentControlOptions('lead')!; - const connection = nativeConnection(rootThreadId, '/root', f.state.worktree); - let sequence = 0; - const native = (operation: string, payload: Record) => - options.request( - { - version: 1, - operation, - operationId: 'native-' + ++sequence, - threadId: rootThreadId, - sessionId: rootThreadId, - payload, - }, - connection, - { signal: f.signal }, - ); - await native('attach', { threadId: rootThreadId, sessionId: rootThreadId }); - await options.bound?.(connection); - const spawn = (id: string, route: string) => - native('spawn', { - caller: rootThreadId, - source: { subagent: { thread_spawn: { agent_path: '/root/' + id, parent_thread_id: rootThreadId, depth: 1 } } }, - bootstrap: { config: { cwd: f.state.worktree, model: f.state.model, reasoningEffort: f.state.effort } }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Route: ' + route + '\nExplore a local reduction.' }, - }, - }); - await spawn('old', 'counterexample'); - const old = await f.session('old'); - expect(f.team.archive.workers[0]!.tasks[0]).toMatchObject({ - routeId: 'counterexample', - message: 'Explore a local reduction.', - }); - expect(await f.call(retirement, 'old')).toMatchObject({ ok: false, error: 'math_team_native_operation_required' }); - const task = f.team.archive.workers[0]!.tasks[0]!; - expect(await f.call(retirement)).toMatchObject({ - ok: true, - releasedAgentIds: ['old'], - cancelledTaskIds: [task.id], - }); - expect(old.interrupt).toHaveBeenCalled(); - expect(await f.call(retirement)).toMatchObject({ ok: true, cancelledTaskIds: [], releasedAgentIds: [] }); - expect(readSolverRunState(f.stateFile).agentTeam?.retiredRoutes).toMatchObject([ - { routeId: 'counterexample', source: 'lead', evidenceRefs: retirement.evidenceRefs }, - ]); - await expect(spawn('new', 'counterexample')).rejects.toThrow('math_team_route_retired:counterexample'); - await spawn('new', 'replacement'); - const replacement = await f.session('new'); - expect(replacement.context).toContain('"routeId":"replacement"'); - await expect( - native('send', { - caller: rootThreadId, - target: { kind: 'path', reference: '/root/new' }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Route: counterexample\nRepeat the route.' }, - }, - }), - ).rejects.toThrow('math_team_route_retired:counterexample'); - old.finish(); - replacement.finish(); - await expect.poll(() => f.team.hasActiveWorkers).toBe(false); - expect(task.status).toBe('cancelled'); - await f.team.close(); - const saved = readSolverRunState(f.stateFile), - restored = f.create(saved); - await restored.restore(); - const restoredOptions = restored.nativeAgentControlOptions(); - await restoredOptions.request( - { - version: 1, - operation: 'attach', - operationId: 'restored-attach', - threadId: rootThreadId, - sessionId: rootThreadId, - payload: { threadId: rootThreadId, sessionId: rootThreadId }, - }, - connection, - { signal: f.signal }, - ); - await restoredOptions.bound?.(connection); - await expect( - restoredOptions.request( - { - version: 1, - operation: 'send', - operationId: 'restored-followup', - threadId: rootThreadId, - sessionId: rootThreadId, - payload: { - caller: rootThreadId, - target: { kind: 'path', reference: '/root/new' }, - input: { - kind: 'message', - mode: 'triggerTurn', - message: { kind: 'plaintext', text: 'Route: counterexample\nReopen it.' }, - }, - }, - }, - connection, - { signal: f.signal }, - ), - ).rejects.toThrow('math_team_route_retired:counterexample'); - }); -}); diff --git a/tests/solverSoftSliceCompaction.test.ts b/tests/solverSoftSliceCompaction.test.ts index b7c6a28d..c04053b3 100644 --- a/tests/solverSoftSliceCompaction.test.ts +++ b/tests/solverSoftSliceCompaction.test.ts @@ -49,7 +49,7 @@ describe('soft research milestones', () => { researchDelegation: { mode: 'team', maxAgents: 3 }, agentTeam: { schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', + transport: 'codex-shared', workers: [], events: [], deliveries: [], @@ -153,15 +153,13 @@ describe('soft research milestones', () => { }); const notice = trigger === 'team' - ? /route_summary.*delegate focused independent obligations.*fewer than 20 lines.*RESEARCH\.md/u + ? /Ask teammates to save their files.*fewer than 20 lines.*RESEARCH\.md/u : /standalone helper.*fewer than 20 lines.*RESEARCH\.md/u; expect(notify.mock.calls).toEqual([[expect.stringMatching(notice), { mode: 'advisory' }]]); if (trigger === 'team') { - expect(options.instructions).toContain('You may delegate using the native collaboration tools'); + expect(options.sharedProofTeam).toMatchObject({ capacity: 3 }); expect(notify.mock.calls.flat()).not.toContainEqual(expect.stringContaining('declaration-submission.json')); - // This file is handled after the turn, outside the whole-proof diagnostics watcher. - expect(options.completedOutput?.file).toMatch(/lean-diagnostics-latest\.json$/u); - fs.writeFileSync(path.join(workspace, '.scratch/declaration-submission.json'), '{"declarations":[]}'); + expect(options.completedOutput).toBeUndefined(); } else if (skill) { expect(notify.mock.calls.flat()).toContainEqual( expect.stringContaining('Never write an empty declarations array'), @@ -194,12 +192,6 @@ describe('soft research milestones', () => { expect(fs.readFileSync(path.join(workspace, 'RESEARCH.md'), 'utf8')).toContain( 'The induction step remains open.', ); - if (trigger === 'team') { - expect(fs.existsSync(path.join(workspace, '.scratch/declaration-submission.json'))).toBe(false); - expect(fs.existsSync(path.join(workspace, '.scratch/declaration-feedback.json'))).toBe(false); - expect(events.some(entry => entry.event === 'declarations_checked')).toBe(false); - expect(state.declarationArtifacts ?? []).toEqual([]); - } } finally { controller.abort(); done.resolve('interrupted'); diff --git a/tests/webAgentActions.test.ts b/tests/webAgentActions.test.ts index c6018208..08ccb7d7 100644 --- a/tests/webAgentActions.test.ts +++ b/tests/webAgentActions.test.ts @@ -119,7 +119,7 @@ describe('Agent actions as the run owner sees them', () => { expect([started, interrupted, member].every(isWebAgentActionBody)).toBe(true); }); - test('retains the matching Lean source and native recipient identity, but keeps stale diagnostics detached', async () => { + test('retains the matching Lean source and shared team Lead, and detaches stale diagnostics', async () => { const root = temporaryDirectory('web-check-probe-'); try { const project = path.join(root, 'proof'), @@ -190,7 +190,6 @@ describe('Agent actions as the run owner sees them', () => { sourceDigest, environmentDigest, }); - // The root and a native child called "solver" have the same process ID; only the child has attributed initial input. const sent: WebAgentActionBody[] = []; const request = { id: 'fixture', @@ -202,12 +201,12 @@ describe('Agent actions as the run owner sees them', () => { hidden: [], solverRunId: () => 'solver-a', }); - for (const nativeAgentControl of [{}, { initialInput: { author: '/root' } }]) { + for (const sharedProofTeam of [undefined, { capacity: 3, requireMetering: false }]) { const session = await modules.M1.open({ workspace: root, - nativeAgentControl, + sharedProofTeam, environment: { DEEPSCIENTIST_MATH_WORKER_ID: 'solver' }, - } as unknown as MathAgentOptions); + } as MathAgentOptions); try { opened.at(-1)!.onItem!('completed', item()); } finally { @@ -216,8 +215,8 @@ describe('Agent actions as the run owner sees them', () => { } expect(sent.every(isWebAgentActionBody)).toBe(true); expect(sent.map(action => [action.workerId, action.lean?.candidate?.nativeRole])).toEqual([ + ['solver', undefined], ['solver', 'lead'], - ['solver', 'member'], ]); result.candidate.file = 'DifferentProbe.lean'; expect(action()?.lean?.candidate).toBeUndefined(); diff --git a/tests/webLibraryNative.test.ts b/tests/webLibraryNative.test.ts index a7cbd81c..4aee1ba7 100644 --- a/tests/webLibraryNative.test.ts +++ b/tests/webLibraryNative.test.ts @@ -19,7 +19,10 @@ import { newestLeanBinary } from './helpers/lean'; // This test exercises real preparation, M2 checks, references and independent S3 acceptance. // The build identity gate is checked by the separate headless build; no model or provider is contacted here. -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); +vi.mock('../src/math/mathBuildManifest', async () => ({ + readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: (await import('./helpers/buildManifest')).fixtureBuildDigest, +})); const lean = newestLeanBinary(); const roots: string[] = []; afterEach(() => { diff --git a/tests/webLibraryResearch.test.ts b/tests/webLibraryResearch.test.ts index e0b31326..3a871950 100644 --- a/tests/webLibraryResearch.test.ts +++ b/tests/webLibraryResearch.test.ts @@ -10,11 +10,11 @@ import type { WebRunInput, WorkerInput } from '../apps/web/shared'; import { formalizationDigest, readFormalizationArtifact } from '../src/math/formalization'; import { LIBRARY_PACK_SCHEMA, type LibraryPack } from '../src/math/libraryPacks'; import { mathDigest, readMathJson, readMathText, writeMathJsonDurable } from '../src/math/mathRuntimeIo'; -import type { AgentTeamWorker } from '../src/solver/agentTeamState'; import { writeSolverRunState } from '../src/solver/archive'; import { MAX_CONTINUATION_ATTACHMENT_BYTES, MAX_CONTINUATION_TOTAL_BYTES, + freezeContinuationInput, readContinuationInput, } from '../src/solver/continuationInput'; import { writeLibraryCatalog } from '../src/solver/libraryCatalog'; @@ -110,6 +110,7 @@ function finishRound(f: Fixture, round: WebLibraryRound, names?: string[], used: const usage = used.tokens === null ? undefined : { totalTokens: used.tokens ?? 100 }; const state = solverState(problem, round.seed.workspaceRoot, { runId: `solver-round-${round.round}`, + taskDigest: mathDigest(readMathText(round.seed.taskFile)), phase: 'finished', workerCount: 1, coordination: 'cooperative', @@ -126,6 +127,13 @@ function finishRound(f: Fixture, round: WebLibraryRound, names?: string[], used: }); const stateFile = `${round.output}.runtime/state.json`; fs.mkdirSync(path.dirname(stateFile), { recursive: true }); + if (round.continuationFile) { + const attachment = readContinuationInput(round.continuationFile, { + taskDigest: state.taskDigest, + problemReceiptDigest: problem.receiptDigest, + }); + state.continuationDigest = freezeContinuationInput(attachment, path.dirname(stateFile)).digest; + } writeSolverRunState(stateFile, state); const raw = { runId: state.runId, @@ -322,6 +330,8 @@ describe('Web library research supervision without provider calls', () => { fs.writeFileSync(path.join(original.workspace, original.projectRelative, 'Submission.lean'), draft); fs.writeFileSync(path.join(original.workspace, 'RESEARCH.md'), notes); finishRound(f, round, ['Research.desired']); + fs.unlinkSync(continuationFile); + fs.unlinkSync(path.join(f.directory, 'original-reference.txt')); return; } const current = readSolverProblem(round.seed.workspaceRoot, round.seed.activeProblemPath); @@ -410,7 +420,7 @@ describe('Web library research supervision without provider calls', () => { expect(readMathJson(path.join(f.directory, 'library-research.json'))).toEqual(result.raw); }); - it('passes the remaining total turn, wall-time and worker token allowance to each later round', async () => { + it('passes the remaining total turn, wall-time and token allowance to each later round', async () => { const f = fixture({ maxRunSeconds: 12 }), calls: WebLibraryRound[] = []; const result = await runWebLibraryResearch({ @@ -427,19 +437,6 @@ describe('Web library research supervision without provider calls', () => { { turns: 1, solveWallMs: 1000, tokens: 50 }, ][round.round], ); - // A cooperative state reports totals at both levels; count the worker records exactly once. - saved.state.workers = [ - { - id: 'solver', - role: 'lead', - worktree: saved.state.worktree, - phase: 'finished', - turns: saved.state.turns, - usage: saved.state.usage, - usageAccounting: saved.state.usageAccounting, - }, - ]; - writeSolverRunState(saved.stateFile, saved.state); if (round.round === 2) expect(Object.keys(saved.problem.frozenFiles).sort()).toEqual([initial, base, feature, extra].sort()); }, @@ -609,46 +606,20 @@ describe('Web library research supervision without provider calls', () => { }); }); - it('charges native members against the shared allowance and carries their saved research into the next library round', async () => { + it('carries the shared proof workspace and team token usage into the next library round', async () => { const f = fixture({ ...webAgentTeamPreset(), maxTotalTokens: 100 }); - const memberTree = path.join(f.directory, 'member'); - const draft = source + '\n-- Research saved by the team member only.\n'; + const draft = source + '\n-- Research saved in the shared workspace.\n'; const notes = 'Investigate using the requested declaration for the original goal.'; const run = vi.fn(async (round: WebLibraryRound) => { const saved = finishRound(f, round, [round.round === 0 ? 'Research.desired' : 'Research.final_hint'], { - tokens: 10, + tokens: 50, }); const { state, stateFile, problem } = saved; - const member: AgentTeamWorker = { - id: 'member', - role: 'researcher', - worktree: memberTree, - phase: 'finished', - status: 'stopped', - turns: 1, - usage: { totalTokens: 40 }, - usageAccounting: { startedTurns: 1, reportedTurns: 1, pending: false, incomplete: false }, - seedCommit: problem.baseCommit, - tasks: [], - cursor: 0, - }; state.researchDelegation = { mode: 'team', maxAgents: 3 }; state.agentTeam = { schema: 'theorem-os.agent-team.v1', - transport: 'native-agent-control', - workers: [ - member, - { - ...member, - id: 'unprepared', - worktree: path.join(f.directory, 'unprepared'), - phase: 'prepared', - status: 'preparing', - turns: 0, - usage: undefined, - usageAccounting: undefined, - }, - ], + transport: 'codex-shared', + workers: [], events: [], deliveries: [], adoptions: [], @@ -656,9 +627,8 @@ describe('Web library research supervision without provider calls', () => { }; writeSolverRunState(stateFile, state); if (round.round === 0) { - git(state.worktree, ['worktree', 'add', '--quiet', '--detach', memberTree, problem.baseCommit]); - fs.writeFileSync(path.join(memberTree, problem.projectRelative, 'Submission.lean'), draft); - fs.writeFileSync(path.join(memberTree, 'RESEARCH.md'), notes); + fs.writeFileSync(path.join(state.worktree, problem.projectRelative, 'Submission.lean'), draft); + fs.writeFileSync(path.join(state.worktree, 'RESEARCH.md'), notes); } else { const continued = readContinuationInput(round.continuationFile!, { taskDigest: mathDigest(readMathText(round.seed.taskFile)), @@ -680,6 +650,18 @@ describe('Web library research supervision without provider calls', () => { }); }); + it('refuses a library restart if the shared proof writer did not stop', async () => { + const f = fixture(webAgentTeamPreset()); + const run = vi.fn(async (round: WebLibraryRound) => { + const { state, stateFile } = finishRound(f, round, ['Research.desired']); + state.writerStopUnconfirmed = { at: Date.now(), reason: 'Fixture writer may still be active' }; + writeSolverRunState(stateFile, state); + }); + await expect(runWebLibraryResearch({ ...f, run })).rejects.toThrow('math_writer_stop_unconfirmed'); + expect(run).toHaveBeenCalledTimes(1); + expect(fs.existsSync(path.join(f.directory, 'rounds'))).toBe(false); + }); + it.each([ 'unknown worker', 'outside worker', diff --git a/tests/webRunner.test.ts b/tests/webRunner.test.ts index d0015608..9a57431b 100644 --- a/tests/webRunner.test.ts +++ b/tests/webRunner.test.ts @@ -98,7 +98,7 @@ else if (args[0] === 'create') { }, }; const signal = new AbortController().signal; - fs.writeFileSync(metadata, `v1|v1|v1|v1||${imageId}\n`); + fs.writeFileSync(metadata, `v1|v1|v1||${imageId}\n`); const old = new DockerWebRunner(config); await expect( old.run({ ...request, input: { ...request.input, workers: 2, coordination: 'cooperative' } }, () => {}, signal), @@ -115,15 +115,26 @@ else if (args[0] === 'create') { await expect(old.run(request, () => {}, signal)).rejects.toThrow('路线审批'); expect(fs.existsSync(created)).toBe(false); - fs.writeFileSync(metadata, `v1|v1|v1|v1|v1|${imageId}\n`); - const current = new DockerWebRunner(config); - expect(await current.readiness()).toMatchObject({ + fs.writeFileSync(metadata, `v1|v1|v1|v1|${imageId}\n`); + const isolated = new DockerWebRunner(config); + expect(await isolated.readiness()).toMatchObject({ + ready: true, + nativeTeam: false, + nativeTeamPreferences: false, + nativeTeamExpertCards: false, + }); + await expect(isolated.run(request, () => {}, signal)).rejects.toThrow('共享工作区团队'); + expect(fs.existsSync(created)).toBe(false); + + fs.writeFileSync(metadata, `v1|v1|v1|v2|${imageId}\n`); + const shared = new DockerWebRunner(config); + expect(await shared.readiness()).toMatchObject({ nativeTeam: true, nativeTeamPreferences: true, nativeTeamExpertCards: true, }); - fs.writeFileSync(metadata, `v1|v1|v1|v1||sha256:${'b'.repeat(64)}\n`); - await expect(current.run(request, () => {}, signal)).rejects.toThrow('无法创建隔离运行环境'); + fs.writeFileSync(metadata, `v1|v1|v1||sha256:${'b'.repeat(64)}\n`); + await expect(shared.run(request, () => {}, signal)).rejects.toThrow('无法创建隔离运行环境'); expect(fs.readFileSync(created, 'utf8')).toBe(imageId); } finally { vi.unstubAllEnvs(); @@ -577,7 +588,7 @@ const fs = require('node:fs'), path = require('node:path'); const args = process.argv.slice(2), root = __dirname; fs.appendFileSync(path.join(root, 'calls.jsonl'), JSON.stringify(args) + '\\n'); async function main() { - if (args[0] === 'image') process.stdout.write('v1|v1|v1||v1|sha256:' + 'a'.repeat(64) + '\\n'); + if (args[0] === 'image') process.stdout.write('v1|v1||v2|sha256:' + 'a'.repeat(64) + '\\n'); else if (args[0] === 'create') fs.writeFileSync(path.join(root, 'container'), 'waiting'); else if (args[0] === 'start') { for await (const _chunk of process.stdin) {} diff --git a/tests/workerRecovery.test.ts b/tests/workerRecovery.test.ts index 780bd1ac..624e1972 100644 --- a/tests/workerRecovery.test.ts +++ b/tests/workerRecovery.test.ts @@ -29,7 +29,10 @@ const host = vi.hoisted(() => ({ delay: vi.fn(), official: vi.fn(), })); -vi.mock('../src/math/mathBuildManifest', () => ({ readMathBuildManifest: vi.fn() })); +vi.mock('../src/math/mathBuildManifest', async () => ({ + readMathBuildManifest: vi.fn(), + readMathBuildManifestDigest: (await import('./helpers/buildManifest')).fixtureBuildDigest, +})); vi.mock('../src/math/leanDiagnostics', async original => ({ ...(await original()), runLeanDiagnostics: host.prepare, From ce1eccde0128036cda6f2511ba48c24fe3866d8e Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:33:21 +0800 Subject: [PATCH 2/4] Translate the shared team worker capability error --- apps/web/i18n/errors.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/i18n/errors.ts b/apps/web/i18n/errors.ts index 0a1c0f10..d6188fba 100644 --- a/apps/web/i18n/errors.ts +++ b/apps/web/i18n/errors.ts @@ -50,8 +50,8 @@ export const errors: Record = { '原生团队由一名 Lead 自主派工,不能与宿主协作或自定义模块方案一起使用。': 'The Lead coordinates the native team. Host collaboration and custom module plans are unavailable with native teams.', '此研究安排不支持计划审批。': 'This research mode does not support plan approval.', - '当前运行镜像未安装支持原生团队与路线审批的 worker,请更新运行镜像。': - 'Update the worker image to support native teams and route approval.', + '当前运行镜像不支持共享工作区团队与路线审批,请更新运行镜像。': + 'Update the worker image to support teams sharing one workspace and route approval.', '这次运行的 Codex 模型服务已不在配置中。': 'This run’s Codex model provider is no longer configured.', '旧协作任务请使用对应的历史版本继续。新建多人研究使用 Codex 原生团队。': 'Continue old collaboration runs from the matching historical release. New multi-agent runs use Codex native teams.', From 76b1d0fb245296a0a57c421bd96cd8f01518ea5a Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:37:17 +0800 Subject: [PATCH 3/4] Run Codex checkpoint tests in the sandbox-enabled CI job --- .github/workflows/verify.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 746734ab..941cb1c3 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -37,7 +37,7 @@ jobs: - name: Verify account, job, persistence and operations boundaries without models run: bun scripts/frontend.ts run bunx vitest run --maxWorkers=4 tests/webAuth.test.ts tests/webSignup.test.ts tests/webAuthPolicy.test.ts tests/webQuota.test.ts tests/webAdmission.test.ts tests/webAdmissionRace.test.ts tests/webProviderCheck.test.ts tests/webI18n.test.ts tests/webFonts.test.ts tests/webKeyVault.test.ts tests/webJobs.test.ts tests/webLifecyclePersistence.test.ts tests/webCollaboration.test.ts tests/webConversations.test.ts tests/webExplain.test.ts tests/webPersistence.test.ts tests/webFormalizations.test.ts tests/webExplanation.test.ts tests/webExplanationServer.test.ts tests/webServer.test.ts tests/webRunStream.test.ts tests/webRunner.test.ts tests/webPrecheck.test.ts tests/webOperations.test.ts tests/webOperationsApi.test.ts tests/webOperationsScheduled.test.ts tests/webOperationsMonitor.test.ts - name: Verify isolated provider routing and usage accounting without models - run: bun scripts/frontend.ts run bunx vitest run --maxWorkers=4 tests/formalizationRelay.test.ts tests/formalizationReviewIsolation.test.ts tests/webFormalizationWorker.test.ts tests/codexSession.test.ts tests/codexSessionLifecycle.test.ts tests/codexSessionCheckpoint.test.ts tests/codexStreamIdle.test.ts tests/codexSessionNotifications.test.ts tests/mathProcess.test.ts tests/mathRuntimeLease.test.ts tests/mathRuntimeLeaseProcess.test.ts tests/formalization.test.ts tests/formalizationRecovery.test.ts tests/formalizationWorkflow.test.ts tests/formalizationLimits.test.ts tests/formalizationFidelityReference.test.ts + run: bun scripts/frontend.ts run bunx vitest run --maxWorkers=4 tests/formalizationRelay.test.ts tests/formalizationReviewIsolation.test.ts tests/webFormalizationWorker.test.ts tests/codexSession.test.ts tests/codexSessionLifecycle.test.ts tests/codexStreamIdle.test.ts tests/codexSessionNotifications.test.ts tests/mathProcess.test.ts tests/mathRuntimeLease.test.ts tests/mathRuntimeLeaseProcess.test.ts tests/formalization.test.ts tests/formalizationRecovery.test.ts tests/formalizationWorkflow.test.ts tests/formalizationLimits.test.ts tests/formalizationFidelityReference.test.ts - name: Verify research recovery, participation and shared run snapshots run: bun scripts/frontend.ts run bunx vitest run --maxWorkers=4 tests/webRunSnapshot.test.ts tests/webResearchProjects.test.ts tests/webResearchApi.test.ts tests/webResearchAssets.test.ts tests/webResearchMathematics.test.ts tests/libraryPacks.test.ts tests/leanSource.test.ts - name: Verify direct formalization and independent background review without models From 23acdee09f83144fbf0625c6755bbe3e580bb286 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:38:21 +0800 Subject: [PATCH 4/4] Use the runner temporary directory in solver CI --- .github/workflows/verify.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 941cb1c3..1b68bddd 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -185,6 +185,7 @@ jobs: npm install --prefix "$RUNNER_TEMP/codex" @openai/codex@0.172.0 "$RUNNER_TEMP/codex/node_modules/.bin/codex" --version echo "THEOREMOS_TEST_STOCK_CODEX=$RUNNER_TEMP/codex/node_modules/.bin/codex" >> "$GITHUB_ENV" + echo "TMPDIR=$RUNNER_TEMP" >> "$GITHUB_ENV" - name: Verify sealed roles, native team sessions and historical inspection without models if: matrix.lean == '4.36.0' run: bunx vitest run --maxWorkers=1 tests/formalizationSandbox.test.ts tests/formalizationAudit.test.ts tests/agentSessionPlan.test.ts tests/codexSession.test.ts tests/skillRunInspection.test.ts tests/workflowHarness.test.ts tests/agentTeamTransportFallback.test.ts tests/agentTeamSolver.test.ts tests/codexSessionCheckpoint.test.ts