diff --git a/.github/workflows/images.yml b/.github/workflows/images.yml index c4972909..6a4270ae 100644 --- a/.github/workflows/images.yml +++ b/.github/workflows/images.yml @@ -59,13 +59,11 @@ jobs: if: matrix.target == 'web' with: bun-version: 1.4.0 - - run: rustup toolchain install 1.95.0 --profile minimal && rustup override set 1.95.0 - if: matrix.target == 'web' - run: bun install --frozen-lockfile if: matrix.target == 'web' - name: Build the workbench from the pinned frontend if: matrix.target == 'web' - run: bun .frontend-source/frontend/build.ts "$PWD" "$PWD/out" web + run: THEOREMOS_FRONTEND_DIR="$PWD/.frontend-source" bun run build:web - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: diff --git a/.github/workflows/rust-linux.yml b/.github/workflows/rust-linux.yml deleted file mode 100644 index b8b56c3e..00000000 --- a/.github/workflows/rust-linux.yml +++ /dev/null @@ -1,102 +0,0 @@ -name: Rust Linux CLI - -on: - push: - branches: [main, migration/rust] - pull_request: - branches: [main] - workflow_dispatch: - -permissions: - contents: read - -jobs: - linux-cli: - runs-on: ubuntu-24.04 - timeout-minutes: 90 - env: - ELAN_TOOLCHAIN: leanprover/lean4:v4.36.0 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 22 - - uses: oven-sh/setup-bun@v2 - with: - bun-version: 1.4.0 - - name: Prepare the verifier's Linux namespaces and sealed filesystem - run: | - # Mathlib and Lean unpack several GB on this disposable VM. - 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 bubblewrap fuse3 squashfuse squashfs-tools - if [ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then - sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 - fi - test -c /dev/fuse - bwrap --unshare-all --die-with-parent --ro-bind / / --proc /proc --dev /dev -- /bin/true - - name: Install the pinned Lean and Rust toolchains - run: | - sh scripts/install-elan.sh - echo "$HOME/.elan/bin" >> "$GITHUB_PATH" - "$HOME/.elan/bin/elan" toolchain install "$ELAN_TOOLCHAIN" - rustup toolchain install 1.95.0 --profile minimal - - run: bun install --frozen-lockfile - - run: cargo +1.95.0 build --locked --release -p theorem-os --bin theorem-os --bin theorem-os-agent - - name: Package the CLI and replay a Lean proof from the archive - run: | - package=$(bash scripts/package-linux-cli.sh "$RUNNER_TEMP/linux-cli") - (cd "$(dirname "$package")" && sha256sum --check "$(basename "$package").sha256") - install_dir="$RUNNER_TEMP/cli-install" - mkdir -p "$install_dir" - tar -xzf "$package" -C "$install_dir" --strip-components=1 - cd "$install_dir" - export PATH="$HOME/.elan/bin:/usr/bin:/bin" - ./bin/theorem-os --help - ./bin/theorem-os-agent --help - prepared="$RUNNER_TEMP/package-prepare" - ./bin/theorem-os example prepare --dir "$prepared" - jq -e '.mode == "model" and .noExplanations == true' "$prepared/case.json" - manifest=$(jq -er '.buildManifestRef' "$prepared/case.json") - jq -e '.schema == "theorem-os.native-build-manifest.v1"' "$manifest" - ./bin/theorem-os example replay --dir "$RUNNER_TEMP/package-replay" - jq -e '.status == "evaluated_passed" and .modelInvoked == false' "$RUNNER_TEMP/package-replay/summary.json" - echo "THEOREMOS_TEST_CLI=$install_dir/bin/theorem-os" >> "$GITHUB_ENV" - - name: Check committed Lake projects offline - run: cargo +1.95.0 test --locked --release -p theorem-os --test statement -- --ignored - - name: Verify installed single-agent proof and resume with a manual library pack - run: bun scripts/test-native-installed-single.ts - - name: Prepare, preflight, and resume the installed team tutorial - run: bun scripts/test-native-team.ts --installed - - name: Verify an installed team can prove a definition contract - run: bun scripts/test-native-team.ts --installed --definition --check-statement - - name: Verify team route approval and resume - run: bun scripts/test-native-team.ts --installed --approval - - name: Verify checked helper handoffs and reject a wrong nominated type - run: | - bun scripts/test-native-team.ts --installed --handoff - bun scripts/test-native-team.ts --installed --handoff-wrong-type - - name: Install and verify the pinned Mathlib package tree - run: | - workspace="$RUNNER_TEMP/lean436-mathlib" - bun scripts/prepare-web-mathlib.ts "$workspace" - packages="$workspace/.lake/packages" - # The verifier requires Git source outside .lake. Lake may create widget build files. - for package in "$packages"/*; do - git -C "$package" clean -ffdx -- . ':(exclude).lake' - git -C "$package" diff --quiet HEAD - done - echo "THEOREMOS_TEST_LEAN436_PACKAGES=$packages" >> "$GITHUB_ENV" - echo "THEOREMOS_TEST_MATHLIB_IMAGE_CACHE=$RUNNER_TEMP/mathlib-image-cache" >> "$GITHUB_ENV" - - name: Verify standalone team resume with explicit and sealed Mathlib imports - run: | - bun scripts/test-native-team.ts --installed --mathlib --check-statement - bun scripts/test-native-team.ts --installed --full-mathlib - bun scripts/test-native-team.ts --installed --compiled-mathlib - - uses: actions/upload-artifact@v4 - with: - name: linux-cli-x86_64 - path: ${{ runner.temp }}/linux-cli/theorem-os-*.tar.gz* - if-no-files-found: error diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index eae81d8f..9e0bb439 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -17,88 +17,6 @@ permissions: contents: read jobs: - verify-rust: - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: 22 - - uses: oven-sh/setup-bun@v2 - with: - bun-version: 1.4.0 - - name: Prepare namespace sandboxes for native process tests - run: | - sudo apt-get update - sudo apt-get install --yes --no-install-recommends bubblewrap - if [ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then - sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 - fi - - run: rustup toolchain install 1.95.0 --profile minimal --component clippy --component rustfmt - - run: cargo +1.95.0 fmt --all --check - - run: cargo +1.95.0 clippy --locked --workspace --all-targets -- -D warnings - - run: bun install --frozen-lockfile - - run: THEOREMOS_TEST_BUN_PARITY=1 cargo +1.95.0 test --locked --workspace --all-targets - - run: cargo +1.95.0 test --locked --test declarations -- --ignored - - run: cargo +1.95.0 build --locked --release --bins - - run: cargo +1.95.0 build --locked --release -p theoremos-process - - run: cargo +1.95.0 build --locked --release -p theoremos-web - - run: THEOREMOS_WEB_STATIC_ADDON="$PWD/target/release/libtheoremos_web.so" bunx vitest run tests/webStaticFiles.test.ts tests/webServer.test.ts tests/webCommunity.test.ts - - run: THEOREMOS_WEB_DOCKER_HOST="$PWD/target/release/theoremos-web-docker" bunx vitest run tests/webRunner.test.ts tests/webFormalizationWorker.test.ts tests/webFormalizationAuditWorker.test.ts tests/webPaperRunner.test.ts - - run: bun scripts/test-native-web.ts - - run: bun scripts/test-native-informalize.ts - - run: bun scripts/test-native-doctor.ts - - run: bun scripts/test-native-build.ts - - run: THEOREMOS_WEB_ASSETS_BIN="$PWD/target/release/theoremos-web-assets" bun run build:web - - run: THEOREMOS_TEST_INFORMALIZE_CLI="$PWD/target/release/theorem-os" THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/informalization.test.ts tests/informalizeCli.test.ts tests/webExplanation.test.ts - - run: THEOREMOS_TEST_BINARY="$PWD/target/release/theorem-os" THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/formalizationEvaluation.test.ts tests/formalizationAdjudication.test.ts tests/formalizeCli.test.ts tests/formalizationElaboration.test.ts tests/nativeFormalizationCompiler.test.ts tests/directFormalizationWorkflow.test.ts tests/directFormalizationEvidence.test.ts - - run: THEOREMOS_TEST_CLI="$PWD/target/release/theorem-os" bunx vitest run tests/mathBatch.test.ts - - run: bun scripts/test-native-run-options.ts - - run: THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/formalizationSource.test.ts tests/formalizationAudit.test.ts tests/formalizationReviewIsolation.test.ts - - run: bun scripts/test-native-process.ts - - run: THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/responseUsageObserver.test.ts tests/formalizationRelay.test.ts tests/researchCredentialRelay.test.ts tests/codexIsolatedChild.test.ts - - run: bun scripts/test-native-archive.ts - - run: THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/evaluatorExecution.test.ts tests/solverBatchAttribution.test.ts tests/leanDiagnosticCapture.test.ts tests/leanToolchainNative.test.ts tests/leanSource.test.ts tests/sourceContextComments.test.ts tests/verifierToolIdentity.test.ts tests/leanLocalDependencies.test.ts tests/leanModuleBuild.test.ts tests/mathProofLease.test.ts tests/leanDiagnostics.test.ts tests/mathRuntimeEnvironment.test.ts tests/mathRetrievalCorpus.test.ts tests/mathProofEnvironment.test.ts tests/mathProofEnvironmentSeed.test.ts tests/verifierSealedEnvironmentCache.test.ts tests/proofReuseEnvironment.test.ts - - run: bun scripts/generate-native-archive-schema.ts --check - - run: bun scripts/test-native-task-bootstrap.ts - - run: THEOREMOS_TEST_CLI="$PWD/target/release/theorem-os" THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/inspection.test.ts tests/storedRunInspection.test.ts tests/contributionFlow.test.ts tests/solverProgress.test.ts tests/obligationProgress.test.ts tests/recovery.test.ts tests/singleContinuationSeed.test.ts - - run: bun scripts/test-native-edit.ts - - run: bun scripts/test-native-library.ts - - run: bun scripts/test-native-library-catalog.ts - - run: bun scripts/test-native-library-pack.ts - - run: bun scripts/test-native-knowledge.ts - - run: bun scripts/test-native-knowledge-pages.ts - - run: THEOREMOS_TEST_BINARY="$PWD/target/release/theorem-os" THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/autoLibrary.test.ts tests/autoLibraryHost.test.ts tests/autoLibraryUsage.test.ts tests/autoLibraryDemand.test.ts - - run: THEOREMOS_TEST_BINARY="$PWD/target/release/theorem-os" bunx vitest run tests/theoremKnowledgeAuthorization.test.ts tests/theoremKnowledgeRuns.test.ts tests/theoremKnowledgeFindings.test.ts tests/theoremKnowledgeEnrichment.test.ts - - run: bun scripts/generate-native-direct-instructions.ts --check - - run: bun scripts/generate-native-knowledge-schema.ts --check - - run: bun scripts/generate-native-task-environments.ts --check - - run: bun scripts/generate-native-knowledge-collectors.ts --check - - run: bun scripts/generate-native-formalization-queries.ts --check - - run: bun scripts/generate-native-evaluation-review-contracts.ts --check - - run: bun scripts/generate-native-informalization-protocol.ts --check - - run: THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" THEOREMOS_TEST_REVIEW_CLI="$PWD/target/release/theorem-os" bunx vitest run --maxWorkers=3 tests/formalizationReview.test.ts tests/formalizationReviewCli.test.ts tests/formalizationReviewV2.test.ts tests/formalizationReviewV2Runner.test.ts - - run: THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/directFormalizationEvidence.test.ts tests/formalizationCompiledCandidate.test.ts tests/formalizationWorkflow.test.ts tests/formalizationRetrievalWorkflow.test.ts tests/formalizationLibrarySymbolsWorkflow.test.ts tests/formalizationFidelityWorkflow.test.ts - - run: cargo +1.95.0 test --locked -p theoremos-solver --test direct_context -- --ignored - - run: bun scripts/test-native-lean-eval.ts - - name: Compare both pinned public Lean-Eval bootstrap revisions - run: | - git init -q "$RUNNER_TEMP/lean-eval-objects" - git -C "$RUNNER_TEMP/lean-eval-objects" fetch --depth=1 https://github.com/leanprover/lean-eval.git 38361be884302c7edce1908c4aef8296eb2cb27e 4ae7061fe4b0b70dcb7fe24fdee067b68636226b - bun scripts/test-native-eval-bootstrap.ts "$RUNNER_TEMP/lean-eval-objects" - - run: THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/leanTask.test.ts tests/leanEvalBootstrap.test.ts tests/leanEvalBenchmark.test.ts tests/libraryEffectivePack.test.ts tests/libraryHostConfig.test.ts tests/libraryPacks.test.ts tests/libraryLegacyBinding.test.ts tests/leanProbeSnapshot.test.ts - - run: bun scripts/test-native-health.ts - - run: bun scripts/test-native-lean-source.ts - - run: bun scripts/test-native-retrieval.ts - - run: THEOREMOS_TEST_BINARY="$PWD/target/release/theorem-os" bunx vitest run tests/huggingMathBundle.test.ts tests/huggingMathImports.test.ts tests/huggingMathClient.test.ts - - run: THEOREMOS_TEST_BINARY="$PWD/target/release/theorem-os" bunx vitest run tests/firstProofCli.test.ts tests/firstProofAutomation.test.ts tests/firstProof.test.ts - - run: THEOREMOS_TEST_BINARY="$PWD/target/release/theorem-os" bunx vitest run tests/comparisonReportSnapshot.test.ts tests/putnamSample.test.ts tests/moduleExperiment.test.ts tests/comparisonHarness.test.ts tests/comparisonSkillBaseline.test.ts tests/comparisonLeanTask.test.ts - - run: bun scripts/test-native-plan.ts - - run: bun scripts/test-native-continuation.ts - - run: THEOREMOS_TEST_AGENT_BINARY="$PWD/target/release/theorem-os-agent" THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/agentTools.test.ts verify: runs-on: ubuntu-24.04 timeout-minutes: 30 @@ -249,49 +167,25 @@ jobs: jq -e '.status == "evaluated_passed" and .source == "preset-replay" and .modelInvoked == false and .official == false' "$replay/summary.json" - name: Verify solver timeout, recovery, projection and acceptance without models run: bun run test:solver-reliability - - name: Resume native research after process death at each saved checkpoint + - 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 - rustup toolchain install 1.95.0 --profile minimal - cargo +1.95.0 build --release --locked -p theoremos-process - ELAN_TOOLCHAIN=leanprover/lean4:v4.33.0 THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/skillProcessRecovery.test.ts - - name: Replay the native solver with Lean and external evaluator outcomes + run: elan toolchain install leanprover/lean4:v4.33.0 + - name: Verify recovery, proof checking and Codex team handoffs without models if: matrix.lean == '4.36.0' run: | - cargo +1.95.0 build --release --locked --bin theorem-os --bin theorem-os-agent - THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" THEOREMOS_TEST_REFERENCE_LEAN=1 bunx vitest run tests/formalizationAudit.test.ts -t "fixed local relay" - THEOREMOS_TEST_REFERENCE_LEAN=1 THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/informalizationLean.test.ts - bun scripts/test-native-check-lean.ts - bun scripts/generate-native-tutorial-contract.ts --check - bun scripts/test-native-auto-library.ts --online - bun scripts/test-native-https-role.ts - bun scripts/test-native-informalize.ts --online - bun scripts/test-native-formalize.ts - bun scripts/test-native-formalization-review.ts - THEOREMOS_TEST_RECOVERY_LEAN=1 THEOREMOS_TEST_CLI="$PWD/target/release/theorem-os" THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/recovery.test.ts - sudo apt-get install --yes --no-install-recommends squashfuse squashfs-tools fuse3 - cargo +1.95.0 test --locked -p theorem-os --test sealed_image -- --ignored - THEOREMOS_TEST_SEED_LEAN=1 THEOREMOS_TEST_CLI="$PWD/target/release/theorem-os" THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/singleContinuationSeed.test.ts - bun scripts/test-native-startup.ts - THEOREMOS_TEST_PARENT_NET_NS="$(readlink /proc/self/ns/net)" bwrap --unshare-net --bind / / --dev-bind /dev /dev --proc /proc --chdir "$PWD" "$(command -v bun)" scripts/test-native-sub2api.ts - THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/agentTeamWorkspace.test.ts tests/agentTeamNativeControl.test.ts tests/agentTeamNativeLifecycle.test.ts tests/agentTeamSourceRecovery.test.ts - THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/projectionDependencyReview.test.ts tests/solverCompactProjection.test.ts tests/taskSourceProjection.test.ts tests/exactSourceIntegration.test.ts tests/leanDeclarationIdentity.test.ts tests/agentTeamProof.test.ts - THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run --maxWorkers=3 tests/projectionNotation.test.ts tests/taskSourceConditionalContext.test.ts tests/taskSourceImplicitInstances.test.ts tests/taskConditionalUniverses.test.ts tests/conditionalProjectionElaborator.test.ts tests/taskSourceNotationHints.test.ts tests/taskSourceNotationContext.test.ts tests/taskSourceMacroProjection.test.ts - bun scripts/test-native-solver.ts - bun scripts/test-native-team.ts --installed - THEOREMOS_TEST_PARENT_NET_NS="$(readlink /proc/self/ns/net)" bwrap --unshare-net --bind / / --dev-bind /dev /dev --proc /proc --chdir "$PWD" "$(command -v bun)" scripts/test-native-team.ts --sub2api - THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/solver.test.ts tests/solverSourceRecovery.test.ts - cargo +1.95.0 test --locked -p theorem-os --test statement -- --ignored - cargo +1.95.0 test --locked -p theoremos-solver --test proof -- --ignored + 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 - name: Verify dependency snapshots and receipt cache bindings run: bunx vitest run --maxWorkers=4 tests/verifierSealedEnvironmentCache.test.ts tests/mathProofEnvironment.test.ts tests/leanProbeSnapshot.test.ts - name: Verify sealed roles, native team sessions and historical inspection without models if: matrix.lean == '4.36.0' - run: THEOREMOS_TEST_CLI="$PWD/target/release/theorem-os" 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/codexSessionAgentControl.test.ts - name: Verify projected proof contracts and retained source contexts run: bunx vitest run --maxWorkers=4 tests/taskTypeContract.test.ts tests/projectionNotation.test.ts tests/taskSourceImplicitInstances.test.ts tests/taskSourceMacroProjection.test.ts tests/taskSourceNotationHints.test.ts tests/taskSourceNotationContext.test.ts - name: Verify search tools, failure reuse and completed research delivery run: bunx vitest run --maxWorkers=4 tests/declarationSearch.test.ts tests/continuationSearch.test.ts tests/tacticBatteryFailureCache.test.ts tests/codexCompletedResponse.test.ts - name: Verify definition contracts, conditional publication and research continuation - run: bunx vitest run --maxWorkers=4 tests/conditionalProjectionElaborator.test.ts tests/customSolverModules.test.ts tests/definitionContractChecks.test.ts tests/nextCheckNegativeDecisions.test.ts tests/planResearchConnections.test.ts tests/planningEvidence.test.ts tests/solver.test.ts tests/taskConditionalUniverses.test.ts tests/taskSourceConditionalContext.test.ts tests/webModuleIdentity.test.ts + run: bunx vitest run --maxWorkers=4 tests/conditionalProjectionElaborator.test.ts tests/customSolverModules.test.ts tests/definitionContractChecks.test.ts tests/nextCheckNegativeDecisions.test.ts tests/planResearchConnections.test.ts tests/solver.test.ts tests/taskConditionalUniverses.test.ts tests/taskSourceConditionalContext.test.ts tests/webModuleIdentity.test.ts diff --git a/AGENTS.md b/AGENTS.md index 3817f072..0ed969e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,6 +2,8 @@ Keep the CLI and mathematics proof behavior independent of the original DeepScientist checkout. The optional `apps/web` workbench is a separate BYOK HTTP service and Docker supervisor; it must not become a dependency of the CLI or mathematics services. Browser assets and their tests live in the product repository at the revision in `frontend-revision`. There is no Electron or desktop build. +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. Preserve frozen problem/source identities, isolated solver worktrees, Lean receipts, independent evaluation, and resumable runs. A model's completed message is never proof acceptance. diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 08f3971c..00000000 --- a/Cargo.lock +++ /dev/null @@ -1,2672 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" -dependencies = [ - "crypto-common", - "generic-array", -] - -[[package]] -name = "aes" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", -] - -[[package]] -name = "aes-gcm" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" -dependencies = [ - "aead", - "aes", - "cipher", - "ctr", - "ghash", - "subtle", -] - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "alloc-no-stdlib" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" - -[[package]] -name = "alloc-stdlib" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" -dependencies = [ - "alloc-no-stdlib", -] - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "async-compression" -version = "0.4.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "515a1f282e33d55983c499d7e9e87082e81cbc32974825bf9032f928392d5844" -dependencies = [ - "compression-codecs", - "compression-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "base64" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "brotli" -version = "8.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", -] - -[[package]] -name = "brotli-decompressor" -version = "5.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", -] - -[[package]] -name = "bumpalo" -version = "3.20.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" - -[[package]] -name = "bytes" -version = "1.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" - -[[package]] -name = "cc" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "cfg_aliases" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" - -[[package]] -name = "chacha20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "rand_core 0.10.1", -] - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "num-traits", - "windows-link", -] - -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common", - "inout", -] - -[[package]] -name = "compression-codecs" -version = "0.4.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fe67f2944eef52fc7b106b8c9450d243a88701a0c065f7f57235e76abaed7df" -dependencies = [ - "brotli", - "compression-core", - "flate2", - "memchr", - "zstd", - "zstd-safe", -] - -[[package]] -name = "compression-core" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" - -[[package]] -name = "convert_case" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "core_maths" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" -dependencies = [ - "libm", -] - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "typenum", -] - -[[package]] -name = "ctor" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501" -dependencies = [ - "quote", - "syn 2.0.119", -] - -[[package]] -name = "ctr" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" -dependencies = [ - "cipher", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "crypto-common", - "subtle", -] - -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "email-encoding" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f690ae2169f2ceb3f45b28b6fcd8fa16839f2f5c8818546774b9425f5f71004" -dependencies = [ - "base64 0.23.1", - "memchr", -] - -[[package]] -name = "email_address" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ab6bbd053d3cdc62ba3de82aae11530a97bbd5b3a572fbdbcd0f0e545e3ff21" - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "errno" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - -[[package]] -name = "find-msvc-tools" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" - -[[package]] -name = "flate2" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" -dependencies = [ - "crc32fast", - "miniz_oxide", - "zlib-rs", -] - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "form_urlencoded" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-core", - "futures-macro", - "futures-task", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi 6.0.0", - "rand_core 0.10.1", - "wasm-bindgen", -] - -[[package]] -name = "ghash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" -dependencies = [ - "opaque-debug", - "polyval", -] - -[[package]] -name = "hashbrown" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "http" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hyper" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" -dependencies = [ - "atomic-waker", - "bytes", - "futures-core", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "rustls-native-certs", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" -dependencies = [ - "base64 0.23.1", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "httparse", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "icu_collator" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bbdf98e5e0aa827770acee171ebb568aaab975a36b56afdb5fd0e2f525750bb" -dependencies = [ - "icu_collator_data", - "icu_collections", - "icu_locale", - "icu_locale_core", - "icu_normalizer", - "icu_properties", - "icu_provider", - "smallvec", - "utf16_iter", - "utf8_iter", - "zerovec", -] - -[[package]] -name = "icu_collator_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038ed8e5817f2059c2f3efb0945ba78d060d3d25e8f1a1bea5139f821a21a2f0" - -[[package]] -name = "icu_collections" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5a396343c7208121dc86e35623d3dfe19814a7613cfd14964994cdc9c9a2e26" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_locale_data", - "icu_provider", - "potential_utf", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "serde", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_locale_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5fdcc9ac77c6d74ff5cf6e65ef3181d6af32003b16fce3a77fb451d2f695993" - -[[package]] -name = "icu_normalizer" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "utf16_iter", - "utf8_iter", - "write16", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" - -[[package]] -name = "icu_properties" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "serde", - "stable_deref_trait", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_segmenter" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c0794db0b1a86193ac9c48768d0e6c52c54448e0870ad87907d456ee0dac964" -dependencies = [ - "core_maths", - "icu_collections", - "icu_locale", - "icu_provider", - "icu_segmenter_data", - "potential_utf", - "utf8_iter", - "zerovec", -] - -[[package]] -name = "icu_segmenter_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a2c462a4d927d512f5f882a033ddd62f33a05bb9f230d98f736ac3dc85938f" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "generic-array", -] - -[[package]] -name = "ipnet" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" - -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - -[[package]] -name = "jobserver" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" -dependencies = [ - "getrandom 0.3.4", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "lettre" -version = "0.11.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15000d8223b52e56d577590183331413c0ef732ebdd9c9b6aebce15824aba899" -dependencies = [ - "base64 0.23.1", - "email-encoding", - "email_address", - "fastrand", - "httpdate", - "idna", - "mime", - "nom", - "percent-encoding", - "quoted_printable", - "rustls", - "socket2", - "tokio", - "url", - "webpki-roots", -] - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link", -] - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - -[[package]] -name = "lru-slab" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "mime" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "1.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "napi" -version = "2.16.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3" -dependencies = [ - "bitflags", - "ctor", - "napi-derive", - "napi-sys", - "once_cell", - "serde", - "serde_json", -] - -[[package]] -name = "napi-derive" -version = "2.16.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c" -dependencies = [ - "cfg-if", - "convert_case", - "napi-derive-backend", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "napi-derive-backend" -version = "1.0.75" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf" -dependencies = [ - "convert_case", - "once_cell", - "proc-macro2", - "quote", - "regex", - "semver", - "syn 2.0.119", -] - -[[package]] -name = "napi-sys" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3" -dependencies = [ - "libloading", -] - -[[package]] -name = "nom" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" -dependencies = [ - "memchr", -] - -[[package]] -name = "num-bigint" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-integer" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - -[[package]] -name = "openssl-probe" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" - -[[package]] -name = "pbkdf2" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" -dependencies = [ - "digest", - "hmac", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pin-project-lite" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" - -[[package]] -name = "pkg-config" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" - -[[package]] -name = "polyval" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "opaque-debug", - "universal-hash", -] - -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "serde_core", - "writeable", - "zerovec", -] - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quinn" -version = "0.11.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" -dependencies = [ - "bytes", - "cfg_aliases", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash", - "rustls", - "socket2", - "thiserror", - "tokio", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-proto" -version = "0.11.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" -dependencies = [ - "bytes", - "getrandom 0.4.3", - "lru-slab", - "rand 0.10.4", - "rand_pcg", - "ring", - "rustc-hash", - "rustls", - "rustls-pki-types", - "slab", - "thiserror", - "tinyvec", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-udp" -version = "0.5.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" -dependencies = [ - "cfg_aliases", - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.52.0", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "quoted_printable" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972" - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" -dependencies = [ - "libc", - "rand_chacha", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" -dependencies = [ - "chacha20", - "getrandom 0.4.3", - "rand_core 0.10.1", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "rand_pcg" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" -dependencies = [ - "rand_core 0.10.1", -] - -[[package]] -name = "regex" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" - -[[package]] -name = "reqwest" -version = "0.12.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-native-certs", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustix" -version = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" -dependencies = [ - "log", - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" -dependencies = [ - "openssl-probe", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pki-types" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" -dependencies = [ - "web-time", - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[package]] -name = "ryu-js" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f232fd0249f55adbe7f15bee58bbbd3d40708000b84e6482066d2ba599e08a9" - -[[package]] -name = "salsa20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" -dependencies = [ - "cipher", -] - -[[package]] -name = "schannel" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "scrypt" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" -dependencies = [ - "pbkdf2", - "salsa20", - "sha2", -] - -[[package]] -name = "security-framework" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" -dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "foldhash", - "indexmap", - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_spanned" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" -dependencies = [ - "serde_core", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" - -[[package]] -name = "socket2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.3", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "theorem-os" -version = "0.1.0" -dependencies = [ - "chrono", - "futures-util", - "http-body-util", - "hyper", - "hyper-util", - "icu_collator", - "icu_properties", - "icu_segmenter", - "libc", - "memchr", - "num-bigint", - "num-traits", - "regex", - "ryu-js", - "serde", - "serde_json", - "sha1", - "sha2", - "subtle", - "tempfile", - "theoremos-lean", - "theoremos-library", - "theoremos-retrieval", - "theoremos-solver", - "theoremos-supervision", - "tokio", - "toml", - "unicode-normalization", - "url", -] - -[[package]] -name = "theoremos-lean" -version = "0.1.0" -dependencies = [ - "hmac", - "libc", - "regex", - "ryu-js", - "serde", - "serde_json", - "sha2", - "tempfile", - "theoremos-supervision", - "tokio", - "toml", -] - -[[package]] -name = "theoremos-library" -version = "0.1.0" -dependencies = [ - "base64 0.22.1", - "chrono", - "crc32fast", - "flate2", - "icu_collator", - "icu_properties", - "icu_segmenter", - "libc", - "regex", - "ryu-js", - "serde", - "serde_json", - "sha2", - "tempfile", - "theoremos-lean", - "theoremos-solver", - "tokio", - "unicode-normalization", - "ureq", - "url", -] - -[[package]] -name = "theoremos-process" -version = "0.1.0" -dependencies = [ - "libc", - "napi", - "napi-derive", - "regex", - "serde", - "serde_json", - "tempfile", - "theoremos-lean", - "theoremos-library", - "theoremos-retrieval", - "theoremos-solver", - "theoremos-supervision", - "tokio", -] - -[[package]] -name = "theoremos-retrieval" -version = "0.1.0" -dependencies = [ - "base64 0.22.1", - "brotli", - "hmac", - "libc", - "regex", - "serde", - "serde_json", - "sha2", - "tempfile", - "theoremos-lean", - "toml", - "unicode-normalization", -] - -[[package]] -name = "theoremos-solver" -version = "0.1.0" -dependencies = [ - "libc", - "regex", - "reqwest", - "serde", - "serde_json", - "sha2", - "tempfile", - "theoremos-lean", - "theoremos-supervision", - "tokio", - "toml", -] - -[[package]] -name = "theoremos-supervision" -version = "0.1.0" -dependencies = [ - "libc", - "serde_json", - "sha2", - "tokio", -] - -[[package]] -name = "theoremos-web" -version = "0.1.0" -dependencies = [ - "aes-gcm", - "base64 0.22.1", - "brotli", - "chrono", - "flate2", - "hmac", - "http-body-util", - "hyper", - "hyper-util", - "icu_collator", - "icu_locale_core", - "icu_normalizer", - "lettre", - "libc", - "napi", - "napi-derive", - "percent-encoding", - "rand 0.8.8", - "regex", - "scrypt", - "serde", - "serde_json", - "sha2", - "subtle", - "tempfile", - "theoremos-lean", - "theoremos-library", - "tokio", - "url", -] - -[[package]] -name = "thiserror" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "serde_core", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.54.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" -dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.9.12+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" -dependencies = [ - "indexmap", - "serde_core", - "serde_spanned", - "toml_datetime", - "toml_parser", - "toml_writer", - "winnow 0.7.15", -] - -[[package]] -name = "toml_datetime" -version = "0.7.5+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" -dependencies = [ - "serde_core", -] - -[[package]] -name = "toml_parser" -version = "1.1.7+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" -dependencies = [ - "winnow 1.0.5", -] - -[[package]] -name = "toml_writer" -version = "1.2.0+spec-1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" - -[[package]] -name = "tower" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" -dependencies = [ - "futures-core", - "futures-util", - "pin-project-lite", - "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.6.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68d6fdd9f81c2819c9a8b0e0cd91660e7746a8e6ea2ba7c6b2b057985f6bcb51" -dependencies = [ - "async-compression", - "bitflags", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "pin-project-lite", - "tokio", - "tokio-util", - "tower", - "tower-layer", - "tower-service", - "url", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "pin-project-lite", - "tracing-core", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - -[[package]] -name = "universal-hash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common", - "subtle", -] - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "ureq" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0" -dependencies = [ - "base64 0.22.1", - "flate2", - "log", - "percent-encoding", - "rustls", - "rustls-pki-types", - "ureq-proto", - "utf8-zero", - "webpki-roots", -] - -[[package]] -name = "ureq-proto" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c" -dependencies = [ - "base64 0.22.1", - "http", - "httparse", - "log", -] - -[[package]] -name = "url" -version = "2.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf16_iter" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" -dependencies = [ - "utf_types", -] - -[[package]] -name = "utf8-zero" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf_types" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "want" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" -dependencies = [ - "cfg-if", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" -dependencies = [ - "js-sys", - "tokio", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.10", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "web-sys" -version = "0.3.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "1.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" - -[[package]] -name = "winnow" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "write16" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" - -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - -[[package]] -name = "yoke" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.8.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" - -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "serde", - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zlib-rs" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" - -[[package]] -name = "zstd" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" -dependencies = [ - "zstd-safe", -] - -[[package]] -name = "zstd-safe" -version = "7.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" -dependencies = [ - "zstd-sys", -] - -[[package]] -name = "zstd-sys" -version = "2.1.2+zstd.1.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" -dependencies = [ - "cc", - "pkg-config", -] diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index bbaed01e..00000000 --- a/Cargo.toml +++ /dev/null @@ -1,3 +0,0 @@ -[workspace] -members = ["rust/supervision", "rust/lean", "rust/cli", "rust/process", "rust/web", "rust/solver", "rust/retrieval", "rust/library"] -resolver = "2" diff --git a/README.md b/README.md index 29dbd0b1..e061ea41 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # TheoremOS -The first Rust release focuses on the Linux CLI. It runs single agents and live teams, resumes saved runs, mounts manually selected Lean library packs, and checks proofs independently with Lean. The browser workbench is deferred. See the [Rust CLI quick start](docs/rust-migration.md). +The Rust CLI and its build instructions are maintained on the [migration/rust branch](https://github.com/HuggingMath/theorem-os-harness/tree/migration/rust). English · [简体中文](README.zh-CN.md) @@ -18,20 +18,20 @@ TheoremOS is a Lean 4 research workbench from [WestlakeNLP, Westlake University] ## Quick start -Run a proof check without a model key or Mathlib. The Rust example needs Linux, Rust 1.95 or later, Git, Bubblewrap with user namespaces enabled, and Elan. +Run a proof check without a model key or Mathlib. On Linux, install Bun, Git, Bubblewrap with user namespaces enabled, and Elan. ```bash -cargo build --locked --release -p theorem-os --bins +bun install --frozen-lockfile elan toolchain install leanprover/lean4:v4.36.0 -./target/release/theorem-os doctor --lean-only +bun run math doctor --lean-only # Choose a new directory outside the checkout. export THEOREMOS_REPLAY="$PWD/../theorem-os-runs/first-replay" -./target/release/theorem-os example replay --dir "$THEOREMOS_REPLAY" -./target/release/theorem-os inspect --run "$THEOREMOS_REPLAY/result.json" +bun run math example replay --dir "$THEOREMOS_REPLAY" +bun run math inspect --run "$THEOREMOS_REPLAY/result.json" ``` -Lean rejects the first candidate on `0 + n = n`. The second uses `Nat.zero_add` and passes both goals. A successful replay reports `evaluated_passed` and `official: false`. The example supplies both candidates (`modelInvoked: false`). To run an agent or a team on your own problem, follow the [Rust CLI guide](docs/rust-migration.md). +Lean rejects the first candidate on `0 + n = n`. The second uses `Nat.zero_add` and passes both goals. A successful replay reports `evaluated_passed` and `official: false`. The example supplies both candidates (`modelInvoked: false`). To run an agent or a team on your own problem, follow the [CLI guide](docs/usage.md). ## Find your way around diff --git a/README.zh-CN.md b/README.zh-CN.md index e1b7002e..70612f7d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,6 +1,6 @@ # TheoremOS -Rust 首版面向 Linux 命令行,支持单人求解、在线组队、Lean 独立验收、续跑和手动选用库包。浏览器工作台后置。参见 [Rust CLI 快速开始](docs/rust-migration.md)。 +Rust CLI 的实现和构建说明保存在 [migration/rust 分支](https://github.com/HuggingMath/theorem-os-harness/tree/migration/rust)。 [English](README.md) · 简体中文 @@ -16,20 +16,20 @@ TheoremOS 是[西湖大学 WestlakeNLP 实验室](https://westlakenlp.com/)开 ## 快速开始 -先在本机验证一个小证明。这个例子不需要模型密钥,也不下载 Mathlib。需要 Linux、Rust 1.95 或更新版本、Git、能创建用户命名空间的 Bubblewrap,以及 Elan。 +先在本机验证一个小证明。这个例子不需要模型密钥,也不下载 Mathlib。需要 Linux、Bun、Git、能创建用户命名空间的 Bubblewrap,以及 Elan。 ```bash -cargo build --locked --release -p theorem-os --bins +bun install --frozen-lockfile elan toolchain install leanprover/lean4:v4.36.0 -./target/release/theorem-os doctor --lean-only +bun run math doctor --lean-only # 选择仓库外尚未使用的目录。 export THEOREMOS_REPLAY="$PWD/../theorem-os-runs/first-replay" -./target/release/theorem-os example replay --dir "$THEOREMOS_REPLAY" -./target/release/theorem-os inspect --run "$THEOREMOS_REPLAY/result.json" +bun run math example replay --dir "$THEOREMOS_REPLAY" +bun run math inspect --run "$THEOREMOS_REPLAY/result.json" ``` -第一次尝试在 `0 + n = n` 处被 Lean 拒绝。第二次用 `Nat.zero_add` 修复,两个目标都通过。成功时状态为 `evaluated_passed`,本地验收标为 `official: false`。两次候选都由示例提供(`modelInvoked: false`)。要把自己的题交给单个 Agent 或研究团队,接着看 [Rust CLI 指南](docs/rust-migration.md)。 +第一次尝试在 `0 + n = n` 处被 Lean 拒绝。第二次用 `Nat.zero_add` 修复,两个目标都通过。成功时状态为 `evaluated_passed`,本地验收标为 `official: false`。两次候选都由示例提供(`modelInvoked: false`)。要把自己的题交给单个 Agent 或研究团队,接着看 [CLI 指南](docs/usage.md)。 ## 按任务找入口 diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index c9809315..3ad0eeb4 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -1,17 +1,6 @@ FROM oven/bun:1.4.0 AS bun FROM docker:29-cli AS docker-cli -FROM rust:1.99.1-bookworm AS native-agent-tools -WORKDIR /build -COPY Cargo.toml Cargo.lock ./ -COPY rust/ rust/ -COPY src/math/runtimeEnvironmentKeys.json src/math/runtimeEnvironmentKeys.json -COPY src/math/mathlibTheoremAliasData.json src/math/mathSearchConceptData.json src/math/mathlibAdditiveData.json src/math/ -COPY resources/ resources/ -RUN cargo build --locked --release --bin theorem-os --bin theorem-os-agent \ - && cargo build --locked --release -p theoremos-process \ - && cargo build --locked --release -p theoremos-web --bin theoremos-web-check - # 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 @@ -44,7 +33,6 @@ COPY scripts ./scripts COPY skills ./skills COPY resources ./resources COPY apps ./apps -COPY rust/web/community-limits.json rust/web/trajectory.json ./rust/web/ COPY LICENSE NOTICE CITATION.cff ./ COPY LICENSES ./LICENSES COPY third_party ./third_party @@ -93,9 +81,6 @@ COPY scripts/pantograph/ ./scripts/pantograph/ RUN bun scripts/build-pantograph.ts /opt/theoremos-pantograph FROM worker-mathlib AS worker -COPY --from=native-agent-tools /build/target/release/theoremos-web-check /usr/local/libexec/theoremos-web-check -COPY --from=native-agent-tools /build/target/release/theorem-os /usr/local/bin/theorem-os -COPY --from=native-agent-tools /build/target/release/theorem-os-agent /usr/local/libexec/theorem-os-agent ENV TMPDIR=/tmp \ PATH=/opt/elan/toolchains/leanprover--lean4---v4.36.0/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin \ DEEPSCIENTIST_MATH_TRUSTED_ELAN_ROOTS=/opt/elan/toolchains/leanprover--lean4---v4.36.0 \ @@ -105,9 +90,8 @@ RUN bun scripts/prepare-web-library.ts \ && chmod -R a+rX /opt/theoremos-library # Use the installed binaries directly: the verifier mounts the toolchain read-only. # Agent shells cannot read /opt/theorem-os or /opt/runtime-state; they run the bundled commands instead. -RUN --mount=type=bind,from=native-agent-tools,source=/build/target/release/libtheoremos_process.so,target=/opt/theoremos-process.so \ - theorem-os build --root /opt/theorem-os --state-root /opt/runtime-state --native-process /opt/theoremos-process.so > /opt/theoremos-build.json \ - && bun scripts/build-agent-tools.ts --out /opt/theoremos-agent-tools --rust-tools /usr/local/libexec/theorem-os-agent --native-process /opt/theoremos-process.so > /dev/null \ +RUN bun scripts/build.ts --state-root /opt/runtime-state > /opt/theoremos-build.json \ + && bun scripts/build-agent-tools.ts --out /opt/theoremos-agent-tools > /dev/null \ && bun scripts/build-proof-environment-seed.ts --project /opt/theoremos-mathlib \ --packages /opt/theoremos-mathlib/.lake/packages --out /opt/theoremos-proof-environment-seed \ && bun scripts/build-proof-environment-seed.ts --project /opt/theoremos-mathlib \ @@ -132,17 +116,7 @@ LABEL org.theoremos.team-expert-cards=v1 LABEL org.theoremos.worker-control=v1 ENTRYPOINT ["/opt/theorem-os/apps/web/worker-entrypoint.sh"] -FROM native-agent-tools AS native-web-static -RUN cargo build --locked --release -p theoremos-web - FROM source AS web -COPY --from=native-web-static /build/target/release/libtheoremos_web.so /usr/local/libexec/theoremos-web.node -COPY --from=native-web-static /build/target/release/theoremos-web /usr/local/bin/theoremos-web -COPY --from=native-web-static /build/target/release/theoremos-web-assets /usr/local/libexec/theoremos-web-assets -COPY --from=native-web-static /build/target/release/theoremos-web-docker /usr/local/libexec/theoremos-web-docker -ENV THEOREMOS_WEB_DOCKER_HOST=/usr/local/libexec/theoremos-web-docker \ - THEOREMOS_WEB_STATIC_ADDON=/usr/local/libexec/theoremos-web.node \ - THEOREMOS_WEB_ASSETS_BIN=/usr/local/libexec/theoremos-web-assets COPY --from=docker-cli /usr/local/bin/docker /usr/local/bin/docker COPY out/web ./out/web COPY out/web-report ./out/web-report @@ -150,4 +124,4 @@ ARG THEOREMOS_SOURCE_COMMIT=unknown LABEL org.opencontainers.image.revision=$THEOREMOS_SOURCE_COMMIT ENV THEOREMOS_WEB_HOST=0.0.0.0 THEOREMOS_WEB_PORT=8787 THEOREMOS_SOURCE_COMMIT=$THEOREMOS_SOURCE_COMMIT EXPOSE 8787 -CMD ["theoremos-web"] +CMD ["bun", "apps/web/server.ts"] diff --git a/rust/web/community-limits.json b/apps/web/community-limits.json similarity index 100% rename from rust/web/community-limits.json rename to apps/web/community-limits.json diff --git a/apps/web/community.ts b/apps/web/community.ts index bca80cdf..db1a5308 100644 --- a/apps/web/community.ts +++ b/apps/web/community.ts @@ -36,8 +36,8 @@ type Activity = CommunityActivity; type Profile = { handle: string; createdAt: string; tokenDigest?: string; tokenCreatedAt?: string }; type Claim = { owner: string; claimedAt: string; expiresAt: string }; -export { default as communityLimits } from '../../rust/web/community-limits.json'; -import communityLimits from '../../rust/web/community-limits.json'; +export { default as communityLimits } from './community-limits.json'; +import communityLimits from './community-limits.json'; export const communityTokenPattern = /^tosc_[a-f0-9]{64}$/u; const fail = (status: number, text: string): never => { throw new WebStorageError(status, text); diff --git a/apps/web/config.ts b/apps/web/config.ts index f9e0f7ff..013fa94b 100644 --- a/apps/web/config.ts +++ b/apps/web/config.ts @@ -11,7 +11,6 @@ import { } from './shared'; import { allowlistFile, normalizeEmail, type WebAuthConfig, type WebSignupMode } from './auth'; import { webQuotaDefaults, type WebQuotaLimits } from './quota'; -import { cliConfigurationSchema } from '../../src/runtime/cliConfiguration'; import { researchExamples } from './problemExamples'; import { webTaskEnvironment, webTaskEnvironmentName, webTaskEnvironmentDescription } from './environment'; @@ -20,64 +19,13 @@ const providerSchema = z id: z.string().regex(/^[a-z][a-z0-9-]{0,39}$/), name: z.string().trim().min(1).max(80), baseUrl: z.string().url().max(512), - harness: z.enum(['codex', 'claude-code', 'opencode', 'cli']).optional(), + harness: z.literal('codex').optional(), execution: z - .object({ - executable: z.string().min(1).max(4096).optional(), - cli: cliConfigurationSchema.optional(), - files: z - .record(z.string().min(1).max(4096), z.string().max(256 * 1024)) - .refine(files => Object.keys(files).length <= 64) - .optional(), - apiKeyEnvironment: z - .string() - .regex(/^[A-Z][A-Z0-9_]{0,63}$/u) - .optional(), - baseUrlEnvironment: z - .string() - .regex(/^[A-Z][A-Z0-9_]{0,63}$/u) - .optional(), - }) + .object({ executable: z.string().min(1).max(4096).optional() }) .strict() .optional(), }) - .strict() - .superRefine((provider, ctx) => { - if ( - provider.harness === 'cli' - ? !provider.execution?.cli - : provider.execution?.cli || - provider.execution?.files || - provider.execution?.apiKeyEnvironment || - provider.execution?.baseUrlEnvironment - ) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CLI launch configuration requires a CLI provider.' }); - const research = provider.execution?.cli?.researchProvider; - if ( - provider.execution?.cli && - (research?.apiKeyEnvironment !== (provider.execution.apiKeyEnvironment ?? 'OPENAI_API_KEY') || - research.baseUrlEnvironment !== (provider.execution.baseUrlEnvironment ?? 'OPENAI_BASE_URL')) - ) - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'CLI providers must declare researchProvider for their key and base URL variables.', - }); - for (const name of Object.keys(provider.execution?.files ?? {})) - if ( - path.isAbsolute(name) || - name.split(/[\\/]/u).some(part => !part || part === '..' || part === '.') || - name === 'cli.json' - ) - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'CLI configuration file paths must be relative ordinary files.', - }); - for (const name of [provider.execution?.apiKeyEnvironment, provider.execution?.baseUrlEnvironment].filter(Boolean)) - if ( - /^(?:HOME|PATH|TMPDIR|TMP|TEMP|ELAN_HOME|LAKE_HOME|LEAN_.+|XDG_.+|DEEPSCIENTIST_.+|THEOREMOS_.+)$/u.test(name!) - ) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Runtime environment names are reserved.' }); - }); + .strict(); export type WebConfig = { host: string; diff --git a/apps/web/formalizationWorker.ts b/apps/web/formalizationWorker.ts index 5e1697d7..f9b69499 100644 --- a/apps/web/formalizationWorker.ts +++ b/apps/web/formalizationWorker.ts @@ -23,7 +23,6 @@ import { elaborateFormalization } from '../../src/solver/formalizationElaboratio import { reportedTotalTokens } from '../../src/solver/usageBudget'; import { startGatewayForwarder } from './explanationWorker'; import { createFormalizationActivity } from './formalizationActivity'; -import { webHarnessExecutable } from './harness'; import { prepareWebProviderProfile } from './worker'; import { webAgentLibraryAccess } from './frozenLibrary'; import { @@ -274,7 +273,8 @@ async function main() { executable: input.provider.execution?.executable ?? process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE ?? - webHarnessExecutable(input.provider), + input.provider.execution?.executable ?? + 'codex', model: input.model, effort: input.effort, buildManifestRef: buildIndex.buildManifestRef, @@ -299,7 +299,8 @@ async function main() { buildIndex.buildManifestRef, input.provider.execution?.executable ?? process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE ?? - webHarnessExecutable(input.provider), + input.provider.execution?.executable ?? + 'codex', ), ...(libraryCatalog ? { libraryCatalog } : {}), }); diff --git a/apps/web/harness.ts b/apps/web/harness.ts index fdc5c17b..01a2df0e 100644 --- a/apps/web/harness.ts +++ b/apps/web/harness.ts @@ -1,228 +1,24 @@ -import fs from 'node:fs'; -import path from 'node:path'; -import { canonicalMathJson, mathDigest, readMathJson, writeMathJsonDurable } from '../../src/math/mathRuntimeIo'; -import { assertMathCanonicalPath } from '../../src/math/paths'; -import type { MathAgentOptions, MathAgentSession } from '../../src/runtime/agentSession'; -import { - bindResearchHarness, - assertResearchHarnessCurrent, - type ResearchHarnessIdentity, -} from '../../src/runtime/researchHarness'; -import { cliConfigurationSchema, readCliConfiguration } from '../../src/runtime/cliConfiguration'; +import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo'; import type { WebProvider, WebRunInput, WebWorkerProvider } from './shared'; -const webCliConfiguration = (provider: WebWorkerProvider) => - provider.execution?.cli ? cliConfigurationSchema.parse(provider.execution.cli) : undefined; - -/** Only the operator's provider declaration chooses a command; browser input never supplies argv or local paths. */ -export const webProviderHarness = (provider: WebProvider) => provider.harness ?? 'codex'; -export function publicWebProvider(provider: WebProvider): WebProvider { - return { - id: provider.id, - name: provider.name, - baseUrl: provider.baseUrl, - ...(provider.harness ? { harness: provider.harness } : {}), - ...(provider.harness === 'cli' && 'execution' in provider - ? { - efforts: webCliConfiguration(provider as WebWorkerProvider)?.efforts.filter(effort => - ['none', 'low', 'medium', 'high', 'xhigh', 'max'].includes(effort), - ) as WebRunInput['effort'][], - } - : {}), - }; +export function publicWebProvider({ id, name, baseUrl, harness }: WebProvider): WebProvider { + return { id, name, baseUrl, ...(harness ? { harness } : {}) }; } + export function webProviderExecutionDigest(provider: WebWorkerProvider): string { return mathDigest( canonicalMathJson({ - harness: webProviderHarness(provider), + harness: provider.harness ?? 'codex', execution: provider.execution ?? null, baseUrl: provider.baseUrl, }), ); } -export function webHarnessExecutable(provider: WebWorkerProvider): string { - const id = webProviderHarness(provider); - return ( - provider.execution?.executable ?? - (id === 'cli' ? (webCliConfiguration(provider)?.executable ?? '') : id === 'claude-code' ? 'claude' : id) - ); -} -/** Web model names belong to the selected provider; OpenCode additionally needs its local provider namespace. */ -export const webHarnessModel = (provider: WebProvider, model: string) => - webProviderHarness(provider) === 'opencode' ? `web/${model}` : model; - -export function webHarnessEnvironment(provider: WebWorkerProvider, apiKey: string): NodeJS.ProcessEnv { - switch (webProviderHarness(provider)) { - case 'codex': - return { THEOREMOS_PROVIDER_API_KEY: apiKey }; - case 'claude-code': - return { ANTHROPIC_API_KEY: apiKey, ANTHROPIC_BASE_URL: provider.baseUrl.replace(/\/v1\/?$/u, '') }; - case 'opencode': - return { OPENAI_API_KEY: apiKey }; - case 'cli': - return { - [provider.execution?.apiKeyEnvironment ?? 'OPENAI_API_KEY']: apiKey, - [provider.execution?.baseUrlEnvironment ?? 'OPENAI_BASE_URL']: provider.baseUrl, - }; - } -} - -/** New dedicated profiles contain generated launch settings only, never a machine's authentication/session files. */ -export function prepareWebNativeProfile( - profile: string, - provider: WebWorkerProvider, - input: Pick, -): void { - fs.mkdirSync(profile, { mode: 0o700 }); - const write = (file: string, text: string) => - fs.writeFileSync(path.join(profile, file), text, { mode: 0o600, flag: 'wx' }); - switch (webProviderHarness(provider)) { - case 'codex': - throw new Error('web_codex_profile_requires_provider_configuration'); - case 'claude-code': - write('settings.json', '{}'); - return; - case 'opencode': - write( - 'opencode.json', - JSON.stringify({ - provider: { - web: { - name: provider.name, - npm: '@ai-sdk/openai', - options: { baseURL: provider.baseUrl, apiKey: '{env:OPENAI_API_KEY}' }, - models: { - [input.model]: { name: input.model, variants: { [input.effort]: { reasoningEffort: input.effort } } }, - }, - }, - }, - }), - ); - return; - case 'cli': { - const configuration = webCliConfiguration(provider); - if (!configuration) throw new Error('web_cli_configuration_missing'); - for (const [file, text] of Object.entries(provider.execution?.files ?? {})) { - const target = path.resolve(profile, file); - if ( - path.isAbsolute(file) || - !target.startsWith(profile + path.sep) || - file.split(/[\\/]/u).some(part => !part || part === '.' || part === '..') || - file === 'cli.json' - ) - throw new Error('web_cli_configuration_path_invalid'); - fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 }); - write(file, text); - } - write('cli.json', JSON.stringify(configuration)); - const actual = readCliConfiguration(profile); - const key = provider.execution?.apiKeyEnvironment ?? 'OPENAI_API_KEY'; - const base = provider.execution?.baseUrlEnvironment ?? 'OPENAI_BASE_URL'; - if ( - !actual.inheritEnvironment.includes(key) || - !actual.inheritEnvironment.includes(base) || - Object.hasOwn(actual.environment, key) || - Object.hasOwn(actual.environment, base) - ) - throw new Error('web_cli_provider_environment_unbound'); - // The BYOK key reaches the native client only through the host research relay. - if (actual.researchProvider?.apiKeyEnvironment !== key || actual.researchProvider.baseUrlEnvironment !== base) - throw new Error('web_cli_research_provider_unbound'); - if (!actual.efforts.includes(input.effort)) throw new Error('math_cli_effort_unsupported'); - return; - } - } -} - -type BoundProfile = { profile: string; identity: ResearchHarnessIdentity; assertCurrent(): void }; -/** Each writer gets separate native mutable state; its immutable settings and executable remain frozen. */ -export function bindWebWorkerProfile(options: MathAgentOptions, provider: WebWorkerProvider): BoundProfile { - const id = webProviderHarness(provider), - parent = fs.realpathSync(options.profile); - const environment = { ...options.environment, ...webHarnessEnvironment(provider, '') }; - // Binding ignores credential values, but includes endpoint environment identity. - const rootIdentity = bindResearchHarness(id, options.executable, parent, environment, options.model); - const name = mathDigest(options.workspace).slice(0, 32), - directory = path.join(path.dirname(parent), 'native-sessions'); - assertMathCanonicalPath(directory); - fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); - const profile = path.join(directory, name), - bindingFile = path.join(directory, name + '.binding.json'); - assertMathCanonicalPath(profile); - assertMathCanonicalPath(bindingFile); - if (!fs.existsSync(bindingFile)) { - // No binding means no session ever used this profile; discard a copy left by an interrupted initialization. - fs.rmSync(profile, { recursive: true, force: true }); - fs.mkdirSync(profile, { mode: 0o700 }); - const names = - id === 'claude-code' - ? ['settings.json'] - : id === 'opencode' - ? ['opencode.json'] - : ['cli.json', ...readCliConfiguration(parent).configurationFiles]; - for (const file of names) { - fs.mkdirSync(path.dirname(path.join(profile, file)), { recursive: true, mode: 0o700 }); - fs.writeFileSync(path.join(profile, file), fs.readFileSync(path.join(parent, file)), { mode: 0o600, flag: 'wx' }); - } - const identity = bindResearchHarness(id, options.executable, profile, environment, options.model); - writeMathJsonDurable(bindingFile, { rootIdentity, identity }); - } - const saved = readMathJson(bindingFile) as { - rootIdentity: ResearchHarnessIdentity; - identity: ResearchHarnessIdentity; - }; - if (canonicalMathJson(saved.rootIdentity) !== canonicalMathJson(rootIdentity) || saved.identity.profile !== profile) - throw new Error('math_harness_identity_changed'); - const snapshot = canonicalMathJson(saved); - const assertCurrent = () => { - if (canonicalMathJson(readMathJson(bindingFile)) !== snapshot) throw new Error('math_harness_identity_changed'); - assertResearchHarnessCurrent(rootIdentity, environment, options.model); - assertResearchHarnessCurrent(saved.identity, environment, options.model); - }; - assertCurrent(); - return { profile, identity: saved.identity, assertCurrent }; -} - -/** Keep configuration changes from being accepted after native execution or writer shutdown. */ -export function pinWebWorkerSession(session: MathAgentSession, binding: BoundProfile): MathAgentSession { - const run = session.run, - close = session.close, - stop = session.stopForFreeze; - session.run = async (...args) => { - binding.assertCurrent(); - const result = await run(...args); - binding.assertCurrent(); - return result; - }; - session.close = async () => { - await close(); - binding.assertCurrent(); - }; - if (stop) - session.stopForFreeze = async () => { - const result = await stop(); - binding.assertCurrent(); - return result; - }; - const receipt = Object.getOwnPropertyDescriptor(session, 'isolationReceipt'); - Object.defineProperty(session, 'isolationReceipt', { - enumerable: true, - configurable: true, - get: () => ({ - ...(receipt?.get ? receipt.get.call(session) : receipt?.value), - harnessIdentity: binding.identity, - }), - }); - return session; -} export function webHarnessResearchError( provider: WebWorkerProvider, - input: Pick, + input: Pick, ): string | undefined { - const id = webProviderHarness(provider); - if (id !== 'codex' && (input.researchMode !== 'skill' || input.skillLoading === 'native')) - return '当前执行器需要读取固定文件的 Skill 研究方式。'; - if (id === 'cli' ? !webCliConfiguration(provider)?.efforts.includes(input.effort) : input.effort === 'none') - return '当前执行器不支持所选推理强度。'; + if (provider.harness && provider.harness !== 'codex') return '此版本只支持 Codex 执行器。'; + if (input.effort === 'none') return '当前执行器不支持所选推理强度。'; } diff --git a/apps/web/i18n/errors.ts b/apps/web/i18n/errors.ts index 72fda556..3cef686f 100644 --- a/apps/web/i18n/errors.ts +++ b/apps/web/i18n/errors.ts @@ -35,7 +35,7 @@ export const errors: Record = { '研究方式无效。': 'Invalid research mode.', '当前运行镜像未安装原生团队后端。': 'The worker image does not include the native team backend.', '原生团队容量必须为 2 至 8 人(含 Lead)。': 'Choose a native team capacity of 2 to 8, including Lead.', - '原生团队需要 Codex 执行器。': 'Native teams require the Codex harness.', + '此版本只支持 Codex 执行器。': 'This version supports the Codex harness.', '角色偏好仅适用于 Codex 原生团队。': 'Profile preferences require a native Codex team.', '当前运行镜像不支持个人专家资料。请移除专家资产或更新运行镜像。': 'This worker image does not support personal experts. Remove the selected expert assets or update the worker image.', @@ -180,14 +180,12 @@ export const errors: Record = { '模型服务拒绝了这个 API Key,请检查所属服务商与权限。': 'The provider rejected this API key. Check its provider and permissions.', '模型服务暂时限流,请稍后再检查。': 'The provider is rate limiting requests. Check again shortly.', - '此服务通过配置的 CLI 调用;本次没有调用模型,连接将在执行时验证。': - 'This service uses the configured CLI. No model was called; the connection will be checked when it runs.', - '服务未提供可查询的模型列表;Key、模型与 {0} 兼容性将在发送时验证。': - 'The service did not provide a model list. The key, model and {0} compatibility will be checked when you submit.', + '服务未提供可查询的模型列表;Key、模型与 Responses API 兼容性将在发送时验证。': + 'The service did not provide a model list. The key, model and Responses API compatibility will be checked when you submit.', '模型列表中没有找到这个名称,请核对服务商的模型名;本次没有调用模型。': "This name was not found in the model list. Check the provider's model name. No model was called.", - 'Key 可访问模型列表,所选模型在列表中。本次没有调用模型;实际发送仍需服务支持 {0}。': - 'The key can access the model list and the selected model is listed. No model was called; submission still requires {0} support.', + 'Key 可访问模型列表,所选模型在列表中。本次没有调用模型;实际发送仍需服务支持 Responses API。': + 'The key can access the model list and the selected model is listed. No model was called; submission still requires Responses API support.', '提交请求标识无效。': 'The submission request ID is invalid.', '提交请求标识无效或不一致。': 'The submission request IDs are invalid or do not match.', '同一提交请求不能使用不同的题目或配置。': @@ -281,10 +279,6 @@ export const errors: Record = { '接口不存在。': 'Endpoint not found.', '验证码格式无效。': 'Invalid verification code format.', '账号状态已变更,请重新读取。': 'The account status changed. Reload and try again.', - '无法读取检查结果。': 'Could not read the check results.', - '无法读取运行镜像状态。': 'Could not read the runtime image status.', - '无法启动 Rust 作业执行器。': 'Could not start the Rust job runner.', - 'Rust 作业执行器意外退出。': 'The Rust job runner exited unexpectedly.', '知识查询或分页参数无效。': 'Invalid knowledge query or paging parameters.', '服务暂时不可用。': 'The service is temporarily unavailable.', '服务已重启;保留最后观测与已有证据。本次运行未恢复执行。': diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index 8f018ed7..e58d2c62 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -1,6 +1,6 @@ import { queueCounts } from './queueCounts'; import { nativeWeb } from './nativeWeb'; -import { webProviderExecutionDigest, webProviderHarness, webHarnessResearchError } from './harness'; +import { webProviderExecutionDigest, webHarnessResearchError } from './harness'; import crypto from 'node:crypto'; import type { WebConfig } from './config'; import type { WebRunner } from './runner'; @@ -15,7 +15,7 @@ import type { WorkerInput, WorkerMessage, } from './shared'; -import { webResearchModeError, webDefaultSkillLoading } from './researchMode'; +import { webResearchModeError } from './researchMode'; import { normalizeWebTeamPreferences } from './nativeTeamProfiles'; import { personalExpertCardsDigest } from '../../src/solver/personalExperts'; import { isProgressEvent, parseWebFailure, webAgentActionLimits, webLimits, webRunEventLimit } from './shared'; @@ -163,11 +163,7 @@ export class WebJobs { }; } private creation(input: WebRunInput, provider: WebWorkerProvider, requestId: string): WebCreation { - const normalized = - webProviderHarness(provider) === 'codex' - ? input - : { ...input, researchMode: input.researchMode ?? 'skill', skillLoading: input.skillLoading ?? 'file' }; - const { apiKey: _key, ...visible } = normalized; + const { apiKey: _key, ...visible } = input; const providerIdentity = { id: provider.id, baseUrl: provider.baseUrl, @@ -228,11 +224,9 @@ export class WebJobs { creationInput: WebRunInput = input, ): WebRun { input = normalizeWebTeamPreferences(input); - if (webProviderHarness(provider) !== 'codex') - input = { ...input, researchMode: input.researchMode ?? 'skill', skillLoading: input.skillLoading ?? 'file' }; - else if (input.nativeTeamCapacity !== undefined && input.researchMode === undefined) + if (input.nativeTeamCapacity !== undefined && input.researchMode === undefined) input = { ...input, researchMode: 'skill' }; - const modeError = webResearchModeError(input, provider); + const modeError = webResearchModeError(input); const harnessError = webHarnessResearchError(provider, input); if (harnessError) throw new WebStorageError(400, harnessError); if (modeError) throw new WebStorageError(400, modeError); @@ -277,7 +271,7 @@ export class WebJobs { }; if (researchConfiguration && !input.nativeTeamCapacity) pinnedInput.modulePlan = structuredClone(researchConfiguration.modulePlan); - if (input.researchMode === 'skill') pinnedInput.skillLoading ??= webDefaultSkillLoading(provider); + if (input.researchMode === 'skill') pinnedInput.skillLoading ??= 'native'; if (knowledgeDigest) pinnedInput.knowledgeDigest = knowledgeDigest; else delete pinnedInput.knowledgeDigest; const { apiKey, knowledgeDigest: _selectedKnowledgeDigest, ...visible } = pinnedInput; @@ -315,16 +309,11 @@ export class WebJobs { ); if (researchConfiguration) run.researchConfiguration = structuredClone(researchConfiguration); if (provider.harness || provider.execution) { - run.harness = webProviderHarness(provider); + run.harness = 'codex'; run.harnessConfigurationDigest = webProviderExecutionDigest(provider); } if (input.researchMode !== 'skill' || input.workers > 1 || input.modulePlan) - run.moduleConfiguration = freezeModuleConfiguration( - run.modulePlan, - run.coordination, - run.workers, - provider.harness, - ); + run.moduleConfiguration = freezeModuleConfiguration(run.modulePlan, run.coordination, run.workers); const creation = requestId ? this.creation(normalizeWebTeamPreferences(creationInput), provider, requestId) : undefined; diff --git a/apps/web/moduleRegistry.ts b/apps/web/moduleRegistry.ts index 95e07af2..95cf28dd 100644 --- a/apps/web/moduleRegistry.ts +++ b/apps/web/moduleRegistry.ts @@ -12,7 +12,7 @@ import { } from '../../src/solver/modules/policy'; import { WebStorage, WebStorageError } from './storage'; import { mathDigest } from '../../src/math/mathRuntimeIo'; -import type { WebFrozenModuleConfiguration, WebHarness } from './shared'; +import type { WebFrozenModuleConfiguration } from './shared'; import { webByokModuleIdentity } from './webModuleIdentity'; export type { WebFrozenModuleConfiguration } from './shared'; @@ -109,12 +109,10 @@ export function freezeModuleConfiguration( plan?: ResearchModulePlan, coordination: 'cooperative' | 'independent' = 'cooperative', workers = 4, - harness: WebHarness = 'codex', ): WebFrozenModuleConfiguration { const selected = plan === undefined ? defaultResearchModulePlan() : (researchModulePlanSchema.parse(plan) as ResearchModulePlan); const configuration = webByokModuleIdentity(configuredResearchModuleIdentity(plan, coordination, workers).identity); - if (harness !== 'codex') configuration.versions.M1 += ':' + harness + ':v1'; const ids = new Set([ 'M1:direct', 'M2:lean-kernel', diff --git a/apps/web/nativeDockerOperation.ts b/apps/web/nativeDockerOperation.ts deleted file mode 100644 index 2ac7b974..00000000 --- a/apps/web/nativeDockerOperation.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { spawn } from 'node:child_process'; -import { createInterface } from 'node:readline'; - -/** The private pipe stays open so cancellation or a lost workbench also ends the Rust operation. */ -export async function nativeDockerOperation( - host: string, - operation: 'precheck' | 'command' | 'inspect' | 'formalize' | 'explain' | 'paper', - request: unknown, - signal?: AbortSignal, - stream?: { onLine(line: string): void; cancelled: string }, -): Promise { - signal?.throwIfAborted(); - const child = spawn(host, [operation], { stdio: ['pipe', 'pipe', 'ignore'] }); - child.stdin.on('error', () => {}); - const closed = new Promise(resolve => child.once('close', resolve)); - let failure: Error | undefined; - child.once('error', () => { - failure = new Error('无法启动 Rust 作业执行器。'); - }); - const control = (word: string) => { - if (child.stdin.writable) child.stdin.write(word + '\n'); - }; - const cancel = () => control('cancel'); - signal?.addEventListener('abort', cancel, { once: true }); - let value: unknown; - let attached = false; - let deadline: ReturnType | undefined; - try { - const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); - child.stdin.write(JSON.stringify(request) + '\n'); - for await (const line of lines) { - const packet = JSON.parse(line); - if (packet.kind === 'created' && child.stdin.writable) - child.stdin.write(signal?.aborted ? 'cancel\n' : 'start\n'); - else if (packet.kind === 'attached' && stream) { - attached = true; - if (packet.timeoutMs > 0) deadline = setTimeout(() => control('timeout'), packet.timeoutMs); - } else if (packet.kind === 'worker' && stream && !signal?.aborted && typeof packet.line === 'string') - stream.onLine(packet.line); - else if (packet.kind === 'failure') failure = new Error(packet.message); - else if (packet.kind === 'value') value = packet.value; - } - const code = await closed; - if (signal?.aborted && stream && attached) throw new Error(stream.cancelled); - signal?.throwIfAborted(); - if (failure) throw failure; - if (code !== 0 || value === undefined) throw new Error('Rust 作业执行器未返回结果。'); - return value; - } finally { - clearTimeout(deadline); - signal?.removeEventListener('abort', cancel); - child.stdin.end(); - child.stdout.resume(); - await closed; - } -} diff --git a/apps/web/providerCheck.ts b/apps/web/providerCheck.ts index 3f90c76d..9c791430 100644 --- a/apps/web/providerCheck.ts +++ b/apps/web/providerCheck.ts @@ -10,19 +10,12 @@ export class WebProviderCheckError extends Error { } /** Lists models only. It never submits a prompt, follows a redirect, or returns an upstream error body. */ export async function checkWebProvider(provider: WebProvider, apiKey: string, model: string) { - if (provider.harness === 'cli') - return { status: 'unknown' as const, message: '此服务通过配置的 CLI 调用;本次没有调用模型,连接将在执行时验证。' }; - const anthropic = provider.harness === 'claude-code'; - const protocol = anthropic ? 'Messages API' : 'Responses API'; + if (provider.harness && provider.harness !== 'codex') + throw new WebProviderCheckError(400, '此版本只支持 Codex 执行器。'); let response: Response; try { - const endpoint = anthropic - ? provider.baseUrl.replace(/\/v1\/?$/u, '').replace(/\/$/u, '') + '/v1/models' - : provider.baseUrl.replace(/\/$/u, '') + '/models'; - response = await fetch(endpoint, { - headers: anthropic - ? { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', Accept: 'application/json' } - : { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' }, + response = await fetch(provider.baseUrl.replace(/\/$/u, '') + '/models', { + headers: { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(10_000), }); @@ -38,7 +31,7 @@ export async function checkWebProvider(provider: WebProvider, apiKey: string, mo if (response.status === 429) throw new WebProviderCheckError(429, '模型服务暂时限流,请稍后再检查。'); return { status: 'unknown' as const, - message: `服务未提供可查询的模型列表;Key、模型与 ${protocol} 兼容性将在发送时验证。`, + message: `服务未提供可查询的模型列表;Key、模型与 Responses API 兼容性将在发送时验证。`, }; } const body = (await response.json().catch(() => undefined)) as { data?: { id?: string }[] } | undefined; @@ -49,6 +42,6 @@ export async function checkWebProvider(provider: WebProvider, apiKey: string, mo }; return { status: 'available' as const, - message: `Key 可访问模型列表,所选模型在列表中。本次没有调用模型;实际发送仍需服务支持 ${protocol}。`, + message: `Key 可访问模型列表,所选模型在列表中。本次没有调用模型;实际发送仍需服务支持 Responses API。`, }; } diff --git a/apps/web/researchMode.ts b/apps/web/researchMode.ts index d4ede474..3eda9360 100644 --- a/apps/web/researchMode.ts +++ b/apps/web/researchMode.ts @@ -1,11 +1,6 @@ import { z } from 'zod'; import { DEFAULT_TEAM_AGENTS, MIN_TEAM_AGENTS, MAX_TEAM_AGENTS } from '../../src/solver/teamCapacity'; -import { - retiredPortfolioMessage, - retiredResearchCoordinationMessage, - type WebProvider, - type WebRunInput, -} from './shared'; +import { retiredPortfolioMessage, retiredResearchCoordinationMessage, type WebRunInput } from './shared'; export const nativeTeamCapacitySchema = z.number().int().min(MIN_TEAM_AGENTS).max(MAX_TEAM_AGENTS); export const nativeTeamPreferencesSchema = z.array(z.string().trim().min(1).max(100)).max(256); @@ -49,7 +44,6 @@ export function webResearchModeError( | 'portfolioExploration' | 'portfolioSeconds' >, - provider?: Pick, ): string | undefined { if (requestsRetiredPortfolio(input)) return retiredPortfolioMessage; if (input.nativeTeamPreferredProfiles?.length && input.nativeTeamCapacity === undefined) @@ -57,7 +51,6 @@ export function webResearchModeError( if (input.nativeTeamCapacity !== undefined) { if (!nativeTeamCapacitySchema.safeParse(input.nativeTeamCapacity).success) return '原生团队容量必须为 2 至 8 人(含 Lead)。'; - if (provider?.harness && provider.harness !== 'codex') return '原生团队需要 Codex 执行器。'; if ( input.researchMode === 'legacy' || input.workers !== 1 || @@ -72,16 +65,14 @@ export function webResearchModeError( return input.skillLoading === undefined ? undefined : '技能加载选项需要 Skill 研究方式。'; } -export function webResearchArguments(input: WebRunInput, provider?: Pick): string[] { - const error = retiredWebRunInputError(input) ?? webResearchModeError(input, provider); +export function webResearchArguments(input: WebRunInput): string[] { + const error = retiredWebRunInputError(input) ?? webResearchModeError(input); if (error) throw new Error(error); const team = input.nativeTeamCapacity; if (!team && input.researchMode !== 'skill') return []; return [ ...(team ? ['--agent-team', String(team)] : ['--research-mode', 'skill']), - ...(input.skillLoading && input.skillLoading !== webDefaultSkillLoading(provider) - ? ['--skill-loading', input.skillLoading] - : []), + ...(input.skillLoading && input.skillLoading !== 'native' ? ['--skill-loading', input.skillLoading] : []), ...(input.nativeTeamPreferredProfiles?.length ? ['--skill-preferred-profiles', input.nativeTeamPreferredProfiles.join(',')] : []), @@ -91,6 +82,3 @@ export function webResearchArguments(input: WebRunInput, provider?: Pick) => input.researchMode === 'skill' && !(input.coordination === 'cooperative' && input.workers > 1); - -export const webDefaultSkillLoading = (provider?: Pick): 'native' | 'file' => - provider?.harness && provider.harness !== 'codex' ? 'file' : 'native'; diff --git a/apps/web/runner.ts b/apps/web/runner.ts index 34701c32..5e5f2434 100644 --- a/apps/web/runner.ts +++ b/apps/web/runner.ts @@ -7,8 +7,6 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { promisify } from 'node:util'; -import { createInterface } from 'node:readline'; -import { nativeDockerOperation } from './nativeDockerOperation'; import { z } from 'zod'; import type { WebConfig } from './config'; import type { WorkerExplanationInput, WorkerExplanationMessage, WorkerInput, WorkerMessage } from './shared'; @@ -557,35 +555,6 @@ export class DockerWebRunner implements WebRunner { 'fi', ].join('\n'); const payload = JSON.stringify({ template, main }); - const host = process.env.THEOREMOS_WEB_DOCKER_HOST; - if (host) { - let output: unknown; - try { - output = await nativeDockerOperation( - host, - 'paper', - { - id, - image, - script, - payload, - maxOutputBytes: webPaperLimits.maxPdfBytes * 2, - maxRunSeconds: webPaperLimits.maxRunSeconds, - }, - signal, - ); - } catch (error) { - throw new WebPaperCompileError( - signal.aborted - ? 'paper_pdf_cancelled' - : error instanceof Error && error.message.startsWith('paper_pdf_') - ? error.message - : 'paper_pdf_container_failed', - ); - } - if (typeof output !== 'string') throw new WebPaperCompileError('paper_pdf_invalid_output'); - return readPaperPdf(output); - } const remove = () => execute('docker', ['rm', '--force', '--volumes', name], { timeout: 15_000 }).then( () => {}, @@ -676,15 +645,6 @@ export class DockerWebRunner implements WebRunner { if (command.type !== 'capture' && command.type !== 'plan-approval') throw new Error(retiredResearchCoordinationCode); if (!this.active.has(id)) throw new Error('运行环境尚未就绪或已结束。'); - const host = process.env.THEOREMOS_WEB_DOCKER_HOST; - if (host) { - const value = await nativeDockerOperation(host, 'command', { id, command }); - try { - return decodeCommandResult(value, id, command); - } catch { - throw new Error('运行环境未返回有效命令回执。'); - } - } return new Promise((resolve, reject) => { const child = spawn( 'docker', @@ -805,29 +765,6 @@ export class DockerWebRunner implements WebRunner { ? { checkedTarget: candidateTarget.name } : {}), }); - const host = process.env.THEOREMOS_WEB_DOCKER_HOST; - if (host) { - const packet = await nativeDockerOperation( - host, - 'precheck', - { - id: checkId, - image: this.config.workerImage, - environment, - withFiles, - payload, - }, - signal, - ); - if ( - !object(packet) || - typeof packet.output !== 'string' || - typeof packet.timedOut !== 'boolean' || - (packet.exitCode !== null && typeof packet.exitCode !== 'number') - ) - throw new Error('无法读取检查结果。'); - return result(packet.output, typeof packet.exitCode === 'number' ? packet.exitCode : null, packet.timedOut); - } const compilePack = `const fs=require("node:fs"); const p=JSON.parse(await Bun.stdin.text()); process.chdir("/tmp"); for(const m of p.modules){fs.mkdirSync(require("node:path").dirname(m.file),{recursive:true});fs.writeFileSync(m.file,m.source); @@ -937,25 +874,6 @@ export class DockerWebRunner implements WebRunner { async readiness() { // The worker image changes only on deployment; outlive the 30 s client poll so listings rarely start docker. if (this.cached && Date.now() - this.cached.at < 60_000) return this.cached.result; - const host = process.env.THEOREMOS_WEB_DOCKER_HOST; - if (host) { - const packet = await nativeDockerOperation(host, 'inspect', this.config.workerImage); - if ( - !object(packet) || - !object(packet.result) || - typeof packet.result.ready !== 'boolean' || - typeof packet.result.message !== 'string' - ) - throw new Error('无法读取运行镜像状态。'); - const result = packet.result as Awaited>; - this.cached = { - at: Date.now(), - result, - workerControl: packet.workerControl === true, - imageId: typeof packet.imageId === 'string' ? packet.imageId : undefined, - }; - return result; - } const metadata = await execute( 'docker', [ @@ -982,96 +900,6 @@ export class DockerWebRunner implements WebRunner { return result; } - private async runNativeProof( - host: string, - image: string, - input: WorkerInput, - onMessage: (message: WorkerMessage) => void, - signal: AbortSignal, - ): Promise { - const child = spawn(host, [], { stdio: ['pipe', 'pipe', 'ignore'] }); - child.stdin.on('error', () => {}); - const control = (word: string) => { - if (child.stdin.writable) child.stdin.write(word + '\n'); - }; - const abort = () => control('cancel'); - const closed = new Promise(resolve => { - child.once('close', resolve); - }); - let failure: Error | undefined; - child.once('error', () => { - failure = new Error('无法启动 Rust 作业执行器。'); - }); - const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); - const workerControl = this.cached?.workerControl === true; - let heartbeat: ReturnType | undefined; - let watchdog: ExecutionDeadline | undefined; - let messages: ReturnType | undefined; - try { - child.stdin.write( - JSON.stringify({ image, workerControl, request: { ...input, observationSourceRefs: true } }) + '\n', - ); - signal.addEventListener('abort', abort, { once: true }); - if (signal.aborted) abort(); - for await (const line of lines) { - let packet: unknown; - try { - packet = JSON.parse(line); - } catch { - continue; - } - if (!object(packet)) continue; - switch (packet.kind) { - case 'attached': - this.active.add(input.id); - watchdog = proofDeadline(input, abort); - messages = proofMessages(input, onMessage, watchdog); - if (workerControl) - heartbeat = setInterval(() => { - if (!child.stdin.writableNeedDrain) control('heartbeat'); - }, webWorkerHeartbeatMs); - break; - case 'worker': - if (typeof packet.line === 'string') messages?.read(packet.line); - break; - case 'journal': - if (!signal.aborted) messages?.read(JSON.stringify(packet.value), true); - break; - case 'capture': - try { - messages?.capture(decodeCommandResult(packet.value, input.id, { type: 'capture' })); - } catch { - /* A run cancelled during bootstrap may have no complete checkpoint. */ - } - break; - case 'drained': - case 'drainedJournal': - clearInterval(heartbeat); - if (signal.aborted || (messages?.error && !messages.result)) control('cancel'); - else if (messages?.result) control('done'); - else control(packet.kind === 'drained' ? 'recover' : 'cancel'); - break; - case 'failure': - if (typeof packet.message === 'string') failure = new Error(packet.message); - break; - } - } - const code = await closed; - if (failure) throw failure; - if (signal.aborted) return; - if (code !== 0) throw new Error('Rust 作业执行器意外退出。'); - if (!messages?.result) throw messages?.error ?? new Error('运行环境已退出,未返回验收结果。'); - } finally { - watchdog?.stop(); - clearInterval(heartbeat); - signal.removeEventListener('abort', abort); - child.stdin.end(); - child.stdout.resume(); - await closed; - this.active.delete(input.id); - } - } - async run(input: WorkerInput, onMessage: (message: WorkerMessage) => void, signal: AbortSignal): Promise { signal.throwIfAborted(); if (retiredWebRunInputError(input.input)) throw new Error(retiredResearchCoordinationCode); @@ -1085,8 +913,6 @@ export class DockerWebRunner implements WebRunner { workerImage = capability.imageId; signal.throwIfAborted(); } - const host = process.env.THEOREMOS_WEB_DOCKER_HOST; - if (host) return this.runNativeProof(host, workerImage, input, onMessage, signal); const name = `theoremos-web-${input.id}`; const environment = input.input.environment ?? 'standard'; const mathlib = environment === 'mathlib'; @@ -1269,20 +1095,6 @@ export class DockerWebRunner implements WebRunner { signal: AbortSignal, ): Promise { signal.throwIfAborted(); - const host = process.env.THEOREMOS_WEB_DOCKER_HOST; - if (host) { - let received = false; - await nativeDockerOperation(host, 'explain', { image: this.config.workerImage, request: input }, signal, { - cancelled: 'explanation_cancelled', - onLine(line) { - const message = parseExplanationMessage(line); - if (message?.type === 'result') received = true; - if (message) onMessage(message); - }, - }); - if (!received) throw new Error('explanation_worker_exited'); - return; - } const name = `theoremos-explain-${input.id}`, mathlib = input.environment === 'mathlib'; const memory = mathlib ? '12g' : '4g'; @@ -1419,26 +1231,6 @@ export class DockerWebRunner implements WebRunner { signal: AbortSignal, ): Promise { signal.throwIfAborted(); - const host = process.env.THEOREMOS_WEB_DOCKER_HOST; - if (host) { - let received = false; - await nativeDockerOperation(host, 'formalize', { image: this.config.workerImage, request: input }, signal, { - cancelled: 'formalization_cancelled', - onLine(line) { - const message = parseFormalizationMessage(line); - if (!message) return; - if ( - 'operation' in input - ? message.type === 'audit-result' || message.type === 'audit-error' - : message.type === 'result' - ) - received = true; - onMessage(message); - }, - }); - if (!received) throw new Error('formalization_worker_exited'); - return; - } const name = `theoremos-formalize-${'operation' in input ? 'audit-' : ''}${input.id}`, mathlib = input.environment === 'mathlib'; const memory = mathlib ? '12g' : '4g'; diff --git a/apps/web/server.ts b/apps/web/server.ts index 367f159f..f389538a 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -1,10 +1,9 @@ import { nativeWeb } from './nativeWeb'; -import { publicWebProvider, webProviderHarness, webHarnessResearchError } from './harness'; +import { publicWebProvider, webHarnessResearchError } from './harness'; import { nativeTeamCapacitySchema, nativeTeamPreferencesSchema, webAgentTeamPreset, - webDefaultSkillLoading, retiredWebRunInputError, webPortfolioSecondsSchema, webResearchModeError, @@ -316,13 +315,13 @@ const paperRequest = paperQuery const explanationEffort = (effort: WebEffort): 'low' | 'high' | 'max' => effort === 'low' ? 'low' : effort === 'medium' || effort === 'high' ? 'high' : 'max'; const gatewayProvider = (provider: WebProvider | undefined) => { - if (provider?.id !== SUB2API_PROVIDER.id || webProviderHarness(provider) !== 'codex') return false; + if (provider?.id !== SUB2API_PROVIDER.id || (provider.harness && provider.harness !== 'codex')) return false; const url = new URL(provider.baseUrl); return url.protocol === 'http:' && url.pathname.replace(/\/$/u, '') === '/v1'; }; const formalizationProvider = (provider: WebProvider | undefined) => !!provider && - webProviderHarness(provider) === 'codex' && + (!provider.harness || provider.harness === 'codex') && (gatewayProvider(provider) || (provider.id !== SUB2API_PROVIDER.id && new URL(provider.baseUrl).protocol === 'https:')); const providerModel = (provider: WebProvider) => @@ -1130,12 +1129,7 @@ export function createWebService( const requestId = bodyRequestId ?? (typeof headerId === 'string' ? headerId : undefined); // Confirmed statements retain their exact artifact bytes; ordinary Lean drafts keep the existing normalization. if (!submitted.formalizationId) submitted.source = submitted.source.trim(); - const codex = webProviderHarness(provider) === 'codex'; - if (!codex) { - submitted.researchMode ??= 'skill'; - submitted.skillLoading ??= 'file'; - } - if (submitted.researchMode === 'skill') submitted.skillLoading ??= webDefaultSkillLoading(provider); + if (submitted.researchMode === 'skill') submitted.skillLoading ??= 'native'; if (!submitted.planApproval) delete submitted.planApproval; // Retry the exact submitted identity before considering migration defaults or runtime capabilities. const creationInput = submitted as WebRunInput; @@ -1161,9 +1155,9 @@ export function createWebService( if (retiredInput) throw new HttpError(400, retiredInput, retiredResearchCoordinationCode); const harnessError = webHarnessResearchError(provider, creationInput); if (harnessError) throw new HttpError(400, harnessError); - const researchModeError = webResearchModeError(creationInput, provider); + const researchModeError = webResearchModeError(creationInput); if (researchModeError) throw new HttpError(400, researchModeError); - const teamEligible = codex && submitted.researchMode !== 'legacy' && !submitted.modulePlan; + const teamEligible = submitted.researchMode !== 'legacy' && !submitted.modulePlan; if (submitted.planApproval && !teamEligible) throw new HttpError(400, '先审计划需要 Codex 原生团队。'); // A typed key wins; an empty one uses the account's saved key, then the server's key for admins. const apiKey = typed || heldKey(session, provider); @@ -2512,7 +2506,7 @@ export function createWebService( } return; } - const providers = providersFor(session).filter(provider => webProviderHarness(provider) === 'codex'); + const providers = providersFor(session).filter(provider => !provider.harness || provider.harness === 'codex'); const defaultProvider = providers.find(provider => provider.id === job?.providerId) ?? providers.find(provider => provider.id === run.providerId) ?? diff --git a/apps/web/shared.ts b/apps/web/shared.ts index 861ec528..1252ceca 100644 --- a/apps/web/shared.ts +++ b/apps/web/shared.ts @@ -80,13 +80,7 @@ export type WebHarness = 'codex' | 'claude-code' | 'opencode' | 'cli'; export type WebProvider = { id: string; name: string; baseUrl: string; harness?: WebHarness; efforts?: WebEffort[] }; /** Operator-owned launch settings. Public provider responses omit these fields. */ export type WebWorkerProvider = WebProvider & { - execution?: { - executable?: string; - cli?: Record; - files?: Record; - apiKeyEnvironment?: string; - baseUrlEnvironment?: string; - }; + execution?: { executable?: string }; }; export type WebEnvironmentOption = { id: WebEnvironment; diff --git a/rust/web/trajectory.json b/apps/web/trajectory.json similarity index 100% rename from rust/web/trajectory.json rename to apps/web/trajectory.json diff --git a/apps/web/trajectory.ts b/apps/web/trajectory.ts index 020876f9..9b3dbf3c 100644 --- a/apps/web/trajectory.ts +++ b/apps/web/trajectory.ts @@ -18,7 +18,7 @@ import type { WebEvent } from './shared'; export const trajectorySchema = 'theorem-os.web-trajectory.v1'; /** Events that mark a mathematical step; heartbeats, context bookkeeping and module notices stay in the activity log. */ -import trajectoryConfig from '../../rust/web/trajectory.json'; +import trajectoryConfig from './trajectory.json'; export const trajectoryEventTypes = new Set(trajectoryConfig.events); export const trajectoryLimits = trajectoryConfig.limits; const textLimits = { guidance: 2_000, headline: 160 } as const; diff --git a/apps/web/worker-entrypoint.sh b/apps/web/worker-entrypoint.sh index 72a274fa..9112c742 100644 --- a/apps/web/worker-entrypoint.sh +++ b/apps/web/worker-entrypoint.sh @@ -1,7 +1,5 @@ #!/bin/sh set -eu -root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) -native_sha=$(cat "$root/out/main/theoremos-process.sha256") case "${2:-run}" in run) script=apps/web/worker.ts ;; explain|formalize) @@ -12,23 +10,13 @@ case "${2:-run}" in ;; *) exit 2 ;; esac -profile=${1:-standard} -case "${2:-run}" in - explain|formalize) - role_sum=$(sha256sum /usr/local/bin/theorem-os) - role_pin="__THEOREMOS_ROLE_LAUNCHER__:{\"file\":\"/usr/local/bin/theorem-os\",\"sha256\":\"${role_sum%% *}\"}" - set -- --define "$role_pin" "$root/$script" - ;; - *) set -- "$root/$script" ;; -esac -set -- bun --define "__THEOREMOS_WORKER_PROCESS_SHA256__:\"$native_sha\"" "$@" -case "$profile" in +case "${1:-standard}" in mathlib) # FUSE mounts need a capability scoped to this new user namespace only. exec bwrap --unshare-user --uid 0 --gid 0 --cap-add CAP_SYS_ADMIN --cap-add CAP_SETFCAP \ --bind / / --dev-bind /dev /dev --proc /proc --die-with-parent \ - -- "$@" + -- bun "$script" ;; - standard) exec "$@" ;; + standard) exec bun "$script" ;; *) exit 2 ;; esac diff --git a/apps/web/worker.ts b/apps/web/worker.ts index 0b3744b1..fa6552ba 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -10,7 +10,6 @@ import { PANTOGRAPH_DIGEST_ENV, PANTOGRAPH_MANIFEST_ENV } from '../../src/math/p import { mathDigest, readMathJson, readMathText } from '../../src/math/mathRuntimeIo'; import { readMathBuildManifest } from '../../src/math/mathBuildManifest'; import { isMathPathWithin } from '../../src/math/paths'; -import { researchHarness } from '../../src/runtime/researchHarness'; import { sub2apiModelCatalog } from '../../src/runtime/sub2api'; import { configurableRuntimeModules, type RuntimeSolverModules } from '../../src/solver/modules/runtime'; import { solverModuleConfiguration } from '../../src/solver/modules/moduleIdentity'; @@ -36,15 +35,7 @@ import { runWebLibraryResearch } from './libraryResearch'; import { retiredWebRunInputError, webResearchArguments } from './researchMode'; import { webProofMessageSink } from './proofJournal'; import { createWebHostDisconnectWatchdog, webWorkerShutdownMs } from './workerDisconnect'; -import { - bindWebWorkerProfile, - pinWebWorkerSession, - prepareWebNativeProfile, - webHarnessEnvironment, - webHarnessExecutable, - webHarnessModel, - webProviderHarness, -} from './harness'; +import { webHarnessResearchError } from './harness'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); type WebWorkerState = { @@ -266,7 +257,7 @@ export function writeWebContinuation( * Agent shells in this container cannot read the application or its build state; they run the bundled commands from * scripts/build-agent-tools.ts instead, which the image installs here. */ -export const webAgentToolsDefault = '/opt/theoremos-agent-tools/math.native'; +export const webAgentToolsDefault = '/opt/theoremos-agent-tools/math.mjs'; export const webPantographManifest = '/opt/theoremos-pantograph/manifest.json'; /** Pass only the frozen knowledge projection to the solver, outside all member worktrees. */ @@ -306,6 +297,8 @@ export function webSolverModules( }, isolation?: WebAgentIsolation, ): RuntimeSolverModules { + const harnessError = webHarnessResearchError(request.provider, request.input); + if (harnessError) throw new Error(harnessError); const base = configurableRuntimeModules(request.input.modulePlan, request.input.coordination, request.input.workers); const identity = webByokModuleIdentity(solverModuleConfiguration(base)); let sessions = 0; @@ -353,65 +346,59 @@ export function webSolverModules( const action = sanitizeAgentItem(phase, { ...item, id }, context!); if (typeof id === 'string') stream!.write(phase, id, action, incremental); }; - const harness = researchHarness(webProviderHarness(request.provider)); - const binding = harness.id === 'codex' ? undefined : bindWebWorkerProfile(options, request.provider); - return harness - .open({ - ...options, - ...(binding ? { profile: binding.profile } : {}), - ...(isolation ? { hiddenRoots: [...(options.hiddenRoots ?? []), ...isolation.hiddenRoots] } : {}), - ...(isolation && options.leanHealthCheck - ? { - leanHealthCheck: { - executable: isNativeToolBundle(isolation.tools) - ? isolation.tools - : options.leanHealthCheck.executable, - arguments: [ - ...(isNativeToolBundle(isolation.tools) ? [] : [isolation.tools]), - 'check-lean', - ...options.leanHealthCheck.arguments.slice(1), - ], - }, - } - : {}), - environment: { ...options.environment, ...webHarnessEnvironment(request.provider, request.input.apiKey) }, - ...(context - ? { - onItem: (phase, item) => show(phase, item), - onItemUpdate: (item, context) => { - options.onItemUpdate?.(item, context); - show('started', item, true); - }, - } - : {}), - }) - .then(opened => { - if (binding) pinWebWorkerSession(opened, binding); - if (!stream) return opened; - const run = opened.run, - interrupt = opened.interrupt, - close = opened.close; - opened.run = async (...args) => { - stream.reset(); - if (options.signal?.aborted) stream.stop(); - args[0] += `\n\n${webProofProgressInstructions}`; - try { - return await run(...args); - } finally { - stream.stop(); + return base.M1.open({ + ...options, + ...(isolation ? { hiddenRoots: [...(options.hiddenRoots ?? []), ...isolation.hiddenRoots] } : {}), + ...(isolation && options.leanHealthCheck + ? { + leanHealthCheck: { + executable: isNativeToolBundle(isolation.tools) + ? isolation.tools + : options.leanHealthCheck.executable, + arguments: [ + ...(isNativeToolBundle(isolation.tools) ? [] : [isolation.tools]), + 'check-lean', + ...options.leanHealthCheck.arguments.slice(1), + ], + }, } - }; - opened.interrupt = async () => { - stream.stop(); - await interrupt(); - }; - opened.close = async () => { + : {}), + environment: { ...options.environment, THEOREMOS_PROVIDER_API_KEY: request.input.apiKey }, + ...(context + ? { + onItem: (phase, item) => show(phase, item), + onItemUpdate: (item, context) => { + options.onItemUpdate?.(item, context); + show('started', item, true); + }, + } + : {}), + }).then(opened => { + if (!stream) return opened; + const run = opened.run, + interrupt = opened.interrupt, + close = opened.close; + opened.run = async (...args) => { + stream.reset(); + if (options.signal?.aborted) stream.stop(); + args[0] += `\n\n${webProofProgressInstructions}`; + try { + return await run(...args); + } finally { stream.stop(); - options.signal?.removeEventListener('abort', stream.stop); - await close(); - }; - return opened; - }); + } + }; + opened.interrupt = async () => { + stream.stop(); + await interrupt(); + }; + opened.close = async () => { + stream.stop(); + options.signal?.removeEventListener('abort', stream.stop); + await close(); + }; + return opened; + }); }, }, }; @@ -468,18 +455,22 @@ async function main(watchdog: ReturnType process.exitCode = 1; return; } + const harnessError = webHarnessResearchError(request.provider, request.input); + if (harnessError) { + send({ type: 'error', message: harnessError }); + process.exitCode = 1; + return; + } const workspaceRoot = process.env.THEOREMOS_WORKER_ROOT || '/work'; const directory = fs.mkdtempSync(path.join(workspaceRoot, 'run-')); let output = path.join(directory, 'result.json'); writeWebActiveRun({ webRunId: request.id, directory, output }, path.join(workspaceRoot, 'active-run.json')); let bridge = createWebWorkerBridge({ webRunId: request.id, directory, output, apiKey: key, onMessage: send }); - const harness = webProviderHarness(request.provider); - const profile = path.join(directory, harness === 'codex' ? 'codex' : 'harness'); - if (harness === 'codex') prepareWebProviderProfile(profile, request); - else prepareWebNativeProfile(profile, request.provider, request.input); + const profile = path.join(directory, 'codex'); + prepareWebProviderProfile(profile, request); fs.mkdirSync(process.env.HOME || '/work/home', { recursive: true, mode: 0o700 }); // Each container owns this profile. No machine profile or authentication file is read. - if (harness === 'codex') process.env.CODEX_HOME = profile; + process.env.CODEX_HOME = profile; process.env.DEEPSCIENTIST_MATH_ENV_FILE = path.join(directory, 'math.env'); fs.writeFileSync(process.env.DEEPSCIENTIST_MATH_ENV_FILE, '', { mode: 0o400, flag: 'wx' }); const originalLog = console.log; @@ -522,7 +513,7 @@ async function main(watchdog: ReturnType }; console.error = () => {}; try { - const researchArguments = webResearchArguments(request.input, request.provider); + const researchArguments = webResearchArguments(request.input); const environment = getLeanTaskEnvironment(request.input.environment ?? 'standard'); configureWebProofSearchEnvironment(environment.id); const receipt = prepareWebProblem(directory, request); @@ -621,7 +612,7 @@ async function main(watchdog: ReturnType '--build-manifest', buildIndex.buildManifestRef, '--model', - webHarnessModel(request.provider, request.input.model), + request.input.model, '--effort', request.input.effort, '--no-explanations', @@ -632,15 +623,8 @@ async function main(watchdog: ReturnType ...expertCardArguments, ...(request.input.nativeTeamCapacity ? ['--harness-profile', profile] - : harness !== 'codex' || request.provider.execution?.executable - ? [ - '--harness', - harness, - '--harness-profile', - profile, - '--harness-executable', - webHarnessExecutable(request.provider), - ] + : request.provider.execution?.executable + ? ['--harness-profile', profile, '--harness-executable', request.provider.execution.executable] : []), ...(round.planApproval ? ['--plan-approval'] : []), ...(knowledgeFile ? ['--knowledge-base', knowledgeFile] : []), diff --git a/bin/math-help.txt b/bin/math-help.txt index ccff187a..4df19871 100644 --- a/bin/math-help.txt +++ b/bin/math-help.txt @@ -3,8 +3,7 @@ theorem-os [arguments] build Freeze mathematical sources and build the solver doctor Check local tools, login and sandbox permissions example Replay or solve a small Lean tutorial without Mathlib - component Create and check a Rust search-order component - run Run or resume an isolated mathematics proof (optional --portfolio-exploration) + run Run or resume an isolated mathematics proof batch Run prepared problems concurrently in separate processes bootstrap-lean-task Prepare a workspace from a Lean source and task description bootstrap-imo Prepare an IMO2026 proof workspace diff --git a/bin/math.ts b/bin/math.ts index 25e8dbcc..0393b4c8 100644 --- a/bin/math.ts +++ b/bin/math.ts @@ -10,9 +10,9 @@ const commands: Readonly> = { build: 'scripts/build.ts', doctor: 'scripts/mathematics/doctor.ts', example: 'scripts/mathematics/runExample.ts', - component: 'scripts/mathematics/component.ts', run: 'out/main/math-solver.js', batch: 'scripts/mathematics/runMathBatch.ts', + 'bootstrap-lean-task': 'scripts/mathematics/bootstrapLeanTask.ts', 'bootstrap-imo': 'scripts/mathematics/bootstrapImo2026.ts', 'bootstrap-lean-eval': 'scripts/mathematics/bootstrapLeanEvalHeldOut.ts', 'list-lean-eval': 'scripts/mathematics/listLeanEval.ts', diff --git a/bin/theorem-os b/bin/theorem-os index 6d5604d3..f6cee832 100755 --- a/bin/theorem-os +++ b/bin/theorem-os @@ -7,8 +7,4 @@ while [ -L "$entry" ]; do case $target in /*) entry=$target ;; *) entry=${entry%/*}/$target ;; esac done bindir=${entry%/*} -native=$bindir/../target/release/theorem-os -if [ -x "$native" ]; then - exec "$native" __package "$bindir/math.ts" "$@" -fi exec bun "$bindir/math.ts" "$@" diff --git a/docs/codex-skill-runtime.md b/docs/codex-skill-runtime.md index 70cd21ed..ad83e3b4 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 [harness configuration and verified limits](harness-portability.md) for supported executors. +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. ## Start and resume @@ -193,7 +193,7 @@ Use the pinned revision of the original experiment to prepare and execute host s `compare --skill-baseline native|file --phase prepare ...` replaces the legacy single arm with skill research. Preparation freezes skill identity in the plan and launch files without starting a model. The existing independent and cooperative arms share the planned model, tools, environment and total token allowance. Reports retain all planned attempts and missing usage. -The `--skill-baseline` comparisons remain **system-mode** comparisons: legacy prompts contain additional mathematical guidance, so `commonGuidanceFrozen` and `strategyIsolation` are false. `--common-research-skill native|file` instead pins the same mathematical skill and minimal host contracts in all three arms. This isolates host strategy choices while preserving their actual coordination and delivery protocols. `--dataset lean-task --source-file FILE --task-file FILE` admits a frozen local statement without importing old answers or human-assisted research history. Plans, launches and reports retain the guidance, model, provider, effort, environment, knowledge and total resource identities. One diagnostic problem establishes that the comparison runs; it cannot establish an efficiency advantage. +The `--skill-baseline` comparisons remain **system-mode** comparisons: legacy prompts contain additional mathematical guidance, so `commonGuidanceFrozen` and `strategyIsolation` are false. In the historical runtime, `--common-research-skill native|file` pins the same mathematical skill and minimal host contracts in all three arms. This isolates host strategy choices while preserving their actual coordination and delivery protocols. `--dataset lean-task --source-file FILE --task-file FILE` admits a frozen local statement without importing old answers or human-assisted research history. Plans, launches and reports retain the guidance, model, provider, effort, environment, knowledge and total resource identities. One diagnostic problem establishes that the comparison runs; it cannot establish an efficiency advantage. Comparison preparation and solver startup share resource binding for the retrieval corpus, installed mathematics tools and proof-search backend before computing the environment digest. Changed pinned resource bytes remain an error. The first preregistered three-arm diagnostic exposed the previous missing tools binding: all three observations were rejected for an environment identity mismatch and had already stopped at their dispatch allowance. Their frozen plan and raw report remain unchanged. Observed consumption was 8,733 tokens for skill, 17,583 for independent and 11,285 for cooperative; these are costs of invalid attempts, not accepted comparison results. The repair is checked with disposable startup processes without rerunning the observed paid sample. diff --git a/docs/generic-cli.md b/docs/generic-cli.md deleted file mode 100644 index 2835d22f..00000000 --- a/docs/generic-cli.md +++ /dev/null @@ -1,149 +0,0 @@ -# Configurable headless CLI harness - -Use `--harness cli` for a headless agent executable beyond the built-in Codex, Claude Code and OpenCode adapters. One `cli.json` describes its command, input and output; the host calls the executable directly with an argv array. This is a command adapter, with no shell interpolation, plugin loader or additional agent workflow engine. - -The executable must accept a noninteractive request and terminate when its work ends. For autonomous proof research it also needs the ability to read the pinned Skill, edit the owned files and run the supplied Lean commands. An interactive-only terminal application needs its own headless wrapper. The adapter does not give an executable tools it does not have. - -## Start a run - -Create a dedicated profile directory outside the proof workspace and save this minimal `cli.json` in it: - -```json -{ - "schema": "theorem-os.cli-harness.v1", - "executable": "/absolute/path/to/your-agent", - "args": ["--model", "{model}"], - "prompt": "stdin", - "session": { "mode": "fresh" }, - "output": { "format": "text" }, - "efforts": ["none"] -} -``` - -Adapt `args` to the actual executable, then use the normal solver command: - -```sh -bun bin/math.ts run --harness cli --harness-profile DEDICATED_PROFILE \ - --model YOUR_MODEL --effort none \ - --workspace NEW_WORKSPACE --task-file TASK_FILE \ - --output RESULT_FILE --build-manifest BUILD_MANIFEST -``` - -`--harness-executable` optionally overrides `executable`. The CLI harness defaults to a solo researcher with file-loaded Skill guidance. Build the standalone runtime with an external `--state-root` and use its build manifest. Web operators can configure the same backend. Sealed formalization and audit roles retain their stronger isolation requirement. See [complete workflows](portable-workflows.md). - -## Input and session contract - -The prompt combines host instructions, pinned Skill paths and the current task. `prompt: "stdin"` writes it to stdin and closes stdin. `prompt: "file"` writes a private file under `.scratch/cli-prompts` and requires `{promptFile}` in the command. `prompt: "argument"` supplies `{prompt}` as one argv value; OS argument length limits apply. Arguments are never split or evaluated as shell code. - -| Session mode | Initial command | Subsequent command | Research context | -| --- | --- | --- | --- | -| `fresh` | `args` | `args` again | Full frozen task every time, with current sources and research notes | -| `generated` | `args` + `startArgs`, with a host UUID in `{sessionId}` | `args` + `resumeArgs`, with the exact saved ID | Native session continuity; full task after a host restart | -| `reported` | `args` + `startArgs`; bind the configured output session ID before publishing the turn | `args` + `resumeArgs`, with the exact saved ID | Native session continuity; full task after a host restart | - -Native `resumeArgs` must include `{sessionId}`. A reported session additionally requires `output.sessionId`; a generated session requires `{sessionId}` in `startArgs`. A mismatched reported ID fails the turn. There is no implicit resume of the latest session. - -Supported template values are `{model}`, `{effort}`, `{profile}`, `{workspace}`, `{prompt}`, `{promptFile}`, `{sessionId}` and `{turnId}`. They work in args and configured environment values. Every initial and resumed command must bind `{model}`. `efforts` defaults to `["none"]`; include `{effort}` and list actual supported levels to expose reasoning control. Unsupported effort levels fail before dispatch. - -## Structured output and usage - -`output.format` accepts `text`, `json` or `jsonl`. JSONL requires one JSON value per nonempty line, with logs on stderr. The adapter reads through process exit, then settles usage once. It never adds repeated final frames as separate requests. - -Fields use RFC 6901 JSON Pointers, including `~1` for `/` and `~0` for `~`. Optional `when` is one `{ "field": POINTER, "value": PRIMITIVE }` equality or an array of equalities that must all match. There are no evaluated expressions. For example: - -```json -{ - "format": "jsonl", - "sessionId": { "field": "/session/id", "when": { "field": "/kind", "value": "init" } }, - "text": { "field": "/result/text", "when": { "field": "/kind", "value": "final" }, "mode": "replace" }, - "usage": { - "when": { "field": "/kind", "value": "final" }, - "inputTokens": "/stats/input", - "outputTokens": "/stats/output", - "cachedInputTokens": "/stats/cached", - "scope": "turn", - "completeness": "partial" - }, - "failures": [{ - "when": [{ "field": "/kind", "value": "final" }, { "field": "/status", "value": "error" }], - "reason": "invalid-request" - }] -} -``` - -Choose `usage.scope: "turn"` for invocation totals and `"session"` for cumulative totals preserved across native resume. Session totals are unavailable in `fresh` mode. Input tokens must already include cached input; cached and reasoning counters are subsets, not additional tokens. `lastInputTokens`, when provided, must describe the latest individual request, rather than the sum of a multi-request turn. - -Usage defaults to `completeness: "partial"`. Set `"complete"` only when the native command accounts for all its requests, including child/background work, in the selected final record. Missing, partial, malformed or zero input/output counters make usage unknown. A finite token budget then blocks further model dispatches; it still permits pending proof checks. These are observed turn limits, with possible in-flight overshoot, rather than provider-request admission. - -Configured terminal failure classes are `authentication`, `context`, `rate-limit`, `request` and `invalid-request`. Match terminal events specifically: a recoverable tool error must not fail the whole research turn. A matching terminal failure retains its classification even when the command exits nonzero, so the host applies the corresponding stop or recovery policy. A nonzero exit without a classified failure produces `math_cli_command_failed` and stops automatic retry. Raw stderr and provider error text are not copied into saved diagnostics. - -## Configuration and isolation - -`environment` maps explicit native environment values, for example `"HOME": "{profile}/home"`. `inheritEnvironment` lists existing process variables needed by that command, for example an API key or endpoint. CLI-only inherited values are excluded from host Lean environment records. Credentials should enter through `inheritEnvironment`, not literal config or argv values. Non-secret inherited values participate in the launch identity; recognized credential names may rotate. Runtime-owned environment names are reserved. - -Research sessions keep native network access, so the provider key never enters the sandbox. Declare the native client's provider variables with `researchProvider`: - -```json -"inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_BASE_URL"], -"researchProvider": { "wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_BASE_URL" } -``` - -Both names must be listed in `inheritEnvironment` and absent from `environment`. The host keeps the real key in a loopback relay. Inside the sandbox the key variable holds a disposable capability and the base variable holds the relay's `/v1` endpoint. The relay forwards only the wire API's request paths, relative to the base the client was configured with: `/responses`, `/chat/completions`, or Anthropic `/messages` and `/messages/count_tokens` (with or without a leading `/v1`). An unset base variable uses the provider's public endpoint. The upstream base must be HTTPS, or HTTP to a loopback/private host. Inherited variables whose names look like credentials (`API_KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `CREDENTIAL`, `PRIVATE_KEY`) are always removed. If one of them has a value and is not the declared `researchProvider` key, the session fails with `math_cli_provider_relay_unsupported` instead of projecting it. A `sealedRole` provider key is never passed to research sessions. Declare a credential with an unusual name through `researchProvider`, since name matching cannot recognize it. - -`configurationFiles` lists existing relative files under the profile whose bytes must remain frozen, such as native settings. The host pins these files, `cli.json`, executable path/bytes and non-secret inherited environment before dispatch, source freezing and resume. Session/cache files can grow. Put every native settings file that affects execution in this list and disable undesired native project/global discovery in the native configuration. - -Execution requires Linux bubblewrap. The host root is read-only; the proof worktree and dedicated profile are writable. HOME defaults to the dedicated profile, XDG state stays there, temporary files stay in the worktree, protected roots and host socket directories are masked, and research networking remains available. The host waits for confirmed process shutdown before freezing source. A valid completion file may stop the process early; it is a handoff for independent verification, never proof acceptance. - -## Sealed formalization and audit roles - -Formalization, independent review, explanation and automatic-library planning use the stronger shared sealed sandbox. They can select `--harness cli` with this additional `cli.json` configuration: - -```json -{ - "schema": "theorem-os.cli-harness.v1", - "executable": "/absolute/path/to/headless-agent", - "args": ["--model", "{model}", "--effort", "{effort}"], - "prompt": "stdin", - "output": { "format": "text" }, - "efforts": ["high"], - "sealedRole": { - "provider": { - "wireApi": "chat-completions", - "baseUrl": "https://models.example.com/v1", - "apiKeyEnvironment": "PROVIDER_API_KEY" - }, - "client": { - "baseUrlEnvironment": "OPENAI_BASE_URL", - "apiKeyEnvironment": "OPENAI_API_KEY" - }, - "profileFiles": { - "native.json": "{\"baseURL\":\"{relayBaseUrl}\",\"apiKey\":\"{relayCapability}\",\"workspace\":\"{workspace}\"}" - } - } -} -``` - -The client environment names must match the native executable's documented configuration. `provider.wireApi` accepts `chat-completions`, `responses` or `anthropic-messages`, with the model/effort fields of that protocol. The endpoint must use HTTPS; HTTP is accepted only on loopback for local gateways/tests. The host loads `provider.apiKeyEnvironment` automatically. That key stays outside the role; the client receives an ephemeral capability and a private loopback endpoint. Direct Internet access and remote-resource/hosted-tool requests are denied. - -`profileFiles` generates a role-specific profile by value. Its templates support `{profile}`, `{workspace}`, `{relayBaseUrl}` and `{relayCapability}`. The last two produce the private `/v1` endpoint and disposable capability. `configurationFiles`, host auth files and native session stores are not copied. Omit `profileFiles` when the CLI accepts environment configuration. Match the executable's normal headless flags to the generated profile; for example a CLI that requires `--config` should receive `/profile/native.json` through `args`. - -The executable must be a self-contained native ELF, or declare `sealedRole.runtime.interpreter`. For a script use, for example: - -```json -{ - "interpreter": "/usr/bin/python3", - "resources": [ - { "source": "/absolute/path/to/helper.py", "target": "/opt/harness/resources/helper.py" } - ] -} -``` - -This object is the value of `sealedRole.runtime`. Each resource is an explicitly selected canonical ordinary file. Targets stay under `/opt/harness/resources/`; resource directories or overrides of system/profile/source roots are rejected. The entrypoint script is projected automatically. Executable/interpreter/resource bytes participate in the frozen identity, and changing them requires a new request. The sandbox also records their digests. No host-root mount or global CLI installation tree is substituted. A packaged CLI can enumerate its required runtime files or supply a self-contained native build. - -In sealed roles, `environment` uses explicit constants and the `{model}`, `{effort}`, `{profile}` and `{workspace}` templates. Ambient `inheritEnvironment` values stay on the host. Per-turn prompt/session/turn environment templates require argv/stdin/file equivalents. Runtime-owned environment names and projection of the real provider key are rejected. Output paths are projected to `/workspace`; host validators still reject invalid JSON/proofs, and the host confirms all native writers stopped before source freezing and independent Lean checks. Usage comes from host provider-request receipts even when `output.usage` is absent. - -## Presets and verification scope - -Example profiles live in `resources/cli-harnesses`. Gemini CLI and Qwen Code presets target the versions recorded there; Aider uses a conservative one-shot profile. Review each preset's native tool and accounting limits before selecting it. The same configuration contract also accepts other headless CLIs or small wrappers without a new TypeScript adapter. - -Tests exercise stdin/file/argument input, exact native resume, plain/JSON/JSONL output, cumulative versus turn usage, missing accounting, process shutdown, full-context one-shot recovery and frozen configuration identity. Shared solver tests check correct proofs, incorrect proofs and reusable helpers using the real isolated Lean kernel. Fixed loopback provider responses verify native CLI protocols without external model calls; they do not establish mathematical success rates or an efficiency gain. diff --git a/docs/harness-portability.md b/docs/harness-portability.md index 844cef2b..317bb741 100644 --- a/docs/harness-portability.md +++ b/docs/harness-portability.md @@ -1,62 +1,9 @@ -# Portable research harnesses +# Codex runtime -Research supports Codex, Claude Code, OpenCode and a configurable [headless CLI harness](generic-cli.md). New collaboration uses the Codex native team. Additional harnesses support solo workloads. Mathematical methods live in one pinned `skills/theoremos-research` directory and can be selected separately from the backend and host coordination. The solver uses `MathAgentSession` for dispatch, native session IDs, activity, usage and confirmed process shutdown. Mathematical acceptance, declaration artifacts, saved sources and independent verification remain host responsibilities. +The CLI and workbench use Codex to run proofs, formalize statements, review evidence, explain proofs and plan library work. Set the Responses API provider and model in the Codex profile. The workbench creates a separate profile for each run and supplies the user's API key to the Codex process. -| Harness | Native transport | Skill loading | Research arrangement | Usage basis | -| --- | --- | --- | --- | --- | -| Codex | app-server over stdio | native or file | Solo and native proof-writing team | Provider requests when the existing relay supplies receipts; otherwise native cumulative thread totals | -| Claude Code | print mode with stream-json | file | Solo for new runs | One final native invocation total, including all API calls inside that invocation | -| OpenCode | native server, session API and SSE | file | Solo for new runs | Deduplicated assistant request totals belonging to the dispatched native message | -| Configured CLI | argv + stdin/file/argument; text, JSON or JSONL | file | Solo for new runs | Explicitly mapped invocation or cumulative session totals; unknown unless complete native coverage is configured | +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. -CLI research, trusted Web provider configuration, automatic-library proof backends and batch launches share this selection. Formalization, review and other sealed roles reuse the same dispatch interface and sandbox across all four backends. The generic CLI requires an explicit executable/resource projection and role relay mapping. See [complete workflows](portable-workflows.md). +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). -Codex runs default to a native team of four including Lead. Use `--agent-team N` for a capacity of 2–8 or `--workers 1` for a solo researcher. Native teams use Codex collaboration tools for dispatch and messaging and `theoremos_team` for proof handoffs. Lead decides decomposition and adoption. Children retain native threads, write Lean in isolated worktrees and deliver asynchronously. The host checks exact deliveries after writer shutdown, rechecks them during integration and independently verifies the whole problem. See the [team launch and delivery protocol](codex-skill-runtime.md#agent-organized-proof-writing-team). - -## Launch - -Build with `bun run build --state-root EXTERNAL_BUILD_DIRECTORY`, then supply its manifest. Select the harness separately from the model: - -```sh -bun bin/math.ts run --harness claude-code \ - --harness-profile DEDICATED_CLAUDE_DIRECTORY \ - --harness-executable /absolute/path/to/claude \ - --model YOUR_CLAUDE_MODEL --effort high \ - --workspace NEW_WORKSPACE --task-file TASK_FILE \ - --output RESULT_FILE --build-manifest BUILD_MANIFEST - -bun bin/math.ts run --harness opencode \ - --harness-profile DEDICATED_OPENCODE_DIRECTORY \ - --harness-executable /absolute/path/to/opencode \ - --model PROVIDER_ID/MODEL_ID --effort high \ - --workspace ANOTHER_NEW_WORKSPACE --task-file TASK_FILE \ - --output ANOTHER_RESULT_FILE --build-manifest BUILD_MANIFEST -``` - -Additional harnesses default to `--research-mode skill --skill-loading file --workers 1 --coordination independent`. Explicit legacy methods also work; unsupported native Skill loading or delegation is rejected. They require a separately created profile directory and explicit model. OpenCode requires `opencode.json` in that directory, with the selected provider configured and the requested effort present in the native model's variants. Unsupported efforts are rejected. Claude uses its explicit native model/effort flags and API authentication environment. - -Only explicit provider definitions enter the OpenCode configuration. Project configuration, plugins, MCP, title models and child agents are disabled for this execution path. Claude disables project settings, hooks, plugins and child tools. The host points both agents to the identical frozen Skill file and generated command help. It does not translate mathematical methods into a separate backend-specific prompt library. - -Native credentials enter an execution-only environment overlay and are excluded from host Lean environment records. For non-sealed Claude Code and OpenCode research sessions the provider key itself stays in the host process: `src/runtime/researchCredentialRelay.ts` starts a loopback relay that holds the key, and the sandboxed client receives only that relay's URL and a disposable capability (`ANTHROPIC_API_KEY`/`ANTHROPIC_BASE_URL` for Claude Code, a rewritten provider `baseURL`/`apiKey` for OpenCode). Credential variables, and any other variable carrying the key, are removed from the sandbox environment. Claude subscription OAuth (`CLAUDE_CODE_OAUTH_TOKEN` alone) and OpenCode providers outside `@ai-sdk/anthropic`, `@ai-sdk/openai` and `@ai-sdk/openai-compatible` fail closed instead of projecting a host key. Standard Anthropic/OpenAI credential names are supported. OpenCode also receives environment variables explicitly referenced by its selected provider's `{env:NAME}` fields; non-secret referenced values participate in the frozen configuration digest. API key rotation does not change that digest. Provider `{file:...}` interpolation and references to runtime-overridden environment variables are explicitly unsupported; use literal configuration or an explicit provider environment reference. - -## Resume and isolation - -Use `--resume` for solo runs and Codex native teams with the same workspace, task, output and build manifest. The saved harness, model, profile, executable and Skill loading are inherited. The host pins the executable's canonical path and file digest, native configuration bytes and endpoint environment identity. It checks this binding before dispatch, after writer shutdown and on resume. Changing the harness or frozen configuration requires a new run. Explicit `--harness-profile` or `--harness-executable` also opts Codex into the binding. `--codex` remains its compatible executable alias. - -For old fixed-task-graph runs, `host-tools` teams and host-mediated read-only investigators, use the original pinned TheoremOS revision and build manifest to resume. The current CLI still reads their saved records with `inspect`. To start a new native team or solo Skill run from old sources and notes, use `--continuation-source-run`. - -`planMathAgentSession` resolves Skill loading, role isolation, structured delivery and continuation before dispatch. New runs freeze that plan and compare it with the actual adapter plan. A CLI without native resume explicitly uses source-context continuation; a CLI without native schema enforcement uses a validated output file when the workflow supplies a validator. Neither is reported as a native capability. Historical Skill checkpoints without `researchSkillWorkflow: full` retain their original single-researcher workflow. - -Claude Code, OpenCode, the configured CLI harness and Codex proof-writing team mode require Linux and `/usr/bin/bwrap`. The shared process wrapper makes the host root read-only, exposes only the run worktree and dedicated native profile as writable directories, and masks protected roots and host socket directories. It exposes the existing pinned Lean lock file when needed. Research networking remains available. Native tool permission lists supplement this OS isolation. Before freezing or accepting source, the host requires the owned process and descendants to have stopped; unconfirmed shutdown quarantines that writer workspace. - -Codex team sessions additionally persist the host-observed identity of their isolated PID namespace init. Recovery checks that identity before reusing a writer worktree, including after abrupt host death. Running child assignments retain their sources and native thread but become interrupted until Lead explicitly assigns more work. Messages, queued tasks, pending deliveries and adoption records remain in the run state. The selected Codex profile must be outside the solver worktrees. - -## Accounting and evidence - -For research-workspace sessions, native invocation totals are added once per actual host turn, including when the same native conversation is reopened. Codex cumulative thread totals retain their original merge semantics. Both additional CLIs can synthesize zero counters when the provider omits usage. A generation with zero or incomplete input/output counts therefore reports unknown usage. Finite budgets block subsequent dispatches when usage is unknown or the observed allowance is exhausted. Research-workspace backends provide observed turn limits. Sealed roles instead use the shared controlled model relay's per-request admission and terminal usage receipts; native totals remain observational and are not charged a second time. - -Validation uses installed Claude Code 2.1.322 and OpenCode 1.19.5 with fixed loopback provider replies, plus disposable native protocol peers. It covers actual Skill reads, shell execution, native session resume, hidden-root denial, missing usage and confirmed shutdown without external model calls. Shared integration tests run each real adapter through the Skill solver and check correct proofs, wrong proofs and reusable helpers with real isolated Lean 4.33.0. These tests establish execution and acceptance behavior; they do not measure mathematical success rate or an efficiency advantage over direct harness use. - -Historical complete-cooperation regressions ran Claude Code, OpenCode and CLI adapters as real local processes with fixed responses to verify the Lead plan, Engineer delivery, independent Reviewer decision, real Lean acceptance and shutdown. Use the corresponding historical revision to reproduce those regressions. - -In the pinned historical version, prepare a portable comparison with `--harness ID --harness-profile CONFIG_TEMPLATE --harness-executable COMMAND --model MODEL`. Each arm receives the allowed frozen configuration in a fresh directory. Template, attempt and backend identities are checked before launch and reporting. Non-Codex common-Skill comparisons require file loading. +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/linux-cli.md b/docs/linux-cli.md index 3ee81706..60c20db2 100644 --- a/docs/linux-cli.md +++ b/docs/linux-cli.md @@ -1,76 +1,3 @@ -# Install the TheoremOS Linux CLI +# Linux CLI -Download the `linux-cli-x86_64` artifact from a successful **Rust Linux CLI** run -in [GitHub Actions](https://github.com/HuggingMath/theorem-os/actions/workflows/rust-linux.yml). -The package targets x86-64 Linux with glibc and is tested on Ubuntu 24.04. -Extract the Actions artifact first, then verify and unpack its tarball. - -```sh -sha256sum -c theorem-os-x86_64-linux-gnu-*.tar.gz.sha256 -tar -xzf theorem-os-x86_64-linux-gnu-*.tar.gz -cd theorem-os-x86_64-linux-gnu-*/ -./bin/theorem-os --help -``` - -Keep the extracted directory and add its `bin` directory to `PATH` if desired. -The installed `formalize --phase report` and `informalize --phase report` -commands export self-contained HTML with Lean source and links to its lines. -For the offline smoke test, install Git, Bubblewrap and Lean 4.36.0 with Elan, -then use a fresh directory. - -```sh -./bin/theorem-os example replay --dir ./replay -``` - -Use `./bin/theorem-os example prepare --dir ./tutorial` to prepare a new -single-agent tutorial. The installed CLI creates a Rust build manifest for the -tutorial and saves it with the case. -Add `--agent-team 2` to prepare a team tutorial. Set `--codex` to the team -backend described below, run `example check --dir ./tutorial` to preflight the -tutorial, then start from that checkpoint with `example resume --dir ./tutorial`. - -Single-agent online runs also need Codex and a provider profile. For teams, -download `codex-backend-linux-x86_64` from a successful -[Codex Backend Linux run](https://github.com/HuggingMath/theorem-os/actions/workflows/codex-backend-linux.yml). -The backend archive contains both executables and their build record. Extract -the Actions artifact, then verify and unpack its tarball. - -```sh -sha256sum -c theoremos-codex-backend-x86_64-linux-gnu-*.tar.gz.sha256 -tar -xzf theoremos-codex-backend-x86_64-linux-gnu-*.tar.gz -``` - -Keep `bin/codex` and `bin/codex-code-mode-host` together. Select the extracted -`bin/codex` with `--codex /absolute/path/to/bin/codex`. On Ubuntu 24.04, the -backend uses the system OpenSSL 3 libraries (`libssl3t64`). You can also build -the backend from its pinned source using the -[backend build instructions](https://github.com/HuggingMath/theorem-os/blob/main/scripts/codex-backend/README.md). - -Mathlib tasks need the locked packages for their Lean environment. Install -Bubblewrap and FUSE support (`squashfuse`, `squashfs-tools`, `fuse3` on Ubuntu) -for the independent verifier. The source revision for each CLI package is in -`SOURCE` alongside the binaries. See the -[migration guide](https://github.com/HuggingMath/theorem-os/blob/main/docs/rust-migration.md) -for preparing problems, choosing a provider and resuming runs. - -The installed CLI accepts HTTPS Responses profiles for an explicitly configured -model. Create a Codex profile directory with this `config.toml` and supply the -provider's bearer token in the host environment as `THEOREMOS_PROVIDER_API_KEY`. -Set `CODEX_HOME` to the profile or pass `--profile` to commands that accept it. -Use the configured model name when invoking the CLI. - -```toml -model = "your-model" -model_provider = "web_provider" - -[model_providers.web_provider] -name = "HTTPS Responses" -base_url = "https://provider.example/v1" -wire_api = "responses" -env_key = "THEOREMOS_PROVIDER_API_KEY" -``` - -The host sends requests to the configured HTTPS endpoint and keeps the bearer -token outside the model worker. Use a Responses service that supports the -selected reasoning effort and Codex tool calls. Online teams also require a -model with Codex multi-agent v2 support. +Follow the [usage guide](usage.md) to run the TypeScript CLI on Linux. The Rust package instructions are on the [migration/rust branch](https://github.com/HuggingMath/theorem-os-harness/blob/migration/rust/docs/linux-cli.md). diff --git a/docs/native-skill-comparison.md b/docs/native-skill-comparison.md index df8863e1..719e6fee 100644 --- a/docs/native-skill-comparison.md +++ b/docs/native-skill-comparison.md @@ -1,6 +1,6 @@ # 原生 Codex 任务与 Skill runtime 的隔离对照 -这套入口准备两个独立冷启动,用来观察 TheoremOS 的研究循环是否改善同一 Codex 任务的完成情况和消耗。当前只提供一个包含两条原始命题的 core Lean fixture;准备本身不调用模型,也没有测得效率收益。 +这套入口准备两个独立冷启动,用来观察 TheoremOS 的研究循环是否改善同一 Codex 任务的完成情况和消耗。该实验使用一个包含两条原始命题的 core Lean fixture;准备本身不调用模型,也没有测得效率收益。 两臂均使用 `deepseek-flash` / `high`、同一个已有 Sub2API profile、同一份原生加载的 `theoremos-research` Skill、任务文本、数学工具与环境投影。每臂单独的 workspace、运行记录和源码必须保留。每臂额度为 10000 token,单 writer,关闭原生子代理,不设置解题时限;正在执行的上游请求可超出额度,后续请求由现有 relay 计费门控停止。 @@ -9,29 +9,11 @@ | `native-skill` | 直接 `createCodexMathSession`,一次 `session.run` | 直接启动单个 Codex 会话,由它自主调用工具,返回后做验收 | | `runtime-skill` | 普通 `bin/math.ts run --research-mode skill` | 现有 Skill 研究循环、停止写入、反馈与后续 dispatch | -原生基线复用现有 app-server adapter,以对齐权限、Lean diagnostics、原生 Skill 和上游请求计费。它不是默认的 `codex exec`。共享的静态数学指导和工具帮助由 `buildCommonResearchGuide` 产生;两臂自己的交付协议仍然不同。native 侧不会处理任务内 helper 提交或发出纠正 turn,runtime 侧保留当前循环的行为。 +原生基线复用现有 app-server adapter,以对齐权限、Lean diagnostics、原生 Skill 和上游请求计费。它不是默认的 `codex exec`。实验固定了两臂共用的数学指导和工具帮助;两臂自己的交付协议仍然不同。native 侧不会处理任务内 helper 提交或发出纠正 turn,runtime 侧保留当前循环的行为。 两臂使用同样的 `proofProjectRoot`、缓存隐藏路径和 worker 环境。两臂的目录互相可读,属于现有研究权限和禁止读取外部候选解的指令约束;此入口没有提供容器级互相隔离。不要用它声称已排除跨臂读取,也不要将同一输入的第二次运行称为新的冷启动。 -## 离线准备 - -先在独立源码 snapshot 中构建,不要覆盖工作树已有 `out`: - -```bash -bun scripts/build.ts --state-root /ABS/EXTERNAL/build-state -bun scripts/mathematics/prepareNativeSkillComparison.ts \ - --directory /ABS/NEW/experiment \ - --build-manifest /ABS/EXTERNAL/build-state/builds/BUILD_ID/manifest.json \ - --profile /home/lzh/.config/deepscientist/math-sol-codex \ - --codex /ABS/CODEX \ - --max-total-tokens 10000 -``` - -准备脚本不读取或复制凭证,不修改原 profile;选择器只冻结 profile 的配置和模型目录摘要。实际模型会话仍使用现有 adapter 的临时 runtime profile。 - -产物包括公共任务、原始源码、环境投影,以及每臂的 `contract.json` 和 `launch.json`。`comparison.json` 固定两个计划样本及它们的摘要。环境、源码构建、模型程序、profile、Skill、任务、原题或 launch 字节变化后需要重新准备,原计划不能继续记作可比较样本。 - -真实启动需要单独授权。获授权后在 `launch.json.cwd` 执行其 `args`,按记录设置 `DEEPSCIENTIST_MATH_ENV_FILE` 和 `CODEX_HOME`;它已经包含合同摘要和精确路径。先运行 `native-skill`,保留全部产物,再运行 `runtime-skill`。同一臂拒绝再次启动,不做恢复实验。 +使用原实验的固定版本准备和运行对照。读取已保存的结果需要保留实验目录、原构建快照和固定的运行配置。 ## 验收、消耗与报告 @@ -46,7 +28,3 @@ bun scripts/mathematics/reportNativeSkillComparison.ts --directory /ABS/experime ``` 报告读取已有记录,不启动模型,也不重放 Lean。输入或观测摘要变化则标为 `invalid`,不参与结果或成本比较;尚未启动的臂为 `not-started`。数学结果可观测但 usage 缺失时,`outcomeComparable` 与 `costComparable` 分别报告。完整验证记录保留在原始 result/state 中,报告不自行宣称模型收益。 - -本地测试使用固定协议 peer 和固定 upstream SSE,真实执行 app-server adapter、loopback relay、进程停止、Lean 全目标检查和独立 S3。普通 Skill 循环由已有运行测试覆盖;新 CLI 参数和资源链另在可丢弃的任务上用实际 `--startup-only` 子进程核对,保持 0 turn、0 模型请求。这些测试验证实现,不代表真实模型效率。 - -本轮没有重启实验、跨题知识复用变量、多因素矩阵或其它 CLI 的对照实现。 diff --git a/docs/portable-workflows.md b/docs/portable-workflows.md deleted file mode 100644 index d3c488fe..00000000 --- a/docs/portable-workflows.md +++ /dev/null @@ -1,33 +0,0 @@ -# Harness selection in complete workflows - -Research methods and execution backends are separate choices. The existing formalization, independent review, proof explanation and automatic-library workflows now share `openWorkflowSession` instead of each creating a Codex session directly. Their mathematical inputs, output validation, role independence and acceptance checks remain in the existing workflows. - -The portable configuration field is `agentHarness`, an optional frozen identity containing `id`, executable path and SHA-256, dedicated profile path and native configuration digest. It is supported on the author and other role configurations, proof-explanation writer/auditors, automatic-library planner and automatic-library prover. Role configuration digests include it when present. Requests without it keep their original fields and digest interpretation, and continue through Codex. - -CLI `formalize`, `informalize` and `evaluate-formalization --phase review --execution model` accept `--harness`, `--harness-profile` and `--harness-executable`. An explicit selection freezes the real executable/configuration bytes; default invocations do not silently rewrite old requests. Model configuration and native identity are checked before dispatch and after close. Native session/cache files may grow. A changed binding requires a new request. Review resume without harness flags inherits an explicitly frozen selection. - -All four backends use the shared sealed-role implementation for these workflows: Linux user/mount/PID/IPC/UTS/network namespaces, role-only `/workspace`, immutable `INPUT.json`, `ROLE.md` and `OUTPUT.schema.json`, independently pinned Lean, and optional sealed mathematics sources/library. The host profile, original source paths, other roles and host credentials are absent. Research-workspace isolation remains a separate contract. - -The native process receives a disposable model capability. A host Unix-socket relay holds the real key and allows only the selected model, effort and inline local-tool protocol. Stored conversations/responses, remote files, hosted tools and arbitrary networking are rejected. The common transport handles admission, cancellation, credential redaction and provider receipts. In sealed roles provider receipts own usage accounting; missing native CLI counters cannot overwrite complete upstream receipts. Missing provider counters remain unknown. - -Claude Code uses its installed native executable with a generated minimal profile and the host's `ANTHROPIC_API_KEY` (or `ANTHROPIC_AUTH_TOKEN`) and optional `ANTHROPIC_BASE_URL`. It uses the native Messages API and existing print/stream-json tools. OpenCode uses its native HTTP/SSE server and a private Unix control socket; only that server is reachable from the host. Its frozen provider selects `@ai-sdk/anthropic`, `@ai-sdk/openai` or `@ai-sdk/openai-compatible`; original plugin/MCP/auth/session configuration is not projected. Only the selected model and effort variant enter the generated provider. A generic CLI supplies the explicit [sealed-role configuration](generic-cli.md#sealed-formalization-and-audit-roles), including its provider endpoint, client environment names and any interpreter/resources. Unsupported native protocols fail before a model request. - -Role prompts and output paths refer to `/workspace` and `/profile`. Native tools can write role outputs and run the pinned Lean binary at `/opt/lean/bin/lean`; source protocol files remain read-only. The existing host validator and independent proof acceptance still decide whether an output is accepted. Native completion is execution evidence. Sealed roles do not import host conversations, skills or native child agents; workflows reconstruct fresh attempts from frozen inputs. - -The independent statement audit uses the native final response on Codex, Claude Code and OpenCode. A generic CLI instead writes `/workspace/AUDIT-REVIEW.json` through the validated-file contract. After confirming writer shutdown and unchanged frozen inputs, the host rereads and validates that handoff, then writes the immutable `OUTPUT.json` and evidence bindings. Valid stdout cannot replace an invalid handoff. The audit remains a semantic opinion and does not establish proof acceptance. - -Automatic-library builds can retain the Codex planner while selecting a portable proof backend separately: - -```sh -theorem-os auto-library --phase prepare ... \ - --prover-harness claude-code \ - --prover-harness-profile DEDICATED_PROFILE \ - --prover-harness-executable /absolute/path/to/claude \ - --prover-model YOUR_MODEL --prover-effort high -``` - -The proof backend receives the normal solver workflow, isolation and independent Lean checks. Its expected executable/configuration binding is checked before and after each nested solver run; it cannot silently change while a build resumes. The planner's sealed-role requirement remains in force. - -`openSession` remains an explicit fixture/preset injection for offline tests. It cannot override an explicitly frozen production `agentHarness`; a conflict is rejected. Production adapter choice is recorded as the real harness ID, never as `injected-preset`. Fixed-response tests verify these execution contracts and compatibility; they do not establish mathematical success or efficiency gains. - -`tests/sealedHarness.test.ts` exercises real Linux isolation, tool writes, source freezing, correct/wrong independent Lean checks, credential/filesystem/network denials and cancellation. Native integration tests discover `claude` and `opencode` on `PATH`, or accept `THEOREMOS_TEST_CLAUDE_CODE_EXECUTABLE` and `THEOREMOS_TEST_OPENCODE_EXECUTABLE`. Only integrations missing their optional native executable are skipped; protocol and generic-CLI isolation tests still run. Local verification used Claude Code 2.1.322, OpenCode 1.19.5 and a disposable Python CLI against fixed loopback provider replies, without paid models. Real provider deployment, mathematical success rate and comparative efficiency require separate evidence. diff --git a/docs/rust-migration.md b/docs/rust-migration.md index 0a98efd5..d6cfdf10 100644 --- a/docs/rust-migration.md +++ b/docs/rust-migration.md @@ -1,279 +1,5 @@ -# Running the Rust migration branch +# Rust CLI migration -The first Rust release targets the Linux CLI. It covers single-agent proof runs, live Codex teams, Lean statement checks and independent proof acceptance, run recovery, and user-selected Lean library packs. +The Rust implementation, Linux package instructions and tests are maintained on the [migration/rust branch](https://github.com/HuggingMath/theorem-os-harness/tree/migration/rust). Resume a Rust run with its original binary and build manifest. -The browser workbench is outside this release. Automatic proof explanations, automatic library generation and benchmark reporting are optional workflows and do not gate the CLI release. The existing tools and historical archives remain available for compatibility. - -The Rust-only runtime uses Lean, Git, Bubblewrap and Codex as external executables. It runs without Bun or Node.js. Teams use the [TheoremOS Codex backend](../scripts/codex-backend/README.md) with AgentControl enabled. - -From the checkout, with Cargo and Rust 1.95 or later: - -```sh -cargo build --locked --release -p theorem-os --bin theorem-os --bin theorem-os-agent -./bin/theorem-os --help -./bin/theorem-os check-finite --input examples/finite/old-b1-nine-constraints.json -``` - -Download the Linux x86-64 archive from the successful Rust Linux CLI GitHub -Actions run or [build the same archive locally](linux-cli.md). To install only -the CLI from a local build, copy `target/release/theorem-os` to an installation -directory. The installed binary can run `example replay` and -`build --native-only` without the checkout or a JavaScript runtime. For an -installed binary, build manifests default to -`${XDG_STATE_HOME:-$HOME/.local/state}/theorem-os`. Set `--state-root` to save -them elsewhere. Keep the same installation directory and executable when -resuming a run. - -To run your own standard Lean task, prepare a new workspace and a Rust-only -manifest. Pass the `buildManifestRef` printed by `build` to the run. Keep the -run output outside the proof workspace. Use the same arguments and add -`--resume` to continue a saved run. - -```sh -./target/release/theorem-os bootstrap-lean-task --environment standard \ - --source Challenge.lean --task-file task.md --workspace work -./target/release/theorem-os build --native-only -./target/release/theorem-os run --workers 1 --workspace work --task-file task.md \ - --output result.json --build-manifest /absolute/path/to/manifest.json -``` - -Supply `--library-pack PACK.json` at preparation to pin a local library pack -into the starting commit. The solver and independent verifier both check the -frozen modules. -Use `--definition-targets Name,Namespace.Other` at preparation for definitions -whose bodies are part of the task. Lean checks those implementations and any -theorems that depend on them. Existing definitions outside the target list stay -frozen. - -For a live team, replace `--workers 1` with `--agent-team 2` and select the -patched backend with `--codex /absolute/path/to/codex`. The CLI defaults to -`out/codex-backend/codex` in the checkout. For an installed CLI, pass -`--codex` or set `THEOREMOS_CODEX_BACKEND_EXECUTABLE` to the installed backend. -The team size includes the Lead. -Use `--startup-only` to preflight the team without a model turn. Replace it -with `--resume` to start the saved run. For the addition tutorial, use -`example prepare --agent-team 2 --codex /absolute/path/to/codex --dir DIR` -and then `example check --dir DIR` and `example resume --dir DIR`. -Use the Sub2API profile or a Responses profile whose model supports Codex -multi-agent v2. -To verify a live provider and the patched backend on a new disposable task, run -`bun scripts/test-native-live-team.ts /absolute/path/to/codex /path/to/new-output`. -It uses the configured provider within a turn and token limit, interrupts after -a member turn is acknowledged, and records the resumed team and independent Lean -checks in `evidence.json`. - -For Mathlib 4.36.0, prepare with `--environment mathlib` and use a manifest -from `build --native-only`. Install the built packages at the revisions in the -generated `lake-manifest.json` under the Lean project's `.lake/packages`, or -point `DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS` to the installed package root. -Keep the package checkouts at their locked commits and keep generated files in -`.lake`. For example, a ProofWidgets checkout used for a JavaScript build can -have a generated `widget/package-lock.json.hash`. Use a clean copy of that -checkout for Rust proof runs. -Use explicit imports whose dependencies can be rebuilt offline from Lean -source. During a proof run, the candidate can add explicit `Mathlib.…` imports -from the same locked packages. The verifier rebuilds their dependencies and -includes the source digest in checkpoint and final acceptance. The team test -adds `Mathlib.Tactic.Lift` to a task that starts with -`Mathlib.Tactic.Linter.DirectoryDependency`. - -For `import Mathlib`, set `DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS` explicitly -to a complete compiled package tree from a trusted build of the exact revisions -in the task's lockfile. Rust verifies the Git source and seals the installed -compiler artifacts in a read-only image. The run and its Lean receipts bind -that image. Separate sandboxes elaborate the statement and candidate, then the -kernel replays the candidate declarations against the sealed Mathlib base. -Keep the package tree and saved image available when resuming. The first run -creates the image in the run directory. You can reuse it across runs with -`--proof-environment-cache-dir /absolute/path/to/private/cache`. -The Rust verifier also stages the package files and temporary image on that -cache's disk. Choose a cache on a larger volume if the system disk is short on -space. For standalone statement checks, the disposable cache follows `TMPDIR`. -For a task with explicit imports that depend on Lake build artifacts, pass -`--compiled-mathlib` at run time and again on resume. It uses the same trusted -compiled image. For example, a candidate can add `Mathlib.Data.Nat.Init` even -though its full dependency tree cannot be rebuilt by the source-only path. - -| Native entry | Contract retained | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | -| `build` | Invoke esbuild, hash the sources and bundles, and durably publish the solver build manifest | -| `batch` | Run prepared jobs with bounded concurrency, isolated logs, checkpoint-friendly cancellation and persisted outcomes | -| `doctor` | Check tools, credentials and connectivity, prepare a dependency image and verify its read-only mount | -| `edit` | Queue approval for an exact saved plan version after validating the run and locking its journal | -| `inspect` | Export the archived plan or inspect independent, cooperative and agent-team records as JSON or Markdown | -| `bootstrap-lean-task` | Prepare a new workspace from a Lean source file, task description and optional frozen pack | -| `bootstrap-lean-eval` | Prepare the public solver baseline and separate verifier at either pinned revision, with host-selected or explicit packs | -| `bootstrap-imo` | Prepare an isolated workspace from a pinned Git commit and write the original contract and bootstrap receipt | -| `check-lean` | Compile saved Lean files, verify the environment and elaborate closed types and expressions in an isolated snapshot | -| `auto-library --phase prepare/demand/pack/usage/inspect` | Freeze a planner and prover, capture a gap, select modules, report their use and read saved builds | -| `library-pack extract/upstream/inspect` | Extract reusable modules from a run commit, backport selected source files or inspect an existing pack | -| `library-catalog build/inspect/search/select` | Build versioned catalogs, query releases and write the selected library pack and lock file | -| `library search/get/request` | Read the pinned catalog, rank interfaces, page through sources, and queue installation requests for the host | -| `search-lean` | Search verified package sources by name or goal, with ranked, bounded results and signed index reuse | -| `freeze-retrieval` | Capture the allowed Lean source files and write a manifest with their sizes and digests | -| `check-finite` | Exhaustive finite Boolean replay, advisory witnesses, input digest and incomplete exit code | -| `knowledge build/enrich/pack/search/get/source/finding/dependencies/consumers/stats` | Build and page through saved catalogs, run Lean enrichment and verify each object against the active host library | -| `kernel-certificate` | Generate, print or write chunked Lean modules; generated source remains unchecked until Lean verifies it | -| `continuation read/search` | Read pinned historical material in UTF-16 pages and rank passages for one or more queries within the same output budget | -| `declarations` | Search a saved index or read an exact declaration; rank, type previews, byte budget and omissions | -| `checkpoint` | Append a host-requested acknowledgment to a worker journal; queuing is not host acceptance | -| `list-lean-eval` | Read the pinned Git checkout and check its files before indexing; `--leaderboard` additionally uses curl | -| `summarize` | Read saved receipts and write the existing report format with its digest | -| `hub` | Log in, export and validate HuggingMath bundles, and preview, apply or record imports | -| `first-proof` | Prepare frozen cases, verify review records and report target-by-target offline evidence | -| `compare` and `sample-putnam` | Publish and check historical reports from frozen plans, knowledge archives and run receipts | -| `web-funnel` (separate binary) | Aggregate operator report in JSON or Chinese text; does not run the Web service | - -`check-lean --file` compiles the requested files and their local dependencies. It supports candidate references. Adding `--type` and `--context` runs a query in a private proof-erased snapshot, and `--expression` checks a term against that type. Mapped workers compile inside their existing sandbox. The host uses a Linux namespace or the configured container backend. Rust holds the lease for sealed packages, captures Lean output and saves the advisory records. - -`check-lean --health` checks the pinned compiler and holds the sealed package lease for the duration of the probe. Use either `--workspace` for a Lean project or `--worktree` for a worker directory. - -`run check-statement` checks files from a Git commit in an offline Bubblewrap sandbox. It accepts a committed `lakefile.toml` or `lakefile.lean`. For a `lakefile.lean`, the pinned Lake executable translates the declarative settings in a separate sandbox. The check compiles the committed local imports, including modules in package and library `srcDir` directories. Install any Git dependencies under `.lake/packages` at the revisions in the committed Lake manifest. Rust verifies the tracked package files, mounts a read-only image, and records its digest in the advisory report. Statement checking allows `sorry` in proof bodies. - -For a statement that needs a custom Lake prerequisite, pass `--lake-build TARGET` for each target. Rust runs `lake build` with the committed configuration before elaborating the requested files. Targets can read the committed Lean sources and Lake configuration and write artifacts under `.lake` in the disposable snapshot. The JSON report lists the requested targets and records the build phase. This option applies to the standalone statement check. - -With `run --workers 1 --no-explanations` and either the default Sub2API profile or a simple Codex Responses profile, Rust runs the public tutorial and supported prepared `theorem-os.lean-task.v1` problems. The native path accepts a pristine `Submission.lean` of up to 65,536 bytes, distinct ASCII declaration names, theorem and designated definition targets, and imports from the pinned toolchain's `Init`, `Std` and `Lean` modules or from an explicit frozen local library pack. A Rust-only manifest also supports the Mathlib imports described above. Host-selected library bindings and other external package environments use the frozen solver host. The standalone binary supports `run --startup-only` on prepared projects. Adding `--check-statement` saves Lean diagnostics for the original committed statement and checks frozen library modules before marking the run prepared. Rust and the source host can resume each other's standard Lean preparations. - -`bootstrap-lean-task` writes the pinned Lake environment, sources, root commit and receipt. Run `bun scripts/test-native-task-bootstrap.ts` to compare the root commit and receipt bytes in all six current environments and read each host’s output with the other. - -The receipt reader authenticates ordinary Lean tasks in every currently supported environment and both historical Lean 4.33 configurations. It compares the root Git tree, protected files, declaration index and optional library modules. For Lean-Eval it checks the benchmark pin, canonical statement hashes, ownership and library configuration, including the historical dependency lock. Hosted knowledge reads use the same problem identity and check the full archived catalogue before serving a page. - -Rust reconstructs ordinary Lean tasks from the Git root commit, compares the receipt against the original declarations and protected files, and resumes the saved Codex thread under its turn and token limits. The proof check and the independent final evaluation each export the original and candidate in separate sandboxes. A fresh Lean kernel checks the candidate against the frozen target types and definitions. When the run uses a local library pack, the verifier reads the modules at the frozen Git revision and replays their exported declarations before checking the proof. For supported explicit Git package imports, both checks rebuild the imported modules from verified sources. Top-level `import Mathlib` uses the sealed compiled base described above. - -With a manifest from `build --native-only`, Rust starts the Lead and members in separate worktrees and resumes their Codex threads from the run directory. It persists mailbox ownership and acknowledgments across recovery. Members can use `theoremos_team` to submit new helper theorems in `Submission.lean`. The host stops the contributor and independently checks the proposed declarations before the Lead can adopt them. The host checks the merged draft before accepting an adoption. Final Lean acceptance still covers every original target. - -Pass `--plan-approval` to ask the Lead for a plan before assigning team work. -Read the saved version with `theorem-os inspect --run RESULT.json --format plan`, then -queue `theorem-os edit --run RESULT.json --approve-plan VERSION`. The gate waits -for approval of that exact version and remains in place across resume. - -Both installed command names and `bun run math` use `bin/theorem-os`. The launcher uses the release binary in its own checkout for migrated commands. It keeps the full command list and runs the original host for other modes, including historical team runs. A checkout without a release binary uses Bun. To invoke the reference implementation explicitly, use `bun bin/math.ts`. The standalone executable under `target/release` lists its own supported modes. - -The independent tutorial supports `example prepare`, `check`, `solve`, `resume` and `replay` at the package entry. Preset replay checks two bundled candidates with Lean without calling a model. Solve and resume use the configured provider and the frozen problem. The worker receives a digest-checked `math.native` and can run `check-lean` from its worktree. Historical team or custom component cases use their original host. - -The native `prepare` phase freezes Codex, Claude Code, OpenCode and generic CLI builds, including their executable and configuration digests, demand and definition targets, against the validated headless build manifest. The `demand` phase authenticates the published finding against its Git commit and captures the current goal, dependency scope and typed lemma requests. - -Rust reads published Auto module records in publication order and verifies their file names, source digests and dependencies. With a host configuration, `auto-library --phase pack` authenticates each record and registers the selected pack for its destination workspace. The `usage` phase reads the solution commit. Adding `--live true` includes observations from current drafts and identifies frozen modules whose bytes changed. The `inspect` phase verifies the saved request and reports its rounds, publications and recorded token use. - -For Auto library `run` and `replay`, Rust selects each module and round, applies time and token limits, and checks the frozen pool and host authorization again before resuming a phase. Rust reserves module names under the shared pool lock, extracts accepted declarations from Git, and publishes the frozen record after checking its digest and reservation. Rust builds the planner input and digest from the frozen library, task and prior feedback. The Rust replay driver selects the preset planner outputs and proof candidates, verifies the recorded failed rounds and checkpoint continuation, installs the published pack into a fresh downstream workspace, and checks the resulting proof and library usage. Rust checks the module statements and frozen packs against committed sources, runs the preset proof rounds, and independently rechecks the accepted module and its downstream proof in Lean. Both replay and online builds use Rust orchestration. Online builds with a Codex planner and one independent Codex prover use the native session host. Replay runs against the pinned Lean toolchain. Resuming a finished build runs entirely in Rust and checks the build manifest, harness identity, and historical packs under the build lock. Run `bun scripts/test-native-auto-library.ts` with the release CLI and Lean 4.36.0 installed to exercise module publication, use in a second proof, and recovery after a pool record changes. - -The worker image builds the restricted `theorem-os-agent` binary for its libc. All eleven worker tools dispatch directly to Rust through `math.native`. The package uses hard links for each tool and retains `math.mjs` for saved command lines. Its Rust commands run without a Bun executable or a process addon in the tool directory. `plan-validate` checks archived cooperative plans and authenticated prepared workspaces. `hub` exports and validates bundles, logs into a Hub account and stages or reconciles private imports. Its import journal preserves the batch, plan, retry key and returned file identities across an uncertain network response. - -The historical `compare` and `sample-putnam` commands publish reports, retain previous evidence by digest, and check report freshness in Rust. Rust binds each stored run to the original dataset, method, provider, skill and token allowance. It verifies v1 and packed v2 knowledge catalogs and reports retained retrievals, references and proof receipts. Putnam samples authenticate each child plan and compare paired outcomes within the same problem. Both reporting phases run without Bun. - -The four offline `formalize` phases run in Rust. The `prepare` phase freezes the source, build manifest, selected harness and review configuration, and writes the configured retrieval corpus and compatibility names. The `inspect` phase validates the saved request, state identity and approval evidence. If a run stopped after finishing a round and freezing its publication evidence, `formalize --phase run` verifies that evidence and publishes the artifact and prepared proof workspace in Rust. The `report` phase exports the original statement, Lean targets and matching reviewer quotations in one HTML file. Installed packages export a self-contained report, and source checkouts with built Web assets can export the interactive report. When `run` reopens a completed request, Rust takes the run lock, checks the saved environment and provider profile, verifies the artifact and authenticates the proof workspace. Rust also settles a run that has exhausted its round or time limit when no dependency image needs preparation. The `replay` phase runs the three-round addition tutorial in Rust using the sandboxed Lean worker, the preset role protocol and the same artifact and proof workspace checks as the authoring host. Native model sessions support direct and task-preserving reviews with Codex through Sub2API or a configured HTTPS Responses profile. For independent formalization, Rust derives queries from the accepted plan and sends the generator pinned Mathlib source hints. It supports lexical search, exact Lean symbol lookup, and lexical queries filtered by resolved object names. An optional older library declaration list checks the names spelled in the elaborated candidate and returns missing names to the generator for repair. Independent formalization can freeze an explicit reference with `--reference-file`, `--reference-pairs` and `--reference-provenance`. Lean checks correspondence separately from model review. Mounted project library packs, falsification, and other harnesses use the compatible package entry. Both native authoring and Rust replay freeze the role input, instructions and output schema with the same Rust code. The host checks those bytes before a correction turn, after closing the writer and when restoring a checkpoint. In the native build, Rust generates the formalization query, runs Lean in the compiler sandbox, validates the exported binders, kernel terms and structures, freezes the compilation record and creates the proof workspace. - -The `evaluate-formalization` CLI prepares, reviews, and scores blind bundles in Rust. Preparation freezes reviewer inputs separately from labels and references, and scoring compares saved decisions with the original labels. For Codex through Sub2API or an HTTPS Responses profile, Rust starts isolated roles for direct v1 and structured v2 review. New model runs default to v2. Rust constructs proof-erased Lean observations, checks task fidelity, and starts independent backtranslation and recheck roles when the review needs them. A completed unavailable observation produces an unknown decision. Reviewers can correct invalid structured output in the same thread, with recorded cumulative usage. Rust revalidates frozen inputs, observations, and receipts when reopening a run, so a role with a valid receipt does not need another model turn. Preset v1 and v2 replay remains available. Historical Lean 4.8 reviews and providers outside the native role host use the Bun compatibility path. - -The six `first-proof` phases run through the Rust CLI. It checks the ten pinned Git blobs, validates coverage and review inputs, freezes an approved case with its original TeX, and binds archived S3 receipts to every original target. Rust authenticates the complete archived formalization evidence when it imports or reopens a model-reviewed case. Reports count a prepared case as attempted only after a recorded solver turn. - -The continuation parity test compares the release binary with the TypeScript CLI on the same frozen snapshots. Cases cover Chinese and Unicode text, multiple query rankings, byte limits and damaged or replaced files. To build and exercise the worker bundle locally: - -```sh -bun install --frozen-lockfile -cargo test --locked --workspace --all-targets -THEOREMOS_TEST_BUN_PARITY=1 cargo test --locked --test web_funnel -cargo test --locked --test declarations -- --ignored -cargo build --locked --release --bins -bun scripts/test-native-continuation.ts -bun scripts/test-native-library.ts -bun scripts/test-native-library-catalog.ts -bun scripts/test-native-library-pack.ts -bun scripts/test-native-knowledge.ts -bun scripts/test-native-knowledge-pages.ts -bun scripts/test-native-lean-source.ts -bun scripts/test-native-retrieval.ts -bun scripts/test-native-health.ts -bun scripts/generate-native-archive-schema.ts --check -bun scripts/test-native-edit.ts -THEOREMOS_TEST_AGENT_BINARY="$PWD/target/release/theorem-os-agent" bunx vitest run tests/agentTools.test.ts -``` - -## Linux process supervision and Codex - -The Rust addon delivers TERM and KILL to owned detached child groups, checks PID namespace identities and collects surviving session members after a tracked child exits. It frames Codex app-server messages, matches replies to outstanding requests and attributes early output to the turn acknowledged by Codex. Rust starts the app-server directly or through Bubblewrap, passes the pinned package descriptors into the sealed role, and manages the protocol pipes. For an isolated writer it reads the namespace identity from Bubblewrap and checks that the namespace and Linux session have both stopped. The TypeScript host still handles session callbacks and timers. Linux pidfd support is required for native signal delivery. - -Rust validates the default Sub2API Responses request before loading the host credential or opening an upstream connection. It admits only the configured model, effort and supported stateless request shape. Rust sends the request to `127.0.0.1:8080`, decompresses the response, redacts the host credential and tracks terminal usage in streamed and ordinary bodies. The addon provides the same validation, credential loading, upstream client and usage observer to the hosted workflows. Bun still owns scheduling for those workflows and handles other upstream protocols. - -For independent native runs, the CLI also owns the private loopback listener and the S1 request ledger. It saves a pending receipt before sending the request, records the settlement before exposing the completed response and stops new requests when a finite budget is exhausted or usage is missing. On resume it marks any pending receipt as interrupted. Codex receives a disposable relay capability. The runtime profile lives beside the run archive and does not write to the configured provider profile. - -Released formalization and proof explanation workflows use the Rust role launcher inside Bubblewrap. It forwards the allowed model route and the private control socket and carries the child process exit status back to the host. The hosted workflow still decides which roles to run. - -The worker image builds the addon for its own libc and enables it for the worker entrypoint and headless bundles. The original TypeScript source entrypoints are available in development checkouts. To compile and test a native headless bundle locally, from the checkout on Linux: - -```sh -cargo build --locked --release -p theoremos-process -./target/release/theorem-os build --native-process "$PWD/target/release/libtheoremos_process.so" --state-root "$PWD/../theoremos-native-build-state" -bun scripts/test-native-process.ts -bun scripts/test-native-build.ts -``` - -Keep `theoremos-process.node` beside the built JavaScript. Each native bundle checks its embedded digest before loading the addon. The worker source entrypoint gets the same digest from the image build. The test exercises an offline Codex conversation, cancellation, stop receipts and addon loading under Node and Bun. The namespace test requires a host that permits Bubblewrap user and PID namespaces: - -```sh -cargo test --locked -p theoremos-process -cargo test --locked -p theoremos-supervision reaps_an_owned_namespace_init -- --ignored -``` - -## Scheduling and recovery - -Rust parses the solver command line, applies resource limits and checks resumed settings against the frozen run. Run `bun scripts/test-native-run-options.ts` to compare the release addon with the source host. Rust calculates token budget status from recorded usage, applies retry and cooldown rules, and selects which saved proof checkpoint to resume. With a finite token limit, an exhausted budget or missing final usage blocks new requests. The host rechecks the frozen source and receipt identity before it reuses a successful proof check. - -The recovery test kills a disposable solver process at 12 points, including before and after request acknowledgment, after helper verification, and after the original proof has passed. The second process reads the saved state using the same native build. Run the test on a Linux host with Bubblewrap and the standard fixture's Lean 4.33.0 toolchain installed. - -```sh -THEOREMOS_TEST_PROCESS_ADDON="$PWD/target/release/libtheoremos_process.so" bunx vitest run tests/skillProcessRecovery.test.ts -``` - -## Research loop, run archives and final acceptance - -In a native build, Rust selects each next step in the Lead loop. Plan approval and recovery precede admission to another model turn. A planning response, rejected source or saved helper returns the Lead to the start of the loop. A candidate ready for a whole-proof check goes to verification. The independent tutorial and supported standard Lean tasks run these steps in Rust. Team runs use the Rust scheduler and frozen Bun host described above. - -For cooperative proofs, Rust derives declaration changes from committed Lean sources, preserves scoped names and attached documentation, and merges checked edits against the current source. A complete delivery can copy the original bytes only when all owned files match the seed and every declaration change and authorized import matches the delivery. Concurrent changes use declaration-level merging. Conditional consumers can move past declarations in the same context to follow their checked inputs. Missing edits and missing insertion anchors remain distinct for recovery. Rust indexes scoped declarations, local opens and notation in the full proof source. It resolves named and receiver-field references, propagates removed dependencies and writes the projected files for Lean. It also prepares the compact projection used to check a helper. A Rust snapshot now selects retained goals, class instances, scoped syntax and possible source dependencies for each helper. It checks frozen definition targets and the exact versions of assumed inputs, builds dependency hints and renders the full or compact source for Lean. Dependency hints bind the source commit and declaration digests. Fresh Lean checks still decide acceptance. The hosted solver schedules those checks, including rechecks of recovered helpers. - -Rust reads and atomically replaces the S1 run state file. It checks file identity on read, syncs the replacement and its directory, and returns the written inode identity for subsequent saves. Both runtimes use the same archive schema and JSON encoding. To check that each runtime can read the other's records, run `bun scripts/test-native-archive.ts` after building the release addon. - -For S3, Rust checks the integrated commit and source digest against the candidate receipt and selects the local Lean, external command or official comparator gate. The host invokes Git through the Rust subprocess runner and launches Lean and the selected comparator in the existing environments. The end-to-end replay uses the tutorial's offline session and real Lean 4.36.0. It checks the final run records and exit codes for acceptance, external rejection, an unavailable evaluator and a timeout. It also resumes a completed run and checks that changing its frozen effort is rejected. - -```sh -cargo build --locked --release -p theoremos-process -bun scripts/test-native-solver.ts -``` - -For Lean-Eval, the process addon checks the public config, hole metadata, Lean headers in Challenge and Submission, namespace ownership, Lake targets and pinned toolchain text. Run `bun scripts/test-native-lean-eval.ts` to compare accepted and rejected bindings. Pass a public Lean-Eval checkout to compare its generated projects as well. The Rust CLI prepares current and historical workspaces with separate source and verifier worktrees, certificate and theory slots, and optional library packs. Rust resolves `THEOREMOS_LIBRARY_HOST_CONFIG` against the task and pinned benchmark revision. It checks modern and legacy releases, the Lake dependency lock and transitive exclusions, and records the selection in the receipt and baseline commit. Run `bun scripts/test-native-eval-bootstrap.ts CHECKOUT` to compare both pinned baseline commits, recovery receipts, verifier manifests and installed modules using an offline leaderboard. The checkout must contain both benchmark commits. - -Rust binds each Lean receipt to its commit, theorem, source file and statement digests. A batch of several targets must also have distinct receipt and check IDs and match the original request order. Rust probes the pinned compiler in the project environment, parses import spans and calculates the build order and digests of local Lean modules. It checks all candidate source roots for excluded imports before verification. Rust decodes Lean's JSON diagnostics and its older text format, including source locations and unsolved goals. - -For project-local builds, Rust verifies the files Lean wrote, signs the persistent module cache and checks each artifact before restoring it. Cache keys, signatures and file names are shared with older builds. Official proof checks rebuild from committed sources. - -Rust verifies the sealed package mount and metadata against the current project configuration, acquires the lease from its Unix socket, and releases it after use. In a native build, Rust reads the frozen mathematics environment, selects tool settings and strips credentials from the projection used in a proof run. - -Formalization evidence readers authenticate the compiler diagnostics, original source, target context, and the exact inspector program for each historical protocol. The shared Rust reader supports the v1 independent review, v2 planned review, v3 structured review and v4 compiler-only evidence. It checks each role's input, output, thread and configuration, source quotes, kernel expressions and recorded statement types. It also validates frozen exemplars for both planning and generation, name compatibility and falsification configurations, and the identity and sources of imported libraries. For retrieval it reconstructs the lexical queries, symbol requests, origins, ranks and results. Fidelity reviews bind each original fragment and Lean binder to the frozen candidate and verify their reference receipts against the original comparison program. Rust reads these archives without launching Bun. First Proof uses the same reader before applying its own independent-review requirement. - -## Web service - -The Web image starts `theoremos-web`. Rust listens on the configured port, issues session and CSRF cookies, records activity, renews sessions and handles logout. It serves `GET /api/session`, `/api/session?runs`, the run list with ETags and the run change event stream using persisted sessions and the account and run information supplied by the workbench. Rust also handles community display names, agent tokens, task claims and releases, first-pass receipts and recovery after restart. The listener authorizes and validates community publication and submission requests. It journals the records and indexes, consumes the proof queue and stores the verdict, points and activity together. A dedicated private Unix socket sends the frozen Lean input to the workbench for source review and sandbox checking. After a restart Rust replays incomplete writes and rechecks pending submissions. It also serves run details, observations, event and action pages, snapshots, share links, historical source and check receipts, command and guidance receipts, v2 evidence downloads and digest-verified saved archives for the authenticated owner. The Rust listener builds the proof outline and exports the local verification ZIP from the saved original source, candidate and evaluator report. The Rust trajectory index reads mathematical events and observation frames in bounded batches. Its page and version endpoints retain plan changes, source revisions and individual check receipts. Run creation and cancellation use the Rust listener for session, CSRF, ownership and maintenance checks. The Rust job backend computes request identities, queue limits and FIFO slots, creates the initial record, persists run summaries and events, and applies cancellation. The private Bun dispatcher resolves provider keys, quotas and research assets. The Rust proof supervisor creates and starts the Docker container, sends the request over private stdin and captures the last checkpoint on cancellation. If Docker attach disconnects, Rust waits for the worker and replays its saved receipts before removing the container and volumes. The dispatcher validates live and recovered messages and tracks the execution deadline. Rust inspects worker image capabilities, delivers plan approvals and checkpoint requests, and runs Lean statement prechecks in disposable networkless containers. Inside the worker image, `theoremos-web-check` writes the frozen files and invokes Lean directly to compile the required modules, source and candidate query. This check requires only its Rust binary and the Lean toolchain at runtime. The workbench builds the candidate query and grants its target receipt only after a successful compiler exit and a matching Lean information message. Direct Bun development runs still use the Bun supervisor unless configured with `THEOREMOS_WEB_DOCKER_HOST`. Rust also starts and removes the separate containers for formalization, background audits, proof explanations and TeX compilation. Before Lean compiles a generated formalization, Rust checks its declarations, extracts and hashes the theorem targets, and erases proof bodies and comments while preserving definitions. The background audit worker then uses Rust to freeze the reviewer’s files, bind the sandbox receipt to those files and the pinned toolchain, and prepare the model turn. After the writer closes, Rust checks the submitted review and its exact quotations against the original statement and compiled Lean types, stores the result, and verifies its digest on resume. Bun opens the isolated model session, forwards requests and usage, and checks the result against the upstream compiler evidence. The other language workers and the PDF and TeX response decoder still run in Bun. The dispatcher publishes current run views to the session registry. Rust handles the home-page login redirect, password login and changes, email challenges, signup, consent, account preferences and encrypted provider keys. The listener creates and verifies login codes and delivers them through SMTP or SMTPS. Deployments using additional Nodemailer options send the mail through the private backend, while Rust owns the browser challenge. Other dynamic workbench routes use Bun over a private Unix socket. `theoremos-web --public-only` serves built pages, tasks and accepted community submissions without a Bun process. Rust also serves the community overview, task, submission and signed-in profile reads as well as shared snapshots, applying the visibility rules to saved records. The `theoremos-web-assets` binary builds the versioned workbench assets, content hashes and compressed files. Running `bun run build:web` in a checkout requires Cargo or `THEOREMOS_WEB_ASSETS_BIN` pointing to that binary. - -The Rust listener serves the health, readiness and product status endpoints. It reports the public build identity and checks the worker image, maintenance state and available disk space. It also serves signed-in knowledge catalog lists, search and detail pages directly from the owner's pinned files. It checks the packed manifest and reads declaration metadata, sources, dependencies, consumers and advisory findings through the same Rust library as the CLI. Catalog publication still uses the workbench host. - -The listener reads the packaged team profile catalog and serves the module registry and private module plans. Rust validates and saves module plans using the same version identity as the comparison CLI. It checks the session again before writing and rejects edits based on an older version. - -Rust serves the administrator's operations panel and maintenance toggle. It checks the session and administrator role, and requires CSRF authentication for changes. The worker dispatcher publishes slot counts and queue times for research, formalization, proof explanations, prechecks, chat and paper jobs. Rust computes the statistics, reads disk and worker status, and combines mail failure counters. The dispatcher remains responsible for running the queues. - -The Rust listener serves the administrator's account overview, manages the file-backed signup allowlist, and updates account restrictions. Blocking an account revokes its sessions and event streams immediately. The dispatcher stops outstanding work. If it is unavailable, the listener retains the restriction and records the pending cleanup for retry. - -With the release binary and the repository dependencies installed, run `bun scripts/test-native-web.ts` to verify public and authenticated HTTP behavior, including cookies, writes and streamed responses. After `bun run build:web`, add `--browser` to exercise the public pages in Chromium. - -## Remaining runtime - -The preset addition replay runs from the Rust binary and the pinned Lean toolchain. It needs no JavaScript dependencies or previously built solver bundle. For an independent tutorial with the default Sub2API profile or a simple Responses profile, use `theorem-os example prepare --native-only --dir DIR` and then `example check`, `example solve` or `example resume`. `theorem-os build --native-only` makes the same kind of manifest for supported single-module runs, including teams, and the offline formalization tutorial. Native proof runs with the default Sub2API profile can generate explanations after acceptance. The solver reads the accepted Lean source and local library modules from the checked Git commit. Each target has a separate explanation archive. Resume reuses approved explanations and continues unfinished ones. Set `--explanation-language zh|en` to select the language or `--no-explanations` to skip generation. The tutorial command keeps its proof-only defaults. A manifest binds the exact Rust binary, so keep that binary to resume the run. - -For proof explanations, `informalize --phase prepare` freezes the root proof and its local imports in Rust. Rust binds the selected writer and auditors to their model configuration and computes the declaration batches. The shared evidence reader reconstructs each saved auditor input, verifies its source quotations, goal verdicts and citations, and regenerates the approved Chinese or English Markdown. The standalone `inspect` phase reports missing, approved or invalid artifacts. Reopening an approved run verifies the saved request, environment, provider profile and artifact under the run lock. The `report` phase exports an offline HTML file with the archived proof, explanation, reviewer comments and links to Lean source positions. When a formalization is bound to the proof, the report also shows the original problem and its corresponding declarations. When every explanation batch has a saved approval, Rust verifies the writer and auditor evidence and publishes the Markdown and JSON archive under the run lock. If publication stopped after the archive was written, Rust verifies and reuses it. The native CLI extracts the Lean outline and runs Codex writer and auditor sessions with the Sub2API profile. Requests using other harnesses can use the compatible package entry. - -The standalone Rust `continuation-seed` imports the canonical Git sources and advisory worker drafts into an idle run. It freezes attachments, preserves shared member notes and strips private session history from inherited diagnostics. Imports without helper declarations run entirely in Rust. Rust compiles local modules in isolation, checks the expected type of each helper with Lean and publishes fresh declaration receipts. Projects without a Lake configuration can use the compiler directly when they have no external dependencies. Rust verifies the manifest's Git revisions in the local `.lake/packages` tree or in a cache root from the frozen environment. It seals those packages in a read-only SquashFS image for the compiler and retries failed batches one declaration at a time. Projects that declare dependencies without a Lake configuration or lack a compatible cache use the solver bundle through the package entry. Input selection happens before the destination is modified. - -To reuse a previous run in the installed CLI, prepare a fresh single-agent destination with `run --startup-only` for the same frozen task. Pass the old and new results to `continuation-seed --source-run OLD_RESULT --run NEW_RESULT --build-manifest NEW_MANIFEST`. Repeat the command if the import is interrupted. Resume the destination with `run --resume` and the original destination options. Rust checks the completed import receipt and immutable attachments before dispatch, and the solver can search the imported drafts. The usual independent Lean evaluation decides final acceptance. - -The native host CLI fully implements 28 of the 35 entries in `bin/math.ts`, including all 11 worker commands. The seven commands with partial Rust support are `run`, `example`, `continuation-seed`, `auto-library`, `informalize`, `formalize` and `evaluate-formalization`. The native `component init` creates a Rust ordering module. `component check` compiles it with rustc and runs a local contract fixture. Existing TypeScript components use their pinned historical version. The Rust CLI runs a Rust child process to construct, mount and lease SquashFS dependency images with the installed filesystem tools. The older host still uses the Python helper. Both use the same cache format and can reuse each other's images. - -The standalone `inspect` command exports the versioned plan, JSON and Markdown for independent, cooperative and agent-team archives. It binds results to their state, reads a bounded journal prefix, verifies frozen continuation and declaration records, and reconstructs obligations, usage and contributions. For native teams, it checks the archived delivery and the corresponding Git versions before attributing a declaration to a target. `recover --snapshot` verifies the manifest, imports the filtered Git history, reconstructs worker drafts and records which helpers need fresh checks. `recover --recheck` reopens the fixed sources, independently checks helpers with Lean, and records the new receipts. Both recovery modes run without Bun. The full solver, online formalization workflows, several authenticated Web routes and the interactive browser client still depend on TypeScript. +For the TypeScript CLI, see the [usage guide](usage.md). diff --git a/docs/solver-modules.md b/docs/solver-modules.md index 86f9b6f7..2966f830 100644 --- a/docs/solver-modules.md +++ b/docs/solver-modules.md @@ -84,7 +84,7 @@ Lead 先根据原题、定义和已有发现判断可行的数学路线,再提 - 每次解析都从族任务重新派生成员:带 `familyMember` 标记的旧成员被丢弃,区间缩小时族任务里失效的成员 id 被移除。`ID_cN` 形式的 id 全部保留给成员,Lead 用这种 id 写任务报 `math_plan_family_member_edited`;改区间、状态或依赖只能改族任务。成员目标文字不含成员总数,扩大 `hi` 时未变区间的成员版本不变。 - RESEARCH.md 中同步的已接受图和计划补丁基都折叠掉成员,Lead 只看到族任务;`COOPERATION.json` 仍列出全部成员。goal-path 复核里,恢复暂停成员的答案改写为恢复族任务;成员不产生机械 connect,也不作为 assume 的消费者。 -族任务派发时,类型预检不等待它自己的成员在源码中出现(族类型不提及成员)。预检 elaborated 后,M2 的可选 `assembleFamily` 在模型派发前写出族证明:`fun i hlo hhi => …`,按 `i < bound` 平衡二分,每个叶子是 `NAME_cK i 下界 上界`,下界用 `Nat.not_lt.mp`。写入方式同 tactic battery(填补 sorry 或插在预检锚点前,在一次性 checkout 中提交),这一步不运行 Lean。候选随后走普通任务检查:条件族把派发时的全部 lemma 输入(含已证成员)绑定为显式假设,通过即以 `conditional` 发布;成员全部集成后,宿主按现有条件证明流程复用并无条件复检合并版本。检查失败或候选无法放置时照常派发模型。同一族版本、依赖和环境在一个进程内只装配一次,不消耗模型 turn 或 attempts;`task_family_assembly` 事件记录结果、`assumedInputs`、commit 与 receipt。显式 `conditional:false` 的族要等全部成员集成后才开工。成员上下文提示只证自己的区间。用 `familyAssemblyProof` 生成的 256 个成员加族证明,在 Lean 4.35.0-rc3(仅 core,成员为项证明)中单文件编译约 0.5 秒、峰值约 512 MiB,`#print axioms` 报告不依赖任何公理。 +旧档案中的 `task_family_assembly` 对应当时宿主生成的候选证明。若需重现,请使用该实验的固定版本。 有限 Boolean 推断可先用 `theorem-os check-finite --input FILE` 或 `--json JSON` 复算。输入是 `theorem-os.finite-boolean-cnf.v1` 的变量、固定赋值和 CNF 子句;输出绑定规范数据与原始输入摘要,保留完整赋值计数、满足数及有界 witness。超过公开枚举规模限制时返回 unsupported,不能报告矛盾;没有新增墙钟截止。结果仅针对输入约束,仍是 advisory,须连同精确数据进入研究证据,不能代替 Lean 或 S3。`examples/finite/old-b1-nine-constraints.json` 重放旧九行约束,在 256 种赋值中得到 5 个满足染色;它只否定该组约束的旧矛盾推断,不否定几何构型或原题。 diff --git a/docs/web-workbench.md b/docs/web-workbench.md index ef096f6d..3e718346 100644 --- a/docs/web-workbench.md +++ b/docs/web-workbench.md @@ -271,7 +271,7 @@ docker compose -f apps/web/compose.yml up -d web | `THEOREMOS_WEB_KEY_SECRET` | 空 | 64 位十六进制,加密账号保存的 API Key;空表示不能保存。只放在 `.env` 或密钥管理里,丢失或更换后已保存的 Key 失效 | | `THEOREMOS_WEB_CLIENT_IP_HEADER` | 空 | 代理写入的访客地址请求头(如 `cf-connecting-ip`),用于按访客限流 | -如本机依赖已齐备,也可只用 Docker 跑 worker、用 Bun 启动网页服务: +本机可以用 Bun 启动网页服务,由工作台管理 Docker worker。 ```bash bun install --frozen-lockfile diff --git a/examples/components/EXPERIMENTS.md b/examples/components/EXPERIMENTS.md index 97067460..127858eb 100644 --- a/examples/components/EXPERIMENTS.md +++ b/examples/components/EXPERIMENTS.md @@ -28,7 +28,7 @@ 自定义规则替换或追加的是模型收到的策略文字,不是 M1 的调用实现或 M5 的分配函数。 报告列出实际组件版本差异,M1 规则的 M4 注入版本也会被记录。 -`goals-first` 不再是内置调度策略,仅保留为 [README.md](README.md) 的组件示例:在研究者仍活跃时,默认 M5 已分别优先分配引理和原题目标, +历史 `goals-first` 示例仅改变 M3 排序。在研究者仍活跃时,当时默认的 M5 已分别优先分配引理和原题目标, 会抵消这种跨任务种类的排序变化。只检查 M3 输出数组不足以说明整个调度行为发生变化。 M2 检查和 S3 完整原题验收在所有组中保持固定。 diff --git a/examples/components/README.md b/examples/components/README.md index 27f876a9..63ace726 100644 --- a/examples/components/README.md +++ b/examples/components/README.md @@ -1,11 +1,13 @@ # 检查研究组件的排序策略 +The Rust component tooling is on the [migration/rust branch](https://github.com/HuggingMath/theorem-os-harness/tree/migration/rust). + 从仓库根目录执行下面的命令。首次构建需要 Cargo,此后 `check` 使用本机的 `rustc` 和链接器编译组件,只依赖 Rust 标准库。 ```bash cargo build --locked --release --bin theorem-os -bin/theorem-os component init --name my-search -bin/theorem-os component check --name my-search +./target/release/theorem-os component init --name my-search +./target/release/theorem-os component check --name my-search ``` `init` 生成 `rust/components/my-search.rs`。文件中的 `ready(tasks, routes)` 接受只读任务和路线,返回按优先级排列的任务引用。默认模板用 `ready_tasks` 筛选就绪任务,再把目标排在研究任务前面。修改排序策略后,在同一文件更新 `ID`。已有同名 Rust 文件、旧 TypeScript 组件或旧运行入口都会阻止创建。 @@ -31,7 +33,6 @@ M3 的 `ready` 排序用于至少三名 Agent 的协作任务;单 Agent 和预 小题默认不限制调度轮数、时间和 Token,适合检查接入流程,不能据此判断策略优劣。 修改源码后使用新案例;恢复原实验时保留它原来的源码、构建、环境和配置。 -下面保留手动组合组件和运行任意已准备题目的方式。 ## 组件合同 @@ -47,54 +48,5 @@ M3 的 `ready` 排序用于至少三名 Agent 的协作任务;单 Agent 和预 S1 档案和 S3 最终评测独立于这些研究决策。 M2 的局部成功与模型审阅均不能跳过 S3 对完整原题的重检。 -## 示例:只替换 M3 - -[runGoalsFirst.ts](../../scripts/mathematics/runGoalsFirst.ts) 是完整入口。 -它保留默认的证明构造、检查、上下文和协作组件,只将已就绪原题目标排在辅助任务之前: - -```ts -import { directSolverModules, type SolverModules } from '../../src/solver/modules'; -import { goalsFirstResearchTasks } from '../../src/solver/modules/search'; - -const modules: SolverModules = { - ...directSolverModules, - id: 'goals-first-example-v1', - M3: { - ...directSolverModules.M3, - version: `${directSolverModules.M3.version}/example-goals-first-v1`, - ready: goalsFirstResearchTasks, - }, -}; -``` - -`goalsFirstResearchTasks` 先调用原有就绪筛选,再排序,保留依赖、暂停与路线预算检查。 -可以在此基础上实现自己的排序规则;返回值必须来自当前可启动任务。 - -在实验固定的历史版本中,按[快速开始](../../README.md#快速开始)准备依赖、题目和任务文件后,从仓库根目录执行。 - -```bash -bun run build -export MATH_BUILD_MANIFEST="/absolute/path/to/the/new/manifest.json" -export MATH_RUN_ROOT="/absolute/path/to/prepared/problem" - -bun scripts/mathematics/runGoalsFirst.ts \ - --build-manifest "$MATH_BUILD_MANIFEST" \ - --workspace "$MATH_RUN_ROOT/workspace" \ - --task-file "$MATH_RUN_ROOT/task.md" \ - --output "$MATH_RUN_ROOT/goals-first-result.json" \ - --workers 4 \ - --startup-only -``` - -预检不调用模型。随后用相同入口和参数,移除 `--startup-only` 并添加 `--resume`, -开始真实求解。使用已有的 Codex profile 时,按快速开始设置 `CODEX_HOME`。 -该入口已注入组件组合,请保留默认 `--scheduler plan`,不要再叠加其他调度策略。 - -自定义实现放入 `src/`,入口放入 `scripts/` 或 `bin/`,使源码纳入构建清单。 -修改组件行为后更新相应 `version` 并重新构建;版本参与运行身份,已有运行会拒绝不同组件版本。 -恢复原实验应保留原构建与组件;测量新组件应使用全新题目工作区和输出目录。 - -比较方法时固定题目、模型、环境、预算和评测器,记录所替换组件及其版本。 -网页同格式方案的批量对照入口、首轮配置和证据边界见[模块实验](EXPERIMENTS.md)。 -单智能体、独立并行和协作的运行与汇总方式见[对照实验](../imo2026/COMPARISON.md)。 -这个示例展示组件替换,不代表排序策略已经带来性能提升。 +`goals-first` 是旧版 M3 排序示例,复现时使用原实验固定的构建和运行入口。 +历史模块配置及比较方式见[模块实验](EXPERIMENTS.md)。 diff --git a/resources/cli-harnesses/README.md b/resources/cli-harnesses/README.md deleted file mode 100644 index 2193b9b1..00000000 --- a/resources/cli-harnesses/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# Headless CLI profiles - -Copy one profile directory into a new dedicated native profile, then use `--harness cli --harness-profile DIR --model MODEL --effort none`. The executable must be installed separately. See the [configuration contract](../../docs/generic-cli.md) for custom commands and wrappers. - -| Profile | Version examined | Evidence | Session and accounting | -| --- | --- | --- | --- | -| `generic` | User supplied | Template; adapt args to the executable | One-shot, full context each time, usage unknown | -| `gemini` | Gemini CLI 0.68.0 | Official package executed through `createCliMathSession` and bubblewrap with a fixed loopback provider; start and exact-ID resume passed | Host UUID; headless result stats describe this invocation | -| `qwen` | Qwen Code 0.27.4 | Official package executed through `createCliMathSession` and bubblewrap with a fixed loopback provider; start and exact-ID resume passed | Host UUID; result usage is cumulative across resume | -| `aider` | Aider 0.86.2 | Official PyPI source and configuration validation; native binary execution remains untested | One-shot message file and text; usage unknown | - -All presets expose `none` for effort because this profile does not bind a portable reasoning-level control. They preserve the selected model. Extend `efforts` only alongside a real native `{effort}` binding. Native CLI upgrades may change flags or event semantics; freeze the installed executable and start a new run when changing versions/configuration. - -For example: - -```sh -mkdir -p DEDICATED_PROFILE -cp -R resources/cli-harnesses/gemini/. DEDICATED_PROFILE/ -bun bin/math.ts run --harness cli --harness-profile DEDICATED_PROFILE \ - --model YOUR_GEMINI_MODEL --effort none \ - --workspace NEW_WORKSPACE --task-file TASK_FILE \ - --output RESULT_FILE --build-manifest BUILD_MANIFEST -``` - -Supply credentials using the names in `inheritEnvironment`. Keep them out of profile files and args. Qwen and Aider declare `researchProvider`, so the host relay holds the OpenAI-compatible key and the native process sees only a disposable capability. Aider's profile relays only its OpenAI-compatible provider; it no longer inherits `ANTHROPIC_API_KEY`. Gemini's native API has no host relay yet: a research session with `GEMINI_API_KEY` set fails with `math_cli_provider_relay_unsupported` rather than exposing the key. HOME defaults to the dedicated profile. Gemini additionally sets `GEMINI_CLI_HOME` to a private home root; the native CLI appends `.gemini`. Qwen sets `QWEN_HOME` to a private settings/session directory. Explicit system settings paths prevent fallback to host system paths; Gemini may ignore these profile files when its privileged settings ownership checks fail. Do not interpret that as those files taking effect. - -Gemini and Qwen retain `usage.completeness: "partial"`: the local probes establish event mapping and continuity, not complete accounting for every provider/tool/background combination. With a finite token budget the host stops subsequent dispatches after an incomplete turn. Cached counters are already part of input totals. Gemini headless resume was measured at 40/5 then 40/5 tokens; Qwen at 40/5 then 80/10. Neither preset claims a latest individual request size. - -Qwen uses `--bare`, disables advisor/workflow and keeps chat recording for exact resume. The inspected version's bare mode disables managed memory, dream, team sync, automatic Skill loading and structured recall, avoiding additional memory model requests after a result. Bare mode also disables some native context/search features; shell/network access and explicit Skill reads remain available. Neither probe performed paid/external model calls or measured proof-solving performance. - -Aider is a file editor and does not provide a general autonomous read/shell tool loop. Its profile explicitly supplies the pinned main Skill via `--read`, and starts each invocation with the full host request. Add the problem's editable files with Aider's native file arguments and create `DIR/state` before use. Read-only reference files and validation commands need explicit native configuration or a suitable wrapper. `--config` and `--env-file` do not disable all Aider default discovery: it still considers config and `.env` files in its private home and git/project roots. Freeze or remove unintended native project settings in a new workspace before starting; do not assume this preset supports unattended Lean research. - -These profiles preserve the host's source freezing, trajectories and independent mathematical acceptance. A final native reply or a successful command exit grants no proof acceptance. diff --git a/resources/cli-harnesses/aider/aider.conf.yml b/resources/cli-harnesses/aider/aider.conf.yml deleted file mode 100644 index 5425155e..00000000 --- a/resources/cli-harnesses/aider/aider.conf.yml +++ /dev/null @@ -1,3 +0,0 @@ -# Explicit config has precedence; Aider still reads default config locations. -# The host must supply an isolated process home and frozen cwd/git config. -{} diff --git a/resources/cli-harnesses/aider/cli.json b/resources/cli-harnesses/aider/cli.json deleted file mode 100644 index c5e4cb1e..00000000 --- a/resources/cli-harnesses/aider/cli.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "schema": "theorem-os.cli-harness.v1", - "executable": "aider", - "args": ["--model", "{model}", "--message-file", "{promptFile}", "--read", "{workspace}/.agents/skills/theoremos-research/SKILL.md", "--config", "{profile}/aider.conf.yml", "--env-file", "{profile}/empty.env", "--yes-always", "--no-pretty", "--no-stream", "--no-auto-commits", "--no-dirty-commits", "--no-gitignore", "--no-check-update", "--no-analytics", "--no-fancy-input", "--no-restore-chat-history", "--chat-history-file", "{profile}/state/aider-history-{turnId}.md", "--llm-history-file", "{profile}/state/aider-llm-{turnId}.txt"], - "prompt": "file", - "session": {"mode": "fresh"}, - "output": {"format": "text"}, - "efforts": ["none"], - "environment": {"NO_COLOR": "1"}, - "inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_API_BASE"], - "researchProvider": {"wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_API_BASE"}, - "configurationFiles": ["aider.conf.yml", "empty.env"] -} diff --git a/resources/cli-harnesses/aider/empty.env b/resources/cli-harnesses/aider/empty.env deleted file mode 100644 index 1facd82d..00000000 --- a/resources/cli-harnesses/aider/empty.env +++ /dev/null @@ -1 +0,0 @@ -# Credentials are passed only through the descriptor's named environment keys. diff --git a/resources/cli-harnesses/gemini/cli.json b/resources/cli-harnesses/gemini/cli.json deleted file mode 100644 index 934afac1..00000000 --- a/resources/cli-harnesses/gemini/cli.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "schema": "theorem-os.cli-harness.v1", - "executable": "gemini", - "args": ["--model", "{model}", "--output-format", "stream-json", "--skip-trust", "--approval-mode", "yolo", "--prompt", "{prompt}"], - "prompt": "argument", - "session": { - "mode": "generated", - "startArgs": ["--session-id", "{sessionId}"], - "resumeArgs": ["--resume", "{sessionId}"] - }, - "output": { - "format": "jsonl", - "text": { - "field": "/content", - "when": [{"field": "/type", "value": "message"}, {"field": "/role", "value": "assistant"}], - "mode": "append" - }, - "sessionId": {"field": "/session_id", "when": {"field": "/type", "value": "init"}}, - "usage": { - "when": {"field": "/type", "value": "result"}, - "inputTokens": "/stats/input_tokens", - "outputTokens": "/stats/output_tokens", - "cachedInputTokens": "/stats/cached", - "scope": "turn", - "completeness": "partial" - }, - "failures": [{ - "when": [{"field": "/type", "value": "result"}, {"field": "/status", "value": "error"}], - "reason": "invalid-request" - }] - }, - "efforts": ["none"], - "environment": { - "GEMINI_CLI_HOME": "{profile}/home", - "GEMINI_CLI_NO_RELAUNCH": "1", - "GEMINI_CLI_SYSTEM_DEFAULTS_PATH": "{profile}/system-defaults.json", - "GEMINI_CLI_SYSTEM_SETTINGS_PATH": "{profile}/system-settings.json", - "NO_COLOR": "1" - }, - "inheritEnvironment": ["GEMINI_API_KEY", "GOOGLE_GEMINI_BASE_URL"], - "configurationFiles": ["home/.gemini/settings.json", "system-defaults.json", "system-settings.json"] -} diff --git a/resources/cli-harnesses/gemini/home/.gemini/settings.json b/resources/cli-harnesses/gemini/home/.gemini/settings.json deleted file mode 100644 index 5f74b1af..00000000 --- a/resources/cli-harnesses/gemini/home/.gemini/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "security": {"auth": {"selectedType": "gemini-api-key"}}, - "telemetry": {"enabled": false}, - "advanced": {"autoConfigureMemory": false} -} diff --git a/resources/cli-harnesses/gemini/system-defaults.json b/resources/cli-harnesses/gemini/system-defaults.json deleted file mode 100644 index 0967ef42..00000000 --- a/resources/cli-harnesses/gemini/system-defaults.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/resources/cli-harnesses/gemini/system-settings.json b/resources/cli-harnesses/gemini/system-settings.json deleted file mode 100644 index 0967ef42..00000000 --- a/resources/cli-harnesses/gemini/system-settings.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/resources/cli-harnesses/generic/cli.json b/resources/cli-harnesses/generic/cli.json deleted file mode 100644 index a7f29f87..00000000 --- a/resources/cli-harnesses/generic/cli.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "schema": "theorem-os.cli-harness.v1", - "executable": "/absolute/path/to/your-agent", - "args": ["--model", "{model}"], - "prompt": "stdin", - "session": { "mode": "fresh" }, - "output": { "format": "text" }, - "efforts": ["none"] -} diff --git a/resources/cli-harnesses/qwen/cli.json b/resources/cli-harnesses/qwen/cli.json deleted file mode 100644 index 02363c41..00000000 --- a/resources/cli-harnesses/qwen/cli.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "schema": "theorem-os.cli-harness.v1", - "executable": "qwen", - "args": ["--bare", "--auth-type", "openai", "--model", "{model}", "--advisor", "off", "--workflow-mode", "off", "--chat-recording", "true", "--output-format", "stream-json", "--approval-mode", "yolo", "--prompt", "{prompt}"], - "prompt": "argument", - "session": { - "mode": "generated", - "startArgs": ["--session-id", "{sessionId}"], - "resumeArgs": ["--resume", "{sessionId}"] - }, - "output": { - "format": "jsonl", - "text": {"field": "/result", "when": {"field": "/type", "value": "result"}, "mode": "replace"}, - "sessionId": { - "field": "/session_id", - "when": [{"field": "/type", "value": "system"}, {"field": "/subtype", "value": "init"}] - }, - "usage": { - "when": {"field": "/type", "value": "result"}, - "inputTokens": "/usage/input_tokens", - "outputTokens": "/usage/output_tokens", - "cachedInputTokens": "/usage/cache_read_input_tokens", - "scope": "session", - "completeness": "partial" - }, - "failures": [{ - "when": [{"field": "/type", "value": "result"}, {"field": "/is_error", "value": true}], - "reason": "invalid-request" - }] - }, - "efforts": ["none"], - "environment": { - "QWEN_HOME": "{profile}/qwen-home", - "QWEN_CODE_SYSTEM_DEFAULTS_PATH": "{profile}/system-defaults.json", - "QWEN_CODE_SYSTEM_SETTINGS_PATH": "{profile}/system-settings.json", - "QWEN_CODE_MODELS_DEV_REFRESH": "off", - "NO_COLOR": "1" - }, - "inheritEnvironment": ["OPENAI_API_KEY", "OPENAI_BASE_URL"], - "researchProvider": {"wireApi": "chat-completions", "apiKeyEnvironment": "OPENAI_API_KEY", "baseUrlEnvironment": "OPENAI_BASE_URL"}, - "configurationFiles": ["qwen-home/settings.json", "system-defaults.json", "system-settings.json"] -} diff --git a/resources/cli-harnesses/qwen/qwen-home/settings.json b/resources/cli-harnesses/qwen/qwen-home/settings.json deleted file mode 100644 index fe9f1725..00000000 --- a/resources/cli-harnesses/qwen/qwen-home/settings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "general": {"chatRecording": true}, - "telemetry": {"enabled": false}, - "memory": { - "enableManagedAutoMemory": false, - "enableManagedAutoDream": false, - "enableAutoSkill": false, - "enableTeamMemory": false, - "enableTeamMemorySync": false, - "enableStructuredRecall": false - } -} diff --git a/resources/cli-harnesses/qwen/system-defaults.json b/resources/cli-harnesses/qwen/system-defaults.json deleted file mode 100644 index 0967ef42..00000000 --- a/resources/cli-harnesses/qwen/system-defaults.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/resources/cli-harnesses/qwen/system-settings.json b/resources/cli-harnesses/qwen/system-settings.json deleted file mode 100644 index 0967ef42..00000000 --- a/resources/cli-harnesses/qwen/system-settings.json +++ /dev/null @@ -1 +0,0 @@ -{} diff --git a/rust/cli/Cargo.toml b/rust/cli/Cargo.toml deleted file mode 100644 index 8b341f8f..00000000 --- a/rust/cli/Cargo.toml +++ /dev/null @@ -1,38 +0,0 @@ -[package] -name = "theorem-os" -version = "0.1.0" -edition = "2024" -license = "AGPL-3.0-only" -publish = false -default-run = "theorem-os" - -[dependencies] -chrono = { version = "0.4", default-features = false, features = ["std", "clock"] } -futures-util = "0.3" -http-body-util = "0.1" -hyper = { version = "1", features = ["server", "http1"] } -hyper-util = { version = "0.1", features = ["tokio"] } -libc = "0.2" -memchr = "2" -num-bigint = "0.4" -num-traits = "0.2" -regex = "1" -ryu-js = "1" -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order", "float_roundtrip", "raw_value"] } -sha2 = "0.10" -sha1 = "0.10" -subtle = "2" -toml = "0.9" -tempfile = "3" -unicode-normalization = "0.1" -icu_properties = "2.2" -icu_segmenter = { version = "2.2", features = ["compiled_data"] } -theoremos-retrieval = { path = "../retrieval" } -theoremos-solver = { path = "../solver" } -tokio = { version = "1", features = ["rt", "time", "process", "signal", "net", "io-util", "macros"] } -theoremos-lean = { path = "../lean" } -url = "2" -icu_collator = "2.2" -theoremos-library = { path = "../library" } -theoremos-supervision = { path = "../supervision" } diff --git a/rust/cli/src/auto_library.rs b/rust/cli/src/auto_library.rs deleted file mode 100644 index 23bacd23..00000000 --- a/rust/cli/src/auto_library.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! Run and replay automatic library builds. -mod replay; -mod workflow; -use crate::{build, edit}; -use serde_json::{Value, json}; -use std::path::Path; -use theoremos_library::auto; - -fn pool_operation(op: &str, directory: &Path, input: &Value) -> Result { - let pool = auto::pool::Pool::for_build(directory, input)?; - if op == "taken" { - return Ok(json!(pool.taken()?)); - } - pool.ensure()?; - for attempt in 0..=200 { - let lease = match edit::Lease::acquire(&pool.directory, "pool.lock") { - Ok(lease) => lease, - Err(e) if e.to_string() == "math_runtime_lease_busy" && attempt < 200 => { - std::thread::sleep(std::time::Duration::from_millis(100)); - continue; - } - Err(e) => return Err(e.to_string()), - }; - let result = if op == "reserve" { - json!(pool.reserve(input["name"].as_str().ok_or("auto_library_name_invalid")?)?) - } else { - pool.publish(directory, input)?; - Value::Null - }; - lease.held().map_err(|e| e.to_string())?; - return Ok(result); - } - Err("math_runtime_lease_busy".into()) -} - -fn prepare_replay(directory: &Path, input: &Value) -> Result { - use std::os::unix::fs::DirBuilderExt; - let root = build::root(input["root"].as_str()).map_err(|e| e.to_string())?; - let directory = build::resolve(directory).map_err(|e| e.to_string())?; - build::canonical(&directory).map_err(|e| e.to_string())?; - if directory.starts_with(&root) || root.starts_with(&directory) { - return Err("Keep auto-library directories outside the source repository.".into()); - } - let mkdir = |path: &Path, parents| { - std::fs::DirBuilder::new() - .recursive(parents) - .mode(0o700) - .create(path) - }; - mkdir(directory.parent().ok_or("math_path_invalid")?, true).map_err(|e| e.to_string())?; - mkdir(&directory, false).map_err(|e| { - if e.kind() == std::io::ErrorKind::AlreadyExists { - "Replay directory already exists; use a new directory.".to_owned() - } else { - e.to_string() - } - })?; - let manifest = build::build(&[ - "--native-only".into(), - "--root".into(), - root.to_str().ok_or("math_path_invalid")?.into(), - "--state-root".into(), - directory - .join("builds") - .to_str() - .ok_or("math_path_invalid")? - .into(), - ]) - .map_err(|e| e.to_string())?; - let file = manifest["buildManifestRef"] - .as_str() - .ok_or("math_build_manifest_invalid")?; - auto::replay::prepare_build(&root, &directory, Path::new(file), input, &|file, root| { - build::verify_solver_manifest(file, root).map_err(|e| e.to_string()) - })?; - Ok(json!(file)) -} - -pub fn operation(args: &[String]) -> Result<(), String> { - let [operation, directory] = args else { - return Err("Invalid Auto library operation".into()); - }; - let input = serde_json::from_reader(std::io::stdin().lock()).map_err(|e| e.to_string())?; - let result = match operation.as_str() { - "replay-plan" => replay::plan(&input)?, - "replay-round" => replay::round(Path::new(directory), &input)?, - "extract" => { - theoremos_library::packing::build("extract", input, &std::env::vars().collect())? - } - "bootstrap-task" => { - let workspace = input["workspace"].as_str().ok_or("math_path_invalid")?; - theoremos_library::lean_task::bootstrap( - Path::new(workspace), - &input["task"], - &std::env::vars().collect(), - None, - )? - } - "taken" | "reserve" | "publish" => pool_operation(operation, Path::new(directory), &input)?, - _ => auto::build::operation(operation, Path::new(directory), input)?, - }; - serde_json::to_writer(std::io::stdout().lock(), &result).map_err(|e| e.to_string())?; - Ok(()) -} - -fn supports_runtime(request: &Value) -> bool { - let environment = request["environment"].as_str(); - let manifest = request["buildManifestRef"].as_str().map(Path::new); - let prover = &request["prover"]; - crate::role_host::supports(&request["planner"]) - && prover["workers"] == 1 - && prover["coordination"] == "independent" - && prover - .get("agentHarness") - .is_none_or(|harness| harness["id"] == "codex") - && (environment == Some("standard") - || environment == Some("mathlib") && manifest.is_some_and(build::is_native_manifest)) -} - -/// Keep unsupported historical role and proof configurations on their existing packaged host. -pub fn supports(args: &[String]) -> bool { - let Ok(root) = build::native_root() else { - return true; - }; - let Ok(Some(directory)) = auto::cli::session_directory(args, &root) else { - return true; - }; - if auto::build::state(&directory).is_ok_and(|state| { - state.is_some_and(|state| { - matches!( - state["status"].as_str(), - Some("built" | "none" | "exhausted") - ) - }) - }) { - return true; - } - let Ok(bytes) = edit::read(&directory.join("request.json"), 8 << 20) else { - return true; - }; - serde_json::from_slice::(&bytes).is_ok_and(|request| supports_runtime(&request)) -} - -pub fn run(args: &[String]) -> Result { - let root = build::native_root().map_err(|e| e.to_string())?; - if let Some(directory) = auto::cli::replay_directory(args, &root)? { - return replay::run(&root, &directory); - } - let directory = - auto::cli::session_directory(args, &root)?.ok_or("auto_library_directory_required")?; - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|e| e.to_string())?; - let summary = runtime.block_on(workflow::run(&root, &directory, None))?; - println!("{}", serde_json::to_string_pretty(&summary).unwrap()); - Ok(match summary["status"].as_str() { - Some("exhausted") => 2, - Some("stopped") => 1, - _ => 0, - }) -} diff --git a/rust/cli/src/auto_library/plan.schema.json b/rust/cli/src/auto_library/plan.schema.json deleted file mode 100644 index 9175eaba..00000000 --- a/rust/cli/src/auto_library/plan.schema.json +++ /dev/null @@ -1,207 +0,0 @@ -{ - "type": "object", - "additionalProperties": false, - "required": [ - "inputDigest", - "decision", - "reason", - "name", - "summary", - "sources", - "lean", - "target", - "application", - "remaining", - "consumerApplication" - ], - "properties": { - "inputDigest": { - "type": "string", - "pattern": "^[a-f0-9]{64}$" - }, - "decision": { - "type": "string", - "enum": [ - "module", - "none" - ] - }, - "reason": { - "type": "string", - "minLength": 1, - "maxLength": 4000 - }, - "name": { - "anyOf": [ - { - "type": "string", - "pattern": "^[A-Z][A-Za-z0-9]{2,47}$" - }, - { - "type": "null", - "const": null - } - ] - }, - "summary": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 2000 - }, - { - "type": "null", - "const": null - } - ] - }, - "sources": { - "anyOf": [ - { - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 400 - }, - "maxItems": 12 - }, - { - "type": "null", - "const": null - } - ] - }, - "lean": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 131072 - }, - { - "type": "null", - "const": null - } - ] - }, - "target": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 256 - }, - { - "type": "null", - "const": null - } - ] - }, - "application": { - "anyOf": [ - { - "type": "string", - "minLength": 1, - "maxLength": 2000 - }, - { - "type": "null", - "const": null - } - ] - }, - "remaining": { - "anyOf": [ - { - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 1000 - }, - "maxItems": 8 - }, - { - "type": "null", - "const": null - } - ] - }, - "consumerApplication": { - "anyOf": [ - { - "type": "object", - "additionalProperties": false, - "required": [ - "declaration", - "application" - ], - "properties": { - "declaration": { - "type": "string", - "minLength": 1, - "maxLength": 1000 - }, - "application": { - "type": "object", - "additionalProperties": false, - "required": [ - "expression", - "expectedType", - "context", - "remainingGoals" - ], - "properties": { - "expression": { - "type": "string", - "minLength": 1, - "maxLength": 12000 - }, - "expectedType": { - "type": "string", - "minLength": 1, - "maxLength": 12000 - }, - "context": { - "type": "object", - "additionalProperties": false, - "required": [ - "file", - "declaration" - ], - "properties": { - "file": { - "type": "string", - "minLength": 1, - "maxLength": 1000 - }, - "declaration": { - "type": "string", - "minLength": 1, - "maxLength": 1000 - } - } - }, - "remainingGoals": { - "type": "array", - "items": { - "type": "string", - "minLength": 1, - "maxLength": 12000 - }, - "maxItems": 32 - } - } - } - } - }, - { - "type": "null", - "const": null - } - ] - } - } -} diff --git a/rust/cli/src/auto_library/planner.md b/rust/cli/src/auto_library/planner.md deleted file mode 100644 index faa6d138..00000000 --- a/rust/cli/src/auto_library/planner.md +++ /dev/null @@ -1,16 +0,0 @@ -You make a bounded decision about one Lean library dependency. Read the frozen INPUT.json and OUTPUT.schema.json before submitting. Do not search Mathlib source, inspect the whole library, run Lean, or try to solve the original theorem. The host checks statements and a separate prover proves them. If no useful tractable dependency appears from the challenge, submit decision none immediately. -A solver will later work on INPUT.challenge. Identify a reusable dependency that removes a concrete step from its proof. It may be a substantial general lemma; it need not solve the whole challenge. When that dependency itself needs a missing fact, propose the smaller prerequisite first so later modules can import it. -INPUT.demand, when present, is a source-bound gap discovered during solving. First use INPUT.library to avoid recreating an available dependency. Address that precise remaining gap and its typed lemmaRequests; do not replace it with an unrelated textbook fact. The current solver handles these requests as owned helpers and checks their consumers before integrating them; published modules are frozen for later attempts. -When an exact application is known, also return consumerApplication:{declaration:"FULL_MODULE_THEOREM",application:{expression:"CLOSED_LEAN_TERM",expectedType:"EXACT_LEAN_TYPE",context:{file:"Submission.lean",declaration:"TARGET"},remainingGoals:["UNRESOLVED_PREMISE"]}}. consumerApplication.declaration is a theorem from your proposed module, including the full TheoremOS.Auto namespace. Only context.declaration is the original target. Use consumerApplication: null when the exact term is unknown. The host checks this term in a separate original-consumer snapshot after the module passes verification, and records whether it actually uses the named theorem. Application elaboration alone never accepts the original problem. -For decision module, target is the exact qualified name of a theorem in INPUT.challenge.source or an explicit INPUT.challenge.definitionTargets entry. In application, name a fully qualified theorem from your proposed Lean source, explain the substitution and why its premises can be supplied. In remaining, list the cases, premises and mathematical obligations still open after using it. Choose none for an unrelated lemma, an already available result, or a premise with no route from the target. A remaining hard step alone is not a reason to reject a useful dependency. -The module is general mathematics: definitions and lemmas a textbook or paper would state, that the problem's proof can use. Do not restate the problem, a special case shaped to it, or its answer. You may follow the literature for standard definitions and lemmas (cite them in sources), but never copy a published solution of this problem or an existing formalization of it. -INPUT.library lists modules already available (hand-written and earlier auto modules). It names theorems in earlier auto modules so you can build a new dependency on them. Their sources are in library/: read a specific listed auto module if you need its exact statement, but do not search the entire library. Do not duplicate an existing module. takenNames are names you may not use. -Name the module with UpperCamelCase (3 to 48 letters or digits). It becomes the file Submission/Library/Auto/.lean. Put every declaration inside `namespace TheoremOS.Auto.` … `end TheoremOS.Auto.`; outside it only imports, comments, open, set_option, universe and variable lines are allowed. -Import only modules of INPUT.environment and modules listed in INPUT.library. In the standard environment, Mathlib is unavailable. Elementary Nat results can use the default Lean imports without an import line. Definitions must be complete. Every theorem and lemma body is `by sorry` or `sorry`: a solver proves them next. -Never use axiom, unsafe, native_decide, implemented_by, extern, #eval, run_cmd or other meta commands, elab or initialize. notation, macro, syntax and attribute commands must be local or scoped. Do not use _root_. -State one small, reusable theorem, at most two. Final name components must be unique within the module. A later solver proves them; unproved theorems are dropped. -Use INPUT.library summaries to avoid duplicate modules. No source search is needed: if an exact imported lemma name is uncertain, state a simpler Mathlib-only lemma or choose none. The host will check the statement after you submit. -Answer decision none (name, summary, sources, lean, target, application and remaining all null) when no module would help. summary says in one paragraph what the module provides; sources lists literature references (may be empty); reason explains the choice. -INPUT.feedback, when present, explains why the previous attempt (INPUT.previous) was rejected or what the solver could not prove. Fix exactly that, or choose a different module. -Write one complete JSON object to OUTPUT.json, with inputDigest copied from INPUT. Use Python json.dumps, write a temporary file in this directory, and rename it atomically to OUTPUT.json. Stop after submitting. -Do not change INPUT.json, ROLE.md or OUTPUT.schema.json. diff --git a/rust/cli/src/auto_library/replay.rs b/rust/cli/src/auto_library/replay.rs deleted file mode 100644 index 85d5cbd4..00000000 --- a/rust/cli/src/auto_library/replay.rs +++ /dev/null @@ -1,302 +0,0 @@ -//! Run preset proof rounds in Rust and verify the archived Auto Library build. -use super::*; -use std::sync::LazyLock; -static FIXTURE: LazyLock = LazyLock::new(|| { - serde_json::from_str(include_str!( - "../../../../resources/auto-library-replay.json" - )) - .unwrap() -}); -type Result = std::result::Result; -fn fail(what: &str) -> Result { - Err(format!("auto_library_replay_failed: {what}")) -} -fn load(file: &Path) -> Result { - serde_json::from_slice(&edit::read(file, 64 << 20).map_err(|e| e.to_string())?) - .map_err(|e| e.to_string()) -} - -pub(super) fn plan(data: &Value) -> Result { - let input = &data["input"]; - let module = input["module"].as_u64().ok_or("invalid replay module")?; - let round = input["round"].as_u64().ok_or("invalid replay round")?; - if module == 0 && round == 1 && data["turn"] == 1 { - return Ok(Value::Null); - } - let mut output = FIXTURE["plans"] - .get(format!("{module}/{round}")) - .cloned() - .ok_or("missing replay plan")?; - output["inputDigest"] = input["inputDigest"].clone(); - Ok(output) -} -pub(super) fn round(directory: &Path, data: &Value) -> Result { - build::canonical(directory).map_err(|e| e.to_string())?; - let root = data["root"].as_str().ok_or("missing replay package")?; - let args: Vec = - serde_json::from_value(data["args"].clone()).map_err(|e| e.to_string())?; - let options = theoremos_solver::options(&args, "cli")?; - let path = |name| { - options[name] - .as_str() - .map(Path::new) - .ok_or("missing replay path") - }; - let workspace = path("workspace")?; - let request = load(&directory.join("request.json"))?; - let Some(case) = workspace.parent() else { - return fail("invalid replay workspace"); - }; - let relative = case - .strip_prefix(directory.join("modules/0")) - .map_err(|_| "invalid replay round directory")?; - let pieces = relative - .iter() - .map(|piece| piece.to_str().ok_or("invalid replay round path")) - .collect::, _>>()?; - let [round_directory, case_name] = pieces.as_slice() else { - return fail("invalid replay round"); - }; - if request["challengeId"] != "replay/quadruple" - || request["challengeSource"] != FIXTURE["source"] - || request["prover"]["model"] != "preset-replay" - || options["build-manifest"] != request["buildManifestRef"] - || options["model"] != request["prover"]["model"] - || workspace.file_name().is_none_or(|name| name != "workspace") - || path("output")? != case.join("result.json") - || path("task-file")? != case.join("task.md") - || !matches!(*round_directory, "round-2" | "round-3" | "round-4") - || !(case_name.starts_with("prove-") - || case_name.starts_with("verify-") - || *case_name == "consumer-application") - { - return fail("invalid replay request"); - } - build::canonical(workspace).map_err(|e| e.to_string())?; - let candidate = if options["startup-only"] == true { - None - } else { - let source = std::fs::read_to_string(workspace.join("generated/problem/Submission.lean")) - .map_err(|e| e.to_string())?; - let key = format!("0/{}", round_directory.trim_start_matches("round-")); - if !matches!(*round_directory, "round-3" | "round-4") - || !case_name.starts_with("prove-") - || Some(source.trim()) != FIXTURE["plans"][key]["lean"].as_str().map(str::trim) - { - return fail("unexpected replay proof source"); - } - Some(if *round_directory == "round-4" { - FIXTURE["proofCandidate"] - .as_str() - .ok_or("missing replay candidate")? - .to_owned() - } else { - source - }) - }; - if build::native_root().map_err(|e| e.to_string())? != Path::new(root) { - build::set_package_root(Path::new(root))?; - } - crate::startup::replay_auto_library(&args, candidate.as_deref()).map(|code| json!(code)) -} - -struct Driver<'a> { - directory: &'a Path, - root: &'a Path, - manifest: String, -} -impl Driver<'_> { - fn solve_destination(&self) -> Result<()> { - let directory = self.directory.join("destination"); - let path = |name| directory.join(name).to_string_lossy().into_owned(); - let candidate = FIXTURE["solution"] - .as_str() - .ok_or("missing replay solution")?; - let code = crate::startup::replay_auto_library( - &[ - "--workspace".into(), - path("workspace"), - "--task-file".into(), - path("task.md"), - "--output".into(), - path("result.json"), - "--build-manifest".into(), - self.manifest.clone(), - "--workers=1".into(), - "--model=preset-replay".into(), - "--effort=none".into(), - "--no-explanations".into(), - ], - Some(candidate), - )?; - if code != 0 { - return fail(&format!("destination solver exited with {code}")); - } - Ok(()) - } - fn report(&self, observations: &Value) -> Result { - let build = self.directory.join("build"); - let state = load(&build.join("state.json"))?; - let lease = edit::Lease::acquire(&build, "run.lock").map_err(|e| e.to_string())?; - let summary = auto::build::terminal(&build, &|file| { - build::verify_solver_manifest(file, self.root).map_err(|e| e.to_string()) - })? - .ok_or("auto_library_replay_failed: build unfinished")?; - lease.held().map_err(|e| e.to_string())?; - if theoremos_lean::configuration::canonical_json(&summary) - != theoremos_lean::configuration::canonical_json(&observations["summary"]) - || summary["status"] != "built" - || summary["published"] != json!(["Quadruple"]) - { - return fail("terminal build changed"); - } - let modules = summary["modules"] - .as_array() - .ok_or("missing replay modules")?; - let outcomes: Vec<_> = modules - .iter() - .map(|m| { - m["rounds"] - .as_array() - .into_iter() - .flatten() - .filter_map(|r| r["outcome"].as_str()) - .collect::>() - .join(",") - }) - .collect(); - if outcomes != ["rejected,statement_failed,no_progress,published", "none"] { - return fail(&format!("outcomes {}", outcomes.join("|"))); - } - let application = &modules[0]["rounds"][3]["applicationCheck"]["check"]; - if application["status"] != "elaborated" - || application["selectedDeclarationUsed"] != true - || application["proofAcceptance"] != "not-assessed" - { - return fail("consumer application"); - } - let seen = observations["seen"] - .as_array() - .ok_or("missing replay planner inputs")?; - let opened = observations["opened"] - .as_array() - .ok_or("missing replay planner sessions")?; - let session = &state["sessions"][0]; - if seen.len() != 6 - || opened.len() != 5 - || session["threadId"] != opened[0] - || session["turns"] != 2 - || session["usageAccounting"]["startedTurns"] != 2 - || session["usageAccounting"]["reportedTurns"] != 2 - { - return fail("planner checkpoint accounting"); - } - let feedback = |n| { - seen.iter() - .find(|x| x["module"] == 0 && x["round"] == n) - .and_then(|x| x["feedback"].as_str()) - .unwrap_or("") - }; - if !feedback(2).contains("notation must be local or scoped") - || !feedback(3).contains("doubel") - || !feedback(4).starts_with("The solver run did not prove the module:") - || !feedback(4).contains("proved none of the stated theorems") - { - return fail("planner feedback"); - } - let last = seen - .iter() - .find(|x| x["module"] == 1) - .ok_or("missing replay planner round")?; - let theorem = "TheoremOS.Auto.Quadruple.quadruple_eq"; - if !last["library"] - .as_array() - .is_some_and(|a| a.contains(&json!("Submission.Library.Auto.Quadruple"))) - || !last["autoTheorems"] - .as_array() - .is_some_and(|a| a.contains(&json!(theorem))) - { - return fail("published module missing in next round"); - } - let records = auto::read_pool(&self.directory.join("pool"))?; - let [record] = records.as_slice() else { - return fail("published records"); - }; - let source = record["source"] - .as_str() - .ok_or("missing replay module source")?; - if record["theorems"] != json!([theorem, "TheoremOS.Auto.Quadruple.quadruple_add"]) - || record["requires"].as_array().is_none_or(|a| a.len() != 1) - || record["visible"] != json!([FIXTURE["base"]["modules"][0]["file"]]) - || record["trigger"]["challengeId"] != "replay/quadruple" - || record["cost"]["rounds"] != 4 - || source.contains("sorry") - || !source.contains("Planned use for the triggering challenge:") - { - return fail("published record"); - } - let included = auto::replay::destination(self.directory)?; - if included != json!(["Quadruple"]) { - return fail("destination pack"); - } - self.solve_destination()?; - let destination = load(&self.directory.join("destination/result.json"))?; - let usage = auto::replay::destination_usage(self.directory)?; - if destination["status"] != "evaluated_passed" - || usage["checked"] != true - || !usage["modules"].as_array().is_some_and(|m| { - m.len() == 1 && m[0]["direct"] == true && m[0]["mentioned"] == json!([theorem]) - }) - { - return fail("destination acceptance or usage"); - } - let public: serde_json::Map<_, _> = [ - "name", - "theorems", - "requires", - "visible", - "trigger", - "cost", - "sourceDigest", - ] - .iter() - .map(|k| (k.to_string(), record[k].clone())) - .collect(); - let feedback: Vec<_> = seen.iter().map(|v|json!({"module":v["module"],"round":v["round"],"feedback":v["feedback"].as_str().map(|s|s.chars().take(400).collect::())})).collect(); - Ok( - json!({"schema":"theorem-os.auto-library-cli.v1","phase":"replay","source":"preset-replay","modelInvoked":false, - "directory":self.directory,"build":summary,"outcomes":outcomes,"plannerFeedback":feedback,"record":public, - "destination":{"status":destination["status"],"included":included,"usage":usage}}), - ) - } -} -pub(super) fn run(root: &Path, directory: &Path) -> Result { - let mut input = FIXTURE.clone(); - input["root"] = json!(root); - let manifest = prepare_replay(directory, &input)? - .as_str() - .ok_or("math_build_manifest_invalid")? - .to_owned(); - let mut preset = super::workflow::Preset::default(); - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|e| e.to_string())?; - let summary = runtime.block_on(super::workflow::run( - root, - &directory.join("build"), - Some(&mut preset), - ))?; - let driver = Driver { - root, - directory, - manifest, - }; - if summary["status"] == "stopped" { - return fail(summary["error"].as_str().unwrap_or("build stopped")); - } - let report = - driver.report(&json!({"seen":preset.seen,"opened":preset.opened,"summary":summary}))?; - println!("{}", serde_json::to_string_pretty(&report).unwrap()); - Ok(0) -} diff --git a/rust/cli/src/auto_library/workflow.rs b/rust/cli/src/auto_library/workflow.rs deleted file mode 100644 index eaa73335..00000000 --- a/rust/cli/src/auto_library/workflow.rs +++ /dev/null @@ -1,647 +0,0 @@ -//! Durable workflow for planning, checking, proving, and publishing one dependency at a time. -mod proof; -use super::{build, edit, pool_operation, replay}; -use crate::role_host::{RoleInput, RoleSession, prompt_with_input}; -use serde_json::{Value, json}; -use sha2::{Digest, Sha256}; -use std::{ - collections::HashSet, - fs::{DirBuilder, OpenOptions}, - io::Write, - os::unix::fs::{DirBuilderExt, OpenOptionsExt}, - path::{Path, PathBuf}, - time::Duration, -}; -use theoremos_lean::configuration::canonical_json; -use theoremos_library::auto::{self, planner}; -use tokio::time::Instant; - -type Result = std::result::Result; -const INSTRUCTIONS: &str = include_str!("planner.md"); -const PROMPT: &str = "Choose one useful reusable dependency using the frozen INPUT.json. Write the complete decision to OUTPUT.json using OUTPUT.schema.json as directed by ROLE.md. State a tractable prerequisite with a concrete use, or submit decision none."; -const CONTINUE: &str = "Continue the same library-planning decision and write the complete OUTPUT.json now. Submit decision none if no useful dependency is clear."; - -fn string(v: &Value) -> &str { - v.as_str().unwrap_or_default() -} -fn array(v: &Value) -> &[Value] { - v.as_array().map(Vec::as_slice).unwrap_or_default() -} -fn number(v: &Value) -> u64 { - v.as_u64().unwrap_or_default() -} -fn now() -> u64 { - chrono::Utc::now().timestamp_millis().max(0) as u64 -} -fn hash(bytes: impl AsRef<[u8]>) -> String { - format!("{:x}", Sha256::digest(bytes)) -} -fn digest(value: &Value) -> String { - hash(canonical_json(value)) -} -fn mkdir(path: &Path) -> Result<()> { - build::canonical(path).map_err(|e| e.to_string())?; - DirBuilder::new() - .recursive(true) - .mode(0o700) - .create(path) - .map_err(|e| e.to_string()) -} -fn write_new(path: &Path, bytes: impl AsRef<[u8]>) -> Result<()> { - mkdir(path.parent().ok_or("math_path_invalid")?)?; - OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o400) - .open(path) - .and_then(|mut file| file.write_all(bytes.as_ref())) - .map_err(|e| e.to_string()) -} -fn load(path: &Path, limit: u64) -> Result> { - if !path.try_exists().map_err(|e| e.to_string())? { - return Ok(None); - } - let bytes = edit::read(path, limit).map_err(|e| e.to_string())?; - serde_json::from_slice(&bytes) - .map(Some) - .map_err(|e| e.to_string()) -} -fn clip(text: &str, limit: usize) -> String { - let mut units = 0; - text.chars() - .take_while(|c| { - units += c.len_utf16(); - units <= limit - }) - .collect() -} -fn feedback(heading: &str, problems: &[String]) -> String { - let lines = problems - .iter() - .map(|p| format!("\n- {p}")) - .collect::(); - clip(&format!("{heading}{lines}"), 16_000) -} -fn rejected(problems: &[String]) -> String { - feedback("The host rejected the module:", problems) -} -fn planner_usage(usage: &Value) -> Option { - usage["totalTokens"].as_u64().or_else(|| { - usage["inputTokens"] - .as_u64()? - .checked_add(usage["outputTokens"].as_u64()?) - }) -} - -#[derive(Default)] -pub(super) struct Preset { - pub(super) seen: Vec, - pub(super) opened: Vec, -} - -struct Workflow<'a> { - directory: &'a Path, - root: &'a Path, - lease: edit::Lease, - request: Value, - identity: String, - state: Value, - elapsed_before: u64, - started: Instant, - preset: Option<&'a mut Preset>, -} - -pub(super) async fn run( - root: &Path, - directory: &Path, - preset: Option<&mut Preset>, -) -> Result { - let lease = edit::Lease::acquire(directory, "run.lock").map_err(|e| e.to_string())?; - let verify = |file: &Path| build::verify_solver_manifest(file, root).map_err(|e| e.to_string()); - if let Some(summary) = auto::build::terminal(directory, &verify)? { - return Ok(summary); - } - let request = auto::build::request(directory, &verify)?; - let identity = digest(&request); - let mut state = auto::build::state(directory)?.unwrap_or_else(|| { - json!({ - "schema":"theorem-os.auto-library-state.v1", "requestDigest":identity, - "status":"running", "modules":[], "sessions":[], "elapsedMs":0 - }) - }); - if state["requestDigest"] != identity { - return Err("auto_library_resume_identity_changed".into()); - } - if preset.is_none() && !super::supports_runtime(&request) { - return Err("This automatic library configuration needs its historical packaged runtime. Native builds support Codex with one independent prover and a standard or Rust-only Mathlib build.".into()); - } - let elapsed_before = number(&state["elapsedMs"]).saturating_add( - state["activeSince"] - .as_u64() - .map_or(0, |since| now().saturating_sub(since)), - ); - state.as_object_mut().unwrap().remove("error"); - state["status"] = "running".into(); - for session in state["sessions"].as_array_mut().unwrap() { - let accounting = &mut session["usageAccounting"]; - if accounting["pending"] == true { - accounting["pending"] = false.into(); - accounting["incomplete"] = true.into(); - session["status"] = "interrupted".into(); - } - } - let mut job = Workflow { - directory, - root, - lease, - request, - identity, - state, - elapsed_before, - started: Instant::now(), - preset, - }; - job.save(true)?; - let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) - .map_err(|e| e.to_string())?; - let outcome = tokio::select! { - result = job.execute() => result, - result = tokio::signal::ctrl_c() => { - result.map_err(|e| e.to_string())?; - Err("auto_library_interrupted".into()) - } - _ = terminate.recv() => Err("auto_library_interrupted".into()), - }; - if let Err(reason) = outcome { - let status = if matches!( - reason.as_str(), - "auto_library_time_limit" - | "auto_library_token_limit" - | "auto_library_usage_unavailable" - ) { - if job.published() { - "built" - } else { - "exhausted" - } - } else { - "stopped" - }; - job.state["status"] = status.into(); - job.state["error"] = clip(&reason, 16_000).into(); - } - job.save(false)?; - Ok(auto::build::summary(directory, &job.state)) -} - -impl Workflow<'_> { - fn elapsed(&self) -> u64 { - self.elapsed_before - .saturating_add(self.started.elapsed().as_millis() as u64) - } - - fn save(&mut self, active: bool) -> Result<()> { - self.state["elapsedMs"] = self.elapsed().into(); - if active { - self.state["activeSince"] = now().into(); - } else { - self.state.as_object_mut().unwrap().remove("activeSince"); - } - crate::startup::write( - &self.directory.join("state.json"), - &self.state, - 0o600, - &self.lease, - ) - .map_err(|e| e.to_string()) - } - - fn published(&self) -> bool { - array(&self.state["modules"]) - .iter() - .any(|module| module.get("published").is_some()) - } - - fn operation(&self, operation: &str, mut input: Value) -> Result { - input["requestDigest"] = self.identity.clone().into(); - match operation { - "taken" | "reserve" | "publish" => pool_operation(operation, self.directory, &input), - _ => auto::build::operation(operation, self.directory, input), - } - } - - fn admission(&self) -> Result { - let summary = auto::build::summary(self.directory, &self.state); - let used = summary["plannerTokens"] - .as_f64() - .zip(summary["proverTokens"].as_f64()) - .map(|(plan, proof)| plan + proof); - self.operation("admit", json!({ - "elapsedMs":self.elapsed(), "used":used, - "maxRunSeconds":self.request["maxRunSeconds"], "maxTotalTokens":self.request["maxTotalTokens"], - "proverSeconds":self.request["prover"]["maxRunSeconds"], "proverTokens":self.request["prover"]["maxTotalTokens"] - })) - } - - fn limits(&self) -> Result<()> { - self.lease.held().map_err(|e| e.to_string())?; - match self.admission()?["reason"].as_str() { - Some(reason) => Err(reason.to_owned()), - None => Ok(()), - } - } - - fn pinned(&self, round: &Value) -> Value { - let mut input = json!({"pool":round["pool"]}); - if let Some(digests) = round.get("poolDigests") { - input["poolDigests"] = digests.clone(); - } - input - } - - fn pack(&self, round: &Value) -> Result { - Ok(self.operation("snapshot", self.pinned(round))?["pack"].clone()) - } - - fn round(&self, m: usize, r: usize) -> &Value { - &self.state["modules"][m]["rounds"][r] - } - - fn update(&mut self, m: usize, r: usize, apply: impl FnOnce(&mut Value)) -> Result<()> { - apply(&mut self.state["modules"][m]["rounds"][r]); - self.save(true) - } - - fn finish( - &mut self, - m: usize, - r: usize, - outcome: &str, - feedback: Option, - ) -> Result<()> { - self.update(m, r, |round| { - round["phase"] = "done".into(); - round["outcome"] = outcome.into(); - if let Some(text) = feedback { - round["feedback"] = text.into(); - } - }) - } - - fn round_directory(&self, m: usize, r: usize) -> PathBuf { - self.directory - .join("modules") - .join(m.to_string()) - .join(format!("round-{}", r + 1)) - } - - async fn execute(&mut self) -> Result<()> { - for module in array(&self.state["modules"]) { - for round in array(&module["rounds"]) { - self.pack(round)?; - } - } - loop { - let modules = array(&self.state["modules"]); - let m = modules.len().saturating_sub(1); - let module = modules.last().unwrap_or(&Value::Null); - let rounds = array(&module["rounds"]); - let r = rounds.len().saturating_sub(1); - let round = rounds.last().unwrap_or(&Value::Null); - let next = self.operation("next", json!({ - "modules":modules.len(), "maxModules":self.request["maxModules"], "status":module["status"], - "rounds":rounds.len(), "maxRounds":self.request["maxRounds"], - "phase":round["phase"], "outcome":round["outcome"], "published":self.published() - }))?; - match string(&next["action"]) { - "finish" => { - self.state["status"] = next["status"].clone(); - return Ok(()); - } - "module" => { - self.limits()?; - let new = json!({"index":modules.len(),"status":"open","openedAtMs":self.elapsed(),"rounds":[]}); - self.state["modules"].as_array_mut().unwrap().push(new); - self.save(true)?; - } - "close" => { - self.state["modules"][m]["status"] = next["status"].clone(); - self.save(true)?; - } - "round" => { - self.limits()?; - let mut snapshot = self.operation("snapshot", json!({}))?; - snapshot["round"] = (rounds.len() + 1).into(); - snapshot["phase"] = "plan".into(); - snapshot["taken"] = self.operation("taken", json!({}))?; - self.state["modules"][m]["rounds"] - .as_array_mut() - .unwrap() - .push(snapshot); - self.save(true)?; - } - "execute" => { - let pack = self.pack(round)?; - match string(&next["phase"]) { - "plan" => self.plan(m, r, &pack).await?, - "check" => self.check(m, r, &pack).await?, - "prove" => self.prove(m, r).await?, - "extract" => self.extract(m, r, &pack).await?, - "verify" => self.verify(m, r, &pack).await?, - "publish" => self.publish(m, r)?, - _ => return Err("auto_library_round_phase_invalid".into()), - } - } - _ => return Err("auto_library_transition_invalid".into()), - } - } - } - - async fn plan(&mut self, m: usize, r: usize, pack: &Value) -> Result<()> { - self.limits()?; - let round = self.round(m, r); - let previous = r - .checked_sub(1) - .map(|i| self.round(m, i)) - .unwrap_or(&Value::Null); - let mut data = json!({ - "challengeId":self.request["challengeId"], "challenge":self.request["challengeSource"], - "task":self.request["task"], "environment":self.request["environment"], "taken":round["taken"], - "module":m, "round":r+1, "maxRounds":self.request["maxRounds"], "feedback":previous["feedback"], - "modules":array(&pack["modules"]) - }); - if let Some(plan) = previous.get("plan") { - data["previous"] = Value::Object( - [ - "name", - "summary", - "lean", - "target", - "application", - "remaining", - ] - .into_iter() - .map(|key| (key.to_owned(), plan[key].clone())) - .collect(), - ); - } - for key in ["definitionTargets", "demand"] { - if let Some(value) = self.request.get(key) { - data[key] = value.clone(); - } - } - let input = planner::input(&data.to_string())?; - if input.is_null() { - return Err("auto_library_planner_input_invalid".into()); - } - let output = self.planner(m, r, &input, pack).await?; - let (plan, problems) = if let Some(output) = output { - planner::validate(&output, &input, &self.request["definitionTargets"]) - } else { - ( - None, - vec!["the planner wrote no readable OUTPUT.json".into()], - ) - }; - if let Some(plan) = plan { - self.update(m, r, |round| round["plan"] = plan)?; - } - if !problems.is_empty() { - return self.finish(m, r, "rejected", Some(rejected(&problems))); - } - let plan = &self.round(m, r)["plan"]; - if plan["decision"] == "none" { - return self.finish(m, r, "none", None); - } - let name = string(&plan["name"]).to_owned(); - if self.operation("reserve", json!({"name":name}))? != true { - return self.finish( - m, - r, - "rejected", - Some(rejected(&[format!( - "name {name} was taken by another build; choose another" - )])), - ); - } - self.update(m, r, |round| { - round["phase"] = "check".into(); - round["name"] = name.into(); - }) - } - - async fn planner( - &mut self, - m: usize, - r: usize, - input: &Value, - pack: &Value, - ) -> Result> { - let sessions = array(&self.state["sessions"]); - let same_round = |s: &&Value| s["module"] == m && s["round"] == r + 1; - let past = sessions.iter().filter(same_round); - if let Some(done) = past.clone().rev().find(|s| { - s["inputDigest"] == input["inputDigest"] - && s["outputDigest"].is_string() - && s["turnId"].is_string() - && matches!(s["status"].as_str(), Some("completed" | "submitted")) - }) { - let output = load( - &self - .directory - .join(string(&done["workspace"])) - .join("OUTPUT.json"), - 1 << 20, - )? - .ok_or("auto_library_checkpoint_changed")?; - if done["outputDigest"] != digest(&output) { - return Err("auto_library_checkpoint_changed".into()); - } - return Ok(Some(output)); - } - let attempt = past.count() + 1; - let base = self.round_directory(m, r); - mkdir(&base)?; - let dir = tempfile::Builder::new() - .prefix(&format!("plan-{attempt}-")) - .tempdir_in(base) - .map_err(|e| e.to_string())? - .keep(); - let input_text = canonical_json(input); - let schema: Value = serde_json::from_str(include_str!("plan.schema.json")).unwrap(); - write_new(&dir.join("INPUT.json"), &input_text)?; - write_new(&dir.join("ROLE.md"), INSTRUCTIONS)?; - write_new(&dir.join("OUTPUT.schema.json"), canonical_json(&schema))?; - mkdir(&dir.join("library"))?; - for item in array(&pack["modules"]) { - write_new( - &dir.join("library").join(string(&item["file"])), - string(&item["source"]), - )?; - } - let s = sessions.len(); - let relative = dir - .strip_prefix(self.directory) - .map_err(|e| e.to_string())?; - let entry = json!({ - "module":m, "round":r+1, "attempt":attempt, "status":"opening", - "inputDigest":input["inputDigest"], "workspace":relative, - "model":self.request["planner"]["model"], "effort":self.request["planner"]["effort"], - "turns":0, "usage":{}, "usageAccounting":{"startedTurns":0,"reportedTurns":0,"pending":false,"incomplete":false} - }); - self.state["sessions"].as_array_mut().unwrap().push(entry); - self.save(true)?; - let result = self.planner_turns(s, input, &input_text, &dir).await; - let record = &mut self.state["sessions"][s]; - if matches!(record["status"].as_str(), Some("opening" | "running")) { - record["status"] = "failed".into(); - } - record["usageAccounting"]["pending"] = false.into(); - record["usageAccounting"]["incomplete"] = (record["usageAccounting"]["startedTurns"] - != record["usageAccounting"]["reportedTurns"]) - .into(); - if let Ok(Some(output)) = &result { - record["outputDigest"] = digest(output).into(); - } - self.save(true)?; - result - } - - fn deadline(&self) -> Instant { - let local = number(&self.request["plannerTurnSeconds"]); - let total = number(&self.request["maxRunSeconds"]); - // Tokio needs a concrete deadline. Use a distant horizon for an unlimited build. - let unlimited = 100 * 365 * 24 * 3600; - let turn = Duration::from_secs(if local == 0 { - unlimited - } else { - local.min(unlimited) - }); - let remaining = if total == 0 { - turn - } else { - Duration::from_millis( - total - .saturating_mul(1000) - .saturating_sub(self.elapsed()) - .max(1), - ) - }; - Instant::now() + turn.min(remaining) - } - - async fn planner_turns( - &mut self, - s: usize, - input: &Value, - input_text: &str, - workspace: &Path, - ) -> Result> { - let role = self.request["planner"].clone(); - let environment = string(&self.request["environment"]); - let prompt = prompt_with_input(PROMPT, input_text); - let mut session = if let Some(preset) = self.preset.as_mut() { - let thread = format!("preset-planner-{}", preset.opened.len() + 1); - preset.opened.push(thread.clone()); - self.state["sessions"][s]["threadId"] = thread.into(); - None - } else { - Some( - RoleSession::open(RoleInput { - role: &role, - workspace, - environment, - instructions: INSTRUCTIONS, - prompt: &prompt, - output_schema: None, - deadline: self.deadline(), - }) - .await?, - ) - }; - let result = async { - let mut last = String::new(); - for turn in 0..3 { - self.limits()?; - let record = &mut self.state["sessions"][s]; - record["usageAccounting"]["startedTurns"] = (turn + 1).into(); - record["usageAccounting"]["pending"] = true.into(); - record["status"] = "running".into(); - self.save(true)?; - let (status, thread, turn_id, usage) = if let Some(preset) = self.preset.as_mut() { - let library = array(&input["library"]).iter().map(|v| v["module"].clone()).collect::>(); - let theorems = array(&input["library"]).iter().flat_map(|v| array(&v["theorems"]).iter().cloned()).collect::>(); - preset.seen.push(json!({"module":input["module"], "round":input["round"], - "feedback":input["feedback"], "library":library, "autoTheorems":theorems, "taken":input["takenNames"]})); - let output = replay::plan(&json!({"input":input, "turn":preset.seen.len()}))?; - let status = if output.is_null() { - "checkpoint" - } else { - write_new(&workspace.join("OUTPUT.json"), canonical_json(&output))?; - "completed" - }; - (status.to_owned(), preset.opened.last().unwrap().clone(), - format!("preset-plan-{}", preset.seen.len()), - Some(json!({"inputTokens":0,"outputTokens":0,"totalTokens":0}))) - } else { - let deadline = self.deadline(); - let reply = session.as_mut().unwrap().turn( - if turn == 0 { &prompt } else { CONTINUE }, None, deadline, - |method, notification| { - if method == "turn/acknowledged" { - if let Some(turn_id) = notification["turnId"].as_str() { - let record = &mut self.state["sessions"][s]; - record["turnId"] = turn_id.into(); - record["turns"] = (turn + 1).into(); - self.save(true)?; - } - } else if method == "thread/tokenUsage/updated" { - let usage = ¬ification["tokenUsage"]["total"]; - if planner_usage(usage).is_some() { - let record = &mut self.state["sessions"][s]; - record["usage"] = usage.clone(); - self.save(true)?; - } - } - Ok(()) - } - ).await?; - (reply.status, reply.thread_id, reply.turn_id, reply.usage) - }; - let record = &mut self.state["sessions"][s]; - record["threadId"] = thread.into(); - if !turn_id.is_empty() { - record["turnId"] = turn_id.into(); - record["turns"] = (turn + 1).into(); - } - record["status"] = status.clone().into(); - if let Some(usage) = usage.filter(|usage| planner_usage(usage).is_some()) { - // Codex reports totals for the thread. They already include its earlier turns. - record["usage"] = usage; - let reported = number(&record["usageAccounting"]["reportedTurns"]); - record["usageAccounting"]["reportedTurns"] = (reported + 1).into(); - } - record["usageAccounting"]["pending"] = false.into(); - self.save(true)?; - last = status; - if last != "checkpoint" { - break; - } - } - if !matches!(last.as_str(), "completed" | "submitted") { - return Err(format!("auto_library_planner_incomplete:{last}")); - } - if edit::read(&workspace.join("INPUT.json"), 8_000_000).map_err(|e| e.to_string())? != input_text.as_bytes() { - return Err("auto_library_planner_input_changed".into()); - } - Ok(load(&workspace.join("OUTPUT.json"), 1 << 20).unwrap_or(None)) - }.await; - if let Some(mut session) = session { - let stopped = session.stop(); - if result.is_ok() { - stopped?; - } - } - result - } -} diff --git a/rust/cli/src/auto_library/workflow/proof.rs b/rust/cli/src/auto_library/workflow/proof.rs deleted file mode 100644 index 03bd6924..00000000 --- a/rust/cli/src/auto_library/workflow/proof.rs +++ /dev/null @@ -1,832 +0,0 @@ -//! Prepare and verify ordinary Lean tasks and publish the declarations extracted from them. -use super::*; -use std::collections::{BTreeMap, VecDeque}; -use theoremos_lean::{ - configuration::canonical_library_json, - type_worker::{self, Query}, - worker::Cancellation, -}; -use theoremos_library::{auto::build as pack, host_release::auto_source}; - -fn modules(pack: &Value) -> HashSet { - array(&pack["modules"]) - .iter() - .map(|item| pack::import_name(string(&item["file"]))) - .collect() -} -fn closure(pack: &Value, source: &str) -> Value { - let modules = array(&pack["modules"]); - let imports = |source: &str| pack::imports(source).unwrap_or_default(); - let by_import: BTreeMap<_, _> = modules - .iter() - .map(|module| (pack::import_name(string(&module["file"])), module)) - .collect(); - let mut queue = VecDeque::from(imports(source)); - let mut reached = HashSet::new(); - while let Some(import) = queue.pop_front() { - if let Some(item) = by_import.get(&import) - && reached.insert(string(&item["file"])) - { - queue.extend(imports(string(&item["source"]))); - } - } - if reached.is_empty() { - Value::Null - } else { - json!({"schema":pack::PACK_SCHEMA,"modules":modules.iter().filter(|m| reached.contains(string(&m["file"]))).collect::>()}) - } -} -fn auto_file(name: &str) -> String { - format!("Submission/Library/Auto/{name}.lean") -} -fn prover_task(name: &str) -> String { - format!( - "Prove the theorems of the TheoremOS library module {name} (namespace TheoremOS.Auto.{name}). Replace each sorry with a proof.\nDo not change any statement or definition. You may add helper lemmas inside the module namespace.\nTheorems left unproved are dropped from the library together with the declarations that mention them." - ) -} -fn header(source: &str, name: &str, plan: &Value) -> String { - let import_end = theoremos_lean::header::header(source) - .ok() - .and_then(|header| header.imports.last().map(|span| span.end)); - let at = import_end - .map(|end| { - let offset = source - .char_indices() - .scan(0, |units, (byte, ch)| { - let boundary = *units; - *units += ch.len_utf16(); - Some((boundary, byte)) - }) - .find(|(units, _)| *units >= end) - .map_or(source.len(), |(_, byte)| byte); - source[offset..] - .find('\n') - .map_or(source.len(), |line| offset + line + 1) - }) - .unwrap_or(0); - let comment = |s: &str| -> String { - s.chars() - .map(|c| { - if matches!(c, '\u{0}'..='\u{8}' | '\u{b}'..='\u{1f}' | '\u{7f}') { - ' ' - } else { - c - } - }) - .collect::() - .replace("-/", "- /") - .replace("/-", "/ -") - }; - let (prefix, rest) = source.split_at(at); - let mut out = prefix.to_owned(); - if !prefix.is_empty() && !prefix.ends_with('\n') { - out.push('\n'); - } - if import_end.is_some() { - out.push('\n'); - } - out += &format!( - "/-! # TheoremOS auto-library module {name}\n\n{}\n\n", - comment(string(&plan["summary"]).trim()) - ); - if plan["target"].is_string() && plan["application"].is_string() && plan["remaining"].is_array() - { - out += &format!( - "Planned use for the triggering challenge:\n* {}: {}\n", - comment(string(&plan["target"])), - comment(string(&plan["application"])) - ); - for item in array(&plan["remaining"]) { - out += &format!("* Remaining: {}\n", comment(string(item))); - } - out.push('\n'); - } - if !array(&plan["sources"]).is_empty() { - out += "Sources:\n"; - for item in array(&plan["sources"]) { - out += &format!("* {}\n", comment(string(item).trim())); - } - out.push('\n'); - } - out += "Written by the TheoremOS library planner and proved by a TheoremOS solver run before solving the problem\nrecorded in the pool record. Only declarations Lean accepted with no gaps are kept. -/\n"; - out + rest -} -fn diagnostics(heading: &str, file: &Path) -> String { - let value = load(file, 64 << 20).ok().flatten().unwrap_or(Value::Null); - let body = if value["timedOut"] == true { - "Lean did not finish in time. Make the definitions and statements cheaper to elaborate." - .into() - } else { - let errors = array(&value["messages"]) - .iter() - .filter(|message| { - let text = string(&message["message"]); - message["severity"] == "error" - || text.contains("declaration uses 'sorry'") - || text.contains("declaration uses sorry") - }) - .take(12) - .map(|message| { - let line = message["line"] - .as_u64() - .map(|line| format!("line {line}:{}: ", number(&message["column"]))) - .unwrap_or_default(); - line + &clip(string(&message["message"]).trim(), 1200) - }) - .collect::>(); - if errors.is_empty() { - let raw = ["stderr", "stdout"] - .into_iter() - .map(|key| string(&value[key]).trim()) - .find(|s| !s.is_empty()) - .unwrap_or("Lean reported no message."); - clip(raw, 4000) - } else { - errors.join("\n") - } - }; - clip(&format!("{heading}\n{body}"), 16_000) -} -fn result_path(directory: &Path) -> PathBuf { - directory.join("result.json") -} -fn runtime_path(directory: &Path) -> PathBuf { - directory.join("result.json.runtime") -} -fn result(directory: &Path) -> Result { - Ok(load(&result_path(directory), 64 << 20)?.unwrap_or(Value::Null)) -} -fn case_path(directory: &Path, case: &Value, prefix: &str) -> Result { - let case = case - .as_str() - .filter(|name| name.starts_with(prefix) && !name.contains('/') && !name.contains('\\')) - .ok_or("auto_library_case_invalid")?; - Ok(directory.join(case)) -} -fn same_json(left: &Value, right: &Value) -> bool { - canonical_library_json(left) == canonical_library_json(right) -} - -impl Workflow<'_> { - async fn solve(&self, directory: &Path, mut flags: Vec) -> Result<()> { - self.lease.held().map_err(|e| e.to_string())?; - let prover = &self.request["prover"]; - let mut args = vec![ - "--workspace".into(), - directory.join("workspace").to_string_lossy().into_owned(), - "--task-file".into(), - directory.join("task.md").to_string_lossy().into_owned(), - "--output".into(), - result_path(directory).to_string_lossy().into_owned(), - "--build-manifest".into(), - string(&self.request["buildManifestRef"]).into(), - "--workers=1".into(), - format!("--model={}", string(&prover["model"])), - format!("--effort={}", string(&prover["effort"])), - format!("--max-turns={}", number(&prover["maxTurns"])), - format!("--max-turn-seconds={}", number(&prover["maxTurnSeconds"])), - format!( - "--prepare-timeout-seconds={}", - number(&prover["prepareTimeoutSeconds"]) - ), - "--no-explanations".into(), - ]; - let startup_only = flags.iter().any(|f| f == "--startup-only"); - if runtime_path(directory).join("state.json").is_file() { - flags.push("--resume".into()); - } - args.append(&mut flags); - if self.preset.is_some() { - let path = self.directory.to_owned(); - let data = json!({"args":args,"root":self.root}); - tokio::task::spawn_blocking(move || replay::round(&path, &data)) - .await - .map_err(|e| e.to_string())??; - } else { - if let Some(harness) = prover.get("agentHarness") - && harness["id"] != "codex" - { - return Err("The Rust automatic library prover needs a Codex profile. Resume this build with its pinned historical runtime.".into()); - } - let exe = std::env::current_exe().map_err(|e| e.to_string())?; - let profile = prover["agentHarness"]["profile"] - .as_str() - .unwrap_or_else(|| string(&self.request["planner"]["profile"])); - let mut command = tokio::process::Command::new(exe); - command - .env("CODEX_HOME", profile) - .current_dir(self.root) - .stdin(std::process::Stdio::null()) - .kill_on_drop(true); - if startup_only { - command.arg("run"); - } else { - command.arg("__independent-turn").arg(self.root); - } - args.push(format!("--codex={}", string(&prover["executable"]))); - // Keep stdout reserved for the command's structured summary. - // Solver events remain available through its durable state and log files. - command.stdout(std::process::Stdio::null()); - let outcome = command - .args(args) - .status() - .await - .map_err(|e| e.to_string())?; - if outcome.code() == Some(78) { - return Err( - "This prover configuration requires its pinned historical runtime.".into(), - ); - } - if !outcome.success() && !result_path(directory).is_file() { - return Err(format!("auto_library_solver_failed: {outcome}")); - } - } - self.lease.held().map_err(|e| e.to_string()) - } - - async fn bootstrap( - &self, - (m, r): (usize, usize), - case: &Path, - source: &str, - task: &str, - pack: Value, - consumer: bool, - ) -> Result { - let mut input = - json!({"source":source, "task":task, "environment":self.request["environment"]}); - if !pack.is_null() { - input["libraryPack"] = pack; - } - if consumer && let Some(targets) = self.request.get("definitionTargets") { - input["definitionTargets"] = targets.clone(); - } - let mut pinned = self.pinned(self.round(m, r)); - pinned.as_object_mut().unwrap().remove("pool"); - pinned["requestDigest"] = self.identity.clone().into(); - let directory = self.directory.to_owned(); - let workspace = case.join("workspace"); - tokio::task::spawn_blocking(move || { - auto::build::bootstrap(&directory, &workspace, &input, &pinned) - }) - .await - .map_err(|e| e.to_string())? - } - - pub(super) async fn check(&mut self, m: usize, r: usize, pack: &Value) -> Result<()> { - self.limits()?; - let round = self.round(m, r); - let name = string(&round["name"]).to_owned(); - let spec = string(&round["plan"]["lean"]).to_owned(); - let dir = self.round_directory(m, r); - let case = match round - .get("prove") - .map(|v| case_path(&dir, v, "prove-")) - .transpose()? - { - Some(case) if case.join("workspace/active-problem.json").is_file() => case, - _ => { - mkdir(&dir)?; - let case = tempfile::Builder::new() - .prefix("prove-") - .tempdir_in(&dir) - .map_err(|e| e.to_string())? - .keep(); - let name_of_case = case - .file_name() - .and_then(|name| name.to_str()) - .ok_or("math_path_invalid")?; - self.update(m, r, |round| round["prove"] = json!(name_of_case))?; - let task = prover_task(&name); - write_new(&case.join("task.md"), format!("{task}\n"))?; - if let Err(reason) = self - .bootstrap((m, r), &case, &spec, &task, closure(pack, &spec), false) - .await - { - return self.finish( - m, - r, - "rejected", - Some(rejected(&[format!( - "the statement could not be set up as a proof task: {reason}" - )])), - ); - } - case - } - }; - let mut report = result(&case)?; - if report["status"] != "prepared" && report["reason"] != "math_statement_check_failed" { - self.solve( - &case, - vec![ - "--startup-only".into(), - "--check-statement".into(), - "--max-run-seconds=0".into(), - ], - ) - .await?; - report = result(&case)?; - } - if report["reason"] == "math_statement_check_failed" { - return self.finish( - m, - r, - "statement_failed", - Some(diagnostics( - "Lean rejected the module statement (theorem bodies may stay sorry):", - &runtime_path(&case).join("statement-diagnostics.json"), - )), - ); - } - if report["status"] != "prepared" { - return Err(format!("auto_library_check_failed: {}", status(&report))); - } - self.update(m, r, |round| round["phase"] = "prove".into()) - } - - pub(super) async fn prove(&mut self, m: usize, r: usize) -> Result<()> { - let case = case_path( - &self.round_directory(m, r), - &self.round(m, r)["prove"], - "prove-", - )?; - let mut report = result(&case)?; - let budget = self.admission()?; - let seconds = budget["seconds"].as_f64(); - let tokens = budget["tokens"].as_f64(); - if !matches!( - report["status"].as_str(), - Some("evaluated_passed" | "evaluated_failed") - ) && seconds.is_none_or(|s| s >= 1.) - && tokens.is_none_or(|t| t > 0.) - { - self.solve( - &case, - vec![ - format!("--max-run-seconds={}", seconds.unwrap_or(0.) as u64), - format!("--max-total-tokens={}", tokens.unwrap_or(0.) as u64), - ], - ) - .await?; - report = result(&case)?; - } - self.update(m, r, |round| { - round["proof"] = json!({"status":report["status"].as_str().unwrap_or("unavailable"), - "tokens":report["tokenBudget"]["reportedTotalTokens"],"turns":report["turns"]}); - round["phase"] = "extract".into(); - }) - } - - pub(super) async fn extract(&mut self, m: usize, r: usize, pack: &Value) -> Result<()> { - let round = self.round(m, r); - let name = string(&round["name"]); - let spec = string(&round["plan"]["lean"]); - let case = case_path(&self.round_directory(m, r), &round["prove"], "prove-")?; - let extracted = case.join("extracted.json"); - if !extracted.try_exists().map_err(|e| e.to_string())? { - let report = result(&case)?; - let file = runtime_path(&case).join("state.json"); - let saved = load(&file, 64 << 20)?.unwrap_or(Value::Null); - let mut commits = Vec::new(); - for value in [ - &report["solution_commit"], - &saved["cooperation"]["canonicalCommit"], - ] { - if let Some(commit) = value.as_str() - && !commits.contains(&commit) - { - commits.push(commit); - } - } - let pack = closure(pack, spec); - let wanted = planner::theorems(spec); - let module_file = auto_file(name); - let mut failures = Vec::new(); - for commit in commits { - let mut selection = json!({"stateFile":file,"files":["Submission.lean"],"commit":commit, - "keepOriginals":true,"dropUnproved":true,"modulePaths":{"Submission.lean":module_file}}); - if !pack.is_null() { - selection["base"] = pack.clone(); - } - let extracted_pack = match tokio::task::spawn_blocking(move || { - theoremos_library::packing::build( - "extract", - selection, - &std::env::vars().collect(), - ) - }) - .await - .map_err(|e| e.to_string())? - { - Ok(pack) => pack, - Err(reason) => { - failures.push(reason); - continue; - } - }; - let item = array(&extracted_pack["modules"]) - .iter() - .find(|item| item["file"] == module_file) - .ok_or("auto_library_extracted_module_missing")?; - let source = string(&item["source"]); - let kept = planner::theorems(source) - .into_iter() - .filter(|lemma| wanted.contains(lemma)) - .collect::>(); - if kept.is_empty() { - failures.push("no stated theorem was proved".into()); - continue; - } - let source = header(source, name, &round["plan"]); - let problems = auto_source::inspect(name, &source, &modules(&pack), false); - if !problems.is_empty() { - failures.extend(problems); - continue; - } - if item["origin"]["kind"] != "run" { - return Err("auto_library_extract_origin_invalid".into()); - } - crate::startup::write( - &extracted, - &json!({"source":source,"kept":kept,"origin":item["origin"]}), - 0o400, - &self.lease, - ) - .map_err(|e| e.to_string())?; - break; - } - if !extracted.is_file() { - let mut reasons = vec![ - "It proved none of the stated theorems in a form the library can keep.".into(), - ]; - reasons.extend(failures.into_iter().take(6)); - reasons.push("State smaller lemmas, or a different module.".into()); - return self.finish( - m, - r, - "no_progress", - Some(feedback( - "The solver run did not prove the module:", - &reasons, - )), - ); - } - } - self.update(m, r, |round| round["phase"] = "verify".into()) - } - - fn extracted(&self, m: usize, r: usize) -> Result { - let case = case_path( - &self.round_directory(m, r), - &self.round(m, r)["prove"], - "prove-", - )?; - load(&case.join("extracted.json"), 4 << 20)? - .ok_or_else(|| "auto_library_extract_missing".into()) - } - - pub(super) async fn verify(&mut self, m: usize, r: usize, pack: &Value) -> Result<()> { - let round = self.round(m, r); - let name = string(&round["name"]).to_owned(); - let item = self.extracted(m, r)?; - let closed = closure(pack, string(&item["source"])); - if !auto_source::inspect(&name, string(&item["source"]), &modules(&closed), false) - .is_empty() - { - return Err("auto_library_extracted_source_invalid".into()); - } - let own = json!({"schema":pack::PACK_SCHEMA,"modules":[{"file":auto_file(&name),"source":item["source"],"origin":item["origin"]}]}); - let dir = self.round_directory(m, r); - let case = match round - .get("verify") - .map(|v| case_path(&dir, v, "verify-")) - .transpose()? - { - Some(case) if case.join("workspace/active-problem.json").is_file() => case, - _ => { - mkdir(&dir)?; - let case = tempfile::Builder::new() - .prefix("verify-") - .tempdir_in(&dir) - .map_err(|e| e.to_string())? - .keep(); - let name_of_case = case - .file_name() - .and_then(|name| name.to_str()) - .ok_or("math_path_invalid")?; - self.update(m, r, |round| round["verify"] = json!(name_of_case))?; - let task = format!("Check that the library module {name} installs."); - write_new(&case.join("task.md"), format!("{task}\n"))?; - let merged = auto::build::merge_pack(closed, own.clone()); - let installed = match merged { - Ok(pack) => { - self.bootstrap( - (m, r), - &case, - "theorem auto_library_installed : True := trivial\n", - &task, - pack, - false, - ) - .await - } - Err(reason) => Err(reason), - }; - if let Err(reason) = installed { - return self.finish( - m, - r, - "verify_failed", - Some(rejected(&[format!( - "the proved module could not be installed: {reason}" - )])), - ); - } - case - } - }; - let mut report = result(&case)?; - if report["status"] != "prepared" && report["reason"] != "math_library_pack_failed" { - self.solve( - &case, - vec!["--startup-only".into(), "--max-run-seconds=0".into()], - ) - .await?; - report = result(&case)?; - } - if report["reason"] == "math_library_pack_failed" { - return self.finish( - m, - r, - "verify_failed", - Some(diagnostics( - "Lean rejected the proved module as a frozen library file:", - &runtime_path(&case).join("library-pack-diagnostics.json"), - )), - ); - } - if report["status"] != "prepared" { - return Err(format!("auto_library_verify_failed: {}", status(&report))); - } - let round = self.round(m, r); - let application = round["plan"]["consumerApplication"].clone(); - if !application.is_null() && round.get("applicationCheck").is_none() { - let case = dir.join("consumer-application"); - let merged = auto::build::merge_pack(pack.clone(), own)?; - let checked = self - .application(m, r, &case, merged, application, &name) - .await; - self.update(m, r, |round| round["applicationCheck"] = checked)?; - } - self.update(m, r, |round| round["phase"] = "publish".into()) - } - - async fn application( - &self, - m: usize, - r: usize, - case: &Path, - pack: Value, - mut selected: Value, - name: &str, - ) -> Value { - let mut check = json!({"authority":"advisory-application-elaboration","proofAcceptance":"not-assessed", - "consumerCoverage":"not-assessed","commit":"","environmentDigest":""}); - let outcome: Result<()> = async { - let task = "Check the selected library application at its original consumer."; - let source = format!( - "import Submission.Library.Auto.{name}\n{}", - string(&self.request["challengeSource"]) - ); - let receipt_file = case.join("workspace/active-problem.json"); - let receipt = match load(&receipt_file, 64 << 20)? { - Some(receipt) => receipt, - None => { - self.bootstrap((m, r), case, &source, task, pack, true) - .await? - } - }; - if receipt["contract"]["formalStatement"] != source { - return Err("auto_library_application_source_changed".into()); - } - check["commit"] = receipt["baseCommit"].clone(); - check["environmentDigest"] = receipt["environmentDigest"].as_str().unwrap_or("").into(); - let mut identity = - json!({"source":source,"pack":receipt["libraryPack"],"selected":selected}); - if let Some(definitions) = self.request.get("definitionTargets") { - identity["definitionTargets"] = definitions.clone(); - } - let expected = digest(&identity); - let file = case.join("application.sha256"); - if file.try_exists().map_err(|e| e.to_string())? { - if edit::read(&file, 64).map_err(|e| e.to_string())? != expected.as_bytes() { - return Err("auto_library_application_identity_changed".into()); - } - } else { - write_new(&file, expected)?; - } - if !case.join("task.md").is_file() { - write_new(&case.join("task.md"), format!("{task}\n"))?; - } - if result(case)?["status"] != "prepared" { - self.solve( - case, - vec!["--startup-only".into(), "--max-run-seconds=0".into()], - ) - .await?; - } - if result(case)?["status"] != "prepared" { - return Err("auto_library_application_environment_unavailable".into()); - } - let report = &selected["application"]; - let (_cancel, cancel) = tokio::sync::watch::channel(false); - let env = std::env::vars() - .map(|(key, value)| (key, Value::String(value))) - .collect(); - let elaboration = type_worker::check( - Path::new(string(&receipt["projectRoot"])), - Query { - file: string(&report["context"]["file"]), - context: string(&report["context"]["declaration"]), - ty: string(&report["expectedType"]), - term: report["expression"].as_str(), - }, - env, - None, - Cancellation::new(cancel), - |_| {}, - ) - .await?; - let passed = elaboration["status"] == "elaborated"; - check["status"] = if passed { - "elaborated" - } else if elaboration["exitCode"] == 1 && elaboration["timedOut"] != true { - "failed" - } else { - "unavailable" - } - .into(); - check["reason"] = if passed { - "selected-expression-elaborated-against-requested-type" - } else { - "selected-expression-did-not-elaborate" - } - .into(); - for (field, value) in [ - ("sourceSnapshotDigest", &elaboration["sourceSnapshotDigest"]), - ("projectionDigest", &elaboration["projectionDigest"]), - ( - "diagnosticEnvironmentDigest", - &elaboration["environment"]["environmentDigest"], - ), - ("toolIdentity", &elaboration["environment"]["toolIdentity"]), - ("files", &elaboration["sourceFiles"]), - ("artifact", &elaboration["artifact"]), - ("elaboratedType", &elaboration["type"]), - ] { - if !value.is_null() { - check[field] = value.clone(); - } - } - if passed { - let theorem = string(&selected["declaration"]); - check["selectedDeclarationUsed"] = array(&elaboration["constants"]) - .iter() - .any(|item| item == theorem.strip_prefix("_root_.").unwrap_or(theorem)) - .into(); - } else { - let message = [ - &elaboration["firstBlocking"]["message"], - &elaboration["stderr"], - &elaboration["stdout"], - ] - .iter() - .filter_map(|v| v.as_str()) - .find(|s| !s.is_empty()) - .unwrap_or("No diagnostic"); - check["diagnostic"] = clip(message, 8000).into(); - } - Ok(()) - } - .await; - if let Err(reason) = outcome { - check["status"] = "unavailable".into(); - check["reason"] = clip(&reason, 1000).into(); - } - selected["check"] = check; - selected - } - - pub(super) fn publish(&mut self, m: usize, r: usize) -> Result<()> { - let round = self.round(m, r); - let name = string(&round["name"]).to_owned(); - let item = self.extracted(m, r)?; - let source = string(&item["source"]); - let file = auto_file(&name); - let dir = self.round_directory(m, r); - let current = closure(&self.pack(round)?, source); - let mut requires = array(¤t["modules"]) - .iter() - .map(|item| json!({"file":item["file"],"digest":hash(string(&item["source"]))})) - .collect::>(); - requires.sort_by(|a, b| { - string(&a["file"]) - .encode_utf16() - .cmp(string(&b["file"]).encode_utf16()) - }); - let mut visible = BTreeMap::new(); - for module in array(&self.state["modules"]).iter().take(m + 1) { - for earlier in array(&module["rounds"]) { - for item in array(&self.pack(earlier)?["modules"]) { - visible - .entry(string(&item["file"]).to_owned()) - .or_insert_with(|| hash(string(&item["source"]))); - } - } - } - let mut files = visible.keys().collect::>(); - files.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16())); - let visible_digest = files - .iter() - .map(|file| json!({"file":file,"digest":visible[file.as_str()]})) - .collect::>(); - let plan = &round["plan"]; - let record_file = dir.join("record.json"); - let binder = self.request.get("libraryBinding"); - let record = match load(&record_file, 4 << 20)? { - Some(record) => record, - None => { - let case = case_path(&dir, &round["prove"], "prove-")?; - let run = - load(&runtime_path(&case).join("state.json"), 64 << 20)?.unwrap_or(Value::Null); - let origin = &item["origin"]; - let summary = auto::build::summary( - self.directory, - &json!({ - "sessions":array(&self.state["sessions"]).iter().filter(|s| s["module"] == m).collect::>(), - "modules":[self.state["modules"][m]],"elapsedMs":self.elapsed() - }), - ); - let mut record = json!({ - "schema":"theorem-os.auto-library-record.v1","name":name,"file":file,"source":source,"sourceDigest":hash(source), - "summary":plan["summary"],"sources":plan["sources"],"theorems":planner::theorems(source), - "requires":requires,"visible":files, - "environment":{"id":self.request["environment"],"digest":self.request["environmentDigest"]}, - "trigger":{"challengeId":self.request["challengeId"],"challengeDigest":hash(string(&self.request["challengeSource"])),"taskDigest":hash(string(&self.request["task"]))}, - "cost":{"plannerTokens":summary["plannerTokens"],"proverTokens":summary["proverTokens"], - "wallMs":self.elapsed().saturating_sub(number(&self.state["modules"][m]["openedAtMs"])), - "rounds":array(&self.state["modules"][m]["rounds"]).len()}, - "planner":{"model":self.request["planner"]["model"],"effort":self.request["planner"]["effort"]}, - "prover":{"runId":run["runId"].as_str().unwrap_or_else(|| string(&origin["runId"])), - "commit":origin["commit"],"model":self.request["prover"]["model"], - "dropped":array(&origin["dropped"]).iter().filter(|item| item["reason"] != "original").collect::>()}, - "buildId":self.request["buildId"],"buildDigest":self.request["buildDigest"], - "publishedAt":chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) - }); - for key in ["receiptDigest", "environmentDigest"] { - if let Some(value) = origin.get(key) { - record["prover"][key] = value.clone(); - } - } - if let Some(binding) = binder { - record["provenance"] = json!({"binding":binding,"visible":visible_digest}); - } - record - } - }; - let verified = case_path(&dir, &round["verify"], "verify-")?; - let receipt = load(&verified.join("workspace/active-problem.json"), 64 << 20)? - .ok_or("auto_library_verify_receipt_missing")?; - if record["name"] != name - || record["source"] != source - || record["buildId"] != self.request["buildId"] - || !same_json(&record["requires"], &json!(requires)) - || !same_json(&record["visible"], &json!(files)) - || result(&verified)?["status"] != "prepared" - || receipt["libraryPack"]["files"][&file] != record["sourceDigest"] - || binder.is_some() - && !same_json(&record["provenance"]["visible"], &json!(visible_digest)) - { - return Err("auto_library_publication_changed".into()); - } - let record = auto::build::checked_record(self.directory, &canonical_json(&record))?; - if !record_file.is_file() { - crate::startup::write(&record_file, &record, 0o400, &self.lease) - .map_err(|e| e.to_string())?; - } - self.operation( - "publish", - json!({"module":m,"round":r+1,"recordDigest":digest(&record)}), - )?; - self.state["modules"][m]["published"] = name.into(); - self.finish(m, r, "published", None) - } -} - -fn status(report: &Value) -> &str { - report["reason"] - .as_str() - .or_else(|| report["status"].as_str()) - .unwrap_or("no result") -} diff --git a/rust/cli/src/batch.rs b/rust/cli/src/batch.rs deleted file mode 100644 index a3b134c9..00000000 --- a/rust/cli/src/batch.rs +++ /dev/null @@ -1,552 +0,0 @@ -//! Schedule prepared launches. Each solver gets a separate session and log. -use chrono::{SecondsFormat, Utc}; -use serde_json::{Value, json}; -use std::{ - collections::HashSet, - fs::{self, File, OpenOptions}, - io::{self, Read, Write}, - os::unix::{ - fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, - process::{CommandExt, ExitStatusExt}, - }, - path::{Component, Path, PathBuf}, - process::{Child, Command, ExitStatus, Stdio}, - sync::atomic::{AtomicI32, Ordering}, - time::{Duration, Instant}, -}; - -const HELP: &str = "Usage: theorem-os batch --launch FILE [--launch FILE ...] --output FILE [--concurrency 2] [--idle-timeout-seconds N] -Launch JSON: {\"args\":[\"executable\",\"--workspace\",\"...\",\"--output\",\"...\"],\"cwd\":\"...\",\"envFile\":\"...\",\"codexHome\":\"...\"} -cwd defaults to the launch file directory; envFile and codexHome are optional. Workspaces must already be prepared. ---idle-timeout-seconds N terminates an attempt whose log stops growing for N seconds (0 disables, the default). A stalled attempt is recorded and does not fail the batch."; -const FORCE_AFTER: Duration = Duration::from_secs(30); -const REPEATED: i32 = 0x100; -static INTERRUPT: AtomicI32 = AtomicI32::new(0); - -extern "C" fn interrupted(signal: i32) { - if INTERRUPT - .compare_exchange(0, signal, Ordering::SeqCst, Ordering::SeqCst) - .is_err() - { - INTERRUPT.fetch_or(REPEATED, Ordering::SeqCst); - } -} - -fn error(e: io::Error) -> String { - e.to_string() -} -fn resolve(base: &Path, input: &str) -> PathBuf { - // path.resolve normalizes ".." before resolving a symlink. - let joined = base.join(input); - let mut result = PathBuf::new(); - for component in joined.components() { - match component { - Component::ParentDir => { - result.pop(); - } - Component::CurDir => (), - other => result.push(other.as_os_str()), - } - } - result -} -fn now() -> String { - Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true) -} - -struct Launch { - file: PathBuf, - workspace: PathBuf, - output: PathBuf, - cwd: PathBuf, - args: Vec, - env_file: Option, - profile: Option, -} - -fn read_launch(path: &Path) -> Result { - const MAX: u64 = 65536; - let fd = OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(path) - .map_err(error)?; - let stat = fd.metadata().map_err(error)?; - if !stat.is_file() || stat.nlink() != 1 { - return Err("math_runtime_integrity".into()); - } - if stat.len() > MAX { - return Err("math_runtime_file_too_large".into()); - } - let mut data = Vec::new(); - (&fd).take(MAX + 1).read_to_end(&mut data).map_err(error)?; - if data.len() as u64 > MAX { - return Err("math_runtime_file_too_large".into()); - } - let identity = |s: &fs::Metadata| { - ( - s.ino(), - s.dev(), - s.mode(), - s.len(), - s.nlink(), - s.mtime(), - s.mtime_nsec(), - s.ctime(), - s.ctime_nsec(), - ) - }; - if identity(&stat) != identity(&fd.metadata().map_err(error)?) - || identity(&stat) != identity(&fs::symlink_metadata(path).map_err(error)?) - { - return Err("math_runtime_integrity".into()); - } - serde_json::from_slice(data.strip_prefix(&[239, 187, 191]).unwrap_or(&data)) - .map_err(|e| e.to_string()) -} - -fn load(file: &str) -> Result { - let file = fs::canonicalize(file).map_err(error)?; - let config = read_launch(&file)?; - let invalid = |field: &str| format!("Invalid {field}: {}", file.display()); - let args: Vec = - serde_json::from_value(config["args"].clone()).map_err(|_| invalid("launch args"))?; - if args.first().is_none_or(|s| s.trim().is_empty()) || args.iter().any(|s| s.contains('\0')) { - return Err(invalid("launch args")); - } - let base = file.parent().unwrap(); - let setting = |name: &str| -> Result, String> { - config - .get(name) - .map(|v| { - v.as_str() - .filter(|s| !s.trim().is_empty()) - .map(|s| resolve(base, s)) - .ok_or_else(|| invalid(name)) - }) - .transpose() - }; - let cwd = setting("cwd")? - .unwrap_or_else(|| base.to_path_buf()) - .canonicalize() - .map_err(error)?; - let argument = |name: &str| -> Result { - let mut values = args.iter().enumerate().filter_map(|(i, arg)| { - if arg == name { - Some(args.get(i + 1).map(String::as_str).unwrap_or("")) - } else { - arg.strip_prefix(name) - .and_then(|suffix| suffix.strip_prefix('=')) - } - }); - let found = values - .next() - .filter(|s| !s.trim().is_empty() && !s.starts_with("--")); - found - .filter(|_| values.next().is_none()) - .map(|s| resolve(&cwd, s)) - .ok_or_else(|| format!("Launch needs exactly one {name}: {}", file.display())) - }; - let workspace = argument("--workspace")?.canonicalize().map_err(error)?; - if !workspace.is_dir() { - return Err(invalid("workspace")); - } - let output = argument("--output")?; - let output = if output.exists() { - output.canonicalize().map_err(error)? - } else { - output - .parent() - .ok_or_else(|| invalid("output"))? - .canonicalize() - .map_err(error)? - .join(output.file_name().ok_or_else(|| invalid("output"))?) - }; - let env_file = setting("envFile")?; - if let Some(ref path) = env_file { - File::open(path).map_err(error)?; - } - let profile = setting("codexHome")? - .map(fs::canonicalize) - .transpose() - .map_err(error)?; - if profile.as_ref().is_some_and(|p| !p.is_dir()) { - return Err(invalid("codexHome")); - } - Ok(Launch { - file, - workspace, - output, - cwd, - args, - env_file, - profile, - }) -} - -struct Batch { - launches: Vec, - output: PathBuf, - logs: PathBuf, - concurrency: usize, - idle: Duration, -} -impl Batch { - fn parse(args: &[String]) -> Result { - let mut iter = args.iter(); - let mut launches = Vec::new(); - let mut seen = HashSet::new(); - let (mut output, mut concurrency, mut seconds) = (None, 2, 0); - let integer = |s: &str| -> Option { - let n = s.trim().parse::().ok()?; - (n.fract() == 0.0 && (0.0..=9_007_199_254_740_991.0).contains(&n)).then_some(n as u64) - }; - while let Some(arg) = iter.next() { - let (key, inline) = arg - .split_once('=') - .map_or((arg.as_str(), None), |(k, v)| (k, Some(v))); - if !matches!( - key, - "--launch" | "--concurrency" | "--idle-timeout-seconds" | "--output" - ) { - return Err(format!("Unknown argument: {key}")); - } - if key != "--launch" && !seen.insert(key) { - return Err(format!("Duplicate argument: {key}")); - } - let value = inline - .or_else(|| { - iter.next() - .map(String::as_str) - .filter(|s| !s.starts_with("--")) - }) - .ok_or_else(|| format!("Missing value for {key}"))?; - match key { - "--launch" => launches.push(value), - "--output" => output = Some(value), - "--concurrency" => { - concurrency = integer(value) - .filter(|n| *n > 0) - .ok_or("--concurrency must be a positive integer")? - as usize - } - _ => { - seconds = integer(value) - .ok_or("--idle-timeout-seconds must be a non-negative integer")? - } - } - } - if launches.is_empty() { - return Err("At least one --launch is required".into()); - } - let output = resolve( - &std::env::current_dir().map_err(error)?, - output - .filter(|s| !s.trim().is_empty()) - .ok_or("--output is required")?, - ); - let launches = launches - .into_iter() - .map(load) - .collect::, _>>()?; - for (i, job) in launches.iter().enumerate() { - for other in &launches[..i] { - if job.workspace.starts_with(&other.workspace) - || other.workspace.starts_with(&job.workspace) - || other.output == job.output - || job.output.starts_with(&other.workspace) - || other.output.starts_with(&job.workspace) - { - return Err(format!( - "Batch jobs must use separate workspaces and outputs: {}, {}", - job.file.display(), - other.file.display() - )); - } - } - if output.starts_with(&job.workspace) || output == job.output { - return Err( - "Batch --output must be separate from problem workspaces and outputs".into(), - ); - } - } - let mut logs = output.as_os_str().to_owned(); - logs.push(".logs"); - Ok(Self { - launches, - output, - logs: logs.into(), - concurrency, - idle: Duration::from_secs(seconds), - }) - } - fn save(&self, state: &Value) -> Result<(), String> { - let parent = self.output.parent().unwrap(); - let temporary = tempfile::NamedTempFile::new_in(parent).map_err(error)?; - // Retain failed evidence; rename is visible only once the new state is durable. - let (mut file, tmp) = temporary.keep().map_err(|e| error(e.error))?; - let mut sorted = state.clone(); - sorted.sort_all_objects(); - file.write_all(sorted.to_string().as_bytes()) - .and_then(|_| file.sync_all()) - .map_err(error)?; - fs::rename(tmp, &self.output).map_err(error)?; - File::open(parent).and_then(|f| f.sync_all()).map_err(error) - } -} - -struct Active { - child: Child, - index: usize, - log: PathBuf, - size: u64, - changed: Instant, - next_sample: Instant, - force: Option, - reaped: bool, -} -impl Active { - fn start(index: usize, launch: &Launch, log: PathBuf, interval: Duration) -> io::Result { - let fd = OpenOptions::new() - .create_new(true) - .write(true) - .mode(0o600) - .open(&log)?; - let mut cmd = Command::new(&launch.args[0]); - cmd.args(&launch.args[1..]) - .current_dir(&launch.cwd) - .stdin(Stdio::null()) - .stdout(fd.try_clone()?) - .stderr(fd); - if let Some(ref env) = launch.env_file { - cmd.env("DEEPSCIENTIST_MATH_ENV_FILE", env); - } - if let Some(ref profile) = launch.profile { - cmd.env("CODEX_HOME", profile); - } - unsafe { - cmd.pre_exec(|| { - if libc::setsid() == -1 { - Err(io::Error::last_os_error()) - } else { - Ok(()) - } - }); - } - Ok(Self { - child: cmd.spawn()?, - index, - log, - size: 0, - changed: Instant::now(), - next_sample: Instant::now() + interval, - force: None, - reaped: false, - }) - } - fn signal(&self, sig: i32, group: bool) { - // The child is a new session leader. Its PID cannot be recycled before we wait for it. - let pid = self.child.id() as i32; - if !self.reaped { - unsafe { - libc::kill(if group { -pid } else { pid }, sig); - } - } - } -} -impl Drop for Active { - fn drop(&mut self) { - if !self.reaped { - self.signal(libc::SIGKILL, true); - let _ = self.child.wait(); - } - } -} - -fn signal_name(signal: i32) -> String { - // Linux exposes the conventional signal abbreviation, the name used in saved Node runs. - unsafe extern "C" { - fn sigabbrev_np(sig: libc::c_int) -> *const libc::c_char; - } - let name = unsafe { sigabbrev_np(signal) }; - if name.is_null() { - return format!("SIG{signal}"); - } - format!( - "SIG{}", - unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy() - ) -} - -fn finish(job: &mut Value, status: Option, cancelled: bool) { - job["exitCode"] = json!(status.and_then(|s| s.code())); - job["signal"] = json!(status.and_then(|s| s.signal()).map(signal_name)); - job["finishedAt"] = json!(now()); - job["status"] = json!(if cancelled { - "cancelled" - } else if job["stalled"] == true { - "stalled" - } else if status.is_some_and(|s| s.success()) && job.get("error").is_none() { - "completed" - } else { - "failed" - }); -} - -fn execute(batch: &Batch) -> Result { - fs::DirBuilder::new() - .recursive(true) - .mode(0o700) - .create(batch.output.parent().unwrap()) - .map_err(error)?; - fs::DirBuilder::new() - .mode(0o700) - .create(&batch.logs) - .map_err(error)?; - let jobs:Vec<_>=batch.launches.iter().enumerate().map(|(i,launch)|{ - let mut job=json!({"launch":launch.file,"workspace":launch.workspace,"output":launch.output,"log":batch.logs.join(format!("{}.log",i+1)),"status":"pending"}); - if let Some(profile)=&launch.profile{job["codexHome"]=json!(profile)} - job - }).collect(); - let mut state = json!({"concurrency":batch.concurrency,"startedAt":now(),"jobs":jobs}); - let mut next = 0; - let mut active: Vec = Vec::new(); - let mut cancelled = false; - let interval = (batch.idle / 4).clamp(Duration::from_millis(250), Duration::from_secs(30)); - batch.save(&state)?; - while next < batch.launches.len() || !active.is_empty() { - let signal = INTERRUPT.load(Ordering::SeqCst); - if signal != 0 { - if !cancelled { - let sig = signal & !REPEATED; - state["interruptedBy"] = json!(signal_name(sig)); - for job in &mut active { - job.signal(sig, false); - job.force = Some(Instant::now() + FORCE_AFTER); - } - cancelled = true; - batch.save(&state)?; - } - if signal & REPEATED != 0 { - for job in &active { - job.signal(libc::SIGKILL, true); - } - } - } - while INTERRUPT.load(Ordering::SeqCst) == 0 - && next < batch.launches.len() - && active.len() < batch.concurrency - { - let i = next; - next += 1; - let launch = &batch.launches[i]; - let job = &mut state["jobs"][i]; - job["startedAt"] = json!(now()); - job["status"] = json!("running"); - let log = batch.logs.join(format!("{}.log", i + 1)); - let started = Active::start(i, launch, log.clone(), interval); - println!( - "{}", - json!({"event":"batch_started","launch":launch.file,"log":log}) - ); - match started { - Ok(child) => { - job["pid"] = json!(child.child.id()); - active.push(child); - } - Err(e) => { - job["error"] = json!(if e.kind() == io::ErrorKind::NotFound { - format!("spawn {} ENOENT", launch.args[0]) - } else { - e.to_string() - }); - finish(job, None, cancelled); - let mut event = job.clone(); - event["event"] = json!("batch_finished"); - println!("{event}"); - } - } - batch.save(&state)?; - } - let mut i = 0; - while i < active.len() { - let child = &mut active[i]; - let job = &mut state["jobs"][child.index]; - if let Some(status) = child.child.try_wait().map_err(error)? { - child.reaped = true; - finish(job, Some(status), cancelled); - let mut event = job.clone(); - event["event"] = json!("batch_finished"); - batch.save(&state)?; - println!("{event}"); - active.swap_remove(i); - continue; - } - let now = Instant::now(); - if child.force.is_some_and(|deadline| now >= deadline) { - child.signal(libc::SIGKILL, true); - } else if !batch.idle.is_zero() - && !cancelled - && child.force.is_none() - && now >= child.next_sample - { - child.next_sample = now + interval; - if let Ok(stat) = fs::metadata(&child.log) { - if stat.len() != child.size { - child.size = stat.len(); - child.changed = now; - } else if now - child.changed >= batch.idle { - job["stalled"] = json!(true); - job["error"] = json!("idle-timeout"); - child.signal(libc::SIGTERM, true); - child.force = Some(now + FORCE_AFTER); - batch.save(&state)?; - } - } - } - i += 1; - } - if cancelled && active.is_empty() { - break; - } - if !active.is_empty() - && (next == batch.launches.len() || active.len() == batch.concurrency || cancelled) - { - std::thread::sleep(Duration::from_millis(20)); - } - } - for job in &mut state["jobs"].as_array_mut().unwrap()[next..] { - job["status"] = json!("skipped"); - } - state["finishedAt"] = json!(now()); - batch.save(&state)?; - Ok(if cancelled { - if state["interruptedBy"] == "SIGINT" { - 130 - } else { - 143 - } - } else if state["jobs"] - .as_array() - .unwrap() - .iter() - .any(|j| j["status"] == "failed") - { - 1 - } else { - 0 - }) -} - -pub fn run(args: &[String]) -> Result { - if args.iter().any(|s| s == "--help") { - println!("{HELP}"); - return Ok(0); - } - let batch = Batch::parse(args)?; - unsafe { - libc::signal(libc::SIGINT, interrupted as *const () as usize); - libc::signal(libc::SIGTERM, interrupted as *const () as usize); - } - execute(&batch) -} diff --git a/rust/cli/src/bin/theorem-os-agent.rs b/rust/cli/src/bin/theorem-os-agent.rs deleted file mode 100644 index d15e94ed..00000000 --- a/rust/cli/src/bin/theorem-os-agent.rs +++ /dev/null @@ -1,39 +0,0 @@ -use std::{env, path::Path, process::ExitCode}; -use theorem_os::{WORKER_COMMANDS, worker_command}; - -fn run() -> Result { - let mut args = env::args(); - let executable = args.next().unwrap_or_default(); - let stem = Path::new(&executable) - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or(""); - let command = if WORKER_COMMANDS.contains(&stem) { - stem.to_owned() - } else { - args.next().unwrap_or_default() - }; - if command == "--list" { - println!("{}", WORKER_COMMANDS.join("\n")); - return Ok(0); - } - if let Some(result) = worker_command(&command, &args.collect::>()) { - return result; - } - let help = matches!(command.as_str(), "" | "help" | "-h" | "--help"); - if !help { - eprintln!("Unknown command: {command}"); - } - eprintln!("Commands: {}", WORKER_COMMANDS.join(", ")); - Ok(u8::from(!help)) -} - -fn main() -> ExitCode { - match run() { - Ok(code) => ExitCode::from(code), - Err(message) => { - eprintln!("{message}"); - ExitCode::FAILURE - } - } -} diff --git a/rust/cli/src/bin/web-funnel.rs b/rust/cli/src/bin/web-funnel.rs deleted file mode 100644 index aef0251d..00000000 --- a/rust/cli/src/bin/web-funnel.rs +++ /dev/null @@ -1,323 +0,0 @@ -//! Aggregate workbench account milestones without printing account identities. -use chrono::{DateTime, NaiveDate}; -use serde::Deserialize; -use serde_json::{Value, json}; -use std::{ - collections::HashSet, - env, fs, - io::ErrorKind, - path::Path, - process::{Command, ExitCode}, -}; - -const USAGE: &str = "Usage: web-funnel --data DIR [--applications N] [--github] [--json]"; -const STAGES: [(&str, &str); 5] = [ - ("applied", "申请内测"), - ("allowlisted", "加入白名单"), - ("logged_in", "首次登录"), - ("submitted", "首次提交运行"), - ("accepted", "首次通过验收"), -]; - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct Account { - email: Option, - username: Option, - created_at: Option, - first_login_at: Option, - first_run_at: Option, - first_accepted_at: Option, -} - -fn accounts(dir: &Path) -> Result, String> { - let entries = match fs::read_dir(dir) { - Ok(entries) => entries, - Err(e) if e.kind() == ErrorKind::NotFound => return Ok(vec![]), - Err(e) => return Err(format!("Cannot list workbench accounts: {e}")), - }; - let mut result = vec![]; - for e in entries { - let file = e.map_err(|e| e.to_string())?; - let name = file.file_name(); - let Some(stem) = name.to_str().and_then(|s| s.strip_suffix(".json")) else { - continue; - }; - if stem.len() != 64 - || !stem - .bytes() - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) - { - continue; - } - let bytes = match fs::read(file.path()) { - Ok(v) => v, - Err(e) if e.kind() == ErrorKind::NotFound => continue, - Err(e) => return Err(format!("Cannot read workbench account: {e}")), - }; - if let Some(account) = serde_json::from_slice::>(&bytes) - .map_err(|_| "Invalid workbench account record.")? - { - result.push(account); - } - } - Ok(result) -} - -fn timestamp(s: Option<&str>) -> Option { - let s = s?; - DateTime::parse_from_rfc3339(s) - .map(|t| t.timestamp_millis()) - .ok() - .or_else(|| { - NaiveDate::parse_from_str(s, "%Y-%m-%d") - .ok()? - .and_hms_opt(0, 0, 0) - .map(|t| t.and_utc().timestamp_millis()) - }) -} - -fn hours(a: Option<&str>, b: &str) -> f64 { - match (timestamp(a), timestamp(Some(b))) { - (Some(a), Some(b)) => (b - a) as f64 / 3_600_000.0, - _ => f64::NAN, - } -} - -fn tenth(n: f64) -> f64 { - let n = n * 10.0; - let lower = n.floor(); - (if n - lower >= 0.5 { lower + 1.0 } else { lower }) / 10.0 -} -fn median(mut xs: Vec) -> Option { - if xs.is_empty() { - return None; - } - xs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); - let mid = xs.len() / 2; - Some(tenth(if xs.len().is_multiple_of(2) { - (xs[mid - 1] + xs[mid]) / 2.0 - } else { - xs[mid] - })) -} -fn js_json(n: f64) -> Value { - if !n.is_finite() { - return Value::Null; - } - serde_json::from_str(ryu_js::Buffer::new().format_finite(n)).unwrap() -} -struct Funnel { - steps: Vec<(usize, f64, Option)>, - login_to_run: Option, - run_to_accepted: Option, -} -impl Funnel { - fn json(&self) -> Value { - let mut times = json!({}); - if let Some(t) = self.login_to_run { - times["loginToRun"] = js_json(t); - } - if let Some(t) = self.run_to_accepted { - times["runToAccepted"] = js_json(t); - } - let steps: Vec<_> = self - .steps - .iter() - .map(|&(i, n, p)| { - let mut step = json!({"step":STAGES[i].0, "count":js_json(n)}); - if let Some(p) = p { - step["ofPrevious"] = js_json(p); - } - step - }) - .collect(); - json!({"steps":steps, "medianHours":times}) - } - fn text(&self) -> String { - let number = |n| ryu_js::Buffer::new().format(n).to_owned(); - let mut lines: Vec<_> = self - .steps - .iter() - .map(|&(i, n, p)| { - let label = STAGES[i].1; - format!( - "{}{} {:>5}{}", - label, - " ".repeat(8 - label.encode_utf16().count()), - number(n), - p.map(|p| format!(" {}%", number(p))).unwrap_or_default() - ) - }) - .collect(); - if let Some(t) = self.login_to_run { - lines.push(format!("登录到首次提交(中位数) {} 小时", number(t))); - } - if let Some(t) = self.run_to_accepted { - lines.push(format!("首次提交到首次通过(中位数) {} 小时", number(t))); - } - lines.join("\n") - } -} - -fn funnel(accounts: Vec, mut admitted: HashSet, applied: Option) -> Funnel { - let mut logged = 0; - let mut submission = vec![]; - let mut acceptance = vec![]; - for a in accounts { - if let Some(id) = a.username.as_ref().or(a.email.as_ref()) { - admitted.insert(id.to_owned()); - } - let present = |s: &String| !s.is_empty(); - if a.username.as_ref().is_some_and(present) - && !a.first_login_at.as_ref().is_some_and(present) - { - continue; - } - logged += 1; - if let Some(first) = a.first_run_at.as_ref().filter(|s| !s.is_empty()) { - submission.push(hours( - a.first_login_at.as_deref().or(a.created_at.as_deref()), - first, - )); - if let Some(accepted) = a.first_accepted_at.as_ref().filter(|s| !s.is_empty()) { - acceptance.push(hours(Some(first), accepted)); - } - } - } - let counts = [ - applied, - Some(admitted.len() as f64), - Some(logged as f64), - Some(submission.len() as f64), - Some(acceptance.len() as f64), - ]; - let steps = counts - .iter() - .enumerate() - .filter_map(|(i, &n)| { - let n = n?; - let p = i - .checked_sub(1) - .and_then(|j| counts[j]) - .filter(|p| *p != 0.0) - .map(|p| { - let ratio = n / p * 1000.0; - ratio.round() / 10.0 - }); - Some((i, n, p)) - }) - .collect(); - Funnel { - steps, - login_to_run: median(submission), - run_to_accepted: median(acceptance), - } -} - -fn run(args: &[String]) -> Result<(), String> { - let has = |key| args.iter().any(|s| s == key); - let value = |key| { - args.iter() - .position(|s| s == key) - .and_then(|i| args.get(i + 1)) - .cloned() - }; - if has("--help") || has("-h") { - println!("{USAGE}"); - return Ok(()); - } - let root = value("--data") - .or_else(|| env::var("THEOREMOS_WEB_DATA_ROOT").ok()) - .filter(|s| !s.is_empty()) - .ok_or("Pass --data .")?; - let mut applied = value("--applications") - .map(|s| { - (if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) { - s.parse::().ok() - } else { - None - }) - .ok_or("--applications takes a whole number.") - }) - .transpose()?; - if has("--github") { - let output = Command::new("gh") - .args([ - "issue", - "list", - "--repo", - "HuggingMath/TheoremOS", - "--label", - "early-access", - "--state", - "all", - "--limit", - "1000", - "--json", - "number", - ]) - .output() - .map_err(|e| format!("gh issue list: {e}"))?; - if !output.status.success() { - return Err("gh issue list failed.".into()); - } - let issues: Vec = - serde_json::from_slice(&output.stdout).map_err(|_| "Invalid gh issue list.")?; - applied = Some(applied.unwrap_or(0.0) + issues.len() as f64); - } - let root = std::path::absolute(root).map_err(|e| e.to_string())?; - let dir = root.join("accounts"); - let default_file = root.join("allowlist.txt"); - if !dir.exists() && !default_file.exists() { - return Err(format!( - "No workbench accounts or allowlist under {}.", - root.display() - )); - } - let mut allowlist = HashSet::new(); - for source in ["THEOREMOS_WEB_ALLOWLIST", "THEOREMOS_WEB_ADMINS"] { - allowlist.extend( - env::var(source) - .unwrap_or_default() - .split(',') - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(str::to_lowercase), - ); - } - let allowlist_file = env::var_os("THEOREMOS_WEB_ALLOWLIST_FILE") - .map(std::path::PathBuf::from) - .unwrap_or(default_file); - if allowlist_file.exists() { - let lines = fs::read_to_string(allowlist_file) - .map_err(|e| format!("Cannot read allowlist: {e}"))?; - allowlist.extend( - lines - .lines() - .map(|l| l.split('#').next().unwrap().trim()) - .filter(|s| !s.is_empty()) - .map(str::to_lowercase), - ); - } - let report = funnel(accounts(&dir)?, allowlist, applied); - if has("--json") { - println!( - "{}", - serde_json::to_string_pretty(&report.json()).map_err(|e| e.to_string())? - ); - } else { - println!("{}", report.text()); - } - Ok(()) -} - -fn main() -> ExitCode { - match run(&env::args().skip(1).collect::>()) { - Ok(()) => ExitCode::SUCCESS, - Err(e) => { - eprintln!("{e}"); - ExitCode::FAILURE - } - } -} diff --git a/rust/cli/src/bootstrap.rs b/rust/cli/src/bootstrap.rs deleted file mode 100644 index d2eb14bf..00000000 --- a/rust/cli/src/bootstrap.rs +++ /dev/null @@ -1,54 +0,0 @@ -use crate::report_flags::{flags, required}; -use serde_json::json; -use std::path::Path; -use theoremos_library::{author::read_pack, io, lean_task}; - -const HELP: &str = "theorem-os bootstrap-lean-task --source FILE --task-file FILE --workspace DIR [--environment ID] [--library-pack FILE] [--definition-targets NAME,NAME] - -Freeze a Lean source file and its task description in a new Git workspace. -The default environment is standard Lean. An explicit library pack must be frozen. -Use --definition-targets with comma-separated qualified names to mark construction holes. -Print the preparation receipt as JSON."; - -pub fn run(args: &[String]) -> Result<(), String> { - let flags = flags( - args, - &[ - "source", - "task-file", - "workspace", - "environment", - "library-pack", - "definition-targets", - ], - )?; - if flags.contains_key("help") { - println!("{HELP}"); - return Ok(()); - } - - let workspace = Path::new(required(&flags, "workspace")?); - let source = io::resolve(Path::new(required(&flags, "source")?))?; - let task = io::resolve(Path::new(required(&flags, "task-file")?))?; - let mut input = json!({ - "source": io::text(&source, lean_task::SOURCE_LIMIT)?, - "task": io::text(&task, 32 * 1024)?, - }); - if flags.contains_key("environment") { - input["environment"] = json!(required(&flags, "environment")?); - } - if flags.contains_key("definition-targets") { - let names: Vec<_> = required(&flags, "definition-targets")? - .split(',') - .map(str::trim) - .collect(); - input["definitionTargets"] = json!(names); - } - if flags.contains_key("library-pack") { - let pack = read_pack(required(&flags, "library-pack")?)?; - input["libraryPack"] = serde_json::to_value(pack).map_err(|error| error.to_string())?; - } - let receipt = lean_task::bootstrap(workspace, &input, &std::env::vars().collect(), None)?; - println!("{receipt}"); - Ok(()) -} diff --git a/rust/cli/src/build.rs b/rust/cli/src/build.rs deleted file mode 100644 index 6b0bc210..00000000 --- a/rust/cli/src/build.rs +++ /dev/null @@ -1,576 +0,0 @@ -//! Build and publish the three headless runtime entries consumed by v1 solver manifests. -use chrono::{SecondsFormat, Utc}; -use serde_json::{Value, json}; -use sha2::{Digest, Sha256}; -use std::ffi::CString; -use std::fs::{self, DirBuilder, File, Metadata, OpenOptions, Permissions}; -use std::io::{self, Write}; -use std::os::unix::{ - ffi::OsStrExt, - fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}, -}; -use std::path::{Component, Path, PathBuf}; -use std::process::Command; - -type Result = std::result::Result>; -const INPUTS: &[&str] = &[ - "bun.lock", - "package.json", - "tsconfig.json", - "extraction.json", - "scripts/build.ts", - "bin/math.ts", - "scripts/mathematics/searchLean.ts", -]; -const TREES: &[&str] = &["src", "scripts", "bin", "resources", "skills"]; -const BUNDLES: &[(&str, &str)] = &[ - ("math-solver", "scripts/mathematics/runMathProof.ts"), - ("search-lean", "scripts/mathematics/searchLean.ts"), - ("check-lean", "scripts/mathematics/checkLean.ts"), -]; -const RESOURCES: &[&str] = &[ - "openai-cartier-support/environment.json", - "openai-character-support/environment.json", - "theorem-os-library/search-data.json", -]; -const DESKTOP: &[&str] = &["electron", "react", "react-dom", "@office-ai/platform"]; -const NATIVE_MANIFEST: &str = "theorem-os.native-build-manifest.v1"; - -pub(crate) fn resolve(input: &Path) -> Result { - let mut path = PathBuf::new(); - for part in std::env::current_dir()?.join(input).components() { - if part == Component::ParentDir { - path.pop(); - } else { - path.push(part); - } - } - Ok(path) -} - -// Check the nearest existing ancestor without allowing even a dangling symlink. -pub(crate) fn canonical(path: &Path) -> Result<()> { - for parent in path.ancestors() { - match parent.symlink_metadata() { - Ok(_) if fs::canonicalize(parent).ok().as_deref() != Some(parent) => { - return Err("math_path_invalid".into()); - } - Ok(_) => return Ok(()), - Err(e) if e.kind() == io::ErrorKind::NotFound => continue, - Err(e) => return Err(e.into()), - } - } - Err("math_path_invalid".into()) -} - -static PACKAGE_ROOT: std::sync::OnceLock = std::sync::OnceLock::new(); - -pub(crate) fn set_package_root(root: &Path) -> std::result::Result<(), String> { - let root = fs::canonicalize(root).map_err(|e| e.to_string())?; - PACKAGE_ROOT - .set(root) - .map_err(|_| "Package directory is already set".into()) -} - -pub(crate) fn root(explicit: Option<&str>) -> Result { - if let Some(dir) = explicit { - let path = resolve(Path::new(dir))?; - canonical(&path)?; - return Ok(path); - } - checkout()?.ok_or_else(|| "Cannot locate the TheoremOS checkout. Use --root DIRECTORY.".into()) -} - -pub(crate) fn is_checkout(root: &Path) -> bool { - root.join("extraction.json").is_file() && root.join("scripts/build.ts").is_file() -} - -fn checkout() -> Result> { - if let Some(root) = PACKAGE_ROOT.get() { - return Ok(Some(root.clone())); - } - for start in [std::env::current_dir()?, std::env::current_exe()?] { - if let Some(dir) = start.ancestors().find(|p| is_checkout(p)) { - return Ok(Some(dir.to_owned())); - } - } - Ok(None) -} - -pub(crate) fn native_root() -> Result { - if let Some(root) = checkout()? { - return Ok(root); - } - let executable = fs::canonicalize("/proc/self/exe")?; - Ok(executable - .parent() - .ok_or("Invalid executable path")? - .to_owned()) -} - -fn identity(s: &Metadata) -> (u64, u64, u32, u64, i64, i64, i64, i64) { - ( - s.dev(), - s.ino(), - s.mode(), - s.len(), - s.mtime(), - s.mtime_nsec(), - s.ctime(), - s.ctime_nsec(), - ) -} - -pub(crate) fn build_file(file: &Path, name: &Path) -> Result { - canonical(file)?; - let mut fd = OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(file)?; - let stat = fd.metadata()?; - if !stat.is_file() || stat.nlink() != 1 { - return Err("math_build_file_invalid".into()); - } - let mut hasher = Sha256::new(); - let bytes = io::copy(&mut fd, &mut hasher)?; - if identity(&fd.metadata()?) != identity(&stat) - || identity(&file.symlink_metadata()?) != identity(&stat) - { - return Err("math_build_file_changed".into()); - } - Ok(json!({"path":name, "bytes":bytes, "sha256":format!("{:x}",hasher.finalize())})) -} - -/// Recompute the identities the host freezes in a v1 build manifest. -pub(crate) fn verify_manifest(path: &Path, root: &Path) -> Result> { - canonical(path)?; - if path.metadata()?.mode() & 0o222 != 0 { - return Err("math_build_manifest_not_frozen".into()); - } - let bytes = crate::edit::read(path, u64::MAX)?; - let m: Value = serde_json::from_slice(&bytes)?; - let bundle_root = root.join("out/main"); - let keys = [ - "schema", - "buildId", - "startedAt", - "finishedAt", - "source", - "bundleRoot", - "bundles", - ]; - let valid = m - .as_object() - .is_some_and(|o| o.len() == keys.len() && keys.iter().all(|k| o.contains_key(*k))) - && m["schema"] == "deepscientist.math.build-manifest.v1" - && m["buildId"].as_str().is_some_and(|id| { - regex::Regex::new(r"(?i)^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$") - .unwrap() - .is_match(id) - }) - && ["startedAt", "finishedAt"].iter().all(|k| { - m[k].as_str().is_some_and(|s| { - s.ends_with('Z') && chrono::DateTime::parse_from_rfc3339(s).is_ok() - }) - }) - && m["bundles"] - .as_array() - .is_some_and(|b| b.len() == BUNDLES.len()); - if !valid { - return Err("math_build_manifest_invalid".into()); - } - if m["source"]["root"] != json!(root) || m["bundleRoot"] != json!(bundle_root) { - return Err("math_build_manifest_identity".into()); - } - if source(root)? != m["source"] { - return Err("math_build_source_changed".into()); - } - for (name, _) in BUNDLES { - let file = bundle_root.join(format!("{name}.js")); - let expected = m["bundles"] - .as_array() - .unwrap() - .iter() - .find(|b| b["path"] == json!(file)) - .ok_or("math_build_manifest_identity")?; - if &build_file(&file, &file)? != expected { - return Err("math_build_artifact_changed".into()); - } - } - Ok(bytes) -} - -fn native_runtime() -> Result { - // Use the running image, even if the package has since replaced its executable. - let mut image = File::open("/proc/self/exe")?; - let before = image.metadata()?; - let mut hasher = Sha256::new(); - let bytes = io::copy(&mut image, &mut hasher)?; - if identity(&before) != identity(&image.metadata()?) || bytes != before.len() { - return Err("math_build_file_changed".into()); - } - Ok(json!({"bytes":bytes,"sha256":format!("{:x}",hasher.finalize())})) -} - -pub(crate) fn is_native_manifest(path: &Path) -> bool { - crate::edit::read(path, 4096) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - .is_some_and(|doc| doc["schema"] == NATIVE_MANIFEST) -} - -pub(crate) fn verify_solver_manifest(path: &Path, root: &Path) -> Result> { - if !is_native_manifest(path) { - return verify_manifest(path, root); - } - canonical(path)?; - if path.metadata()?.mode() & 0o222 != 0 { - return Err("math_build_manifest_not_frozen".into()); - } - let bytes = crate::edit::read(path, 4096)?; - let doc: Value = serde_json::from_slice(&bytes)?; - if doc["sourceRoot"] != json!(root) { - return Err("math_build_manifest_identity".into()); - } - let id = doc["buildId"] - .as_str() - .ok_or("math_build_manifest_invalid")?; - if !regex::Regex::new(r"^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$")?.is_match(id) - || doc.as_object().is_none_or(|fields| fields.len() != 4) - || doc["schema"] != NATIVE_MANIFEST - { - return Err("math_build_manifest_invalid".into()); - } - if doc["runtime"] != native_runtime()? { - return Err("math_build_artifact_changed".into()); - } - Ok(bytes) -} - -fn collect(dir: &Path, paths: &mut Vec) -> Result<()> { - canonical(dir)?; - for entry in dir.read_dir()? { - let entry = entry?; - let kind = entry.file_type()?; - if kind.is_symlink() { - return Err("math_build_source_symlink".into()); - } - if kind.is_dir() { - collect(&entry.path(), paths)?; - } else if kind.is_file() { - paths.push(entry.path()); - } else { - return Err("math_build_source_invalid".into()); - } - } - Ok(()) -} - -fn source(root: &Path) -> Result { - let mut paths: Vec<_> = INPUTS.iter().map(|p| root.join(p)).collect(); - for tree in TREES { - let dir = root.join(tree); - if dir.try_exists()? { - collect(&dir, &mut paths)?; - } - } - // JS's default sort orders UTF-16 code units, including supplementary characters. - paths.sort_by(|a, b| { - a.to_string_lossy() - .encode_utf16() - .cmp(b.to_string_lossy().encode_utf16()) - }); - paths.dedup(); - let inputs: Vec<_> = paths - .iter() - .map(|p| build_file(p, p)) - .collect::>()?; - let provenance: Value = serde_json::from_slice(&fs::read(root.join("extraction.json"))?)?; - let commit = provenance["sourceCommit"] - .as_str() - .ok_or("math_build_source_invalid")?; - if provenance["schema"] != "deepscientist.math.extraction.v1" - || !(40..=64).contains(&commit.len()) - || !commit - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) - { - return Err("math_build_source_invalid".into()); - } - Ok(json!({"root":root,"commit":commit,"submodules":[],"inputs":inputs})) -} - -fn compile(root: &Path, output: &Path, native: Option<&str>) -> Result<()> { - let arch = match std::env::consts::ARCH { - "x86_64" => "x64", - "aarch64" => "arm64", - "x86" => "ia32", - other => other, - }; - let platform = std::env::consts::OS; - let compiler = root.join(format!( - "node_modules/@esbuild/{platform}-{arch}/bin/esbuild" - )); - let meta = output.join("metafile.json"); - let mut command = Command::new(&compiler); - command.current_dir(root).args([ - "--bundle", - "--platform=node", - "--format=cjs", - "--loader:.py=text", - "--loader:.lean=text", - "--tsconfig=tsconfig.json", - "--log-level=warning", - ]); - command - .arg(format!("--outdir={}", output.display())) - .arg(format!("--metafile={}", meta.display())); - for (name, entry) in BUNDLES { - command.arg(format!("{name}={entry}")); - } - let mut resource_digests = serde_json::Map::new(); - for name in RESOURCES { - let relative = Path::new("resources").join(name); - let bytes = fs::read(root.join(&relative))?; - let target = output.join(relative); - fs::create_dir_all(target.parent().unwrap())?; - write_frozen(&target, &bytes, 0o444)?; - resource_digests.insert( - (*name).into(), - format!("{:x}", Sha256::digest(&bytes)).into(), - ); - } - command.arg(format!( - "--define:__THEOREMOS_RESOURCE_DIGESTS__={}", - Value::Object(resource_digests) - )); - if let Some(hash) = native { - command.arg(format!( - "--define:__THEOREMOS_NATIVE_PROCESS_SHA256__=\"{hash}\"" - )); - } - // Reject these import edges in the input graph, including unused modules - // and package subpaths. Never ship the external references as runtime stubs. - for package in DESKTOP { - command.arg(format!("--external:{package}")); - } - let status = command - .status() - .map_err(|e| format!("{}: {e}", compiler.display()))?; - if !status.success() { - return Err(format!("esbuild failed ({status})").into()); - } - let graph: Value = serde_json::from_slice(&fs::read(&meta)?)?; - for input in graph["inputs"] - .as_object() - .ok_or("Invalid esbuild metafile")? - .values() - { - for import in input["imports"] - .as_array() - .ok_or("Invalid esbuild imports")? - { - let path = import["path"] - .as_str() - .ok_or("Invalid esbuild import path")?; - if DESKTOP.iter().any(|p| { - path == *p - || path - .strip_prefix(p) - .is_some_and(|rest| rest.starts_with('/')) - }) { - return Err(format!("Desktop dependency is forbidden: {path}").into()); - } - } - } - fs::remove_file(meta)?; - Ok(()) -} - -fn write_frozen(file: &Path, bytes: &[u8], mode: u32) -> Result<()> { - let mut fd = OpenOptions::new() - .write(true) - .create_new(true) - .mode(mode) - .open(file)?; - fd.write_all(bytes)?; - fd.set_permissions(Permissions::from_mode(mode))?; - fd.sync_all()?; - Ok(()) -} - -fn publish_bundle(staging: &Path, out: &Path) -> Result<()> { - // On a rebuild, exchange the whole directory. Readers see either old or new - // binaries, and the temporary directory guard removes the displaced generation. - if let Err(e) = fs::rename(staging, out) { - if !matches!(e.raw_os_error(), Some(libc::ENOTEMPTY | libc::EEXIST)) { - return Err(e.into()); - } - let old = CString::new(staging.as_os_str().as_bytes())?; - let new = CString::new(out.as_os_str().as_bytes())?; - // SAFETY: both paths are NUL-terminated live buffers for this call. - if unsafe { - libc::renameat2( - libc::AT_FDCWD, - old.as_ptr(), - libc::AT_FDCWD, - new.as_ptr(), - libc::RENAME_EXCHANGE, - ) - } != 0 - { - return Err(io::Error::last_os_error().into()); - } - } - Ok(()) -} - -fn timestamp() -> String { - Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true) -} - -pub(crate) fn build(args: &[String]) -> Result { - let option = |name: &str| -> Result> { - args.iter() - .position(|a| a == name) - .map(|i| { - args.get(i + 1) - .filter(|v| !v.is_empty() && !v.starts_with("--")) - .map(String::as_str) - .ok_or_else(|| format!("Missing value for {name}").into()) - }) - .transpose() - }; - let native = args.iter().any(|arg| arg == "--native-only"); - let root = match option("--root")? { - None if native => native_root()?, - dir => root(dir)?, - }; - let installed = native && !is_checkout(&root); - let state = match option("--state-root")? { - Some(dir) => resolve(Path::new(dir))?, - None if installed => std::env::var_os("XDG_STATE_HOME") - .map(PathBuf::from) - .filter(|path| path.is_absolute()) - .or_else(|| std::env::home_dir().map(|home| home.join(".local/state"))) - .ok_or("Set --state-root or XDG_STATE_HOME to save native build manifests.")? - .join("theorem-os"), - None => root - .parent() - .ok_or("Invalid source root")? - .join(".deepscientist-math-standalone-state"), - }; - if !installed && state.starts_with(&root) { - return Err("math_build_state_root_must_be_external".into()); - } - canonical(&state)?; - let native_path = option("--native-process")?.map(Path::new); - if native { - if native_path.is_some() { - return Err("--native-only cannot be combined with --native-process".into()); - } - return build_native(&root, &state); - } - if native_path.is_some_and(|path| !path.is_absolute() || !cfg!(target_os = "linux")) { - return Err("math_native_process_requires_absolute_linux_path".into()); - } - let native = native_path.map(fs::read).transpose()?; - let hash = native.as_ref().map(|b| format!("{:x}", Sha256::digest(b))); - let started = timestamp(); - let before = source(&root)?; - let out = root.join("out"); - canonical(&out)?; - fs::create_dir_all(&out)?; - let staging = tempfile::Builder::new() - .prefix(".build-") - .tempdir_in(&out)?; - compile(&root, staging.path(), hash.as_deref())?; - if let (Some(bytes), Some(hash)) = (&native, &hash) { - write_frozen(&staging.path().join("theoremos-process.node"), bytes, 0o444)?; - write_frozen( - &staging.path().join("theoremos-process.sha256"), - format!("{hash}\n").as_bytes(), - 0o444, - )?; - } - if source(&root)? != before { - return Err("math_runtime_build_inputs_changed".into()); - } - let bundle_root = out.join("main"); - let mut bundles = Vec::new(); - for (stem, _) in BUNDLES { - let name = format!("{stem}.js"); - let file = staging.path().join(&name); - File::open(&file)?.sync_all()?; - bundles.push(build_file(&file, &bundle_root.join(name))?); - } - // The worker image is built as root and read by the unprivileged solver. - fs::set_permissions(staging.path(), Permissions::from_mode(0o755))?; - File::open(staging.path())?.sync_all()?; - let (directory, id, staged_manifest) = stage_manifest(&state)?; - let manifest = directory.join("manifest.json"); - let mut doc = json!({"schema":"deepscientist.math.build-manifest.v1","buildId":id,"startedAt":started,"finishedAt":timestamp(), - "source":before,"bundleRoot":bundle_root,"bundles":bundles}); - write_manifest(&staged_manifest, &mut doc)?; - publish_bundle(staging.path(), &bundle_root)?; - File::open(&out)?.sync_all()?; - publish_manifest(&staged_manifest, &directory)?; - Ok( - json!({"buildId":id,"buildManifestRef":manifest,"bundleRoot":bundle_root,"bundleCount":bundles.len()}), - ) -} - -fn stage_manifest(state: &Path) -> Result<(PathBuf, String, tempfile::TempDir)> { - let builds = state.join("builds"); - canonical(&builds)?; - DirBuilder::new() - .recursive(true) - .mode(0o700) - .create(&builds)?; - let id = fs::read_to_string("/proc/sys/kernel/random/uuid")? - .trim() - .to_string(); - let directory = builds.join(&id); - let staged_manifest = tempfile::Builder::new() - .prefix(".build-") - .tempdir_in(&builds)?; - Ok((directory, id, staged_manifest)) -} - -fn write_manifest(staged: &tempfile::TempDir, doc: &mut Value) -> Result<()> { - doc.sort_all_objects(); - write_frozen( - &staged.path().join("manifest.json"), - &serde_json::to_vec(doc)?, - 0o400, - )?; - File::open(staged.path())?.sync_all()?; - Ok(()) -} - -fn publish_manifest(staged: &tempfile::TempDir, directory: &Path) -> Result<()> { - fs::rename(staged.path(), directory)?; - File::open(directory.parent().ok_or("math_path_invalid")?)?.sync_all()?; - Ok(()) -} - -fn build_native(root: &Path, state: &Path) -> Result { - let runtime = native_runtime()?; - let (directory, id, staged) = stage_manifest(state)?; - let mut doc = - json!({"schema":NATIVE_MANIFEST,"buildId":id,"sourceRoot":root,"runtime":runtime}); - write_manifest(&staged, &mut doc)?; - publish_manifest(&staged, &directory)?; - Ok(json!({"buildId":id,"buildManifestRef":directory.join("manifest.json"),"bundleCount":0})) -} - -pub fn run(args: &[String]) -> std::result::Result<(), String> { - if args.iter().any(|arg| arg == "--help" || arg == "-h") { - println!( - "Usage: theorem-os build [--root DIRECTORY] [--state-root DIRECTORY] [--native-only | --native-process ABSOLUTE_LIBRARY]\nBuilds the isolated mathematics solver and freezes its source and artifact identities. --native-only pins the running Rust binary for standalone workflows." - ); - return Ok(()); - } - println!("{}", build(args).map_err(|e| e.to_string())?); - Ok(()) -} diff --git a/rust/cli/src/check_lean.rs b/rust/cli/src/check_lean.rs deleted file mode 100644 index 3650e9a2..00000000 --- a/rust/cli/src/check_lean.rs +++ /dev/null @@ -1,422 +0,0 @@ -//! Standalone environment check shared by the host CLI and the mixed agent bundle. -use crate::library::io; -use serde_json::{Value, json}; -use std::{ - env, fs, - path::{Component, Path, PathBuf}, - time::Duration, -}; -use theoremos_lean::{environment::Env, health}; -use tokio::signal::unix::{SignalKind, signal}; - -pub const HELP: &str = "Usage: theorem-os check-lean (--workspace DIR | --worktree ROOT) --file FILE [--file FILE --timeout-seconds N] ---worktree is the worker root containing .scratch/worker-project.json. --workspace is the Lean project directory. -File paths are relative to the project. --type TYPE --context DECLARATION elaborates a closed type in a proof-erased snapshot of one file. -Add --expression TERM to check a closed term against the type. Add --candidate REF to tag a single saved file check. -Use --health instead of --file to check the pinned compiler and environment. A timeout of zero waits until completion. -These diagnostics are advisory."; -fn shell_quote(path: &Path) -> String { - format!("'{}'", path.to_string_lossy().replace("'", "'\\''")) -} -fn absolute(path: &Path) -> Result { - let mut out = PathBuf::new(); - for c in env::current_dir() - .map_err(|e| e.to_string())? - .join(path) - .components() - { - if c == Component::ParentDir { - out.pop(); - } else { - out.push(c); - } - } - Ok(out) -} -fn real(path: &Path) -> Result { - fs::canonicalize(path).map_err(|e| { - if e.kind() == std::io::ErrorKind::NotFound { - let missing = absolute(path).unwrap_or_else(|_| path.to_owned()); - let first = missing - .ancestors() - .take_while(|p| !p.exists()) - .last() - .unwrap_or(&missing); - format!( - "ENOENT: no such file or directory, lstat '{}'", - first.display() - ) - } else { - e.to_string() - } - }) -} -fn project_at(root: &Path) -> Result, String> { - let locator = root.join(".scratch/worker-project.json"); - io::canonical(&locator)?; - let modern = locator.exists(); - let file = if modern { - locator - } else { - root.join("COOPERATION.json") - }; - io::canonical(&file)?; - if !file.exists() { - return Ok(None); - } - let encoded = io::text(&file, if modern { 16000 } else { 32_000_000 })?; - let context: Value = serde_json::from_str(&encoded).map_err(|e| e.to_string())?; - let relative = if modern { - if context["schema"] != "theorem-os.worker-project.v1" { - return Err("math_worker_project_invalid".into()); - } - &context["projectRelative"] - } else { - &context["researchDelivery"]["projectRelative"] - }; - let relative = relative - .as_str() - .filter(|s| !Path::new(s).is_absolute()) - .ok_or("math_worker_project_missing")?; - let full = absolute(&root.join(relative))?; - if !full.starts_with(root) { - return Err("math_worker_project_outside_worktree".into()); - } - io::canonical(&full)?; - if !full.is_dir() { - return Err("math_worker_project_missing".into()); - } - Ok(Some(full)) -} -fn resolve(workspace: Option<&str>, worktree: Option<&str>) -> Result { - let infrastructure = |message: String| json!({"status":"infrastructure-error","classification":"infrastructure","exitCode":1,"timedOut":false,"leanStarted":false,"error":health::failure("project",&message)}); - if let Some(workspace) = workspace { - return real(Path::new(workspace)).map_err(infrastructure); - } - let root = real(Path::new(worktree.unwrap())).map_err(infrastructure)?; - if let Some(project) = project_at(&root).map_err(infrastructure)? { - return Ok(project); - } - for parent in root.ancestors().skip(1).filter(|p| p.parent().is_some()) { - if !parent.join(".scratch/worker-project.json").exists() - && !parent.join("COOPERATION.json").exists() - { - continue; - } - if let Ok(Some(project)) = project_at(parent) - && root.starts_with(&project) - { - let message = format!( - "Expected the worker worktree root {}; received its subdirectory {}.", - parent.display(), - root.display() - ); - let recovery = format!( - "Use check-lean --worktree {} --file 'OWNED_FILE.lean', or check-lean --workspace {} --file 'OWNED_FILE.lean'. File paths are relative to the Lean project, without its prefix.", - shell_quote(parent), - shell_quote(&project) - ); - return Err( - json!({"status":"usage-error","classification":"usage","exitCode":1,"timedOut":false,"leanStarted":false,"error":{"code":"math_worktree_root_required","message":message,"recovery":recovery}}), - ); - } - break; - } - Err(infrastructure(format!( - "ENOENT: no such file or directory, open '{}'", - root.join("COOPERATION.json").display() - ))) -} -struct Options<'a> { - health: bool, - ty: Option<&'a str>, - context: Option<&'a str>, - term: Option<&'a str>, - files: Vec, - candidate: Option<&'a str>, - workspace: Option<&'a str>, - worktree: Option<&'a str>, - timeout: Option, -} -fn parse(args: &[String]) -> Result, String> { - let mut workspace = None; - let mut worktree = None; - let mut seconds = "0"; - let mut files = Vec::new(); - let mut candidate = None; - let (mut ty, mut context, mut term) = (None, None, None); - let mut health = false; - let mut it = args.iter().map(String::as_str).peekable(); - if it.peek() == Some(&"check-lean") { - it.next(); - } - while let Some(arg) = it.next() { - if arg == "--health" { - health = true; - continue; - } - let (key, inline) = arg - .split_once('=') - .map_or((arg, None), |(k, v)| (k, Some(v))); - if !matches!( - key, - "--workspace" - | "--worktree" - | "--timeout-seconds" - | "--file" - | "--type" - | "--context" - | "--expression" - | "--candidate" - ) { - return Err(format!("Unknown check-lean argument: {key}")); - } - let value = inline - .or_else(|| it.next().filter(|s| !s.starts_with("--"))) - .ok_or_else(|| format!("{key} requires a value"))?; - match key { - "--workspace" => workspace = Some(value), - "--worktree" => worktree = Some(value), - "--timeout-seconds" => seconds = value, - "--candidate" => candidate = Some(value), - "--file" => files.push(value.to_owned()), - "--type" => ty = Some(value), - "--context" => context = Some(value), - "--expression" => term = Some(value), - _ => unreachable!(), - } - } - let seconds = if seconds.trim().is_empty() { - 0.0 - } else { - seconds.trim().parse::().unwrap_or(f64::NAN) - }; - if workspace.is_some_and(|s| !s.is_empty()) == worktree.is_some_and(|s| !s.is_empty()) - || (!health && files.is_empty()) - || !(0.0..=9_007_199_254_740_991.0).contains(&seconds) - || seconds.fract() != 0.0 - { - return Err("Exactly one of --workspace/--worktree, --file (or --health) and a nonnegative --timeout-seconds are required".into()); - } - if health && (!files.is_empty() || ty.is_some() || context.is_some() || term.is_some()) { - return Err( - "--health checks the environment only; omit --file, --type, --context and --expression" - .into(), - ); - } - if (ty.is_some() || context.is_some()) - && (ty.is_none_or(str::is_empty) || context.is_none_or(str::is_empty) || files.len() != 1) - { - return Err("--type requires --context and exactly one --file".into()); - } - if term.is_some() && ty.is_none_or(str::is_empty) { - return Err("--expression requires --type and --context".into()); - } - if candidate.is_some_and(|reference| { - static REF: std::sync::LazyLock = std::sync::LazyLock::new(|| regex::Regex::new(r"^(?:message:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?:research|delivery):[a-f0-9]{64})$").unwrap()); - files.len()!=1 || ty.is_some() || !REF.is_match(reference) - }) { - return Err( - "--candidate requires a team evidence reference and one saved --file probe".into(), - ); - } - Ok(Options { - ty, - context, - term, - health, - files, - candidate, - workspace: workspace.filter(|s| !s.is_empty()), - worktree, - timeout: (seconds > 0.0).then(|| Duration::from_secs(seconds as u64)), - }) -} -fn guard(project: &Path, files: &[String]) -> Result<(), Value> { - use theoremos_lean::{constraints, sources}; - let checked = (|| { - let file = project.join(".lake/source-constraints.json"); - if file.exists() { - let text = io::text(&file, isize::MAX as usize) - .map_err(|message| json!({ "message":message }))?; - let problem = - serde_json::from_str(&text).map_err(|e| json!({"message":e.to_string()}))?; - constraints::check(project, &problem)?; - } - sources::validate(project.to_str().unwrap_or(""), files) - .map_err(|message| json!({"message":message})) - })(); - checked.map_err(|error:Value| { - let message=error["message"].as_str().unwrap_or("math_diagnostics_failed"); - let mut result=json!({"status":"source-error","classification":"source","exitCode":1,"timedOut":false,"leanStarted":false, - "error":{"message":message,"code":"math_diagnostics_failed","recovery":format!("Inspect the requested saved sources and their imports in {}. --file paths are relative to this Lean project; do not repeat the project directory prefix. For example: check-lean --workspace {} --file 'Submission.lean'.",shell_quote(project), shell_quote(project))}}); - if let Some(file)=error["file"].as_str() { - result["error"]["code"]=message.into(); - result["error"]["file"]=file.into(); - result["error"]["recovery"]=recovery(message,error["declaration"].as_str()).into(); - } - result - }) -} - -fn recovery(reason: &str, name: Option<&str>) -> String { - match reason{ - "math_local_module_import_cycle"=>"Remove the added local import that creates a cycle. Owned modules may import frozen dependencies and each other, but a module cannot import one that imports it. Preserve the saved proof work.".into(), - "math_library_module_changed"=>"This Submission/Library module is a frozen host library: restore its exact bytes from the seed commit with git show. Import it and add new helpers in another owned file.".into(), - "math_library_declaration_redeclared"=>format!("{} is already declared by a frozen Submission/Library module. Remove or rename the copy and use the library declaration by importing its module.",name.unwrap_or("This declaration")), - "math_original_context_changed"=>"Restore the original imports, namespace/section placement, variables, opens, scopes and options from the seed commit. Keep new helpers; move helper-specific scopes and instances inside their proofs. Added imports may use Mathlib or any pinned Mathlib.* module, frozen local modules already imported by the original owned sources, or other owned modules; avoid import cycles.".into(), - _=>format!("Restore the original name, parameters, type and any frozen proof or definition body{} from the seed commit. Preserve new proof work.",name.map(|n|format!(" of {n}")).unwrap_or_default()), - } -} - -async fn execute(project: &Path, source: Env, options: &Options<'_>) -> std::io::Result { - use std::cell::Cell; - use theoremos_lean::worker::{self, Cancellation}; - if !options.health - && let Err(report) = guard(project, &options.files) - { - return Ok(report); - } - let home = std::env::home_dir().unwrap_or_default(); - let home = home.to_string_lossy(); - let mut term = signal(SignalKind::terminate())?; - let mut int = signal(SignalKind::interrupt())?; - let (send, rx) = tokio::sync::watch::channel(false); - let watcher = tokio::spawn(async move { - tokio::select! {_=term.recv()=>(),_=int.recv()=>()}; - let _ = send.send(true); - }); - let cancelled = |mut rx: tokio::sync::watch::Receiver| async move { - let _ = rx.wait_for(|s| *s).await; - }; - let ready = health::check( - project, - source.clone(), - &home, - options.timeout, - cancelled(rx.clone()), - ) - .await; - let attempted = Cell::new(false); - let report = if options.health || ready["status"] != "ready" { - ready - } else { - let progress = |file: &str| { - attempted.set(true); - eprintln!("{}", json!({"event":"lean_check_started","file":file})); - }; - let cancel = Cancellation::new(rx); - let checked = if let (Some(ty), Some(context)) = (options.ty, options.context) { - let q = theoremos_lean::type_worker::Query { - file: &options.files[0], - ty, - context, - term: options.term, - }; - theoremos_lean::type_worker::check( - project, - q, - source.clone(), - options.timeout, - cancel, - progress, - ) - .await - } else { - worker::files( - project, - &options.files, - source.clone(), - options.timeout, - cancel, - progress, - ) - .await - }; - match checked { - Ok(mut result) => { - let failed = result["started"] == false - && result["timedOut"] != true - && result["aborted"] != true; - let class = if result["timedOut"] == true { - "timeout" - } else if result["aborted"] == true { - "cancelled" - } else if result["exitCode"] == 0 { - "success" - } else if failed { - "infrastructure" - } else { - "lean" - }; - result["classification"] = class.into(); - if let Some(reference) = options.candidate { - result["candidate"] = json!({"ref":reference,"file":options.files[0]}); - } - if failed { - result["status"] = "infrastructure-error".into(); - result["leanStarted"] = false.into(); - result["error"] = health::failure( - "toolchain", - result["stderr"] - .as_str() - .filter(|s| !s.is_empty()) - .unwrap_or("Lean compiler process did not start"), - ); - } - result - } - Err(e) => { - let mut repeated = - health::check(project, source, &home, None, std::future::pending()).await; - let started = if attempted.get() { - Value::Null - } else { - false.into() - }; - if repeated["status"] != "ready" { - repeated["leanStarted"] = started; - repeated - } else { - json!({"status":"diagnostics-error","classification":"tooling","exitCode":1,"timedOut":false,"leanStarted":started,"error":{"code":"math_diagnostics_failed","message":e}}) - } - } - } - }; - watcher.abort(); - Ok(report) -} -pub fn run(args: &[String]) -> Result { - if args.iter().any(|s| s == "--help") { - println!("{HELP}"); - return Ok(0); - } - let report = match parse(args) { - Err(message) => { - json!({"status":"usage-error","classification":"usage","exitCode":1,"timedOut":false,"leanStarted":false,"error":{"code":"math_diagnostics_failed","message":message}}) - } - Ok(options) => match resolve(options.workspace, options.worktree) { - Err(report) => report, - Ok(project) => { - let source: Env = env::vars_os() - .filter_map(|(k, v)| { - Some((k.into_string().ok()?, v.into_string().ok()?.into())) - }) - .collect(); - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|e| e.to_string())?; - runtime - .block_on(execute(&project, source, &options)) - .map_err(|e| e.to_string())? - } - }, - }; - println!("{report}"); - Ok(if report["timedOut"] == true { - 124 - } else { - report["exitCode"].as_u64().unwrap_or(1) as u8 - }) -} diff --git a/rust/cli/src/checkpoint.rs b/rust/cli/src/checkpoint.rs deleted file mode 100644 index 0a122aac..00000000 --- a/rust/cli/src/checkpoint.rs +++ /dev/null @@ -1,176 +0,0 @@ -use serde_json::{Value, json}; -use sha2::{Digest, Sha256}; -use std::env; -use std::fs::{self, OpenOptions}; -use std::io::{Read, Write}; -use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; -use std::path::{Component, Path, PathBuf}; - -const HELP: &str = "Usage: theorem-os checkpoint --log FILE --request-id ID [--worktree DIR]"; -const NOTES_ERROR: &str = - "Save your current research in a nonempty RESEARCH.md before acknowledging the checkpoint."; -const USE_REQUEST: &str = "Use the checkpoint command from the current host request."; -const NOTES_LIMIT: u64 = 1_000_000; -const LINE_LIMIT: usize = 16_000_000; - -fn absolute_join(worktree: &Path, name: &str) -> Option { - if !worktree.is_absolute() { - return None; - } - let mut out = PathBuf::new(); - for part in worktree.join(name).components() { - match part { - Component::RootDir => out.push("/"), - Component::ParentDir => { - out.pop(); - } - Component::Normal(v) => out.push(v), - Component::CurDir => {} - Component::Prefix(_) => return None, - } - } - Some(out) -} -fn canonical(path: &Path) -> bool { - for ancestor in path.ancestors() { - match fs::symlink_metadata(ancestor) { - Ok(_) => return ancestor.canonicalize().is_ok_and(|p| p == ancestor), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(_) => return false, - } - } - false -} -fn notes_digest(worktree: &Path) -> Option { - let path = absolute_join(worktree, "RESEARCH.md")?; - if !canonical(&path) { - return None; - } - let file = OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(path) - .ok()?; - let stat = file.metadata().ok()?; - if !stat.is_file() || stat.nlink() != 1 || stat.len() > NOTES_LIMIT { - return None; - } - let mut data = Vec::new(); - file.take(NOTES_LIMIT + 1).read_to_end(&mut data).ok()?; - if data.len() as u64 > NOTES_LIMIT { - return None; - } - let text = String::from_utf8_lossy(&data); - // Node hashes the decoded text, including whitespace, if ECMAScript trim yields a nonempty string. - let js_whitespace = |c: char| matches!(c,'\u{9}'..='\u{d}'|'\u{20}'|'\u{a0}'|'\u{1680}'|'\u{2000}'..='\u{200a}'|'\u{2028}'|'\u{2029}'|'\u{202f}'|'\u{205f}'|'\u{3000}'|'\u{feff}'); - if text.trim_matches(js_whitespace).is_empty() { - return None; - } - Some(format!("{:x}", Sha256::digest(text.as_bytes()))) -} -fn queue(worktree: &Path, log: &str, request: &str) -> Result { - let digest = notes_digest(worktree).ok_or(NOTES_ERROR)?; - if !log - .strip_prefix("DELIVERIES-") - .and_then(|s| s.strip_suffix(".jsonl")) - .is_some_and(|s| { - s.len() == 64 - && s.bytes() - .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) - }) - { - return Err("math_delivery_log_invalid".into()); - } - let path = absolute_join(worktree, log) - .filter(|p| canonical(p)) - .ok_or("math_path_invalid")?; - let mut line = - json!({"kind":"checkpoint","requestId":request,"notesDigest":digest}).to_string(); - line.push('\n'); - if line.len() > LINE_LIMIT { - return Err("math_delivery_line_too_large".into()); - } - let mut file = OpenOptions::new() - .append(true) - .create(true) - .mode(0o600) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(&path) - .map_err(|e| format!("{}: {}", path.display(), e))?; - let stat = file.metadata().map_err(|e| e.to_string())?; - if !stat.is_file() || stat.nlink() != 1 { - return Err("math_delivery_log_invalid".into()); - } - file.write_all(line.as_bytes()) - .and_then(|_| file.sync_all()) - .map_err(|e| e.to_string())?; - Ok(json!({"status":"queued","file":log})) -} -fn command(args: &[String]) -> Result<(), String> { - let (mut worktree, mut log, mut request, mut help) = (None, None, None, false); - let mut args = args.iter(); - while let Some(arg) = args.next() { - if arg == "--" { - if let Some(extra) = args.next() { - return Err(format!( - "Unexpected argument '{extra}'. This command does not take positional arguments" - )); - } - break; - } - let (key, inline) = arg - .split_once('=') - .map_or((arg.as_str(), None), |(k, v)| (k, Some(v))); - match key { - "--help" | "-h" => { - if inline.is_some() { - return Err("Option '-h, --help' does not take an argument".into()); - } - help = true - } - "--worktree" | "--log" | "--request-id" => { - let v = if let Some(s) = inline { - s - } else { - let s = args - .next() - .ok_or_else(|| format!("Option '{key} ' argument missing"))?; - if s.starts_with('-') && s != "-" { - return Err(format!( - "Option '{key}' argument is ambiguous.\nDid you forget to specify the option argument for '{key}'?\nTo specify an option argument starting with a dash use '{key}=-XYZ'." - )); - } - s - }; - match key { - "--worktree" => worktree = Some(PathBuf::from(v)), - "--log" => log = Some(v), - _ => request = Some(v), - } - } - _ if arg.starts_with('-') && arg != "-" => { - return Err(format!("Unknown option '{key}'")); - } - _ => { - return Err(format!( - "Unexpected argument '{arg}'. This command does not take positional arguments" - )); - } - } - } - if help { - println!("{HELP}"); - return Ok(()); - } - let log = log.filter(|s| !s.is_empty()).ok_or(USE_REQUEST)?; - let request = request.filter(|s| !s.is_empty()).ok_or(USE_REQUEST)?; - let worktree = match worktree { - Some(p) => p, - None => env::current_dir().map_err(|e| e.to_string())?, - }; - println!("{}", queue(&worktree, log, request)?); - Ok(()) -} -pub fn run(args: &[String]) -> Result<(), String> { - command(args).map_err(|e| json!({"status":"error","error":e}).to_string()) -} diff --git a/rust/cli/src/comparison/experiment.rs b/rust/cli/src/comparison/experiment.rs deleted file mode 100644 index 9ef8ce8a..00000000 --- a/rust/cli/src/comparison/experiment.rs +++ /dev/null @@ -1,176 +0,0 @@ -use super::{ - policy::{ordered, positive, s, shape, unique}, - *, -}; -use std::collections::HashSet; -use theoremos_library::module_plan::{SLOTS, append, ascii_id, configuration, valid_plan}; -fn method(mut identity: Value, harness: &Value) -> String { - if !harness.is_null() && harness["id"] != "codex" { - append(&mut identity, "M1", &format!(":{}:v1", s(&harness["id"]))); - } - let versions: Vec<_> = SLOTS - .iter() - .map(|slot| json!([slot, identity["versions"][slot]])) - .collect(); - digest(&json!({"id":identity["id"],"versions":versions})) -} -pub fn describe(plan: &Value) -> Result> { - let e = &plan["moduleExperiment"]; - if e.is_null() { - return Ok(None); - } - let vs = rows(&e["variants"]); - if !shape(e, &["schema", "baseline", "variants"]) - || e["schema"] != "theorem-os.module-experiment.v1" - || !(2..=8).contains(&vs.len()) - || !unique(vs.iter().map(|v| s(&v["id"]))) - || !vs.iter().any(|v| v["id"] == e["baseline"]) - { - return Err("module_experiment_invalid".into()); - } - let mut variants = vec![]; - let mut seen = HashSet::new(); - for v in vs { - let label = s(&v["label"]).trim_matches(theoremos_lean::declarations::whitespace); - if !shape(v, &["id", "label", "plan"]) - || !ascii_id(s(&v["id"]), 48, true) - || label.is_empty() - || label.encode_utf16().count() > 80 - || label.contains(['\r', '\n', '\0', '|']) - || !valid_plan(&v["plan"]) - { - return Err("module_experiment_invalid".into()); - } - let mut v = v.clone(); - let cfg = configuration(&v["plan"]); - let method = method(cfg.clone(), &Value::Null); - if !seen.insert(method.clone()) { - return Err("module_experiment_duplicate_effective_configuration".into()); - } - v["label"] = label.into(); - v["moduleConfiguration"] = cfg; - v["methodDigest"] = method.into(); - variants.push(v); - } - let cfg = &plan["configuration"]; - if cfg["method"] != "direct" - || cfg["scheduler"] != "plan" - || positive(&cfg["workers"]).is_none_or(|n| !(3..=8).contains(&n)) - { - return Err("comparison_module_configuration_mismatch".into()); - } - let reps = positive(&cfg["repetitions"]).ok_or("comparison_module_repetitions_missing")?; - let names: Vec<_> = variants.iter().map(|v| v["id"].clone()).collect(); - let jobs = rows(&plan["jobs"]); - if !ordered(jobs, &names, reps) - || jobs.iter().any(|j| { - let v = variants.iter().find(|v| v["id"] == j["arm"]); - v.is_none_or(|v| { - j["methodDigest"] != method(v["moduleConfiguration"].clone(), &plan["agentHarness"]) - }) || s(&j["modulePlan"]).is_empty() - || s(&j["modulePlanDigest"]).is_empty() - }) - { - return Err("comparison_module_plan_identity_mismatch".into()); - } - let base=variants.iter().find(|v|v["id"]==e["baseline"]).unwrap()["moduleConfiguration"]["versions"].clone(); - for v in &mut variants { - v["changedComponents"] = json!( - SLOTS - .iter() - .filter(|s| v["moduleConfiguration"]["versions"][s] != base[s]) - .collect::>() - ); - } - Ok(Some(json!({"baseline":e["baseline"],"variants":variants}))) -} -pub fn pairs(e: &Value, results: &[Value]) -> Value { - let baseline = &e["baseline"]; - let observed = |r: &Value| { - !matches!( - s(&r["status"]), - "missing" | "invalid" | "unfinished" | "prepared" - ) - }; - let reports = rows(&e["variants"]) - .iter() - .filter(|v| v["id"] != *baseline) - .map(|variant| { - let pairs: Vec<_> = results - .iter() - .filter(|b| b["arm"] == *baseline) - .map(|b| { - let t = results - .iter() - .find(|r| r["arm"] == variant["id"] && r["repetition"] == b["repetition"]); - let complete = observed(b) && t.is_some_and(observed); - let delta = |k: &str| -> Option { - if !complete { - return None; - } - Some(t?[k].as_f64()? - b[k].as_f64()?) - }; - json!({ - "repetition": b["repetition"], - "baselineStatus": b["status"], - "treatmentStatus": t.map_or(json!("missing"),|r|r["status"].clone()), - "complete": complete, - "baselineAccepted": b["accepted"], - "treatmentAccepted": t.is_some_and(|r|r["accepted"]==true), - "tokenDelta": delta("totalTokens"), - "solveWallDeltaMs": delta("solveWallMs"), - }) - }) - .collect(); - let count = |b: bool, t: bool| { - pairs - .iter() - .filter(|p| { - p["complete"] == true - && p["baselineAccepted"] == b - && p["treatmentAccepted"] == t - }) - .count() - }; - let mean = |k: &str| { - let numbers: Vec<_> = pairs.iter().filter_map(|p| p[k].as_f64()).collect(); - ( - numbers.len(), - if numbers.is_empty() { - None - } else { - Some(numbers.iter().sum::() / numbers.len() as f64) - }, - ) - }; - let (tokens, token_mean) = mean("tokenDelta"); - let (times, time_mean) = mean("solveWallDeltaMs"); - let complete = pairs.iter().filter(|p| p["complete"] == true).count(); - let delta = pairs - .iter() - .map(|p| { - i64::from(p["treatmentAccepted"] == true) - - i64::from(p["baselineAccepted"] == true) - }) - .sum::(); - json!({ - "baseline": baseline, - "treatment": variant["id"], - "plannedPairs": pairs.len(), - "observedPairs": complete, - "incompletePairs": pairs.len()-complete, - "wins": count(false,true), - "losses": count(true,false), - "bothAccepted": count(true,true), - "neitherAccepted": count(false,false), - "acceptanceRateDelta": (!pairs.is_empty()).then(||delta as f64/pairs.len() as f64), - "tokenPairs": tokens, - "meanTokenDelta": token_mean, - "timePairs": times, - "meanSolveWallDeltaMs": time_mean, - "pairs": pairs, - }) - }) - .collect::>(); - json!(reports) -} diff --git a/rust/cli/src/comparison/freshness.rs b/rust/cli/src/comparison/freshness.rs deleted file mode 100644 index 8c360f73..00000000 --- a/rust/cli/src/comparison/freshness.rs +++ /dev/null @@ -1,84 +0,0 @@ -use super::*; - -pub fn check(current: &Value, saved: &Value) -> Result { - let raw = rows(&saved["runs"]); - let saved_rows: Vec<_> = raw.iter().filter(|r| r.is_object()).collect(); - let hash = saved["reportHash"].as_str(); - let invalid = saved["schema"] != current["schema"] - || saved_rows.len() != raw.len() - || hash.is_some_and(|h| h != digest(&obj_without(saved, &["reportHash"]))); - let bound = hash.is_some() - && saved["sourcePlanDigest"].is_string() - && saved["sourceBatchDigest"].is_string() - && saved_rows.iter().all(|r| r.get("sourceSnapshot").is_some()); - let mut out = vec![]; - for row in rows(¤t["runs"]) { - let prev = saved_rows.iter().copied().find(|r| { - ["arm", "repetition", "result"] - .iter() - .all(|k| r.get(k) == row.get(k)) - }); - // The legacy JS encoder rejects an undefined root value. A report predating source snapshots is unbound. - let changed = prev.is_some_and(|p| { - ["sourceSnapshot", "status", "error", "accepted"] - .iter() - .any(|k| p.get(k) != row.get(k)) - || canonical_json(&p["knowledgeFunnel"]) != canonical_json(&row["knowledgeFunnel"]) - }); - let freshness = if invalid { - "invalid" - } else if !bound || prev.is_none() { - "unknown" - } else if changed { - "stale" - } else if row["sourceSnapshot"].is_null() && row["status"] == "invalid" { - "unknown" - } else { - "current" - }; - let mut previous = Value::Null; - if let Some(r) = prev { - previous = json!({}); - present(&mut previous, r, &["status", "accepted", "sourceSnapshot"]); - } - let mut observed = json!({"observation":row["currentObservation"]}); - present( - &mut observed, - row, - &[ - "status", - "accepted", - "error", - "comparisonIdentityMatches", - "sourceSnapshot", - ], - ); - let mut item = json!({"freshness":freshness,"previous":previous,"current":observed}); - present(&mut item, row, &["arm", "repetition", "result"]); - out.push(item); - } - let freshness = if invalid { - "invalid" - } else if !bound { - "unknown" - } else if saved["sourcePlanDigest"] != current["sourcePlanDigest"] - || saved["sourceBatchDigest"] != current["sourceBatchDigest"] - || saved_rows.len() != out.len() - || out.iter().any(|r| r["freshness"] == "stale") - { - "stale" - } else if out.iter().any(|r| r["freshness"] == "unknown") { - "unknown" - } else { - "current" - }; - Ok(json!({ - "schema": "theoremos.comparison-report-freshness.v1", - "evidence": "recorded-not-replayed", - "checkedAt": now(), - "freshness": freshness, - "savedGeneratedAt": saved["generatedAt"], - "note": "A continuation may change the stored observation or budget. It is not counted as a solve under different frozen comparison inputs.", - "runs": out, - })) -} diff --git a/rust/cli/src/comparison/funnel.rs b/rust/cli/src/comparison/funnel.rs deleted file mode 100644 index f1d9d896..00000000 --- a/rust/cli/src/comparison/funnel.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! Reconstruct retained catalog observations, including the consumer and proof that each use names. -use super::*; -use policy::s; -use std::collections::{HashMap, HashSet}; -use theoremos_library::knowledge::{closed_goals, task_version}; -use theoremos_solver::receipts::matches_problem; - -struct Goal<'a> { - target: &'a Value, - task: Value, - version: String, - source: &'static str, - proof: Option<&'a Value>, -} -fn originals_for<'a>(state: &'a Value, nodes: &'a [Value]) -> Vec> { - let check = &state["check"]; - let problem = &state["problem"]; - let whole = check["passed"] == true && matches_problem(problem, check); - let closures = closed_goals(state); - rows(&problem["targets"]) - .iter() - .enumerate() - .map(|(index, target)| { - let node = nodes.iter().find(|n| { - n["task"]["kind"] == "goal" - && n["task"]["proofPath"] == target["proofPath"] - && n["task"]["theoremName"] == target["theoremName"] - }); - let task = node.map_or_else( - || { - let mut t = json!({ - "id": format!("original_goal_{}",index+1), - "kind": "goal", - "objective": format!("Prove {}",s(&target["theoremName"])), - "revision": 0, - "dependsOn": [], - }); - if let Some(m) = target.as_object() { - t.as_object_mut().unwrap().extend(m.clone()); - } - t - }, - |n| n["task"].clone(), - ); - let (source, proof) = if whole { - ("whole-original-check", Some(check)) - } else if let Some(proof) = node - .filter(|_| closures.contains(s(&task["id"]))) - .and_then(|n| n.get("integratedCheck").or_else(|| n.get("proof"))) - { - ("integrated-original-task", Some(proof)) - } else { - ("not-recorded", None) - }; - let version = task_version(&task); - Goal { - target, - source, - proof, - version, - task, - } - }) - .collect() -} -fn dedup<'a>(items: impl Iterator) -> Vec<&'a Value> { - let mut found = HashSet::new(); - items.filter(|v| found.insert(canonical_json(v))).collect() -} -fn field<'a>(items: &[&'a Value], key: &str) -> Vec<&'a Value> { - items.iter().flat_map(|v| rows(&v[key])).collect() -} -fn distinct(a: &[&Value]) -> usize { - a.iter() - .filter_map(|v| v.as_str()) - .collect::>() - .len() -} -fn available(t: &Value, p: &Value) -> bool { - let r = &p["references"]; - if p["passed"] != true { - return false; - } - if !r.is_null() - && r["scope"] != "statement" - && r["sourceCommit"] == p["commit"] - && r["root"]["name"] == t["theoremName"] - && r["root"]["file"] == t["proofPath"] - { - return true; - } - let mut receipts = rows(&p["verification"]["results"]).iter().filter(|r| { - r["theoremName"] == t["theoremName"] - && r["proofPath"] == t["proofPath"] - && r["targetCommit"] == p["commit"] - && r["status"] == "kernel_verified" - }); - receipts - .next() - .is_some_and(|r| r.get("declarationReferences").is_some()) - && receipts.next().is_none() -} -fn coverage<'a>(nodes: &'a [Value], goals: &'a [Goal]) -> (usize, usize) { - let mut consumers = HashMap::new(); - for (task, proof) in nodes - .iter() - .filter_map(|n| { - n.get("integratedCheck") - .filter(|p| p["passed"] == true) - .or_else(|| n.get("proof").filter(|p| p["passed"] == true)) - .map(|p| (&n["task"], p)) - }) - .chain(goals.iter().filter_map(|g| g.proof.map(|p| (&g.task, p)))) - { - let id = canonical_json(&json!([ - task["id"], - task_version(task), - proof["commit"], - proof["sourceDigest"] - ])); - consumers.insert(id, available(task, proof)); - } - (consumers.len(), consumers.values().filter(|v| **v).count()) -} -fn original_use<'a, 'b>(goals: &'a [Goal<'b>], u: &Value) -> Option<&'a Goal<'b>> { - let c = &u["consumer"]; - goals - .iter() - .find(|g| g.task["id"] == c["taskId"] && c["taskDigest"] == g.version) -} -fn referenced_at_closure(goals: &[Goal], u: &Value) -> bool { - let Some(g) = original_use(goals, u) else { - return false; - }; - let Some(p) = g.proof else { - return false; - }; - if u["status"] != "checked-reference" - || u["checkedCommit"] != p["commit"] - || u["checkedSourceDigest"] != p["sourceDigest"] - { - return false; - } - let refs = if g.source == "integrated-original-task" { - &p["references"]["proof"] - } else { - let Some(r) = rows(&p["verification"]["results"]).iter().find(|r| { - r["proofPath"] == g.target["proofPath"] && r["theoremName"] == g.target["theoremName"] - }) else { - return false; - }; - &r["declarationReferences"]["proof"] - }; - rows(refs).iter().any(|r| { - !s(&r["name"]).is_empty() - && !s(&r["file"]).is_empty() - && r["name"] == u["declaration"]["name"] - && r["file"] == u["declaration"]["file"] - }) -} -pub fn report(state: &Value, mode: &Value) -> Value { - let catalog = &state["knowledgeDigest"]; - let ledger = &state["knowledgeRetrievals"]; - let all_retrievals = rows(&ledger["observations"]); - let observed: Vec<_> = all_retrievals - .iter() - .filter(|r| r["catalogDigest"] == *catalog) - .collect(); - let retrievals = dedup(observed.iter().copied()); - let included: Vec<_> = retrievals - .iter() - .copied() - .filter(|r| r["included"] == true) - .collect(); - let detailed: Vec<_> = retrievals - .iter() - .copied() - .filter(|r| r.get("searchCandidateIds").is_some()) - .collect(); - let requests = field(&retrievals, "residualSearches"); - let residual_hits = field(&requests, "candidateIds"); - let returned = field(&detailed, "searchCandidateIds"); - let packet = field(&retrievals, "candidateIds"); - let exposed = field(&included, "candidateIds"); - let nodes = rows(&state["cooperation"]["tasks"]); - let goals = originals_for(state, nodes); - let authored: Vec<_> = rows(&state["knowledgeUses"]) - .iter() - .map(|u| obj_without(u, &["workerId", "commit"])) - .collect(); - let all_uses: Vec<_> = authored - .iter() - .chain( - rows(&state["cooperation"]["deliveries"]) - .iter() - .flat_map(|d| rows(&d["knowledgeUses"])), - ) - .collect(); - let kept: Vec<_> = all_uses - .iter() - .copied() - .filter(|u| u["catalogDigest"] == *catalog) - .collect(); - let uses = dedup(kept.iter().copied()); - let uses_where = |f: &dyn Fn(&Value) -> bool| uses.iter().filter(|u| f(u)).count(); - let linked = uses_where(&|u| { - included.iter().any(|r| { - if !rows(&r["candidateIds"]).contains(&u["id"]) { - return false; - } - let c = &r["consumer"]; - let k = &u["consumer"]; - if c.get("taskId").is_some() || c.get("taskDigest").is_some() { - return c.get("taskId") == k.get("taskId") - && c.get("taskDigest") == k.get("taskDigest"); - } - original_use(&goals, u).is_some_and(|g| { - g.target["theoremName"] == c["theoremName"] - && g.target["proofPath"] == c["proofPath"] - }) - }) - }); - let current = uses_where(&|u| { - nodes.iter().any(|n| { - n["task"]["id"] == u["consumer"]["taskId"] - && task_version(&n["task"]) == u["consumer"]["taskDigest"] - }) || original_use(&goals, u).is_some() - }); - let applications: Vec<_> = uses.iter().filter_map(|u| u.get("application")).collect(); - let checks: Vec<_> = applications.iter().filter_map(|a| a.get("check")).collect(); - let curr = checks - .iter() - .filter(|c| c["environmentDigest"] == state["environmentDigest"]) - .count(); - let checked = |u: &Value| u["status"] == "checked-reference"; - let (consumers, with_refs) = coverage(nodes, &goals); - let coverage = json!({ - "retrievalLedger": if ledger.is_null(){"not-recorded"}else{"recorded"}, - "droppedRetrievalObservations": ledger.get("dropped").cloned().unwrap_or(0.into()), - "useHistory": "retained-records-only; earlier-drops-not-counted", - "contextSelectionLink": "same-catalog-candidate-and-consumer; ordering-and-causality-not-assessed", - "rawSearchHits": if detailed.is_empty(){"not-recorded"}else if detailed.len()(), - "returnedResidualHitOccurrences": residual_hits.len(), - "distinctReturnedResidualCandidates": distinct(&residual_hits), - "observationsWithRawHitDetails": detailed.len(), - "observationsWithoutRawHitDetails": retrievals.len()-detailed.len(), - "returnedCandidateOccurrences": (!detailed.is_empty()).then_some(returned.len()), - "distinctReturnedCandidates": (!detailed.is_empty()).then(||distinct(&returned)), - "packetCandidateOccurrences": packet.len(), - "distinctPacketCandidates": distinct(&packet), - }); - let context = json!({ - "includedSections": included.len(), - "omittedSections": retrievals.len()-included.len(), - "includedCandidateExposures": exposed.len(), - "distinctIncludedCandidates": distinct(&exposed), - }); - let selection = json!({ - "recordedUses": uses.len(), - "distinctCandidates": uses.iter().filter_map(|u|u["id"].as_str()).filter(|s|!s.is_empty()).collect::>().len(), - "duplicateRecords": kept.len()-uses.len(), - "reportedAttempts": uses_where(&|u|u["status"]=="reported-attempt"), - "modelReportedUses": uses_where(&|u|u["attribution"]=="model-reported-origin"), - "hostDiscoveredReferences": uses_where(&|u|u["attribution"]=="host-observed-reference"), - "exactCatalogReferences": uses_where(&|u|checked(u)&&u["catalogDeclarationMatch"]==true), - "modelReportedAdaptationReferences": uses_where(&|u|checked(u)&&u["catalogDeclarationMatch"]==false), - "referencesWithoutCatalogMatchObservation": uses_where(&|u|checked(u)&&u.get("catalogDeclarationMatch").is_none()), - "checkedReferences": uses_where(&checked), - "withRetainedIncludedContext": linked, - "withoutRetainedIncludedContext": uses.len()-linked, - "currentConsumerContracts": current, - "historicalOrMissingConsumerContracts": uses.len()-current, - }); - let application = json!({ - "reports": applications.len(), - "checks": checks.len(), - "reportsWithoutCheck": applications.len()-checks.len(), - "elaborated": checks.iter().filter(|c|c["status"]=="elaborated").count(), - "elaboratedUsingSelectedDeclaration": checks.iter().filter(|c|c["status"]=="elaborated"&&c["selectedDeclarationUsed"]==true).count(), - "failed": checks.iter().filter(|c|c["status"]=="failed").count(), - "unavailable": checks.iter().filter(|c|c["status"]=="unavailable").count(), - "reused": checks.iter().filter(|c|c["reused"]==true).count(), - "matchingRecordedEnvironment": curr, - "otherRecordedEnvironment": checks.len()-curr, - }); - let closure = json!({ - "originalGoals": goals.len(), - "recordedClosedOriginalGoals": goals.iter().filter(|g|g.proof.is_some()).count(), - "usesWithClosedOriginalConsumer": uses_where(&|u|original_use(&goals,u).is_some_and(|g|g.proof.is_some())), - "checkedReferencesAtClosedOriginalReceipt": uses_where(&|u|referenced_at_closure(&goals,u)), - "goals": goals.iter().map(|g|json!({"theoremName":g.target["theoremName"],"proofPath":g.target["proofPath"],"taskId":g.task["id"],"taskDigest":g.version,"closed":g.proof.is_some(),"source":g.source})).collect::>(), - }); - json!({ - "schema": "theorem-os.knowledge-funnel.v1", - "evidence": "recorded-not-replayed", - "attribution": "observed-not-causal", - "acceptance": "not-assessed", - "scope": "retained-observations", - "mode": mode.as_str().unwrap_or("unspecified"), - "catalogDigest": catalog, - "coverage": coverage, - "retrieval": retrieval, - "context": context, - "selection": selection, - "application": application, - "consumerClosure": closure, - }) -} diff --git a/rust/cli/src/comparison/knowledge.rs b/rust/cli/src/comparison/knowledge.rs deleted file mode 100644 index a4b25dfb..00000000 --- a/rust/cli/src/comparison/knowledge.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Authenticate the original knowledge snapshot and classify same-problem material. -use super::{ - policy::{hash, s, shape}, - *, -}; -use std::{collections::HashSet, os::unix::fs::MetadataExt}; -use theoremos_lean::declarations::{Mode, qualified_names, scan}; -use theoremos_library::knowledge::archive::Archive; - -pub fn check( - directory: &Path, - record: Option<&Value>, - problem: Option<&str>, - targets: &[Value], -) -> Result> { - let Some(binding) = record else { - return Ok(None); - }; - let file = directory.join("knowledge/catalog.json"); - if !shape(binding, &["file", "digest", "format", "mode"]) - || binding["file"] != json!(file) - || !hash(&binding["digest"]) - || !matches!(s(&binding["format"]), "v1" | "v2") - || !matches!(s(&binding["mode"]), "transfer" | "recovery") - { - return Err("comparison_knowledge_identity_mismatch".into()); - } - let catalog = Archive::open(s(&binding["file"]), binding["digest"].as_str())?; - if catalog.format != binding["format"] || fs::metadata(&file).map_err(err)?.mode() & 0o222 != 0 - { - return Err("comparison_knowledge_identity_mismatch".into()); - } - let base = catalog.materialize()?; - let entries = rows(&base["entries"]) - .iter() - .filter(|e| { - problem.is_some_and(|id| { - rows(&e["provenance"]).iter().any(|p| p["problemId"] == id) - || targets.contains(&e["name"]) - }) - }) - .count(); - let findings = rows(&base["routeFindings"]) - .iter() - .filter(|f| problem.is_some_and(|id| f["scope"]["problemId"] == id)) - .count(); - let mut duplicates = HashSet::new(); - if !targets.is_empty() { - for (hash, source) in base["sources"] - .as_object() - .ok_or("math_knowledge_schema_invalid")? - { - let source = s(source); - for name in qualified_names(source, &scan(source, Mode::Named)) { - if targets.iter().any(|target| target == &name) { - duplicates.insert((hash, name)); - } - } - } - } - if binding["mode"] == "transfer" && (entries > 0 || findings > 0 || !duplicates.is_empty()) { - return Err("comparison_transfer_contains_target_knowledge; use --knowledge-mode recovery for same-problem material".into()); - } - let mut observation = binding.clone(); - observation["sameProblemEntries"] = entries.into(); - observation["sameProblemFindings"] = findings.into(); - observation["sameTargetSourceDeclarations"] = duplicates.len().into(); - observation["scopeCheck"] = "recorded-problem-target-and-source-declaration-identities".into(); - Ok(Some(observation)) -} diff --git a/rust/cli/src/comparison/mod.rs b/rust/cli/src/comparison/mod.rs deleted file mode 100644 index 7e3a62db..00000000 --- a/rust/cli/src/comparison/mod.rs +++ /dev/null @@ -1,246 +0,0 @@ -//! Historical reports operate only on persisted inputs. Preparation and execution belong to the frozen host. -mod experiment; -mod freshness; -mod funnel; -mod knowledge; -mod ordinary; -mod policy; -mod sample; -use crate::{ - build, - report_flags::{flags, required}, -}; -use serde_json::{Value, json}; -use sha2::{Digest, Sha256}; -use std::{ - fs::{self, File}, - io::Write, - os::unix::fs::{DirBuilderExt, OpenOptionsExt}, - path::Path, -}; -use theoremos_lean::configuration::canonical_json; -use theoremos_library::io; - -type Result = std::result::Result; -fn err(e: impl std::fmt::Display) -> String { - e.to_string() -} -fn now() -> i64 { - chrono::Utc::now().timestamp_millis() -} -fn sha(b: impl AsRef<[u8]>) -> String { - format!("{:x}", Sha256::digest(b)) -} -fn digest(v: &Value) -> String { - sha(canonical_json(v)) -} -fn read(path: &Path) -> Result { - let text = io::text(path, usize::MAX)?; - serde_json::from_str(&text).map_err(err) -} -fn obj_without(value: &Value, keys: &[&str]) -> Value { - let mut v = value.clone(); - if let Some(map) = v.as_object_mut() { - for &k in keys { - map.shift_remove(k); - } - } - v -} -fn rows(v: &Value) -> &[Value] { - v.as_array().map(Vec::as_slice).unwrap_or_default() -} -fn present(dst: &mut Value, src: &Value, keys: &[&str]) { - for &k in keys { - if let Some(v) = src.get(k) { - dst[k] = v.clone(); - } - } -} -fn publish(path: &Path, report: &Value) -> Result<()> { - io::canonical(path)?; - if path.try_exists().map_err(err)? { - let previous_text = io::text(path, usize::MAX)?; - let previous: Value = serde_json::from_str(&previous_text).map_err(err)?; - let ignored = ["generatedAt", "reportHash"]; - if canonical_json(&obj_without(&previous, &ignored)) - != canonical_json(&obj_without(report, &ignored)) - { - let history = path.with_extension("json.history"); - io::canonical(&history)?; - fs::DirBuilder::new() - .recursive(true) - .mode(0o700) - .create(&history) - .map_err(err)?; - let snapshot = history.join(format!("{}.json", sha(&previous_text))); - match fs::OpenOptions::new() - .create_new(true) - .write(true) - .mode(0o400) - .open(&snapshot) - { - Ok(mut f) => { - f.write_all(previous_text.as_bytes()) - .and_then(|_| f.sync_all()) - .map_err(err)?; - } - Err(e) - if e.kind() == std::io::ErrorKind::AlreadyExists - && io::text(&snapshot, usize::MAX)? == previous_text => {} - Err(e) => return Err(err(e)), - } - } - } - let directory = path.parent().ok_or("math_path_invalid")?; - let mut f = tempfile::NamedTempFile::new_in(directory).map_err(err)?; - f.write_all(canonical_json(report).as_bytes()) - .and_then(|_| f.as_file().sync_all()) - .map_err(err)?; - f.persist(path).map_err(err)?; - File::open(directory) - .and_then(|dir| dir.sync_all()) - .map_err(err) -} -fn current(directory: &Path, plan: &Value) -> Result { - if plan["schema"] != "deepscientist.math.comparison.v1" || rows(&plan["jobs"]).is_empty() { - return Err("invalid comparison plan".into()); - } - ordinary::current(directory, plan) -} -fn totals(runs: &[Value], names: &[Value]) -> Value { - json!(names.iter().map(|arm|{ - let selected:Vec<_>=runs.iter().filter(|r|r["arm"]==*arm).collect();let accepted=selected.iter().filter(|r|r["accepted"]==true).count(); - json!({ - "arm": arm, - "planned": selected.len(), - "accepted": accepted, - "acceptanceRate": if selected.is_empty(){Value::Null}else{json!(accepted as f64/selected.len() as f64)}, - "reportedTokens": selected.iter().filter_map(|r|r["totalTokens"].as_f64()).sum::(), - "missingTokenRuns": selected.iter().filter(|r|r["totalTokens"].is_null()).count(), - }) - }).collect::>()) -} -const COMMON: &[&str] = &[ - "phase", - "directory", - "repo", - "build-manifest", - "module-experiment", - "provider", - "model", - "effort", - "workers", - "repetitions", - "max-turns", - "max-run-seconds", - "max-turn-seconds", - "max-total-tokens", - "evaluator-timeout-seconds", - "proof-environment-cache-dir", - "knowledge-base", - "knowledge-mode", -]; -pub fn run(command: &str, args: &[String]) -> Result { - let sample = command == "sample-putnam"; - let mut opts = COMMON.to_vec(); - if sample { - opts.extend(["count", "seed"]); - } else { - opts.extend([ - "problem", - "task-file", - "method", - "scheduler", - "dataset", - "skill-baseline", - "common-research-skill", - "source-file", - "harness", - "harness-profile", - "harness-executable", - ]); - } - let flags = flags(args, &opts)?; - let retired = if sample { - "Prepare legacy PutnamBench comparisons from their pinned historical TheoremOS revision." - } else { - "Prepare and execute legacy comparisons from their pinned historical TheoremOS revision." - }; - if flags.contains_key("help") { - let line = if sample { - "Prepare legacy samples from their pinned historical TheoremOS revision." - } else { - retired - }; - println!("Usage: theorem-os {command} --phase report|check-report --directory DIR\n{line}"); - return Ok(0); - } - let check = match required(&flags, "phase")? { - "report" => false, - "check-report" => true, - "prepare" => return Err(retired.into()), - "run" if !sample => return Err(retired.into()), - _ if sample => { - return Err( - "sample-putnam supports only --phase prepare, report or check-report".into(), - ); - } - _ => return Err("invalid --phase".into()), - }; - let directory = io::absolute(Path::new(required(&flags, "directory")?))?; - if sample { - io::canonical(&directory)?; - if build::root(None).is_ok_and(|root| directory.starts_with(root)) - || directory.ancestors().any(|p| { - p.join("extraction.json").is_file() && p.join("scripts/build.ts").is_file() - }) - { - return Err("Keep PutnamBench experiments outside the source checkout.".into()); - } - if flags.keys().any(|k| !matches!(*k, "phase" | "directory")) { - return Err("Sample options are frozen; report only accepts --directory.".into()); - } - println!("{}", canonical_json(&sample::run(&directory, check)?)); - } else { - for key in [ - "harness", - "harness-profile", - "harness-executable", - "module-experiment", - "skill-baseline", - "common-research-skill", - "provider", - "dataset", - "source-file", - "evaluator-timeout-seconds", - ] { - if flags.contains_key(key) { - return Err(format!( - "--{key} is frozen during prepare; run and report use comparison.json" - )); - } - } - if flags.contains_key("knowledge-base") || flags.contains_key("knowledge-mode") { - return Err("--knowledge-base and --knowledge-mode are frozen during prepare; run and report use comparison.json".into()); - } - let file = directory.join("report.json"); - let plan = read(&directory.join("comparison.json"))?; - let report = current(&directory, &plan)?; - let output = if check { - let mut result = json!({"reportFile":file}); - result.as_object_mut().unwrap().extend( - freshness::check(&report, &read(&file)?)? - .as_object() - .unwrap() - .clone(), - ); - result - } else { - publish(&file, &report)?; - json!({"reportFile":file,"totals":report["totals"]}) - }; - println!("{}", canonical_json(&output)); - } - Ok(0) -} diff --git a/rust/cli/src/comparison/ordinary.rs b/rust/cli/src/comparison/ordinary.rs deleted file mode 100644 index cda12931..00000000 --- a/rust/cli/src/comparison/ordinary.rs +++ /dev/null @@ -1,478 +0,0 @@ -//! Reconstruct comparison rows from the frozen protocol and persisted run records. -use super::*; -use std::collections::HashSet; -use theoremos_solver::{ - archive, - budget::{BudgetObservation, build_token_budget}, - receipts, -}; - -fn count(v: &Value) -> Option { - v.as_f64() - .filter(|n| n.fract() == 0. && (0.0..=9_007_199_254_740_991.).contains(n)) -} -fn tokens(v: &Value) -> Option { - count(&v["totalTokens"]).or_else(|| { - count(&json!( - count(&v["inputTokens"])? + count(&v["outputTokens"])? - )) - }) -} -fn usage(state: &Value) -> Value { - let mut solver = state.clone(); - if solver.get("id").is_none() { - solver["id"] = "solver".into(); - } - let workers = state["workers"] - .as_array() - .map(Vec::as_slice) - .unwrap_or_else(|| std::slice::from_ref(&solver)); - let value = |v: &Value| v.as_f64().unwrap_or_default(); - let mut missing = vec![]; - let mut observed = vec![]; - for w in workers { - let t = &w["usageAccounting"]; - let r = &w["requestUsageAccounting"]; - let usage = tokens(&w["usage"]); - let requests = !r.is_null(); - let started = if requests { - value(&r["startedRequests"]) - } else { - t["startedTurns"] - .as_f64() - .unwrap_or_else(|| value(&w["turns"])) - }; - let incomplete = if requests { - r["incomplete"] == true - } else { - t["incomplete"] == true - }; - let attempted = if requests { - started > 0. || incomplete - } else { - value(&w["turns"]) > 0. || w["error"].as_str().is_some_and(|s| !s.is_empty()) - }; - if attempted && usage.is_none() { - missing.push(w["id"].clone()); - } - observed.push(BudgetObservation { - started, - requests, - incomplete, - tokens: usage, - reported: if requests { - value(&r["reportedRequests"]) - } else { - value(&t["reportedTurns"]) - }, - pending: if requests { - value(&r["pendingRequests"]) - } else { - f64::from(t["pending"] == true) - }, - }); - } - let recorded = &state["tokenBudget"]; - let budget = if recorded.is_null() { - Value::Null - } else { - build_token_budget( - value(&recorded["maxTotalTokens"]), - observed, - recorded["enforcement"] - .as_str() - .unwrap_or("provider-observed-dispatch-limit") - .into(), - ) - }; - let worker_count = state.get("workerCount").cloned().unwrap_or(1.into()); - let complete = Some(workers.len() as f64) == worker_count.as_f64() - && missing.is_empty() - && if budget.is_null() { - tokens(&state["usage"]).is_some() - } else { - budget["usageComplete"] == true - }; - let reported = if budget.is_null() { - json!(tokens(&state["usage"])) - } else { - budget["reportedTotalTokens"].clone() - }; - let mut result = json!({ - "tokenBudget": budget, - "workerCount": worker_count, - "observedWorkerCount": workers.len(), - "missingUsageWorkers": missing, - "usageComplete": complete, - "reportedTotalTokens": reported, - "totalTokens": if complete{reported}else{Value::Null}, - }); - present(&mut result, state, &["turns", "dispatchCounts", "usage"]); - result -} -fn input(file: &Path) -> Result { - if !file.try_exists().map_err(err)? { - return Err(format!( - "ENOENT: no such file or directory, open '{}'", - file.display() - )); - } - read(file) -} -fn observation(output: &Path) -> Result<(Value, Value)> { - let file = if output.file_name().is_some_and(|n| n == "state.json") { - output.to_owned() - } else { - Path::new(&format!("{}.runtime", output.display())).join("state.json") - }; - let state = archive::parse(&input(&file)?)?; - let result = if output != file && output.try_exists().map_err(err)? { - let result = input(output)?; - if result["schema"] != "deepscientist.math.run.v2" - || result["runId"] != state["runId"] - || result["stateFile"] - .as_str() - .map(|s| io::absolute(Path::new(s))) - .transpose()? - .as_ref() - != Some(&file) - { - return Err("math_inspect_result_identity_mismatch".into()); - } - result - } else { - Value::Null - }; - Ok((state, result)) -} -fn row(plan: &Value, job: &Value, batch: &Value) -> Result { - let execution = rows(&batch["jobs"]) - .iter() - .find(|b| b.get("launch") == job.get("launch")) - .unwrap_or(&Value::Null); - let output = io::absolute(Path::new( - job["output"] - .as_str() - .ok_or("invalid comparison job output")?, - ))?; - let elapsed = |k: &str| { - chrono::DateTime::parse_from_rfc3339(execution[k].as_str()?) - .ok() - .map(|d| d.timestamp_millis()) - }; - let wall = elapsed("startedAt") - .zip(elapsed("finishedAt")) - .and_then(|(a, b)| (b >= a).then_some(b - a)); - let mut r = json!({ - "status": "missing", - "accepted": false, - "turns": null, - "dispatches": null, - "solveWallMs": null, - "sourceSnapshot": null, - "comparisonIdentityMatches": null, - "currentObservation": null, - "knowledgeFunnel": null, - "totalTokens": null, - "usageComplete": false, - "overrunTokens": null, - "tokenBudget": null, - "missingUsageWorkers": [], - "workerErrors": [], - "wallMs": wall, - "batchStatus": execution["status"], - "signal": execution["signal"], - "batchError": execution["error"], - "exitCode": execution["exitCode"], - "result": job["output"], - }); - present( - &mut r, - job, - &["arm", "repetition", "researchSkill", "commonResearchSkill"], - ); - present(&mut r, execution, &["log"]); - let input = observation(&output); - let (state, result) = match input { - Ok(pair) => pair, - Err(e) => { - if output.exists() - || Path::new(&format!("{}.runtime/state.json", output.display())).exists() - { - r["status"] = "invalid".into(); - } - failure(&mut r, &e); - return Ok(r); - } - }; - r["sourceSnapshot"] = json!({ - "schema": "theoremos.run-observation.v1", - "runId": state["runId"], - "stateDigest": digest(&state), - "resultDigest": if result.is_null(){Value::Null}else{digest(&result).into()}, - }); - let status = if state["phase"] != "finished" { - "unfinished" - } else { - result["status"].as_str().unwrap_or("missing") - }; - let accepted = receipts::recorded_local(&state, &result); - let max = state["tokenBudget"]["maxTotalTokens"] - .as_f64() - .unwrap_or_default(); - let mut observation = json!({ - "status": status, - "localAcceptanceEvidenceMatches": accepted, - "maxTotalTokens": max, - "solutionCommit": result["solution_commit"], - }); - present( - &mut observation, - &state, - &["runId", "phase", "turns", "model", "effort"], - ); - r["currentObservation"] = observation; - let usage = usage(&state); - let cfg = &plan["configuration"]; - let workers = if plan["moduleExperiment"].is_null() - && (job["arm"] == "single" || job["arm"] == "skill") - { - Some(1.) - } else { - cfg["workers"].as_f64() - }; - let coordination = if !plan["moduleExperiment"].is_null() || job["arm"] == "cooperative" { - "cooperative" - } else { - "independent" - }; - let expected_limit = cfg["maxTotalTokens"].as_f64().unwrap_or_default(); - let bound = policy::state_identity(plan, job, &state); - let defect = if let Err(ref e) = bound { - e.as_str() - } else if state["agentHarness"] != job["agentHarness"] { - "comparison_harness_identity_mismatch" - } else if state["problem"]["receiptDigest"] != job["receiptDigest"] - || ["taskDigest", "buildDigest", "environmentDigest"] - .iter() - .any(|k| state.get(k) != plan.get(k)) - || state.get("methodDigest") != job.get("methodDigest") - || state.get("knowledgeDigest") != plan["knowledge"].get("digest") - || state["evaluatorDigest"] != sha("host-default") - || ["model", "effort"] - .iter() - .any(|k| state.get(k) != cfg.get(k)) - || Some(state["workerCount"].as_f64().unwrap_or(1.)) != workers - || state["coordination"].as_str().unwrap_or("cooperative") != coordination - { - "comparison_run_identity_mismatch" - } else if state["researchMode"].as_str().unwrap_or("legacy") - != if job["researchSkill"].is_null() { - "legacy" - } else { - "skill" - } - || state["researchSkill"] != job["researchSkill"] - { - "comparison_skill_identity_mismatch" - } else if state["commonResearchSkill"] != job["commonResearchSkill"] { - "comparison_common_guidance_identity_mismatch" - } else if max != expected_limit { - "comparison_token_budget_mismatch" - } else { - "" - }; - r["comparisonIdentityMatches"] = defect.is_empty().into(); - if !defect.is_empty() { - r["status"] = "invalid".into(); - failure(&mut r, defect); - let mut history = usage; - history["comparisonEligible"] = false.into(); - history["identityError"] = defect.into(); - history["status"] = status.into(); - history["expectedEnvironmentDigest"] = plan["environmentDigest"].clone(); - history["observedEnvironmentDigest"] = state["environmentDigest"].clone(); - r["historicalObservation"] = history; - return Ok(r); - } - present( - &mut r, - &usage, - &[ - "turns", - "usage", - "dispatchCounts", - "missingUsageWorkers", - "tokenBudget", - "usageComplete", - "totalTokens", - ], - ); - r["dispatches"] = r["turns"].clone(); - r["accepted"] = accepted.into(); - r["status"] = status.into(); - if let (Some(a), Some(b)) = ( - count(&state["solveStartedAt"]), - count(&state["solveFinishedAt"]), - ) && b >= a - { - r["solveWallMs"] = json!(b - a); - } - let budget = &usage["tokenBudget"]; - r["overrunTokens"] = if !budget["overrunTokens"].is_null() { - budget["overrunTokens"].clone() - } else { - json!(r["totalTokens"].as_f64().map(|n| if expected_limit > 0. { - (n - expected_limit).max(0.) - } else { - 0. - })) - }; - let mut worker_errors = vec![]; - for w in rows(&state["workers"]) { - if let Some(msg) = w["error"].as_str().filter(|s| !s.is_empty()) { - worker_errors.push(json!({"id":w["id"],"error":msg,"category":category(msg)})); - } - } - r["workerErrors"] = worker_errors.into(); - if status == "evaluated_passed" && !accepted { - failure(&mut r, "comparison_acceptance_evidence_incomplete"); - } else if let Some(e) = result["reason"].as_str() { - failure(&mut r, e); - } - if state["knowledgeDigest"] - .as_str() - .is_some_and(|s| !s.is_empty()) - { - r["knowledgeFunnel"] = funnel::report(&state, &plan["knowledge"]["mode"]); - } - Ok(r) -} -fn failure(r: &mut Value, e: &str) { - r["error"] = e.into(); - if !e.is_empty() { - r["failureCategory"] = category(e).into(); - } -} -use theoremos_library::inspection::category::category; -pub fn current(directory: &Path, plan: &Value) -> Result { - policy::dataset(plan, directory)?; - policy::strategy(plan)?; - let target = vec![plan["problem"].clone()]; - let knowledge = knowledge::check( - directory, - plan.get("knowledge"), - plan["problem"].as_str(), - plan["knowledgeTargetNames"].as_array().unwrap_or(&target), - )?; - let variants = experiment::describe(plan)?; - policy::providers(plan)?; - let batch_file = directory.join("batch.json"); - let batch = if batch_file.try_exists().map_err(err)? { - read(&batch_file)? - } else { - Value::Null - }; - let runs = rows(&plan["jobs"]) - .iter() - .map(|job| row(plan, job, &batch)) - .collect::>>()?; - let enforcements: HashSet<_> = runs - .iter() - .map(|r| { - r["tokenBudget"]["enforcement"] - .as_str() - .unwrap_or("unknown") - }) - .collect(); - let skill = !plan["skillBaseline"].is_null(); - let common = !plan["commonResearchSkill"].is_null(); - let comparison_kind = if variants.is_some() { - "module-plan" - } else if common { - "research-strategy" - } else if skill { - "system-mode" - } else { - "coordination" - }; - let names = variants.as_ref().map_or_else( - || { - vec![ - json!(if skill { "skill" } else { "single" }), - json!("independent"), - json!("cooperative"), - ] - }, - |e| { - rows(&e["variants"]) - .iter() - .map(|v| v["id"].clone()) - .collect() - }, - ); - let mut report = json!({ - "schema": "deepscientist.math.comparison-report.v1", - "evidence": "recorded-not-replayed", - "generatedAt": now(), - "sourcePlanDigest": digest(plan), - "sourceBatchDigest": digest(&batch), - "official": false, - "comparisonKind": comparison_kind, - "tokenAccounting": "provider-reported-all-roles", - "tokenBudgetEnforcement": if enforcements.len()==1{enforcements.iter().next().unwrap()}else{"mixed"}, - "budgetNote": "Each run records whether the shared allowance gates dispatches or upstream requests. In-flight work may exceed it; missing usage prevents complete token or cost comparisons.", - "totals": totals(&runs,&names), - "runs": runs, - }); - present( - &mut report, - plan, - &[ - "problem", - "configuration", - "sourceCommit", - "taskDigest", - "buildDigest", - "environmentDigest", - "dataset", - "sourceProblem", - "leanTask", - "sourceCommitKind", - "skillBaseline", - "commonResearchSkill", - "commonProviderProfile", - "agentHarness", - ], - ); - if let Some(knowledge) = knowledge { - report["knowledge"] = knowledge; - } - if let Some(metadata) = policy::metadata(plan) { - report["provider"] = metadata.clone(); - } - if skill { - report["guidanceComparison"] = if common { - json!({ - "commonGuidanceFrozen": true, - "strategyIsolation": true, - "isolationScope": "shared-mathematical-guidance-with-host-policy-as-treatment", - "protocolDifferencesCounted": true, - "capabilities": "same-frozen-runtime-and-tools-not-provider-certified", - "note": "Every planned arm is configured to load the identical pinned mathematical skill and shared method/tool context. Differences are host research/coordination policy, assignment facts and delivery protocols; their cost is part of the treatment. Native child delegation is disabled. Runtime identity checks do not replace provider execution evidence or establish an efficiency gain.", - }) - } else { - json!({ - "commonGuidanceFrozen": false, - "strategyIsolation": false, - "note": "The skill researcher and legacy coordination arms receive different research instructions and protocols. This compares complete system modes under shared model, tool, environment and total-token settings; it does not isolate a coordination algorithm. A strategy experiment still requires equal frozen mathematical guidance and matched capability checks.", - }) - }; - } - if let Some(experiment) = variants { - report["pairedComparisons"] = experiment::pairs(&experiment, &runs); - report["moduleExperiment"] = experiment; - } - report["reportHash"] = digest(&report).into(); - Ok(report) -} diff --git a/rust/cli/src/comparison/policy.rs b/rust/cli/src/comparison/policy.rs deleted file mode 100644 index b566c090..00000000 --- a/rust/cli/src/comparison/policy.rs +++ /dev/null @@ -1,322 +0,0 @@ -use super::*; -use regex::Regex; -use std::{collections::HashSet, fs, path::PathBuf, sync::LazyLock}; -use theoremos_library::lean_task::current_environment; - -static PROVIDERS: LazyLock = - LazyLock::new(|| serde_json::from_str(include_str!("providers.json")).unwrap()); -static PUTNAM: LazyLock = - LazyLock::new(|| Regex::new("^putnam_[0-9]{4}_[ab][1-6]$").unwrap()); -pub const PUTNAM_PIN: &str = "13d042960189f55d748048317c24064a0e2215ea"; -pub const PUTNAM_REPO: &str = "https://github.com/trishullab/PutnamBench.git"; -pub fn s(v: &Value) -> &str { - v.as_str().unwrap_or_default() -} -pub fn hash(v: &Value) -> bool { - s(v).len() == 64 - && s(v) - .bytes() - .all(|b| b.is_ascii_digit() || matches!(b, b'a'..=b'f')) -} -pub fn dataset(plan: &Value, directory: &Path) -> Result<()> { - let id = s(&plan["problem"]); - let pin = &plan["sourceCommit"]; - let source = &plan["sourceProblem"]; - let lean = &plan["leanTask"]; - match plan.get("dataset").map(s) { - None if !source.is_null() - || !lean.is_null() - || !plan["sourceCommitKind"].is_null() - || pin == PUTNAM_PIN - || id.starts_with("putnam_") => - { - return Err("comparison_dataset_invalid".into()); - } - None => (), - Some("imo2026") => { - if !(1..=6).any(|n| id == format!("imo2026_q{n}")) - || pin != "834c01f2ecac89b648759b1c95bc6180b0ede149" - || plan.get("sourceProblem").is_some() - || !lean.is_null() - || !plan["sourceCommitKind"].is_null() - { - return Err("comparison_imo_source_identity_mismatch".into()); - } - } - Some("lean-task") => { - let env = current_environment("standard").unwrap(); - if !source.is_null() - || plan["sourceCommitKind"] != "input-sha256" - || lean["sourceRelativePath"] != "source.lean" - || !hash(&lean["sourceSha256"]) - || *pin != lean["sourceSha256"] - || lean["environment"] != "standard" - || lean["toolchain"] != env["toolchain"] - || lean["environmentDigest"] != env["dependencyDigest"] - { - return Err("comparison_lean_task_source_identity_mismatch".into()); - } - if sha(io::text(&directory.join("source.lean"), 2 << 20)?) != lean["sourceSha256"] { - return Err("comparison_lean_task_source_changed".into()); - } - } - Some("putnambench") => { - let env = current_environment("mathlib").unwrap(); - if !lean.is_null() - || !plan["sourceCommitKind"].is_null() - || !PUTNAM.is_match(id) - || pin != PUTNAM_PIN - || source["repositoryUrl"] != PUTNAM_REPO - || source["sourceRelativePath"] != format!("lean4/src/{id}.lean") - || !hash(&source["sourceSha256"]) - || source["toolchain"] != env["toolchain"] - || source["mathlibRevision"] != env["mathlibRevision"] - || source["environmentDigest"] != env["dependencyDigest"] - { - return Err("comparison_putnam_source_identity_mismatch".into()); - } - } - _ => return Err("comparison_dataset_invalid".into()), - } - Ok(()) -} -pub fn ordered(jobs: &[Value], names: &[Value], repetitions: usize) -> bool { - repetitions.checked_mul(names.len()) == Some(jobs.len()) - && jobs.iter().enumerate().all(|(i, j)| { - let rep = i / names.len(); - j["repetition"].as_f64() == Some((rep + 1) as f64) - && j["arm"] == names[(i % names.len() + rep) % names.len()] - }) -} -pub fn positive(v: &Value) -> Option { - v.as_f64() - .filter(|n| n.fract() == 0. && (1.0..=9_007_199_254_740_991.).contains(n)) - .map(|n| n as usize) -} -pub fn strategy(plan: &Value) -> Result<()> { - let jobs = rows(&plan["jobs"]); - let skill = &plan["skillBaseline"]; - let common = &plan["commonResearchSkill"]; - let harness = &plan["agentHarness"]; - let provider = &plan["configuration"]["provider"]; - if !common.is_null() && common != skill - || jobs.iter().any(|j| j["commonResearchSkill"] != *common) - { - return Err("comparison_common_guidance_identity_mismatch".into()); - } - if !common.is_null() - && provider.is_null() - && plan["commonProviderProfile"].is_null() - && harness.is_null() - { - return Err("comparison_common_provider_identity_missing".into()); - } - if !plan["commonProviderProfile"].is_null() && (common.is_null() || !provider.is_null()) { - return Err("comparison_common_provider_identity_mismatch".into()); - } - if !skill.is_null() { - if !plan["moduleExperiment"].is_null() - || plan["configuration"]["method"] != "direct" - || plan["configuration"]["scheduler"] != "plan" - || skill["name"] != "theoremos-research" - || !hash(&skill["digest"]) - || !matches!(s(&skill["loading"]), "native" | "file") - { - return Err("comparison_skill_configuration_mismatch".into()); - } - let reps = positive(&plan["configuration"]["repetitions"]) - .ok_or("comparison_skill_repetitions_missing")?; - if !ordered( - jobs, - &[json!("skill"), json!("independent"), json!("cooperative")], - reps, - ) || jobs.iter().any(|j| { - &j["researchSkill"] - != if j["arm"] == "skill" { - skill - } else { - &Value::Null - } - }) { - return Err("comparison_skill_plan_identity_mismatch".into()); - } - } else if jobs.iter().any(|j| !j["researchSkill"].is_null()) { - return Err("comparison_skill_identity_mismatch".into()); - } - if harness.is_null() { - if jobs.iter().any(|j| !j["agentHarness"].is_null()) { - return Err("comparison_harness_identity_mismatch".into()); - } - } else { - if !provider.is_null() || !plan["commonProviderProfile"].is_null() { - return Err("comparison_harness_provider_conflict".into()); - } - for j in jobs { - let h = &j["agentHarness"]; - if !h.is_object() { - return Err("comparison_harness_identity_mismatch".into()); - } - let mut expected = h.clone(); - expected["profile"] = harness["profile"].clone(); - if &expected != harness || h["profile"] != json!(sibling(j, "harness")) { - return Err("comparison_harness_identity_mismatch".into()); - } - } - } - Ok(()) -} -pub fn metadata(plan: &Value) -> Option<&'static Value> { - PROVIDERS - .get(s(&plan["configuration"]["provider"])) - .map(|p| &p["metadata"]) -} -fn sibling(job: &Value, name: &str) -> PathBuf { - Path::new(s(&job["launch"])) - .parent() - .unwrap_or(Path::new(".")) - .join(name) -} -fn expected_profile(profile: &Path, provider: &str, model: &str, effort: &str) -> Result { - let recipe = PROVIDERS - .get(provider) - .ok_or("comparison_provider_invalid")?; - let display = match provider { - "deepseek" => "DeepSeek", - "westlake" => "Westlake", - _ => "Sub2API", - }; - if model != "deepseek-flash" && !(provider == "deepseek" && model == "deepseek-v4-pro") { - return Err(format!( - "{display} requires --model {}", - if provider == "deepseek" { - "deepseek-v4-pro or deepseek-flash" - } else { - "deepseek-flash" - } - )); - } - if !matches!(effort, "low" | "high" | "max") { - return Err(format!("{display} requires --effort low, high or max")); - } - let catalog = serde_json::to_string(&profile.join("models.json")) - .map_err(err)? - .replace('\u{7f}', r"\u007f"); - let config = s(&recipe["config"]) - .replace("@MODEL@", &json!(model).to_string()) - .replace("@EFFORT@", &json!(effort).to_string()) - .replace("@CATALOG@", &catalog); - Ok(digest( - &json!({"config.toml":config,"models.json":recipe["models"]}), - )) -} -fn content(profile: &Path) -> Result { - let mut files = json!({}); - for name in ["config.toml", "models.json"] { - let file = profile.join(name); - if !file.exists() { - return Err(format!( - "ENOENT: no such file or directory, open '{}'", - file.display() - )); - } - files[name] = io::text(&file, usize::MAX)?.into(); - } - Ok(files) -} -pub fn providers(plan: &Value) -> Result<()> { - let cfg = &plan["configuration"]; - let Some(provider) = cfg.get("provider").filter(|v| !v.is_null()) else { - return Ok(()); - }; - if metadata(plan).is_none() { - return Err("comparison_provider_invalid".into()); - } - for j in rows(&plan["jobs"]) { - let profile = sibling(j, "codex"); - if j["codexProfile"] != json!(profile) - || j["codexProfileDigest"].as_str().is_none_or(str::is_empty) - || j["codexProfileDigest"] - != expected_profile(&profile, s(provider), s(&cfg["model"]), s(&cfg["effort"]))? - { - return Err("comparison_provider_profile_identity_mismatch".into()); - } - } - Ok(()) -} -pub fn provider_input(plan: &Value, job: &Value) -> Result<()> { - if !plan["configuration"]["provider"].is_null() - && digest(&content(Path::new(s(&job["codexProfile"])))?) != job["codexProfileDigest"] - { - return Err("comparison_provider_profile_changed".into()); - } - if let Some(common) = plan.get("commonProviderProfile").filter(|v| !v.is_null()) { - let path = Path::new(s(&common["profile"])); - if !path.join("config.toml").exists() { - return Err("comparison_common_provider_unverified".into()); - } - let files = content(path)?; - let parsed: toml::Value = toml::from_str(s(&files["config.toml"])).map_err(err)?; - if parsed - .get("model_provider") - .and_then(toml::Value::as_str) - .is_none_or(|k| PROVIDERS.get(k).is_none()) - { - return Err("comparison_common_provider_unverified".into()); - } - if json!({"profile":fs::canonicalize(path).map_err(err)?,"digest":digest(&files)}) - != *common - { - return Err("comparison_common_provider_changed".into()); - } - } - Ok(()) -} -pub fn state_identity(plan: &Value, job: &Value, state: &Value) -> Result<()> { - provider_input(plan, job)?; - for (dataset, key, reason) in [ - ( - "putnambench", - "sourceProblem", - "comparison_putnam_source_identity_mismatch", - ), - ( - "lean-task", - "leanTask", - "comparison_lean_task_source_identity_mismatch", - ), - ] { - if plan["dataset"] == dataset - && (state["problem"]["kind"] != "lean-task" - || state["problem"]["contract"]["formalStatement"] - .as_str() - .map(sha) - .as_deref() - != plan[key]["sourceSha256"].as_str()) - { - return Err(reason.into()); - } - } - if !plan["configuration"]["provider"].is_null() - && (state["providerProfile"] - != json!(fs::canonicalize(s(&job["codexProfile"])).map_err(err)?) - || state["providerProfileDigest"] != job["codexProfileDigest"]) - { - return Err("comparison_provider_identity_mismatch".into()); - } - let common = &plan["commonProviderProfile"]; - if !common.is_null() - && (state["providerProfile"] != common["profile"] - || state["providerProfileDigest"] != common["digest"]) - { - return Err("comparison_common_provider_identity_mismatch".into()); - } - Ok(()) -} -pub fn shape(v: &Value, keys: &[&str]) -> bool { - v.as_object() - .is_some_and(|o| o.len() == keys.len() && keys.iter().all(|k| o.contains_key(*k))) -} -pub fn unique<'a>(a: impl Iterator) -> bool { - let mut set = HashSet::new(); - a.into_iter().all(|v| set.insert(v)) -} diff --git a/rust/cli/src/comparison/providers.json b/rust/cli/src/comparison/providers.json deleted file mode 100644 index 62fd0f28..00000000 --- a/rust/cli/src/comparison/providers.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "deepseek": { - "metadata": { - "id": "deepseek", - "baseUrl": "https://api.deepseek.com", - "wireApi": "responses", - "apiKeyEnvironment": "DEEPSEEK_API_KEY", - "defaultModel": "deepseek-v4-pro", - "defaultEffort": "high" - }, - "config": "model = @MODEL@\nmodel_provider = \"deepseek\"\nmodel_reasoning_effort = @EFFORT@\nmodel_catalog_json = @CATALOG@\nweb_search = \"disabled\"\napproval_policy = \"never\"\nsandbox_mode = \"workspace-write\"\n\n[model_providers.deepseek]\nname = \"DeepSeek\"\nbase_url = \"https://api.deepseek.com\"\nwire_api = \"responses\"\nenv_key = \"DEEPSEEK_API_KEY\"\nrequires_openai_auth = false\nrequest_max_retries = 0\nstream_max_retries = 0\nstream_idle_timeout_ms = 60000\n\n[shell_environment_policy]\ninherit = \"all\"\nexclude = [ \"DEEPSEEK_API_KEY\" ]\n\n[history]\npersistence = \"none\"\n\n[analytics]\nenabled = false\n", - "models": "{\n \"models\": [\n {\n \"slug\": \"deepseek-v4-pro\",\n \"display_name\": \"deepseek-v4-pro\",\n \"description\": \"DeepSeek mathematical research model\",\n \"prefer_websockets\": false,\n \"support_verbosity\": true,\n \"default_verbosity\": \"low\",\n \"apply_patch_tool_type\": \"freeform\",\n \"web_search_tool_type\": \"text\",\n \"input_modalities\": [\n \"text\"\n ],\n \"supports_image_detail_original\": false,\n \"truncation_policy\": {\n \"mode\": \"tokens\",\n \"limit\": 10000\n },\n \"supports_parallel_tool_calls\": true,\n \"tool_mode\": null,\n \"multi_agent_version\": \"v2\",\n \"use_responses_lite\": false,\n \"include_skills_usage_instructions\": false,\n \"auto_review_model_override\": null,\n \"context_window\": 1048576,\n \"max_context_window\": 1048576,\n \"effective_context_window_percent\": 95,\n \"auto_compact_token_limit\": null,\n \"comp_hash\": \"3000\",\n \"reasoning_summary_format\": \"experimental\",\n \"default_reasoning_summary\": \"none\",\n \"default_reasoning_level\": \"high\",\n \"supported_reasoning_levels\": [\n {\n \"effort\": \"low\",\n \"description\": \"low reasoning\"\n },\n {\n \"effort\": \"high\",\n \"description\": \"high reasoning\"\n },\n {\n \"effort\": \"max\",\n \"description\": \"max reasoning\"\n }\n ],\n \"shell_type\": \"shell_command\",\n \"visibility\": \"list\",\n \"minimal_client_version\": \"0.144.0\",\n \"supported_in_api\": true,\n \"availability_nux\": null,\n \"upgrade\": null,\n \"priority\": 1,\n \"model_messages\": null,\n \"base_instructions\": \"You are a mathematical research agent. Use the available tools to work on the assigned frozen problem. Follow the developer instructions and source constraints. Only the host Lean checks can accept a proof.\",\n \"experimental_supported_tools\": [],\n \"supports_search_tool\": true,\n \"default_service_tier\": null,\n \"supports_reasoning_summaries\": true\n },\n {\n \"slug\": \"deepseek-flash\",\n \"display_name\": \"deepseek-flash\",\n \"description\": \"DeepSeek mathematical research model\",\n \"prefer_websockets\": false,\n \"support_verbosity\": true,\n \"default_verbosity\": \"low\",\n \"apply_patch_tool_type\": \"freeform\",\n \"web_search_tool_type\": \"text\",\n \"input_modalities\": [\n \"text\",\n \"image\"\n ],\n \"supports_image_detail_original\": true,\n \"truncation_policy\": {\n \"mode\": \"tokens\",\n \"limit\": 10000\n },\n \"supports_parallel_tool_calls\": true,\n \"tool_mode\": null,\n \"multi_agent_version\": \"v2\",\n \"use_responses_lite\": false,\n \"include_skills_usage_instructions\": false,\n \"auto_review_model_override\": null,\n \"context_window\": 1048576,\n \"max_context_window\": 1048576,\n \"effective_context_window_percent\": 95,\n \"auto_compact_token_limit\": null,\n \"comp_hash\": \"3000\",\n \"reasoning_summary_format\": \"experimental\",\n \"default_reasoning_summary\": \"none\",\n \"default_reasoning_level\": \"high\",\n \"supported_reasoning_levels\": [\n {\n \"effort\": \"low\",\n \"description\": \"low reasoning\"\n },\n {\n \"effort\": \"high\",\n \"description\": \"high reasoning\"\n },\n {\n \"effort\": \"max\",\n \"description\": \"max reasoning\"\n }\n ],\n \"shell_type\": \"shell_command\",\n \"visibility\": \"list\",\n \"minimal_client_version\": \"0.144.0\",\n \"supported_in_api\": true,\n \"availability_nux\": null,\n \"upgrade\": null,\n \"priority\": 2,\n \"model_messages\": null,\n \"base_instructions\": \"You are a mathematical research agent. Use the available tools to work on the assigned frozen problem. Follow the developer instructions and source constraints. Only the host Lean checks can accept a proof.\",\n \"experimental_supported_tools\": [],\n \"supports_search_tool\": true,\n \"default_service_tier\": null,\n \"supports_reasoning_summaries\": true\n }\n ]\n}\n" - }, - "westlake": { - "metadata": { - "id": "westlake", - "baseUrl": "https://hpc-api.westlake.edu.cn/v1", - "wireApi": "chat-completions", - "transport": "session-local-responses-bridge", - "apiKeyEnvironment": "WESTLAKEHPC_API_KEY", - "defaultModel": "deepseek-flash", - "defaultEffort": "max" - }, - "config": "model = @MODEL@\nmodel_provider = \"westlake\"\nmodel_reasoning_effort = @EFFORT@\nmodel_catalog_json = @CATALOG@\nweb_search = \"disabled\"\napproval_policy = \"never\"\nsandbox_mode = \"workspace-write\"\n\n[model_providers.westlake]\nname = \"Westlake DeepSeek\"\nbase_url = \"https://hpc-api.westlake.edu.cn/v1\"\nwire_api = \"responses\"\nenv_key = \"WESTLAKEHPC_API_KEY\"\nrequires_openai_auth = false\nrequest_max_retries = 0\nstream_max_retries = 0\nstream_idle_timeout_ms = 60000\n\n[shell_environment_policy]\ninherit = \"all\"\nexclude = [ \"WESTLAKEHPC_API_KEY*\" ]\n\n[history]\npersistence = \"none\"\n\n[analytics]\nenabled = false\n\n[features]\nmulti_agent = false\nmulti_agent_v2 = false\ngoals = false\nview_image = false\n", - "models": "{\n \"models\": [\n {\n \"slug\": \"deepseek-flash\",\n \"display_name\": \"deepseek-flash\",\n \"description\": \"Westlake DeepSeek via a session-local Chat Completions bridge\",\n \"prefer_websockets\": false,\n \"support_verbosity\": true,\n \"default_verbosity\": \"low\",\n \"apply_patch_tool_type\": \"freeform\",\n \"web_search_tool_type\": \"text\",\n \"input_modalities\": [\n \"text\"\n ],\n \"supports_image_detail_original\": false,\n \"truncation_policy\": {\n \"mode\": \"tokens\",\n \"limit\": 10000\n },\n \"supports_parallel_tool_calls\": true,\n \"tool_mode\": null,\n \"multi_agent_version\": null,\n \"use_responses_lite\": false,\n \"include_skills_usage_instructions\": false,\n \"auto_review_model_override\": null,\n \"context_window\": 131072,\n \"max_context_window\": 131072,\n \"effective_context_window_percent\": 95,\n \"auto_compact_token_limit\": null,\n \"comp_hash\": \"3000\",\n \"reasoning_summary_format\": \"experimental\",\n \"default_reasoning_summary\": \"none\",\n \"default_reasoning_level\": \"high\",\n \"supported_reasoning_levels\": [\n {\n \"effort\": \"low\",\n \"description\": \"low reasoning\"\n },\n {\n \"effort\": \"high\",\n \"description\": \"high reasoning\"\n },\n {\n \"effort\": \"max\",\n \"description\": \"max reasoning\"\n }\n ],\n \"shell_type\": \"shell_command\",\n \"visibility\": \"list\",\n \"minimal_client_version\": \"0.144.0\",\n \"supported_in_api\": true,\n \"availability_nux\": null,\n \"upgrade\": null,\n \"priority\": 2,\n \"model_messages\": null,\n \"base_instructions\": \"You are a mathematical research agent. Use the available tools to work on the assigned frozen problem. Follow the developer instructions and source constraints. Only the host Lean checks can accept a proof.\",\n \"experimental_supported_tools\": [],\n \"supports_search_tool\": false,\n \"default_service_tier\": null,\n \"supports_reasoning_summaries\": true\n }\n ]\n}\n" - }, - "sub2api": { - "metadata": { - "id": "sub2api", - "baseUrl": "http://127.0.0.1:8080/v1", - "wireApi": "responses", - "apiKeyEnvironment": "SUB2API_WESTLAKE_API_KEY", - "defaultModel": "deepseek-flash", - "defaultEffort": "high" - }, - "config": "model = @MODEL@\nmodel_provider = \"sub2api\"\nmodel_reasoning_effort = @EFFORT@\nmodel_catalog_json = @CATALOG@\nweb_search = \"disabled\"\napproval_policy = \"never\"\nsandbox_mode = \"workspace-write\"\n\n[model_providers.sub2api]\nname = \"Sub2API DeepSeek\"\nbase_url = \"http://127.0.0.1:8080/v1\"\nwire_api = \"responses\"\nenv_key = \"SUB2API_WESTLAKE_API_KEY\"\nrequires_openai_auth = false\nrequest_max_retries = 0\nstream_max_retries = 0\nstream_idle_timeout_ms = 60000\n\n[shell_environment_policy]\ninherit = \"all\"\nexclude = [ \"SUB2API_WESTLAKE_API_KEY*\" ]\n\n[history]\npersistence = \"none\"\n\n[analytics]\nenabled = false\n\n[features]\nmulti_agent = false\nmulti_agent_v2 = false\ngoals = false\nview_image = false\n", - "models": "{\n \"models\": [\n {\n \"slug\": \"deepseek-flash\",\n \"display_name\": \"deepseek-flash\",\n \"description\": \"DeepSeek Flash via the local sub2api gateway\",\n \"prefer_websockets\": false,\n \"support_verbosity\": true,\n \"default_verbosity\": \"low\",\n \"apply_patch_tool_type\": \"freeform\",\n \"web_search_tool_type\": \"text\",\n \"input_modalities\": [\n \"text\"\n ],\n \"supports_image_detail_original\": false,\n \"truncation_policy\": {\n \"mode\": \"tokens\",\n \"limit\": 10000\n },\n \"supports_parallel_tool_calls\": true,\n \"tool_mode\": null,\n \"multi_agent_version\": null,\n \"use_responses_lite\": false,\n \"include_skills_usage_instructions\": false,\n \"auto_review_model_override\": null,\n \"context_window\": 131072,\n \"max_context_window\": 131072,\n \"effective_context_window_percent\": 95,\n \"auto_compact_token_limit\": null,\n \"comp_hash\": \"3000\",\n \"reasoning_summary_format\": \"experimental\",\n \"default_reasoning_summary\": \"none\",\n \"default_reasoning_level\": \"high\",\n \"supported_reasoning_levels\": [\n {\n \"effort\": \"low\",\n \"description\": \"low reasoning\"\n },\n {\n \"effort\": \"high\",\n \"description\": \"high reasoning\"\n },\n {\n \"effort\": \"max\",\n \"description\": \"max reasoning\"\n }\n ],\n \"shell_type\": \"shell_command\",\n \"visibility\": \"list\",\n \"minimal_client_version\": \"0.144.0\",\n \"supported_in_api\": true,\n \"availability_nux\": null,\n \"upgrade\": null,\n \"priority\": 2,\n \"model_messages\": null,\n \"base_instructions\": \"You are a mathematical research agent. Use the available tools to work on the assigned frozen problem. Follow the developer instructions and source constraints. Only the host Lean checks can accept a proof.\",\n \"experimental_supported_tools\": [],\n \"supports_search_tool\": false,\n \"default_service_tier\": null,\n \"supports_reasoning_summaries\": true\n }\n ]\n}\n" - } -} diff --git a/rust/cli/src/comparison/sample.rs b/rust/cli/src/comparison/sample.rs deleted file mode 100644 index e42e29f6..00000000 --- a/rust/cli/src/comparison/sample.rs +++ /dev/null @@ -1,112 +0,0 @@ -use super::*; -mod manifest; - -pub fn run(directory: &Path, check: bool) -> Result { - let manifest = manifest::load(directory)?; - let sample = &manifest["sample"]; - let observations = rows(&manifest["observations"]); - let file = directory.join("report.json"); - if check { - let saved = read(&file)?; - let mut children = vec![]; - let mut changed = false; - let previous = rows(&saved["problems"]); - for item in observations { - let path = Path::new( - item["reportFile"] - .as_str() - .ok_or("putnam_sample_identity_mismatch")?, - ); - let child = read(path)?; - let report = current(path.parent().unwrap(), &item["plan"])?; - let status = freshness::check(&report, &child)?; - changed |= previous - .iter() - .find(|p| p["problem"] == item["problem"]) - .and_then(|p| p["report"].get("reportHash")) - != child.get("reportHash"); - children.push(json!({"problem":item["problem"],"reportFile":path,"report":status})); - } - let hash = saved["reportHash"].as_str(); - let status = if saved["schema"] != "theorem-os.putnambench-sample-report.v1" - || hash.is_some_and(|s| s != digest(&obj_without(&saved, &["reportHash"]))) - { - "invalid" - } else if hash.is_none() { - "unknown" - } else if changed - || previous.len() != children.len() - || children - .iter() - .any(|c| c["report"]["freshness"] != "current") - { - "stale" - } else { - "current" - }; - return Ok(json!({ - "schema": "theoremos.putnambench-report-freshness.v1", - "evidence": "recorded-not-replayed", - "freshness": status, - "problems": children, - "invokesModel": false, - })); - } - let mut reports = vec![]; - let mut all_runs = vec![]; - let mut names = vec![]; - for item in observations { - let path = Path::new( - item["reportFile"] - .as_str() - .ok_or("putnam_sample_identity_mismatch")?, - ); - let report = current(path.parent().unwrap(), &item["plan"])?; - publish(path, &report)?; - if reports.is_empty() { - names = rows(&report["totals"]) - .iter() - .map(|t| t["arm"].clone()) - .collect(); - } - for row in rows(&report["runs"]) { - let mut r = row.clone(); - if r.get("problem").is_none() { - r["problem"] = item["problem"].clone(); - } - all_runs.push(r); - } - reports.push(json!({"problem":item["problem"],"reportFile":path,"report":report})); - } - let summary = json!({ - "reportFile": file, - "problems": reports.len(), - "plannedRuns": all_runs.len(), - "missingResults": all_runs.iter().filter(|r|r["status"]=="missing").count(), - "invokesModel": false, - }); - let mut report = json!({ - "schema": "theorem-os.putnambench-sample-report.v1", - "generatedAt": now(), - "official": false, - "evidence": "recorded-not-replayed", - "totals": totals(&all_runs,&names), - "problems": reports, - "runs": all_runs, - }); - present( - &mut report, - sample, - &[ - "selection", - "repositoryUrl", - "sourceCommit", - "environment", - "configuration", - "knowledge", - ], - ); - report["reportHash"] = digest(&report).into(); - publish(&file, &report)?; - Ok(summary) -} diff --git a/rust/cli/src/comparison/sample/manifest.rs b/rust/cli/src/comparison/sample/manifest.rs deleted file mode 100644 index 95dbb383..00000000 --- a/rust/cli/src/comparison/sample/manifest.rs +++ /dev/null @@ -1,157 +0,0 @@ -use super::*; -use regex::Regex; -use std::{collections::HashSet, sync::LazyLock}; -const REPOSITORY: &str = "https://github.com/trishullab/PutnamBench.git"; -const REVISION: &str = "13d042960189f55d748048317c24064a0e2215ea"; -const INVALID: &str = "putnam_sample_manifest_invalid"; -const MISMATCH: &str = "putnam_sample_identity_mismatch"; -static ID: LazyLock = LazyLock::new(|| Regex::new(r"^putnam_[0-9]{4}_[ab][1-6]$").unwrap()); - -fn keys(value: &Value, required: &[&str]) -> bool { - value.as_object().is_some_and(|object| { - object.len() == required.len() && required.iter().all(|key| object.contains_key(*key)) - }) -} -fn hash(value: &Value, length: usize) -> bool { - value.as_str().is_some_and(|text| { - text.len() == length - && text - .bytes() - .all(|b| b.is_ascii_digit() || matches!(b, b'a'..=b'f')) - }) -} -fn number(value: &Value) -> Option { - value.as_f64().filter(|n| n.fract() == 0. && *n >= 0.) -} -fn valid(sample: &Value) -> bool { - if !keys( - &obj_without(sample, &["knowledge"]), - &[ - "schema", - "repositoryUrl", - "sourceCommit", - "selection", - "environment", - "excludedCounts", - "configuration", - "buildDigest", - "runtimeEnvironmentDigest", - "moduleExperimentDigest", - "problems", - ], - ) { - return false; - } - let selection = &sample["selection"]; - let environment = &sample["environment"]; - sample["schema"] == "theorem-os.putnambench-sample.v1" - && sample["repositoryUrl"] == REPOSITORY - && sample["sourceCommit"] == REVISION - && keys( - selection, - &["algorithm", "seed", "count", "poolDigest", "eligibleCount"], - ) - && selection["algorithm"] == "sha256-seed-nul-id-v1" - && selection["seed"] - .as_str() - .is_some_and(|s| (1..=128).contains(&s.encode_utf16().count())) - && number(&selection["count"]).is_some_and(|n| (1.0..=20.).contains(&n)) - && number(&selection["eligibleCount"]).is_some_and(|n| n > 0.) - && hash(&selection["poolDigest"], 64) - && keys(environment, &["toolchain", "mathlibRevision", "digest"]) - && environment["toolchain"] - .as_str() - .is_some_and(|s| !s.is_empty()) - && hash(&environment["mathlibRevision"], 40) - && hash(&environment["digest"], 64) - && sample["excludedCounts"] - .as_object() - .is_some_and(|m| m.values().all(|v| number(v).is_some())) - && sample["configuration"].is_object() - && [ - "buildDigest", - "runtimeEnvironmentDigest", - "moduleExperimentDigest", - ] - .iter() - .all(|k| hash(&sample[*k], 64)) - && sample["problems"].as_array().is_some_and(|problems| { - (1..=20).contains(&problems.len()) - && problems.iter().all(|p| { - keys( - p, - &[ - "id", - "sourceRelativePath", - "sourceSha256", - "theoremNames", - "comparisonDirectory", - "comparisonDigest", - ], - ) && p["id"].as_str().is_some_and(|id| ID.is_match(id)) - && p["sourceRelativePath"].is_string() - && hash(&p["sourceSha256"], 64) - && p["theoremNames"].as_array().is_some_and(|a| { - a.len() == 1 && a[0].as_str().is_some_and(|id| ID.is_match(id)) - }) - && p["comparisonDirectory"].is_string() - && hash(&p["comparisonDigest"], 64) - }) - }) -} -pub fn load(directory: &Path) -> Result { - let sample = read(&directory.join("sample.json"))?; - if !valid(&sample) { - return Err(INVALID.into()); - } - knowledge::check(directory, sample.get("knowledge"), None, &[])?; - let problems = rows(&sample["problems"]); - let selection = &sample["selection"]; - if number(&selection["count"]) != Some(problems.len() as f64) - || number(&selection["eligibleCount"]) < number(&selection["count"]) - { - return Err(MISMATCH.into()); - } - let mut seen = HashSet::new(); - let mut observations = Vec::new(); - for p in problems { - let id = p["id"].as_str().unwrap(); - let dir = directory.join(id); - if !seen.insert(id) - || p["comparisonDirectory"] != json!(dir) - || p["sourceRelativePath"] != format!("lean4/src/{id}.lean") - || p["theoremNames"][0] != id - { - return Err(MISMATCH.into()); - } - let plan_file = dir.join("comparison.json"); - io::canonical(&plan_file)?; - let source = io::text(&plan_file, usize::MAX)?; - if sha(&source) != p["comparisonDigest"] { - return Err("putnam_sample_plan_changed".into()); - } - let plan: Value = serde_json::from_str(&source).map_err(err)?; - let env = &sample["environment"]; - let frozen = &plan["sourceProblem"]; - if plan["dataset"] != "putnambench" - || plan["problem"] != id - || plan["sourceCommit"] != sample["sourceCommit"] - || frozen["sourceSha256"] != p["sourceSha256"] - || frozen["toolchain"] != env["toolchain"] - || frozen["mathlibRevision"] != env["mathlibRevision"] - || frozen["environmentDigest"] != env["digest"] - || canonical_json(&plan["configuration"]) != canonical_json(&sample["configuration"]) - || plan["buildDigest"] != sample["buildDigest"] - || plan["environmentDigest"] != sample["runtimeEnvironmentDigest"] - || ["digest", "format", "mode"] - .iter() - .any(|k| plan["knowledge"].get(k) != sample["knowledge"].get(k)) - || plan.get("moduleExperiment").is_none() - || digest(&plan["moduleExperiment"]) != sample["moduleExperimentDigest"] - { - return Err(MISMATCH.into()); - } - observations.push(json!({"problem":id,"reportFile":dir.join("report.json"),"comparisonDirectory":dir,"plan":plan})); - } - Ok(json!({"sample":sample,"observations":observations})) -} diff --git a/rust/cli/src/component/contract.rs b/rust/cli/src/component/contract.rs deleted file mode 100644 index 9069c81c..00000000 --- a/rust/cli/src/component/contract.rs +++ /dev/null @@ -1,131 +0,0 @@ -// Compiled together with one local component by 'theorem-os component check'. -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Research, - Goal, -} - -#[derive(Clone, Copy)] -pub struct Task { - pub id: &'static str, - pub kind: Kind, - pub route: &'static str, - pub depends_on: &'static [&'static str], - pub paused: bool, - pub complete: bool, -} - -#[derive(Clone, Copy)] -pub struct Route { - pub id: &'static str, - pub stopped: bool, - pub turns: u32, - pub max_turns: Option, -} - -pub fn ready_tasks<'a>(tasks: &'a [Task], routes: &[Route]) -> Vec<&'a Task> { - tasks - .iter() - .filter(|task| { - !task.paused - && !task.complete - && routes.iter().any(|route| { - route.id == task.route - && !route.stopped - && route.max_turns.is_none_or(|limit| route.turns < limit) - }) - && task - .depends_on - .iter() - .all(|id| tasks.iter().any(|t| t.id == *id && t.complete)) - }) - .collect() -} - -fn verify( - tasks: &[Task], - routes: &[Route], - expected: &[&str], -) -> Result, &'static str> { - let ordered = component::ready(tasks, routes); - if ordered.len() != expected.len() - || expected.iter().any(|id| { - let original = tasks.iter().find(|task| task.id == *id).unwrap(); - ordered - .iter() - .filter(|task| std::ptr::eq(**task, original)) - .count() - != 1 - }) - { - return Err( - "Return each ready task exactly once. Blocked, paused and stopped tasks must stay excluded.", - ); - } - Ok(ordered.into_iter().map(|task| task.id).collect()) -} - -fn main() -> Result<(), Box> { - let goal = Task { - id: "goal", - kind: Kind::Goal, - route: "main", - depends_on: &[], - paused: false, - complete: false, - }; - let tasks = [ - Task { - id: "research", - kind: Kind::Research, - ..goal - }, - goal, - Task { - id: "blocked", - depends_on: &["goal"], - ..goal - }, - Task { - id: "paused", - paused: true, - ..goal - }, - Task { - id: "stopped", - kind: Kind::Research, - route: "stopped", - ..goal - }, - ]; - let main = Route { - id: "main", - stopped: false, - turns: 0, - max_turns: None, - }; - let routes = [ - main, - Route { - id: "stopped", - stopped: true, - ..main - }, - ]; - let order = verify(&tasks, &routes, &["research", "goal"])?; - let exhausted = routes.map(|route| Route { - turns: 1, - max_turns: Some(1), - ..route - }); - if !component::ready(&tasks, &exhausted).is_empty() { - return Err("An exhausted route must not receive new tasks.".into()); - } - let mut progressed = tasks; - progressed[1].complete = true; - verify(&progressed, &routes, &["research", "blocked"])?; - // Preserve the component ID verbatim, even if it contains a newline or quote. - let result = std::env::args_os().nth(1).unwrap(); - std::fs::write(result, format!("{}\n{}", order.join(","), component::ID))?; - Ok(()) -} diff --git a/rust/cli/src/component/mod.rs b/rust/cli/src/component/mod.rs deleted file mode 100644 index bf3ef62e..00000000 --- a/rust/cli/src/component/mod.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! Create and check a local Rust search-order component. -use crate::build; -use serde_json::json; -use std::error::Error; -use std::fs; -use std::io::Write; -use std::path::Path; -use std::process::Command; - -type Result = std::result::Result>; -const USAGE: &str = "Usage: theorem-os component init|check --name my-search -init creates rust/components/my-search.rs and preserves existing components. -check compiles the component with rustc and checks ordering, dependencies, pauses and route budgets. -Use the pinned historical TheoremOS revision for TypeScript components and scheduling experiments."; -const TEMPLATE: &str = include_str!("template.rs"); -const CONTRACT: &str = include_str!("contract.rs"); - -fn check(file: &Path) -> Result<()> { - let directory = tempfile::Builder::new() - .prefix("theoremos-component-") - .tempdir()?; - let driver = directory.path().join("check.rs"); - let binary = directory.path().join("check"); - let result = directory.path().join("result"); - let path = file.to_str().ok_or("Invalid component source path")?; - fs::write( - &driver, - format!("#[path = {path:?}] mod component;\n{CONTRACT}"), - )?; - let compiled = Command::new("rustc") - .arg("--edition=2024") - .arg(&driver) - .arg("-o") - .arg(&binary) - .status() - .map_err(|e| format!("Cannot run rustc for component check: {e}"))?; - if !compiled.success() { - return Err("The Rust component did not compile.".into()); - } - if !Command::new(binary).arg(&result).status()?.success() { - return Err("The Rust component failed the local ordering contract.".into()); - } - let report = fs::read_to_string(result)?; - let (ordered, id) = report - .split_once('\n') - .ok_or("Missing component check result")?; - println!( - "{}", - serde_json::to_string_pretty(&json!({ - "status": "passed", - "component": id, - "readyTasks": ordered.split(',').collect::>(), - "checks": ["dependencies", "paused tasks", "stopped routes", "route budgets", "unchanged inputs"], - "note": "Local ordering contract only; measure effectiveness with real experiments." - }))? - ); - Ok(()) -} - -fn execute(args: &[String]) -> Result<()> { - let mut options = args.iter().map(String::as_str); - let mut action = None; - let mut name = None; - let mut help = false; - while let Some(arg) = options.next() { - match arg { - "--help" | "-h" => help = true, - "--name" => { - name = Some( - options - .next() - .filter(|s| !s.starts_with('-')) - .ok_or("--name requires a value")?, - ) - } - a if a.starts_with("--name=") => name = Some(&a[7..]), - "init" | "check" if action.is_none() => action = Some(arg), - _ => return Err("Use component init|check --name my-search.".into()), - } - } - if help { - println!("{USAGE}"); - return Ok(()); - } - let action = action.ok_or("Use component init|check --name my-search.")?; - let name = name.ok_or("Use component init|check --name my-search.")?; - if name.len() > 64 - || !name.as_bytes().first().is_some_and(u8::is_ascii_lowercase) - || !name.split('-').all(|s| { - !s.is_empty() - && s.bytes() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) - }) - { - return Err("Use a component name such as my-search: lowercase letters, digits and hyphens, up to 64 characters.".into()); - } - let root = build::root(None)?; - let relative = format!("rust/components/{name}.rs"); - let source = root.join(&relative); - build::canonical(&source)?; - if action == "check" && source.try_exists()? { - return check(&source); - } - for previous in ["src/components", "scripts/components"] { - let path = root.join(previous).join(format!("{name}.ts")); - build::canonical(&path)?; - if path.try_exists()? { - return Err(format!("A TypeScript component already exists at {}. Use its pinned historical TheoremOS revision or choose a new name.", path.display()).into()); - } - } - if action == "check" { - return Err(format!("Component source not found: {}", source.display()).into()); - } - if source.try_exists()? { - return Err(format!( - "File already exists; choose a new component name: {}", - source.display() - ) - .into()); - } - let parent = source.parent().unwrap(); - fs::create_dir_all(parent)?; - let mut stage = tempfile::NamedTempFile::new_in(parent)?; - stage.write_all(TEMPLATE.replace("__NAME__", name).as_bytes())?; - stage.persist_noclobber(&source)?; - println!( - "Created {relative}\n\nEdit the ready function, then run:\ntheorem-os component check --name {name}" - ); - Ok(()) -} - -pub fn run(args: &[String]) -> std::result::Result { - execute(args).map(|_| 0).map_err(|err| err.to_string()) -} diff --git a/rust/cli/src/component/template.rs b/rust/cli/src/component/template.rs deleted file mode 100644 index 03638479..00000000 --- a/rust/cli/src/component/template.rs +++ /dev/null @@ -1,10 +0,0 @@ -use crate::{Kind, Route, Task, ready_tasks}; - -pub const ID: &str = "__NAME__-v1"; - -// Reorder the eligible tasks. Bump ID when the strategy changes. -pub fn ready<'a>(tasks: &'a [Task], routes: &[Route]) -> Vec<&'a Task> { - let mut candidates = ready_tasks(tasks, routes); - candidates.sort_by_key(|task| task.kind != Kind::Goal); - candidates -} diff --git a/rust/cli/src/continuation/mod.rs b/rust/cli/src/continuation/mod.rs deleted file mode 100644 index 98a41052..00000000 --- a/rust/cli/src/continuation/mod.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! Read and search the immutable snapshots produced by the solver. -mod search; -use theoremos_library::continuation as snapshot; - -const HELP: &str = "Usage: theorem-os continuation read --snapshot FILE --sha256 DIGEST --id ID [--offset N] [--max-bytes 1024..16000] - theorem-os continuation search --snapshot FILE --sha256 DIGEST --query TEXT [--query TEXT ...] [--kind KIND]... [--limit 1..20] [--max-bytes 1024..16000] -Reads only immutable continuation snapshots. Output is advisory historical text, not -proof acceptance. Concatenate text pages exactly using nextOffset until truncated -is false. Offsets count UTF-16 code units; the entire JSON line fits --max-bytes. -search ranks paragraph passages lexically (BM25) with bounded snippets; read a hit -with --id and --offset startOffset. KIND is proof-source, research-notes, diagnostics -or reference; repeat --kind to select several (default: all). Up to 8 queries share -one index. Multiple queries return an array of independently ranked results, each -with its query; --max-bytes bounds the entire JSON line, including every query."; - -fn trim(s: &str) -> &str { - s.trim_matches(|c: char| c == '\u{feff}' || (c != '\u{85}' && c.is_whitespace())) -} - -// The existing CLI converts numeric flags with JavaScript Number(), including -// empty strings, exponents and unsigned integer literals with a radix prefix. -fn number(s: &str) -> f64 { - let s = trim(s); - if s.is_empty() { - return 0.0; - } - for (prefix, radix) in [("0x", 16), ("0b", 2), ("0o", 8)] { - if s.get(..2).is_some_and(|p| p.eq_ignore_ascii_case(prefix)) { - let digits = &s[2..]; - if digits.starts_with('+') { - return f64::NAN; - } - return u64::from_str_radix(digits, radix).map_or(f64::NAN, |n| n as f64); - } - } - s.parse().unwrap_or(f64::NAN) -} - -pub fn run(argv: &[String]) -> Result<(), String> { - let Some((command, args)) = argv.split_first() else { - println!("{HELP}"); - return Ok(()); - }; - if matches!(command.as_str(), "" | "--help" | "-h" | "help") - || args.iter().any(|s| s == "--help") - { - println!("{HELP}"); - return Ok(()); - } - let read = match command.as_str() { - "read" => true, - "search" => false, - _ => return Err("Expected continuation read or continuation search".into()), - }; - let (mut file, mut digest, mut id) = ("", "", ""); - let (mut queries, mut kinds) = (Vec::new(), Vec::new()); - let (mut limit, mut max_bytes, mut offset) = (8.0, 16000.0, 0.0); - let mut args = args.iter().map(String::as_str); - while let Some(flag) = args.next() { - if flag == "--" { - if let Some(value) = args.next() { - return Err(format!( - "Unexpected argument '{value}'. This command does not take positional arguments" - )); - } - break; - } - let (key, inline) = flag - .split_once('=') - .map_or((flag, None), |(key, value)| (key, Some(value))); - let supported = matches!(key, "--snapshot" | "--sha256" | "--max-bytes") - || if read { - matches!(key, "--id" | "--offset") - } else { - matches!(key, "--query" | "--kind" | "--limit") - }; - if !supported { - return Err(if key.starts_with('-') && key != "-" { - let option = - if let Some(short) = key.strip_prefix('-').filter(|s| !s.starts_with('-')) { - let name = short.chars().next().unwrap(); - if short.chars().count() == 1 { - format!("-{name}") - } else { - name.to_string() - } - } else { - key.to_owned() - }; - format!("Unknown option '{option}'") - } else { - format!( - "Unexpected argument '{flag}'. This command does not take positional arguments" - ) - }); - } - let value = if let Some(value) = inline { - value - } else { - let value = args - .next() - .ok_or_else(|| format!("Option '{key} ' argument missing"))?; - if value.starts_with('-') && value != "-" { - return Err(format!( - "Option '{key}' argument is ambiguous.\nDid you forget to specify the option argument for '{key}'?\nTo specify an option argument starting with a dash use '{key}=-XYZ'." - )); - } - value - }; - match key { - "--snapshot" => file = value, - "--sha256" => digest = value, - "--id" => id = value, - "--query" => queries.push(value.to_owned()), - "--kind" => kinds.push(value.to_owned()), - "--offset" => offset = number(value), - "--limit" => limit = number(value), - "--max-bytes" => max_bytes = number(value), - _ => unreachable!(), - } - } - let required = |name: &str, s: &str| { - if trim(s).is_empty() { - Err(format!("--{name} is required")) - } else { - Ok(()) - } - }; - if !read && queries.is_empty() { - return Err("--query is required".into()); - } - required("snapshot", file)?; - required("sha256", digest)?; - let packet = if read { - required("id", id)?; - if !(0.0..=9_007_199_254_740_991.0).contains(&offset) - || offset.fract() != 0.0 - || !(1024.0..=16000.0).contains(&max_bytes) - || max_bytes.fract() != 0.0 - { - return Err("math_continuation_read_options_invalid".into()); - } - snapshot::page( - &snapshot::load(file, digest)?, - id, - offset as usize, - max_bytes as usize, - )? - .to_string() - } else { - search::search(file, digest, &queries, &kinds, limit, max_bytes)? - }; - println!("{packet}"); - Ok(()) -} diff --git a/rust/cli/src/continuation/search.rs b/rust/cli/src/continuation/search.rs deleted file mode 100644 index 805f901d..00000000 --- a/rust/cli/src/continuation/search.rs +++ /dev/null @@ -1,394 +0,0 @@ -//! Read-only passage search over verified continuation attachments. -use super::snapshot::{self, Attachment, Snapshot}; -use icu_properties::{ - CodePointMapData, - props::{GeneralCategory as Category, GeneralCategoryGroup as Group, Script}, -}; -use regex::Regex; -use serde::Serialize; -use serde_json::{Value, json}; -use std::{ - collections::{HashMap, HashSet}, - io::{self, Write}, - ops::Range, - sync::LazyLock, -}; -use unicode_normalization::UnicodeNormalization; - -const KINDS: [&str; 4] = ["proof-source", "research-notes", "diagnostics", "reference"]; -const OPTIONS: &str = "math_continuation_search_options_invalid"; -const MAX_QUERY_TERMS: usize = 512; -const TARGET: usize = 1200; -const MAX_PASSAGE: usize = 4000; -static PARAGRAPH: LazyLock = - LazyLock::new(|| Regex::new(r"\n[ \t\r]*\n(?:[\s&&[^\x85]]|\u{feff})*").unwrap()); - -fn category(c: char) -> Category { - CodePointMapData::::new().get(c) -} - -fn han(c: char) -> bool { - CodePointMapData::